diff --git a/docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.i18n.yaml new file mode 100644 index 0000000000..2d20fa39db --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.md +/: + en: b414093b29c38765 + zh: 2a69f37a40e35a99 +/loader-validates-entry-options-and-include-parses-yaml-1-2: + en: 0ba0b666924ce1f0 + zh: 0c5668ee67163d00 +/loader-validates-entry-options-and-include-parses-yaml-1-2/change: + en: b0d2ae6a748cab50 + zh: a2521c4dc48e4d3d +/loader-validates-entry-options-and-include-parses-yaml-1-2/migration: + en: 2c167e1042c952a5 + zh: aec49a7754befae0 diff --git a/docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.md b/docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.md new file mode 100644 index 0000000000..336418a559 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.md @@ -0,0 +1,27 @@ +--- +kind: upgrade-guide +description: "Cordis Loader 1.0.0-rc.9 and Include 1.2.0 parse YAML 1.2, reject malformed entries, and return PatchResult from applyEntryPatches." +--- + +# Loader validates entry options, and Include parses YAML 1.2 + +English | [中文](guide.zh.md) + +## Change + +`@deepseek-ai/cordis-plugin-loader` now carries upstream Loader 1.0.0-rc.9, and `@deepseek-ai/cordis-plugin-include` carries Include 1.2.0. Hand-written `cordis.yml`, `cordis.patch.yml` and overlay files, and code that calls the Include or Loader exports, are affected: + +- Include and `parseEntryYaml` parse YAML 1.2 under the core schema instead of the js-yaml JSON schema. A binary integer such as `0b101` now reads as the string `'0b101'`. An empty `!!js` scalar now reads as an empty expression, which evaluates to `undefined`, instead of failing to parse. +- Entry options are validated before an entry is created or updated. `name` must be a string; `group` a boolean; `disabled` a boolean or `!!js` expression; a group's `config` a list; `inject` a string list or a mapping; `isolate` a mapping whose values are `true` or a string. An entry that loaded before with such a value is now rejected and logged, and its siblings still start. An Include file with an entry that is not a mapping is rejected as a whole. Ids containing `:` remain accepted. +- Parse, entry option and config validation errors name the file position as `file:line:column`. When an entry's own module cannot be found, the error is a `ModuleNotFoundError` without Node's `imported from` part; its `code` is still `ERR_MODULE_NOT_FOUND`. +- A patch that replaces a group's `config` brings child entries that later patches can address, and the children it replaces can no longer be patched. +- `applyEntryPatches(data, patches, warn)` returns `{ data, index }` instead of the entry list, and writes generated ids into the anonymous entries of a replaced group `config` in `patches`. `parseEntryYaml` throws the `YAMLError` of the `yaml` package instead of a js-yaml `YAMLException`. + +## Migration + +1. Write binary integers that must stay numbers in decimal or hexadecimal. +2. Run `dsh --dump-config` for each profile. A parse error now names its line and column; fix the reported value. +3. Start the profile and check the log for `invalid entry options` and `invalid config`. Correct each listed path at the position shown. +4. Where a later patch addressed a child of a group whose `config` an earlier patch replaced, check that the child now receives the patch. +5. In code, read `applyEntryPatches(...).data`, and pass `structuredClone(patches)` where the patch list must stay unchanged. Catch parse errors without depending on js-yaml types; `entryYamlErrorPosition(error)` still returns the position. +6. Confirm that `dsh --dump-config` prints the expected entries and that the profile starts without those diagnostics. diff --git a/docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.zh.md new file mode 100644 index 0000000000..d1e3170659 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.2/cordis-loader-entry-validation/guide.zh.md @@ -0,0 +1,27 @@ +--- +kind: upgrade-guide +description: "Cordis Loader 1.0.0-rc.9 与 Include 1.2.0 按 YAML 1.2 解析、拒绝格式错误的条目,applyEntryPatches 改为返回 PatchResult。" +--- + +# Loader 校验条目选项,Include 按 YAML 1.2 解析 + +[English](guide.md) | 中文 + +## 变更 + +`@deepseek-ai/cordis-plugin-loader` 现在包含上游 Loader 1.0.0-rc.9,`@deepseek-ai/cordis-plugin-include` 包含 Include 1.2.0。受影响的是手写的 `cordis.yml`、`cordis.patch.yml` 与 overlay 文件,以及调用 Include 或 Loader 导出的代码: + +- Include 和 `parseEntryYaml` 按 YAML 1.2 core schema 解析,不再使用 js-yaml 的 JSON schema。`0b101` 这样的二进制整数现在读作字符串 `'0b101'`。空的 `!!js` 标量现在读作空表达式,求值结果为 `undefined`,不再解析失败。 +- 创建或更新条目前会校验条目选项。`name` 必须是字符串;`group` 必须是布尔值;`disabled` 必须是布尔值或 `!!js` 表达式;group 的 `config` 必须是列表;`inject` 必须是字符串列表或映射;`isolate` 必须是映射,其值为 `true` 或字符串。此前能加载但含有这类值的条目现在会被拒绝并记录日志,同级条目仍会启动。Include 文件中只要有一个条目不是映射,整个文件都会被拒绝。含 `:` 的 id 仍然可以使用。 +- 解析错误、条目选项错误和配置校验错误都会以 `file:line:column` 指出文件位置。条目自身的模块找不到时,错误为 `ModuleNotFoundError`,不含 Node 的 `imported from` 部分;其 `code` 仍为 `ERR_MODULE_NOT_FOUND`。 +- 替换 group `config` 的 patch 带来的子条目可以被后续 patch 定位,被替换掉的子条目则不能再被 patch。 +- `applyEntryPatches(data, patches, warn)` 返回 `{ data, index }`,不再直接返回条目列表;它会把生成的 id 写入 `patches` 中被替换的 group `config` 里的匿名条目。`parseEntryYaml` 抛出 `yaml` 包的 `YAMLError`,不再抛出 js-yaml 的 `YAMLException`。 + +## 迁移 + +1. 必须保持为数字的二进制整数改写为十进制或十六进制。 +2. 对每个 profile 运行 `dsh --dump-config`。解析错误现在会给出行号和列号;按提示修正对应的值。 +3. 启动 profile,检查日志中的 `invalid entry options` 和 `invalid config`,在给出的位置修正列出的每个路径。 +4. 如果后续 patch 针对的是某个 group 的子条目,而该 group 的 `config` 已被前面的 patch 替换,确认该子条目现在会应用这个 patch。 +5. 在代码中读取 `applyEntryPatches(...).data`;如果 patch 列表必须保持不变,传入 `structuredClone(patches)`。捕获解析错误时不要依赖 js-yaml 的类型;`entryYamlErrorPosition(error)` 仍会返回错误位置。 +6. 确认 `dsh --dump-config` 输出预期的条目,且 profile 启动时不再出现上述诊断。 diff --git a/packages/boot/app-boot/src/compatibility-preflight.ts b/packages/boot/app-boot/src/compatibility-preflight.ts index c8aeedf2ad..0cfe31d15b 100644 --- a/packages/boot/app-boot/src/compatibility-preflight.ts +++ b/packages/boot/app-boot/src/compatibility-preflight.ts @@ -156,7 +156,7 @@ function preflight( data = config.initial } if (!Array.isArray(data)) return undefined - const children = applyEntryPatches(data as EntryOptions[], config.patches, patchWarning(ctx)) + const children = applyEntryPatches(data as EntryOptions[], structuredClone(config.patches), patchWarning(ctx)).data return check(children, pathToFileURL(filename).href) ? `its included file ${filename} reaches an incompatible plugin, and that file is never rewritten` : undefined @@ -180,7 +180,7 @@ export function prepareProfilePatches( ctx: Context, patches: PatchOptions[], parentURL: string, binName = 'dsh', ): PatchOptions[] { if (ctx.get('profileContext') === undefined) return patches - const entries = applyEntryPatches([], patches, patchWarning(ctx)) + const entries = applyEntryPatches([], structuredClone(patches), patchWarning(ctx)).data const rows = prepareProfileEntries(ctx, entries, parentURL, binName) return rows.length === 0 ? [] : [{ insert: rows }] } diff --git a/packages/boot/app-boot/src/config-schema/collect.ts b/packages/boot/app-boot/src/config-schema/collect.ts index 0eed38de5c..dead6f222f 100644 --- a/packages/boot/app-boot/src/config-schema/collect.ts +++ b/packages/boot/app-boot/src/config-schema/collect.ts @@ -52,6 +52,10 @@ function entryList(value: unknown): unknown[] { return value as unknown[] } +function hasNonRecordEntry(rows: readonly unknown[]): boolean { + return rows.some(row => !record(row) || (row.group === true && Array.isArray(row.config) && hasNonRecordEntry(row.config))) +} + function includePatches(value: unknown): PatchOptions[] | undefined { if (value === undefined) return undefined if (!Array.isArray(value)) throw new Error('include patches must be a literal patch list; config expressions are not evaluated') @@ -157,9 +161,11 @@ export async function collectConfigSchemas( } const patches = includePatches(config.patches) const rows = entryList(source) + // Include rejects the whole file when any entry, including a group child, is not a mapping. + if (hasNonRecordEntry(rows)) throw new Error(`include ${filename} has an entry that is not a mapping; child declarations are unavailable`) let children: EntryOptions[] try { - children = applyEntryPatches(rows as EntryOptions[], patches, warn(path)) + children = applyEntryPatches(rows as EntryOptions[], patches, warn(path)).data } catch (error) { throw new Error(`include patches could not be composed for ${filename}; child declarations are unavailable`, { cause: error }) } diff --git a/packages/boot/app-boot/src/index.ts b/packages/boot/app-boot/src/index.ts index 13b3ff792c..52cf730d18 100644 --- a/packages/boot/app-boot/src/index.ts +++ b/packages/boot/app-boot/src/index.ts @@ -480,7 +480,7 @@ function rowIds(patches: readonly PatchOptions[]): Set { } } // Patch warnings are logged when the generation itself is prepared. - visit(applyEntryPatches([], patches as PatchOptions[], () => {})) + visit(applyEntryPatches([], patches as PatchOptions[], () => {}).data) return ids } @@ -614,9 +614,9 @@ export interface ConfigDumpLayer { * Compose the configured entry list: parse the base config file with the * include's entry-list dialect, apply every layer's patches as ONE flattened * list through the include's own patch algorithm (`applyEntryPatches`) — the - * same call `boot()` makes, so even patch-visibility corner cases (a later - * layer targeting a group child a plain config replacement introduced, which - * the single-pass id index never sees) compose identically — then render the + * same call `boot()` makes, so patch-visibility cases (a later layer + * targeting a group child that a group config replacement introduced or + * removed) compose identically — then render the * result as YAML in the same dialect (`!!js` expressions print verbatim, * unevaluated). Row admission is a later stage: a plugin row the compatibility * policy denies still appears here, while a denied bundle contributes no layer. @@ -673,14 +673,14 @@ export function renderConfigDump( // The patches are cloned per call: applyEntryPatches clones entries and // inserted rows but assigns override values such as `config` by reference, // so each snapshot keeps its own copies of those values. - const snapshot = (count: number, warnings: string[]): ReturnType => { + const snapshot = (count: number, warnings: string[]): ReturnType['data'] => { const flattened = structuredClone(layers.slice(0, count).flatMap(layer => layer.patches)) return applyEntryPatches(base, flattened, (message: string, ...args: unknown[]) => { // The include logs through cordis's printf-style logger (`%C` = code); a // dump has no logger, so substitute inline for a plain line. let index = 0 warnings.push(message.replace(/%C/g, () => JSON.stringify(args[index++]))) - }) + }).data } let previous = base let previousWarnings: string[] = [] diff --git a/packages/boot/app-boot/src/profile.ts b/packages/boot/app-boot/src/profile.ts index 32719f2484..86caac54a0 100644 --- a/packages/boot/app-boot/src/profile.ts +++ b/packages/boot/app-boot/src/profile.ts @@ -758,5 +758,5 @@ export function composeEntries( return applyEntryPatches([], structuredClone(layers.flat()), (message: string, ...args: unknown[]) => { let index = 0 warn(message.replace(/%C/g, () => JSON.stringify(args[index++]))) - }) + }).data } diff --git a/packages/boot/app-boot/tests/app-boot.spec.ts b/packages/boot/app-boot/tests/app-boot.spec.ts index e46864210f..b4eded6e9c 100644 --- a/packages/boot/app-boot/tests/app-boot.spec.ts +++ b/packages/boot/app-boot/tests/app-boot.spec.ts @@ -887,7 +887,7 @@ describe('loadOverlayPatches', () => { expect(loadOverlayPatches(NAME, valid)).toEqual([{ id: 'target', config: { value: { __jsExpr: 'process.env.VALUE' } } }]) expect(() => loadOverlayPatches(NAME, join(dir, 'missing.yml'))).toThrow(`${NAME}: failed to read overlay`) const malformed = join(dir, 'malformed.yml') - writeFileSync(malformed, ': bad') + writeFileSync(malformed, '- [bad\n') expect(() => loadOverlayPatches(NAME, malformed)).toThrow(`${NAME}: failed to parse overlay`) const mapping = join(dir, 'mapping.yml') writeFileSync(mapping, 'id: target\n') @@ -1202,7 +1202,7 @@ describe('boot', () => { it.each([ ['missing', undefined, 'config file not found'], - ['malformed', 'invalid: [unclosed\n', 'unexpected end'], + ['malformed', 'invalid: [unclosed\n', 'must be sufficiently indented and end with a ] (at '], ['non-array', 'entries: []\n', 'top-level array'], ])('rejects a %s root configuration', async (_kind, content, message) => { const dir = tmp() diff --git a/packages/boot/app-boot/tests/config-dump.spec.ts b/packages/boot/app-boot/tests/config-dump.spec.ts index 8a56d57e34..c3bc3bf88a 100644 --- a/packages/boot/app-boot/tests/config-dump.spec.ts +++ b/packages/boot/app-boot/tests/config-dump.spec.ts @@ -115,12 +115,9 @@ describe('renderConfigDump', () => { }) it('composes all layers as one flattened patch list, exactly like boot()', () => { - // boot() flattens every layer into ONE applyEntryPatches call, whose id - // index sees inserted rows but NOT children introduced by a plain group - // `config` replacement. A per-layer composition would rebuild the index - // between layers and let the second layer patch that child — a tree the - // real boot never mounts. Pin the single-call semantics: the child patch - // is skipped (with the layer-labeled warning), matching boot. + // boot() flattens every layer into ONE applyEntryPatches call. Children + // supplied by a group `config` replacement join the id index, so a later + // layer can patch them, and the dump lists that layer on the group row. const dir = tmp() const base = join(dir, 'base.yml') writeFileSync(base, [ @@ -138,14 +135,23 @@ describe('renderConfigDump', () => { }, { label: 'b.yml', patches: [{ id: 'child', config: { v: 2 } }] }, ], line => void warnings.push(line)) - expect(warnings).toEqual([`${NAME}: [b.yml] patch: entry "child" not found`]) + expect(warnings).toEqual([]) const parsed = parseEntryYaml(dump) as { config?: { config?: { v?: number } }[] }[] - expect(parsed[0]?.config?.[0]?.config?.v).toBe(1) - // The skipped layer did not change the row, so the comment does not list it. - expect(dump).toContain('# == base.yml, patched by a.yml\n- id: g') - expect(dump).not.toContain('b.yml\n- id: g') + expect(parsed[0]?.config?.[0]?.config?.v).toBe(2) + expect(dump).toContain('# == base.yml, patched by a.yml, b.yml\n- id: g') + }) + + it('drops the children of a replaced group config from the patch index', () => { + const dir = tmp() + const base = join(dir, 'base.yml') + writeFileSync(base, '- id: g\n name: ./group.mjs\n group: true\n config:\n - id: child\n name: ./noop.mjs\n') + const warnings: string[] = [] + renderConfigDump(NAME, base, [ + { label: 'a.yml', patches: [{ id: 'g', config: [] }, { id: 'child', disabled: true }] }, + ], line => void warnings.push(line)) + expect(warnings).toEqual([`${NAME}: [a.yml] patch: entry "child" not found`]) }) it('reports a patch whose target row is absent through warn with its layer label and keeps composing', () => { diff --git a/packages/boot/app-boot/tests/config-schema.spec.ts b/packages/boot/app-boot/tests/config-schema.spec.ts index debb11641a..04ae5a3e9c 100644 --- a/packages/boot/app-boot/tests/config-schema.spec.ts +++ b/packages/boot/app-boot/tests/config-schema.spec.ts @@ -418,15 +418,18 @@ describe('collectConfigSchemas', () => { expect(validates(result, [{ name: 'good', config: 3 }])).toBe(true) }) - it('keeps healthy group and include siblings after malformed child rows', async () => { + it('keeps healthy group siblings after a malformed child row and rejects an include with a non-mapping entry', async () => { modules.set('good', { Config: Schema.string() }) const result = await collectConfigSchemas(profile, [ row('cordis:group', [{ name: false }, row('good')]), - row('cordis:include', { path: './missing.yml', initial: [null, row('good')] }), + row('cordis:include', { path: './missing.yml', initial: [row('good'), { ...row('cordis:group', [null]), group: true }] }), ], resolution) - expect(result['x-cordis'].diagnostics.map(item => item.path)).toEqual(['/0/config/0', '/1/include/0']) + expect(result['x-cordis'].diagnostics.map(item => [item.path, item.message])).toEqual([ + ['/0/config/0', expect.any(String)], + ['/1', expect.stringContaining('has an entry that is not a mapping')], + ]) expect(result['x-cordis'].entries.filter(entry => entry.status === 'schema').map(entry => entry.path)) - .toEqual(['/0/config/1', '/1/include/1']) + .toEqual(['/0/config/1']) }) it.each([ diff --git a/packages/boot/app-boot/tests/user-patches.spec.ts b/packages/boot/app-boot/tests/user-patches.spec.ts index 5b0257aac1..a974eaddec 100644 --- a/packages/boot/app-boot/tests/user-patches.spec.ts +++ b/packages/boot/app-boot/tests/user-patches.spec.ts @@ -132,12 +132,12 @@ describe('loadOptionalPatches', () => { .toThrow(new RegExp(`^${NAME}: failed to read patches `)) }) - it('fails loud on unparsable YAML and on a !!js tag with no expression body', () => { + it('fails loud on unparsable YAML and on an unknown tag', () => { const dir = tmp() writeFileSync(join(dir, PROFILE_PATCH_FILENAME), 'invalid: [unclosed\n') expect(() => loadOptionalPatches(NAME, join(dir, PROFILE_PATCH_FILENAME))) .toThrow(new RegExp(`^${NAME}: failed to parse patches `)) - writeFileSync(join(dir, PROFILE_PATCH_FILENAME), '- id: x\n config:\n a: !!js\n') + writeFileSync(join(dir, PROFILE_PATCH_FILENAME), '- id: x\n config:\n a: !js process.env.A\n') expect(() => loadOptionalPatches(NAME, join(dir, PROFILE_PATCH_FILENAME))) .toThrow(new RegExp(`^${NAME}: failed to parse patches `)) }) @@ -343,8 +343,8 @@ describe('profile reconciliation settlement', () => { const ctx = await boot(NAME, join(dir, 'cordis.yml'), patches) onTestFinished(() => ctx.fiber.dispose()) // Reload diagnostics carry the import error's message without stack frames. - const prefix = 'missing-plugin \\(\\./missing\\.mjs\\): failed to import: Error \\[ERR_MODULE_NOT_FOUND\\]' - const diagnostic = new RegExp(`^${prefix}: Cannot find module '[^']*missing\\.mjs' imported from [^\\n]*$`, 'u') + const prefix = 'missing-plugin \\(\\./missing\\.mjs\\): failed to import: ModuleNotFoundError' + const diagnostic = new RegExp(`^${prefix}: Cannot find module '[^']*missing\\.mjs'$`, 'u') expect(await reconcileProfilePatches(ctx, patches, NAME)).toEqual([expect.stringMatching(diagnostic)]) }) diff --git a/packages/boot/plugin-manager/tests/patch.spec.ts b/packages/boot/plugin-manager/tests/patch.spec.ts index 9580da1e52..9ee0b9ec87 100644 --- a/packages/boot/plugin-manager/tests/patch.spec.ts +++ b/packages/boot/plugin-manager/tests/patch.spec.ts @@ -86,7 +86,7 @@ it('updates the last matching named override and leaves mismatched names untouch { id: 'tool', name: 'package', config: { value: { __jsExpr: 'process.platform' } }, disabled: false }, { id: 'tool', name: 'another-package', disabled: true }, ]) - expect(applyEntryPatches([{ id: 'tool', name: 'package' }], patches, () => {})) + expect(applyEntryPatches([{ id: 'tool', name: 'package' }], patches, () => {}).data) .toMatchObject([{ id: 'tool', name: 'package', disabled: false }]) expect(await writePluginEnabled(profile, 'tool', 'package', true)).toBe(false) expect(await readFile(profile.patchPath, 'utf8')).toBe(text) diff --git a/packages/bundle/web-app/tests/browser-defaults.spec.ts b/packages/bundle/web-app/tests/browser-defaults.spec.ts index 73ee9b1a82..b831a0f68f 100644 --- a/packages/bundle/web-app/tests/browser-defaults.spec.ts +++ b/packages/bundle/web-app/tests/browser-defaults.spec.ts @@ -20,7 +20,7 @@ it.each([ expect(rows).toHaveLength(1) expect(rows[0]!.name).toBe('@deepseek-ai/dsh-client-ui-sidebar-browser') const configured = applyEntryPatches(rows, override === undefined ? [] : [{ id: 'ui-sidebar-browser', disabled: override }], - (message) => { throw new Error(message) }) + (message) => { throw new Error(message) }).data const ctx = new Context() onTestFinished(() => ctx.fiber.dispose()) if (profile !== undefined) { diff --git a/packages/bundle/web-app/tests/document-conversion.e2e.ts b/packages/bundle/web-app/tests/document-conversion.e2e.ts index e5b4f130d9..b59841f3a2 100644 --- a/packages/bundle/web-app/tests/document-conversion.e2e.ts +++ b/packages/bundle/web-app/tests/document-conversion.e2e.ts @@ -28,7 +28,7 @@ it('loads one shared conversion row and retains caller-owned PDFs after disposal .filter(row => row.name === '@deepseek-ai/dsh-office-kit') expect(rows.map(row => row.id)).toEqual(['office-kit']) const configured = applyEntryPatches(rows, [{ id: 'office-kit', config: { maxConcurrentConversions: 1, outputDirectory } }], - (message) => { throw new Error(message) }) + (message) => { throw new Error(message) }).data const configPath = join(directory, 'cordis.yml') await writeFile(configPath, JSON.stringify(configured)) ctx.baseUrl = pathToFileURL(directory).href + '/' diff --git a/packages/bundle/web-app/tests/document-preview.spec.ts b/packages/bundle/web-app/tests/document-preview.spec.ts index ae78c1aa59..852b8c15f6 100644 --- a/packages/bundle/web-app/tests/document-preview.spec.ts +++ b/packages/bundle/web-app/tests/document-preview.spec.ts @@ -52,7 +52,7 @@ it('loads the shipped Office rows with separately patched settings and authorize const configured = applyEntryPatches(rows, [ { id: 'office-kit', config: providerConfig }, { id: 'ui-sidebar-documentpreview', config: clientConfig }, - ], (message) => { throw new Error(message) }) + ], (message) => { throw new Error(message) }).data expect(configured.find(row => row.id === 'ui-sidebar-documentpreview')!.config).toEqual(clientConfig) await writeFile(configPath, JSON.stringify([ { name: '@deepseek-ai/dsh-session' }, diff --git a/packages/host/plugin-inventory/tests/inventory.spec.ts b/packages/host/plugin-inventory/tests/inventory.spec.ts index 6e022ea922..980f9e6fda 100644 --- a/packages/host/plugin-inventory/tests/inventory.spec.ts +++ b/packages/host/plugin-inventory/tests/inventory.spec.ts @@ -181,7 +181,7 @@ describe('PluginInventoryGateway', () => { name: 'cordis:not-installed', disabled: true, }) - await ctx.loader.create({ name: 'cordis:active', group: true }) + await ctx.loader.create({ name: 'cordis:active', group: true, config: [] }) const snapshot = await inventory.list() // No agent-preset roster is composed, so the snapshot carries no presets. diff --git a/packages/test-support/client-runtime/src/assembly/bundle-roster.ts b/packages/test-support/client-runtime/src/assembly/bundle-roster.ts index d31ab8c876..98c6e46e24 100644 --- a/packages/test-support/client-runtime/src/assembly/bundle-roster.ts +++ b/packages/test-support/client-runtime/src/assembly/bundle-roster.ts @@ -56,7 +56,7 @@ export function bundleRoster( const layers = bundles.map(name => readLayer(name, anchor)) const entries = applyEntryPatches([], layers.flatMap(layer => layer.patches), (message: string, ...args: unknown[]) => { throw new Error(`client-test-runtime: bundle patch ${describe(message, args)}`) - }) + }).data const anchors = layers.map(layer => layer.manifestPath) const rows: ClientRosterRow[] = [] const seen = new Set() diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 680fd27625..754929b4b4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -18572,7 +18572,7 @@ importers: version: 16.3.3(@testing-library/dom@10.4.2)(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) vitest: specifier: ^4.1.11 - version: 4.1.11(@opentelemetry/api@1.9.1)(@types/node@22.20.1)(@vitest/coverage-v8@4.1.11)(happy-dom@20.11.6)(jsdom@29.1.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.0)) + version: 4.1.11(@opentelemetry/api@1.9.1)(@types/node@22.20.1)(@vitest/coverage-v8@4.1.11)(happy-dom@20.11.6)(jsdom@29.1.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.1)) devDependencies: '@deepseek-ai/cordis': specifier: workspace:~ @@ -18792,7 +18792,7 @@ importers: version: 4.3.2 vitest: specifier: ^4.1.11 - version: 4.1.11(@opentelemetry/api@1.9.1)(@types/node@22.20.1)(@vitest/coverage-v8@4.1.11)(happy-dom@20.11.6)(jsdom@29.1.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.0)) + version: 4.1.11(@opentelemetry/api@1.9.1)(@types/node@22.20.1)(@vitest/coverage-v8@4.1.11)(happy-dom@20.11.6)(jsdom@29.1.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.1)) devDependencies: '@deepseek-ai/cordis': specifier: workspace:~ @@ -20156,9 +20156,9 @@ importers: '@deepseek-ai/cosmokit': specifier: link:../cosmokit version: link:../cosmokit - js-yaml: - specifier: ^4.1.0 - version: 4.3.2 + yaml: + specifier: ^2.9.1 + version: 2.9.1 vendor/loader: dependencies: @@ -27905,6 +27905,11 @@ packages: engines: {node: '>= 14.6'} hasBin: true + yaml@2.9.1: + resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==} + engines: {node: '>= 14.6'} + hasBin: true + yargs-parser@20.2.9: resolution: {integrity: sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==} engines: {node: '>=10'} @@ -30910,6 +30915,14 @@ snapshots: optionalDependencies: vite: 8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.0) + '@vitest/mocker@4.1.11(vite@8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.1))': + dependencies: + '@vitest/spy': 4.1.11 + estree-walker: 3.0.3 + magic-string: 0.30.21 + optionalDependencies: + vite: 8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.1) + '@vitest/pretty-format@4.1.11': dependencies: tinyrainbow: 3.1.0 @@ -35661,6 +35674,21 @@ snapshots: tsx: 4.23.13 yaml: 2.9.0 + vite@8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.1): + dependencies: + lightningcss: 1.33.0 + picomatch: 4.0.7 + postcss: 8.5.28 + rolldown: 1.2.7 + tinyglobby: 0.2.17 + optionalDependencies: + '@types/node': 22.20.1 + esbuild: 0.28.2 + fsevents: 2.3.3 + jiti: 2.7.0 + tsx: 4.23.13 + yaml: 2.9.1 + vitepress-plugin-mermaid@2.0.17(mermaid@11.17.2)(vitepress@1.6.4(@algolia/client-search@5.55.2)(@types/node@22.20.1)(@types/react@18.3.31)(lightningcss@1.33.0)(postcss@8.5.28)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(search-insights@2.17.3)(typescript@6.0.3)): dependencies: mermaid: 11.17.2 @@ -35780,6 +35808,37 @@ snapshots: transitivePeerDependencies: - msw + vitest@4.1.11(@opentelemetry/api@1.9.1)(@types/node@22.20.1)(@vitest/coverage-v8@4.1.11)(happy-dom@20.11.6)(jsdom@29.1.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.1)): + dependencies: + '@vitest/expect': 4.1.11 + '@vitest/mocker': 4.1.11(vite@8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.1)) + '@vitest/pretty-format': 4.1.11 + '@vitest/runner': 4.1.11 + '@vitest/snapshot': 4.1.11 + '@vitest/spy': 4.1.11 + '@vitest/utils': 4.1.11 + es-module-lexer: 2.1.0 + expect-type: 1.3.0 + magic-string: 0.30.21 + obug: 2.1.3 + pathe: 2.0.3 + picomatch: 4.0.7 + std-env: 4.1.0 + tinybench: 2.9.0 + tinyexec: 1.2.4 + tinyglobby: 0.2.17 + tinyrainbow: 3.1.0 + vite: 8.2.2(@types/node@22.20.1)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.1) + why-is-node-running: 2.3.0 + optionalDependencies: + '@opentelemetry/api': 1.9.1 + '@types/node': 22.20.1 + '@vitest/coverage-v8': 4.1.11(vitest@4.1.11) + happy-dom: 20.11.6 + jsdom: 29.1.1(@noble/hashes@2.4.0) + transitivePeerDependencies: + - msw + vscode-jsonrpc@5.0.1: {} vscode-jsonrpc@9.0.1: {} @@ -35908,6 +35967,8 @@ snapshots: yaml@2.9.0: {} + yaml@2.9.1: {} + yargs-parser@20.2.9: {} yargs-parser@21.1.1: {} diff --git a/scripts/cordis-entry-commit.spec.ts b/scripts/cordis-entry-commit.spec.ts index e915af7b29..98e68ea8b4 100644 --- a/scripts/cordis-entry-commit.spec.ts +++ b/scripts/cordis-entry-commit.spec.ts @@ -99,7 +99,7 @@ describe('Loader tree mutation reports', () => { describe('Include patch data ownership', () => { it('detaches file entries even with no patches', () => { const data: EntryOptions[] = [{ id: 'x', name: 'example', config: { value: 1 } }] - const result = applyEntryPatches(data, undefined, vi.fn()) + const result = applyEntryPatches(data, undefined, vi.fn()).data result[0]!.disabled = true ;(result[0]!.config as { value: number }).value = 2 expect(data).toEqual([{ id: 'x', name: 'example', config: { value: 1 } }]) @@ -109,7 +109,7 @@ describe('Include patch data ownership', () => { const insert: EntryOptions[] = [{ id: 'g', name: 'group', group: true, config: [{ id: 'x', name: 'example', config: { value: 1 } }] }] const warn = vi.fn() - const result = applyEntryPatches([], [{ insert }, { id: 'x', disabled: true }], warn) + const result = applyEntryPatches([], [{ insert }, { id: 'x', disabled: true }], warn).data const children = result[0]!.config as Array<{ disabled?: boolean; config: { value: number } }> expect(children[0]!.disabled).toBe(true) children[0]!.config.value = 2 diff --git a/scripts/cordis-entry-yaml.spec.ts b/scripts/cordis-entry-yaml.spec.ts index 75d938e84b..13f670487f 100644 --- a/scripts/cordis-entry-yaml.spec.ts +++ b/scripts/cordis-entry-yaml.spec.ts @@ -10,11 +10,15 @@ describe('Include YAML dialect', () => { expect(stringifyEntryYaml(parsed)).toBe(source) }) - it('reads binary integers as numbers and dates as strings', () => { - expect(parseEntryYaml('- 0b101\n- 2001-01-01\n- ~\n')).toEqual([5, '2001-01-01', null]) + it('reads scalars under the YAML 1.2 core schema', () => { + expect(parseEntryYaml('- 0b101\n- 0o17\n- 0x1F\n- yes\n- 2001-01-01\n- ~\n')).toEqual(['0b101', 15, 31, 'yes', '2001-01-01', null]) expect(parseEntryYaml('')).toBeUndefined() }) + it('rejects unknown tags', () => { + expect(() => parseEntryYaml('- !!binary aGVsbG8=\n- !custom value\n')).toThrow() + }) + it('writes repeated references in full', () => { const shared = { value: 1 } expect(stringifyEntryYaml([{ config: shared }, { config: shared }])).toBe('- config:\n value: 1\n- config:\n value: 1\n') diff --git a/scripts/cordis-loader-rc9.spec.ts b/scripts/cordis-loader-rc9.spec.ts new file mode 100644 index 0000000000..8c5fa3eb80 --- /dev/null +++ b/scripts/cordis-loader-rc9.spec.ts @@ -0,0 +1,106 @@ +/** Loader rc.9 and Include 1.2 entry validation, located config errors and module lookup failures. */ +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import { Context, FiberState } from '@deepseek-ai/cordis' +import Loader, { EntryValidationError, Group, ModuleNotFoundError, type EntryOptions } from '@deepseek-ai/cordis-plugin-loader' +import Include, { ConfigFileError } from '@deepseek-ai/cordis-plugin-include' +import Schema from '@deepseek-ai/schemastery' +import { describe, expect, it, onTestFinished } from 'vitest' + +const Typed = Object.assign((_ctx: Context, _config: { value: number }) => {}, { + Config: Schema.object({ value: Schema.number().required() }), +}) + +async function fixture(filename: string, content: string) { + const dir = await mkdtemp(join(tmpdir(), 'dsh-loader-rc9-')) + const ctx = new Context() + onTestFinished(async () => { + await ctx.fiber.dispose() + await rm(dir, { recursive: true, force: true, maxRetries: 3 }) + }) + ctx.baseUrl = pathToFileURL(dir).href + '/' + await ctx.plugin(Loader) + ctx.loader.builtins.include = Include + ctx.loader.builtins.group = Group + ctx.loader.builtins.example = () => {} + ctx.loader.builtins.typed = Typed + const path = join(dir, filename) + await writeFile(path, content) + const errors: unknown[] = [] + const warnings: unknown[] = [] + ctx.logger.exporter({ + export: ({ type, args }: { type: string; args: unknown[] }) => { + if (type === 'error') errors.push(...args) + if (type === 'warn') warnings.push(...args) + }, + }) + const id = await ctx.loader.create({ name: 'cordis:include', config: { path: `./${filename}` } }) + await ctx.loader.await() + const entry = ctx.loader.resolve(id) + return { ctx, path, entry, include: entry.subtree as Include | undefined, errors, warnings } +} + +describe('Loader 1.0.0-rc.9 entry options', () => { + it('rejects invalid options before a tree changes', async () => { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + await ctx.plugin(Loader) + ctx.loader.builtins.example = () => {} + // Options read from a file are untyped; set the invalid values past the compiler. + const invalid = { name: 'cordis:example' } as EntryOptions + Reflect.set(invalid, 'disabled', 'yes') + Reflect.set(invalid, 'isolate', { svc: 1 }) + const error = await ctx.loader.create(invalid).catch((caught: unknown) => caught) + expect(error).toBeInstanceOf(EntryValidationError) + expect((error as EntryValidationError).issues).toEqual([ + { message: 'disabled must be a boolean', path: ['disabled'] }, + { message: 'isolate.svc must be true or a string', path: ['isolate', 'svc'] }, + ]) + expect(ctx.loader.root.data).toEqual([]) + await expect(ctx.loader.create({ name: 'cordis:example', group: true })).rejects.toThrow('config is required') + }) + + it('accepts explicit ids containing the separator from a file', async () => { + const app = await fixture('rows.yml', '- id: pkg:row\n name: cordis:example\n') + expect(app.include!.store['pkg:row']!.fiber!.state).toBe(FiberState.ACTIVE) + }) +}) + +describe('Include 1.2.0 config files', () => { + it('reports invalid entries and config values at their file positions', async () => { + const app = await fixture('rows.yml', [ + '- id: bad', + ' name: cordis:example', + ' disabled: 1', + '- id: typed', + ' name: cordis:typed', + ' config:', + ' value: text', + '', + ].join('\n')) + const messages = app.errors.map(String).join('\n') + expect(messages).toContain(`disabled must be a boolean (at disabled, ${app.path}:3:13)`) + expect(messages).toContain(`${app.path}:7:12`) + expect(app.include!.store['bad']).toBeUndefined() + expect(app.include!.store['typed']!.fiber!.state).not.toBe(FiberState.ACTIVE) + }) + + it('reports an unknown plugin module at its name position', async () => { + const app = await fixture('rows.yml', '- id: missing\n name: ./missing-plugin.js\n') + const error = app.errors.find(error => error instanceof ModuleNotFoundError) + expect(error?.specifier).toBe('./missing-plugin.js') + expect(error?.message).toContain(`(at name, ${app.path}:2:9)`) + }) + + it('parses YAML 1.2 core scalars and locates syntax errors', async () => { + const app = await fixture('rows.yml', '- id: typed\n name: cordis:typed\n config:\n value: 0x10\n') + expect(app.include!.store['typed']!.fiber!.effectiveConfig).toEqual({ value: 16 }) + await writeFile(app.path, '- id: typed\n name: [\n') + await app.include!.refresh() + const error = app.warnings.find(warning => warning instanceof ConfigFileError) + expect(error).toBeInstanceOf(ConfigFileError) + expect((error as ConfigFileError).issues[0]!.location).toMatchObject({ filename: app.path, line: 3 }) + }) +}) diff --git a/scripts/cordis-loader-resolve.spec.ts b/scripts/cordis-loader-resolve.spec.ts index 44febb061d..fac3fcb8ff 100644 --- a/scripts/cordis-loader-resolve.spec.ts +++ b/scripts/cordis-loader-resolve.spec.ts @@ -84,15 +84,18 @@ describe('Loader project resolution', () => { await expect(tree.import('./missing.js')).rejects.toThrow() }) - it('retains native import when helper creation is denied', async () => { + it('retains native import while helper creation is denied and retries it later', async () => { const { root, baseUrl } = await fixture() const tree = await treeFor(baseUrl) - const denied = vi.mocked(fs.mkdir).mockRejectedValueOnce(Object.assign(new Error('read-only project'), { code: 'EACCES' })) + const denied = vi.mocked(fs.mkdir).mockRejectedValue(Object.assign(new Error('read-only project'), { code: 'EACCES' })) onTestFinished(() => { denied.mockReset() }) expect(await createResolve(baseUrl)).toBeUndefined() expect(await tree.import('node:path')).toMatchObject({ join }) await expect(tree.import('fixture-dep')).rejects.toThrow() expect(existsSync(join(root, '.cordis'))).toBe(false) + denied.mockReset() + expect(await tree.import('fixture-dep')).toMatchObject({ tag: 'bare-dep' }) + expect(existsSync(join(root, '.cordis', 'resolve.mjs'))).toBe(true) }) it('retains native import without a file-backed package scope', async () => { diff --git a/scripts/verify-default-product-isolation.ts b/scripts/verify-default-product-isolation.ts index da405afe5e..aace669cc1 100644 --- a/scripts/verify-default-product-isolation.ts +++ b/scripts/verify-default-product-isolation.ts @@ -219,7 +219,7 @@ export function verifyDefaultProductIsolation(root: string): ProductIsolationRes failures.push(`${display(filename)}: included composition must contain an entry array`) return } - const entries = applyEntryPatches(content as EntryOptions[], entry.config.patches as PatchOptions[] | undefined, () => {}) + const entries = applyEntryPatches(content as EntryOptions[], entry.config.patches as PatchOptions[] | undefined, () => {}).data scanEntries(entries, filename, true, nestedStack) } } diff --git a/scripts/verify-product-use.ts b/scripts/verify-product-use.ts index dee30a0727..d4a1f0a73b 100644 --- a/scripts/verify-product-use.ts +++ b/scripts/verify-product-use.ts @@ -179,7 +179,7 @@ export function verifyProductUse( const content: unknown = existsSync(filename) ? loadCordisYaml(readFileSync(filename, 'utf8')) : row.config.initial configs.add(filename) if (!Array.isArray(content)) { failures.push(`${display(filename)}: Include requires an entry array or initial entries`); continue } - const entries = applyEntryPatches(content as EntryOptions[], row.config.patches as PatchOptions[] | undefined, () => {}) + const entries = applyEntryPatches(content as EntryOptions[], row.config.patches as PatchOptions[] | undefined, () => {}).data scanEntries(entries, filename, reach, new Set([...stack, filename])) } } diff --git a/vendor/README.md b/vendor/README.md index 2edebc8b40..06f3affe18 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -13,14 +13,14 @@ This file covers the manifest, the local-modification log, and the procedure for | `cosmokit/` | `@deepseek-ai/cosmokit` | `cosmokit` | 1.8.1 | https://github.com/shigma/cosmokit | `02e691c5aa7f37f6e0b1cee7ee8f4a21c2e34507` | | `schemastery/` | `@deepseek-ai/schemastery` | `schemastery` | 3.18.0 | https://github.com/shigma/schemastery (`packages/core`) | `cf0b7e5481d0e31d10cdc30bc45c09366c332f27` | | `cordis/` | `@deepseek-ai/cordis` | `cordis` | 4.0.0-rc.12 | https://github.com/cordiverse/cordis (`packages/core`) | `01b396240ce47cf2779c40af9bc445bb748fe112` | -| `loader/` | `@deepseek-ai/cordis-plugin-loader` | `@cordisjs/plugin-loader` | 1.0.0-rc.8 | https://github.com/cordiverse/cordis (`packages/loader`) | `0b96d9fd517b998e44e2209560c9e5f0671ce933` | -| `include/` | `@deepseek-ai/cordis-plugin-include` | `@cordisjs/plugin-include` | 1.1.1 | https://github.com/cordiverse/cordis (`packages/include`) | `0b96d9fd517b998e44e2209560c9e5f0671ce933` | +| `loader/` | `@deepseek-ai/cordis-plugin-loader` | `@cordisjs/plugin-loader` | 1.0.0-rc.9 | https://github.com/cordiverse/cordis (`packages/loader`) | `01b396240ce47cf2779c40af9bc445bb748fe112` | +| `include/` | `@deepseek-ai/cordis-plugin-include` | `@cordisjs/plugin-include` | 1.2.0 | https://github.com/cordiverse/cordis (`packages/include`) | `01b396240ce47cf2779c40af9bc445bb748fe112` | | `group/` | `@deepseek-ai/cordis-plugin-group` | `@cordisjs/plugin-group` | 1.0.0 | https://github.com/cordiverse/cordis (`packages/group`) | `01b396240ce47cf2779c40af9bc445bb748fe112` | | `timer/` | `@deepseek-ai/cordis-plugin-timer` | `@cordisjs/plugin-timer` | 1.1.4 | https://github.com/cordiverse/cordis (`packages/timer`) | `01b396240ce47cf2779c40af9bc445bb748fe112` | | `hmr/` | `@deepseek-ai/cordis-plugin-hmr` | `@cordisjs/plugin-hmr` | 1.0.15 | https://github.com/cordiverse/cordis (`packages/hmr`) | `ed8a7755c26a27a72064a21dea036ad1d1d6833c` | | `logger-console/` | `@deepseek-ai/cordis-plugin-logger-console` | `@cordisjs/plugin-logger-console` | 1.0.0 | https://github.com/cordiverse/cordis (`packages/logger-console`) | `01b396240ce47cf2779c40af9bc445bb748fe112` | -Third-party dependencies of the vendored packages stay on npm: `@standard-schema/spec`, `js-yaml`, `chokidar`, `picomatch`, `@babel/code-frame`, `supports-color`, `node-addon-require-builtin`. +Third-party dependencies of the vendored packages stay on npm: `@standard-schema/spec`, `yaml`, `chokidar`, `picomatch`, `@babel/code-frame`, `supports-color`, `node-addon-require-builtin`. Intentionally **not** vendored (verified unused by this set): `reggol`, `@cordisjs/utils`, `@cordisjs/element`, `@cordisjs/unyaml` (dev-time YAML import hook only). @@ -34,10 +34,10 @@ Keep this log exhaustive — every divergence from upstream must be listed. Each - **V4 · Vendored TypeScript source internal specifiers**: changed local relative imports/exports from upstream's specifier shape to explicit `.ts` specifiers so TypeScript rewrites emitted JS to `.js` while declarations keep explicit, NodeNext-safe `.ts` specifiers. This includes `loader/src/config/isolate.ts` using `declare module './entry.ts'`. Core's upstream source already uses explicit `.ts` specifiers. Type-only dependencies use `import type` or inline `type` modifiers so ESM output does not retain erased interfaces. - **V5 · `schemastery/tsdown.config.ts` and `logger-console/tsdown.config.ts`**: ours, not upstream files — per-package build-shape overrides (dual ESM+CJS output; separate node/browser entries) for the repo-root tsdown build. They read the JS emitted under `lib/types` and then write the publish runtime entries under `lib/`. Like the regenerated tsconfigs, they are not part of the upstream sync surface. - **V6 · `cordis/src/fiber.ts` lifecycle hardening**: locally closes three reentrant disposal gaps. An effect's owner-list wrapper is registered before its setup body runs, so an unload begun from inside setup awaits setup and every collected cleanup; synchronous setup failure removes the wrapper and rolls back collected cleanup. Async cleanup stays owner-visible until quiescence, and Cordis's internal effect composition joins an already-running cleanup while repeated public disposer calls retain their upstream single-shot result. Effect creation is rejected while the owner is `UNLOADING` (while `PENDING` and `LOADING` remain legal), preventing cleanup-time registrations from escaping the unload snapshot. Child fibers register and receive their parent-owned disposer before `internal/plugin` publication, resolve dependency declarations added by that notification before activation, drain effects attached while pending, and contain teardown-notification failures per observer so one callback cannot starve peers or interrupt ownership cleanup. -- **V7 · JSDoc enrichment**: added `@param`/`@returns` tags and contract documentation (disposal semantics, waterfall veto, bail conditions, error cases) across the public plugin-author surface — `Context` (class, statics, the `isolate()` rule that isolated scopes never fall back to an injected view, and the `Context` interface properties incl. `[Context.root]`), module re-exports, shared utility helpers, `EventsService`, `Fiber`, `ValidationError` and its path helpers, `RegistryService`, `ReflectService`, `Service` and its intercept-metadata members, `LoggerService` and their `declare module './context.ts'` overloads. The upstream line comment on `reflect.ts`'s exported `locate()` is rewritten as JSDoc. Loader documentation covers `loader/src/{index,internal,config/entry,config/group,config/isolate,config/tree,config/utils}.ts`, including entry ownership, tree mutation methods, and the `!!js` discriminator. The upstream `EventsService.dispatch()` deprecation annotation is omitted: DSH enumerates callbacks to contain each observer failure independently, which the typed dispatch methods do not provide. Timer retains its local class and helper summaries; its README is local documentation because the upstream package has none. Cosmokit and Schemastery add summaries to their exported helpers, types and namespaces, logger-console to its exporters and config namespace, and HMR to its build-failure logger in `hmr/src/error.ts`. Comment-only; no code changes. Motivation: the website API-reference generator renders these docs and hard-errors on undocumented members. Retire this entry when the enrichment is upstreamed. +- **V7 · JSDoc enrichment**: added `@param`/`@returns` tags and contract documentation (disposal semantics, waterfall veto, bail conditions, error cases) across the public plugin-author surface — `Context` (class, statics, the `isolate()` rule that isolated scopes never fall back to an injected view, and the `Context` interface properties incl. `[Context.root]`), module re-exports, shared utility helpers, `EventsService`, `Fiber`, `ValidationError` and its path helpers, `RegistryService`, `ReflectService`, `Service` and its intercept-metadata members, `LoggerService` and their `declare module './context.ts'` overloads. The upstream line comment on `reflect.ts`'s exported `locate()` is rewritten as JSDoc. Loader documentation covers `loader/src/{index,internal,config/entry,config/group,config/isolate,config/tree,config/utils}.ts`, including entry ownership, tree mutation methods, the `!!js` discriminator, entry option validation, source positions and `ModuleNotFoundError`. The upstream `EventsService.dispatch()` deprecation annotation is omitted: DSH enumerates callbacks to contain each observer failure independently, which the typed dispatch methods do not provide. Timer retains its local class and helper summaries; its README is local documentation because the upstream package has none. Cosmokit and Schemastery add summaries to their exported helpers, types and namespaces, logger-console to its exporters and config namespace, and HMR to its build-failure logger in `hmr/src/error.ts`. Comment-only; no code changes. Motivation: the website API-reference generator renders these docs and hard-errors on undocumented members. Retire this entry when the enrichment is upstreamed. - **V9 · `hmr/src/index.ts` module-watcher readiness and native paths**: realpath the existing watch base, classify framework modules and attach listeners before reporting readiness, and compare config paths using both canonical and configured spellings. This preserves Node module-cache identity across Windows short-name paths and filesystem aliases. The main watcher uses `ignoreInitial: true` so startup reads do not trigger another refresh; exact profile patch watching is owned by `packages/boot/hmr/src/watch-config.ts`. The Include change listener logs a rejected `Include.refresh()` instead of leaving the rejection unhandled; the rejection reports unsaved runtime changes while Include keeps its running tree. Covered by `packages/boot/hmr/tests/watch-config.spec.ts` and `scripts/cordis-vendor-hmr-include.spec.ts`. - **V10 · Vendored Node-compatible TypeScript**: marked erased imports explicitly across `cordis`, `loader`, `include`, `hmr`, and `schemastery` so Node's native TypeScript transform does not request types as runtime exports. Schemastery's source uses an ESM default export and its package declares `type: module`. Conditional exports select `.mjs` for import and `.cjs` for require; without them, concurrent imports under module-hook hosts reach the CJS entry and can race its require of ESM Cosmokit (`ERR_REQUIRE_ESM_RACE_CONDITION`). -- **V11 · Include patch and YAML exports**: `include/src/index.ts` exports upstream `applyPatches` as `applyEntryPatches`, so `dsh --dump-config` composes entries with the same algorithm that mounting uses. It also exports `parseEntryYaml`, `stringifyEntryYaml` and `entryYamlErrorPosition` over the `!!js` YAML dialect, and `_read()` parses through `parseEntryYaml`, so every DSH reader and writer of Include-dialect YAML uses Include's parser; `stringifyEntryYaml` always writes with `noRefs` and offers no option to emit aliases, while Include's own writer keeps upstream's options. Covered by `packages/boot/app-boot/tests/config-reload.spec.ts`, `scripts/cordis-entry-commit.spec.ts` and `scripts/cordis-entry-yaml.spec.ts`. +- **V11 · Include patch and YAML exports**: `include/src/index.ts` exports upstream `applyPatches` as `applyEntryPatches` with its `PatchResult` type, so `dsh --dump-config` composes entries with the same algorithm that mounting uses. It also exports `parseEntryYaml`, `stringifyEntryYaml` and `entryYamlErrorPosition` over the `!!js` YAML dialect, using the `yaml` options with which `_read()` parses Include's own file, so every DSH reader and writer of Include-dialect YAML uses Include's parser. `parseEntryYaml` throws the first parse error or warning, such as an unknown tag, and returns `undefined` for an empty document; `stringifyEntryYaml` always writes with `aliasDuplicateObjects: false`, matching the previous `noRefs` output, and offers no option to emit aliases, while Include's own writer keeps upstream's options. Covered by `packages/boot/app-boot/tests/config-reload.spec.ts`, `scripts/cordis-entry-commit.spec.ts` and `scripts/cordis-entry-yaml.spec.ts`. - **V14 · Include persistence results**: `include/src/index.ts` keeps an error for unsaved journal changes. `flush()` retries pending writes and rejects while changes remain unsaved; `stop()` returns the same result and always stops the child tree; a later successful flush clears previous errors. A failed `refresh()` can also reject while runtime changes remain unsaved. Patch-owned changes route to the parent Include, so callers that need them persisted must flush that parent too. The constructor omits upstream's `ctx.hmr.watch(this.filename, () => this.refresh())` registration because neither HMR provider exposes `watch()`; both find each Include by scanning loader entries for its `filename` and call `refresh()`. Ordinary Fiber teardown keeps its error containment. Covered by `scripts/cordis-include-journal.spec.ts` and `packages/host/directory-picker-auto/tests/loader-composition.spec.ts`. - **V15 · Configuration access across Core, Loader, Include and HMR**: rc.11 Core owns raw `Fiber.config`, `internal/config(fiber, next)`, `internal/commit` and awaited `internal/update(config, next)`. Root-fiber candidate resolution remains available without a plugin schema. Local `rawConfig`, `resolveConfig(candidate)` and `effectiveConfig` accessors retain the DSH consumer API. Fiber caches the object passed to activation or a successful update that keeps the instance; candidate resolution is pure, failed or superseded updates cannot replace the cache, and volatile updates retain references. Loader resolves only entry roots and excludes Group/Include tree carriers, so nested `!!js` expressions wait for their own injections. Include retains its tree-carrier marker and public patch exports, and HMR transfers raw config through the accessors. Covered by `scripts/cordis-config-access.spec.ts`, `scripts/cordis-core-lifecycle.spec.ts` and the boot/HMR suites. - **V16 · `cordis/package.json` publishes `src`**: added `src` to the `files` list, joining the other eight vendored packages. Cordis declares `"./src/*": "./src/*"` in its exports, so a tarball without `src` publishes an export map pointing at absent files; the release change judgement also reads `files` to decide whether a diff reaches the payload, and a package whose only published paths are build output has no tracked path to match. @@ -46,15 +46,14 @@ Keep this log exhaustive — every divergence from upstream must be listed. Each - **V23 · `loader/src/config/entry.ts` module identity**: retains each entry's raw import result as `moduleNamespace`, before plugin export normalization. HMR matches that object to Node's cached module namespace and updates it after a successful reload. `EntryTree.import()` keeps its existing arguments and return value; `loader/README.md` documents the additive field. - **V24 · `timer/locale/{en,zh}.json` display metadata**: local English and Chinese titles and descriptions for the Settings plugin inventory. `timer/package.json` exports and publishes these locale resources. - **V25 · Loader lifecycle adaptations**: before a combined context/config update, Loader refreshes dependencies locally, which prevents activation against stale isolation bindings; disabled-entry updates await disposal. Failed fibers require an explicit update after correcting their input or dependencies. Core retains the effect hardening in V6; rc.11 owns dependency teardown ordering and superseded-activation handling. -- **V26 · `loader/src/config/tree.ts` cross-tree moves**: backports [cordiverse/cordis#271](https://github.com/cordiverse/cordis/pull/271), merged after `v4.0.0-rc.11`. When `EntryTree.update()` moves an entry into a group of another tree, the entry and the same-tree members of its group move their store registrations to the target tree, and the move is rejected before either tree changes when the target tree already holds one of their ids. The source tree receives a removal and the target tree a creation, without `legacy` or `from`. In rc.11 the entry stays registered in the source tree and the target receives an update with `legacy`, so the Include journal writes a partial row and reconciling the target file creates a second Entry. Retire this entry when the vendored Loader includes the upstream fix. Covered by `scripts/cordis-include-journal.spec.ts`. -- **V27 · `loader/src/config/tree.ts` explicit ids with `:`**: `ensureId()` accepts explicit ids containing `EntryTree.sep`; upstream rejects them. Generated bundles from `@deepseek-ai/dsh-creation-recommendations` prefix their row ids with `:`, and installed profiles already contain such rows. `resolve()` still splits ids on `:`, so these entries cannot be addressed by nested path. Covered by `scripts/cordis-entry-commit.spec.ts` and `packages/experimental/creation-recommendations/tests/loader-composition.spec.ts`. -- **V28 · Core rc.12 compatibility in Loader and Include**: `loader/src/index.ts` declares `[Service.metadata]`, resolves its intercept through `[Service.resolveIntercept]` and logs through `ctx[Context.root]`; `include/src/index.ts` logs through `ctx[Context.root]`. These lines match the `v4.0.0-rc.12` tag while the rest of both packages keeps its rc.11 baseline. Retire this entry when Loader and Include are synchronized to that tag. +- **V26 · `loader/src/config/tree.ts` cross-tree moves**: backports [cordiverse/cordis#271](https://github.com/cordiverse/cordis/pull/271), merged after `v4.0.0-rc.12`. When `EntryTree.update()` moves an entry into a group of another tree, the entry and the same-tree members of its group move their store registrations to the target tree, and the move is rejected before either tree changes when the target tree already holds one of their ids. The source tree receives a removal and the target tree a creation, without `legacy` or `from`. Upstream at `v4.0.0-rc.12` keeps the entry registered in the source tree and the target receives an update with `legacy`, so the Include journal writes a partial row and reconciling the target file creates a second Entry. Retire this entry when the vendored Loader includes the upstream fix. Covered by `scripts/cordis-include-journal.spec.ts`. +- **V27 · `loader/src/config/utils.ts` explicit ids with `:`**: `validateOptions()` accepts ids containing `EntryTree.sep`, so `EntryTree.create()`, `EntryTree.update()` and group reconciliation admit them; upstream rejects them with an `id must not contain` issue. `validateOptions()` keeps its upstream `sep` parameter. Generated bundles from `@deepseek-ai/dsh-creation-recommendations` prefix their row ids with `:`, and installed profiles already contain such rows. `resolve()` still splits ids on `:`, so these entries cannot be addressed by nested path. Covered by `scripts/cordis-entry-commit.spec.ts`, `scripts/cordis-loader-rc9.spec.ts` and `packages/experimental/creation-recommendations/tests/loader-composition.spec.ts`. ### Resolver adaptations -Relative to the resolver source in Cordis `v4.0.0-rc.11`: +Relative to the resolver source in Cordis `v4.0.0-rc.12`: -- **Web build imports:** `loader/src/resolve.ts` uses default imports for Node builtin modules to support the Web shell's browser externalization. The shell supplies its own module loader. +- **Web build imports:** `loader/src/resolve.ts` and `loader/src/config/tree.ts` use default imports for Node builtin modules to support the Web shell's browser externalization. The shell supplies its own module loader. - **Package-scope cache keys:** `loader/src/resolve.ts` normalizes directory paths with `path.resolve()` before finding the package scope. A root config and a nested config in the same package therefore share the same cached resolver promise and helper-file write. Covered by `scripts/cordis-loader-resolve.spec.ts`. ## Sync procedure diff --git a/vendor/include/README.md b/vendor/include/README.md index 1ce78ec9a9..997f1857df 100644 --- a/vendor/include/README.md +++ b/vendor/include/README.md @@ -35,16 +35,22 @@ Example `cordis.yml`: | Field | Description | | --- | --- | -| `path` | YAML or JSON file path resolved from `ctx.baseUrl`. | +| `path` | YAML or JSON file path resolved from `ctx.baseUrl`; on Windows a drive-letter path is used as a file path. | | `initial` | Entry list written when the file is missing. | | `patches` | Runtime patches applied after reading the file. | | `enableLogs` | Enables loader apply, reload, and unload logs. | -Patches can insert entries or override fields on entries with a matching `id`. +Patches can insert entries or override fields on entries with a matching `id`. A patch that replaces a group's `config` brings its own child entries, which later patches can address; the children it replaces can no longer be patched. + +## File format and errors + +YAML files are parsed as YAML 1.2 under the core schema with the `yaml` package, plus the `!!js` tag for Loader expressions. Unknown tags are rejected. The file must be a top-level array whose entries, including the entries of each group, are mappings. A file that cannot be read, parsed or validated rejects with `ConfigFileError`; parse and validation errors carry `issues`, each with a message and a `file:line:column` location, and JSON files report the position of their syntax error. Include implements `getLocation(id, path)` for its entries: values written in the file resolve to the file, values supplied by a patch resolve through the parent entry to that patch, and values changed at runtime but not yet written resolve to nothing. + +Anonymous entries receive ids before the Loader sees them. An anonymous entry identical to one named on the previous read, under the same parent, keeps that id unless the file or an inserted patch row now uses it explicitly. ## Patch composition and persistence -`applyEntryPatches(data, patches, warn)` uses the same upstream algorithm as mounting. It clones file entries even without patches and clones inserted entry lists before indexing them, so later patches can address inserted rows without mutating those input lists. `parseEntryYaml(content)` and `stringifyEntryYaml(value, options)` read and write Include’s YAML dialect for configuration tools, and `entryYamlErrorPosition(error)` locates a parse error. `stringifyEntryYaml` writes repeated references in full instead of as aliases. Nested entry expressions remain literal until their owning Loader entry evaluates them. +`applyEntryPatches(data, patches, warn)` uses the same upstream algorithm as mounting and returns a `PatchResult`: the composed entries as `data`, and as `index` the owner of every entry and key, built from the patches that apply. It clones file entries even without patches and clones inserted entry lists and replaced group configs before indexing them, so later patches can address those rows without mutating the input lists. It writes generated ids for anonymous entries of a replaced group config into the patch itself, so callers that keep their patches unchanged pass clones. `parseEntryYaml(content)` and `stringifyEntryYaml(value, options)` read and write Include’s YAML dialect for configuration tools with the options Include uses for its own file, and `entryYamlErrorPosition(error)` locates a parse error. `stringifyEntryYaml` writes repeated references in full instead of as aliases; Include’s own writer may write a repeated reference as an alias. Nested entry expressions remain literal until their owning Loader entry evaluates them. Tree mutations arrive through `commit(change)` and enter a journal. Include merges them with the latest file before writing; file edits win conflicts on the same fields and produce a diagnostic. Patch-owned fields and inserted entries update the parent Include’s patches instead of the included file. Invalid, missing or read-only files leave unsaved changes in memory. diff --git a/vendor/include/package.json b/vendor/include/package.json index 4788d0a828..37afb43bb3 100644 --- a/vendor/include/package.json +++ b/vendor/include/package.json @@ -35,6 +35,6 @@ }, "dependencies": { "@deepseek-ai/cosmokit": "workspace:~", - "js-yaml": "^4.1.0" + "yaml": "^2.9.1" } } diff --git a/vendor/include/src/index.ts b/vendor/include/src/index.ts index ae489afeaa..8e9add4f8b 100644 --- a/vendor/include/src/index.ts +++ b/vendor/include/src/index.ts @@ -1,27 +1,40 @@ -import { type EntryChange, type EntryOptions, EntryTree, EntryGroup, isJsExpr } from '@deepseek-ai/cordis-plugin-loader' +import { type EntryChange, type EntryOptions, EntryTree, EntryGroup, isJsExpr, type SourceLocation } from '@deepseek-ai/cordis-plugin-loader' import { Context, Service } from '@deepseek-ai/cordis' import { deepEqual } from '@deepseek-ai/cosmokit' import { basename, dirname, extname, join } from 'node:path' import { access, constants, readFile, rename, rm, writeFile } from 'node:fs/promises' import { setTimeout as sleep } from 'node:timers/promises' import { fileURLToPath, pathToFileURL } from 'node:url' -import * as yaml from 'js-yaml' +import { + isAlias, isMap, isNode, isScalar, isSeq, LineCounter, parseDocument, Scalar, stringify, YAMLError, + type Document, type Range, type ScalarTag, type SchemaOptions, +} from 'yaml' +import { stringifyString } from 'yaml/util' import { applyJournal, flatten, type Journal, merge, reconcile, record } from './journal.ts' -import { applyPatches, ensureIds, ensureInsertIds, PatchIndex, type PatchOptions, routeJournal } from './patch.ts' +import { applyPatches, ensureIds, ensureInsertIds, type PatchIndex, type PatchOptions, routeJournal } from './patch.ts' /** Shared patch semantics used by config dumps and mounting. */ export { applyPatches as applyEntryPatches } from './patch.ts' -/** Serialized entry patch options. */ -export type { PatchOptions } from './patch.ts' +/** Serialized entry patch options and the composed result of applying them. */ +export type { PatchOptions, PatchResult } from './patch.ts' -const JsExpr = new yaml.Type('tag:yaml.org,2002:js', { - kind: 'scalar', - resolve: (data) => typeof data === 'string', - construct: (data) => ({ __jsExpr: data }), - predicate: isJsExpr, - represent: (data) => data['__jsExpr'], -}) +// A Windows drive-letter path, e.g. `C:\app\cordis.yml` or `C:/app/cordis.yml`. +const driveLetter = /^[A-Za-z]:[\\/]/ -const schema = yaml.JSON_SCHEMA.extend(JsExpr) +const JsExpr: ScalarTag = { + tag: 'tag:yaml.org,2002:js', + identify: isJsExpr, + resolve: (source) => ({ __jsExpr: source }), + // quoted like any other string + stringify: (item, ctx, onComment, onChompKeep) => { + const scalar = new Scalar((item.value as any).__jsExpr) + return stringifyString(Object.assign(scalar, { type: item.type }), ctx, onComment, onChompKeep) + }, +} + +const yamlOptions: SchemaOptions = { + schema: 'core', + customTags: [JsExpr], +} /** Options for {@link stringifyEntryYaml}. */ export interface EntryYamlStringifyOptions { @@ -30,14 +43,18 @@ export interface EntryYamlStringifyOptions { } /** - * Parse text in Include's YAML dialect. A `!!js` scalar becomes a child-owned JavaScript expression node that stays - * literal until its owning Loader entry evaluates it. + * Parse text in Include's YAML dialect: YAML 1.2 under the core schema, plus `!!js`. A `!!js` scalar becomes a + * child-owned JavaScript expression node that stays literal until its owning Loader entry evaluates it. Include + * reads its own file with the same options. * @param content - YAML source text. * @returns the parsed value, or `undefined` for an empty document. - * @throws the parser's syntax error; {@link entryYamlErrorPosition} reads its location. + * @throws the first parse error, or the first warning such as an unknown tag; {@link entryYamlErrorPosition} reads its location. */ export function parseEntryYaml(content: string): unknown { - return yaml.load(content, { schema }) + const document = parseDocument(content, yamlOptions) + const [error] = [...document.errors, ...document.warnings] + if (error) throw error + return document.contents === null ? undefined : document.toJS() } /** @@ -48,17 +65,18 @@ export function parseEntryYaml(content: string): unknown { * @returns YAML text ending with a newline. */ export function stringifyEntryYaml(value: unknown, options: EntryYamlStringifyOptions = {}): string { - return yaml.dump(value, { schema, noRefs: true, lineWidth: options.lineWidth ?? 80 }) + return stringify(value, { ...yamlOptions, singleQuote: true, aliasDuplicateObjects: false, lineWidth: options.lineWidth ?? 80 }) } /** - * Locate a syntax error thrown by {@link parseEntryYaml}. + * Locate a parse error thrown by {@link parseEntryYaml}. * @param error - any caught value; only a parse error thrown by {@link parseEntryYaml} yields a position. * @returns the one-based line and column of the error, or `undefined` when the error carries no source location. */ export function entryYamlErrorPosition(error: unknown): { line: number; column: number } | undefined { - if (!(error instanceof yaml.YAMLException) || !error.mark) return undefined - return { line: error.mark.line + 1, column: error.mark.column + 1 } + if (!(error instanceof YAMLError) || !error.linePos) return undefined + const [{ line, col }] = error.linePos + return { line, column: col } } const types: Record = { @@ -69,16 +87,40 @@ const types: Record = { type ConfigStage = 'read' | 'parse' | 'validate' +/** JSON is parsed as YAML too, for node ranges and line positions. */ +interface Syntax { + document: Document + lines: LineCounter +} + +function parseSyntax(content: string): Syntax { + const lines = new LineCounter() + const document = parseDocument(content, { ...yamlOptions, prettyErrors: false, lineCounter: lines }) + return { document, lines } +} + interface Snapshot { content: string data: EntryOptions[] + /** Parsed on first use. */ + syntax?: Syntax +} + +// e.g. `at position 17 (line 2 column 16)` +const jsonPosition = /\s+at position (\d+)(?: \(line \d+ column \d+\))?$/ + +export interface ConfigIssue { + message: string + location: SourceLocation } export class ConfigFileError extends Error { name = 'ConfigFileError' - constructor(public stage: ConfigStage, path: string, cause: unknown) { - super(`failed to ${stage} config file ${path}`, { cause }) + constructor(public stage: ConfigStage, path: string, cause: unknown, public issues: ConfigIssue[] = []) { + super([`failed to ${stage} config file ${path}`, ...issues.map(({ message, location }) => { + return ` - ${message} (at ${location.filename}:${location.line}:${location.column})` + })].join('\n'), { cause }) } } @@ -119,6 +161,50 @@ export namespace Include { } } +/** Index path of an entry in a nested entry list. */ +function findEntry(entries: EntryOptions[], id: string): PropertyKey[] | undefined { + for (const [index, options] of entries.entries()) { + if (options.id === id) return [index] + if (!options.group || !Array.isArray(options.config)) continue + const path = findEntry(options.config, id) + if (path) return [index, 'config', ...path] + } +} + +function findInvalidEntries(entries: unknown[], prefix: PropertyKey[] = []): PropertyKey[][] { + return entries.flatMap((options: any, index) => { + if (!options || typeof options !== 'object' || Array.isArray(options)) return [[...prefix, index]] + if (!options.group || !Array.isArray(options.config)) return [] + return findInvalidEntries(options.config, [...prefix, index, 'config']) + }) +} + +/** + * Range of the node at `path`, or of its deepest ancestor. A collection is + * represented by the key that holds it. + */ +function seek(document: Document, path: PropertyKey[]): Range | null | undefined { + let node: unknown = document.contents + let anchor = isNode(node) ? node.range : undefined + for (const key of path) { + if (isAlias(node)) node = node.resolve(document) + if (isMap(node)) { + const pair = node.items.find(pair => String(isScalar(pair.key) ? pair.key.value : pair.key) === String(key)) + if (!pair) break + node = pair.value + if (isNode(pair.key)) anchor = pair.key.range + } else if (isSeq(node)) { + const item = node.items[key as number] + if (!isNode(item)) break + node = item + anchor = item.range + } else { + break + } + } + return isScalar(node) ? node.range : anchor +} + export class Include extends EntryTree { static inject = ['loader'] @@ -132,6 +218,8 @@ export class Include extends EntryTree { private cache?: Snapshot /** Tree-side changes that have not reached the file yet. */ private journal: Journal = new Map() + /** Where the entries of the applied tree come from. */ + private index?: PatchIndex /** Ids we assigned to entries the file leaves anonymous. */ private anonymous = new Map() @@ -150,7 +238,11 @@ export class Include extends EntryTree { constructor(ctx: Context, public config: Include.Config) { super(ctx) this.enableLogs = config.enableLogs ?? ctx.fiber.entry?.parent.tree.enableLogs ?? false - this.filename = fileURLToPath(new URL(this.config.path, this.ctx.baseUrl)) + // On Windows, a drive-letter path is converted with `pathToFileURL`. + // `new URL()` would read its `C:` as a URL scheme, which `fileURLToPath` rejects. + this.filename = fileURLToPath(process.platform === 'win32' && driveLetter.test(this.config.path) + ? pathToFileURL(this.config.path) + : new URL(this.config.path, this.ctx.baseUrl)) const ext = extname(this.filename) if (!types[ext]) { throw new Error(`extension "${ext}" not supported`) @@ -289,30 +381,59 @@ export class Include extends EntryTree { if (content === this.cache?.content) return let data: any - try { - data = this.type === 'application/yaml' - ? parseEntryYaml(content) - : JSON.parse(content) - } catch (error) { - throw new ConfigFileError('parse', this.filename, error) + let syntax: Syntax | undefined + if (this.type === 'application/yaml') { + syntax = parseSyntax(content) + const { document, lines } = syntax + // unknown tags are only warnings to the parser, but leave the data incomplete + const errors: YAMLError[] = [...document.errors, ...document.warnings] + if (errors.length) { + const issues = errors.map(error => ({ message: error.message, location: this._locate(lines, error.pos[0]) })) + throw new ConfigFileError('parse', this.filename, undefined, issues) + } + data = document.toJS() + } else { + try { + data = JSON.parse(content) + } catch (error) { + const match = error instanceof SyntaxError && error.message.match(jsonPosition) + if (!match) throw new ConfigFileError('parse', this.filename, error) + const message = error.message.slice(0, match.index) + const location = this._locate(parseSyntax(content).lines, +match[1]) + throw new ConfigFileError('parse', this.filename, undefined, [{ message, location }]) + } } // An empty or truncated file (routine mid-edit) parses to `undefined`, so // every non-array shape is rejected here as one "invalid file" signal. if (!Array.isArray(data)) { - throw new ConfigFileError('validate', this.filename, new TypeError('config file must be a top-level array')) + const message = 'config file must be a top-level array' + const { document, lines } = syntax ?? parseSyntax(content) + const range = document.contents?.range + if (!range) throw new ConfigFileError('validate', this.filename, new TypeError(message)) + throw new ConfigFileError('validate', this.filename, undefined, [{ message, location: this._locate(lines, range[0]) }]) + } + // ids, patches and the journal all assume an entry is an object + const invalid = findInvalidEntries(data) + if (invalid.length) { + const { document, lines } = syntax ?? parseSyntax(content) + const issues = invalid.map((path) => { + const range = seek(document, path) + return { message: 'entry must be an object', location: this._locate(lines, range?.[0] ?? 0) } + }) + throw new ConfigFileError('validate', this.filename, undefined, issues) } this._assignIds(data) if (this.cache) { - const index = new PatchIndex(this.config.patches ?? []) + const { index } = applyPatches(data, this.config.patches) const conflicts = reconcile(this.journal, flatten(this.cache.data), flatten(data), (id, key) => index.fileOwned(id, key)) for (const { id, reason } of conflicts) { this.ctx.logger.error('config conflict in %C: entry %C %s; file wins', this.filename, id, reason) } } - this.cache = { content, data } + this.cache = { content, data, syntax } this._scheduleApply() // the file changed while tree-side changes were pending: write the merge if (this.journal.size) this.dirtyWrite = true @@ -430,60 +551,91 @@ export class Include extends EntryTree { private dump(data: EntryOptions[]) { return this.type === 'application/yaml' - ? yaml.dump(data, { schema }) + ? stringify(data, { ...yamlOptions, singleQuote: true }) : JSON.stringify(data, null, 2) } + getLocation(id: string, path: PropertyKey[]): SourceLocation | undefined { + if (!this.cache || !this.index) return + // values changed at runtime are not written anywhere yet + const record = this.journal.get(id) + if (record?.kind === 'remove') return + if (path.length && record && String(path[0]) in record.changes) return + + const owner = path.length ? this.index.key(id, String(path[0])) : this.index.entry(id) + if (owner.type === 'patch') { + return this.ctx.fiber.entry?.getLocation(['config', 'patches', owner.index, ...path]) + } else if (owner.type === 'embedded') { + const prefix = findEntry(this.config.patches![owner.index][owner.key], id) + if (!prefix) return + return this.ctx.fiber.entry?.getLocation(['config', 'patches', owner.index, owner.key, ...prefix, ...path]) + } + const prefix = findEntry(this.cache.data, id) + if (!prefix) return + const { document, lines } = this.cache.syntax ??= parseSyntax(this.cache.content) + const range = seek(document, [...prefix, ...path]) + if (range) return this._locate(lines, range[0]) + } + + private _locate(lines: LineCounter, offset: number): SourceLocation { + const { line, col } = lines.linePos(offset) + return { filename: this.filename, line, column: col } + } + /** * Entries the file leaves anonymous get an id here, before the loader sees * them. One that looks exactly like an entry we named on the previous read - * keeps that id, so editing a neighbor does not restart it; anything else - * gets a fresh id. Assigned ids stay in memory until the next write. + * keeps that id, unless it is already explicitly owned, so editing a + * neighbor does not restart it; anything else gets a fresh id. Assigned + * ids stay in memory until the next write. */ private _assignIds(data: EntryOptions[]) { const used = new Set() - const pending: { options: EntryOptions; parent: string | null }[] = [] - const walk = (entries: EntryOptions[], parent: string | null) => { + const collect = (entries: EntryOptions[]) => { for (const options of entries) { - if (options.id) { - used.add(options.id) - } else { - pending.push({ options, parent }) - } - if (options.group && Array.isArray(options.config)) { - walk(options.config, options.id ?? null) - } + if (options.id) used.add(options.id) + if (options.group && Array.isArray(options.config)) collect(options.config) } } - walk(data, null) + collect(data) + for (const patch of this.config.patches ?? []) { + if (patch.insert) collect(patch.insert) + } const previous = this.anonymous this.anonymous = new Map() - for (const { options, parent } of pending) { - let id: string | undefined - for (const [candidate, info] of previous) { - if (info.parent !== parent || !deepEqual(info.options, options)) continue - id = candidate - previous.delete(candidate) - break + const assign = (entries: EntryOptions[], parent: string | null) => { + for (const options of entries) { + if (!options.id) { + let id: string | undefined + for (const [candidate, info] of previous) { + if (info.parent !== parent || used.has(candidate) || !deepEqual(info.options, options)) continue + id = candidate + previous.delete(candidate) + break + } + if (!id) { + do { + id = Math.random().toString(16).slice(2, 10) + } while (used.has(id) || this.store[id]) + } + used.add(id) + this.anonymous.set(id, { parent, options: structuredClone(options) }) + const rest = { ...options } + for (const key of Object.keys(options)) delete options[key] + Object.assign(options, { id }, rest) + } + if (options.group && Array.isArray(options.config)) assign(options.config, options.id) } - if (!id) { - do { - id = Math.random().toString(16).slice(2, 10) - } while (used.has(id) || this.store[id]) - } - used.add(id) - this.anonymous.set(id, { parent, options: structuredClone(options) }) - const rest = { ...options } - for (const key of Object.keys(options)) delete options[key] - Object.assign(options, { id }, rest) } + assign(data, null) } private _scheduleApply() { if (this._disposed || !this.cache) return - const tree = applyPatches(this.cache.data, this.config.patches, this.warn) - this._pendingTree = applyJournal(tree, this.journal, undefined, this.warn) + const { data, index } = applyPatches(this.cache.data, this.config.patches, this.warn) + this.index = index + this._pendingTree = applyJournal(data, this.journal, undefined, this.warn) this._applyTask ??= (async () => { try { while (this._pendingTree) { diff --git a/vendor/include/src/patch.ts b/vendor/include/src/patch.ts index 45a4700bfe..c132f0a29d 100644 --- a/vendor/include/src/patch.ts +++ b/vendor/include/src/patch.ts @@ -1,5 +1,5 @@ import type { EntryOptions } from '@deepseek-ai/cordis-plugin-loader' -import { type Dict, omit } from '@deepseek-ai/cosmokit' +import type { Dict } from '@deepseek-ai/cosmokit' import { applyChanges, detach, flatten, type Journal, place } from './journal.ts' export interface PatchOptions { @@ -41,79 +41,10 @@ export function ensureInsertIds(patches: PatchOptions[] | undefined, used: (id: } /** - * Overlay `patches` onto a fresh clone of `data`. Inserted entries are cloned - * too, so the tree owns every object it mounts. + * Who supplies an entry, or one key of it, in the patched tree: the file, a + * patch that overrides that key, or the patch the entry is written in. */ -export function applyPatches(data: EntryOptions[], patches: PatchOptions[] | undefined, warn: Warn): EntryOptions[] { - data = structuredClone(data) - if (!patches?.length) return data - - const entryMap = new Map() - const buildMap = (entries: EntryOptions[]) => { - for (const entry of entries) { - if (entry.id) entryMap.set(entry.id, entry) - if (entry.group && Array.isArray(entry.config)) { - buildMap(entry.config) - } - } - } - buildMap(data) - - for (const patch of patches) { - const { id, insert, name, ...overrides } = patch - - if (insert) { - const clone = structuredClone(insert) - if (id) { - const target = entryMap.get(id) - if (!target) { - warn('patch insert: entry %C not found', id) - continue - } - if (!target.group) { - warn('patch insert: entry %C is not a group', id) - continue - } - if (!Array.isArray(target.config)) target.config = [] - target.config.push(...clone) - } else { - data.push(...clone) - } - buildMap(clone) - continue - } - - if (!id) { - warn('patch: id is required for non-insert patches') - continue - } - - const target = entryMap.get(id) - if (!target) { - warn('patch: entry %C not found', id) - continue - } - - if (name && name !== target.name) { - warn('patch: name mismatch for %C (expected %C, got %C), skipping', id, target.name, name) - continue - } - - for (const [key, value] of Object.entries(overrides)) { - if (key === 'id') continue - target[key] = value - } - } - - return data -} - -/** - * Who owns an entry, or one key of it, in the patched tree: the file, a patch - * that overrides that key (the last one wins), or the patch that inserted the - * whole entry. - */ -export type EntryOwner = EntryOwner.File | EntryOwner.Patch | EntryOwner.Insert +export type EntryOwner = EntryOwner.File | EntryOwner.Patch | EntryOwner.Embedded export namespace EntryOwner { export interface File { @@ -126,56 +57,34 @@ export namespace EntryOwner { index: number } - export interface Insert { - type: 'insert' + /** An entry written in `patches[index][key]`. */ + export interface Embedded { + type: 'embedded' /** Index into the patch list. */ index: number - /** The insert list (or nested group config) holding the entry. */ - list: EntryOptions[] - options: EntryOptions - /** The group the entry is inserted into (`null` for the root). */ - parent: string | null + key: 'insert' | 'config' } } -export class PatchIndex { - private keys = new Map>() - private inserts = new Map() +const FILE: EntryOwner.File = { type: 'file' } - constructor(public patches: PatchOptions[]) { - patches.forEach((patch, index) => { - const { id, insert } = patch - if (insert) { - const walk = (list: EntryOptions[], parent: string | null) => { - for (const options of list) { - this.inserts.set(options.id, { type: 'insert', index, list, options, parent }) - if (options.group && Array.isArray(options.config)) walk(options.config, options.id) - } - } - walk(insert, id ?? null) - return - } - if (!id) return - const keys = this.keys.get(id) ?? new Map() - for (const key of Object.keys(omit(patch, ['id', 'insert', 'name']))) { - keys.set(key, index) - } - this.keys.set(id, keys) - }) - } +/** Where every entry and key of a patched tree comes from. */ +export class PatchIndex { + constructor( + private owners: Map, + private keys: Map>, + ) {} /** Owner of the entry as a whole. */ - entry(id: string | null): EntryOwner { - if (id === null) return { type: 'file' } - return this.inserts.get(id) ?? { type: 'file' } + entry(id: string | null) { + if (id === null) return FILE + return this.owners.get(id) ?? FILE } /** Owner of one key of an entry. */ key(id: string, key: string): EntryOwner { - const insert = this.inserts.get(id) - if (insert) return insert const index = this.keys.get(id)?.get(key) - return index === undefined ? { type: 'file' } : { type: 'patch', index } + return index === undefined ? this.entry(id) : { type: 'patch', index } } fileOwned(id: string, key: string | null) { @@ -183,21 +92,131 @@ export class PatchIndex { } } +export interface PatchResult { + data: EntryOptions[] + index: PatchIndex +} + +/** + * Overlay `patches` onto a fresh clone of `data`. Entry lists from patches + * are cloned too, so the tree owns every entry it mounts. The index is built + * in the same pass, so a patch that does not apply owns nothing. + */ +export function applyPatches(data: EntryOptions[], patches: PatchOptions[] | undefined, warn: Warn = () => {}): PatchResult { + data = structuredClone(data) + const entries = new Map() + const owners = new Map() + const keys = new Map>() + + const mount = (list: EntryOptions[], owner: EntryOwner.File | EntryOwner.Embedded) => { + for (const options of list) { + if (options.id) { + entries.set(options.id, options) + owners.set(options.id, owner) + // earlier overrides were aimed at the entry this one replaces + keys.delete(options.id) + } + if (options.group && Array.isArray(options.config)) mount(options.config, owner) + } + } + + const unmount = (list: EntryOptions[]) => { + for (const options of list) { + if (options.id) { + entries.delete(options.id) + owners.delete(options.id) + keys.delete(options.id) + } + if (options.group && Array.isArray(options.config)) unmount(options.config) + } + } + + mount(data, FILE) + + patches?.forEach((patch, index) => { + const { id, insert, name, ...overrides } = patch + const target = id ? entries.get(id) : undefined + + if (insert) { + if (id && !target) return warn('patch insert: entry %C not found', id) + if (target && !target.group) return warn('patch insert: entry %C is not a group', id) + const clone = structuredClone(insert) + if (target) { + if (!Array.isArray(target.config)) target.config = [] + target.config.push(...clone) + } else { + data.push(...clone) + } + mount(clone, { type: 'embedded', index, key: 'insert' }) + return + } + + if (!id) return warn('patch: id is required for non-insert patches') + if (!target) return warn('patch: entry %C not found', id) + if (name && name !== target.name) { + return warn('patch: name mismatch for %C (expected %C, got %C), skipping', id, target.name, name) + } + + // the entries of a group config the patch replaces go away with it + if ('config' in overrides && target.group && Array.isArray(target.config)) { + unmount(target.config) + } + + const overridden = keys.get(id) ?? new Map() + keys.set(id, overridden) + for (const [key, value] of Object.entries(overrides)) { + target[key] = value + overridden.set(key, index) + } + + // entries of a group config the patch supplies can be patched in turn + if ('config' in overrides && target.group && Array.isArray(target.config)) { + // ids go on the patch itself, before the tree takes its own copy + ensureIds(target.config, id => entries.has(id)) + target.config = structuredClone(target.config) + mount(target.config, { type: 'embedded', index, key: 'config' }) + } + }) + + return { data, index: new PatchIndex(owners, keys) } +} + /** * Route a journal to its owners: file-owned changes are applied to `data`, * patch-owned ones to `patches`. Both are mutated in place, so pass clones. * Returns whether any patch changed. */ export function routeJournal(journal: Journal, data: EntryOptions[], patches: PatchOptions[], warn: Warn) { - const index = new PatchIndex(patches) + let { index } = applyPatches(data, patches) let patched = false - const insertList = (owner: EntryOwner.Insert) => owner.options.config ??= [] + // entries that move, appear or go away change the owners of later records + const reindex = () => { + index = applyPatches(data, patches).index + } + + // the list an entry is written in, and the group its top level belongs to + const container = (owner: EntryOwner.File | EntryOwner.Embedded) => { + if (owner.type === 'file') return { list: data, parent: null } + const patch = patches[owner.index] + return { list: patch[owner.key] as EntryOptions[], parent: patch.id ?? null } + } + + // the list holding the entries of a group, when a patch supplies them + const children = (parent: string) => { + const owner = index.key(parent, 'config') + if (owner.type === 'file') return + if (owner.type === 'patch') { + const config = patches[owner.index].config + return Array.isArray(config) ? config : undefined + } + const found = flatten(container(owner).list).get(parent) + return found && (found.options.config ??= []) + } const placeAt = (options: EntryOptions, parent: string | null, position: number) => { - const owner = index.entry(parent) - if (owner.type === 'insert') { - const list = insertList(owner) + const list = parent === null ? undefined : children(parent) + if (list) { list.splice(Math.min(position, list.length), 0, options) patched = true } else if (!place(data, options, parent, position)) { @@ -207,40 +226,33 @@ export function routeJournal(journal: Journal, data: EntryOptions[], patches: Pa for (const [id, record] of journal) { const owner = index.entry(id) + const { list, parent: base } = container(owner) + const embedded = owner.type === 'embedded' + if (record.kind === 'remove') { - if (owner.type === 'insert') { - owner.list.splice(owner.list.indexOf(owner.options), 1) - patched = true - } else { - detach(data, id) - } + detach(list, id) + patched ||= embedded + reindex() continue } - const current = owner.type === 'insert' ? owner : flatten(data).get(id) + const current = flatten(list).get(id) if (!current) { const options = { id } as EntryOptions applyChanges(options, record.changes) placeAt(options, record.parent ?? null, record.position) + reindex() continue } - if (record.parent !== undefined && current.parent !== record.parent) { + // an entry at the top of a patch list belongs to the group the patch targets + if (record.parent !== undefined && (current.parent ?? base) !== record.parent) { // moving across owners: carry the full options over - if (owner.type === 'insert') { - owner.list.splice(owner.list.indexOf(owner.options), 1) - patched = true - } else { - detach(data, id) - } + detach(list, id) + patched ||= embedded applyChanges(current.options, record.changes) placeAt(current.options, record.parent, record.position) - continue - } - - if (owner.type === 'insert') { - applyChanges(current.options, record.changes) - patched = true + reindex() continue } @@ -251,6 +263,7 @@ export function routeJournal(journal: Journal, data: EntryOptions[], patches: Pa ;(patchChanges[keyOwner.index] ??= {})[key] = record.changes[key] return false }) + patched ||= embedded for (const [i, changes] of Object.entries(patchChanges)) { applyChanges(patches[i] as any, changes) patched = true diff --git a/vendor/loader/README.md b/vendor/loader/README.md index 2b71deba01..f745df38bb 100644 --- a/vendor/loader/README.md +++ b/vendor/loader/README.md @@ -48,13 +48,21 @@ root.loader.update(id, { config: { enabled: false } }) For file-backed trees, use `@cordisjs/plugin-include`. +## Entry validation and source positions + +`create()` and `update()` check the resulting options with `validateOptions()` before the tree changes and reject with `EntryValidationError`, whose `issues` list each rejected path. `id` and `name` must be strings, and `name` is required; `group` must be a boolean; `disabled` a boolean or `!!js` expression; a group's `config` an array; `inject` a string array or a mapping; `intercept` and `isolate` mappings, with each `isolate` value `true` or a string. `create()` and `update()` also check the entries of a group's `config`. A group checks each entry again as it creates it; an invalid entry is logged, any running entry with its id is disposed, and its siblings still start. Explicit ids may contain `:`. + +`EntryTree.getLocation(id, path)` returns where an entry option is written; the base tree returns `undefined`, and Include implements it. Config validation errors and entry option errors of an entry with a source list each issue with its `file:line:column`, and their stack frames name the entry ids from the innermost tree outward. A config passed at runtime has no source position, so its validation errors keep their original message. + ## Module resolution Without Node module internals, Loader resolves bare specifiers, package imports and self-references in the nearest package scope containing the configuration file. Relative specifiers use the configuration URL directly, and `cordis:` builtins bypass filesystem resolution. Other specifiers, including `node:` builtins and absolute URLs, initialize an ignored `.cordis/resolve.mjs` helper in that scope to preserve native ESM import conditions. If no scope exists or writing the helper files fails, Loader uses its native import fallback. This fallback emits no diagnostic of its own; project-only dependencies can remain unavailable, and the resulting import error can name the Loader module rather than the configuration project. Failure to import a written helper propagates to the caller without this fallback. -Initialization results are cached for the lifetime of the resolver module, including failed writes and rejected helper imports. Fixing the filesystem does not retry initialization for an already cached scope. Concurrent initialization through filesystem aliases of the same package can contend for the temporary helper files and cause a write failure. +A successful initialization is cached for the lifetime of the resolver module, and so is a rejected helper import. A scope whose helper files cannot be written is not cached, so a later import retries the initialization. A helper file that already holds the expected content is not rewritten, and a rename blocked by a transient `EACCES`, `EPERM` or `EBUSY` lock is retried with a bounded backoff. Concurrent initialization through filesystem aliases of the same package can contend for the temporary helper files and cause a write failure. + +On Windows, an entry `name` that is a drive-letter path such as `C:\app\plugin.js` is imported as its file URL. When the entry's own module cannot be found, the import rejects with `ModuleNotFoundError`, whose `specifier` is the entry `name` and whose message keeps Node's description and hints without the importer; an entry with a source position reports it as `(at name, file:line:column)`. A missing module imported by the plugin propagates Node's original error. Node module internals are classified by their available APIs, including the v1 API used by Node 24.0–24.11. diff --git a/vendor/loader/src/config/entry.ts b/vendor/loader/src/config/entry.ts index b73c116d3f..f8f3ed241c 100644 --- a/vendor/loader/src/config/entry.ts +++ b/vendor/loader/src/config/entry.ts @@ -1,9 +1,9 @@ -import { Context, Fiber, FiberState, Inject } from '@deepseek-ai/cordis' +import { Context, Fiber, FiberState, Inject, ValidationError } from '@deepseek-ai/cordis' import { deepEqual, isNullable, updateVolatile, volatileEntries, type Volatile } from '@deepseek-ai/cosmokit' import { Loader } from '../index.ts' import { EntryGroup } from './group.ts' -import { EntryTree } from './tree.ts' -import { evaluate, isJsExpr } from './utils.ts' +import { EntryTree, ModuleNotFoundError } from './tree.ts' +import { evaluate, formatIssues, formatLocation, isJsExpr, relocate } from './utils.ts' import { equalExceptVolatile } from './diff.ts' /** Serialized plugin entry options stored in loader config files. */ @@ -60,6 +60,23 @@ export class Entry { this.context.emit('loader/entry-init', this) } + /** + * Merge partial options into `target`; a nullish value deletes its key. + * @param target - Options to modify in place. + * @param options - Changes to apply. + * @returns `target`. + */ + static merge(target: Partial, options: Partial) { + for (const [key, value] of Object.entries(options)) { + if (isNullable(value)) { + delete target[key] + } else { + target[key] = value + } + } + return target + } + get context(): Context { return this.ctx } @@ -125,13 +142,7 @@ export class Entry { if (create) { this.options = options as EntryOptions } else { - for (const [key, value] of Object.entries(options)) { - if (isNullable(value)) { - delete this.options[key] - } else { - this.options[key] = value - } - } + Entry.merge(this.options, options) } sortKeys(this.options) @@ -199,14 +210,41 @@ export class Entry { return true } - getOuterStack = () => { - let entry: Entry | undefined = this - const result: string[] = [] - do { - result.push(` at ${entry.parent.tree.ctx.baseUrl}#${entry.options.id}`) - entry = entry.parent.ctx.fiber.entry - } while (entry) - return result + /** + * Where a value of this entry's options is written. + * @param path - Path inside the entry options; empty for the entry itself. + * @returns The source position, or undefined when the tree has no source. + */ + getLocation(path: PropertyKey[] = []) { + return this.parent.tree.getLocation(this.options.id, path) + } + + /** Stack frames from this entry out through its owning entries, each with its source position when known. */ + getOuterStack = () => this.parent.getOuterStack(this.options.id) + + /** + * Rewrite a config validation error to list each issue with its source position, when this entry has a source. + * @param error - Error to rewrite in place. + */ + traceValidation(error: ValidationError) { + const frames = this.getOuterStack() + // an entry outside any source has nothing to point to + if (!frames.length) return + const issues = error.issues.map(({ message, path }) => ({ message, path: ValidationError.normalizePath(path) })) + const locate = (path: PropertyKey[]) => this.getLocation(['config', ...path]) + relocate(error, formatIssues('invalid config', issues, locate), frames) + } + + private _reportImport(error: unknown) { + if (error instanceof ModuleNotFoundError) { + const location = this.getLocation(['name']) + if (location) { + // before Node's hints + const [first, ...hints] = error.message.split('\n') + relocate(error, [`${first} (at name, ${formatLocation(location)})`, ...hints].join('\n'), this.getOuterStack()) + } + } + this.ctx.logger.error(error) } /** Import and start the configured plugin if it is not already running. */ @@ -227,7 +265,7 @@ export class Entry { try { moduleNamespace = await this.parent.tree.import(this.options.name, this.getOuterStack) } catch (error) { - this.ctx.logger.error(error) + this._reportImport(error) return } const plugin = this.loader.unwrapExports(moduleNamespace) diff --git a/vendor/loader/src/config/group.ts b/vendor/loader/src/config/group.ts index 448f3a3588..d8c205ef95 100644 --- a/vendor/loader/src/config/group.ts +++ b/vendor/loader/src/config/group.ts @@ -1,6 +1,8 @@ import { Context, Service } from '@deepseek-ai/cordis' +import { isNullable } from '@deepseek-ai/cosmokit' import { Entry, type EntryOptions } from './entry.ts' import { EntryTree } from './tree.ts' +import { EntryValidationError, formatIssues, formatLocation, relocate, validateOptions, type Issue } from './utils.ts' /** Runtime owner for a list of child loader entries. */ export class EntryGroup { @@ -17,7 +19,13 @@ export class EntryGroup { return this.ctx } + /** + * Create or replace the entry for `options`. Invalid options reject with `EntryValidationError` and dispose any entry already registered under their id. + * @returns The full entry id. + */ async create(options: Omit) { + const issues = validateOptions(options, EntryTree.sep) + if (issues.length) throw this._reject(options as EntryOptions, issues) const id = this.tree.ensureId(options) const entry: Entry = this.tree.store[id] ??= new Entry(this.ctx.loader) // Entry may be moved from another group, @@ -28,6 +36,35 @@ export class EntryGroup { return entry.id } + /** + * Stack frames for an entry of this group, followed by those of the owning entries. + * @param id - Tree-local entry id. + * @returns Frames that point at the entries' source positions. + */ + getOuterStack(id: string): string[] { + const location = this.tree.getLocation(id, []) + const frames = location ? [` at ${id} (${formatLocation(location)})`] : [] + return [...frames, ...this.ctx.fiber.entry?.getOuterStack() ?? []] + } + + private _reject(options: EntryOptions, issues: Issue[]) { + const error = new EntryValidationError(issues) + const id = options?.id + if (isNullable(id)) return error + // unregistered first, so the disposal is not taken for a self-dispose + const entry = this.tree.store[id] + if (entry) { + delete this.tree.store[id] + entry.fiber?.dispose() + this.context.emit('loader/partial-dispose', entry, entry.options, false) + } + const frames = this.getOuterStack(id) + if (!frames.length) return error + const locate = (path: PropertyKey[]) => this.tree.getLocation(id, path) + relocate(error, formatIssues('invalid entry options', issues, locate), frames) + return error + } + unlink(options: EntryOptions) { const config = this.data const index = config.indexOf(options) @@ -49,8 +86,9 @@ export class EntryGroup { async update(config: EntryOptions[]) { const oldConfig = this.data as EntryOptions[] this.data = config - const oldMap = Object.fromEntries(oldConfig.map(options => [options.id, options])) - const newMap = Object.fromEntries(config.map(options => [options.id ?? Symbol('anonymous'), options])) + const oldMap = Object.fromEntries(oldConfig.map(options => [options?.id, options])) + // non-objects are rejected by `create` + const newMap = Object.fromEntries(config.map(options => [options?.id ?? Symbol('anonymous'), options])) // update inner plugins const ids = Reflect.ownKeys({ ...oldMap, ...newMap }) as string[] diff --git a/vendor/loader/src/config/tree.ts b/vendor/loader/src/config/tree.ts index 5b5648f576..b0db124059 100644 --- a/vendor/loader/src/config/tree.ts +++ b/vendor/loader/src/config/tree.ts @@ -1,9 +1,46 @@ import { composeError, Context } from '@deepseek-ai/cordis' import { isNonNullable, type Dict } from '@deepseek-ai/cosmokit' +import url from 'node:url' import { Entry, type EntryOptions } from './entry.ts' import { EntryGroup } from './group.ts' +import { EntryValidationError, validateOptions, type SourceLocation } from './utils.ts' import { createResolve } from '../resolve.ts' +// A Windows drive-letter path, e.g. `C:\app\plugin.js` or `C:/app/plugin.js`. +const driveLetter = /^[A-Za-z]:[\\/]/ + +// Node names the modules only in the message: +// `Cannot find (module|package) '' imported from ` +function parseNotFound(error: any) { + if (error?.code !== 'ERR_MODULE_NOT_FOUND' || typeof error.message !== 'string') return + // later lines are hints, e.g. `Did you mean to import ...?` + const [first, ...hints] = error.message.split('\n') as string[] + const match = first.match(/^(Cannot find (?:module|package) '.*') imported from (.*)$/) + if (match) return { description: match[1], parent: match[2], hints } +} + +function toPath(href: string) { + try { + return href.startsWith('file:') ? url.fileURLToPath(href) : href + } catch { + return href + } +} + +/** A configured plugin module that cannot be found, as opposed to a missing module imported by that plugin. */ +export class ModuleNotFoundError extends Error { + name = 'ModuleNotFoundError' + code = 'ERR_MODULE_NOT_FOUND' + + /** + * @param specifier - Entry `name` that failed to resolve. + * @param message - Node's description and hints, without its importer. + */ + constructor(public specifier: string, message: string) { + super(message) + } +} + /** * One tree-side mutation, reported to `EntryTree.commit()` synchronously after * it has been applied to `entry.options` / `group.data`. @@ -125,6 +162,8 @@ export abstract class EntryTree { /** Create an entry in the root group or a nested group. */ async create(options: Omit, parent: string | null = null, position = Infinity) { const group = this.resolveGroup(parent) + const issues = validateOptions(options, EntryTree.sep, true) + if (issues.length) throw new EntryValidationError(issues) const id = group.tree.ensureId(options) group.data.splice(position, 0, options as EntryOptions) group.tree.commit({ id, group, options: options as EntryOptions }) @@ -145,6 +184,8 @@ export abstract class EntryTree { const entry = this.resolve(id) const source = entry.parent const legacy = { ...entry.options } + const issues = validateOptions(Entry.merge({ ...legacy }, options), EntryTree.sep, true) + if (issues.length) throw new EntryValidationError(issues) if (parent !== undefined) { const target = this.resolveGroup(parent) const moved = target.tree === source.tree ? [] : members(entry) @@ -178,28 +219,70 @@ export abstract class EntryTree { return task } - /** Import a plugin module from a specifier or `cordis:` builtin. */ + /** + * Import a plugin module from a specifier or `cordis:` builtin. On Windows a drive-letter path is imported as a file URL. + * Rejects with `ModuleNotFoundError` when the specifier itself cannot be found; other import errors propagate unchanged. + */ import(name: string, getOuterStack?: () => string[]) { if (name.startsWith('cordis:')) { return this.ctx.loader.builtins[name.slice(7)] } + // On Windows, a drive-letter path is converted with `pathToFileURL`. + if (process.platform === 'win32' && driveLetter.test(name)) { + name = url.pathToFileURL(name).href + } + // to tell `name` apart from a module it imports + let parent: string | undefined + // the helper resolves `name` only + let unresolved: unknown return composeError(async (info) => { // ModuleJob.run // onImport.tracePromise.__proto__ // internal.import info.offset += 3 if (this.ctx.loader.internal) { - return await this.ctx.loader.internal.import(name, this.ctx.baseUrl!, {}) + parent = this.ctx.baseUrl! + return await this.ctx.loader.internal.import(name, parent, {}) } else if (name.startsWith('.')) { + parent = import.meta.url return await import(/* @vite-ignore */new URL(name, this.ctx.baseUrl).href) } else { const resolve = await createResolve(this.ctx.baseUrl) - const url = resolve ? resolve(name) : name + let url = name + if (resolve) { + try { + url = resolve(name) + } catch (error) { + unresolved = error + throw error + } + } + parent = import.meta.url return await import(/* @vite-ignore */ url) } - }, getOuterStack) + }, getOuterStack).catch((error: unknown) => { + const notFound = parseNotFound(error) + if (!notFound) throw error + if (error !== unresolved && (!parent || notFound.parent !== toPath(parent))) throw error + const result = new ModuleNotFoundError(name, [notFound.description, ...notFound.hints].join('\n')) + const frames = getOuterStack?.() ?? [] + // Node's frames are those of its resolver + if (frames.length) result.stack = [`${result.name}: ${result.message}`, ...frames].join('\n') + throw result + }) } /** Report an applied mutation synchronously. In-memory trees may use a no-op. */ abstract commit(change: EntryChange): void + + /** + * Where a value of the entry options is written. A path that leaves the + * source falls back to its deepest written ancestor. + * @param _id - Tree-local entry id. + * @param _path - Path inside the entry options. + * @returns The source position, or undefined for trees without a source file. + */ + getLocation(_id: string, _path: PropertyKey[]): SourceLocation | undefined { + return undefined + } } diff --git a/vendor/loader/src/config/utils.ts b/vendor/loader/src/config/utils.ts index 8e28be0c4c..bcc3e912a8 100644 --- a/vendor/loader/src/config/utils.ts +++ b/vendor/loader/src/config/utils.ts @@ -23,10 +23,140 @@ export function interpolate(ctx: object, value: any) { /** Return true when a value is a serialized loader JavaScript expression. */ export function isJsExpr(value: any): value is JsExpr { - return value instanceof Object && '__jsExpr' in value + return value instanceof Object && typeof value.__jsExpr === 'string' } /** Serialized JavaScript expression produced by the include YAML tag. */ export interface JsExpr { __jsExpr: string } + +/** Source position of a config value: 1-based, with columns in UTF-16 code units. */ +export interface SourceLocation { + /** Path of the config file that writes the value. */ + filename: string + line: number + column: number +} + +/** + * Format a source position as `file:line:column`. + * @param location - Position to format. + * @returns The formatted position. + */ +export function formatLocation(location: SourceLocation) { + return `${location.filename}:${location.line}:${location.column}` +} + +/** + * Format one validation issue as an indented list item. + * @param message - Issue description. + * @param location - Source position of the value, when known. + * @param path - Dotted option path of the value, when not the root. + * @returns The list item, with its path and position in parentheses. + */ +export function formatIssue(message: string, location?: SourceLocation, path?: string) { + const where = [path, location && formatLocation(location)].filter(Boolean).join(', ') + return where ? ` - ${message} (at ${where})` : ` - ${message}` +} + +/** One rejected entry option. */ +export interface Issue { + message: string + /** Path from the entry options to the rejected value; empty for the entry itself. */ + path: PropertyKey[] +} + +/** Map an option path to the source position that writes it. */ +export type Locate = (path: PropertyKey[]) => SourceLocation | undefined + +/** + * Format a titled list of validation issues. + * @param title - First line of the message. + * @param issues - Issues to list in order. + * @param locate - Resolves each issue path to a source position. + * @returns The multi-line message. + */ +export function formatIssues(title: string, issues: readonly Issue[], locate?: Locate) { + const lines = issues.map(({ message, path }) => { + return formatIssue(message, locate?.(path), path.length ? path.map(String).join('.') : undefined) + }) + return `${title}:\n${lines.join('\n')}` +} + +/** + * Replace an error's message and stack frames, so the error points at the config source instead of the loader internals. + * @param error - Error to rewrite in place. + * @param message - New message. + * @param frames - Stack frames listed after the message line. + */ +export function relocate(error: Error, message: string, frames: string[]) { + error.message = message + error.stack = [`${error.name}: ${message}`, ...frames].join('\n') +} + +/** Entry options rejected by `validateOptions()`; `issues` lists every rejected option. */ +export class EntryValidationError extends TypeError { + name = 'EntryValidationError' + + constructor(public issues: Issue[]) { + super(formatIssues('invalid entry options', issues)) + } +} + +// only `disabled` takes an expression +function isPlainObject(value: unknown): value is Record { + return !!value && typeof value === 'object' && !Array.isArray(value) && !isJsExpr(value) +} + +/** + * Check entry options before an entry is created or updated. Explicit ids may contain `sep`. + * @param options - Candidate entry options. + * @param sep - Tree id separator; kept for the upstream signature. + * @param deep - Also check the entries of a group's `config`. + * @returns Every issue found; empty when the options are valid. + */ +export function validateOptions(options: unknown, sep: string, deep = false): Issue[] { + if (!isPlainObject(options)) return [{ message: 'entry must be an object', path: [] }] + const issues: Issue[] = [] + const check = (key: string, expected: string, valid: (value: any) => boolean, required = false) => { + const value = options[key] + if (value === undefined || value === null) { + if (required) issues.push({ message: `${key} is required`, path: [key] }) + } else if (!valid(value)) { + issues.push({ message: `${key} must be ${expected}`, path: [key] }) + } + } + + check('id', 'a string', value => typeof value === 'string') + check('name', 'a string', value => typeof value === 'string', true) + check('group', 'a boolean', value => typeof value === 'boolean') + check('disabled', 'a boolean', value => typeof value === 'boolean' || isJsExpr(value)) + // a group's config is its entry list + if (options.group === true) check('config', 'an array', Array.isArray, true) + + check('inject', 'an array or an object', value => Array.isArray(value) || isPlainObject(value)) + if (Array.isArray(options.inject)) { + options.inject.forEach((name, index) => { + if (typeof name === 'string') return + issues.push({ message: `inject.${index} must be a string`, path: ['inject', index] }) + }) + } + check('intercept', 'an object', isPlainObject) + check('isolate', 'an object', isPlainObject) + if (isPlainObject(options.isolate)) { + for (const [name, label] of Object.entries(options.isolate)) { + if (label === true || typeof label === 'string') continue + issues.push({ message: `isolate.${name} must be true or a string`, path: ['isolate', name] }) + } + } + // from a source, each entry is checked as its group creates it + if (deep && options.group === true && Array.isArray(options.config)) { + options.config.forEach((child, index) => { + for (const { message, path } of validateOptions(child, sep, true)) { + issues.push({ message, path: ['config', index, ...path] }) + } + }) + } + return issues +} diff --git a/vendor/loader/src/index.ts b/vendor/loader/src/index.ts index 2a9e1bb9a3..3582bc1360 100644 --- a/vendor/loader/src/index.ts +++ b/vendor/loader/src/index.ts @@ -1,4 +1,4 @@ -import { Context, FiberState, Inject, Service } from '@deepseek-ai/cordis' +import { Context, FiberState, Inject, Service, ValidationError, type Fiber } from '@deepseek-ai/cordis' import { defineProperty, isNullable, type Awaitable, type Dict } from '@deepseek-ai/cosmokit' import { ModuleLoader } from './internal.ts' import { Entry, type EntryOptions } from './config/entry.ts' @@ -101,9 +101,30 @@ export class Loader extends EntryTree { ctx.reflect.provide('loader', this, this[Service.check]) + // the source config each entry fiber last resolved + const sources = new WeakMap() + + // Registered before the built-in validation listener, so validation + // failures can be traced to the config source. A config passed in at + // runtime is not written anywhere yet, so its failures are left as is. + ctx.on('internal/config', (fiber, next) => { + if (!fiber.entry || fiber.parent.fiber?.entry === fiber.entry) return next() + try { + return next() + } catch (error) { + if (ValidationError.is(error) && sources.get(fiber) === fiber.entry.options.config) { + fiber.entry.traceValidation(error) + } + throw error + } + }, { prepend: true }) + + // Registered after the built-in validation listener, so interpolation runs + // on the source config and validation sees the interpolated result. ctx.on('internal/config', (fiber, next) => { const config = next() if (!fiber.entry || fiber.parent.fiber?.entry === fiber.entry) return config + sources.set(fiber, config) // Tree carriers preserve the expressions owned by their child entries. if (fiber.runtime?.callback[EntryGroup.key]) return config return interpolate(fiber.ctx, config) diff --git a/vendor/loader/src/resolve.ts b/vendor/loader/src/resolve.ts index 6d5aadcf8b..9aa014d9f2 100644 --- a/vendor/loader/src/resolve.ts +++ b/vendor/loader/src/resolve.ts @@ -1,6 +1,7 @@ import fs from 'node:fs' import fsPromises from 'node:fs/promises' import path from 'node:path' +import timers from 'node:timers/promises' import url from 'node:url' import type { Dict } from '@deepseek-ai/cosmokit' @@ -19,6 +20,18 @@ const HELPER_FILES = { const cache: Dict> = Object.create(null) +const RENAME_RETRIES = 10 +const RENAME_BACKOFF = 20 + +/** + * On Windows a rename over a file that another process holds open fails with + * one of these; the lock is normally gone within milliseconds. + */ +function isTransientRenameError(error: unknown) { + const code = (error as NodeJS.ErrnoException | undefined)?.code + return code === 'EACCES' || code === 'EPERM' || code === 'EBUSY' +} + /** Nearest ancestor of `dir` that owns a `package.json`, if any. */ function findScope(dir: string) { while (true) { @@ -41,11 +54,25 @@ function resolveScope(baseUrl: string | undefined) { } async function write(filename: string, content: string) { + // The helper content is constant; skipping an identical rewrite avoids + // repeating the rename that another process may have blocked. + if (await fsPromises.readFile(filename, 'utf8').catch(() => undefined) === content) return // Another process may be writing the same path; `rename` is atomic, so a // concurrent reader only ever observes the complete helper. const temp = `${filename}.${process.pid}` await fsPromises.writeFile(temp, content) - await fsPromises.rename(temp, filename) + for (let attempt = 0; ; attempt++) { + try { + await fsPromises.rename(temp, filename) + return + } catch (error) { + if (attempt >= RENAME_RETRIES || !isTransientRenameError(error)) { + await fsPromises.rm(temp, { force: true }).catch(() => {}) + throw error + } + } + await timers.setTimeout(RENAME_BACKOFF * (attempt + 1)) + } } async function _createResolve(scope: string): Promise { @@ -71,5 +98,8 @@ async function _createResolve(scope: string): Promise { export async function createResolve(baseUrl: string | undefined) { const scope = resolveScope(baseUrl) if (!scope) return - return await (cache[scope] ??= _createResolve(scope)) + const resolve = await (cache[scope] ??= _createResolve(scope)) + // A scope that cannot be prepared may succeed on a later attempt. + if (!resolve) delete cache[scope] + return resolve }