@wildshard/build 0.0.0 → 0.4.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.
@@ -0,0 +1,369 @@
1
+ import { printSpawnWarnings } from '@wildshard/sdk/internal/spawnWarnings';
2
+ import { executeBundle } from '@wildshard/sdk/executeBundle';
3
+ import { generationRecipes } from '@wildshard/sdk/internal/generationRecipe';
4
+ import { mergeProjectSections } from '@wildshard/sdk/internal/projectSections';
5
+ import { writeEmptyShardSource } from '@wildshard/sdk/internal/newProject';
6
+ import { shardFolderName, shardOutputRoot, shardRepoRoot } from '@wildshard/upload/sharddev/shardSource';
7
+ import { clientPage } from '@wildshard/sdk/internal/clientPage';
8
+ import { assertConfigBoundary } from '@wildshard/sdk/configBoundary';
9
+ import { createProjectGeneration, finishProjectGeneration, isProjectGenerator, type ProjectGenerationContext, type ProjectGenerationInputRoot } from '@wildshard/sdk/projectGeneration';
10
+ // oxlint-disable-next-line import/no-nodejs-modules -- The author CLI verifies and writes local build products.
11
+ import { cpSync, existsSync, readdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
12
+ // oxlint-disable-next-line import/no-nodejs-modules -- Resolve source assets inside the author project.
13
+ import { join, resolve, sep } from 'node:path';
14
+ // oxlint-disable-next-line import/no-nodejs-modules -- Build phase diagnostics belong only to the CI compiler process.
15
+ import process from 'node:process';
16
+ import { bundle } from '@wildshard/sdk/internal/bundle';
17
+ import ts from '@typescript/typescript6';
18
+ import { parseShardfile, type Shardfile } from '@wildshard/format/shardSchema';
19
+ import { preflightAssetGraph, offlineMemoryAdmission, prepareAssetDecoders } from "@wildshard/format/shardfileAssets";
20
+ import { preflightDeclaredCosts } from '@wildshard/format/assetAdmission';
21
+ import { preflightShardfile } from '@wildshard/format/preflight';
22
+
23
+ import { readBoundedFile } from '@wildshard/sdk/sourceReader';
24
+ import { encodeCanonicalJson, hashImmutableBytes } from '@wildshard/sdk/immutable';
25
+ import { withAssetOwner } from '@wildshard/sdk/internal/assetScope';
26
+ import { hashAssetBytes } from '@wildshard/sdk/assetHandle';
27
+
28
+ import { projectPerformancePolicy } from '@wildshard/sdk/internal/performancePolicy';
29
+ import { checkProjectRuntime } from '@wildshard/sdk/internal/runtimePerformance';
30
+ import { admitProduct, assertBuildSides, assertProductTargets, namedJsonReader, SIDE_SECTIONS } from '@wildshard/sdk/productOutput';
31
+ import { bakeAuthoredWorld } from '@wildshard/sdk/internal/bake/authoredWorld';
32
+ import { parseWorldSource } from '@wildshard/sdk/worldSource';
33
+ import { compileBehaviourSource } from '@wildshard/sdk/internal/behaviourSource';
34
+ import { buildBehaviourProject } from '@wildshard/sdk/buildBehaviour';
35
+ import { packProjectMap, generatedProjectMap, type ProjectMap } from '@wildshard/sdk/projectMap';
36
+ import { projectPlaceholders } from '@wildshard/sdk/bake/placeholders';
37
+ import type { ScriptAdmissionRows } from '@wildshard/format/scriptContract';
38
+ import { readCookInput, type CookInput } from '@wildshard/sdk/internal/cookInput';
39
+ import { audioEncodeLine, encodeMountAudio, readStereoMarks } from '@wildshard/sdk/internal/audioEncode';
40
+ import { AUTHOR_BUDGETS, AUTHOR_BUDGETS_MODULE, authorManifest, sceneCardUrls } from '@wildshard/sdk/internal/authorManifest';
41
+ import { discoveryDocument, discoveryUrl } from '@wildshard/sdk/internal/discoveryDocument';
42
+ import { outputScriptAdmissionRows, outputPlatformPayloads, clearOutputProduct, writeOutputProduct, type OutputProductOptions } from '@wildshard/sdk/outputProduct';
43
+ import { prepareProjectOutput, prepareProjectOutputInput, projectOutputContext, mergeProjectBlobs, projectMirrors, type PreparedProjectOutput } from '@wildshard/sdk/projectOutput';
44
+ import type { RuntimeMirror } from '@wildshard/sdk/runtimeMirrors';
45
+ import { proveRuntimeData, writeRuntimeFiles } from '@wildshard/sdk/outputRuntime';
46
+ import { readManifestSource, type ProjectManifestSource } from '@wildshard/sdk/projectManifest';
47
+ import { projectDecisionOptions } from '@wildshard/sdk/projectDecisions';
48
+ import { projectDecisionBudget } from '@wildshard/sdk/internal/projectPolicy';
49
+ import { nameBlob } from '@wildshard/sdk/blobs';
50
+ import { lowerMaterialGraphs } from '@wildshard/sdk/internal/materialGraphFiles';
51
+ import { parseDiscoveryValues, type DiscoveryValues } from '@wildshard/format/discoveryValues';
52
+ import { diagnosticNow } from '@wildshard/sdk/internal/diagnosticClock';
53
+ import { expandCreatureLayers } from '@wildshard/sdk/internal/creatureLayers';
54
+ import { expandCreatureHitVolumes } from '@wildshard/sdk/internal/creatureHitVolumes';
55
+ import { expandHarvestSource } from '@wildshard/sdk/internal/harvestSource';
56
+ import { expandJournalIconSource } from '@wildshard/sdk/internal/journalIconSource';
57
+ import { expandCombatSource } from '@wildshard/sdk/internal/combatSource';
58
+
59
+ /** Stable JSON encoding: sorted object keys, no timestamps or host paths. */
60
+ export function canonicalJson(value: unknown): string { return encodeCanonicalJson(value); }
61
+ /** Hash of immutable wire bytes; this is also their output filename. */
62
+ export function contentHash(bytes: Uint8Array): string { return hashImmutableBytes(bytes); }
63
+
64
+ /** Validate graph closure costs and actual bytes through the same admission used by the browser loader. */
65
+ export function validateProject(input: unknown, assets: ReadonlyMap<string, Uint8Array>, project?: string, scripts: ScriptAdmissionRows = [], sections?: ReadonlyMap<string, unknown>): Shardfile {
66
+ const source = parseShardfile(input, sections);
67
+ return admitProduct(source, assets, projectPerformancePolicy(project, source), scripts, sections);
68
+ }
69
+
70
+ async function authorModule(project: string, file: string): Promise<{ exports: Record<string, unknown>; hash: string; mapHash: string }> {
71
+ await prepareAssetDecoders();
72
+ // The compiled declaration executes here; only its returned data is emitted.
73
+ // Source-text inspection still enters the recorder's exact-content guard.
74
+ const built = await bundle({ entry: resolve(project, file), fileName: 'config', plugins: [{name:'wildshard-author-execution',api:{wildshardInputIdentity:'execution'}}], external: [/^node:/u, 'assemblyscript/dist/asc.js'], codeSplitting: false });
75
+ const chunks = built.output.filter((out) => out.type === 'chunk');
76
+ if (chunks.length !== 1) throw new Error('config must bundle as one module');
77
+ const chunk = chunks[0]; if (chunk === undefined) throw new Error('config chunk missing');
78
+ assertConfigBoundary([...chunk.imports, ...chunk.dynamicImports]);
79
+ const loaded: unknown = await executeBundle(generationRecipes(chunk.code), project);
80
+ if (typeof loaded !== 'object' || loaded === null) throw new Error('Author module has no exports');
81
+ // Bundler source-location comments change when an author moves a project.
82
+ // Parse before dropping comments so literal text remains part of identity.
83
+ const syntax = ts.createSourceFile('config.js', chunk.code, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
84
+ const executable = ts.createPrinter({ removeComments: true, newLine: ts.NewLineKind.LineFeed }).printFile(syntax);
85
+ return { exports: Object.fromEntries(Object.entries(loaded)), hash: contentHash(new TextEncoder().encode(chunk.code)), mapHash: contentHash(new TextEncoder().encode(executable)) };
86
+ }
87
+
88
+ /** GR9: a declared output's build program (`programs` in shard.config.ts, keyed by slug), if the folder has one for it. */
89
+ function outputProgram(loaded: Record<string, unknown>, output: string): ((ctx: ProjectGenerationContext) => unknown) | undefined {
90
+ const programs = loaded['programs'];
91
+ if (programs === undefined) return undefined;
92
+ if (typeof programs !== 'object' || programs === null) throw new Error('config programs must map output slugs to build functions');
93
+ const program: unknown = Object.hasOwn(programs, output) ? Reflect.get(programs, output) : undefined;
94
+ if (program !== undefined && !isProjectGenerator(program)) throw new Error(`config program for ${output} must be a build function`);
95
+ return program;
96
+ }
97
+
98
+ /** SF88g: one declared output of a source folder that emits several products (`outputs` in shard.config.ts, keyed by slug). */
99
+ function outputDeclaration(loaded: Record<string, unknown>, output: string): unknown {
100
+ const outputs = loaded['outputs'];
101
+ if (typeof outputs !== 'object' || outputs === null || !Object.hasOwn(outputs, output)) throw new Error(`config declares no output ${output}`);
102
+ return Reflect.get(outputs, output);
103
+ }
104
+
105
+ async function projectModule(project: string, decisionLegacyLines?: number, selected?: string, mapSourceHash?: string, inputRoots: readonly ProjectGenerationInputRoot[] = []): Promise<{ map: Awaited<ReturnType<typeof generatedProjectMap>> | undefined; discovery: DiscoveryValues | undefined; shard: Shardfile; commons: unknown; baked: ReadonlyMap<string, Uint8Array>; output: PreparedProjectOutput; mirrors: readonly RuntimeMirror[] }> {
106
+ const program = await authorModule(project, 'shard.config.ts'), loaded = program.exports;
107
+ if (!('default' in loaded)) throw new Error('config has no default export');
108
+ if ('generate' in loaded && typeof loaded['generate'] !== 'function') throw new Error('config generate export must be a build function');
109
+ let declaration: unknown = selected === undefined ? loaded['generate'] ?? loaded['default'] : outputDeclaration(loaded, selected);
110
+ let shard: Shardfile;
111
+ const baked = new Map<string, Uint8Array>(), root = realpathSync(project);
112
+ const sidecarModule = existsSync(resolve(project, 'generators/output.ts')) ? await authorModule(project, 'generators/output.ts') : undefined;
113
+ // Config and sidecar share pending work. Each bundled callback carries its
114
+ // own recipe; the complete identity remains a safe fallback for dynamic calls.
115
+ const generation = createProjectGeneration(project, contentHash(new TextEncoder().encode(canonicalJson({
116
+ program: program.hash, output: selected ?? null, ...(sidecarModule === undefined ? {} : { sidecar: sidecarModule.hash }),
117
+ }))), baked, undefined, inputRoots, selected ?? 'default');
118
+ let generationSucceeded = false;
119
+ try {
120
+ let generatedOutput: unknown, map: Awaited<ReturnType<typeof generatedProjectMap>> | undefined;
121
+ let discovery: DiscoveryValues | undefined;
122
+ // GR9: a selected output's build program supplies its world GLB bytes and its map lattice
123
+ let programWorld: Uint8Array | undefined;
124
+ const outputBuild = selected === undefined ? undefined : outputProgram(loaded, selected);
125
+ if (outputBuild !== undefined) {
126
+ const result: unknown = await outputBuild(generation);
127
+ if (typeof result !== 'object' || result === null || Object.keys(result).some(key => key !== 'world' && key !== 'map')) throw new Error('Output program returns only world and map');
128
+ if ('world' in result) {
129
+ if (!(result.world instanceof Uint8Array)) throw new Error('Output program world must be GLB bytes');
130
+ programWorld = result.world;
131
+ }
132
+ if ('map' in result) map = await generatedProjectMap(result.map, mapSourceHash ?? program.mapHash);
133
+ }
134
+ if (isProjectGenerator(declaration)) {
135
+ declaration = await declaration(generation);
136
+ if (typeof declaration === 'object' && declaration !== null && 'shard' in declaration) {
137
+ if (!('output' in declaration) || Object.keys(declaration).some(key => !['shard', 'output', 'map', 'discovery'].includes(key))) throw new Error('Generated project requires shard, output and optional map/discovery');
138
+ if ('map' in declaration) map = await generatedProjectMap(declaration.map, mapSourceHash ?? program.mapHash);
139
+ if ('discovery' in declaration) discovery = parseDiscoveryValues(declaration.discovery);
140
+ generatedOutput = declaration.output;
141
+ if (generatedOutput === undefined) throw new Error('Generated project output is absent');
142
+ declaration = declaration.shard;
143
+ }
144
+ }
145
+ const sourcePath = (path: string): string => {
146
+ const resolved = realpathSync(resolve(root, path));
147
+ if (!resolved.startsWith(`${root}${sep}`)) throw new Error('Authored source resolves outside the author project'); return resolved;
148
+ };
149
+ if ('behaviour' in loaded) {
150
+ const compiled = await compileBehaviourSource(loaded['behaviour'], declaration, path => new TextDecoder('utf-8', { fatal: true }).decode(readBoundedFile(sourcePath(path), 1_000_000)));
151
+ declaration = compiled.declaration;
152
+ for (const [hash, bytes] of compiled.assets) baked.set(hash, bytes);
153
+ }
154
+ const sidecar = sidecarModule?.exports;
155
+ if (sidecar !== undefined && ('output' in loaded || !('output' in sidecar))) throw new Error('Output sidecar requires one unambiguous output export');
156
+ if (generatedOutput !== undefined && (sidecar !== undefined || 'output' in loaded)) throw new Error('Generated project requires one unambiguous output declaration');
157
+ let sidecarOutput = sidecar?.['output'];
158
+ const prepareOutput = sidecar?.['prepareOutput'];
159
+ if (prepareOutput !== undefined) {
160
+ if (!isProjectGenerator(prepareOutput) || sidecarModule === undefined) throw new Error('Output preparation must be a build function');
161
+ sidecarOutput = await prepareOutput(generation);
162
+ }
163
+ const outputInput = prepareProjectOutputInput(generatedOutput ?? (sidecar === undefined ? loaded['output'] : sidecarOutput));
164
+ const sections = projectOutputContext(outputInput);
165
+ // D74: inline material graphs become content-addressed graph files of the closure before any admission reads them
166
+ const lowered = lowerMaterialGraphs(declaration);
167
+ declaration = lowered.declaration;
168
+ for (const [hash, bytes] of lowered.assets) baked.set(hash, bytes);
169
+ if (typeof declaration === 'object' && declaration !== null && 'world' in declaration) {
170
+ const world = parseWorldSource(declaration.world);
171
+ const product = await bakeAuthoredWorld(declaration, programWorld ?? readBoundedFile(sourcePath(world.glb), 256_000_000), hash => baked.get(hash), sections);
172
+ shard = product.shard;
173
+ for (const [hash, bytes] of product.assets) baked.set(hash, bytes);
174
+ } else shard = parseShardfile(declaration, sections);
175
+ checkProjectRuntime(project, projectPerformancePolicy(project, shard), undefined, shard.identity);
176
+ // GR6: an output sidecar may also build the project's map lattice (`prepareMap(ctx)` → `{ pixels, name? }`), as a
177
+ // source program returning `map` does; one producer of the map only
178
+ const prepareMap = sidecar?.['prepareMap'];
179
+ if (prepareMap !== undefined) {
180
+ if (!isProjectGenerator(prepareMap)) throw new Error('Map preparation must be a build function');
181
+ if (map !== undefined) throw new Error('Generated project declares its map twice');
182
+ map = await generatedProjectMap(await prepareMap(generation), mapSourceHash ?? program.mapHash);
183
+ }
184
+ // A sidecar may compute finite discovery data through the same explicit input context.
185
+ const prepareDiscovery = sidecar?.['prepareDiscovery'];
186
+ if (prepareDiscovery !== undefined) {
187
+ if (!isProjectGenerator(prepareDiscovery)) throw new Error('Discovery preparation must be a build function');
188
+ if (discovery !== undefined) throw new Error('Generated project declares its discovery twice');
189
+ discovery = parseDiscoveryValues(await prepareDiscovery(generation));
190
+ }
191
+ shard = mergeProjectSections(shard, sidecar?.['sections'], sections);
192
+ const output = await prepareProjectOutput(project, outputInput, { source: shard, options: projectDecisionOptions(loaded['buildOptions'], projectDecisionBudget(project, decisionLegacyLines)) });
193
+ // The CLI-only sidecar may declare the runtime/const.ts mirrors too (a browser config cannot import data/ values).
194
+ if (sidecar !== undefined && 'mirrors' in loaded && 'mirrors' in sidecar) throw new Error('Runtime mirrors declared by both the config and its output sidecar');
195
+ const mirrors = projectMirrors('mirrors' in loaded ? loaded['mirrors'] : sidecar !== undefined && 'mirrors' in sidecar ? sidecar['mirrors'] : undefined);
196
+ if (mapSourceHash !== undefined && map === undefined) throw new Error('Generated map source identity requires a generated map');
197
+ generationSucceeded = true;
198
+ return { map, discovery, shard, commons: 'commons' in loaded ? loaded['commons'] : undefined, baked, output, mirrors };
199
+ } finally { await finishProjectGeneration(generation, generationSucceeded); }
200
+ }
201
+
202
+ /** Compile authored geometry and read its remaining immutable inputs without writing hashes into the author folder. */
203
+ export async function readProjectAssets(project: string, map?: ProjectMap, manifestSource?: ProjectManifestSource, options: { decisionLegacyLines?: number; output?: string; mapSourceHash?: string } = {}): Promise<{ shard: Shardfile; assets: Map<string, Uint8Array>; output: Omit<OutputProductOptions, 'runtime'>; mirrors: readonly RuntimeMirror[] }> {
204
+ const loaded = await withAssetOwner(() => projectModule(project, options.decisionLegacyLines, options.output, options.mapSourceHash, manifestSource?.imageRoots)), pinned = new Map(pinnedCommons(loaded.commons, loaded.shard, project));
205
+ for (const [hash, bytes] of loaded.baked) pinned.set(hash, bytes);
206
+ for (const [hash, bytes] of loaded.output.assets) {
207
+ const previous = pinned.get(hash);
208
+ if (previous !== undefined && hashAssetBytes(previous) !== hashAssetBytes(bytes)) throw new Error('Output asset conflicts with baked input');
209
+ pinned.set(hash, bytes);
210
+ }
211
+ const sections = outputPlatformPayloads(loaded.output.options.platform);
212
+ const level = manifestSource === undefined || manifestSource.file === undefined && loaded.shard.manifest === undefined ? undefined : await readManifestSource(manifestSource, loaded.shard.manifest, loaded.map?.map.bytes);
213
+ if (level !== undefined && loaded.shard.manifest !== undefined && canonicalJson(loaded.shard.manifest) !== canonicalJson(level.authored)) throw new Error('Authored manifest differs from configured level metadata');
214
+ const source = level === undefined ? loaded.shard : parseShardfile({ ...loaded.shard, manifest: level.manifest }, sections);
215
+ if (map !== undefined && loaded.map !== undefined) throw new Error('Build map and generated map cannot compete');
216
+ const selectedMap = loaded.map?.map ?? map, packed = selectedMap === undefined ? undefined : packProjectMap(source, selectedMap, sections);
217
+ if (packed !== undefined && selectedMap !== undefined) pinned.set(packed.hash, selectedMap.bytes);
218
+ const journal = expandJournalIconSource(packed?.shard ?? source, sections), shard = journal.shard;
219
+ printSpawnWarnings(shard);
220
+ const mapBlobs = loaded.map?.name === undefined ? [] : [nameBlob(loaded.map.name, 'image', loaded.map.map.bytes)];
221
+ // Explicit authored hints retain their positions; automatic UI hints never duplicate them or commons.
222
+ const declaredLate = new Set([...(shard.late ?? []), ...(loaded.output.late ?? [])].map(row => row.hash)),
223
+ existingFiles = new Set(shard.files.map(row => row.hash)), libraryRoots = new Set(shard.library);
224
+ const late = [...loaded.output.late ?? [], ...(level?.late ?? []).filter(row => !declaredLate.has(row.hash) && !shard.requires.commons.includes(row.hash)
225
+ && (!existingFiles.has(row.hash) || libraryRoots.has(row.hash)))];
226
+ const merged = mergeProjectBlobs(shard, pinned, [...loaded.output.blobs, ...mapBlobs, ...journal.blobs, ...(level?.blobs ?? [])], loaded.output.options.namedFiles, late, sections);
227
+ return { shard: merged.shard, assets: projectAssets(project, merged.shard, 'project', merged.assets),
228
+ output: { ...loaded.output.options, namedFiles: merged.namedFiles, ...(loaded.discovery === undefined ? {} : { discovery: loaded.discovery }) }, mirrors: loaded.mirrors };
229
+ }
230
+
231
+ function pinnedCommons(input: unknown, source: Shardfile, project: string): ReadonlyMap<string, Uint8Array> | undefined {
232
+ if (input === undefined) return undefined;
233
+ preflightDeclaredCosts(source, offlineMemoryAdmission(projectPerformancePolicy(project, source)));
234
+ if (typeof input !== 'object' || input === null || !('catalogue' in input) || !('assets' in input)) throw new Error('Build-only commons export needs a compiled catalogue');
235
+ const catalogue = input.catalogue;
236
+ if (typeof catalogue !== 'object' || catalogue === null || !('format' in catalogue) || catalogue.format !== 'wildshard.commons' || !('version' in catalogue) || catalogue.version !== 0 || !(input.assets instanceof Map)) throw new Error('Unsupported build-only commons catalogue');
237
+ const assets = new Map<string, Uint8Array>();
238
+ for (const hash of source.requires.commons) {
239
+ const bytes: unknown = input.assets.get(hash);
240
+ if (!(bytes instanceof Uint8Array) || bytes.length !== source.requires.commonsWire[hash] || hashAssetBytes(bytes) !== hash) throw new Error('Pinned commons export misses or changes a required asset');
241
+ assets.set(hash, bytes);
242
+ }
243
+ return assets;
244
+ }
245
+ /** Preflight and read bounded immutable files from an author project or flat built product. */
246
+ export function projectAssets(project: string, shard: Shardfile, layout: 'project' | 'product' = 'project', pinned?: ReadonlyMap<string, Uint8Array>): Map<string, Uint8Array> {
247
+ preflightShardfile(shard); preflightAssetGraph(shard);
248
+ preflightDeclaredCosts(shard, offlineMemoryAdmission(projectPerformancePolicy(project, shard)));
249
+ assertProductTargets(shard, projectPerformancePolicy(project, shard));
250
+ const read = (hash: string, size: number, folder: string): Uint8Array => {
251
+ const bytes = pinned?.get(hash) ?? readBoundedFile(resolve(project, layout === 'project' ? folder : '.', hash), size);
252
+ if (bytes.length !== size) throw new Error('Project asset differs from its declared wire size'); return bytes;
253
+ };
254
+ return new Map([...shard.files.map((f) => [f.hash, read(f.hash, f.compressed, 'assets')] as const), ...shard.requires.commons.map((h) => [`commons:${h}`, read(h, shard.requires.commonsWire[h] ?? 0, 'commons')] as const)]);
255
+ }
256
+ /**
257
+ * Build a deterministic shard.json, immutable files and the distributed normal client when present; a shardfile with a
258
+ * terrain gains its far / near placeholders when `placeholders` is set (the CLI's default).
259
+ */
260
+ export async function buildProject(project: string, output?: string, options: { decisionLegacyLines?: number; output?: string; outputFormat?: 2; manifest?: ProjectManifestSource; copyRuntime?: boolean; devserver?: boolean; client?: string | null; map?: ProjectMap; mapSourceHash?: string; placeholders?: boolean; admit?: (shard: Shardfile, assets: ReadonlyMap<string, Uint8Array>, policy: 'warn' | 'refuse', sections: ReadonlyMap<string, unknown>) => Promise<void> } = {}): Promise<Shardfile> {
261
+ let phaseStarted = diagnosticNow();
262
+ const phase = (name: string): void => {
263
+ const now = diagnosticNow();
264
+ if (process.env['GITHUB_ACTIONS'] === 'true') console.info(`author timing: ${JSON.stringify({ pid: process.pid, phase: name, product: options.output ?? project, seconds: Number(((now - phaseStarted) / 1000).toFixed(3)) })}`);
265
+ phaseStarted = diagnosticNow();
266
+ };
267
+ await buildBehaviourProject(project); phase('behaviour-compile');
268
+ const loaded = await readProjectAssets(project, options.map, options.manifest, options), assets = loaded.assets;
269
+ phase('project-read');
270
+ // SERVER-PARITY SS8: a kind or script whose side has no half to run it refuses here, one plain line each, before any write.
271
+ assertBuildSides(outputPlatformPayloads(loaded.output.platform, SIDE_SECTIONS), namedJsonReader(loaded.output.namedFiles ?? [], assets));
272
+ // G348: a shardfile with a terrain gets its far and near placeholders from its own terrain, tiles and look (`wildshard
273
+ // build` asks for them; existing product builds keep theirs in the repo bake until the grid reads `near`)
274
+ // a static import: the author CLI must bundle to one module (scripts/wildshard.mjs); the bakers' closure stays
275
+ // renderer-free (the Node sim proofs import this module under the renderer-denying loader)
276
+ const sections = outputPlatformPayloads(loaded.output.platform);
277
+ const creatures = expandCreatureHitVolumes(expandCreatureLayers(loaded.shard, console.warn, sections), assets);
278
+ const expanded = expandCombatSource(expandHarvestSource(creatures, console.warn, sections), console.warn, sections);
279
+ const shard = validateProject(options.placeholders === true ? await projectPlaceholders(expanded, assets) : expanded, assets, project, outputScriptAdmissionRows(loaded.output.platform), sections);
280
+ phase('asset-admission');
281
+ // The decision rows travel with the moves they bind, so a headless admission resolves the same registries as the build.
282
+ await options.admit?.(shard, assets, projectPerformancePolicy(project, shard), outputPlatformPayloads(loaded.output.platform));
283
+ phase('simulation-admission');
284
+ const destination = output ?? resolve(shardOutputRoot(project), 'public/shardfiles', shard.identity.slug);
285
+ const clientPlan = shard.runtime !== null;
286
+ if (options.copyRuntime === true || clientPlan) {
287
+ const root = realpathSync(project), target = resolve(destination);
288
+ if (target === root || target.startsWith(`${root}${sep}`) || root.startsWith(`${target}${sep}`)) throw new Error('Runtime output must be separate from its author project');
289
+ }
290
+ clearOutputProduct(destination);
291
+ let descriptor: ReturnType<typeof writeOutputProduct>;
292
+ try {
293
+ const runtime = options.copyRuntime === true || clientPlan ? writeRuntimeFiles(project, destination) : undefined;
294
+ const encoded = await encodedCookInput(project, shard.identity.slug);
295
+ const cook = await withDiscovery(project, shard.manifest ?? options.manifest?.composed ?? authorManifest(shard, sceneCardUrls(project, shardFolderName(project))), loaded.output.discovery, encoded?.input, assets);
296
+ descriptor = writeOutputProduct(shard, assets, destination, { ...loaded.output, ...(runtime === undefined ? {} : { runtime }), ...(cook === undefined ? {} : { cook }) });
297
+ assertNoRenamedAudioNames(destination, encoded?.renamed ?? new Map());
298
+ phase('product-write');
299
+ // AUDIO AU18's engine music line moved to `wildshard check`'s validate step (SDK-SPLIT SP7b): naming engine music
300
+ // reads the engine's tables, and the build never loads the engine; the cook refuses a name the engine lacks too.
301
+ if (runtime !== undefined) proveRuntimeData(destination, descriptor, loaded.mirrors);
302
+ phase('runtime-proof');
303
+ } catch (error) { clearOutputProduct(destination); throw error; }
304
+ const directory = import.meta.dirname;
305
+ const clientFolder = options.devserver === true ? 'client-devserver' : 'client';
306
+ const client = options.client === null ? undefined : options.client ?? [resolve(directory, clientFolder), resolve(directory, 'dist', clientFolder)].find((path) => existsSync(resolve(path, 'index.html')));
307
+ if (client !== undefined) {
308
+ cpSync(client, destination, { recursive: true });
309
+ const json = canonicalJson(descriptor).replaceAll('<', String.raw`\u003c`);
310
+ const recorded = existsSync(resolve(destination, 'programs', `${shard.identity.slug}.json`));
311
+ writeFileSync(resolve(destination, 'index.html'), clientPage(readFileSync(resolve(destination, 'index.html'), 'utf8'), json, shard.identity.slug, recorded));
312
+ }
313
+ return shard;
314
+ }
315
+ /** AUDIO AU7: the cook input with its source recordings encoded to AU5's targets, and the before and after MB printed. */
316
+ async function encodedCookInput(project: string, slug: string): Promise<{ readonly input: CookInput; readonly renamed: ReadonlyMap<string, string> } | undefined> {
317
+ const input = readCookInput(project, slug);
318
+ if (input === undefined) return undefined;
319
+ const { mounts, stats, encoder, renamed } = await encodeMountAudio(input.mounts, { stereo: readStereoMarks(project) });
320
+ if (stats.files > 0) console.info(audioEncodeLine(slug, stats, encoder));
321
+ // AU21: a name the shard's own JSON does not hold (the engine's piano music.json names its island and pine slots) moves
322
+ // with the next engine pin of this product.
323
+ for (const [from, to] of renamed) console.info(`audio: ${from} is served as ${to.slice(to.lastIndexOf('/') + 1)} (its encoded bytes' hash)`);
324
+ return { input: { ...input, mounts }, renamed };
325
+ }
326
+ /** AU21: the written product names no recording by the name the encode retired (its sections, code or a JSON mount the
327
+ * rewrite missed), so nothing reads a URL the product no longer serves. The recordings themselves are not read. */
328
+ export function assertNoRenamedAudioNames(destination: string, renamed: ReadonlyMap<string, string>): void {
329
+ if (renamed.size === 0) return;
330
+ const names = [...renamed.keys()].map(url => ({ url, name: Buffer.from(url.slice(url.lastIndexOf('/') + 1)) }));
331
+ for (const entry of readdirSync(destination, { recursive: true, withFileTypes: true })) {
332
+ if (!entry.isFile() || /\.(?:m4a|wav|flac|aiff?)$/u.test(entry.name)) continue;
333
+ const file = join(entry.parentPath, entry.name), bytes = readFileSync(file), stale = names.find(({ name }) => bytes.includes(name));
334
+ if (stale !== undefined) throw new Error(`audio: ${file.slice(destination.length + 1)} names ${stale.url}, which the build serves as ${renamed.get(stale.url) ?? ''} (AU21)`);
335
+ }
336
+ }
337
+ /** C3: a manifest's bindings go with the product, so a page needs nothing compiled to enter it: the packed level manifest, an
338
+ * output's composed one, which packs no images of its own, or for an author with neither, the plain one their shard implies. */
339
+ async function withDiscovery(project: string, manifest: unknown, values: DiscoveryValues | undefined, input: CookInput | undefined, assets: ReadonlyMap<string, Uint8Array>): Promise<CookInput | undefined> {
340
+ if (typeof manifest !== 'object' || manifest === null || !('slug' in manifest) || typeof manifest.slug !== 'string' || !('bindings' in manifest)) return input;
341
+ // A manifest's slug is its product's folder (`packManifestImages`).
342
+ const folder = manifest.slug, document = await discoveryDocument(folder, manifest, values, async (module, name) => {
343
+ if (module === AUTHOR_BUDGETS_MODULE) return AUTHOR_BUDGETS;
344
+ if (name === 'css') return readFileSync(resolve(project, module), 'utf8');
345
+ if (module.endsWith('.json')) return JSON.parse(readFileSync(resolve(project, module), 'utf8')) as unknown;
346
+ return (await authorModule(project, `${module.replace(/^\.\//u, '')}.ts`)).exports[name];
347
+ });
348
+ // Rows name their images where the author keeps them. A product holding those bytes serves them; the rest ride as mounts.
349
+ const mounts = new Map<string, Uint8Array>(), art = new Map<string, number>();
350
+ const packed = JSON.stringify(document).replaceAll(/"\/(src\/shards\/[^"]+(\.[a-z]+))"/gu, (row: string, path: string, extension: string) => {
351
+ if (!/^\.(?:jpe?g|png|webp|svg|hdr)$/u.test(extension)) return row;
352
+ // `/src/shards/<folder>/x` names x in this shard source, whether it sits there or at a single-shard repo's src/ (SA17).
353
+ const own = `src/shards/${shardFolderName(project)}/`;
354
+ const bytes = readFileSync(path.startsWith(own) ? resolve(project, path.slice(own.length)) : resolve(shardRepoRoot(project), path)), hash = hashAssetBytes(bytes), held = assets.has(hash);
355
+ const url = `/shardfiles/${folder}/blobs/image/${hash}${extension}`;
356
+ if (!held) mounts.set(url, bytes);
357
+ art.set(url, bytes.length);
358
+ return `"${url}"`;
359
+ });
360
+ for (const [, url, hash] of packed.matchAll(/"(\/shardfiles\/[^/"]+\/blobs\/image\/([a-f0-9]{64})\.[a-z0-9]+)"/gu)) {
361
+ const bytes = hash === undefined ? undefined : assets.get(hash);
362
+ if (url !== undefined && bytes !== undefined) art.set(url, bytes.length);
363
+ }
364
+ return {...input, mounts: [...input?.mounts ?? [], ...[...mounts].map(([url, bytes]) => ({url, bytes})),
365
+ {url: discoveryUrl(folder), bytes: new TextEncoder().encode(`${packed.slice(0, -1)},"art":${JSON.stringify(Object.fromEntries(art))}}`)}]};
366
+ }
367
+ /** Create the runtime-free source layout without replacing existing work. */
368
+ /** A bare shard source at `project` (`wildshard new --empty` writes the same one at a new repo's `src/`). */
369
+ export function newProject(project: string, slug: string): void { writeEmptyShardSource(project, slug); }
@@ -0,0 +1,64 @@
1
+ import { assertConfigBoundary } from '@wildshard/sdk/configBoundary';
2
+ // oxlint-disable-next-line import/no-nodejs-modules -- Author inputs must remain within the project.
3
+ import { realpathSync } from 'node:fs';
4
+ // oxlint-disable-next-line import/no-nodejs-modules -- Author inputs must remain within the project.
5
+ import { resolve, sep } from 'node:path';
6
+ import { executeBundle } from '@wildshard/sdk/executeBundle';
7
+ import { bundle } from '@wildshard/sdk/internal/bundle';
8
+ // oxlint-disable-next-line import/no-nodejs-modules -- Resolve the defining reader into the same author bundle.
9
+ import { fileURLToPath } from 'node:url';
10
+ import type { Object3D } from 'three';
11
+ import { readScene, type SceneDescription } from '@wildshard/sdk/scene';
12
+ import { confined, publishScene, type SynthResult } from '@wildshard/sdk/bake';
13
+
14
+ /** Inspect an ordinary three.js graph and publish canonical scene.json, with an immutable content-hash copy.
15
+ * Graph generation still executes on each synth; expensive producers use the verified native bake cache separately.
16
+ * No client, rendering, physics service, wire-format admission or generated source file is involved. */
17
+ export function synthScene(scene: Object3D, project: string, slug: string): SynthResult {
18
+ if (!/^[a-z][a-z0-9-]{0,127}$/u.test(slug)) throw new Error('Scene synth requires a bounded shard slug');
19
+ return publishScene(readScene(scene), project, slug);
20
+ }
21
+ /** Execute a local author config in Node and synthesize its named scene and identity exports.
22
+ * This transitional declaration composes real three.js objects; the existing default shardfile declaration is optional.
23
+ * Only the scene reader's supported features enter JSON; missing scenes refuse instead of synthesizing a fake world. */
24
+ export async function synthProject(project: string): Promise<SynthResult> {
25
+ const root = realpathSync(project), entry = confined(root, 'shard.config.ts');
26
+ const three = import.meta.resolve('three'), reader = fileURLToPath(import.meta.resolve('@wildshard/sdk/scene'));
27
+ // Reader and SDK declarations must share one module graph, not just the same three.js constructors.
28
+ const virtual = resolve(root, '.wildshard-synth-entry.ts');
29
+ const wrapper = `import * as input from ${JSON.stringify(entry)};
30
+ import { Object3D } from 'three';
31
+ import { readScene } from ${JSON.stringify(reader)};
32
+ if (!(input.scene instanceof Object3D)) throw new Error(typeof input.default?.describe === 'function'
33
+ ? 'synth takes the older scene form (shard.config.ts exports scene, a three.js Scene, and identity); this one is a defineShard shard, which needs no synth: wildshard check . builds it and wildshard watch . shows it'
34
+ : 'Scene config must export a real three.js scene (export const scene) and its identity (export const identity)');
35
+ if (typeof input.identity?.slug !== 'string') throw new Error('Scene config must export identity.slug');
36
+ export default { scene: readScene(input.scene), slug: input.identity.slug };`;
37
+ const built = await bundle({ entry: virtual, fileName: 'scene', target: 'esnext', platform: 'node', external: [/^node:/u, 'assemblyscript/dist/asc.js'],
38
+ plugins: [{ name: 'author-scene-three-identity', resolveId(id, importer) {
39
+ if (id === virtual) return virtual;
40
+ const author = importer?.startsWith(root + sep) === true && !importer.startsWith(resolve(root, 'node_modules') + sep);
41
+ if (author && (/^@wildshard\/(?:game|engine)\//u.test(id) || /^@wildshard\/(?:sdk|sharddev)\/runtime\//u.test(id))) throw new Error('Scene synth cannot import trusted runtime');
42
+ return id === 'three' ? { id: three, external: true } : null;
43
+ }, load(id) {
44
+ if (id === virtual) return wrapper;
45
+ const file = id.split('?')[0] ?? id;
46
+ if (!file.startsWith(root + sep)) return null;
47
+ const relative = file.slice(root.length + 1).split(sep).join('/');
48
+ if (relative.startsWith('node_modules/')) return null;
49
+ if (relative !== 'shard.config.ts' && !/^(?:generators|data|quests|assets|behaviour|blender)\//u.test(relative)) throw new Error('Scene synth source is outside authoring folders');
50
+ if (realpathSync(file) !== file) throw new Error('Scene synth author source must not be a symlink');
51
+ return null;
52
+ } }],
53
+ });
54
+ const chunks = built.output.filter(output => output.type === 'chunk'), chunk = chunks[0];
55
+ if (chunks.length !== 1 || chunk === undefined) throw new Error('Scene config must compile as one module');
56
+ assertConfigBoundary([...chunk.imports, ...chunk.dynamicImports]);
57
+ const loaded: unknown = await executeBundle(chunk.code, root);
58
+ if (typeof loaded !== 'object' || loaded === null || !('default' in loaded)) throw new Error('Scene config produced no reader result');
59
+ const data = loaded.default;
60
+ if (typeof data !== 'object' || data === null || !('slug' in data) || typeof data.slug !== 'string'
61
+ || !('scene' in data) || typeof data.scene !== 'object' || data.scene === null || !('version' in data.scene) || data.scene.version !== 1) throw new Error('Invalid scene reader result');
62
+ // Only the defining readScene inside this trusted author bundle creates this result. Wire admission is separate.
63
+ return publishScene(data.scene as SceneDescription, root, data.slug);
64
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # @wildshard/build
2
-
3
- Placeholder. The first real release publishes from CI (project-wildshard/sharddev, npm-publish.yml). Do not install 0.0.0.