import { readFileSync } from 'node:fs' import { readFile } from 'node:fs/promises' import { dirname, relative, resolve as resolvePath } from 'node:path' import type { UserConfig, TsdownPlugin } from 'tsdown' import { clientCssPlugin } from './vendor/dsh-mnemon/tsdown.config.ts' const PLUGIN_ID = 'dsh-brain' const VENDOR_ROOT = 'vendor/dsh-mnemon' const MNEMON_ENTRY = '\0dsh-brain-mnemon-entry.mjs' function mnemonClientPlugin(): TsdownPlugin { const paths = JSON.parse(readFileSync(VENDOR_ROOT + '/tsconfig.json', 'utf8')).compilerOptions.paths as Record const css = clientCssPlugin() const resolveCss = css.resolveId const loadCss = css.load if (typeof resolveCss !== 'function' || typeof loadCss !== 'function') { throw new Error('Mnemon CSS plugin must expose resolveId and load hooks') } return { name: 'dsh-brain-mnemon-browser', resolveId(source, importer, options) { if (source === 'brain:mnemon-client') return MNEMON_ENTRY const asset = /^(dsh-brain-mnemon-[^/]+)\/(presentation\/[^/]+)$/.exec(source) if (asset !== null) { const path = resolvePath(VENDOR_ROOT, 'plugins', asset[1], asset[2]) return source.endsWith('.module.css') ? resolveCss.call(this, path, undefined, options) : path } if (source === 'dsh-brain-mnemon/client' || importer?.replaceAll('\\', '/').includes('/' + VENDOR_ROOT + '/')) { return resolveCss.call(this, source, importer, options) } return null }, load(id, options) { if (id === MNEMON_ENTRY) { const from = (path: string) => JSON.stringify(resolvePath(VENDOR_ROOT, path)) return [ 'export { apply as applyMnemon, inject as mnemonServices } from ' + from('src/client/index.ts'), ...Object.entries({ Runtime: 'runtime', Documents: 'documents', MemorySpaces: 'memory-spaces', Skills: 'skills' }).map(([name, source]) => { const specifier = Object.keys(paths).find(key => key.endsWith('-' + source + '/client')) const entry = specifier === undefined ? undefined : paths[specifier]?.[0] if (entry === undefined) throw new Error('Missing vendored browser entry for Mnemon ' + source) return 'export { apply as apply' + name + ' } from ' + from(entry) }), ].join('\n') } return loadCss.call(this, id, options) }, renderChunk(code) { // The upstream CSS loader uses absolute virtual IDs internally. return code.replace(/^[ \t]*\/\/ \\0dsh-brain-mnemon-css:[^\r\n]*[\r\n]+/gm, '') }, } } const CSS_VIRTUAL_PREFIX = '\0dsh-brain-css:' const CSS_VIRTUAL_SUFFIX = '.mjs' function cssHash(value: string): string { let hash = 2166136261 for (let index = 0; index < value.length; index += 1) { hash ^= value.charCodeAt(index) hash = Math.imul(hash, 16777619) } return (hash >>> 0).toString(36) } /** Minimal CSS-modules inliner: scope class names, inject one