dsh-brain/tsdown.mnemon.config.ts

172 lines
7.4 KiB
TypeScript

import { readFileSync, readdirSync } from 'node:fs'
import { resolve } from 'node:path'
import type { UserConfig, TsdownPlugin } from 'tsdown'
import upstream, { clientCssPlugin } from './vendor/dsh-mnemon/tsdown.config.ts'
import documents from './vendor/dsh-mnemon/plugins/dsh-brain-mnemon-source-documents/tsdown.config.ts'
import memorySpaces from './vendor/dsh-mnemon/plugins/dsh-brain-mnemon-source-memory-spaces/tsdown.config.ts'
import runtime from './vendor/dsh-mnemon/plugins/dsh-brain-mnemon-source-runtime/tsdown.config.ts'
import skills from './vendor/dsh-mnemon/plugins/dsh-brain-mnemon-source-skills/tsdown.config.ts'
const vendor = 'vendor/dsh-mnemon'
const outDir = 'lib/mnemon-vendor'
const prefix = 'dsh-brain-mnemon-'
const tsconfig = vendor + '/tsconfig.json'
const [upstreamHost, upstreamClient] = upstream
interface Manifest {
dependencies: Record<string, string>
exports: Record<string, string | { default: string; types?: string }>
types?: string
typesVersions?: Record<string, Record<string, string[]>>
dsh?: { bundle?: { patch?: string } }
bin?: Record<string, string>
}
function readManifest(directory: string): Manifest {
return JSON.parse(readFileSync(directory + '/package.json', 'utf8'))
}
const rootManifest = readManifest(vendor)
const components = Object.keys(rootManifest.dependencies)
.filter(name => name.startsWith(prefix))
.map(name => {
const directory = vendor + '/plugins/' + name
return { name, directory, output: 'components/' + name.slice(prefix.length), manifest: readManifest(directory) }
})
const entry: Record<string, string> = Object.fromEntries(
Object.entries(upstreamHost.entry as Record<string, string>).map(([name, source]) => ['lib/' + name, vendor + '/' + source]),
)
for (const { directory, output, manifest } of components) {
for (const [specifier, value] of Object.entries(manifest.exports)) {
if (specifier === './client' || typeof value === 'string' || !value.default.startsWith('./lib/')) continue
const name = value.default.slice('./lib/'.length, -'.js'.length)
entry[output + '/lib/' + name] = directory + '/src/' + name + '.ts'
}
}
const assets: TsdownPlugin = {
name: 'dsh-brain-mnemon-assets',
generateBundle() {
const emit = (directory: string, file: string, output: string) => {
this.addWatchFile(directory + '/' + file)
this.emitFile({ type: 'asset', fileName: output, source: readFileSync(directory + '/' + file) })
}
const emitDirectory = (directory: string, output: string, asset: string) => {
for (const file of readdirSync(directory + '/' + asset, { withFileTypes: true })) {
const path = asset + '/' + file.name
if (file.isDirectory()) emitDirectory(directory, output, path)
else if (file.isFile()) emit(directory, path, output + path)
}
}
// Keep the fork identity for the bundled host and retain each component's assets.
for (const [directory, output, manifest] of [[vendor, '', rootManifest],
...components.map(component => [component.directory, component.output + '/', component.manifest] as const),
] as const) {
const assetDirectories = new Set(Object.values(manifest.exports)
.filter((value): value is string => typeof value === 'string' && value.includes('/', 2))
.map(value => value.split('/')[1]))
for (const asset of assetDirectories) emitDirectory(directory, output, asset)
const patch = manifest.dsh?.bundle?.patch
if (patch) emit(directory, patch.slice(2), output + patch.slice(2))
this.addWatchFile(directory + '/package.json')
const exports = Object.fromEntries(Object.entries(manifest.exports).map(([key, value]) => [key,
typeof value === 'string' ? value : { types: value.default.replace(/\.js$/, '.d.ts'), default: value.default }]))
const primary = exports['.']
this.emitFile({ type: 'asset', fileName: output + 'package.json', source: JSON.stringify({
...manifest,
exports,
...(manifest.types && typeof primary === 'object' && { types: primary.types.slice(2) }),
...(manifest.typesVersions && { typesVersions: { '*': Object.fromEntries(Object.entries(exports)
.filter(([key, value]) => key !== '.' && typeof value === 'object')
.map(([key, value]) => [key.slice(2), [(value as { types: string }).types.slice(2)]])) } }),
...(manifest.bin && { bin: Object.fromEntries(Object.entries(manifest.bin).map(([name, file]) => [name, file.replace(/\.mjs$/, '.js')])) }),
}, null, 2) + '\n' })
}
for (const notice of ['LICENSE', 'THIRD_PARTY_NOTICES.md', 'FORK_NOTICE.md']) {
emit(vendor, notice, notice)
}
for (const file of Object.values(rootManifest.bin ?? {})) {
emit(vendor, file, file.replace(/\.mjs$/, '.js'))
}
},
}
const host: UserConfig = {
...upstreamHost,
entry,
tsconfig,
outDir,
target: 'es2022',
dts: true,
outputOptions: { chunkFileNames: 'lib/[name]-[hash].js' },
deps: { alwaysBundle: [/^dsh-brain-mnemon(?:[-/]|$)/] },
plugins: [upstreamHost.plugins, assets],
}
const css = clientCssPlugin()
const resolveCss = css.resolveId
const resolveClientAssets: TsdownPlugin = {
...css,
resolveId(source, importer, options) {
if (source === 'dsh-brain-mnemon/client') return resolve(vendor, 'src/client/extension-sdk.ts')
const component = components.find(({ name }) => source.startsWith(name + '/presentation/'))
const path = component ? resolve(component.directory, source.slice(component.name.length + 1)) : source
if (typeof resolveCss === 'function') return resolveCss.call(this, path, importer, options)
return null
},
}
const portableCssComments: TsdownPlugin = {
name: 'dsh-brain-mnemon-portable-css-comments',
renderChunk(code) {
// Upstream virtual CSS IDs contain absolute paths. Drop their generated module labels.
return code.replace(/^[ \t]*\/\/ \\0(?:dsh-brain-mnemon-css|source-css):[^\r\n]*[\r\n]+/gm, '')
},
}
const client: UserConfig = {
...upstreamClient,
entry: { 'lib/client': vendor + '/src/client/index.ts' },
tsconfig,
outDir,
plugins: [resolveClientAssets, portableCssComments],
alias: Object.fromEntries(components.flatMap(({ name, directory, manifest }) => Object.values(manifest.exports)
.filter((value): value is string => typeof value === 'string' && value.startsWith('./presentation/'))
.map(value => [name + value.slice(1), resolve(directory, value)]))),
}
const sourceClients = [
['source-documents', documents],
['source-memory-spaces', memorySpaces],
['source-runtime', runtime],
['source-skills', skills],
] as const
const browserConfigs = sourceClients.map(([slug, [, config]]): UserConfig => {
return {
...config,
plugins: [config.plugins, portableCssComments],
name: prefix + slug + '/client',
entry: { ['components/' + slug + '/lib/client']: vendor + '/plugins/' + prefix + slug + '/src/client.ts' },
tsconfig,
outDir,
}
})
// The DSH client factories are CommonJS-shaped scripts, while their SDK types are ESM.
const browserTypes: UserConfig = {
name: 'dsh-brain-mnemon-client-types',
entry: Object.assign({}, client.entry, ...browserConfigs.map(config => config.entry)),
tsconfig,
outDir,
format: 'esm',
fixedExtension: false,
clean: false,
dts: { emitDtsOnly: true },
deps: { alwaysBundle: [/^dsh-brain-mnemon(?:[-/]|$)/] },
outputOptions: { chunkFileNames: 'lib/client-[name]-[hash].js' },
}
export default [host, client, ...browserConfigs, browserTypes]