@arcadia-eternity/content-sdk 4.5.3 → 4.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +2 -2
  2. package/dist/author-api.d.ts +12 -2
  3. package/dist/author-api.js +11 -2
  4. package/dist/author-git.d.ts +63 -0
  5. package/dist/author-git.js +324 -0
  6. package/dist/author-reference.d.ts +15 -1
  7. package/dist/author-reference.js +20 -1
  8. package/dist/cli.js +5 -4
  9. package/dist/content-query.d.ts +15 -1
  10. package/dist/content-query.js +53 -11
  11. package/dist/content-workspace.d.ts +435 -6
  12. package/dist/content-workspace.js +238 -77
  13. package/dist/debug-environments.d.ts +393 -33
  14. package/dist/debug-environments.js +10 -50
  15. package/dist/demo.js +1 -1
  16. package/dist/effect-declarations.d.ts +14 -0
  17. package/dist/effect-declarations.js +103 -0
  18. package/dist/environment-host-base.d.ts +175 -0
  19. package/dist/environment-host-base.js +86 -0
  20. package/dist/environment-member-transfer.d.ts +5 -0
  21. package/dist/environment-member-transfer.js +95 -0
  22. package/dist/environment-rules.d.ts +728 -3
  23. package/dist/environment-rules.js +158 -74
  24. package/dist/environment-sharing.d.ts +51 -0
  25. package/dist/environment-sharing.js +321 -0
  26. package/dist/environment.d.ts +2 -0
  27. package/dist/environment.js +32 -9
  28. package/dist/jobs.d.ts +5 -0
  29. package/dist/jobs.js +59 -10
  30. package/dist/learnsets.d.ts +47 -0
  31. package/dist/learnsets.js +124 -0
  32. package/dist/lib/content.d.ts +1 -1
  33. package/dist/lib/content.js +26 -2
  34. package/dist/lib/presentation.js +5 -11
  35. package/dist/managed-projects.d.ts +6 -0
  36. package/dist/managed-projects.js +137 -45
  37. package/dist/managed-sources.d.ts +17 -0
  38. package/dist/managed-sources.js +28 -10
  39. package/dist/mcp-contracts.d.ts +405 -12
  40. package/dist/mcp-contracts.js +3 -1
  41. package/dist/mcp.js +23 -1
  42. package/dist/pack-project.d.ts +2 -1
  43. package/dist/pack-project.js +40 -5
  44. package/dist/prepared-document.d.ts +476 -0
  45. package/dist/prepared-document.js +47 -0
  46. package/dist/preview.js +5 -5
  47. package/dist/project.d.ts +3 -1
  48. package/dist/project.js +47 -4
  49. package/dist/rule-composition.d.ts +290 -0
  50. package/dist/rule-composition.js +267 -0
  51. package/dist/template/.github/scripts/release-payload.mjs +91 -0
  52. package/dist/template/.github/scripts/release-test-npm.mjs +27 -0
  53. package/dist/template/.github/scripts/verify-release.mjs +138 -0
  54. package/dist/template/.github/workflows/release-pack.yml +77 -0
  55. package/dist/template/README.md +15 -2
  56. package/dist/template/gitignore-template +7 -0
  57. package/dist/template/npm-lock-template.json +2319 -0
  58. package/dist/template/package.json +4 -2
  59. package/dist/template/skills/arcadia-content-authoring/references/tool-workflows.md +1 -1
  60. package/dist/template/skills/arcadia-content-git/SKILL.md +14 -0
  61. package/dist/template/skills/arcadia-content-release/SKILL.md +29 -0
  62. package/dist/template/test/pack.test.mjs +24 -5
  63. package/dist/testing.d.ts +1 -0
  64. package/dist/testing.js +26 -7
  65. package/dist/workspace-cli.js +2 -2
  66. package/dist/workspace-materials.d.ts +4 -1
  67. package/dist/workspace-materials.js +8 -2
  68. package/dist/workspace.d.ts +11 -0
  69. package/dist/workspace.js +191 -31
  70. package/package.json +16 -4
  71. package/release-payload.mjs +91 -0
  72. package/release-test-npm.mjs +27 -0
@@ -1,29 +1,58 @@
1
- import { createHash, randomUUID } from 'node:crypto';
1
+ import { sha256Hex, skillParameterCatalogSchema, readElementCatalog, } from '@arcadia-eternity/const';
2
+ import { randomUUID } from 'node:crypto';
2
3
  import { lstat, mkdir, readFile, readdir, realpath, rename, rm, writeFile } from 'node:fs/promises';
3
4
  import { join, resolve } from 'node:path';
4
5
  import writeFileAtomic from 'write-file-atomic';
5
6
  import semver from 'semver';
6
7
  import { inspectNpmProject } from '@arcadia-eternity/pack-loader/node';
7
- import { normalizeEnvironmentDocument } from './debug-environments.js';
8
+ import { normalizeEnvironmentDocument, EnvironmentDocumentV2Schema, EnvironmentRulesSchema, EnvironmentRuleDeclarationSchema, } from './debug-environments.js';
9
+ import { z } from 'zod';
8
10
  import { withSourceLock } from './source-lock.js';
9
- import { contentError, materialFiles, writeMaterials } from './workspace-materials.js';
11
+ import { contentError, readJson, materialFiles, writeMaterials } from './workspace-materials.js';
10
12
  import { errorCode, isRecord } from './types.js';
13
+ import { compactMaterials, expandSharedMaterials, exportDependencies, } from './environment-sharing.js';
14
+ import { environmentShareMaterials } from './environment-host-base.js';
15
+ export { copyEnvironmentMember } from './environment-member-transfer.js';
16
+ import { parseManifestDraft, preparedDocument } from './prepared-document.js';
17
+ export { readInstalledEnvironmentDocument } from './prepared-document.js';
11
18
  export { normalizeEnvironmentDocument } from './debug-environments.js';
19
+ const compositionSchema = z
20
+ .object({
21
+ rules: EnvironmentRulesSchema,
22
+ requiredCapabilities: z.array(z.string()).optional(),
23
+ fields: z.array(z.object({
24
+ path: z.array(z.string()),
25
+ value: z.unknown(),
26
+ sources: z.array(z.string()),
27
+ effectiveSources: z.array(z.string()),
28
+ })),
29
+ ruleSets: z.array(z.object({ id: z.string(), name: z.string(), rules: EnvironmentRuleDeclarationSchema })),
30
+ })
31
+ .strict();
32
+ const contentChoices = z.array(z.object({ id: z.string(), name: z.string().optional() }));
33
+ const contentCatalogSchema = z.object({
34
+ species: contentChoices,
35
+ skills: contentChoices,
36
+ marks: contentChoices,
37
+ stages: contentChoices,
38
+ });
39
+ export const exportSelectionSchema = z
40
+ .object({
41
+ revision: z.string().min(1),
42
+ locations: z.array(z.string().min(1)).max(50000),
43
+ })
44
+ .strict();
45
+ function exportRevision(draft, content, dependencies) {
46
+ return sha256Hex(JSON.stringify([draft, content, dependencies]));
47
+ }
12
48
  const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
13
49
  const envId = /^[a-z0-9][a-z0-9_-]{0,79}$/;
14
- const revision = (text) => createHash('sha256').update(text).digest('hex');
15
50
  const json = (value) => JSON.stringify(value, null, 2) + '\n';
16
51
  const checkId = (id, pattern = uuid) => {
17
52
  if (typeof id !== 'string' || !pattern.test(id))
18
53
  throw contentError('RESOURCE_ID_INVALID');
19
54
  return id;
20
55
  };
21
- async function readJson(file, limit = 4 * 1024 * 1024) {
22
- const info = await lstat(file);
23
- if (!info.isFile() || info.isSymbolicLink() || info.size > limit)
24
- throw contentError('WORKSPACE_FILE_INVALID');
25
- return JSON.parse(await readFile(file, 'utf8'));
26
- }
27
56
  async function regularDirectory(path) {
28
57
  await mkdir(path, { recursive: true, mode: 0o700 });
29
58
  const info = await lstat(path);
@@ -55,6 +84,14 @@ async function checkedPreparation(result, document, directory) {
55
84
  return {
56
85
  contentRevision: result.contentRevision,
57
86
  packages,
87
+ ...(result.contentCatalog !== undefined && { contentCatalog: contentCatalogSchema.parse(result.contentCatalog) }),
88
+ ...(result.ruleComposition !== undefined && { ruleComposition: compositionSchema.parse(result.ruleComposition) }),
89
+ ...(result.skillParameters !== undefined && {
90
+ skillParameters: skillParameterCatalogSchema.parse(result.skillParameters),
91
+ }),
92
+ ...(isRecord(result.elementCatalog) && {
93
+ elementCatalog: readElementCatalog(result.elementCatalog),
94
+ }),
58
95
  members: (inspection.members ?? []),
59
96
  };
60
97
  }
@@ -73,8 +110,7 @@ function activeProcess(pid) {
73
110
  throw error;
74
111
  }
75
112
  }
76
- /** One owner edits persistent npm projects. Prepared metadata is a disposable receipt,
77
- * never a selectable historical version. Runtime loaders capture their own inputs. */
113
+ /** One write owner publishes prepared documents alongside the locked npm materials. */
78
114
  class ContentWorkspaceImplementation {
79
115
  root;
80
116
  bootId = randomUUID();
@@ -168,6 +204,18 @@ class ContentWorkspaceImplementation {
168
204
  #directory(id) {
169
205
  return join(this.root, 'environments', checkId(id, envId));
170
206
  }
207
+ async #archiveRemovedDeclarations(id) {
208
+ const text = await readFile(join(this.#directory(id), 'package.json'), 'utf8').catch(error => {
209
+ if (errorCode(error) !== 'ENOENT')
210
+ throw error;
211
+ return undefined;
212
+ });
213
+ if (!text || !Object.hasOwn(JSON.parse(text).arcadiaEnvironment ?? {}, 'disabled'))
214
+ return;
215
+ const archive = join(this.root, 'migration-backups');
216
+ await regularDirectory(archive);
217
+ await writeFileAtomic(join(archive, `${id}-${sha256Hex(text)}.json`), text);
218
+ }
171
219
  #manifest(document, previous = {}) {
172
220
  const { packages, ...metadata } = document;
173
221
  const priorDependencies = isRecord(previous.dependencies) ? previous.dependencies : {};
@@ -189,19 +237,10 @@ class ContentWorkspaceImplementation {
189
237
  throw contentError('WORKSPACE_PATH_INVALID');
190
238
  await readJson(join(directory, 'package.json'));
191
239
  const text = await readFile(join(this.#directory(id), 'package.json'), 'utf8');
192
- const manifest = JSON.parse(text);
193
- if (!isRecord(manifest.arcadiaEnvironment) || !isRecord(manifest.dependencies))
194
- throw contentError('ENVIRONMENT_MANIFEST_INVALID');
195
- const sources = manifest.arcadiaEnvironment.sources;
196
- if (!Array.isArray(sources))
197
- throw contentError('ENVIRONMENT_MANIFEST_INVALID');
198
- const document = normalizeEnvironmentDocument({
199
- ...manifest.arcadiaEnvironment,
200
- packages: Object.fromEntries(Object.entries(manifest.dependencies).filter(([name]) => !sources.includes(name))),
201
- });
202
- if (document.id !== id)
240
+ const draft = parseManifestDraft(text);
241
+ if (draft.document.id !== id)
203
242
  throw contentError('ENVIRONMENT_ID_MISMATCH');
204
- return { document, revision: revision(text) };
243
+ return draft;
205
244
  }
206
245
  listDrafts() {
207
246
  return this.#exclusive(() => this.#listDrafts());
@@ -228,9 +267,20 @@ class ContentWorkspaceImplementation {
228
267
  throw error;
229
268
  return null;
230
269
  });
231
- if ((previous === null ? null : revision(previous)) !== input.expectedRevision)
270
+ if ((previous === null ? null : sha256Hex(previous)) !== input.expectedRevision)
232
271
  throw contentError('REVISION_CONFLICT');
233
272
  await regularDirectory(directory);
273
+ await this.#archiveRemovedDeclarations(document.id);
274
+ if (previous !== null) {
275
+ const receiptFile = join(directory, '.arcadia-prepared.json');
276
+ const receipt = await readJson(receiptFile).catch(error => {
277
+ if (errorCode(error) !== 'ENOENT')
278
+ throw error;
279
+ return undefined;
280
+ });
281
+ if (receipt && !receipt.document && receipt.draftRevision === sha256Hex(previous))
282
+ await writeFileAtomic(receiptFile, json({ ...receipt, document: parseManifestDraft(previous).document }));
283
+ }
234
284
  await writeFileAtomic(file, json(this.#manifest(document, previous ? JSON.parse(previous) : {})));
235
285
  return this.#draft(document.id);
236
286
  }, true);
@@ -248,21 +298,34 @@ class ContentWorkspaceImplementation {
248
298
  }
249
299
  async #installation(id) {
250
300
  const directory = this.#directory(id);
251
- await readJson(join(directory, 'package-lock.json'), 16 * 1024 * 1024);
301
+ const lock = await readJson(join(directory, 'package-lock.json'), 16 * 1024 * 1024);
252
302
  await lstat(join(directory, 'node_modules'));
253
- const draft = await this.#draft(id);
254
303
  const metadata = await readJson(join(directory, '.arcadia-prepared.json'));
255
304
  if (metadata.format !== 'arcadia.environment-installation/1' ||
256
305
  metadata.installationId !== id ||
257
306
  typeof metadata.contentRevision !== 'string')
258
307
  throw contentError('ENVIRONMENT_INSTALLATION_INVALID');
259
- // The manifest is authoritative. Metadata describes preparation, not a frozen document.
308
+ const document = preparedDocument(metadata, metadata.document === undefined ? await readFile(join(directory, 'package.json'), 'utf8') : '');
309
+ const locked = isRecord(lock.packages) ? lock.packages : {};
310
+ const members = Array.isArray(metadata.members)
311
+ ? metadata.members.map(member => {
312
+ const entry = locked['node_modules/' + member.name];
313
+ return isRecord(entry) &&
314
+ typeof entry.resolved === 'string' &&
315
+ /^file:candidates\/[a-zA-Z0-9_.-]+\.tgz$/.test(entry.resolved) &&
316
+ typeof entry.integrity === 'string' &&
317
+ member.name !== '@arcadia-eternity/data-pack-base'
318
+ ? { ...member, archiveIntegrity: entry.integrity }
319
+ : member;
320
+ })
321
+ : undefined;
260
322
  return {
261
323
  ...metadata,
324
+ members,
262
325
  installationId: id,
263
326
  environmentId: id,
264
327
  workspaceId: this.workspaceId,
265
- document: draft.document,
328
+ document,
266
329
  directory,
267
330
  materialDirectory: `environments/${id}`,
268
331
  status: 'ready',
@@ -309,6 +372,7 @@ class ContentWorkspaceImplementation {
309
372
  throw contentError('ENVIRONMENT_ID_MISMATCH');
310
373
  const source = input.projectDirectory ??
311
374
  input.directory ??
375
+ input.seedDirectory ??
312
376
  (await this.#options.resolveProject?.(input.environmentId)) ??
313
377
  this.#directory(input.environmentId);
314
378
  return this.#install(document, source, preparer, input);
@@ -325,10 +389,14 @@ class ContentWorkspaceImplementation {
325
389
  let journaled = false;
326
390
  try {
327
391
  await input.onProgress?.({ stage: 'preparing' });
328
- await writeMaterials(staging, await materialFiles(source, { ...this.#options, signal }), {
329
- ...this.#options,
330
- signal,
331
- });
392
+ const limits = { ...this.#options, signal };
393
+ let materials = await materialFiles(source, limits);
394
+ if (input.importing) {
395
+ const restored = await environmentShareMaterials(materials, document, limits);
396
+ materials = restored.files;
397
+ document = restored.document;
398
+ }
399
+ await writeMaterials(staging, materials, limits);
332
400
  const manifest = await readJson(join(staging, 'package.json'));
333
401
  const base = '@arcadia-eternity/data-pack-base';
334
402
  if (Object.hasOwn(document.packages, base) || document.sources.includes(base)) {
@@ -347,10 +415,15 @@ class ContentWorkspaceImplementation {
347
415
  await writeFile(join(staging, '.arcadia-prepared.json'), json({
348
416
  format: 'arcadia.environment-installation/1',
349
417
  installationId: document.id,
350
- draftRevision: revision(text),
418
+ document,
419
+ draftRevision: sha256Hex(text),
351
420
  contentRevision: result.contentRevision,
352
421
  packages: result.packages,
353
422
  members: result.members,
423
+ ruleComposition: result.ruleComposition,
424
+ skillParameters: result.skillParameters,
425
+ contentCatalog: result.contentCatalog,
426
+ elementCatalog: result.elementCatalog,
354
427
  createdAt: Date.now(),
355
428
  ...(input.importId ? { importId: input.importId } : {}),
356
429
  }));
@@ -368,6 +441,7 @@ class ContentWorkspaceImplementation {
368
441
  }
369
442
  await input.beforeCommit?.();
370
443
  signal.throwIfAborted();
444
+ await this.#archiveRemovedDeclarations(document.id);
371
445
  if (input.importId)
372
446
  return this.#finishImport(input.importId);
373
447
  try {
@@ -438,9 +512,6 @@ class ContentWorkspaceImplementation {
438
512
  ...((await this.#options.retentions?.list(id)) ?? []).map(x => ({ kind: 'retention', ...x })),
439
513
  ];
440
514
  }
441
- references(id) {
442
- return this.#exclusive(() => this.#references(id));
443
- }
444
515
  clearInstallation(id) {
445
516
  return this.#exclusive(async () => {
446
517
  const references = await this.#references(id);
@@ -451,21 +522,78 @@ class ContentWorkspaceImplementation {
451
522
  await rm(join(directory, '.arcadia-prepared.json'), { force: true });
452
523
  }, true);
453
524
  }
454
- async #export(id) {
525
+ async #exportVersion(id) {
455
526
  const draft = await this.#draft(id);
456
527
  const installation = await this.#installation(id);
457
528
  if (installation.draftRevision !== draft.revision)
458
529
  throw contentError('ENVIRONMENT_PREPARATION_REQUIRED', '环境已修改,请先准备环境再导出');
459
- const files = await materialFiles(this.#directory(id), this.#options);
530
+ return { draft, installation };
531
+ }
532
+ async #shareFiles(id, document) {
533
+ return environmentShareMaterials(await materialFiles(this.#directory(id), this.#options), document);
534
+ }
535
+ previewEnvironmentExport(id) {
536
+ return this.#exclusive(async () => {
537
+ const { draft, installation } = await this.#exportVersion(id);
538
+ const lock = await readJson(join(this.#directory(id), 'package-lock.json'), 16 * 1024 * 1024);
539
+ const hasOnline = Object.values(lock.packages ?? {}).some(entry => isRecord(entry) && typeof entry.resolved === 'string' && entry.resolved.startsWith('https:'));
540
+ const dependencies = hasOnline ? exportDependencies((await this.#shareFiles(id, draft.document)).files) : [];
541
+ return { revision: exportRevision(draft.revision, installation.contentRevision, dependencies), dependencies };
542
+ });
543
+ }
544
+ missingEnvironmentArchives(probe) {
545
+ return this.#exclusive(async () => {
546
+ if (probe?.lock?.path !== 'package-lock.json' ||
547
+ !Array.isArray(probe.archives) ||
548
+ probe.archives.length > (this.#options.maxFiles ?? 50000) ||
549
+ probe.archives.some(ref => !ref?.external))
550
+ throw contentError('ENVIRONMENT_EXPORT_INVALID');
551
+ const missing = new Set();
552
+ await expandSharedMaterials([probe.lock], probe.archives, {
553
+ ...this.#options,
554
+ offline: true,
555
+ missing,
556
+ signal: this.#controller.signal,
557
+ environments: join(this.root, 'environments'),
558
+ cache: this.#options.npmCache ?? join(this.root, 'npm-cache'),
559
+ });
560
+ return [...missing];
561
+ });
562
+ }
563
+ async #export(id, mode) {
564
+ const { draft, installation } = await this.#exportVersion(id);
565
+ const { contentRevision } = installation;
566
+ const shared = await this.#shareFiles(id, draft.document);
567
+ let files = shared.files;
568
+ let archives = [];
569
+ if (mode !== 'offline') {
570
+ let locations = [];
571
+ if (mode !== 'share') {
572
+ const selection = exportSelectionSchema.safeParse(mode);
573
+ if (!selection.success)
574
+ throw contentError('ENVIRONMENT_EXPORT_INVALID');
575
+ if (exportRevision(draft.revision, contentRevision, exportDependencies(files)) !== selection.data.revision)
576
+ throw contentError('REVISION_CONFLICT', '环境已修改,请重新导出');
577
+ locations = selection.data.locations;
578
+ }
579
+ const compact = await compactMaterials(files, this.#options, locations);
580
+ files = compact.materials;
581
+ archives = compact.archives;
582
+ }
460
583
  return {
461
- format: 'arcadia.environment-export/2',
462
- document: draft.document,
463
- contentRevision: installation.contentRevision,
584
+ format: shared.usesBase
585
+ ? 'arcadia.environment-export/4'
586
+ : archives.length
587
+ ? 'arcadia.environment-export/3'
588
+ : 'arcadia.environment-export/2',
589
+ ...(archives.length || shared.usesBase ? { archives } : {}),
590
+ document: shared.document,
591
+ contentRevision,
464
592
  files: files.map(({ path, bytes }) => ({ path, data: bytes.toString('base64') })),
465
593
  };
466
594
  }
467
- exportEnvironment(id) {
468
- return this.#exclusive(() => this.#export(id));
595
+ exportEnvironment(id, mode = 'share') {
596
+ return this.#exclusive(() => this.#export(id, mode));
469
597
  }
470
598
  async #snapshot() {
471
599
  for (const name of await readdir(join(this.root, 'imports'))) {
@@ -497,7 +625,7 @@ class ContentWorkspaceImplementation {
497
625
  captureSnapshot() {
498
626
  return this.#exclusive(async () => {
499
627
  const snapshot = await this.#snapshot();
500
- this.#snapshotFingerprint = revision(json(snapshot));
628
+ this.#snapshotFingerprint = sha256Hex(json(snapshot));
501
629
  const stamp = { workspaceId: this.workspaceId, bootId: this.bootId, generation: ++this.#snapshotGeneration };
502
630
  return { snapshot, stamp };
503
631
  });
@@ -511,7 +639,7 @@ class ContentWorkspaceImplementation {
511
639
  return false;
512
640
  const expected = this.#snapshotFingerprint;
513
641
  this.#snapshotFingerprint = undefined;
514
- return revision(json(await this.#snapshot())) === expected;
642
+ return sha256Hex(json(await this.#snapshot())) === expected;
515
643
  });
516
644
  }
517
645
  restoreSnapshot(snapshot, { mode }, preparer) {
@@ -544,7 +672,10 @@ class ContentWorkspaceImplementation {
544
672
  const manifest = JSON.parse(manifestText);
545
673
  const lock = await readJson(join(staging, 'package-lock.json'));
546
674
  await writeFile(join(staging, 'package.json'), json({ ...manifest, dependencies: lock.packages['']?.dependencies ?? {} }));
547
- const result = await preparer({ directory: staging, draft: drafts.get(id) });
675
+ const applied = normalizeEnvironmentDocument(entry.version.document);
676
+ if (applied.id !== id)
677
+ throw contentError('WORKSPACE_SNAPSHOT_INVALID');
678
+ const result = await preparer({ directory: staging, draft: applied });
548
679
  await inspectNpmProject(staging);
549
680
  await writeFile(join(staging, 'package.json'), manifestText);
550
681
  await writeFile(join(staging, '.arcadia-prepared.json'), json({
@@ -552,6 +683,10 @@ class ContentWorkspaceImplementation {
552
683
  format: 'arcadia.environment-installation/1',
553
684
  contentRevision: result.contentRevision,
554
685
  packages: result.packages ?? [],
686
+ ruleComposition: result.ruleComposition,
687
+ skillParameters: result.skillParameters,
688
+ contentCatalog: result.contentCatalog,
689
+ elementCatalog: result.elementCatalog,
555
690
  }));
556
691
  await rename(staging, this.#directory(id));
557
692
  }
@@ -577,7 +712,7 @@ class ContentWorkspaceImplementation {
577
712
  }
578
713
  importEnvironment(bundle, input, preparer) {
579
714
  return this.#exclusive(async () => {
580
- if (bundle?.format !== 'arcadia.environment-export/2')
715
+ if (!['arcadia.environment-export/2', 'arcadia.environment-export/3', 'arcadia.environment-export/4'].includes(bundle?.format))
581
716
  throw contentError('ENVIRONMENT_EXPORT_INVALID');
582
717
  const document = normalizeEnvironmentDocument({
583
718
  ...bundle.document,
@@ -593,8 +728,30 @@ class ContentWorkspaceImplementation {
593
728
  const staging = join(this.root, 'staging', `import-${randomUUID()}`);
594
729
  await mkdir(staging);
595
730
  try {
596
- await writeMaterials(staging, bundle.files, this.#options);
597
- const result = await this.#install(document, staging, preparer, input);
731
+ const files = bundle.format !== 'arcadia.environment-export/2'
732
+ ? await expandSharedMaterials(bundle.files, bundle.archives, {
733
+ ...this.#options,
734
+ signal: input.signal
735
+ ? AbortSignal.any([input.signal, this.#controller.signal])
736
+ : this.#controller.signal,
737
+ offline: this.#options.allowShareDownloads !== true || input.allowDownload === false,
738
+ environments: join(this.root, 'environments'),
739
+ supplied: bundle.suppliedArchives,
740
+ cache: this.#options.npmCache ?? join(this.root, 'npm-cache'),
741
+ })
742
+ : bundle.files;
743
+ await writeMaterials(staging, files, { ...this.#options, signal: input.signal });
744
+ // The recipient owns the captured local archives, including registered ZIP sources.
745
+ const manifest = await readJson(join(staging, 'package.json'));
746
+ const dependencies = manifest.dependencies;
747
+ for (const name of [...document.sources]) {
748
+ const spec = isRecord(dependencies) ? dependencies[name] : undefined;
749
+ if (typeof spec === 'string' && /^file:candidates\/[a-zA-Z0-9_.-]+\.tgz$/.test(spec)) {
750
+ document.packages[name] = spec;
751
+ document.sources = document.sources.filter(source => source !== name);
752
+ }
753
+ }
754
+ const result = await this.#install(document, staging, preparer, { ...input, importing: true });
598
755
  return result;
599
756
  }
600
757
  finally {
@@ -631,6 +788,7 @@ class ContentWorkspaceImplementation {
631
788
  const prepared = await readJson(join(staging, '.arcadia-prepared.json'));
632
789
  if (prepared.importId !== id || prepared.installationId !== environmentId)
633
790
  throw contentError('IMPORT_INTENT_INVALID');
791
+ await this.#archiveRemovedDeclarations(environmentId);
634
792
  const previous = join(this.root, 'staging', `replaced-${environmentId}`);
635
793
  let moved = false;
636
794
  try {
@@ -725,10 +883,21 @@ class ContentWorkspaceImplementation {
725
883
  }
726
884
  }
727
885
  export const ContentWorkspace = ContentWorkspaceImplementation;
728
- /** Change desired roots only. Resolved material and all published installations remain immutable. */
729
- export async function setEnvironmentPackageEnabled(workspace, input) {
730
- const { environmentId, expectedRevision, name, enabled, cascade = false } = input;
731
- if (typeof name !== 'string' || typeof enabled !== 'boolean' || typeof cascade !== 'boolean')
886
+ export function addEnvironmentPackage(workspace, input) {
887
+ return changeEnvironmentPackage(workspace, { ...input, action: 'add' });
888
+ }
889
+ export function removeEnvironmentPackage(workspace, input) {
890
+ return changeEnvironmentPackage(workspace, { ...input, action: 'remove' });
891
+ }
892
+ async function changeEnvironmentPackage(workspace, input) {
893
+ const { environmentId, expectedRevision, name } = input;
894
+ const cascade = input.action === 'remove' ? (input.cascade ?? false) : false;
895
+ if (!EnvironmentDocumentV2Schema.shape.sources.safeParse([name]).success || typeof cascade !== 'boolean')
896
+ throw contentError('ENVIRONMENT_PACKAGE_INVALID');
897
+ if (input.action === 'add' &&
898
+ ((input.version !== undefined && (typeof input.version !== 'string' || !input.version.trim())) ||
899
+ (input.source !== undefined && typeof input.source !== 'boolean') ||
900
+ (input.version !== undefined && input.source === true)))
732
901
  throw contentError('ENVIRONMENT_PACKAGE_INVALID');
733
902
  const draft = (await workspace.listDrafts()).find(item => item.document.id === environmentId);
734
903
  if (!draft)
@@ -736,33 +905,31 @@ export async function setEnvironmentPackageEnabled(workspace, input) {
736
905
  if (draft.revision !== expectedRevision)
737
906
  throw contentError('REVISION_CONFLICT');
738
907
  const document = structuredClone(draft.document);
739
- const disabled = document.disabled ?? { packages: {}, sources: [] };
740
- document.disabled = disabled;
741
908
  const active = new Set([...Object.keys(document.packages), ...document.sources]);
742
- if (enabled) {
743
- if (active.has(name))
744
- return draft;
745
- if (Object.hasOwn(disabled.packages, name)) {
746
- document.packages[name] = disabled.packages[name];
747
- delete disabled.packages[name];
909
+ if (input.action === 'add') {
910
+ const version = input.version?.trim();
911
+ if (version !== undefined) {
912
+ document.packages[name] = version;
913
+ document.sources = document.sources.filter(value => value !== name);
748
914
  }
749
- else if (disabled.sources.includes(name)) {
750
- document.sources.push(name);
751
- disabled.sources = disabled.sources.filter(value => value !== name);
915
+ else if (input.source === true) {
916
+ delete document.packages[name];
917
+ if (!document.sources.includes(name))
918
+ document.sources.push(name);
752
919
  }
753
920
  else
754
- throw contentError('ENVIRONMENT_PACKAGE_NOT_FOUND');
921
+ throw contentError('ENVIRONMENT_PACKAGE_DECLARATION_REQUIRED', '新增内容包需要指定版本或已登记来源');
755
922
  }
756
923
  else {
757
924
  const version = (await workspace.listInstallations())
758
925
  .filter((item) => item.status === 'ready')
759
926
  .filter(item => item.environmentId === environmentId && item.members)
760
927
  .sort((a, b) => b.createdAt - a.createdAt)[0];
761
- // A graph captured for different roots/ranges cannot justify disabling a shared dependency.
928
+ // A graph captured for different roots/ranges cannot justify removing a shared dependency.
762
929
  if (!version ||
763
930
  Object.entries(document.packages).some(([key, range]) => version.document.packages[key] !== range) ||
764
931
  document.sources.some(key => !version.document.sources.includes(key)))
765
- throw contentError('ENVIRONMENT_DEPENDENCIES_UNRESOLVED', '先准备当前组合,再调整依赖的启用状态');
932
+ throw contentError('ENVIRONMENT_DEPENDENCIES_UNRESOLVED', '请先准备当前组合,再移出内容包');
766
933
  const affected = new Set([name]);
767
934
  for (let changed = true; changed;) {
768
935
  changed = false;
@@ -778,15 +945,9 @@ export async function setEnvironmentPackageEnabled(workspace, input) {
778
945
  if (!cascade && roots.some(key => key !== name))
779
946
  throw contentError('ENVIRONMENT_PACKAGE_REQUIRED', `仍被这些资源包依赖:${roots.filter(key => key !== name).join('、')}`);
780
947
  for (const key of roots) {
781
- if (Object.hasOwn(document.packages, key)) {
782
- disabled.packages[key] = document.packages[key];
783
- delete document.packages[key];
784
- }
785
- else {
786
- disabled.sources.push(key);
787
- document.sources = document.sources.filter(value => value !== key);
788
- }
948
+ delete document.packages[key];
949
+ document.sources = document.sources.filter(value => value !== key);
789
950
  }
790
951
  }
791
- return workspace.saveDraft({ document, expectedRevision });
952
+ return workspace.saveDraft({ document: normalizeEnvironmentDocument(document), expectedRevision });
792
953
  }