@arcadia-eternity/content-sdk 4.13.0 → 4.15.0

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 (68) hide show
  1. package/README.md +16 -5
  2. package/dist/appimage-sdk.d.ts +2 -0
  3. package/dist/appimage-sdk.js +110 -0
  4. package/dist/author-api.d.ts +6 -1
  5. package/dist/author-api.js +27 -3
  6. package/dist/author-environment-install.d.ts +14 -0
  7. package/dist/author-environment-install.js +104 -0
  8. package/dist/author-environment-source.d.ts +162 -0
  9. package/dist/author-environment-source.js +226 -0
  10. package/dist/author-install.d.ts +22 -0
  11. package/dist/author-install.js +289 -0
  12. package/dist/author-reference.d.ts +1 -1
  13. package/dist/author-reference.js +23 -4
  14. package/dist/cli.js +56 -23
  15. package/dist/command-discovery.d.ts +3 -0
  16. package/dist/command-discovery.js +122 -0
  17. package/dist/content-query.js +4 -1
  18. package/dist/content-workspace.d.ts +2 -138
  19. package/dist/content-workspace.js +6 -6
  20. package/dist/debug-environment-install.d.ts +15 -0
  21. package/dist/debug-environment-install.js +130 -0
  22. package/dist/debug-environments.d.ts +135 -0
  23. package/dist/debug-environments.js +48 -0
  24. package/dist/demo.js +22 -8
  25. package/dist/desktop-cli.d.ts +3 -0
  26. package/dist/desktop-cli.js +72 -0
  27. package/dist/desktop-client.d.ts +71 -0
  28. package/dist/desktop-client.js +162 -0
  29. package/dist/environment-demo.d.ts +8 -0
  30. package/dist/environment-demo.js +52 -0
  31. package/dist/environment-rules.js +38 -19
  32. package/dist/environment.d.ts +12 -8
  33. package/dist/environment.js +107 -58
  34. package/dist/init.d.ts +1 -0
  35. package/dist/init.js +125 -0
  36. package/dist/jobs.d.ts +3 -1
  37. package/dist/jobs.js +34 -15
  38. package/dist/lib/presentation.js +12 -2
  39. package/dist/managed-projects.d.ts +5 -1
  40. package/dist/managed-projects.js +3 -3
  41. package/dist/mcp-contracts.d.ts +28 -1
  42. package/dist/mcp-contracts.js +24 -1
  43. package/dist/mcp.js +21 -7
  44. package/dist/official-environment-packages.d.ts +6 -0
  45. package/dist/official-environment-packages.js +19 -0
  46. package/dist/official-environments.d.ts +7 -0
  47. package/dist/official-environments.js +25 -0
  48. package/dist/pack-project.d.ts +1 -0
  49. package/dist/pack-project.js +66 -0
  50. package/dist/package-updates.d.ts +2 -1
  51. package/dist/package-updates.js +30 -17
  52. package/dist/prepared-document.d.ts +1 -0
  53. package/dist/prepared-document.js +5 -13
  54. package/dist/preview-control.js +24 -1
  55. package/dist/preview.d.ts +1 -0
  56. package/dist/preview.js +6 -4
  57. package/dist/project.d.ts +1 -0
  58. package/dist/project.js +57 -18
  59. package/dist/template/README.md +8 -8
  60. package/dist/template/package.json +2 -2
  61. package/dist/template/skills/arcadia-content-authoring/SKILL.md +15 -2
  62. package/dist/template/skills/arcadia-content-authoring/references/tool-workflows.md +25 -1
  63. package/dist/testing.d.ts +3 -4
  64. package/dist/testing.js +22 -8
  65. package/dist/workspace-cli.js +6 -4
  66. package/dist/workspace.d.ts +1 -0
  67. package/dist/workspace.js +66 -15
  68. package/package.json +10 -5
package/dist/cli.js CHANGED
@@ -1,20 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  import { spawn } from 'node:child_process';
3
3
  import { createRequire } from 'node:module';
4
+ import { readFile } from 'node:fs/promises';
4
5
  import { siblingModulePath } from './module-path.js';
5
6
  import { errorMessage } from './types.js';
7
+ import { commandHelp as help, commandsCli } from './command-discovery.js';
6
8
  const require = createRequire(import.meta.url);
7
9
  const [command, ...args] = process.argv.slice(2);
8
- const help = `arcadia-content <command>
9
- check Check TypeScript and JSON/YAML content
10
- build Compile TypeScript and assemble content/media/locales metadata
11
- rename Change package/project/namespace identities and local references
12
- demo Run the battle configured in arcadia.config.mjs
13
- preview Prepare a local candidate for the full battle client; stop with Ctrl+C
14
- pack [--release] Build a content archive; --release verifies a distributable in a clean consumer
15
- setup Install the pinned development SDK and tool
16
- workspace <directory> <operation> [--execute] Structured author operations
17
- `;
18
10
  function run(file, arguments_) {
19
11
  return new Promise((resolve, reject) => {
20
12
  const child = spawn(file, arguments_, { stdio: 'inherit', cwd: process.cwd() });
@@ -43,6 +35,12 @@ async function build() {
43
35
  try {
44
36
  if (!command || command === '--help' || command === '-h')
45
37
  console.log(help);
38
+ else if (command === 'commands')
39
+ await commandsCli(args);
40
+ else if (command === 'desktop')
41
+ await (await import('./desktop-cli.js')).desktopCli(args);
42
+ else if (command === 'init')
43
+ await (await import('./init.js')).initCommand(args);
46
44
  else if (command === 'workspace') {
47
45
  const { workspaceCli } = await import('./workspace-cli.js');
48
46
  await workspaceCli(args);
@@ -55,28 +53,63 @@ try {
55
53
  await run(process.execPath, [siblingModulePath('rename'), ...args]);
56
54
  else {
57
55
  if (!['check', 'build', 'demo', 'preview', 'pack'].includes(command) ||
58
- (args.length && !(command === 'pack' && args.length === 1 && args[0] === '--release')))
56
+ (args.length &&
57
+ !(command === 'pack' && args.length === 1 && args[0] === '--release') &&
58
+ !(command === 'demo' &&
59
+ args.length === 2 &&
60
+ args[0] === '--seed' &&
61
+ args[1].length > 0 &&
62
+ args[1].length <= 200)))
59
63
  throw new Error(`Unknown command or option.\n${help}`);
60
- if (command === 'check') {
61
- await data(true);
62
- await types(true);
63
- }
64
- else if (command === 'build')
65
- await build();
66
- else if (command === 'demo')
64
+ if (command === 'demo') {
65
+ if (args.length)
66
+ process.env.ARCADIA_DEBUG_SEED = args[1];
67
67
  await import('./demo.js');
68
+ }
68
69
  else if (command === 'preview')
69
70
  await (await import('./preview.js')).previewCommand();
70
- else {
71
- await build();
72
- const { packBuiltProject } = await import('./pack-project.js');
73
- const packed = await packBuiltProject(process.cwd(), { release: args[0] === '--release' });
71
+ else if (command === 'pack') {
72
+ const standalone = await checkStandaloneEnvironment(command);
73
+ const release = args[0] === '--release';
74
+ if (standalone && release)
75
+ throw new Error('Use pack to build an installable environment recipe.');
76
+ if (!standalone)
77
+ await build();
78
+ const { packBuiltProject, packEnvironmentProject } = await import('./pack-project.js');
79
+ const packed = standalone
80
+ ? await packEnvironmentProject(process.cwd())
81
+ : await packBuiltProject(process.cwd(), { release });
74
82
  console.log(`Packed ${packed.filename}`);
75
- console.log(`ARCADIA_RESULT=${JSON.stringify({ ...(args[0] === '--release' ? { verifiedRelease: true } : {}), filename: packed.filename, integrity: packed.integrity, shasum: packed.shasum, files: packed.files.map((file) => file.path) })}`);
83
+ console.log(`ARCADIA_RESULT=${JSON.stringify({ ...(release ? { verifiedRelease: true } : {}), filename: packed.filename, integrity: packed.integrity, shasum: packed.shasum, files: packed.files.map(file => file.path) })}`);
76
84
  }
85
+ else if (await checkStandaloneEnvironment(command)) {
86
+ console.log('Environment declaration OK');
87
+ }
88
+ else if (command === 'check') {
89
+ await data(true);
90
+ await types(true);
91
+ }
92
+ else if (command === 'build')
93
+ await build();
77
94
  }
78
95
  }
79
96
  catch (error) {
80
97
  console.error(errorMessage(error));
81
98
  process.exitCode = 1;
82
99
  }
100
+ async function checkStandaloneEnvironment(operation) {
101
+ const text = await readFile('package.json', 'utf8');
102
+ const manifest = JSON.parse(text);
103
+ if (manifest.arcadia || !Object.hasOwn(manifest, 'arcadiaEnvironment'))
104
+ return false;
105
+ if (operation === 'pack')
106
+ return true;
107
+ if (operation !== 'check')
108
+ throw new Error('Standalone environment projects support check, demo, preview and pack. This build command requires a content pack.');
109
+ const { environmentProjectDocument } = await import('./debug-environments.js');
110
+ const { assertEnvironmentRequirements, prepareEnvironmentRules } = await import('./environment-rules.js');
111
+ const document = environmentProjectDocument(manifest);
112
+ assertEnvironmentRequirements(document.requires);
113
+ prepareEnvironmentRules(document.rules);
114
+ return true;
115
+ }
@@ -0,0 +1,3 @@
1
+ export declare const desktopHelp: string;
2
+ export declare const commandHelp: string;
3
+ export declare function commandsCli(args: string[]): Promise<void>;
@@ -0,0 +1,122 @@
1
+ import { createRequire } from 'node:module';
2
+ const commands = [
3
+ {
4
+ name: 'commands',
5
+ arguments: '--json',
6
+ target: 'sdk',
7
+ description: 'List CLI commands and workspace operations as JSON.',
8
+ },
9
+ {
10
+ name: 'init',
11
+ arguments: '<pack|environment> <directory> [--id <id>]',
12
+ target: 'sdk',
13
+ description: 'Create an author project in a new or empty directory.',
14
+ },
15
+ {
16
+ name: 'check',
17
+ arguments: '',
18
+ target: 'project',
19
+ description: 'Check content sources or a standalone environment declaration.',
20
+ },
21
+ {
22
+ name: 'build',
23
+ arguments: '',
24
+ target: 'project',
25
+ description: 'Compile TypeScript and assemble content pack metadata.',
26
+ },
27
+ {
28
+ name: 'rename',
29
+ arguments: '--name <package-name> --project-id <id> --namespace <namespace>',
30
+ target: 'project',
31
+ description: 'Change the identities and local references of a content pack.',
32
+ },
33
+ {
34
+ name: 'demo',
35
+ arguments: '[--seed <seed>]',
36
+ target: 'project',
37
+ description: 'Run a headless battle with the saved project teams.',
38
+ },
39
+ {
40
+ name: 'preview',
41
+ arguments: '',
42
+ target: 'project',
43
+ description: 'Prepare a local candidate for the full battle client. Stop with Ctrl+C.',
44
+ },
45
+ {
46
+ name: 'pack',
47
+ arguments: '[--release]',
48
+ target: 'project',
49
+ description: 'Build a content pack or environment archive. --release verifies a content pack in a clean consumer.',
50
+ },
51
+ {
52
+ name: 'setup',
53
+ arguments: '[--sdk-dir <directory>] [--offline]',
54
+ target: 'project',
55
+ description: 'Install the pinned development SDK and tool.',
56
+ },
57
+ {
58
+ name: 'workspace',
59
+ arguments: '<directory> [<operation>] [--execute]',
60
+ target: 'project',
61
+ description: 'Run a structured author operation. The default operation is describe.',
62
+ },
63
+ {
64
+ name: 'desktop instances',
65
+ arguments: '',
66
+ target: 'desktop',
67
+ description: 'List running Desktop instances available to this user.',
68
+ },
69
+ ...['packages', 'environments'].flatMap((library) => [
70
+ {
71
+ name: 'desktop ' + library + ' list',
72
+ arguments: '[--instance <id>]',
73
+ target: 'desktop',
74
+ description: 'List ' + library + ' in the selected Desktop library.',
75
+ },
76
+ {
77
+ name: 'desktop ' + library + ' install',
78
+ arguments: library === 'packages'
79
+ ? '<file.tgz|file.zip|name@version> [--instance <id>] [--allow-download]'
80
+ : '<file.tgz|name@version> [--instance <id>] [--allow-download] [--id <environment-id>]',
81
+ target: 'desktop',
82
+ description: 'Install into the selected Desktop library. Downloads require --allow-download.',
83
+ },
84
+ ]),
85
+ ];
86
+ export const desktopHelp = commands
87
+ .filter(command => command.target === 'desktop')
88
+ .map(command => ['arcadia-content', command.name, command.arguments].filter(Boolean).join(' '))
89
+ .join('\n');
90
+ export const commandHelp = [
91
+ 'arcadia-content <command>',
92
+ ...commands.map(command => ` ${[command.name, command.arguments].filter(Boolean).join(' ')} ${command.description}`),
93
+ ].join('\n');
94
+ export async function commandsCli(args) {
95
+ if (args.length !== 1 || args[0] !== '--json')
96
+ throw new Error('Usage: arcadia-content commands --json');
97
+ const { jobKind, outputSchemas } = await import('./mcp-contracts.js');
98
+ // These raw session operations have no corresponding structured MCP result schema.
99
+ const operations = [...Object.keys(outputSchemas), 'snapshot', 'job', 'jobs', 'cancel'].sort();
100
+ console.log(JSON.stringify({
101
+ schemaVersion: 1,
102
+ sdkVersion: createRequire(import.meta.url)('../package.json').version,
103
+ commands,
104
+ workspace: {
105
+ operations,
106
+ input: { source: 'stdin', format: 'json-object', ignoredBy: ['describe', 'git-status'] },
107
+ jobs: jobKind.options.map(name => ({
108
+ name,
109
+ requiresExecute: name !== 'check',
110
+ projectKinds: name === 'release' ? ['pack'] : ['pack', 'environment'],
111
+ options: [
112
+ ...(name === 'preview' || name === 'demo' ? ['--environment <id>'] : []),
113
+ ...(name === 'demo' ? ['--seed <seed>'] : []),
114
+ ],
115
+ })),
116
+ previewOperations: [
117
+ { name: 'team-validate', requiresExecute: false },
118
+ { name: 'battle', requiresExecute: true },
119
+ ],
120
+ },
121
+ }));
122
+ }
@@ -2,6 +2,7 @@ import { contentLocaleCollection } from '@arcadia-eternity/schema';
2
2
  import { lstat, readFile, realpath } from 'node:fs/promises';
3
3
  import { dirname, join } from 'node:path';
4
4
  import { AuthorWorkspace, WorkspaceError, diagnostic, } from './workspace.js';
5
+ import { findAuthorInstallation } from './author-install.js';
5
6
  import { recordSharing } from './lib/yaml-sharing.js';
6
7
  import { errorCode, isRecord } from './types.js';
7
8
  const kinds = ['content', 'presentations', 'resources', 'assets', 'files', 'locales', 'diagnostics'];
@@ -123,8 +124,10 @@ async function catalogs(workspace, scope) {
123
124
  const diagnostics = [];
124
125
  if (scope === 'project')
125
126
  return { catalogs: result, diagnostics };
127
+ const installed = await findAuthorInstallation(workspace.root, manifest.dependencies);
128
+ const declared = isRecord(manifest.dependencies) ? manifest.dependencies : {};
126
129
  const queue = runtimeDependencies(manifest).map(([name, optional]) => ({
127
- from: workspace.root,
130
+ from: installed && Object.hasOwn(declared, name) ? installed.directory : workspace.root,
128
131
  name,
129
132
  optional,
130
133
  }));
@@ -664,144 +664,7 @@ export type RemoveEnvironmentPackageInput = {
664
664
  type PackageWorkspace = Pick<ContentWorkspace, 'listDrafts' | 'listInstallations' | 'saveDraft'>;
665
665
  export declare function addEnvironmentPackage(workspace: PackageWorkspace, input: AddEnvironmentPackageInput): Promise<EnvironmentDraft>;
666
666
  export declare function removeEnvironmentPackage(workspace: PackageWorkspace, input: RemoveEnvironmentPackageInput): Promise<EnvironmentDraft>;
667
- /** Resolve presets from the same selected base installation as the battle materials. */
668
- export declare function readOfficialEnvironments(root: string, legacyCatalog: string | URL): Promise<{
669
- defaultEnvironment: string;
670
- environments: {
671
- id: string;
672
- name: string;
673
- packages: Record<string, string>;
674
- sources: string[];
675
- schemaVersion: 2;
676
- rules: {
677
- schemaVersion: 1 | 2;
678
- mechanics?: {
679
- skillSlots?: {
680
- normalMax: number;
681
- climaxMax: number;
682
- climaxMin?: number | undefined;
683
- } | undefined;
684
- individualValueDefault?: number | undefined;
685
- individualValues?: {
686
- max: number;
687
- } | undefined;
688
- allowFaintSwitch?: boolean | undefined;
689
- timer?: {
690
- enabled: boolean;
691
- turnTimeLimit?: number | undefined;
692
- totalTimeLimit?: number | undefined;
693
- animationPauseEnabled?: boolean | undefined;
694
- maxAnimationDuration?: number | undefined;
695
- } | undefined;
696
- teamSelection?: {
697
- enabled: boolean;
698
- mode?: "FULL_TEAM" | "TEAM_SELECTION" | "VIEW_ONLY" | undefined;
699
- minTeamSize?: number | undefined;
700
- maxTeamSize?: number | undefined;
701
- allowStarterSelection?: boolean | undefined;
702
- showOpponentTeam?: boolean | undefined;
703
- teamInfoVisibility?: "BASIC" | "FULL" | "HIDDEN" | undefined;
704
- timeLimit?: number | undefined;
705
- } | undefined;
706
- inheritance?: {
707
- eligible: "all" | "off" | "species" | string[];
708
- pool?: {
709
- mode: "append" | "fallback" | "replace";
710
- skills: string[];
711
- } | undefined;
712
- } | undefined;
713
- enhancement?: {
714
- mode: "active" | "forbidden" | "suppressed";
715
- minLevel?: number | undefined;
716
- defaultBranches?: string[] | undefined;
717
- stages?: string[] | undefined;
718
- species?: string[] | undefined;
719
- } | undefined;
720
- secondGenerationNatures?: "all" | "off" | "species" | string[] | undefined;
721
- } | undefined;
722
- skillParameters?: {
723
- profile?: string | undefined;
724
- groups?: Record<string, number> | undefined;
725
- overrides?: {
726
- skill: string;
727
- useId: string;
728
- parameter: string;
729
- value: number;
730
- }[] | undefined;
731
- } | undefined;
732
- matchups?: {
733
- table?: string | undefined;
734
- adjustments?: {
735
- attack: string;
736
- defense: string;
737
- multiplier: number;
738
- }[] | undefined;
739
- } | undefined;
740
- learnsetAdjustments?: {
741
- species: string;
742
- source: "inherited" | "normal";
743
- skill: string;
744
- action: "add" | "remove";
745
- level?: number | undefined;
746
- }[] | undefined;
747
- tier?: "standard" | undefined;
748
- allow?: {
749
- species?: string[] | undefined;
750
- skills?: string[] | undefined;
751
- marks?: string[] | undefined;
752
- } | undefined;
753
- deny?: {
754
- species?: string[] | undefined;
755
- skills?: string[] | undefined;
756
- marks?: string[] | undefined;
757
- } | undefined;
758
- team?: {
759
- minSize?: number | undefined;
760
- maxSize?: number | undefined;
761
- uniqueSpecies?: boolean | undefined;
762
- } | undefined;
763
- constraints?: ({
764
- id: string;
765
- allOf: {
766
- kind: "mark" | "skill" | "species";
767
- ids: string[];
768
- fromCollections?: string[] | undefined;
769
- }[];
770
- kind: "ban";
771
- scope: "pet" | "team";
772
- exceptWhen?: {
773
- kind: "mark" | "skill" | "species";
774
- ids: string[];
775
- fromCollections?: string[] | undefined;
776
- }[] | undefined;
777
- exceptAny?: {
778
- kind: "mark" | "skill" | "species";
779
- ids: string[];
780
- fromCollections?: string[] | undefined;
781
- }[][] | undefined;
782
- } | {
783
- id: string;
784
- allOf: {
785
- kind: "mark" | "skill" | "species";
786
- ids: string[];
787
- fromCollections?: string[] | undefined;
788
- }[];
789
- kind: "memberLimit";
790
- max: number;
791
- })[] | undefined;
792
- collections?: {
793
- id: string;
794
- kind: "mark" | "skill" | "species";
795
- ids: string[];
796
- }[] | undefined;
797
- };
798
- requires: {
799
- engine?: string | undefined;
800
- sdk?: string | undefined;
801
- capabilities?: string[] | undefined;
802
- };
803
- }[];
804
- }>;
667
+ export declare function readOfficialEnvironments(root: string, resolvePackage: (specifier: string) => string, cachedCatalog?: string): Promise<import("./official-environments.js").OfficialEnvironmentCatalog>;
805
668
  /** The host supplies this catalog from the application distribution. */
806
669
  export declare function readShippedEnvironments(file: string | URL, bundledVersions: Record<string, string>): Promise<{
807
670
  defaultEnvironment: string;
@@ -941,3 +804,4 @@ export declare function readShippedEnvironments(file: string | URL, bundledVersi
941
804
  }[];
942
805
  }>;
943
806
  export declare function synchronizeShippedEnvironments(workspace: OwnedContentWorkspace, catalog: Awaited<ReturnType<typeof readShippedEnvironments>>, adopted: Record<string, string>, prepare: (document: EnvironmentDocument, expectedRevision: string | null) => Promise<unknown>, officialBaseRoot?: string): Promise<string>;
807
+ export { acquireAuthorEnvironment, parseAuthorEnvironmentNpmSpec, type AuthorEnvironmentSource, } from './author-environment-source.js';
@@ -1,4 +1,5 @@
1
1
  import { sha256Hex, skillParameterCatalogSchema, readElementCatalog, } from '@arcadia-eternity/const';
2
+ import { bundledEnvironmentCatalog } from './official-environments.js';
2
3
  import { randomUUID } from 'node:crypto';
3
4
  import { isDeepStrictEqual } from 'node:util';
4
5
  import { lstat, mkdir, readFile, readdir, realpath, rename, rm, writeFile } from 'node:fs/promises';
@@ -1085,15 +1086,13 @@ async function changeEnvironmentPackage(workspace, input) {
1085
1086
  }
1086
1087
  return workspace.saveDraft({ document: normalizeEnvironmentDocument(document), expectedRevision });
1087
1088
  }
1088
- /** Resolve presets from the same selected base installation as the battle materials. */
1089
- export async function readOfficialEnvironments(root, legacyCatalog) {
1089
+ export async function readOfficialEnvironments(root, resolvePackage, cachedCatalog) {
1090
1090
  const manifest = await readJson(join(root, 'package.json'));
1091
1091
  if (manifest.name !== hostBaseName || typeof manifest.version !== 'string' || !semver.valid(manifest.version))
1092
1092
  throw contentError('BUNDLED_PACKAGE_INVALID');
1093
- const file = isRecord(manifest.arcadia) ? manifest.arcadia.environments : undefined;
1094
- if (file !== undefined && file !== 'dist/environment/presets.json')
1095
- throw contentError('SHIPPED_ENVIRONMENT_CATALOG_INVALID');
1096
- return readShippedEnvironments(file ? join(root, file) : legacyCatalog, { [hostBaseName]: manifest.version });
1093
+ return cachedCatalog
1094
+ ? readShippedEnvironments(cachedCatalog, { [hostBaseName]: manifest.version })
1095
+ : bundledEnvironmentCatalog(manifest.version, resolvePackage);
1097
1096
  }
1098
1097
  /** The host supplies this catalog from the application distribution. */
1099
1098
  export async function readShippedEnvironments(file, bundledVersions) {
@@ -1137,3 +1136,4 @@ export async function synchronizeShippedEnvironments(workspace, catalog, adopted
1137
1136
  }
1138
1137
  return catalog.defaultEnvironment;
1139
1138
  }
1139
+ export { acquireAuthorEnvironment, parseAuthorEnvironmentNpmSpec, } from './author-environment-source.js';
@@ -0,0 +1,15 @@
1
+ export declare function stageEnvironmentDependencies({ materialRoot, sourceRoot, installation, dependencies, hasSources, lockText, sourceLocked, }: {
2
+ materialRoot: string;
3
+ sourceRoot: string;
4
+ installation: string;
5
+ dependencies: Record<string, string>;
6
+ hasSources: boolean;
7
+ lockText?: string;
8
+ sourceLocked: boolean;
9
+ }): Promise<{
10
+ installed: string;
11
+ lockText: string | undefined;
12
+ } | {
13
+ installed?: undefined;
14
+ lockText: any;
15
+ }>;
@@ -0,0 +1,130 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { createReadStream } from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import { copyFile, readFile, realpath } from 'node:fs/promises';
5
+ import { join, dirname } from 'node:path';
6
+ import { sha256Hex } from '@arcadia-eternity/const';
7
+ import { stageCatalogProject, withShippedCatalogArchive } from '@arcadia-eternity/pack-loader/node';
8
+ import { satisfies, validRange } from 'semver';
9
+ import { isRecord, errorCode } from './types.js';
10
+ const officialBase = '@arcadia-eternity/data-pack-base';
11
+ const candidateArchive = /^file:candidates\/[a-zA-Z0-9_.-]+\.tgz$/;
12
+ // The standalone SDK need not ship the official catalog. Prefer an available matching
13
+ // version when there is no registry pin. A registry lock always retains its own integrity.
14
+ async function baseDirectory(root, range, pinned) {
15
+ for (const loader of [createRequire(join(root, 'package.json')), createRequire(import.meta.url)]) {
16
+ let file;
17
+ try {
18
+ file = loader.resolve(officialBase + '/package.json');
19
+ }
20
+ catch (error) {
21
+ if (errorCode(error) !== 'MODULE_NOT_FOUND')
22
+ throw error;
23
+ continue;
24
+ }
25
+ const { name, version } = JSON.parse(await readFile(file, 'utf8'));
26
+ if (name === officialBase && satisfies(version, range) && (!pinned || version === pinned))
27
+ return dirname(file);
28
+ }
29
+ return undefined;
30
+ }
31
+ async function matchesIntegrity(file, integrity) {
32
+ const tokens = integrity.split(/\s+/);
33
+ for (const algorithm of ['sha512', 'sha384', 'sha256', 'sha1']) {
34
+ const expected = tokens.filter(token => token.startsWith(algorithm + '-'));
35
+ if (!expected.length)
36
+ continue;
37
+ const hash = createHash(algorithm);
38
+ for await (const chunk of createReadStream(file))
39
+ hash.update(chunk);
40
+ return expected.includes(algorithm + '-' + hash.digest('base64'));
41
+ }
42
+ throw new Error('INSTALL_LOCK_INTEGRITY_INVALID');
43
+ }
44
+ export async function stageEnvironmentDependencies({ materialRoot, sourceRoot, installation, dependencies, hasSources, lockText, sourceLocked, }) {
45
+ const root = await realpath(materialRoot);
46
+ const lock = lockText ? JSON.parse(lockText) : undefined;
47
+ if (lock && (![2, 3].includes(lock.lockfileVersion) || !isRecord(lock.packages)))
48
+ throw new Error('INSTALL_LOCK_INVALID');
49
+ const local = new Set();
50
+ const locations = new Map();
51
+ for (const [name, spec] of Object.entries(dependencies)) {
52
+ if (candidateArchive.test(spec))
53
+ local.add(spec);
54
+ else if (!validRange(spec))
55
+ throw new Error(`INSTALL_VERSION_INVALID: ${name}`);
56
+ }
57
+ const requiredArchives = new Set(local);
58
+ const basePin = lock?.packages['node_modules/' + officialBase];
59
+ const localBasePin = typeof basePin?.resolved === 'string' && /^file:candidates\/debug-base-[a-f0-9]{64}\.tgz$/.test(basePin.resolved);
60
+ const range = dependencies[officialBase];
61
+ const bundled = range && validRange(range) && (!basePin?.resolved || localBasePin)
62
+ ? await baseDirectory(sourceRoot, range, basePin && satisfies(basePin.version, range) ? basePin.version : undefined)
63
+ : undefined;
64
+ if (localBasePin && range && validRange(range) && satisfies(basePin.version, range) && !bundled)
65
+ throw new Error(`BASE_PACK_VERSION_UNAVAILABLE: install ${officialBase}@${basePin.version} or regenerate the debug lock to use a registry artifact`);
66
+ for (const [location, entry] of Object.entries(lock?.packages ?? {})) {
67
+ if (!isRecord(entry) ||
68
+ entry.link ||
69
+ (location &&
70
+ (!location.startsWith('node_modules/') || location.includes('\\') || location.split('/').includes('..'))))
71
+ throw new Error('INSTALL_LOCK_INVALID');
72
+ if (typeof entry.resolved !== 'string')
73
+ continue;
74
+ if (candidateArchive.test(entry.resolved)) {
75
+ // Locally staged source archives and the local base are regenerated by the debug host.
76
+ if (entry.resolved === basePin?.resolved && localBasePin)
77
+ continue;
78
+ if (/^file:candidates\/[a-f0-9]{40}\.tgz$/.test(entry.resolved) && !local.has(entry.resolved))
79
+ continue;
80
+ local.add(entry.resolved);
81
+ const pins = locations.get(entry.resolved) ?? [];
82
+ pins.push({ location, integrity: typeof entry.integrity === 'string' ? entry.integrity : undefined });
83
+ locations.set(entry.resolved, pins);
84
+ }
85
+ else {
86
+ const url = new URL(entry.resolved);
87
+ if (url.protocol !== 'https:' || url.username || url.password)
88
+ throw new Error('INSTALL_LOCK_INVALID');
89
+ }
90
+ }
91
+ if (bundled && Object.keys(dependencies).length === 1 && !hasSources)
92
+ return { installed: await stageCatalogProject(installation, bundled), lockText };
93
+ for (const spec of local) {
94
+ const relative = spec.slice(5);
95
+ const file = join(root, relative);
96
+ const pins = locations.get(spec) ?? [];
97
+ const canonical = await realpath(file).catch(error => {
98
+ if (errorCode(error) !== 'ENOENT' || sourceLocked || requiredArchives.has(spec))
99
+ throw error;
100
+ });
101
+ if (!canonical) {
102
+ // A previous preview can still mention an archive the author removed or renamed.
103
+ // Let npm resolve the current declarations without that obsolete local pin.
104
+ for (const pin of pins)
105
+ delete lock.packages[pin.location];
106
+ continue;
107
+ }
108
+ if (canonical !== file)
109
+ throw new Error('MATERIAL_PATH_ESCAPE');
110
+ const captured = join(installation, relative);
111
+ await copyFile(file, captured);
112
+ for (const pin of pins) {
113
+ if (!pin.integrity || (await matchesIntegrity(captured, pin.integrity)))
114
+ continue;
115
+ if (sourceLocked)
116
+ throw new Error(`ENVIRONMENT_ARCHIVE_INTEGRITY: ${relative} differs from package-lock.json`);
117
+ // npm may serve the old byte stream from its cache even for a changed file:
118
+ // dependency. Discard this generated resolution and resolve the captured bytes.
119
+ delete lock.packages[pin.location];
120
+ }
121
+ }
122
+ if (bundled) {
123
+ await withShippedCatalogArchive(bundled, undefined, async (file) => {
124
+ const relative = 'candidates/debug-base-' + sha256Hex(await readFile(file)) + '.tgz';
125
+ await copyFile(file, join(installation, relative));
126
+ dependencies[officialBase] = 'file:' + relative;
127
+ });
128
+ }
129
+ return { lockText: lock && JSON.stringify(lock) };
130
+ }