@arcadia-eternity/content-sdk 4.11.1 → 4.13.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.
package/README.md CHANGED
@@ -98,4 +98,4 @@ Workspace files own persistent environment projects and their current installati
98
98
 
99
99
  `pnpm --filter @arcadia-eternity/content-sdk watch` builds once, then rebuilds when `src`, `template`, or either bundled skill directory under `docs/guides` changes. Rebuilds are serialized, include deletions, and recover after a failed build. The root `pnpm watch` includes this watcher. `pnpm --filter @arcadia-eternity/content-sdk clear` removes `dist`; root `pnpm clear` includes it as well. The package `typecheck` validates the TypeScript implementation and generated declarations; Node tests exercise the source modules directly.
100
100
 
101
- `ManagedProjects.synchronizeBundledBase(workspace, validate)` refreshes shipped base content in existing environments at host startup. It replaces only the local base files and their manifest/lock entries, preserves installed third-party dependencies, and commits each validated update atomically. Old base version declarations follow the shipped version. `synchronizeProject` provides the same staged update for desktop library projects and external startup projects; unchanged base materials are a no-op, including across restarts.
101
+ At startup, `synchronizeShippedEnvironments` refreshes the official presets and compares their compiled base materials when the version is unchanged. User environments and explicit startup npm projects keep their locks. Preparing a rule edit reuses the installed base when it satisfies the request. An unavailable exact pin fails preparation. `ManagedProjects.synchronizeProject` and `synchronizeBundledBase` remain explicit migration APIs.
@@ -664,6 +664,144 @@ 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
805
  /** The host supplies this catalog from the application distribution. */
668
806
  export declare function readShippedEnvironments(file: string | URL, bundledVersions: Record<string, string>): Promise<{
669
807
  defaultEnvironment: string;
@@ -802,4 +940,4 @@ export declare function readShippedEnvironments(file: string | URL, bundledVersi
802
940
  };
803
941
  }[];
804
942
  }>;
805
- export declare function synchronizeShippedEnvironments(workspace: OwnedContentWorkspace, catalog: Awaited<ReturnType<typeof readShippedEnvironments>>, adopted: Record<string, string>, prepare: (document: EnvironmentDocument, expectedRevision: string | null) => Promise<unknown>): Promise<string>;
943
+ 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>;
@@ -5,7 +5,7 @@ import { lstat, mkdir, readFile, readdir, realpath, rename, rm, writeFile } from
5
5
  import { join, resolve } from 'node:path';
6
6
  import writeFileAtomic from 'write-file-atomic';
7
7
  import semver from 'semver';
8
- import { inspectNpmProject } from '@arcadia-eternity/pack-loader/node';
8
+ import { catalogMaterialDigest, inspectNpmProject } from '@arcadia-eternity/pack-loader/node';
9
9
  import { normalizeEnvironmentDocument, EnvironmentDocumentV2Schema, EnvironmentRulesSchema, EnvironmentRuleDeclarationSchema, } from './debug-environments.js';
10
10
  import { z } from 'zod';
11
11
  import { withSourceLock } from './source-lock.js';
@@ -1085,6 +1085,16 @@ async function changeEnvironmentPackage(workspace, input) {
1085
1085
  }
1086
1086
  return workspace.saveDraft({ document: normalizeEnvironmentDocument(document), expectedRevision });
1087
1087
  }
1088
+ /** Resolve presets from the same selected base installation as the battle materials. */
1089
+ export async function readOfficialEnvironments(root, legacyCatalog) {
1090
+ const manifest = await readJson(join(root, 'package.json'));
1091
+ if (manifest.name !== hostBaseName || typeof manifest.version !== 'string' || !semver.valid(manifest.version))
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 });
1097
+ }
1088
1098
  /** The host supplies this catalog from the application distribution. */
1089
1099
  export async function readShippedEnvironments(file, bundledVersions) {
1090
1100
  const schema = z
@@ -1106,16 +1116,22 @@ export async function readShippedEnvironments(file, bundledVersions) {
1106
1116
  }
1107
1117
  return catalog;
1108
1118
  }
1109
- export async function synchronizeShippedEnvironments(workspace, catalog, adopted, prepare) {
1119
+ export async function synchronizeShippedEnvironments(workspace, catalog, adopted, prepare, officialBaseRoot) {
1110
1120
  await workspace.registerBuiltinEnvironments(catalog.environments.map(doc => doc.id), adopted);
1121
+ const selectedDigest = officialBaseRoot && (await catalogMaterialDigest(officialBaseRoot));
1111
1122
  const drafts = await workspace.listDrafts();
1112
1123
  for (const document of catalog.environments) {
1113
1124
  const id = document.id;
1114
1125
  const current = drafts.find(item => item.document.id === id);
1115
1126
  if (current && isDeepStrictEqual(current.document, document)) {
1116
1127
  const [installed] = await workspace.listInstallations(id);
1117
- if (installed?.status === 'ready' && installed.draftRevision === current.revision)
1118
- continue;
1128
+ if (installed?.status === 'ready' && installed.draftRevision === current.revision) {
1129
+ if (!selectedDigest || !Object.hasOwn(document.packages, hostBaseName))
1130
+ continue;
1131
+ const digest = await catalogMaterialDigest(join(installed.directory, 'node_modules', hostBaseName)).catch(() => null);
1132
+ if (digest === selectedDigest)
1133
+ continue;
1134
+ }
1119
1135
  }
1120
1136
  await prepare(document, current?.revision ?? null);
1121
1137
  }
@@ -1,8 +1,11 @@
1
+ import { type PackageUpdate } from './package-updates.js';
2
+ export { officialPackage, findPackageUpdate, selectPackageUpdate, startAutomaticContentUpdates, selectServerBase, installServerBaseUpdate, } from './package-updates.js';
1
3
  import type { ContentWorkspace, EnvironmentInstallation, PrepareEnvironmentInput, StaticPreparer } from './content-workspace.js';
2
4
  import type { ManagedSource } from './managed-sources.js';
3
5
  import { type UnknownRecord } from './types.js';
4
6
  export interface ManagedProjectsOptions {
5
7
  bundledPackageRoot?: string;
8
+ resolveBaseVersion?: (version: string) => Promise<string | undefined>;
6
9
  registry?: string;
7
10
  offline?: boolean;
8
11
  /** Host permission to acquire metadata/materials; never grants authority to execute them. */
@@ -31,11 +34,12 @@ export declare class ManagedProjects {
31
34
  onProgress?: PrepareEnvironmentInput['onProgress'];
32
35
  environmentId: string;
33
36
  seedDirectory?: string;
37
+ useSelectedBase?: boolean;
34
38
  expectedRevision: string | null;
35
39
  document?: PrepareEnvironmentInput['document'];
36
40
  signal?: AbortSignal;
37
41
  beforeCommit?: () => Promise<void>;
38
- }, validate: StaticPreparer): Promise<EnvironmentInstallation>;
42
+ }, validate: StaticPreparer, officialBaseRoot?: string): Promise<EnvironmentInstallation>;
39
43
  /** Refresh only shipped bytes, without resolving or downloading third-party dependencies. */
40
44
  synchronizeBundledBase(workspace: ContentWorkspace, validate: StaticPreparer): Promise<void>;
41
45
  synchronizeProject<T>(project: string, consume: (directory: string, version: string) => Promise<T>): Promise<T | undefined>;
@@ -47,3 +51,4 @@ export declare class ManagedProjects {
47
51
  }, consume: (directory: string, signal: AbortSignal) => Promise<T>): Promise<T>;
48
52
  close(): Promise<void>;
49
53
  }
54
+ export declare function withOfficialUpdateArchive<T>(candidate: PackageUpdate, npmCli: string | undefined, signal: AbortSignal, use: (file: string) => Promise<T>): Promise<T>;
@@ -2,8 +2,10 @@ import { sha256Hex } from '@arcadia-eternity/const';
2
2
  import { execFile } from 'node:child_process';
3
3
  import { mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, writeFile } from 'node:fs/promises';
4
4
  import { join, resolve } from 'node:path';
5
+ import { withOfficialUpdateDirectory } from './package-updates.js';
6
+ export { officialPackage, findPackageUpdate, selectPackageUpdate, startAutomaticContentUpdates, selectServerBase, installServerBaseUpdate, } from './package-updates.js';
5
7
  import { isDeepStrictEqual, promisify } from 'node:util';
6
- import { valid, validRange } from 'semver';
8
+ import { satisfies, valid, validRange } from 'semver';
7
9
  import { inspectNpmProject, resolveNpmInvocation, withShippedEnvironmentProject, withShippedCatalogArchive, } from '@arcadia-eternity/pack-loader/node';
8
10
  import { normalizeEnvironmentDocument } from './debug-environments.js';
9
11
  import { acquireSource } from './managed-sources.js';
@@ -101,6 +103,9 @@ export class ManagedProjects {
101
103
  throw contentError('INSTALL_SOURCES_INVALID');
102
104
  this.#options = {
103
105
  ...options,
106
+ get bundledPackageRoot() {
107
+ return options.bundledPackageRoot;
108
+ },
104
109
  registry: registryUrl(options.registry),
105
110
  sources: structuredClone(options.sources ?? {}),
106
111
  timeoutMs: limit(options.timeoutMs, DEFAULT_TIMEOUT, 3600_000),
@@ -222,7 +227,7 @@ export class ManagedProjects {
222
227
  await rm(staging, { recursive: true, force: true });
223
228
  }
224
229
  }
225
- prepareEnvironment(workspace, input, validate) {
230
+ prepareEnvironment(workspace, input, validate, officialBaseRoot) {
226
231
  if (typeof validate !== 'function')
227
232
  return Promise.reject(contentError('STATIC_PREPARER_REQUIRED'));
228
233
  return this.#track(this.#prepare(async () => {
@@ -236,6 +241,7 @@ export class ManagedProjects {
236
241
  return input.document ?? draft?.document;
237
242
  }, {
238
243
  ...input,
244
+ officialBaseRoot,
239
245
  projectDirectory: input.seedDirectory ?? join(workspace.root, 'environments', input.environmentId),
240
246
  }, async (directory, signal, document) => {
241
247
  return workspace.prepareEnvironment({ ...input, document, projectDirectory: directory, signal }, validate);
@@ -362,11 +368,42 @@ export class ManagedProjects {
362
368
  const includesBase = Object.hasOwn(dependencies, baseName) || document.sources.includes(baseName);
363
369
  if (Object.hasOwn(dependencies, baseName) && document.sources.includes(baseName))
364
370
  throw contentError('INSTALL_DUPLICATE_PACKAGE');
365
- const baseRoot = this.#options.bundledPackageRoot;
371
+ let baseRoot = input.officialBaseRoot ?? this.#options.bundledPackageRoot;
366
372
  if (includesBase && !baseRoot)
367
373
  throw contentError('BUNDLED_PACKAGE_UNAVAILABLE');
368
374
  if (includesBase) {
369
- const baseManifest = JSON.parse(await readFile(join(baseRoot, 'package.json'), 'utf8'));
375
+ let range = dependencies[baseName];
376
+ if (!input.useSelectedBase && input.projectDirectory && range) {
377
+ const seed = join(input.projectDirectory, 'node_modules', baseName);
378
+ const resolved = await realpath(seed).catch(error => {
379
+ if (errorCode(error) !== 'ENOENT')
380
+ throw error;
381
+ });
382
+ if (resolved) {
383
+ if (resolved !== join(await realpath(input.projectDirectory), 'node_modules', baseName))
384
+ throw contentError('MATERIAL_PATH_ESCAPE');
385
+ const pinned = JSON.parse(await readFile(join(seed, 'package.json'), 'utf8'));
386
+ if (range.startsWith('file:')) {
387
+ const lock = JSON.parse(await readFile(join(input.projectDirectory, 'package-lock.json'), 'utf8'));
388
+ const member = lock.packages?.['node_modules/' + baseName];
389
+ if (member?.resolved !== range || member.version !== pinned.version)
390
+ throw contentError('BASE_PACK_VERSION_UNAVAILABLE');
391
+ range = member.version;
392
+ }
393
+ if (pinned.name === baseName && satisfies(pinned.version, range))
394
+ baseRoot = resolved;
395
+ }
396
+ }
397
+ let baseManifest = JSON.parse(await readFile(join(baseRoot, 'package.json'), 'utf8'));
398
+ if (range && !satisfies(baseManifest.version, range)) {
399
+ const cached = valid(range) && (await this.#options.resolveBaseVersion?.(range));
400
+ if (!cached)
401
+ throw contentError('BASE_PACK_VERSION_UNAVAILABLE', '本机缺少环境所需的基础包 ' + range);
402
+ baseRoot = cached;
403
+ baseManifest = JSON.parse(await readFile(join(cached, 'package.json'), 'utf8'));
404
+ if (!satisfies(baseManifest.version, range))
405
+ throw contentError('BASE_PACK_VERSION_UNAVAILABLE');
406
+ }
370
407
  if (baseManifest.name !== baseName)
371
408
  throw contentError('BUNDLED_PACKAGE_INVALID');
372
409
  dependencies[baseName] = baseManifest.version;
@@ -568,3 +605,8 @@ export class ManagedProjects {
568
605
  await Promise.allSettled([...this.#pending]);
569
606
  }
570
607
  }
608
+ // Discard the npm development/runtime dependencies before passing the official catalog
609
+ // to the same offline installer used for the application's bundled copy.
610
+ export async function withOfficialUpdateArchive(candidate, npmCli, signal, use) {
611
+ return withOfficialUpdateDirectory(candidate, signal, directory => withShippedCatalogArchive(directory, npmCli, use));
612
+ }
@@ -4,7 +4,7 @@ import { copyFile, lstat, mkdir, mkdtemp, readFile, realpath, rename, rm, writeF
4
4
  import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
5
5
  import { promisify } from 'node:util';
6
6
  import { compileEffectModule, emptyNpmContentHost, parseNpmPackOutput, prepareNpmProject, resolveNpmInvocation, } from '@arcadia-eternity/pack-loader/node';
7
- import { releasePayload, normalizeReleaseArchive } from '../release-payload.mjs';
7
+ import { releasePayload, normalizeReleaseArchive, requireClientRange } from '../release-payload.mjs';
8
8
  import { ManagedProjects } from './managed-projects.js';
9
9
  import { errorCode } from './types.js';
10
10
  const exec = promisify(execFile);
@@ -89,6 +89,8 @@ export async function packBuiltProject(directory = process.cwd(), { cache, relea
89
89
  const root = await realpath(resolve(directory));
90
90
  const manifestText = await readFile(join(root, 'package.json'), 'utf8');
91
91
  const manifest = JSON.parse(manifestText);
92
+ if (!release && manifest.arcadia)
93
+ requireClientRange(manifest);
92
94
  const preview = parseNpmPackOutput(String((await npm(root, ['pack', '--dry-run', '--ignore-scripts', '--json'], cache)).stdout))[0];
93
95
  if (!preview || preview.files.length > 50000)
94
96
  fail('npm returned an invalid package file list');
@@ -0,0 +1,24 @@
1
+ export declare const officialPackage = "@arcadia-eternity/data-pack-base";
2
+ export interface PackageUpdate {
3
+ name: string;
4
+ version: string;
5
+ range: string;
6
+ url: string;
7
+ integrity: string;
8
+ }
9
+ export declare function startAutomaticContentUpdates(update: (options: {
10
+ signal: AbortSignal;
11
+ }) => Promise<unknown>, onError: (error: unknown) => void): () => Promise<void> | undefined;
12
+ export declare function selectPackageUpdate(metadata: unknown, name: string, current: string, client: string): PackageUpdate | null;
13
+ export declare function findPackageUpdate(name: string, current: string, client: string, signal?: AbortSignal): Promise<PackageUpdate | null>;
14
+ export declare function withOfficialUpdateDirectory<T>(candidate: PackageUpdate, signal: AbortSignal, use: (directory: string) => Promise<T>): Promise<T>;
15
+ /** Only completed version directories are eligible. Offline startup never contacts the registry. */
16
+ export declare function selectServerBase(store: string, shipped: string, host: string, pin?: string, validate?: (directory: string) => Promise<void>): Promise<{
17
+ directory: string;
18
+ version: string;
19
+ cached: boolean;
20
+ }>;
21
+ export declare function installServerBaseUpdate(store: string, candidate: PackageUpdate, host: string, validate: (directory: string, signal: AbortSignal) => Promise<void>, options?: {
22
+ signal?: AbortSignal;
23
+ beforeCommit?: (directory: string) => Promise<void>;
24
+ }): Promise<void>;
@@ -0,0 +1,222 @@
1
+ import { catalogMaterialDigest } from '@arcadia-eternity/pack-loader/node';
2
+ import semver from 'semver';
3
+ import { mkdir, mkdtemp, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises';
4
+ import { join } from 'node:path';
5
+ import { tmpdir } from 'node:os';
6
+ import { acquireSource } from './managed-sources.js';
7
+ import { errorCode, isRecord } from './types.js';
8
+ export const officialPackage = '@arcadia-eternity/data-pack-base';
9
+ export function startAutomaticContentUpdates(update, onError) {
10
+ const controller = new AbortController();
11
+ let running;
12
+ let timer;
13
+ function schedule(delay) {
14
+ timer = setTimeout(() => {
15
+ running = check();
16
+ }, delay);
17
+ timer.unref();
18
+ }
19
+ async function check() {
20
+ let delay = 6 * 60 * 60 * 1000;
21
+ try {
22
+ await update({ signal: controller.signal });
23
+ }
24
+ catch (error) {
25
+ if (controller.signal.aborted)
26
+ return;
27
+ onError(error);
28
+ delay = 15 * 60 * 1000;
29
+ }
30
+ if (!controller.signal.aborted)
31
+ schedule(delay);
32
+ }
33
+ schedule(3000);
34
+ return () => {
35
+ controller.abort();
36
+ clearTimeout(timer);
37
+ return running;
38
+ };
39
+ }
40
+ export function selectPackageUpdate(metadata, name, current, client) {
41
+ if (!isRecord(metadata) ||
42
+ metadata.name !== name ||
43
+ !isRecord(metadata.versions) ||
44
+ !isRecord(metadata['dist-tags']) ||
45
+ typeof metadata['dist-tags'].latest !== 'string' ||
46
+ !semver.valid(metadata['dist-tags'].latest))
47
+ throw new Error('npm 返回了无效的包版本清单');
48
+ const latest = metadata['dist-tags'].latest;
49
+ const candidates = Object.keys(metadata.versions)
50
+ .filter(version => semver.valid(version) &&
51
+ !semver.prerelease(version) &&
52
+ semver.gt(version, current) &&
53
+ semver.lte(version, latest))
54
+ .sort(semver.rcompare);
55
+ for (const version of candidates) {
56
+ const pkg = metadata.versions[version];
57
+ if (!isRecord(pkg))
58
+ throw new Error('npm 返回了无效的包版本清单');
59
+ const range = isRecord(pkg.engines) && pkg.engines.arcadia;
60
+ if (pkg.deprecated ||
61
+ typeof range !== 'string' ||
62
+ !range.trim() ||
63
+ range.length > 256 ||
64
+ !semver.satisfies(client, range))
65
+ continue;
66
+ const expected = `https://registry.npmjs.org/${name}/-/${name.split('/').at(-1)}-${version}.tgz`;
67
+ if (pkg.version !== version ||
68
+ !isRecord(pkg.dist) ||
69
+ pkg.dist.tarball !== expected ||
70
+ typeof pkg.dist.integrity !== 'string' ||
71
+ !/^sha512-[A-Za-z0-9+/]{86}==$/.test(pkg.dist.integrity))
72
+ throw new Error('npm 返回了无效的发行归档');
73
+ return { name, version, range, url: expected, integrity: pkg.dist.integrity };
74
+ }
75
+ return null;
76
+ }
77
+ export async function findPackageUpdate(name, current, client, signal) {
78
+ const timeout = AbortSignal.timeout(20000);
79
+ const response = await fetch('https://registry.npmjs.org/' + encodeURIComponent(name), {
80
+ headers: { Accept: 'application/vnd.npm.install-v1+json' },
81
+ redirect: 'error',
82
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
83
+ });
84
+ if (!response.ok)
85
+ throw new Error('无法检查 npm 包更新(HTTP ' + response.status + ')');
86
+ // The full version history is needed to find a compatible release below latest.
87
+ const limit = 8 * 1024 * 1024;
88
+ if (!response.body || Number(response.headers.get('content-length')) > limit) {
89
+ await response.body?.cancel();
90
+ throw new Error('npm 版本清单过大或为空');
91
+ }
92
+ const chunks = [];
93
+ let size = 0;
94
+ for await (const chunk of response.body) {
95
+ size += chunk.length;
96
+ if (size > limit)
97
+ throw new Error('npm 版本清单过大');
98
+ chunks.push(chunk);
99
+ }
100
+ return selectPackageUpdate(JSON.parse(Buffer.concat(chunks).toString('utf8')), name, current, client);
101
+ }
102
+ async function acquireOfficial(candidate, destination, signal) {
103
+ if (candidate.name !== officialPackage ||
104
+ !semver.valid(candidate.version) ||
105
+ typeof candidate.range !== 'string' ||
106
+ !candidate.range.trim() ||
107
+ candidate.range.length > 256 ||
108
+ !semver.validRange(candidate.range) ||
109
+ candidate.url !== `https://registry.npmjs.org/${officialPackage}/-/data-pack-base-${candidate.version}.tgz` ||
110
+ !/^sha512-[A-Za-z0-9+/]{86}==$/.test(candidate.integrity))
111
+ throw new Error('INVALID_OFFICIAL_PACKAGE');
112
+ const { directory } = await acquireSource({ kind: 'url', url: candidate.url, integrity: candidate.integrity }, { destination, signal });
113
+ const manifest = JSON.parse(await readFile(join(directory, 'package.json'), 'utf8'));
114
+ if (manifest.name !== officialPackage ||
115
+ manifest.version !== candidate.version ||
116
+ manifest.engines?.arcadia !== candidate.range ||
117
+ manifest.arcadia?.projectId !== 'base' ||
118
+ manifest.arcadia?.namespace !== 'base')
119
+ throw new Error('INVALID_OFFICIAL_PACKAGE');
120
+ return directory;
121
+ }
122
+ export async function withOfficialUpdateDirectory(candidate, signal, use) {
123
+ const stage = await mkdtemp(join(tmpdir(), 'arcadia-official-update-'));
124
+ try {
125
+ return await use(await acquireOfficial(candidate, join(stage, 'source'), signal));
126
+ }
127
+ finally {
128
+ await rm(stage, { recursive: true, force: true });
129
+ }
130
+ }
131
+ /** Only completed version directories are eligible. Offline startup never contacts the registry. */
132
+ export async function selectServerBase(store, shipped, host, pin, validate) {
133
+ const bundled = JSON.parse(await readFile(join(shipped, 'package.json'), 'utf8'));
134
+ const fallback = { directory: shipped, version: bundled.version, cached: false };
135
+ const bundledCompatible = bundled.engines?.arcadia === undefined || semver.satisfies(host, bundled.engines.arcadia);
136
+ if (pin === 'bundled') {
137
+ if (!bundledCompatible)
138
+ throw new Error('INCOMPATIBLE_OFFICIAL_PACKAGE');
139
+ await validate?.(shipped);
140
+ return fallback;
141
+ }
142
+ if (pin && semver.valid(pin) !== pin)
143
+ throw new Error('Invalid base pack version: ' + pin);
144
+ const entries = await readdir(store, { withFileTypes: true }).catch(error => {
145
+ if (errorCode(error) === 'ENOENT')
146
+ return [];
147
+ throw error;
148
+ });
149
+ const candidates = entries
150
+ .filter(entry => entry.isDirectory() && semver.valid(entry.name) === entry.name)
151
+ .map(entry => ({ directory: join(store, entry.name), version: entry.name, cached: true }));
152
+ if (bundledCompatible)
153
+ candidates.push(fallback);
154
+ // Inspect cached ties first to detect an ambiguous release while retaining the shipped reference.
155
+ candidates.sort((a, b) => semver.rcompare(a.version, b.version));
156
+ let lastError;
157
+ for (const candidate of candidates) {
158
+ const { directory, version, cached } = candidate;
159
+ if (pin && version !== pin)
160
+ continue;
161
+ try {
162
+ if (cached) {
163
+ const manifest = JSON.parse(await readFile(join(directory, 'package.json'), 'utf8'));
164
+ if (manifest.name !== officialPackage || manifest.version !== version)
165
+ throw new Error('INVALID_OFFICIAL_PACKAGE');
166
+ if (!manifest.engines?.arcadia?.trim() || !semver.satisfies(host, manifest.engines.arcadia))
167
+ continue;
168
+ const digest = await catalogMaterialDigest(directory);
169
+ const recorded = await readFile(join(directory, '.arcadia-material-digest'), 'utf8').catch(error => {
170
+ if (errorCode(error) !== 'ENOENT')
171
+ throw error;
172
+ });
173
+ if (recorded !== undefined && digest !== recorded)
174
+ throw new Error('OFFICIAL_MATERIAL_DIGEST_MISMATCH');
175
+ if (version === bundled.version && bundledCompatible) {
176
+ if (digest !== (await catalogMaterialDigest(shipped)))
177
+ console.warn('OFFICIAL_BASE_VERSION_CONFLICT', version, 'using bundled materials');
178
+ continue;
179
+ }
180
+ }
181
+ await validate?.(directory);
182
+ return candidate;
183
+ }
184
+ catch (error) {
185
+ lastError = error;
186
+ console.warn('Skipping unusable official base', version, directory, error);
187
+ }
188
+ }
189
+ throw new Error('No compatible installed base pack ' + (pin ? 'at version ' + pin : 'for Arcadia ' + host), {
190
+ cause: lastError,
191
+ });
192
+ }
193
+ export async function installServerBaseUpdate(store, candidate, host, validate, options = {}) {
194
+ if (!semver.satisfies(host, candidate.range))
195
+ throw new Error('INCOMPATIBLE_OFFICIAL_PACKAGE');
196
+ await mkdir(store, { recursive: true, mode: 0o700 });
197
+ const stage = await mkdtemp(join(store, '.install-'));
198
+ try {
199
+ const timeout = AbortSignal.timeout(120000);
200
+ const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
201
+ const directory = await acquireOfficial(candidate, join(stage, 'source'), signal);
202
+ await validate(directory, signal);
203
+ const digest = await catalogMaterialDigest(directory);
204
+ await writeFile(join(directory, '.arcadia-material-digest'), digest);
205
+ signal.throwIfAborted();
206
+ await options.beforeCommit?.(directory);
207
+ options.signal?.throwIfAborted();
208
+ try {
209
+ await rename(directory, join(store, candidate.version));
210
+ }
211
+ catch (error) {
212
+ // Concurrent installers can only publish a complete, verified directory at this version.
213
+ if (!['EEXIST', 'ENOTEMPTY'].includes(errorCode(error) ?? ''))
214
+ throw error;
215
+ if ((await catalogMaterialDigest(join(store, candidate.version))) !== digest)
216
+ throw new Error('OFFICIAL_BASE_VERSION_CONFLICT: ' + candidate.version, { cause: error });
217
+ }
218
+ }
219
+ finally {
220
+ await rm(stage, { recursive: true, force: true });
221
+ }
222
+ }
@@ -270,7 +270,7 @@ export declare function preparedDocument(metadata: UnknownRecord, legacyManifest
270
270
  capabilities?: string[] | undefined;
271
271
  };
272
272
  };
273
- /** Plain npm projects use compatibility defaults. Managed projects must have prepared rules. */
273
+ /** Managed projects read their applied rules. Plain npm projects may install one rules recipe. */
274
274
  export declare function readInstalledEnvironmentDocument(directory: string, contentRevision?: string): Promise<{
275
275
  id: string;
276
276
  name: string;
@@ -1,6 +1,6 @@
1
1
  import { sha256Hex } from '@arcadia-eternity/const';
2
- import { readFile } from 'node:fs/promises';
3
- import { join } from 'node:path';
2
+ import { readFile, realpath } from 'node:fs/promises';
3
+ import { join, resolve } from 'node:path';
4
4
  import { normalizeEnvironmentDocument } from './debug-environments.js';
5
5
  import { contentError, readJson } from './workspace-materials.js';
6
6
  import { errorCode, isRecord } from './types.js';
@@ -31,17 +31,44 @@ export function preparedDocument(metadata, legacyManifest) {
31
31
  throw contentError('ENVIRONMENT_PREPARATION_REQUIRED');
32
32
  return draft.document;
33
33
  }
34
- /** Plain npm projects use compatibility defaults. Managed projects must have prepared rules. */
34
+ /** Managed projects read their applied rules. Plain npm projects may install one rules recipe. */
35
35
  export async function readInstalledEnvironmentDocument(directory, contentRevision) {
36
36
  const manifest = await readFile(join(directory, 'package.json'), 'utf8');
37
+ const project = JSON.parse(manifest);
37
38
  const receipt = await readJson(join(directory, '.arcadia-prepared.json')).catch(error => {
38
39
  if (errorCode(error) !== 'ENOENT')
39
40
  throw error;
40
- if (JSON.parse(manifest).arcadiaEnvironment)
41
+ if (project.arcadiaEnvironment)
41
42
  throw contentError('ENVIRONMENT_PREPARATION_REQUIRED');
42
43
  return undefined;
43
44
  });
44
45
  if (receipt && contentRevision !== undefined && receipt.contentRevision !== contentRevision)
45
46
  throw contentError('ENVIRONMENT_PREPARATION_REQUIRED');
46
- return receipt && preparedDocument(receipt, manifest);
47
+ if (receipt)
48
+ return preparedDocument(receipt, manifest);
49
+ // An ordinary npm project can select a rules recipe as a direct dependency.
50
+ const root = await realpath(directory);
51
+ let selected;
52
+ for (const name of Object.keys(project.dependencies ?? {})) {
53
+ if (!/^(?:@[a-z0-9._-]+\/)?[a-z0-9][a-z0-9._-]*$/.test(name))
54
+ continue;
55
+ const file = resolve(root, 'node_modules', name, 'package.json');
56
+ const installed = await realpath(file).catch(error => {
57
+ if (errorCode(error) !== 'ENOENT')
58
+ throw error;
59
+ });
60
+ if (!installed)
61
+ continue;
62
+ if (installed !== file)
63
+ throw contentError('MATERIAL_PATH_ESCAPE');
64
+ const pkg = await readJson(file);
65
+ if (!pkg.arcadiaEnvironment)
66
+ continue;
67
+ if (pkg.name !== name)
68
+ throw contentError('ENVIRONMENT_MANIFEST_INVALID');
69
+ if (selected)
70
+ throw contentError('ENVIRONMENT_PRESET_AMBIGUOUS', '项目依赖多个环境包,请显式选择环境声明。');
71
+ selected = parseManifestDraft(JSON.stringify(pkg)).document;
72
+ }
73
+ return selected;
47
74
  }
@@ -8,10 +8,17 @@ const require = createRequire(import.meta.url)
8
8
  const sdkRequire = createRequire(require.resolve('@arcadia-eternity/content-sdk'))
9
9
  const { valid, validRange } = sdkRequire('semver')
10
10
 
11
+ export function requireClientRange(source) {
12
+ const range = source.engines?.arcadia
13
+ if (typeof range !== 'string' || !range.trim() || range.length > 256 || !validRange(range))
14
+ throw Error('发行内容包必须在 package.json 的 engines.arcadia 声明有效的客户端版本范围')
15
+ }
16
+
11
17
  export function releasePayload(source, included, presentation) {
12
18
  if (!source.arcadia?.projectId || !source.arcadia.namespace || !source.arcadia.content || !valid(source.version))
13
19
  throw Error('发行包需要有效版本、projectId、namespace 和内容入口')
14
20
  if (typeof source.license !== 'string' || !source.license.trim()) throw Error('请先设置 package.json 的 license')
21
+ requireClientRange(source)
15
22
  const fields = [
16
23
  'name',
17
24
  'version',
@@ -21,7 +21,7 @@
21
21
  "devDependencies": {
22
22
  "@types/node": "26.6.6",
23
23
  "typescript": "6.0.3",
24
- "@arcadia-eternity/content-sdk": "4.11.1",
24
+ "@arcadia-eternity/content-sdk": "4.13.0",
25
25
  "fflate": "0.8.3"
26
26
  },
27
27
  "arcadia": {
@@ -38,6 +38,6 @@
38
38
  "license": "MIT",
39
39
  "engines": {
40
40
  "node": ">=24 <25",
41
- "arcadia": "^4.11.1"
41
+ "arcadia": "^4.13.0"
42
42
  }
43
43
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arcadia-eternity/content-sdk",
3
- "version": "4.11.1",
3
+ "version": "4.13.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "engines": {
@@ -63,10 +63,10 @@
63
63
  "zod": "4.6.7",
64
64
  "fflate": "0.8.3",
65
65
  "simple-git": "4.1.0",
66
- "@arcadia-eternity/battle": "4.11.1",
67
- "@arcadia-eternity/const": "4.11.1",
68
- "@arcadia-eternity/pack-loader": "4.11.1",
69
- "@arcadia-eternity/schema": "4.11.1"
66
+ "@arcadia-eternity/pack-loader": "4.13.0",
67
+ "@arcadia-eternity/schema": "4.13.0",
68
+ "@arcadia-eternity/const": "4.13.0",
69
+ "@arcadia-eternity/battle": "4.13.0"
70
70
  },
71
71
  "repository": {
72
72
  "type": "git",
@@ -8,10 +8,17 @@ const require = createRequire(import.meta.url)
8
8
  const sdkRequire = createRequire(require.resolve('@arcadia-eternity/content-sdk'))
9
9
  const { valid, validRange } = sdkRequire('semver')
10
10
 
11
+ export function requireClientRange(source) {
12
+ const range = source.engines?.arcadia
13
+ if (typeof range !== 'string' || !range.trim() || range.length > 256 || !validRange(range))
14
+ throw Error('发行内容包必须在 package.json 的 engines.arcadia 声明有效的客户端版本范围')
15
+ }
16
+
11
17
  export function releasePayload(source, included, presentation) {
12
18
  if (!source.arcadia?.projectId || !source.arcadia.namespace || !source.arcadia.content || !valid(source.version))
13
19
  throw Error('发行包需要有效版本、projectId、namespace 和内容入口')
14
20
  if (typeof source.license !== 'string' || !source.license.trim()) throw Error('请先设置 package.json 的 license')
21
+ requireClientRange(source)
15
22
  const fields = [
16
23
  'name',
17
24
  'version',