@wildshard/sdk 0.2.6 → 0.2.7

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.
@@ -4,15 +4,16 @@
4
4
  // content it shows. `wildshard build` refuses a cut whose stamp no longer matches the content (src/cli/hero/hero.ts).
5
5
  // Jake, 2026-11-12 17:14 Cancún: "you have to update the hero images for the templates."
6
6
  //
7
- // Serve the candidate first (engine: `scripts/serve-build.sh --shard <slug>`), and run this from the shard project
8
- // root. Headless Chromium on the real GPU (Metal), never a visible window. The view is `hero.json`'s `camera`
7
+ // Serve the candidate first: `wildshard dev .` (SA17; its page enters the shard by `?skipintro`), or an engine build
8
+ // (engine: `scripts/serve-build.sh --shard <slug>`), and run this from the shard project root. A new project's
9
+ // generated `data:` card gets files of its own: `card/<slot>.jpg`, and manifest.json names them after the capture. Headless Chromium on the real GPU (Metal), never a visible window. The view is `hero.json`'s `camera`
9
10
  // ({ pos: [x,y,z], look: [x,y,z], fov, center }, engine scripts/hero-shots.mjs's view shape) when the shard declares
10
11
  // one, else the player's own spawn view. Sizes: thumb 640x360, portrait 804x1626, landscape 1600x900.
11
12
  //
12
13
  // `wildshard hero <shard-dir> --stamp-existing` captures nothing: it stamps the hero files already there as showing
13
14
  // the content now. It exists for a shard repo that gains this check with curated heroes and no stamp. WARNING: use it
14
15
  // only when those images match the current content; a wrong stamp hides a stale hero until the next content change.
15
- import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
16
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
16
17
  import { basename, dirname, join, resolve } from 'node:path';
17
18
  import { heroSlotFiles, writeHeroStamp } from '../src/cli/hero/stamp.ts';
18
19
  import { stampExistingHero } from '../src/cli/hero/adopt.ts';
@@ -40,11 +41,35 @@ function servedName(shard) {
40
41
  return String(JSON.parse(readFileSync(join(shard, 'manifest.json'), 'utf8')).name);
41
42
  }
42
43
 
43
- /** Enter the shard the way a player does: SHARD SELECT, its card, ENTER WORLD (hidden shards are Developer cards). */
44
+ /** The served root, so the URL `wildshard dev` prints (`…/?skipintro`) works as `--base` as well as a bare origin. */
45
+ function servedRoot(base) {
46
+ const url = new URL(base);
47
+ url.search = ''; url.hash = '';
48
+ return url.href.replace(/\/+$/u, '');
49
+ }
50
+
51
+ /** True when `base` is a `wildshard dev` server: it answers its reload poll, `/__wildshard_dev_revision`. */
52
+ async function isDevServer(base) {
53
+ try {
54
+ const response = await fetch(`${base.replace(/\/+$/u, '')}/__wildshard_dev_revision`, { cache: 'no-store' });
55
+ return response.ok && typeof (await response.json()).revision === 'number';
56
+ } catch { return false; }
57
+ }
58
+
59
+ /** Enter the shard the way a player does: SHARD SELECT, its card, ENTER WORLD (hidden shards are Developer cards).
60
+ * A `wildshard dev` page serves this shard alone and enters it by `?skipintro`; its SHARD SELECT lists engine's. */
44
61
  async function enter(page, base, name, log) {
45
- const url = `${base.replace(/\/+$/u, '')}/?mute=1&sw=0&tier=desktop&nolock=1&perf=0`;
46
- log(`hero: loading ${url}, card "${name}"`);
62
+ const dev = await isDevServer(base);
63
+ const url = `${base.replace(/\/+$/u, '')}/?${dev ? 'skipintro&' : ''}mute=1&sw=0&tier=desktop&nolock=1&perf=0`;
64
+ log(dev ? `hero: loading ${url} (wildshard dev)` : `hero: loading ${url}, card "${name}"`);
47
65
  await page.goto(url, { waitUntil: 'load' });
66
+ if (!dev) await selectCard(page, base, name);
67
+ await page.waitForFunction(() => Boolean(window.__wildshard?.world?.hud?.entered && window.__wildshard?.world?.game) && document.querySelector('.ws-load') === null,
68
+ undefined, { timeout: 240000, polling: 500 });
69
+ if (await page.evaluate(() => window.__wildshard.world.hud.paused)) await page.keyboard.press('Escape');
70
+ }
71
+
72
+ async function selectCard(page, base, name) {
48
73
  await page.locator('.ws-main-select').click({ timeout: 120000 });
49
74
  await page.locator('.ws-menu-card').first().waitFor({ timeout: 60000 });
50
75
  const names = await page.evaluate(() => [...document.querySelectorAll('.ws-menu-card')].map(card => card.querySelector('b')?.textContent?.trim() ?? ''));
@@ -53,18 +78,20 @@ async function enter(page, base, name, log) {
53
78
  await page.evaluate(index => document.querySelector(`.ws-menu-dots i[data-i="${index}"]`)?.click(), at);
54
79
  await sleep(1000);
55
80
  await page.locator('.ws-menu-play').click();
56
- await page.waitForFunction(() => Boolean(window.__wildshard?.world?.hud?.entered && window.__wildshard?.world?.game) && document.querySelector('.ws-load') === null,
57
- undefined, { timeout: 240000, polling: 500 });
58
- if (await page.evaluate(() => window.__wildshard.world.hud.paused)) await page.keyboard.press('Escape');
59
81
  }
60
82
 
61
- export async function captureHero(shard, base, { name = servedName(shard), log = console.info } = {}) {
83
+ export async function captureHero(shard, given, { name = servedName(shard), log = console.info } = {}) {
84
+ const base = servedRoot(given);
62
85
  // Loaded here, so --stamp-existing needs no browser or engine to resolve.
63
86
  const [{ chromium }, { NAME_ASKED, saveFixture }, { KEYCHAIN_ARGS }] = await Promise.all([
64
87
  import('playwright'), import('@wildshard/engine/scripts/debug-settings.mjs'), import('./chromium-keychain.mjs')]);
65
- const files = await heroSlotFiles(shard);
66
- const missing = Object.keys(VIEWS).filter(slot => files[slot] === undefined);
67
- if (missing.length > 0) throw new Error(`${join(shard, 'manifest.json')}: card.${missing.join(', card.')} must name a file in the shard folder (e.g. /src/shards/${shardFolderName(shard)}/card/${missing[0]}.jpg), not a data: url`);
88
+ // A `data:` slot (new's generated card) is captured to card/<slot>.jpg and named in both card files after; any other
89
+ // slot must already name a file in the shard folder.
90
+ const files = { ...(await heroSlotFiles(shard)) }, card = JSON.parse(readFileSync(join(shard, 'manifest.json'), 'utf8')).card ?? {};
91
+ const missing = Object.keys(VIEWS).filter(slot => files[slot] === undefined && String(card[slot]).startsWith('data:'));
92
+ const unnamed = Object.keys(VIEWS).filter(slot => files[slot] === undefined && !missing.includes(slot));
93
+ if (unnamed.length > 0) throw new Error(`${join(shard, 'manifest.json')}: card.${unnamed.join(', card.')} must name a file in the shard folder (e.g. card/${unnamed[0]}.jpg)`);
94
+ for (const slot of missing) files[slot] = join(shard, 'card', `${slot}.jpg`);
68
95
  const stampFile = join(shard, 'hero.json');
69
96
  const camera = existsSync(stampFile) ? JSON.parse(readFileSync(stampFile, 'utf8')).camera : undefined;
70
97
  const errors = [], shots = {};
@@ -110,11 +137,23 @@ export async function captureHero(shard, base, { name = servedName(shard), log =
110
137
  } finally { await browser.close(); }
111
138
  if (errors.length > 0) throw new Error(`page errors during capture, nothing written: ${errors.slice(0, 3).join(' | ')}`);
112
139
  // Write every file, then the stamp, so a failed capture leaves the old hero and its old stamp.
140
+ if (missing.length > 0) mkdirSync(join(shard, 'card'), { recursive: true });
113
141
  for (const [slot, bytes] of Object.entries(shots)) {
114
142
  const partial = `${files[slot]}.partial`;
115
143
  try { writeFileSync(partial, bytes); renameSync(partial, files[slot]); } finally { rmSync(partial, { force: true }); }
116
144
  log(`hero: wrote ${files[slot]}`);
117
145
  }
146
+ if (missing.length > 0) {
147
+ const named = Object.fromEntries(missing.map(slot => [slot, `/src/shards/${shardFolderName(shard)}/card/${slot}.jpg`]));
148
+ // new writes the card twice, manifest.json and the reference world's data/card.json, and build refuses a pair that
149
+ // differs; so the slots move in both. Each file keeps its own layout (new writes them on one line).
150
+ for (const file of ['manifest.json', join('data', 'card.json')].map(name => join(shard, name)).filter(existsSync)) {
151
+ const text = readFileSync(file, 'utf8'), json = JSON.parse(text);
152
+ json.card = { ...json.card, ...named };
153
+ writeFileSync(file, `${/^\{\s*\n/u.test(text) ? JSON.stringify(json, null, 2) : JSON.stringify(json)}\n`);
154
+ log(`hero: ${file} card.${missing.join(', card.')} now name card/*.jpg`);
155
+ }
156
+ }
118
157
  return await writeHeroStamp(shard, { base, ...(camera === undefined ? {} : { camera }) });
119
158
  }
120
159
 
@@ -122,7 +161,7 @@ if (process.argv[1] !== undefined && resolve(process.argv[1]) === resolve(import
122
161
  const [dir, flag, base] = process.argv.slice(2);
123
162
  const adopt = flag === '--stamp-existing' && base === undefined;
124
163
  if (dir === undefined || (!adopt && (flag !== '--base' || base === undefined))) {
125
- console.error('usage: wildshard hero <source> --base <served-build-url> (serve the candidate first: engine scripts/serve-build.sh --shard <slug>)');
164
+ console.error('usage: wildshard hero <source> --base <served-build-url> (serve the candidate first: `wildshard dev .` prints its URL)');
126
165
  console.error(' wildshard hero <source> --stamp-existing WARNING: no capture; stamps the hero images already there as current.');
127
166
  console.error(' Use it ONLY when you have looked at those images and they show the current content; a wrong stamp hides a stale hero.');
128
167
  process.exit(2);
@@ -0,0 +1,57 @@
1
+ // SHARD-AUTHORING SA5 (J317): every @wildshard/sdk export is in one tier (lint/export-tiers.json): contract, rows,
2
+ // scripts, bake kit or internal. `exportTierProblems` names each unclassed export, stale row and unknown tier;
3
+ // `renderExportTiers` is docs/api/EXPORT-TIERS.md, the API doc that shows each export's tier.
4
+ // node scripts/export-tiers.mjs write docs/api/EXPORT-TIERS.md
5
+ // node scripts/export-tiers.mjs --check fail on a problem or a stale page
6
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
7
+ import { dirname, resolve } from 'node:path';
8
+ import { pathToFileURL } from 'node:url';
9
+
10
+ const ROOT = resolve(import.meta.dirname, '..');
11
+ export const TIERS = ['contract', 'rows', 'scripts', 'bake kit', 'internal'];
12
+ export const TIER_FILE = 'lint/export-tiers.json';
13
+ export const TIER_PAGE = 'docs/api/EXPORT-TIERS.md';
14
+
15
+ const readJson = (path) => JSON.parse(readFileSync(path, 'utf8'));
16
+ /** The package's exports and the tier file, read from `root`.
17
+ * @param {string} [root] @returns {{ exports: Record<string, unknown>, tiers: { tiers: Record<string, string>, exports: Record<string, string> } }} */
18
+ export function readExportTiers(root = ROOT) {
19
+ return { exports: readJson(resolve(root, 'package.json')).exports ?? {}, tiers: readJson(resolve(root, TIER_FILE)) };
20
+ }
21
+ /** One line per problem; empty when every export has exactly one known tier and every row names an export.
22
+ * @param {Record<string, unknown>} exports @param {{ tiers: Record<string, string>, exports: Record<string, string> }} tiers @returns {string[]} */
23
+ export function exportTierProblems(exports, tiers) {
24
+ const problems = [];
25
+ for (const tier of TIERS) if (typeof tiers.tiers?.[tier] !== 'string') problems.push(`tier "${tier}" has no description in ${TIER_FILE}`);
26
+ for (const tier of Object.keys(tiers.tiers ?? {})) if (!TIERS.includes(tier)) problems.push(`unknown tier "${tier}" in ${TIER_FILE}`);
27
+ for (const subpath of Object.keys(exports)) {
28
+ const tier = tiers.exports?.[subpath];
29
+ if (tier === undefined) problems.push(`unclassed export ${subpath}: give it a tier (${TIERS.join(', ')}) in ${TIER_FILE}`);
30
+ else if (!TIERS.includes(tier)) problems.push(`export ${subpath} has unknown tier "${tier}"`);
31
+ }
32
+ for (const subpath of Object.keys(tiers.exports ?? {})) if (!Object.hasOwn(exports, subpath)) problems.push(`${TIER_FILE} classes ${subpath}, which package.json does not export`);
33
+ return problems;
34
+ }
35
+ const specifier = (subpath) => `@wildshard/sdk${subpath === '.' ? '' : `/${subpath.slice(2)}`}`;
36
+ const target = (value) => (typeof value === 'string' ? value : JSON.stringify(value));
37
+ /** docs/api/EXPORT-TIERS.md: each tier, what it promises, and its exports with the file each resolves to.
38
+ * @param {Record<string, unknown>} exports @param {{ tiers: Record<string, string>, exports: Record<string, string> }} tiers @returns {string} */
39
+ export function renderExportTiers(exports, tiers) {
40
+ const sections = TIERS.map((tier) => {
41
+ const rows = Object.keys(exports).filter((subpath) => tiers.exports[subpath] === tier).sort();
42
+ return `## ${tier} (${rows.length})\n\n${tiers.tiers[tier]}\n\n| Export | Tier | File |\n|---|---|---|\n${rows.map((subpath) => `| \`${specifier(subpath)}\` | ${tier} | \`${target(exports[subpath])}\` |`).join('\n')}\n`;
43
+ });
44
+ return `# @wildshard/sdk exports, by tier\n\n<!-- generated by scripts/export-tiers.mjs from package.json exports and ${TIER_FILE}: do not edit -->\n\n${Object.keys(exports).length} exports. A shard project imports from contract, rows, scripts and the bake kit; internal may change in any release. A new export needs a row in \`${TIER_FILE}\` (\`test/export-tiers.test.ts\` fails without one); then run \`node scripts/export-tiers.mjs\`.\n\n${sections.join('\n')}`;
45
+ }
46
+
47
+ if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {
48
+ const { exports, tiers } = readExportTiers(ROOT), problems = exportTierProblems(exports, tiers);
49
+ if (problems.length > 0) { console.error(problems.join('\n')); process.exit(1); }
50
+ const page = renderExportTiers(exports, tiers), path = resolve(ROOT, TIER_PAGE);
51
+ if (process.argv.includes('--check')) {
52
+ let current = '';
53
+ try { current = readFileSync(path, 'utf8'); } catch { /* missing reads as stale */ }
54
+ if (current !== page) { console.error(`${TIER_PAGE} is stale: run node scripts/export-tiers.mjs`); process.exit(1); }
55
+ } else { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, page); }
56
+ console.info(`export tiers: ${Object.keys(exports).length} exports classed`);
57
+ }
@@ -0,0 +1,95 @@
1
+ #!/usr/bin/env node
2
+ // repo-kit's scratch folder maker (meta docs/plans/REPO-DISK-PLAN.md row DK3). One copy lives in repo-kit; every org
3
+ // repo and singleplayer carries a byte-identical copy at scripts/scratch-dir.mjs (DK8 checks the copies).
4
+ //
5
+ // node scripts/scratch-dir.mjs <task> "<purpose>"
6
+ //
7
+ // creates <repo>/tmp/<task>/ and tmp/<task>/.owner, then prints the folder's absolute path. .owner is JSON: the session
8
+ // id ($CLAUDE_SESSION_ID, else $CLAUDE_CODE_SESSION_ID, else the Codex lane name in $WS_LANE_NAME), the lane name, the
9
+ // herdr pane ($HERDR_PANE_ID), the start time and the purpose. DK4's SessionEnd hook removes the folders whose .owner
10
+ // names the ending session; a .keep file in the folder (one line: why to keep it) stops that and DK6's 3-day sweep.
11
+ //
12
+ // <task> is one plain folder name: letters, digits, '.', '_' and '-', not starting with '.', never containing '/' or
13
+ // '..'. The helper deletes nothing. It refuses a folder that already exists unless that folder's .owner names this
14
+ // same session (then it prints the path again), so it never takes over another lane's or an ownerless folder.
15
+ import { mkdirSync, readFileSync, rmdirSync, writeFileSync } from 'node:fs';
16
+ import { join, resolve } from 'node:path';
17
+ import { pathToFileURL } from 'node:url';
18
+
19
+ const ROOT = resolve(import.meta.dirname, '..');
20
+ const TASK = /^[A-Za-z0-9_-][A-Za-z0-9._-]*$/u;
21
+
22
+ /** Why a task name is refused, or null when it is a plain folder name.
23
+ * @param {string} task @returns {string | null} */
24
+ export function refuseTask(task) {
25
+ if (typeof task !== 'string' || task === '') return 'a task name is required';
26
+ if (task.includes('/') || task.includes('\\')) return `task "${task}" contains a path separator`;
27
+ if (task.includes('..')) return `task "${task}" contains ".."`;
28
+ if (task.length > 100) return `task "${task}" is longer than 100 characters`;
29
+ if (!TASK.test(task)) return `task "${task}" must be letters, digits, ".", "_" and "-", not starting with "."`;
30
+ return null;
31
+ }
32
+
33
+ /** The .owner record for a new folder.
34
+ * @param {string} task @param {string} purpose @param {NodeJS.ProcessEnv} env @param {Date} now */
35
+ export function ownerRecord(task, purpose, env, now) {
36
+ const lane = env.WS_LANE_NAME || null;
37
+ return {
38
+ task,
39
+ session: env.CLAUDE_SESSION_ID || env.CLAUDE_CODE_SESSION_ID || lane,
40
+ lane,
41
+ pane: env.HERDR_PANE_ID || null,
42
+ started: now.toISOString(),
43
+ purpose,
44
+ };
45
+ }
46
+
47
+ /** @param {string} path @returns {{session?: unknown} | null} */
48
+ function readOwner(path) {
49
+ try { return JSON.parse(readFileSync(path, 'utf8')); } catch { return null; }
50
+ }
51
+
52
+ /** Make <root>/tmp/<task>/ and its .owner; returns the folder's absolute path. Throws on a refused name, an empty
53
+ * purpose, or a folder that exists and is not this session's.
54
+ * @param {string} task @param {string} purpose
55
+ * @param {{root?: string, env?: NodeJS.ProcessEnv, now?: Date}} [options] */
56
+ export function scratchDir(task, purpose, { root = ROOT, env = process.env, now = new Date() } = {}) {
57
+ const refusal = refuseTask(task);
58
+ if (refusal) throw new Error(refusal);
59
+ if (typeof purpose !== 'string' || purpose.trim() === '') throw new Error('a purpose is required');
60
+ const tmp = join(resolve(root), 'tmp');
61
+ const dir = join(tmp, task);
62
+ const owner = ownerRecord(task, purpose.trim(), env, now);
63
+ mkdirSync(tmp, { recursive: true });
64
+ try {
65
+ mkdirSync(dir);
66
+ } catch (error) {
67
+ if (!(error instanceof Error && 'code' in error && error.code === 'EEXIST')) throw error;
68
+ const existing = readOwner(join(dir, '.owner'));
69
+ if (existing && owner.session && existing.session === owner.session) return dir;
70
+ throw new Error(existing
71
+ ? `${dir} already belongs to session ${String(existing.session)}; pick another task name`
72
+ : `${dir} already exists with no .owner; pick another task name`);
73
+ }
74
+ try {
75
+ writeFileSync(join(dir, '.owner'), `${JSON.stringify(owner, null, 2)}\n`, { flag: 'wx' });
76
+ } catch (error) {
77
+ rmdirSync(dir); // only the empty folder this call just made
78
+ throw error;
79
+ }
80
+ return dir;
81
+ }
82
+
83
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
84
+ const [task = '', purpose = '', ...rest] = process.argv.slice(2);
85
+ if (rest.length > 0 || task === '--help' || task === '-h') {
86
+ console.error('usage: node scripts/scratch-dir.mjs <task> "<purpose>"');
87
+ process.exit(2);
88
+ }
89
+ try {
90
+ console.log(scratchDir(task, purpose));
91
+ } catch (error) {
92
+ console.error(`scratch-dir: ${error instanceof Error ? error.message : String(error)}`);
93
+ process.exit(1);
94
+ }
95
+ }
@@ -84,6 +84,27 @@ export async function runWildshard(args) {
84
84
  folder: output?.slug ?? folder, ...(output !== undefined ? { composed: outputManifest(root, folder, output.row) } : existsSync(resolve(project, 'manifest.json')) ? { file: resolve(project, 'manifest.json') } : {}),
85
85
  imageRoots: [{ prefix: `/src/shards/${folder}/`, directory: project }, { prefix: '/assets/', directory: resolve(root, 'public/assets') }],
86
86
  };
87
+ // TS21: `check` on a folder that declares outputs (and no --output) checks each output with its own composed manifest,
88
+ // into <folder>/<slug> when a folder is named, and gives one verdict, as build-shards builds each output.
89
+ const declared = args[0] === 'check' && selected === undefined && project !== undefined && existsSync(resolve(project, 'shard.config.ts')) ? shardOutputs(root, folder) : null;
90
+ if (declared !== null) {
91
+ if (args.includes('--json')) throw new Error(`wildshard check: ${folder} declares ${declared.length} outputs; --json checks one: add --output=<slug>`);
92
+ const rest = args.slice(2), extra = rest.filter(arg => !arg.startsWith('--'));
93
+ if (extra.length > 1 || rest.some(arg => arg.startsWith('--'))) throw new Error('usage: wildshard check <source> [folder] [--json] [--output=<slug>]');
94
+ const [into] = extra, failed = [], before = process.exitCode;
95
+ for (const { slug } of declared) {
96
+ console.info(`== ${slug}`);
97
+ process.exitCode = undefined;
98
+ // A setup error (a missing manifest, a refused source) fails this output; the rest are still checked.
99
+ try { await runWildshard(['check', project, ...(into === undefined ? [] : [resolve(into, slug)]), `--output=${slug}`]); }
100
+ catch (error) { console.error(`${slug}: ${error instanceof Error ? error.message : String(error)}`); process.exitCode = 1; }
101
+ if (process.exitCode !== undefined && process.exitCode !== 0) failed.push(slug);
102
+ }
103
+ process.exitCode = before;
104
+ console.info(`check ${failed.length === 0 ? 'pass' : 'fail'}: ${declared.length} outputs${failed.length === 0 ? '' : `, failed: ${failed.join(', ')}`}`);
105
+ if (failed.length > 0) process.exitCode = 1;
106
+ return;
107
+ }
87
108
  const legacy = project === undefined ? undefined : decisionLegacyLines(root, folder);
88
109
  await (await runner)(args, { ...(legacy === undefined ? {} : { decisionLegacyLines: legacy }), ...(manifest === undefined ? {} : { manifest }), writeShardfile });
89
110
  }
@@ -20,9 +20,8 @@ Run each step from the project folder. Read the step's section first: it says wh
20
20
  instead where a step is not built yet.
21
21
 
22
22
  1. **new**: `wildshard new <dir>` started this repo. `GUIDE.md#1-the-loop`; every flag in `GUIDE.md#every-verb`.
23
- 2. **dev**: walk the shard on your machine. Not built yet (SA15): `GUIDE.md#walking-your-shard` says how to walk it
24
- today, and `GUIDE.md#4-what-reloads-under-dev` how `dev` will behave. Done when you have walked it, or know which
25
- way in needs the Wildshard team.
23
+ 2. **dev**: `wildshard dev .` serves the shard on localhost; open the URL it prints. `GUIDE.md#walking-your-shard`,
24
+ and what reloads on save in `GUIDE.md#4-what-reloads-under-dev`. Done when you have walked it.
26
25
  3. **check**: `wildshard check .` after every change. `GUIDE.md#1-the-loop`; what it measures in
27
26
  `GUIDE.md#3-budgets`. Done when the last line reads `check pass`.
28
27
  4. **hero**: capture a new hero after your last change to the world. `GUIDE.md#the-hero`, then step 1 of
@@ -23,13 +23,12 @@ guide heading with that anchor.
23
23
  These steps need `src/manifest.json`, which `wildshard new` writes for the default template only; without it, write
24
24
  down that the hero needs the Wildshard team.
25
25
 
26
- 1. **Real image files.** `manifest.json` and `data/card.json` must name the same image files inside the shard source,
27
- not the `data:` card `new` wrote; change both together (`GUIDE.md#2-the-shard-source`). Done when both point at
28
- files such as `card/thumb.jpg`.
29
- 2. **A served build carrying this exact shard source.** Today that needs an engine checkout
30
- (`GUIDE.md#walking-your-shard`). Done when you have its URL, or have written down that it needs the Wildshard team.
31
- 3. **Capture.** `wildshard hero . --base <url>` (`GUIDE.md#the-hero`). Done when `hero.json` and the three images are
32
- rewritten.
26
+ 1. **A served build carrying this exact shard source:** `wildshard dev .`, left running (`GUIDE.md#the-hero`). Done
27
+ when it prints its URL.
28
+ 2. **Capture.** `wildshard hero . --base <that url>` (`GUIDE.md#the-hero`). The `data:` card `new` wrote becomes
29
+ `card/thumb.jpg`, `card/portrait.jpg` and `card/landscape.jpg`, named in both `manifest.json` and
30
+ `data/card.json`. Done when `hero.json` and the three images are rewritten.
31
+ 3. **Stop `dev`** with Ctrl-C. Done when its port is free.
33
32
  4. **Look at all three images** with your own eyes or the Read tool: the shard, not a loading screen, a black frame or
34
33
  another shard. Done when each shows the current world.
35
34
  5. **Commit** the images and `hero.json` together (`GUIDE.md#uploading` step 2), then `wildshard check .`. Done at
@@ -43,8 +43,8 @@ Read `GUIDE.md#2-the-shard-source` before your first edit: it says what ships in
43
43
  6. **Check.** `wildshard check .` (`GUIDE.md#1-the-loop`). The report card measures draws, triangles, memory and
44
44
  download against their limits (`GUIDE.md#3-budgets`); a refusal names its fix, for example
45
45
  `GUIDE.md#budget-triangles` or `GUIDE.md#budget-download`. Done when the last line reads `check pass`.
46
- 7. **See it in the world.** Walk the shard where the model stands (`GUIDE.md#walking-your-shard`). Done when you have
47
- seen it there, or written down that walking needs the Wildshard team today.
46
+ 7. **See it in the world.** `wildshard dev .`, then walk to where the model stands (`GUIDE.md#walking-your-shard`).
47
+ Done when you have seen it there.
48
48
  8. **The hero.** The world changed, so before the next upload follow the `wildshard-goldens` skill
49
49
  (`GUIDE.md#the-hero`). Done when that skill's hero steps are done, or you have written down that this repo has no
50
50
  `manifest.json` card to capture.
package/src/cli/help.ts CHANGED
@@ -53,8 +53,8 @@ const VERBS: Readonly<Record<string, string>> = {
53
53
  hero: `hero <source> --base <served-build-url>
54
54
  Capture the shard's hero (thumb, portrait,
55
55
  landscape) in headless Chromium from a served build
56
- of this candidate, and stamp hero.json with its
57
- content
56
+ of this candidate (the URL \`wildshard dev .\` prints),
57
+ and stamp hero.json with its content
58
58
  hero <source> --stamp-existing
59
59
  No capture: stamp the hero images already in the
60
60
  shard source as current. WARNING: use it ONLY when
@@ -140,21 +140,48 @@ function oneDraw(geometry: ReturnType<typeof placeholderGeometry>, name: string)
140
140
  return staticGlb([{ geometry, material: new MeshStandardMaterial({ color: 0xffffff, vertexColors: true }), castShadow: false }], name);
141
141
  }
142
142
 
143
- /**
144
- * Bake one far proxy (a single-draw GLB) and its impostor (G539: the camera-facing tile atlas the far tier draws past the
145
- * proxy's band, `bakeFarImpostor`), refused over any §3.2 far cap. Only one of the two draws at a time; both are resident.
146
- */
147
- export async function bakeFarPlaceholder(grid: PlaceholderGrid, look: PlaceholderLook, parts: readonly PlaceholderPart[] = []): Promise<{ manifest: FarManifest; bytes: Uint8Array; impostor: Uint8Array }> {
143
+ type FarRow = NonNullable<Shardfile['far']>;
144
+ /** The §3.2 far caps a far row is admitted under (`CONTENT_CAPS.far`). */
145
+ export interface FarCaps { readonly resident: number; readonly compressed: number; readonly triangles: number; readonly draws: number }
146
+ /** Whether a far row fits every §3.2 far cap. */
147
+ function farWithinCaps(far: FarRow, caps: FarCaps = CONTENT_CAPS.far): boolean {
148
+ return far.decoded + far.gpu <= caps.resident && far.compressed <= caps.compressed && far.triangles <= caps.triangles && far.draws <= caps.draws;
149
+ }
150
+ /** The far GLB, its impostor, and the far row with the impostor (`far`) and without it (`meshOnly`). */
151
+ async function farRows(grid: PlaceholderGrid, look: PlaceholderLook, parts: readonly PlaceholderPart[]) {
148
152
  const geometry = placeholderGeometry(grid, look, parts);
149
153
  const bytes = oneDraw(geometry, 'far-proxy'), file = fileRow(bytes);
150
154
  geometry.computeBoundingBox(); const box = geometry.boundingBox; if (box === null) throw new Error('Missing far bounds');
151
155
  const baked = await bakeFarImpostor(geometry, look.family);
152
156
  // Admit the defining image envelope, including decode workspace and RGBA fallback; runtime packing stays RGBA 5551.
153
157
  const impostorFile: PlaceholderFile = { hash: hashImmutableBytes(baked.png), kind: 'image', compressed: baked.png.length, ...assetCost('image', baked.png), dependencies: [], critical: false };
154
- const far: NonNullable<Shardfile['far']> = { bounds: { min: box.min.toArray(), max: box.max.toArray() }, files: [file.hash, impostorFile.hash], impostor: { file: impostorFile.hash, ...baked.row },
155
- compressed: file.compressed + impostorFile.compressed, decoded: file.decoded + impostorFile.decoded, gpu: file.gpu + impostorFile.gpu, triangles: file.triangles, draws: file.draws };
156
- if (far.decoded + far.gpu > CONTENT_CAPS.far.resident || far.compressed > CONTENT_CAPS.far.compressed || far.triangles > CONTENT_CAPS.far.triangles || far.draws > CONTENT_CAPS.far.draws) throw new Error(`Far proxy exceeds content caps: ${JSON.stringify(far)}`);
157
- return { manifest: { far, file, impostorFile, look: { family: look.family, haze: look.haze, ...(look.grade === undefined ? {} : { grade: look.grade }), ...(look.band === undefined ? {} : { band: look.band }) } }, bytes, impostor: baked.png };
158
+ const meshOnly: FarRow = { bounds: { min: box.min.toArray(), max: box.max.toArray() }, files: [file.hash], compressed: file.compressed, decoded: file.decoded, gpu: file.gpu, triangles: file.triangles, draws: file.draws };
159
+ const far: FarRow = { ...meshOnly, files: [file.hash, impostorFile.hash], impostor: { file: impostorFile.hash, ...baked.row },
160
+ compressed: file.compressed + impostorFile.compressed, decoded: file.decoded + impostorFile.decoded, gpu: file.gpu + impostorFile.gpu };
161
+ return { far, meshOnly, file, impostorFile, bytes, impostor: baked.png, look: { family: look.family, haze: look.haze, ...(look.grade === undefined ? {} : { grade: look.grade }), ...(look.band === undefined ? {} : { band: look.band }) } };
162
+ }
163
+
164
+ /**
165
+ * Bake one far proxy (a single-draw GLB) and its impostor (G539: the camera-facing tile atlas the far tier draws past the
166
+ * proxy's band, `bakeFarImpostor`), refused over any §3.2 far cap. Only one of the two draws at a time; both are resident.
167
+ */
168
+ export async function bakeFarPlaceholder(grid: PlaceholderGrid, look: PlaceholderLook, parts: readonly PlaceholderPart[] = []): Promise<{ manifest: FarManifest; bytes: Uint8Array; impostor: Uint8Array }> {
169
+ const { far, file, impostorFile, bytes, impostor, look: runtime } = await farRows(grid, look, parts);
170
+ if (!farWithinCaps(far)) throw new Error(`Far proxy exceeds content caps: ${JSON.stringify(far)}`);
171
+ return { manifest: { far, file, impostorFile, look: runtime }, bytes, impostor };
172
+ }
173
+
174
+ /**
175
+ * `wildshard build`'s generic far proxy for a shard that ships none: the far bake with its impostor, or the GLB alone
176
+ * (the proxy then draws at every distance) when the pair would breach a §3.2 far cap, as an authored far's impostor is
177
+ * dropped (`authoredFarImpostor`); refused only when the GLB alone breaches one. `impostor` is null when dropped.
178
+ */
179
+ export async function projectFarPlaceholder(grid: PlaceholderGrid, look: PlaceholderLook, caps: FarCaps = CONTENT_CAPS.far): Promise<{ far: FarRow; file: PlaceholderFile; bytes: Uint8Array; impostor: { file: PlaceholderFile; bytes: Uint8Array } | null }> {
180
+ const rows = await farRows(grid, look, []);
181
+ if (farWithinCaps(rows.far, caps)) return { far: rows.far, file: rows.file, bytes: rows.bytes, impostor: { file: rows.impostorFile, bytes: rows.impostor } };
182
+ if (!farWithinCaps(rows.meshOnly, caps)) throw new Error(`Far proxy exceeds content caps: ${JSON.stringify(rows.meshOnly)}`);
183
+ console.warn(`far impostor dropped: the proxy and its impostor are ${rows.far.decoded + rows.far.gpu} B resident (cap ${caps.resident}), ${rows.far.compressed} B compressed (cap ${caps.compressed}); the far proxy draws at every distance`);
184
+ return { far: rows.meshOnly, file: rows.file, bytes: rows.bytes, impostor: null };
158
185
  }
159
186
 
160
187
  /** A baked `terrain.bin` (the WSTR lattice) as a placeholder grid. */
@@ -504,7 +531,7 @@ async function authoredFarImpostor(shard: Shardfile, assets: Map<string, Uint8Ar
504
531
  const baked = await bakeFarImpostor(geometry, 'pbr');
505
532
  const file: PlaceholderFile = { hash: hashImmutableBytes(baked.png), kind: 'image', compressed: baked.png.length, ...assetCost('image', baked.png), dependencies: [], critical: false };
506
533
  const next = { ...far, files: [...far.files, file.hash], impostor: { file: file.hash, ...baked.row }, compressed: far.compressed + file.compressed, decoded: far.decoded + file.decoded, gpu: far.gpu + file.gpu };
507
- if (next.decoded + next.gpu > CONTENT_CAPS.far.resident || next.compressed > CONTENT_CAPS.far.compressed) return shard;
534
+ if (!farWithinCaps(next)) return shard;
508
535
  assets.set(file.hash, baked.png);
509
536
  return { ...shard, files: [...shard.files, file], far: next };
510
537
  }
@@ -567,9 +594,9 @@ export async function projectPlaceholders(project: Shardfile, assets: Map<string
567
594
  const grid = colliderGrid(collider), look = shardfileLook(shard), files = [...shard.files];
568
595
  let far = shard.far, near = shard.near;
569
596
  if (far === null) {
570
- const baked = await bakeFarPlaceholder(grid, look);
571
- far = baked.manifest.far; files.push(baked.manifest.file, baked.manifest.impostorFile);
572
- assets.set(baked.manifest.file.hash, baked.bytes); assets.set(baked.manifest.impostorFile.hash, baked.impostor);
597
+ const baked = await projectFarPlaceholder(grid, look);
598
+ far = baked.far; files.push(baked.file); assets.set(baked.file.hash, baked.bytes);
599
+ if (baked.impostor !== null) { files.push(baked.impostor.file); assets.set(baked.impostor.file.hash, baked.impostor.bytes); }
573
600
  }
574
601
  if (near === undefined) {
575
602
  const baked = await bakeNearPlaceholder({ grid, look, prototypes: await shardfileWorld(shard, assets), residentBytes: Math.min(NEAR_BAKE.residentBytes, NEAR_PLACEHOLDER_LIMITS.contentBytes) });
@@ -59,7 +59,7 @@ function isDraft(folder: string): boolean {
59
59
  }
60
60
 
61
61
  interface Admitted { readonly shard: Shardfile; readonly observed: PerformanceObservations; readonly policy: 'warn' | 'refuse' }
62
- export interface CheckOptions { readonly decisionLegacyLines?: number; readonly manifest?: ProjectManifestSource; readonly writeShardfile?: (folder: string, source: string, options?: { readonly draftWarning?: boolean }) => Promise<string> }
62
+ export interface CheckOptions { readonly decisionLegacyLines?: number; readonly output?: string; readonly manifest?: ProjectManifestSource; readonly writeShardfile?: (folder: string, source: string, options?: { readonly draftWarning?: boolean }) => Promise<string> }
63
63
 
64
64
  /** Lint, build (no client; the shard file too, SA3), validate the built folder, prove its tape and read its report card. */
65
65
  export async function checkProject(projectPath: string, outputPath: string | undefined, options: CheckOptions = {}): Promise<CheckResult> {
@@ -73,6 +73,8 @@ export async function checkProject(projectPath: string, outputPath: string | und
73
73
  // SA16 (J314): a hand-written source (`--template blender`) has nothing to build: format's pack settles it into the
74
74
  // built folder, which is then admitted as a built shard is.
75
75
  const handwritten = isHandwrittenSource(project);
76
+ // TS21: a declared output is built from code; a hand-written shard file has one product and no outputs.
77
+ if (handwritten && options.output !== undefined) throw new Error(`${project}: a hand-written shard file declares no outputs, so check takes no --output`);
76
78
  const settleInto = async (source: string): Promise<Shardfile> => {
77
79
  // Its build output goes beside src/, never inside the folder pack reads (or a built folder named as a source).
78
80
  if (!isRepoSource(source)) throw new Error(`${source}: a hand-written shard file builds only from a repo's src/: run wildshard check on the repo`);
@@ -91,6 +93,7 @@ export async function checkProject(projectPath: string, outputPath: string | und
91
93
  ? { status: 'skip', note: 'a hand-written shard file: no code to lint' } : lintProject(project)),
92
94
  build: async (): Promise<StepOutcome> => {
93
95
  const shard = handwritten ? await settleInto(project) : await buildProject(project, output, { outputFormat: 2, client: null, placeholders: true, admit,
96
+ ...(options.output === undefined ? {} : { output: options.output }),
94
97
  ...(options.decisionLegacyLines === undefined ? {} : { decisionLegacyLines: options.decisionLegacyLines }),
95
98
  ...(options.manifest === undefined ? {} : { manifest: options.manifest }) });
96
99
  output ??= resolve(shardOutputRoot(project), 'public/shardfiles', shard.identity.slug);
@@ -5,6 +5,7 @@ import { existsSync } from 'node:fs';
5
5
  import { buildProject, readProjectAssets, validateProject } from './project';
6
6
  import { ShardfileSchema, type Shardfile } from '@wildshard/format/shardSchema';
7
7
  import { devProject } from './dev';
8
+ import { devClient } from './devClient';
8
9
  import { proveAuthorSimulation, measureSimulation, validateSimulation } from '@wildshard/engine/host/headless';
9
10
  import { performanceReport, performanceReportLines, type PerformanceObservations } from './reportCard';
10
11
  import { projectPerformancePolicy } from './performancePolicy';
@@ -71,13 +72,16 @@ async function runCommand(given: readonly string[], options: CliOptions): Promis
71
72
  }
72
73
  if (command === 'check') {
73
74
  const rest = args.slice(1), json = rest.includes('--json'), positional = rest.filter(value => !value.startsWith('--'));
74
- if (positional.length === 0 || positional.length > 2 || rest.some(value => value.startsWith('--') && value !== '--json') || rest.filter(value => value === '--json').length > 1) throw new Error('usage: wildshard check <source> [folder] [--json]');
75
+ // TS21: --output=<slug> checks one declared output of the folder (scripts/wildshard.mjs composes its manifest and, with
76
+ // no --output on a folder that declares outputs, checks each in turn).
77
+ const outputs = rest.filter(value => value.startsWith('--output=')), selected = outputs[0]?.slice('--output='.length);
78
+ if (positional.length === 0 || positional.length > 2 || rest.some(value => value.startsWith('--') && value !== '--json' && !value.startsWith('--output=')) || rest.filter(value => value === '--json').length > 1 || outputs.length > 1 || selected === '') throw new Error('usage: wildshard check <source> [folder] [--json] [--output=<slug>]');
75
79
  // --json: stdout carries the verdict document alone; everything the steps print goes to stderr.
76
80
  // (scripts/wildshard.mjs moves log and debug for the whole run; the steps here log with info and warn.)
77
81
  const saved = { info: console.info, warn: console.warn }, toError = console.error.bind(console);
78
82
  if (json) Object.assign(console, { info: toError, warn: toError });
79
83
  let result;
80
- try { result = await checkProject(findShardSource(positional[0] ?? ''), positional[1], options); } finally { Object.assign(console, saved); }
84
+ try { result = await checkProject(findShardSource(positional[0] ?? ''), positional[1], selected === undefined ? options : { ...options, output: selected }); } finally { Object.assign(console, saved); }
81
85
  process.stdout.write(json ? `${JSON.stringify(result, null, 2)}\n` : `${checkLines(result).join('\n')}\n`);
82
86
  if (result.verdict === 'fail') process.exitCode = 1;
83
87
  return;
@@ -123,9 +127,22 @@ async function runCommand(given: readonly string[], options: CliOptions): Promis
123
127
  if (command === 'dev') {
124
128
  const port = output === undefined ? 0 : Number(output);
125
129
  if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error('dev port must be 0..65535');
126
- const server = await devProject(resolve(input), { port, ...(options.decisionLegacyLines === undefined ? {} : { decisionLegacyLines: options.decisionLegacyLines }) });
127
- const close = (): void => { void server.close(); }; process.once('SIGINT', close); process.once('SIGTERM', close);
128
- console.info(`wildshard dev: ${server.url}`); return;
130
+ const server = await devProject(resolve(input), { port, client: await devClient(), ...(options.decisionLegacyLines === undefined ? {} : { decisionLegacyLines: options.decisionLegacyLines }) });
131
+ // SD-6: a signal handler replaces Node's default exit, so the handler ends the process itself: free the port and the
132
+ // build products, then exit 0 (exit drops the watchers and any rebuild still running). A second signal exits at once.
133
+ let stopping = false;
134
+ const stop = async (): Promise<void> => {
135
+ // oxlint-disable-next-line unicorn/no-process-exit -- a second Ctrl-C ends `dev` without waiting for the first.
136
+ if (stopping) process.exit(0);
137
+ stopping = true;
138
+ try { await server.close({ exiting: true }); } catch (error) { console.error(`wildshard dev: ${error instanceof Error ? error.message : String(error)}`); }
139
+ // oxlint-disable-next-line unicorn/no-process-exit -- the signal handler replaced Node's default exit; ending is its job.
140
+ process.exit(0);
141
+ };
142
+ const onSignal = (): void => { void stop(); };
143
+ process.on('SIGINT', onSignal); process.on('SIGTERM', onSignal);
144
+ // SA15: `?skipintro` walks straight into the shard; the bare page sits on the game's title over it
145
+ console.info(`wildshard dev: ${server.url}?skipintro`); return;
129
146
  }
130
147
  if (command === 'build') {
131
148
  if (output === '--behaviour-only' && (buildFlag === undefined || buildFlag === '--check')) {
@@ -0,0 +1,19 @@
1
+ /** The client page a build or `wildshard dev` serves: engine's built `index.html` with this shard's descriptor added.
2
+ * A draft (never prepared) has no recorded entry programs, so the bank says so and the page skips the read that would
3
+ * 404 (engine `spawnDownload.ts` `shardPackBase`: `entryPrograms[slug] === false` means the cook published none). */
4
+ const BACKSLASH = String.fromCodePoint(92);
5
+
6
+ export function clientPage(html: string, descriptorJson: string, slug: string, recordedPrograms: boolean): string {
7
+ // A function replacement: a `$&` or `$'` in the shard's own text stays literal.
8
+ const page = html.replace('</head>', () => `<script id="ws-shardfile" type="application/json">${descriptorJson}</script></head>`);
9
+ if (recordedPrograms) return page;
10
+ const expression = /(<script type="application\/json" id="boot-module-files">)([^<]+)(<\/script>)/u, match = expression.exec(page);
11
+ if (match?.[2] === undefined) return page;
12
+ const bank: unknown = JSON.parse(match[2]);
13
+ if (typeof bank !== 'object' || bank === null || Array.isArray(bank)) return page;
14
+ const recorded: unknown = 'entryPrograms' in bank ? bank.entryPrograms : undefined;
15
+ const entryPrograms = typeof recorded === 'object' && recorded !== null && !Array.isArray(recorded) ? { ...recorded, [slug]: false } : { [slug]: false };
16
+ // `<` as its JSON escape, as project.ts writes the descriptor: the bank sits inside a <script>.
17
+ const json = JSON.stringify({ ...bank, entryPrograms }).replaceAll('<', `${BACKSLASH}u003c`);
18
+ return page.replace(expression, (_whole, open: string, _bank: string, close: string) => `${open}${json}${close}`);
19
+ }