@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.
- package/README.md +2 -2
- package/dist/author-api.d.ts +12 -2
- package/dist/author-api.js +11 -2
- package/dist/author-git.d.ts +63 -0
- package/dist/author-git.js +324 -0
- package/dist/author-reference.d.ts +15 -1
- package/dist/author-reference.js +20 -1
- package/dist/cli.js +5 -4
- package/dist/content-query.d.ts +15 -1
- package/dist/content-query.js +53 -11
- package/dist/content-workspace.d.ts +435 -6
- package/dist/content-workspace.js +238 -77
- package/dist/debug-environments.d.ts +393 -33
- package/dist/debug-environments.js +10 -50
- package/dist/demo.js +1 -1
- package/dist/effect-declarations.d.ts +14 -0
- package/dist/effect-declarations.js +103 -0
- package/dist/environment-host-base.d.ts +175 -0
- package/dist/environment-host-base.js +86 -0
- package/dist/environment-member-transfer.d.ts +5 -0
- package/dist/environment-member-transfer.js +95 -0
- package/dist/environment-rules.d.ts +728 -3
- package/dist/environment-rules.js +158 -74
- package/dist/environment-sharing.d.ts +51 -0
- package/dist/environment-sharing.js +321 -0
- package/dist/environment.d.ts +2 -0
- package/dist/environment.js +32 -9
- package/dist/jobs.d.ts +5 -0
- package/dist/jobs.js +59 -10
- package/dist/learnsets.d.ts +47 -0
- package/dist/learnsets.js +124 -0
- package/dist/lib/content.d.ts +1 -1
- package/dist/lib/content.js +26 -2
- package/dist/lib/presentation.js +5 -11
- package/dist/managed-projects.d.ts +6 -0
- package/dist/managed-projects.js +137 -45
- package/dist/managed-sources.d.ts +17 -0
- package/dist/managed-sources.js +28 -10
- package/dist/mcp-contracts.d.ts +405 -12
- package/dist/mcp-contracts.js +3 -1
- package/dist/mcp.js +23 -1
- package/dist/pack-project.d.ts +2 -1
- package/dist/pack-project.js +40 -5
- package/dist/prepared-document.d.ts +476 -0
- package/dist/prepared-document.js +47 -0
- package/dist/preview.js +5 -5
- package/dist/project.d.ts +3 -1
- package/dist/project.js +47 -4
- package/dist/rule-composition.d.ts +290 -0
- package/dist/rule-composition.js +267 -0
- package/dist/template/.github/scripts/release-payload.mjs +91 -0
- package/dist/template/.github/scripts/release-test-npm.mjs +27 -0
- package/dist/template/.github/scripts/verify-release.mjs +138 -0
- package/dist/template/.github/workflows/release-pack.yml +77 -0
- package/dist/template/README.md +15 -2
- package/dist/template/gitignore-template +7 -0
- package/dist/template/npm-lock-template.json +2319 -0
- package/dist/template/package.json +4 -2
- package/dist/template/skills/arcadia-content-authoring/references/tool-workflows.md +1 -1
- package/dist/template/skills/arcadia-content-git/SKILL.md +14 -0
- package/dist/template/skills/arcadia-content-release/SKILL.md +29 -0
- package/dist/template/test/pack.test.mjs +24 -5
- package/dist/testing.d.ts +1 -0
- package/dist/testing.js +26 -7
- package/dist/workspace-cli.js +2 -2
- package/dist/workspace-materials.d.ts +4 -1
- package/dist/workspace-materials.js +8 -2
- package/dist/workspace.d.ts +11 -0
- package/dist/workspace.js +191 -31
- package/package.json +16 -4
- package/release-payload.mjs +91 -0
- package/release-test-npm.mjs +27 -0
|
@@ -1,94 +1,178 @@
|
|
|
1
|
+
export { RuleCompositionError, resolveEnvironmentMechanics } from '@arcadia-eternity/const';
|
|
2
|
+
import { readSkillParameterCatalog, resolveSkillParameters, requireElementChart } from '@arcadia-eternity/const';
|
|
3
|
+
import { composeRuleSets } from './rule-composition.js';
|
|
4
|
+
import { allowsEnhancementRecord, splitRuleDeclaration, resolveEnvironmentMechanics, resolveEnvironmentTeam, validateConstraintReferences, EnvironmentRulesSchema, parseRuleData, EnvironmentRequirementsSchema, teamConstraintIssues, } from '@arcadia-eternity/const';
|
|
5
|
+
import { assertLearningChoices, validateLearningReferences } from './learnsets.js';
|
|
6
|
+
export { resolveLearnset, learningIssues, isEligible, assertNatureChoice, validateLearningReferences, assertLearningChoices, } from './learnsets.js';
|
|
1
7
|
import { isRecord } from './types.js';
|
|
2
8
|
function fail(code) {
|
|
3
9
|
throw Object.assign(new Error(code), { code });
|
|
4
10
|
}
|
|
5
11
|
const record = (value) => isRecord(value);
|
|
6
|
-
const keysAllowed = (value, names) => Object.keys(value).every(name => names.includes(name));
|
|
7
12
|
const identifier = (value) => typeof value === 'string' && value.length > 0 && value.length <= 256 && !/\p{Cc}/u.test(value);
|
|
8
13
|
/** Validate the currently implemented rule vocabulary before admitting an environment. */
|
|
14
|
+
function validateRuleFields(input) {
|
|
15
|
+
return parseRuleData(EnvironmentRulesSchema, input);
|
|
16
|
+
}
|
|
17
|
+
function checkIVDefault(rules) {
|
|
18
|
+
const { max, defaultValue } = resolveEnvironmentMechanics(rules).individualValues;
|
|
19
|
+
if (defaultValue > max)
|
|
20
|
+
fail('ENVIRONMENT_IV_DEFAULT_EXCEEDS_MAX');
|
|
21
|
+
return rules;
|
|
22
|
+
}
|
|
9
23
|
export function validateEnvironmentRules(input) {
|
|
10
|
-
|
|
11
|
-
if (!record(rules) || !keysAllowed(rules, ['schemaVersion', 'tier', 'allow', 'deny', 'team']))
|
|
12
|
-
fail('ENVIRONMENT_RULES_INVALID');
|
|
13
|
-
if (rules.schemaVersion !== 1 || (rules.tier !== undefined && rules.tier !== 'standard'))
|
|
14
|
-
fail('ENVIRONMENT_RULES_UNSUPPORTED');
|
|
15
|
-
for (const group of [rules.allow, rules.deny]) {
|
|
16
|
-
if (group === undefined)
|
|
17
|
-
continue;
|
|
18
|
-
if (!record(group) || !keysAllowed(group, ['species', 'skills', 'marks']))
|
|
19
|
-
fail('ENVIRONMENT_RULES_INVALID');
|
|
20
|
-
for (const values of Object.values(group)) {
|
|
21
|
-
if (!Array.isArray(values) ||
|
|
22
|
-
values.length > 10000 ||
|
|
23
|
-
values.some(value => !identifier(value)) ||
|
|
24
|
-
new Set(values).size !== values.length)
|
|
25
|
-
fail('ENVIRONMENT_RULES_INVALID');
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
if (rules.team !== undefined &&
|
|
29
|
-
(!record(rules.team) || !keysAllowed(rules.team, ['minSize', 'maxSize', 'uniqueSpecies'])))
|
|
30
|
-
fail('ENVIRONMENT_RULES_INVALID');
|
|
31
|
-
const team = record(rules.team) ? rules.team : {};
|
|
32
|
-
const minSize = team.minSize === undefined ? 1 : team.minSize;
|
|
33
|
-
const maxSize = team.maxSize === undefined ? 6 : team.maxSize;
|
|
34
|
-
const uniqueSpecies = team.uniqueSpecies;
|
|
35
|
-
if (typeof minSize !== 'number' ||
|
|
36
|
-
typeof maxSize !== 'number' ||
|
|
37
|
-
!Number.isInteger(minSize) ||
|
|
38
|
-
!Number.isInteger(maxSize) ||
|
|
39
|
-
minSize < 1 ||
|
|
40
|
-
maxSize > 6 ||
|
|
41
|
-
minSize > maxSize ||
|
|
42
|
-
(uniqueSpecies !== undefined && typeof uniqueSpecies !== 'boolean'))
|
|
43
|
-
fail('ENVIRONMENT_RULES_INVALID');
|
|
44
|
-
return structuredClone(rules);
|
|
24
|
+
return checkIVDefault(validateRuleFields(input));
|
|
45
25
|
}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
26
|
+
const capabilityFields = {
|
|
27
|
+
'team.constraints.v1': (rules) => rules.constraints?.length,
|
|
28
|
+
'team.skill-slots.v1': (rules) => rules.mechanics?.skillSlots,
|
|
29
|
+
'training.individual-values.v1': (rules) => rules.mechanics?.individualValues || rules.mechanics?.individualValueDefault !== undefined,
|
|
30
|
+
'training.inheritance.v1': (rules) => rules.mechanics?.inheritance || rules.mechanics?.secondGenerationNatures || rules.learnsetAdjustments?.length,
|
|
31
|
+
'training.enhancement.v1': (rules) => rules.mechanics?.enhancement,
|
|
32
|
+
'battle.skill-parameters.v1': (rules) => rules.skillParameters,
|
|
33
|
+
'battle.type-chart.v1': (rules) => rules.matchups,
|
|
34
|
+
'battle.faint-switch.v1': (rules) => rules.mechanics?.allowFaintSwitch !== undefined,
|
|
35
|
+
};
|
|
36
|
+
export const environmentCapabilities = Object.freeze(['rules.composition.v1', ...Object.keys(capabilityFields)]);
|
|
37
|
+
const currentHost = { engine: '4', sdk: '2', capabilities: environmentCapabilities };
|
|
38
|
+
export function assertEnvironmentRequirements(input, host = currentHost) {
|
|
39
|
+
const parsed = EnvironmentRequirementsSchema.safeParse(input === undefined ? {} : input);
|
|
40
|
+
if (!parsed.success)
|
|
50
41
|
fail('ENVIRONMENT_REQUIREMENT_INVALID');
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
if (
|
|
54
|
-
fail('
|
|
55
|
-
|
|
56
|
-
if (
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
fail('ENVIRONMENT_CAPABILITY_UNSUPPORTED');
|
|
61
|
-
if (requires.engine !== undefined || requires.sdk !== undefined)
|
|
62
|
-
fail('ENVIRONMENT_REQUIREMENT_UNSUPPORTED');
|
|
42
|
+
const requires = parsed.data;
|
|
43
|
+
for (const name of ['engine', 'sdk'])
|
|
44
|
+
if (requires[name] !== undefined && requires[name] !== host[name])
|
|
45
|
+
fail('ENVIRONMENT_REQUIREMENT_UNSUPPORTED');
|
|
46
|
+
const missing = requires.capabilities?.filter(id => !host.capabilities.includes(id)) ?? [];
|
|
47
|
+
if (missing.length)
|
|
48
|
+
throw Object.assign(new Error('ENVIRONMENT_CAPABILITY_UNSUPPORTED: ' + missing.join(', ')), {
|
|
49
|
+
code: 'ENVIRONMENT_CAPABILITY_UNSUPPORTED',
|
|
50
|
+
});
|
|
63
51
|
}
|
|
64
52
|
/** Admission checks apply to normalized team definitions, before creating any battle. */
|
|
65
53
|
export function assertEnvironmentTeam(input, team) {
|
|
66
54
|
const rules = validateEnvironmentRules(input);
|
|
67
|
-
const { minSize
|
|
55
|
+
const { minSize, maxSize, uniqueSpecies } = resolveEnvironmentTeam(rules);
|
|
68
56
|
if (!Array.isArray(team) || team.length < minSize || team.length > maxSize)
|
|
69
57
|
fail('ENVIRONMENT_TEAM_REJECTED');
|
|
70
|
-
const
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
58
|
+
for (const pet of team)
|
|
59
|
+
assertEnvironmentMember(rules, pet);
|
|
60
|
+
if (teamConstraintIssues(rules.constraints, team, 'team').length)
|
|
61
|
+
fail('ENVIRONMENT_TEAM_REJECTED');
|
|
62
|
+
if (uniqueSpecies && new Set(team.map(pet => pet.species)).size !== team.length)
|
|
63
|
+
fail('ENVIRONMENT_TEAM_REJECTED');
|
|
64
|
+
}
|
|
65
|
+
export function assertPlayableTeam(rules, team, ...content) {
|
|
66
|
+
assertEnvironmentTeam(rules, team);
|
|
67
|
+
assertLearningChoices(rules, team, ...content);
|
|
68
|
+
}
|
|
69
|
+
/** Check one build against prepared rules independently of team size and composition. */
|
|
70
|
+
export function assertEnvironmentMember(rules, pet) {
|
|
71
|
+
const ivLimit = resolveEnvironmentMechanics(rules).individualValues.max;
|
|
72
|
+
if (!record(pet))
|
|
73
|
+
fail('ENVIRONMENT_TEAM_REJECTED');
|
|
74
|
+
const petRecord = pet;
|
|
75
|
+
if (!identifier(petRecord.species) ||
|
|
76
|
+
!Array.isArray(petRecord.skills) ||
|
|
77
|
+
petRecord.skills.some(skill => !identifier(skill)))
|
|
78
|
+
fail('ENVIRONMENT_TEAM_REJECTED');
|
|
79
|
+
if ([petRecord.ability, petRecord.emblem].some(mark => mark !== undefined && mark !== '' && !identifier(mark)))
|
|
80
|
+
fail('ENVIRONMENT_TEAM_REJECTED');
|
|
81
|
+
if (petRecord.enhancement !== undefined) {
|
|
82
|
+
if (!identifier(petRecord.enhancement) ||
|
|
83
|
+
!allowsEnhancementRecord(rules.mechanics?.enhancement, petRecord.species, petRecord.enhancement))
|
|
80
84
|
fail('ENVIRONMENT_TEAM_REJECTED');
|
|
81
|
-
const selected = {
|
|
82
|
-
species: [petRecord.species],
|
|
83
|
-
skills: petRecord.skills,
|
|
84
|
-
marks: [petRecord.ability, petRecord.emblem].filter(value => !!value),
|
|
85
|
-
};
|
|
86
|
-
for (const kind of ['species', 'skills', 'marks']) {
|
|
87
|
-
const allow = rules.allow?.[kind], deny = rules.deny?.[kind];
|
|
88
|
-
if (selected[kind].some(id => !identifier(id) || (allow !== undefined && !allow.includes(id)) || deny?.includes(id)))
|
|
89
|
-
fail('ENVIRONMENT_TEAM_REJECTED');
|
|
90
|
-
}
|
|
91
85
|
}
|
|
92
|
-
if (
|
|
86
|
+
if (petRecord.ivs !== undefined &&
|
|
87
|
+
(!record(petRecord.ivs) ||
|
|
88
|
+
Object.values(petRecord.ivs).some(value => typeof value !== 'number' || !Number.isInteger(value) || value < 0 || value > ivLimit)))
|
|
89
|
+
fail('ENVIRONMENT_TEAM_REJECTED');
|
|
90
|
+
if (teamConstraintIssues(rules.constraints, [
|
|
91
|
+
{
|
|
92
|
+
species: petRecord.species,
|
|
93
|
+
skills: petRecord.skills,
|
|
94
|
+
ability: petRecord.ability,
|
|
95
|
+
emblem: petRecord.emblem,
|
|
96
|
+
},
|
|
97
|
+
], 'pet').length)
|
|
93
98
|
fail('ENVIRONMENT_TEAM_REJECTED');
|
|
99
|
+
const selected = {
|
|
100
|
+
species: [petRecord.species],
|
|
101
|
+
skills: [
|
|
102
|
+
...petRecord.skills,
|
|
103
|
+
...(petRecord.inheritedSkill === undefined ? [] : [petRecord.inheritedSkill]),
|
|
104
|
+
],
|
|
105
|
+
marks: [petRecord.ability, petRecord.emblem].filter(value => !!value),
|
|
106
|
+
};
|
|
107
|
+
for (const kind of ['species', 'skills', 'marks']) {
|
|
108
|
+
const allow = rules.allow?.[kind], deny = rules.deny?.[kind];
|
|
109
|
+
if (selected[kind].some(id => !identifier(id) || (allow !== undefined && !allow.includes(id)) || deny?.includes(id)))
|
|
110
|
+
fail('ENVIRONMENT_TEAM_REJECTED');
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
/** Author declarations are expanded only against a captured installation. */
|
|
114
|
+
export function defaultRuleDeclaration(definitions = []) {
|
|
115
|
+
return definitions.some(row => isRecord(row) && row.id === 'base:classic')
|
|
116
|
+
? { schemaVersion: 2, include: ['base:classic'] }
|
|
117
|
+
: { schemaVersion: 1 };
|
|
118
|
+
}
|
|
119
|
+
export function prepareEnvironmentRules(input, definitions = [], host = currentHost) {
|
|
120
|
+
const declaration = input === undefined ? defaultRuleDeclaration(definitions) : input;
|
|
121
|
+
const prepared = composeRuleSets(declaration, definitions, validateRuleFields);
|
|
122
|
+
checkIVDefault(prepared.rules);
|
|
123
|
+
const requiredCapabilities = Object.entries(capabilityFields)
|
|
124
|
+
.filter(([, used]) => used(prepared.rules))
|
|
125
|
+
.map(([key]) => key);
|
|
126
|
+
if (isRecord(declaration) && ['include', 'constraintEdits', 'collections'].some(field => field in declaration))
|
|
127
|
+
requiredCapabilities.unshift('rules.composition.v1');
|
|
128
|
+
assertEnvironmentRequirements({ capabilities: requiredCapabilities }, host);
|
|
129
|
+
return { ...prepared, requiredCapabilities };
|
|
130
|
+
}
|
|
131
|
+
export function validateEnvironmentRuleDeclaration(input) {
|
|
132
|
+
return splitRuleDeclaration(input);
|
|
133
|
+
}
|
|
134
|
+
/** Validate selectors once against the catalog held by this preparation. */
|
|
135
|
+
export function assertRuleContentReferences(rules, catalog, fields = []) {
|
|
136
|
+
const known = {
|
|
137
|
+
species: (id) => catalog.species.has(id),
|
|
138
|
+
skill: (id) => catalog.skill.has(id),
|
|
139
|
+
mark: (id) => catalog.mark.has(id),
|
|
140
|
+
};
|
|
141
|
+
validateConstraintReferences(rules.constraints, known);
|
|
142
|
+
validateLearningReferences(rules, known.species, known.skill, id => catalog.stage.has(id));
|
|
143
|
+
function check(path, kind, ids) {
|
|
144
|
+
for (const id of ids)
|
|
145
|
+
if (!known[kind](id))
|
|
146
|
+
throw Object.assign(new Error(`ENVIRONMENT_REFERENCE_MISSING: ${path} / ${kind} / ${id}`), {
|
|
147
|
+
code: 'ENVIRONMENT_REFERENCE_MISSING',
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
for (const field of fields)
|
|
151
|
+
if (field.path[0] === 'collections') {
|
|
152
|
+
const collection = field.value;
|
|
153
|
+
check(collection.id, collection.kind, collection.ids);
|
|
154
|
+
}
|
|
155
|
+
if (rules.schemaVersion === 2)
|
|
156
|
+
for (const side of ['allow', 'deny']) {
|
|
157
|
+
const selection = rules[side];
|
|
158
|
+
if (selection?.species)
|
|
159
|
+
check(side, 'species', selection.species);
|
|
160
|
+
if (selection?.skills)
|
|
161
|
+
check(side, 'skill', selection.skills);
|
|
162
|
+
if (selection?.marks)
|
|
163
|
+
check(side, 'mark', selection.marks);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
/** Resolve declarations against the exact package data used to build this runtime. */
|
|
167
|
+
export function prepareRulesForContent(declaration, data) {
|
|
168
|
+
const composition = prepareEnvironmentRules(declaration, data.ruleSets);
|
|
169
|
+
const { rules, fields } = composition;
|
|
170
|
+
resolveSkillParameters(readSkillParameterCatalog(data), rules.skillParameters);
|
|
171
|
+
requireElementChart(data, rules.matchups);
|
|
172
|
+
assertRuleContentReferences(rules, indexRuleContent(data), fields);
|
|
173
|
+
return { rules, fields, ruleSets: composition.ruleSets, requiredCapabilities: composition.requiredCapabilities };
|
|
174
|
+
}
|
|
175
|
+
export function indexRuleContent(data) {
|
|
176
|
+
const ids = (rows = []) => new Set(rows.flatMap(row => (isRecord(row) && typeof row.id === 'string' ? [row.id] : [])));
|
|
177
|
+
return { species: ids(data.species), skill: ids(data.skills), mark: ids(data.marks), stage: ids(data.enhancements) };
|
|
94
178
|
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
type Material = {
|
|
2
|
+
path: string;
|
|
3
|
+
bytes: Buffer;
|
|
4
|
+
};
|
|
5
|
+
export type ArchiveReference = {
|
|
6
|
+
location: string;
|
|
7
|
+
paths: string[];
|
|
8
|
+
digest: string;
|
|
9
|
+
bundledBase?: true;
|
|
10
|
+
external?: {
|
|
11
|
+
name: string;
|
|
12
|
+
version: string;
|
|
13
|
+
integrity: string;
|
|
14
|
+
manual: boolean;
|
|
15
|
+
};
|
|
16
|
+
};
|
|
17
|
+
type Limits = {
|
|
18
|
+
maxBytes?: number;
|
|
19
|
+
maxFiles?: number;
|
|
20
|
+
signal?: AbortSignal;
|
|
21
|
+
};
|
|
22
|
+
export declare function packageLocation(path: string): string;
|
|
23
|
+
export declare function verifyArchive(bytes: Buffer, integrity: string): void;
|
|
24
|
+
export declare function readArchiveFiles(bytes: Buffer, limits: Limits): Promise<Map<string, Buffer<ArrayBufferLike>>>;
|
|
25
|
+
export declare function exportDependencies(materials: Material[]): {
|
|
26
|
+
name: string;
|
|
27
|
+
version: string;
|
|
28
|
+
integrity: string;
|
|
29
|
+
manual: boolean;
|
|
30
|
+
location: string;
|
|
31
|
+
bytes: number;
|
|
32
|
+
}[];
|
|
33
|
+
export declare function compactMaterials(materials: Material[], limits: Limits, included?: string[]): Promise<{
|
|
34
|
+
archives: ArchiveReference[];
|
|
35
|
+
materials: Material[];
|
|
36
|
+
}>;
|
|
37
|
+
type ImportOptions = Limits & {
|
|
38
|
+
offline: boolean;
|
|
39
|
+
cache: string;
|
|
40
|
+
environments?: string;
|
|
41
|
+
missing?: Set<string>;
|
|
42
|
+
supplied?: Record<string, string>;
|
|
43
|
+
};
|
|
44
|
+
export declare function expandSharedMaterials(files: {
|
|
45
|
+
path: string;
|
|
46
|
+
data: string;
|
|
47
|
+
}[], references: ArchiveReference[], limits: ImportOptions): Promise<(Material | {
|
|
48
|
+
path: string;
|
|
49
|
+
data: string;
|
|
50
|
+
})[]>;
|
|
51
|
+
export {};
|
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
import { sha256Bytes } from '@arcadia-eternity/const';
|
|
2
|
+
import { sha256 } from '@noble/hashes/sha2.js';
|
|
3
|
+
import { bytesToHex } from '@noble/hashes/utils.js';
|
|
4
|
+
import { lstat, readdir } from 'node:fs/promises';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { Readable } from 'node:stream';
|
|
7
|
+
import { matchesArchiveIntegrity, tarFiles } from './managed-sources.js';
|
|
8
|
+
import { isBaseMaterial } from './environment-host-base.js';
|
|
9
|
+
import { contentError, materialFiles, readJson } from './workspace-materials.js';
|
|
10
|
+
import { errorCode, isRecord } from './types.js';
|
|
11
|
+
const candidate = /^file:candidates\/[a-zA-Z0-9_.-]+\.tgz$/;
|
|
12
|
+
const publicTarball = /^https:\/\/registry\.npmjs\.org\/(?:@[a-z0-9_.-]+\/)?[a-z0-9][a-z0-9_.-]*\/-\/[a-zA-Z0-9_.+-]+\.tgz$/;
|
|
13
|
+
const locationPattern = /^(?:node_modules\/(?:@[a-z0-9_.-]+\/)?[a-z0-9][a-z0-9_.-]*\/)*node_modules\/(?:@[a-z0-9_.-]+\/)?[a-z0-9][a-z0-9_.-]*$/;
|
|
14
|
+
function sourceFor(lock, location) {
|
|
15
|
+
if (!locationPattern.test(location) || !isRecord(lock) || !isRecord(lock.packages))
|
|
16
|
+
return;
|
|
17
|
+
const pkg = lock.packages[location];
|
|
18
|
+
if (!isRecord(pkg) ||
|
|
19
|
+
typeof pkg.version !== 'string' ||
|
|
20
|
+
typeof pkg.resolved !== 'string' ||
|
|
21
|
+
typeof pkg.integrity !== 'string' ||
|
|
22
|
+
!/^sha(?:256|384|512)-[A-Za-z0-9+/]+={0,2}$/.test(pkg.integrity))
|
|
23
|
+
return;
|
|
24
|
+
if (candidate.test(pkg.resolved) || /^https:\/\//.test(pkg.resolved))
|
|
25
|
+
return { resolved: pkg.resolved, integrity: pkg.integrity, version: pkg.version };
|
|
26
|
+
}
|
|
27
|
+
export function packageLocation(path) {
|
|
28
|
+
const start = path.lastIndexOf('node_modules/');
|
|
29
|
+
if (start < 0 || (start && path[start - 1] !== '/'))
|
|
30
|
+
return '';
|
|
31
|
+
const parts = path.slice(start + 13).split('/');
|
|
32
|
+
return path.slice(0, start + 13) + parts.slice(0, parts[0].startsWith('@') ? 2 : 1).join('/');
|
|
33
|
+
}
|
|
34
|
+
function fileDigest(files) {
|
|
35
|
+
const digest = sha256.create();
|
|
36
|
+
for (const file of files)
|
|
37
|
+
digest.update(Buffer.from(file.path + '\0')).update(sha256Bytes(file.bytes));
|
|
38
|
+
return bytesToHex(digest.digest());
|
|
39
|
+
}
|
|
40
|
+
export function verifyArchive(bytes, integrity) {
|
|
41
|
+
if (!matchesArchiveIntegrity(bytes, integrity))
|
|
42
|
+
throw contentError('SOURCE_INTEGRITY_MISMATCH', '内容包归档与锁定摘要不符');
|
|
43
|
+
}
|
|
44
|
+
export async function readArchiveFiles(bytes, limits) {
|
|
45
|
+
const files = await tarFiles(Readable.from([bytes]), {
|
|
46
|
+
signal: limits.signal ?? AbortSignal.timeout(120000),
|
|
47
|
+
timeoutMs: 120000,
|
|
48
|
+
maxFiles: limits.maxFiles ?? 50000,
|
|
49
|
+
maxBytes: limits.maxBytes ?? 256 * 1024 * 1024,
|
|
50
|
+
});
|
|
51
|
+
// npm strips the first directory component, including in older non-package/ tarballs.
|
|
52
|
+
return new Map(files.map(file => [file.name.slice(file.name.indexOf('/') + 1), file.bytes]));
|
|
53
|
+
}
|
|
54
|
+
function externalDependency(source, location) {
|
|
55
|
+
if (!source.resolved.startsWith('https:'))
|
|
56
|
+
return;
|
|
57
|
+
return {
|
|
58
|
+
name: location.slice(location.lastIndexOf('node_modules/') + 13),
|
|
59
|
+
version: source.version,
|
|
60
|
+
integrity: source.integrity,
|
|
61
|
+
manual: !publicTarball.test(source.resolved),
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
export function exportDependencies(materials) {
|
|
65
|
+
const lock = JSON.parse(materials.find(file => file.path === 'package-lock.json').bytes.toString());
|
|
66
|
+
return [...Map.groupBy(materials, file => packageLocation(file.path))].flatMap(([location, files]) => {
|
|
67
|
+
const source = sourceFor(lock, location);
|
|
68
|
+
const dependency = source && externalDependency(source, location);
|
|
69
|
+
if (!dependency)
|
|
70
|
+
return [];
|
|
71
|
+
const bytes = files.reduce((total, file) => total + Math.ceil(file.bytes.length / 3) * 4, 0);
|
|
72
|
+
return [{ ...dependency, location, bytes }];
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
export async function compactMaterials(materials, limits, included = []) {
|
|
76
|
+
const byPath = new Map(materials.map(file => [file.path, file.bytes]));
|
|
77
|
+
const lock = JSON.parse(byPath.get('package-lock.json').toString());
|
|
78
|
+
const groups = Map.groupBy(materials, file => packageLocation(file.path));
|
|
79
|
+
const archives = [];
|
|
80
|
+
const omitted = new Set();
|
|
81
|
+
const selected = new Set(included);
|
|
82
|
+
for (const [location, files] of groups) {
|
|
83
|
+
const source = sourceFor(lock, location);
|
|
84
|
+
const paths = files.map(file => file.path.slice(location.length + 1));
|
|
85
|
+
if (!source) {
|
|
86
|
+
const locked = lock.packages?.[location];
|
|
87
|
+
if (typeof locked?.resolved === 'string' && /^https?:/.test(locked.resolved))
|
|
88
|
+
throw contentError('MATERIAL_INTEGRITY_REQUIRED', `无法核对 ${location} 的归档摘要,请重新准备环境后再试。`);
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
const external = externalDependency(source, location);
|
|
92
|
+
if (external && selected.delete(location))
|
|
93
|
+
continue;
|
|
94
|
+
if (source.resolved.startsWith('file:')) {
|
|
95
|
+
const bytes = byPath.get(source.resolved.slice(5));
|
|
96
|
+
if (!bytes)
|
|
97
|
+
throw contentError('ENVIRONMENT_SOURCE_MISSING');
|
|
98
|
+
verifyArchive(bytes, source.integrity);
|
|
99
|
+
const tar = await readArchiveFiles(bytes, limits);
|
|
100
|
+
if (!files.every((file, i) => tar.get(paths[i])?.equals(file.bytes)))
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
archives.push({
|
|
104
|
+
location,
|
|
105
|
+
paths,
|
|
106
|
+
digest: fileDigest(files),
|
|
107
|
+
...(external && { external }),
|
|
108
|
+
});
|
|
109
|
+
omitted.add(location);
|
|
110
|
+
}
|
|
111
|
+
if (selected.size)
|
|
112
|
+
throw contentError('ENVIRONMENT_EXPORT_INVALID');
|
|
113
|
+
return {
|
|
114
|
+
archives,
|
|
115
|
+
materials: materials.filter(file => !omitted.has(packageLocation(file.path))),
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
// A full offline import may already hold the package even after npm's download cache was cleared.
|
|
119
|
+
async function installedArchives(environments) {
|
|
120
|
+
const index = new Map();
|
|
121
|
+
for (const entry of await readdir(environments, { withFileTypes: true })) {
|
|
122
|
+
if (!entry.isDirectory())
|
|
123
|
+
continue;
|
|
124
|
+
const directory = join(environments, entry.name);
|
|
125
|
+
const lock = await readJson(join(directory, 'package-lock.json'), 16 * 1024 * 1024).catch(() => undefined);
|
|
126
|
+
if (!isRecord(lock?.packages))
|
|
127
|
+
continue;
|
|
128
|
+
for (const location of Object.keys(lock.packages)) {
|
|
129
|
+
const source = sourceFor(lock, location);
|
|
130
|
+
if (!source)
|
|
131
|
+
continue;
|
|
132
|
+
const matches = index.get(source.integrity) ?? [];
|
|
133
|
+
matches.push({ directory, location });
|
|
134
|
+
index.set(source.integrity, matches);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return index;
|
|
138
|
+
}
|
|
139
|
+
async function registryTarball(source, name, limits) {
|
|
140
|
+
const manual = !publicTarball.test(source.resolved);
|
|
141
|
+
const options = {
|
|
142
|
+
cache: join(limits.cache, '_cacache'),
|
|
143
|
+
resolved: source.resolved,
|
|
144
|
+
offline: manual || limits.offline,
|
|
145
|
+
preferOffline: true,
|
|
146
|
+
integrity: source.integrity,
|
|
147
|
+
retry: { retries: 0 },
|
|
148
|
+
timeout: 30000,
|
|
149
|
+
signal: limits.signal,
|
|
150
|
+
};
|
|
151
|
+
try {
|
|
152
|
+
const { tarball } = (await import('pacote')).default;
|
|
153
|
+
const read = (settings) => tarball.stream(
|
|
154
|
+
// A private lock entry can be a hosted Git URL. Keep it on npm's registry/cache path.
|
|
155
|
+
manual ? name : source.resolved, async (stream) => {
|
|
156
|
+
const chunks = [];
|
|
157
|
+
let size = 0;
|
|
158
|
+
for await (const chunk of stream) {
|
|
159
|
+
size += chunk.length;
|
|
160
|
+
if (size > (limits.maxBytes ?? 256 * 1024 * 1024))
|
|
161
|
+
throw contentError('MATERIAL_LIMIT');
|
|
162
|
+
chunks.push(chunk);
|
|
163
|
+
}
|
|
164
|
+
return Buffer.concat(chunks);
|
|
165
|
+
}, settings);
|
|
166
|
+
// Older Arcadia imports populated the cache root directly, alongside npm's _cacache.
|
|
167
|
+
if (await lstat(join(limits.cache, 'content-v2')).then(stat => stat.isDirectory(), () => false)) {
|
|
168
|
+
try {
|
|
169
|
+
return await read({ ...options, cache: limits.cache, offline: true });
|
|
170
|
+
}
|
|
171
|
+
catch (error) {
|
|
172
|
+
limits.signal?.throwIfAborted();
|
|
173
|
+
if (errorCode(error) === 'MATERIAL_LIMIT')
|
|
174
|
+
throw error;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return await read(options);
|
|
178
|
+
}
|
|
179
|
+
catch (cause) {
|
|
180
|
+
limits.signal?.throwIfAborted();
|
|
181
|
+
if (errorCode(cause) === 'MATERIAL_LIMIT')
|
|
182
|
+
throw cause;
|
|
183
|
+
if (manual)
|
|
184
|
+
throw contentError('PACKAGE_ARCHIVE_REQUIRED', `请补充 ${name}@${source.version} 的归档(${source.integrity})`);
|
|
185
|
+
throw Object.assign(new Error(`无法取得 ${name} 的锁定归档,请允许下载或补充对应的 .tgz 文件。`, { cause }), {
|
|
186
|
+
code: 'PACKAGE_ARCHIVE_REQUIRED',
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
function matchingFiles(ref, available) {
|
|
191
|
+
const result = [];
|
|
192
|
+
for (const path of ref.paths) {
|
|
193
|
+
const bytes = available.get(path);
|
|
194
|
+
const destination = ref.location + '/' + path;
|
|
195
|
+
if (!bytes || packageLocation(destination) !== ref.location)
|
|
196
|
+
return;
|
|
197
|
+
result.push({ path: destination, bytes });
|
|
198
|
+
}
|
|
199
|
+
return fileDigest(result) === ref.digest ? result : undefined;
|
|
200
|
+
}
|
|
201
|
+
export async function expandSharedMaterials(files, references, limits) {
|
|
202
|
+
if (!Array.isArray(files) || !Array.isArray(references))
|
|
203
|
+
throw contentError('ENVIRONMENT_EXPORT_INVALID');
|
|
204
|
+
const maxBytes = limits.maxBytes ?? 256 * 1024 * 1024;
|
|
205
|
+
const maxFiles = limits.maxFiles ?? 50000;
|
|
206
|
+
let remaining = maxBytes;
|
|
207
|
+
const byPath = new Map();
|
|
208
|
+
for (const file of files) {
|
|
209
|
+
if (!isRecord(file) || typeof file.data !== 'string' || typeof file.path !== 'string')
|
|
210
|
+
throw contentError('MATERIAL_ENCODING_INVALID');
|
|
211
|
+
remaining -= Buffer.byteLength(file.data, 'base64');
|
|
212
|
+
if (remaining < 0 || files.length > maxFiles)
|
|
213
|
+
throw contentError('MATERIAL_LIMIT');
|
|
214
|
+
byPath.set(file.path, Buffer.from(file.data, 'base64'));
|
|
215
|
+
}
|
|
216
|
+
const lock = JSON.parse(byPath.get('package-lock.json')?.toString() ?? 'null');
|
|
217
|
+
let suppliedBytes = 0;
|
|
218
|
+
const supplied = new Map();
|
|
219
|
+
for (const [integrity, data] of Object.entries(limits.supplied ?? {})) {
|
|
220
|
+
if (typeof data !== 'string' || !/^sha(256|384|512)-[A-Za-z0-9+/]+={0,2}$/.test(integrity))
|
|
221
|
+
throw contentError('MATERIAL_ENCODING_INVALID');
|
|
222
|
+
const bytes = Buffer.from(data, 'base64');
|
|
223
|
+
suppliedBytes += bytes.length;
|
|
224
|
+
if (suppliedBytes > maxBytes)
|
|
225
|
+
throw contentError('MATERIAL_LIMIT');
|
|
226
|
+
verifyArchive(bytes, integrity);
|
|
227
|
+
supplied.set(integrity, bytes);
|
|
228
|
+
}
|
|
229
|
+
const expanded = [];
|
|
230
|
+
const locations = new Set();
|
|
231
|
+
let installed;
|
|
232
|
+
let fileCount = files.length;
|
|
233
|
+
for (const ref of references) {
|
|
234
|
+
limits.signal?.throwIfAborted();
|
|
235
|
+
// Old exports can describe a sender-specific base, including a registry reference.
|
|
236
|
+
if (isRecord(ref) && typeof ref.location === 'string' && isBaseMaterial(ref.location))
|
|
237
|
+
continue;
|
|
238
|
+
if (!isRecord(ref) ||
|
|
239
|
+
ref.bundledBase ||
|
|
240
|
+
typeof ref.location !== 'string' ||
|
|
241
|
+
locations.has(ref.location) ||
|
|
242
|
+
!Array.isArray(ref.paths) ||
|
|
243
|
+
!ref.paths.length ||
|
|
244
|
+
ref.paths.length + fileCount > maxFiles ||
|
|
245
|
+
ref.paths.some(path => typeof path !== 'string'))
|
|
246
|
+
throw contentError('ENVIRONMENT_EXPORT_INVALID');
|
|
247
|
+
fileCount += ref.paths.length;
|
|
248
|
+
locations.add(ref.location);
|
|
249
|
+
const source = sourceFor(lock, ref.location);
|
|
250
|
+
if (!source)
|
|
251
|
+
throw contentError('MATERIAL_LOCK_NOT_PORTABLE');
|
|
252
|
+
if (limits.missing) {
|
|
253
|
+
const external = externalDependency(source, ref.location);
|
|
254
|
+
if (!external ||
|
|
255
|
+
!ref.external ||
|
|
256
|
+
external.integrity !== ref.external.integrity ||
|
|
257
|
+
external.manual !== ref.external.manual ||
|
|
258
|
+
external.name !== ref.external.name ||
|
|
259
|
+
external.version !== ref.external.version)
|
|
260
|
+
throw contentError('ENVIRONMENT_EXPORT_INVALID');
|
|
261
|
+
}
|
|
262
|
+
if (!source.resolved.startsWith('file:') && limits.environments && !supplied.has(source.integrity)) {
|
|
263
|
+
installed ??= await installedArchives(limits.environments);
|
|
264
|
+
let reused = false;
|
|
265
|
+
for (const candidate of installed.get(source.integrity) ?? []) {
|
|
266
|
+
const local = await materialFiles(candidate.directory, {
|
|
267
|
+
...limits,
|
|
268
|
+
subtree: candidate.location,
|
|
269
|
+
maxBytes: remaining,
|
|
270
|
+
}).catch(() => []);
|
|
271
|
+
limits.signal?.throwIfAborted();
|
|
272
|
+
const recorded = new Map(local.map(file => [file.path.slice(candidate.location.length + 1), file.bytes]));
|
|
273
|
+
const matches = matchingFiles(ref, recorded);
|
|
274
|
+
if (matches) {
|
|
275
|
+
remaining -= matches.reduce((sum, file) => sum + file.bytes.length, 0);
|
|
276
|
+
if (remaining < 0)
|
|
277
|
+
throw contentError('MATERIAL_LIMIT');
|
|
278
|
+
if (!limits.missing)
|
|
279
|
+
expanded.push(...matches);
|
|
280
|
+
reused = true;
|
|
281
|
+
break;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
if (reused)
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
let bytes;
|
|
288
|
+
if (source.resolved.startsWith('file:')) {
|
|
289
|
+
const local = byPath.get(source.resolved.slice(5));
|
|
290
|
+
if (!local)
|
|
291
|
+
throw contentError('ENVIRONMENT_SOURCE_MISSING');
|
|
292
|
+
bytes = local;
|
|
293
|
+
}
|
|
294
|
+
else if (supplied.has(source.integrity)) {
|
|
295
|
+
bytes = supplied.get(source.integrity);
|
|
296
|
+
}
|
|
297
|
+
else {
|
|
298
|
+
try {
|
|
299
|
+
bytes = await registryTarball(source, ref.location.slice(ref.location.lastIndexOf('node_modules/') + 13), limits);
|
|
300
|
+
}
|
|
301
|
+
catch (error) {
|
|
302
|
+
limits.signal?.throwIfAborted();
|
|
303
|
+
if (!limits.missing || !limits.offline || errorCode(error) !== 'PACKAGE_ARCHIVE_REQUIRED')
|
|
304
|
+
throw error;
|
|
305
|
+
limits.missing.add(source.integrity);
|
|
306
|
+
continue;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
verifyArchive(bytes, source.integrity);
|
|
310
|
+
const archive = await readArchiveFiles(bytes, { ...limits, maxBytes: remaining });
|
|
311
|
+
const restored = matchingFiles(ref, archive);
|
|
312
|
+
if (!restored)
|
|
313
|
+
throw contentError('SOURCE_INTEGRITY_MISMATCH');
|
|
314
|
+
remaining -= restored.reduce((sum, file) => sum + file.bytes.length, 0);
|
|
315
|
+
if (remaining < 0)
|
|
316
|
+
throw contentError('MATERIAL_LIMIT');
|
|
317
|
+
if (!limits.missing)
|
|
318
|
+
expanded.push(...restored);
|
|
319
|
+
}
|
|
320
|
+
return [...files, ...expanded];
|
|
321
|
+
}
|
package/dist/environment.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { prepareNpmProject } from '@arcadia-eternity/pack-loader/node';
|
|
|
2
2
|
import { type ManifestArcadia, 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
|
+
import { prepareRulesForContent } from './environment-rules.js';
|
|
5
6
|
type PreparedNpmEnvironment = Awaited<ReturnType<typeof prepareNpmProject>>;
|
|
6
7
|
export interface BattleLike {
|
|
7
8
|
cleanup(): Promise<void>;
|
|
@@ -20,6 +21,7 @@ export interface ContentCandidate {
|
|
|
20
21
|
export interface PreparedBattleEnvironment {
|
|
21
22
|
environment: PreparedNpmEnvironment;
|
|
22
23
|
environmentDocument: EnvironmentDocumentV2;
|
|
24
|
+
effectiveRules: ReturnType<typeof prepareRulesForContent>['rules'];
|
|
23
25
|
candidate: ContentCandidate;
|
|
24
26
|
environmentLock: {
|
|
25
27
|
file: string;
|