@arcadia-eternity/content-sdk 4.12.0 → 4.14.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 (67) 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/managed-projects.d.ts +7 -3
  39. package/dist/managed-projects.js +10 -6
  40. package/dist/mcp-contracts.d.ts +28 -1
  41. package/dist/mcp-contracts.js +24 -1
  42. package/dist/mcp.js +21 -7
  43. package/dist/official-environment-packages.d.ts +6 -0
  44. package/dist/official-environment-packages.js +19 -0
  45. package/dist/official-environments.d.ts +7 -0
  46. package/dist/official-environments.js +25 -0
  47. package/dist/pack-project.d.ts +1 -0
  48. package/dist/pack-project.js +66 -0
  49. package/dist/package-updates.d.ts +10 -3
  50. package/dist/package-updates.js +71 -21
  51. package/dist/prepared-document.d.ts +1 -0
  52. package/dist/prepared-document.js +5 -13
  53. package/dist/preview-control.js +24 -1
  54. package/dist/preview.d.ts +1 -0
  55. package/dist/preview.js +6 -4
  56. package/dist/project.d.ts +1 -0
  57. package/dist/project.js +57 -18
  58. package/dist/template/README.md +8 -8
  59. package/dist/template/package.json +2 -2
  60. package/dist/template/skills/arcadia-content-authoring/SKILL.md +15 -2
  61. package/dist/template/skills/arcadia-content-authoring/references/tool-workflows.md +25 -1
  62. package/dist/testing.d.ts +3 -4
  63. package/dist/testing.js +22 -8
  64. package/dist/workspace-cli.js +6 -4
  65. package/dist/workspace.d.ts +1 -0
  66. package/dist/workspace.js +66 -15
  67. package/package.json +10 -5
@@ -54,18 +54,29 @@ export function assertEnvironmentRequirements(input, host = currentHost) {
54
54
  code: 'ENVIRONMENT_CAPABILITY_UNSUPPORTED',
55
55
  });
56
56
  }
57
+ function rejectTeam(detail) {
58
+ const code = 'ENVIRONMENT_TEAM_REJECTED';
59
+ throw Object.assign(new Error(code), { code, detail });
60
+ }
57
61
  /** Admission checks apply to normalized team definitions, before creating any battle. */
58
62
  export function assertEnvironmentTeam(input, team) {
59
63
  const rules = validateEnvironmentRules(input);
60
64
  const { minSize, maxSize, uniqueSpecies } = resolveEnvironmentTeam(rules);
61
- if (!Array.isArray(team) || team.length < minSize || team.length > maxSize)
62
- fail('ENVIRONMENT_TEAM_REJECTED');
65
+ if (!Array.isArray(team))
66
+ rejectTeam('队伍必须是精灵列表');
67
+ if (team.length < minSize || team.length > maxSize)
68
+ rejectTeam(`队伍需要 ${minSize}–${maxSize} 只精灵,当前为 ${team.length} 只`);
63
69
  for (const pet of team)
64
70
  assertEnvironmentMember(rules, pet);
65
- if (teamConstraintIssues(rules.constraints, team, 'team').length)
66
- fail('ENVIRONMENT_TEAM_REJECTED');
67
- if (uniqueSpecies && new Set(team.map(pet => pet.species)).size !== team.length)
68
- fail('ENVIRONMENT_TEAM_REJECTED');
71
+ const [issue] = teamConstraintIssues(rules.constraints, team, 'team');
72
+ if (issue)
73
+ rejectTeam(issue.message);
74
+ if (uniqueSpecies) {
75
+ const species = team.map(pet => pet.species);
76
+ const duplicate = species.find((id, index) => species.indexOf(id) !== index);
77
+ if (duplicate)
78
+ rejectTeam(`team.uniqueSpecies 禁止重复携带 ${duplicate}`);
79
+ }
69
80
  }
70
81
  export function assertPlayableTeam(rules, team, ...content) {
71
82
  assertEnvironmentTeam(rules, team);
@@ -75,22 +86,23 @@ export function assertPlayableTeam(rules, team, ...content) {
75
86
  export function assertEnvironmentMember(rules, pet) {
76
87
  const ivLimit = resolveEnvironmentMechanics(rules).individualValues.max;
77
88
  if (!record(pet))
78
- fail('ENVIRONMENT_TEAM_REJECTED');
89
+ rejectTeam('精灵配置应为对象');
79
90
  const petRecord = pet;
80
91
  if (!identifier(petRecord.species) ||
81
92
  !Array.isArray(petRecord.skills) ||
82
93
  petRecord.skills.some(skill => !identifier(skill)))
83
- fail('ENVIRONMENT_TEAM_REJECTED');
94
+ rejectTeam('精灵配置需要有效的物种和技能 ID');
84
95
  if ([petRecord.ability, petRecord.emblem].some(mark => mark !== undefined && mark !== '' && !identifier(mark)))
85
- fail('ENVIRONMENT_TEAM_REJECTED');
96
+ rejectTeam(`${petRecord.species} 的特性或纹章 ID 无效`);
86
97
  if (petRecord.enhancement !== undefined) {
87
- if (!identifier(petRecord.enhancement) ||
88
- !allowsEnhancementRecord(rules.mechanics?.enhancement, petRecord.species, petRecord.enhancement, typeof petRecord.level === 'number' ? petRecord.level : undefined))
89
- fail('ENVIRONMENT_TEAM_REJECTED');
98
+ if (!identifier(petRecord.enhancement))
99
+ rejectTeam(`${petRecord.species} 的强化阶段 ID 无效`);
100
+ if (!allowsEnhancementRecord(rules.mechanics?.enhancement, petRecord.species, petRecord.enhancement, typeof petRecord.level === 'number' ? petRecord.level : undefined))
101
+ rejectTeam(`${petRecord.species} 不能使用强化阶段 ${petRecord.enhancement}`);
90
102
  }
91
103
  const sourceLimits = petRecord.ivMax;
92
104
  if (sourceLimits !== undefined && !record(sourceLimits))
93
- fail('ENVIRONMENT_TEAM_REJECTED');
105
+ rejectTeam(`${petRecord.species} 的资质上限无效`);
94
106
  if (petRecord.ivs !== undefined &&
95
107
  (!record(petRecord.ivs) ||
96
108
  Object.entries(petRecord.ivs).some(([stat, value]) => {
@@ -104,16 +116,17 @@ export function assertEnvironmentMember(rules, pet) {
104
116
  value < 0 ||
105
117
  value > max);
106
118
  })))
107
- fail('ENVIRONMENT_TEAM_REJECTED');
108
- if (teamConstraintIssues(rules.constraints, [
119
+ rejectTeam(`${petRecord.species} 的资质或资质上限不符合环境要求`);
120
+ const [issue] = teamConstraintIssues(rules.constraints, [
109
121
  {
110
122
  species: petRecord.species,
111
123
  skills: petRecord.skills,
112
124
  ability: petRecord.ability,
113
125
  emblem: petRecord.emblem,
114
126
  },
115
- ], 'pet').length)
116
- fail('ENVIRONMENT_TEAM_REJECTED');
127
+ ], 'pet');
128
+ if (issue)
129
+ rejectTeam(`${petRecord.species}:${issue.message}`);
117
130
  const selected = {
118
131
  species: [petRecord.species],
119
132
  skills: [
@@ -124,8 +137,14 @@ export function assertEnvironmentMember(rules, pet) {
124
137
  };
125
138
  for (const kind of ['species', 'skills', 'marks']) {
126
139
  const allow = rules.allow?.[kind], deny = rules.deny?.[kind];
127
- if (selected[kind].some(id => !identifier(id) || (allow !== undefined && !allow.includes(id)) || deny?.includes(id)))
128
- fail('ENVIRONMENT_TEAM_REJECTED');
140
+ for (const id of selected[kind]) {
141
+ if (!identifier(id))
142
+ rejectTeam(`${petRecord.species} 的 ${kind} ID 无效`);
143
+ if (deny?.includes(id))
144
+ rejectTeam(`${petRecord.species}:deny.${kind} 禁止使用 ${id}`);
145
+ if (allow !== undefined && !allow.includes(id))
146
+ rejectTeam(`${petRecord.species}:allow.${kind} 未包含 ${id}`);
147
+ }
129
148
  }
130
149
  }
131
150
  /** Compatibility defaults for unmanaged projects with the official base package. */
@@ -1,5 +1,5 @@
1
1
  import { prepareNpmProject } from '@arcadia-eternity/pack-loader/node';
2
- import { type ManifestArcadia, type PackageManifest } from './workspace.js';
2
+ import { type PackageManifest } from './workspace.js';
3
3
  import { playersFromTeams, type ProjectTeam } from './project-teams.js';
4
4
  import { type EnvironmentDocumentV2 } from './debug-environments.js';
5
5
  import { prepareRulesForContent } from './environment-rules.js';
@@ -8,11 +8,16 @@ export interface BattleLike {
8
8
  cleanup(): Promise<void>;
9
9
  }
10
10
  export interface ContentCandidate {
11
+ kind: 'pack' | 'environment';
12
+ members: Array<{
13
+ name: string;
14
+ version: string;
15
+ }>;
11
16
  packageName: string | undefined;
12
17
  version: string | undefined;
13
- integrity: string;
14
- shasum: string;
15
- sdkApi: unknown;
18
+ integrity?: string;
19
+ shasum?: string;
20
+ sdkApi?: unknown;
16
21
  build: unknown;
17
22
  environmentRevision: string;
18
23
  environmentId: string;
@@ -31,20 +36,19 @@ export interface PreparedBattleEnvironment {
31
36
  loadTeams(ids: string[]): ReturnType<typeof playersFromTeams>;
32
37
  teams: ProjectTeam[];
33
38
  teamVersions: Record<string, string | null>;
34
- manifest: PackageManifest & {
35
- arcadia: ManifestArcadia;
36
- };
39
+ manifest: PackageManifest;
37
40
  files: string[];
38
41
  dispose(): Promise<void>;
39
42
  track(battle: BattleLike): void;
40
43
  untrack(battle: BattleLike): void;
41
44
  }
42
45
  /** Pack and install exactly what a consuming server receives. Approval is limited to this local demo. */
43
- export declare function prepareBattleEnvironment(root?: string, { offline, cache, environmentId, sources, lockRoot, }?: {
46
+ export declare function prepareBattleEnvironment(root?: string, { offline, cache, environmentId, sources, lockRoot, sourceRoot, }?: {
44
47
  offline?: boolean;
45
48
  cache?: string;
46
49
  environmentId?: string;
47
50
  sources?: Record<string, string | undefined>;
48
51
  lockRoot?: string;
52
+ sourceRoot?: string;
49
53
  }): Promise<PreparedBattleEnvironment>;
50
54
  export {};
@@ -13,6 +13,9 @@ import { DebugEnvironments, normalizeEnvironmentDocument } from './debug-environ
13
13
  import { assertEnvironmentRequirements, defaultRuleDeclaration, prepareRulesForContent, validateEnvironmentRuleDeclaration, } from './environment-rules.js';
14
14
  import { siblingModulePath } from './module-path.js';
15
15
  import { errorCode } from './types.js';
16
+ import { packBuiltProject } from './pack-project.js';
17
+ import { findAuthorInstallation, stageInstalledDependencies } from './author-install.js';
18
+ import { stageEnvironmentDependencies } from './debug-environment-install.js';
16
19
  const exec = promisify(execFile);
17
20
  function requirePackedInfo(entry) {
18
21
  if (!entry?.shasum)
@@ -23,11 +26,33 @@ async function npm(args, options) {
23
26
  const invocation = await resolveNpmInvocation(args);
24
27
  return exec(invocation.file, invocation.args, options);
25
28
  }
29
+ async function packAuthorProject(root, directory, manifest, cacheArgs) {
30
+ const archive = process.env.ARCADIA_TEST_RELEASE_ARCHIVE;
31
+ if (archive && !/^[a-z0-9][a-z0-9._-]*\.tgz$/.test(archive))
32
+ throw new Error('Invalid release archive filename');
33
+ const result = await npm([
34
+ 'pack',
35
+ ...(archive ? [join(root, archive)] : []),
36
+ '--json',
37
+ '--ignore-scripts',
38
+ '--pack-destination',
39
+ directory,
40
+ ...cacheArgs,
41
+ ], { cwd: root });
42
+ const packed = requirePackedInfo(parseNpmPackOutput(String(result.stdout))[0]);
43
+ if (archive && packed.integrity !== process.env.ARCADIA_TEST_RELEASE_INTEGRITY)
44
+ throw new Error('Release archive integrity changed before testing');
45
+ const files = packed.files.map(file => file.path);
46
+ assert.ok(manifest.arcadia?.content && files.includes(manifest.arcadia.content));
47
+ if (!archive && manifest.arcadia.effects)
48
+ assert.ok(files.includes(manifest.arcadia.effects));
49
+ assert.ok(!files.some(file => /^(?:\.arcadia|\.github|node_modules|test|scripts|debug)\//.test(file)), 'the package must contain content, not a developer workspace');
50
+ return packed;
51
+ }
26
52
  /** Pack and install exactly what a consuming server receives. Approval is limited to this local demo. */
27
- export async function prepareBattleEnvironment(root = process.cwd(), { offline = !process.env.ARCADIA_TEST_RELEASE_ARCHIVE, cache, environmentId = 'default', sources = {}, lockRoot, } = {}) {
53
+ export async function prepareBattleEnvironment(root = process.cwd(), { offline, cache, environmentId = 'default', sources = {}, lockRoot, sourceRoot = lockRoot ?? root, } = {}) {
28
54
  root = resolve(root);
29
55
  const temporary = await mkdtemp(join(tmpdir(), 'arcadia-pack-template-'));
30
- const manifest = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'));
31
56
  const cacheArgs = cache ? ['--cache', resolve(cache)] : [];
32
57
  const battles = new Set();
33
58
  const sourceRevisions = {};
@@ -42,17 +67,16 @@ export async function prepareBattleEnvironment(root = process.cwd(), { offline =
42
67
  }
43
68
  try {
44
69
  workspace = await AuthorWorkspace.open(root, { watch: false });
45
- const selected = (await new DebugEnvironments(workspace).list()).find(entry => entry.id === environmentId);
70
+ const manifest = JSON.parse((await workspace.read('package.json')).text);
71
+ const standalone = workspace.projectKind === 'environment';
72
+ const definitions = await new DebugEnvironments(workspace).list();
73
+ const selected = standalone && environmentId === 'default' ? definitions[0] : definitions.find(entry => entry.id === environmentId);
46
74
  if (!selected)
47
75
  throw new Error(`ENVIRONMENT_MISSING: ${environmentId}`);
76
+ environmentId = selected.id;
48
77
  const { version: _version, ...selectedDocument } = selected;
49
- const environmentDocument = environmentId === 'default'
50
- ? {
51
- ...selectedDocument,
52
- schemaVersion: 2,
53
- rules: { schemaVersion: 1 },
54
- requires: {},
55
- }
78
+ const environmentDocument = selected.id === 'default'
79
+ ? { ...selectedDocument, schemaVersion: 2, rules: { schemaVersion: 1 }, requires: {} }
56
80
  : normalizeEnvironmentDocument(selectedDocument);
57
81
  assertEnvironmentRequirements(environmentDocument.requires);
58
82
  validateEnvironmentRuleDeclaration(environmentDocument.rules);
@@ -67,28 +91,11 @@ export async function prepareBattleEnvironment(root = process.cwd(), { offline =
67
91
  throw error;
68
92
  }
69
93
  }
70
- const archive = process.env.ARCADIA_TEST_RELEASE_ARCHIVE;
71
- if (archive && !/^[a-z0-9][a-z0-9._-]*\.tgz$/.test(archive))
72
- throw new Error('Invalid release archive filename');
73
- const result = await npm([
74
- 'pack',
75
- ...(archive ? [join(root, archive)] : []),
76
- '--json',
77
- '--ignore-scripts',
78
- '--pack-destination',
79
- temporary,
80
- ...cacheArgs,
81
- ], {
82
- cwd: root,
83
- });
84
- const packed = requirePackedInfo(parseNpmPackOutput(String(result.stdout))[0]);
85
- if (archive && packed.integrity !== process.env.ARCADIA_TEST_RELEASE_INTEGRITY)
86
- throw new Error('Release archive integrity changed before testing');
87
- const files = packed.files.map(file => file.path);
88
- assert.ok(files.includes(manifest.arcadia.content));
89
- if (!archive && manifest.arcadia.effects)
90
- assert.ok(files.includes(manifest.arcadia.effects));
91
- assert.ok(!files.some(file => /^(?:\.arcadia|\.github|node_modules|test|scripts|debug)\//.test(file)), 'the package must contain content, not a developer workspace');
94
+ const durable = await findAuthorInstallation(sourceRoot, manifest.dependencies, root);
95
+ if (durable)
96
+ cacheArgs.splice(0, cacheArgs.length, '--cache', join(dirname(durable.directory), 'npm-cache'));
97
+ const packed = standalone ? undefined : await packAuthorProject(root, temporary, manifest, cacheArgs);
98
+ const files = packed?.files.map(file => file.path) ?? [];
92
99
  const installation = join(temporary, 'server-project');
93
100
  await mkdir(join(installation, 'candidates'), { recursive: true });
94
101
  const dependencies = { ...selected.packages };
@@ -99,7 +106,42 @@ export async function prepareBattleEnvironment(root = process.cwd(), { offline =
99
106
  await cp(join(directory, packedInfo.filename), join(installation, filename));
100
107
  dependencies[metadata.name] = `file:${filename}`;
101
108
  }
102
- await addCandidate(temporary, manifest, packed);
109
+ if (packed) {
110
+ if (!manifest.name)
111
+ throw new Error('ENVIRONMENT_PACKAGE_NAME_MISSING');
112
+ await addCandidate(temporary, { name: manifest.name }, packed);
113
+ }
114
+ let candidateOverrides;
115
+ let installLock = oldLock?.text;
116
+ let installed;
117
+ if (standalone && !selected.sources.length) {
118
+ installed = durable?.directory;
119
+ }
120
+ if (standalone && !installed && !durable) {
121
+ const sourceLock = await workspace.read('package-lock.json').catch(error => {
122
+ if (errorCode(error) !== 'ENOENT')
123
+ throw error;
124
+ return undefined;
125
+ });
126
+ installLock = sourceLock?.text ?? installLock;
127
+ const staged = await stageEnvironmentDependencies({
128
+ materialRoot: root,
129
+ sourceRoot,
130
+ installation,
131
+ dependencies,
132
+ hasSources: selected.sources.length > 0,
133
+ lockText: installLock,
134
+ sourceLocked: !!sourceLock,
135
+ });
136
+ installed = staged.installed;
137
+ installLock = staged.lockText;
138
+ }
139
+ if (!installed && durable) {
140
+ const staged = await stageInstalledDependencies(durable, manifest.dependencies, installation, dependencies, selected.sources, installLock);
141
+ installLock = staged.lock;
142
+ if (!standalone && manifest.name)
143
+ candidateOverrides = { [manifest.name]: staged.localOverrides };
144
+ }
103
145
  for (const name of selected.sources) {
104
146
  const source = sources[name];
105
147
  if (typeof source !== 'string')
@@ -123,7 +165,9 @@ export async function prepareBattleEnvironment(root = process.cwd(), { offline =
123
165
  if (metadata.name !== name)
124
166
  throw new Error(`ENVIRONMENT_SOURCE_IDENTITY: ${name}`);
125
167
  await exec(process.execPath, [siblingModulePath('cli'), 'build'], { cwd: captured });
126
- const info = requirePackedInfo(parseNpmPackOutput(String((await npm(['pack', '--json', '--ignore-scripts', ...cacheArgs], { cwd: captured })).stdout))[0]);
168
+ const info = requirePackedInfo(standalone
169
+ ? await packBuiltProject(captured, { cache: cacheArgs[1] })
170
+ : parseNpmPackOutput(String((await npm(['pack', '--json', '--ignore-scripts', ...cacheArgs], { cwd: captured })).stdout))[0]);
127
171
  if (info.files.some(file => /^(?:debug|test|scripts|node_modules|\.arcadia|\.github)\//.test(file.path)))
128
172
  throw new Error('ENVIRONMENT_PACKAGE_FILES');
129
173
  await addCandidate(captured, metadata, info);
@@ -132,32 +176,37 @@ export async function prepareBattleEnvironment(root = process.cwd(), { offline =
132
176
  await sourceWorkspace.close();
133
177
  }
134
178
  }
135
- if (oldLock)
136
- await writeFile(join(installation, 'package-lock.json'), oldLock.text);
137
- await writeFile(join(installation, 'package.json'), JSON.stringify({
138
- name: 'arcadia-template-demo-server',
139
- version: '1.0.0',
140
- private: true,
141
- dependencies,
142
- }));
143
- await npm([
144
- 'install',
145
- ...(offline ? ['--offline'] : []),
146
- '--ignore-scripts',
147
- '--omit=dev',
148
- '--no-audit',
149
- '--no-fund',
150
- ...cacheArgs,
151
- ], { cwd: installation });
152
- environment = await prepareNpmProject(installation, emptyNpmContentHost, {
179
+ if (!installed) {
180
+ if (installLock)
181
+ await writeFile(join(installation, 'package-lock.json'), installLock);
182
+ await writeFile(join(installation, 'package.json'), JSON.stringify({
183
+ name: 'arcadia-template-demo-server',
184
+ version: '1.0.0',
185
+ private: true,
186
+ dependencies,
187
+ ...(candidateOverrides && { overrides: candidateOverrides }),
188
+ }));
189
+ await npm([
190
+ 'install',
191
+ ...((offline ?? (!standalone && !process.env.ARCADIA_TEST_RELEASE_ARCHIVE)) ? ['--offline'] : []),
192
+ '--ignore-scripts',
193
+ '--omit=dev',
194
+ '--no-audit',
195
+ '--no-fund',
196
+ ...cacheArgs,
197
+ ], { cwd: installation });
198
+ await mkdir(join(installation, 'node_modules'), { recursive: true });
199
+ installed = installation;
200
+ }
201
+ environment = await prepareNpmProject(installed, emptyNpmContentHost, {
153
202
  policy: { profile: 'local-development' },
154
- }, archive ? { effectPreparation: 'prebuilt-only' } : {});
155
- if (environmentId === 'default')
203
+ }, process.env.ARCADIA_TEST_RELEASE_ARCHIVE || standalone ? { effectPreparation: 'prebuilt-only' } : {});
204
+ if (!standalone && environmentId === 'default')
156
205
  environmentDocument.rules = defaultRuleDeclaration(environment.sandbox.data.ruleSets);
157
206
  const { rules: effectiveRules } = prepareRulesForContent(environmentDocument.rules, environment.sandbox.data);
158
207
  let environmentLock;
159
208
  if (lockFile) {
160
- const text = await readFile(join(installation, 'package-lock.json'), 'utf8');
209
+ const text = await readFile(join(installed, 'package-lock.json'), 'utf8');
161
210
  if (lockRoot) {
162
211
  lockWorkspace = await AuthorWorkspace.open(resolve(lockRoot), { watch: false });
163
212
  const saved = await lockWorkspace.write({ file: lockFile, expectedVersion: oldLock?.version ?? null, text });
@@ -171,11 +220,11 @@ export async function prepareBattleEnvironment(root = process.cwd(), { offline =
171
220
  return playersFromTeams(teamLibrary, ids);
172
221
  }
173
222
  const candidate = {
223
+ kind: standalone ? 'environment' : 'pack',
224
+ members: environment.installation.members.map(({ name, version }) => ({ name, version })),
174
225
  packageName: manifest.name,
175
226
  version: manifest.version,
176
- integrity: packed.integrity ?? '',
177
- shasum: packed.shasum,
178
- sdkApi: manifest.arcadia.sdkApi,
227
+ ...(packed && { integrity: packed.integrity ?? '', shasum: packed.shasum, sdkApi: manifest.arcadia?.sdkApi }),
179
228
  build: environment.build,
180
229
  environmentRevision: await gameplayRevision({
181
230
  kind: 'native-v4',
package/dist/init.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function initCommand(args: string[]): Promise<void>;
package/dist/init.js ADDED
@@ -0,0 +1,125 @@
1
+ import { constants } from 'node:fs';
2
+ import { copyFile, lstat, mkdir, readdir, rename, rm, rmdir, writeFile } from 'node:fs/promises';
3
+ import { createRequire } from 'node:module';
4
+ import { basename, dirname, join, resolve } from 'node:path';
5
+ import YAML from 'yaml';
6
+ import { connectDevelopmentSdk, copyAuthorSkill, createSourceProject } from './project.js';
7
+ import { errorCode } from './types.js';
8
+ const require = createRequire(import.meta.url);
9
+ const usage = 'Usage: arcadia-content init <pack|environment> <directory> [--id <id>]';
10
+ const basePackage = '@arcadia-eternity/data-pack-base';
11
+ async function createEnvironment(directory, id) {
12
+ const sdkVersion = require('../package.json').version;
13
+ let baseVersion = '*';
14
+ try {
15
+ baseVersion = require(basePackage + '/package.json').version;
16
+ }
17
+ catch (error) {
18
+ if (errorCode(error) !== 'MODULE_NOT_FOUND')
19
+ throw error;
20
+ }
21
+ const manifest = {
22
+ name: '@arcadia-local/' + id,
23
+ version: '0.1.0',
24
+ private: true,
25
+ type: 'module',
26
+ files: ['debug/teams', 'candidates'],
27
+ scripts: {
28
+ check: 'arcadia-content check',
29
+ demo: 'arcadia-content demo',
30
+ preview: 'arcadia-content preview',
31
+ pack: 'arcadia-content pack',
32
+ },
33
+ engines: { arcadia: '^' + sdkVersion },
34
+ devDependencies: { '@arcadia-eternity/content-sdk': sdkVersion },
35
+ dependencies: { [basePackage]: baseVersion },
36
+ arcadiaEnvironment: { schemaVersion: 2, id, name: id, sources: [], rules: { schemaVersion: 1 }, requires: {} },
37
+ };
38
+ const teams = join(directory, 'debug', 'teams');
39
+ await mkdir(teams, { recursive: true });
40
+ await writeFile(join(directory, 'package.json'), JSON.stringify(manifest, null, 2) + '\n');
41
+ await writeFile(join(directory, '.gitignore'), 'node_modules/\n.arcadia/\n/*.tgz\n');
42
+ for (const [name, species, skill] of [
43
+ ['Blue', 'pet_dilan', 'skill_paida'],
44
+ ['Orange', 'pet_xiuxiu', 'skill_lizhua'],
45
+ ]) {
46
+ const id = name.toLowerCase();
47
+ const stats = (value) => ({ hp: value, atk: value, def: value, spa: value, spd: value, spe: value });
48
+ const pet = { name: species, species, level: 100, nature: 'Hardy', skills: [skill], evs: stats(0), ivs: stats(31) };
49
+ await writeFile(join(teams, id + '.yaml'), YAML.stringify({ schemaVersion: 1, id, name, team: [pet] }));
50
+ }
51
+ await copyAuthorSkill(directory);
52
+ await connectDevelopmentSdk(directory);
53
+ }
54
+ export async function initCommand(args) {
55
+ if (args.includes('--help') || args.includes('-h')) {
56
+ console.log(usage);
57
+ return;
58
+ }
59
+ const [kind, path, ...flags] = args;
60
+ if ((kind !== 'pack' && kind !== 'environment') ||
61
+ !path ||
62
+ path.startsWith('-') ||
63
+ (flags.length > 0 && (flags.length !== 2 || flags[0] !== '--id')))
64
+ throw new Error(usage);
65
+ const directory = resolve(path);
66
+ const id = flags[1] ?? basename(directory);
67
+ if (!/^[a-z0-9][a-z0-9-]{0,79}$/.test(id) || (kind === 'environment' && id === 'default'))
68
+ throw new Error('Invalid project ID. Supply --id with a lowercase alphanumeric or hyphenated name; default is reserved for environments.');
69
+ await mkdir(dirname(directory), { recursive: true });
70
+ let created = true;
71
+ try {
72
+ await mkdir(directory);
73
+ }
74
+ catch (error) {
75
+ if (errorCode(error) !== 'EEXIST')
76
+ throw error;
77
+ created = false;
78
+ if (!(await lstat(directory)).isDirectory() || (await readdir(directory)).length)
79
+ throw new Error('Project destination must be a new or empty directory: ' + directory, { cause: error });
80
+ }
81
+ // Reserve the empty destination while generating the template. Keep the directory
82
+ // itself intact so "init ." also works in the caller's current working directory.
83
+ const staging = join(directory, '.arcadia-init');
84
+ await mkdir(staging);
85
+ const project = join(staging, 'project');
86
+ const installed = [];
87
+ try {
88
+ if ((await readdir(directory)).some(name => name !== '.arcadia-init'))
89
+ throw new Error('Project destination is no longer empty: ' + directory);
90
+ if (kind === 'pack')
91
+ await createSourceProject(project, id);
92
+ else
93
+ await createEnvironment(project, id);
94
+ const entries = await readdir(project, { withFileTypes: true });
95
+ // package.json is the completion marker for tools opening the new project.
96
+ entries.sort((a, b) => Number(a.name === 'package.json') - Number(b.name === 'package.json'));
97
+ for (const entry of entries) {
98
+ const source = join(project, entry.name);
99
+ const target = join(directory, entry.name);
100
+ if (entry.isDirectory()) {
101
+ await mkdir(target);
102
+ installed.push(target);
103
+ // Move children into the directory we just reserved. Re-copying SDK
104
+ // junctions on Windows would require permission to create symlinks.
105
+ for (const child of await readdir(source))
106
+ await rename(join(source, child), join(target, child));
107
+ }
108
+ else {
109
+ await copyFile(source, target, constants.COPYFILE_EXCL);
110
+ installed.push(target);
111
+ }
112
+ }
113
+ }
114
+ catch (error) {
115
+ for (const target of installed.reverse())
116
+ await rm(target, { recursive: true, force: true });
117
+ throw error;
118
+ }
119
+ finally {
120
+ await rm(staging, { recursive: true, force: true });
121
+ if (created && !(await readdir(directory)).length)
122
+ await rmdir(directory);
123
+ }
124
+ console.log(JSON.stringify({ kind, directory, id }));
125
+ }
package/dist/jobs.d.ts CHANGED
@@ -32,6 +32,7 @@ export interface Job {
32
32
  sourceRevision: string;
33
33
  contentRevision: string;
34
34
  environmentId: string;
35
+ seed?: string;
35
36
  preparationRevision: string;
36
37
  state: string;
37
38
  phase: string;
@@ -59,10 +60,11 @@ export declare class AuthorJobs {
59
60
  get hasLivePreviews(): boolean;
60
61
  initialize(): Promise<void>;
61
62
  refresh(): Promise<void>;
62
- start({ kind, sourceRevision, environmentId, }: {
63
+ start({ kind, sourceRevision, environmentId, seed, }: {
63
64
  kind: string;
64
65
  sourceRevision?: string;
65
66
  environmentId?: string;
67
+ seed?: string;
66
68
  }): Promise<Job>;
67
69
  get(jobId: string): Job;
68
70
  list(): Job[];