@ultimat3/cli 31.1.0 → 31.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CLAUDE.md +3 -3
  2. package/package.json +29 -29
  3. package/src/app-load.ts +3 -2
  4. package/src/binding-names.ts +124 -0
  5. package/src/browser-transport.ts +28 -0
  6. package/src/cmd-doctor.ts +8 -0
  7. package/src/cmd-exercise.ts +13 -1
  8. package/src/cmd-upgrade.ts +28 -4
  9. package/src/dev-boot.ts +4 -5
  10. package/src/dev-rebuild.ts +38 -5
  11. package/src/doctor-typescript.ts +31 -0
  12. package/src/error-codes.ts +2 -0
  13. package/src/island-build-pool.ts +35 -0
  14. package/src/island-bundle.ts +137 -176
  15. package/src/island-cache-inputs.ts +141 -0
  16. package/src/island-duplicates.ts +36 -0
  17. package/src/island-group-cache.ts +289 -0
  18. package/src/island-groups.ts +117 -0
  19. package/src/island-outputs.ts +153 -0
  20. package/src/island-runtime.ts +5 -0
  21. package/src/island-styles.ts +68 -19
  22. package/src/mcp-errors-shot.ts +49 -0
  23. package/src/mcp-errors.ts +5 -41
  24. package/src/measure-scope.ts +17 -4
  25. package/src/messages-upgrade.ts +2 -0
  26. package/src/offline-ports.ts +106 -0
  27. package/src/prerender.ts +2 -2
  28. package/src/runtime-storage-boot.ts +41 -7
  29. package/src/templates/scaffold-repo.ts +2 -1
  30. package/src/templates/sign-in-oidc.ts +24 -9
  31. package/src/transport-calls.ts +7 -3
  32. package/src/transport-values.ts +59 -0
  33. package/src/typescript-floor.ts +83 -0
  34. package/src/upgrade-report.ts +8 -1
  35. package/src/verify-e2e.ts +17 -5
  36. package/wiki/Client-Data.md +14 -8
  37. package/wiki/Configuration.md +1 -1
  38. package/wiki/Deployment.md +1 -1
  39. package/wiki/Entities-And-Migrations.md +15 -10
  40. package/wiki/Storage-And-Uploads.md +1 -1
  41. package/wiki/Testing.md +1 -0
  42. package/wiki/Upgrading.md +17 -4
@@ -1,16 +1,15 @@
1
- // The island chunk table: every `*.island.tsx` in the app compiled as its OWN bundle entry point,
1
+ // The island chunk table: every `*.island.tsx` in the app compiled as a bundle entry point,
2
2
  // addressed by a hash of its SOURCE GRAPH (`graphHash` — `Bun.build`'s minified output is not
3
3
  // byte-deterministic), plus the resolver that turns a page's `src` specifier into the URL its
4
- // `data-x-entry` carries. One entry point per island is axiom 6 made mechanical — the page's graph
5
- // never reaches an island, so a `site/` document stays at 0kb whatever the island imports.
6
- //
7
- // `islands: { sharedChunks: true }` builds every island in ONE split build instead, so a module two
8
- // islands import is one shared chunk a browser fetches once (`island-link.ts` names and links the
9
- // outputs). Measured on a fixture of two islands sharing a 20 kB module, As of 2026-09-29: 41,926 B
10
- // charged to the page with both off, 21,996 B on; the page with one of them 21,837 → 21,894 B. Off
11
- // by default: tree shaking across one split build keeps what ANY importer uses (`config-islands.ts`
12
- // in `@ultimat3/core` has the measurement that decided it).
4
+ // `data-x-entry` carries. The page's graph never reaches an island, so a `site/` document stays at
5
+ // 0kb whatever the island imports — axiom 6 made mechanical.
13
6
  //
7
+ // Islands every route renders together are ONE split build, sharing what they import as chunks;
8
+ // every other island is built alone (`island-groups.ts` has the rule and the measurement).
9
+ // `islands: { sharedChunks: true }` makes every island one group: tree shaking across one split
10
+ // build keeps what ANY importer uses, so it trades single-island routes' bytes for cache reuse
11
+ // across routes (`config-islands.ts` in `@ultimat3/core` has the measurement).
12
+
14
13
  // No page-client bootstrap is prepended (plan 101, decided 2026-09-22): the handle is one
15
14
  // `globalThis` object created lazily by the first transport call or realtime hook. Measured before
16
15
  // that decision on `examples/dummy`, a core-importing wrapper cost contact-sales 875 → 8,827 B.
@@ -20,20 +19,33 @@
20
19
 
21
20
  // Bun ships no path API. `posix` does the specifier arithmetic (an app-relative route file is
22
21
  // POSIX by construction), `join`/`basename` the filesystem side.
23
- import { basename, join, posix, relative, sep } from 'node:path';
24
- import { ISLAND_EXTENSION, islandModuleId } from '@ultimat3/render';
22
+ import { join, posix, relative, sep } from 'node:path';
23
+ import { logger, renderThrowable } from '@ultimat3/core';
24
+ import { ISLAND_EXTENSION } from '@ultimat3/render';
25
25
  import { loadAppConfig } from './app-config-load';
26
26
  import type { IslandResolve } from './document-options';
27
27
  import { IslandBuildFailedError } from './errors';
28
+ import { boundedMap } from './island-build-pool';
29
+ import {
30
+ environmentDigest,
31
+ inputDigester,
32
+ inputFiles,
33
+ listingDigester,
34
+ } from './island-cache-inputs';
28
35
  import { refuseDuplicatedModules } from './island-duplicate-refusal';
36
+ import type { ModuleIdentityIo } from './island-duplicates';
37
+ import { hostIo, memoizedIo } from './island-duplicates';
29
38
  import { entryMissing, onlyMissing } from './island-entry-missing';
30
- import { describeBuildError, sourcesContentOf, stableChunk, stripDebugId } from './island-identity';
31
- import type { BuiltOutput, LinkedFile } from './island-link';
32
- import { linkOutputs, sharedChunkName } from './island-link';
39
+ import type { GroupOutput } from './island-group-cache';
40
+ import { groupKey, readGroup, sweepOnce, writeGroup } from './island-group-cache';
41
+ import { islandGroups } from './island-groups';
42
+ import { describeBuildError } from './island-identity';
43
+ import { linkOutputs } from './island-link';
44
+ import { builtOutputs, entryChunks, ISLAND_BASE_PATH, sharedChunks } from './island-outputs';
33
45
  import { frameworkDedupePlugins } from './island-package-dedupe';
34
46
  import {
35
47
  islandRealtimePlugin,
36
- REALTIME_ISLAND_ENTRY,
48
+ reachesRealtime,
37
49
  realtimeIslandEntry,
38
50
  realtimeKind,
39
51
  } from './island-realtime';
@@ -42,17 +54,12 @@ import type { Runtimes } from './island-runtime';
42
54
  import { loadingRuntime, mergeBuilds, runtimeBuilder, runtimeShared } from './island-runtime';
43
55
  import { solidDedupePlugin } from './island-solid-dedupe';
44
56
  import type { SourcePaths } from './island-sources';
45
- import { sourcesOnDisk } from './island-sources';
46
- import { islandStylesPlugin } from './island-styles';
57
+ import type { IslandStyles } from './island-styles';
58
+ import { islandStylesPlugin, stylesheetsOf } from './island-styles';
47
59
  import { hasPathSegment } from './path-segments';
48
60
  import { solidJsxPlugin } from './solid-loader';
49
61
 
50
- /**
51
- * Where a chunk is served from, in `x dev`, in the container and in a static export — one base
52
- * path, because the URL is minted by one resolver and baked into the document. Sits beside
53
- * `ICON_BASE_PATH` and `MEDIA_BASE_PATH`, deliberately outside the dev-only `/_x` namespace.
54
- */
55
- export const ISLAND_BASE_PATH = '/islands';
62
+ export { ISLAND_BASE_PATH } from './island-outputs';
56
63
 
57
64
  /**
58
65
  * `shared/` is in and `api/` is out: an island is markup, and an API route has no document to put
@@ -122,8 +129,10 @@ export interface IslandBundle {
122
129
  export async function discoverIslands(root: string): Promise<readonly string[]> {
123
130
  const files: string[] = [];
124
131
  for await (const absolute of new Bun.Glob(ISLAND_GLOB).scan({ cwd: root, absolute: true })) {
125
- if (hasPathSegment(absolute, 'node_modules')) continue;
126
- files.push(relative(root, absolute).split(sep).join('/'));
132
+ // Root-relative, as `isScannedModule` tests it: an app under `<anything>/node_modules/<app>`
133
+ // holds the segment in every absolute path, and found no island at all.
134
+ const file = relative(root, absolute).split(sep).join('/');
135
+ if (!hasPathSegment(file, 'node_modules')) files.push(file);
127
136
  }
128
137
  return files.sort();
129
138
  }
@@ -139,13 +148,14 @@ async function buildAll(
139
148
  root: string,
140
149
  files: readonly string[],
141
150
  splitting: boolean,
142
- runtimes: Runtimes,
143
- ): Promise<{ readonly chunks: readonly IslandChunk[]; readonly shared: readonly SharedChunk[] }> {
144
- if (files.length === 0) return { chunks: [], shared: [] };
151
+ context: BuildContext,
152
+ persists: boolean | undefined,
153
+ ): Promise<GroupOutput> {
154
+ if (files.length === 0) return { chunks: [], shared: [], inputs: [], stylesheets: [] };
155
+ const { runtimes } = context;
145
156
  // Inside the refusal: the realtime probe PARSES the island's graph, and a file that will not
146
157
  // parse rejected with a raw `AggregateError: Failed to scan imports` — out of the web boot, with
147
158
  // no code, no file and no fix — before `Bun.build` ever ran to raise the one below.
148
- const persists = appPersistsRecords();
149
159
  const realtime = await Promise.all(
150
160
  files.map((file) =>
151
161
  realtimeKind(root, file, persists).catch((error: unknown) => {
@@ -196,7 +206,7 @@ async function buildAll(
196
206
  solidDedupePlugin(root),
197
207
  ...frameworkDedupePlugins(root),
198
208
  solidJsxPlugin,
199
- islandStylesPlugin,
209
+ context.styles,
200
210
  ],
201
211
  // The third one, and it is a `define` rather than the plugin this used to be: Bun selects
202
212
  // the `development`/`production` export condition from the BUILD PROCESS's own `NODE_ENV`,
@@ -223,7 +233,7 @@ async function buildAll(
223
233
  metafile: true,
224
234
  });
225
235
  } catch (error) {
226
- throw await blame(root, files, error, splitting, runtimes);
236
+ throw await blame(root, files, error, splitting, context, persists);
227
237
  }
228
238
  if (!built.success) {
229
239
  throw new IslandBuildFailedError({
@@ -237,7 +247,7 @@ async function buildAll(
237
247
  logs: 'the bundler returned no metafile',
238
248
  });
239
249
  }
240
- await refuseDuplicatedModules(files.join(', '), built.metafile);
250
+ await refuseDuplicatedModules(files.join(', '), built.metafile, context.io);
241
251
  const sources = new Map<string, SourcePaths>();
242
252
  const linked = linkOutputs(await builtOutputs(root, files, built.outputs, sources));
243
253
  const chunks = loadingRuntime(entryChunks(files, linked, sources), live, runtime).map(
@@ -247,7 +257,18 @@ async function buildAll(
247
257
  },
248
258
  );
249
259
  const shared = sharedChunks(chunks, linked, sources);
250
- return { chunks, shared: [...shared, ...runtimeShared(runtime, live)] };
260
+ const read = Object.keys(built.metafile.inputs);
261
+ const stylesheets = stylesheetsOf(read);
262
+ // The bundler's inputs, the runtime's, and every Sass partial a sheet `@use`s: a partial moves
263
+ // the sheet's class hashes and is read by the Sass compiler, never by the bundler.
264
+ const partials = context.styles.dependenciesOf(stylesheets);
265
+ const readFiles = [...(await inputFiles(read)), ...(runtime?.inputs ?? []), ...partials];
266
+ return {
267
+ chunks,
268
+ shared: [...shared, ...runtimeShared(runtime, live)],
269
+ inputs: [...new Set(readFiles)].sort(),
270
+ stylesheets,
271
+ };
251
272
  }
252
273
 
253
274
  /**
@@ -260,12 +281,13 @@ async function blame(
260
281
  files: readonly string[],
261
282
  error: unknown,
262
283
  splitting: boolean,
263
- runtimes: Runtimes,
284
+ context: BuildContext,
285
+ persists: boolean | undefined,
264
286
  ): Promise<IslandBuildFailedError> {
265
287
  if (files.length > 1) {
266
288
  for (const file of files) {
267
289
  try {
268
- await buildAll(root, [file], splitting, runtimes);
290
+ await buildAll(root, [file], splitting, context, persists);
269
291
  } catch (alone) {
270
292
  if (alone instanceof IslandBuildFailedError) return alone;
271
293
  }
@@ -274,135 +296,13 @@ async function blame(
274
296
  return new IslandBuildFailedError({ file: files.join(', '), logs: describeBuildError(error) });
275
297
  }
276
298
 
277
- /**
278
- * Bun's `./a/b.island.js` → `a/b.island.js`. A realtime wrapper's output is named after its
279
- * VIRTUAL entry, which Bun places relative to the cwd behind `_.._/` segments — so everything up to
280
- * and including the prefix goes, leaving the island's own spelling.
281
- */
282
- const outputKey = (path: string): string => {
283
- const bare = path.startsWith('./') ? path.slice(2) : path;
284
- const at = bare.indexOf(REALTIME_ISLAND_ENTRY);
285
- return at === -1 ? bare : bare.slice(at + REALTIME_ISLAND_ENTRY.length);
286
- };
287
-
288
- const withoutExtension = (file: string): string =>
289
- file.slice(0, file.length - posix.extname(file).length);
290
-
291
- /** Every code output paired with its source map's inputs and, for an entry, its island. */
292
- async function builtOutputs(
293
- root: string,
294
- files: readonly string[],
295
- artifacts: readonly Bun.BuildArtifact[],
296
- sourcePaths: Map<string, SourcePaths>,
297
- ): Promise<readonly BuiltOutput[]> {
298
- const byStem = new Map(files.map((file) => [withoutExtension(file), file]));
299
- const maps = new Map<string, string>();
300
- for (const artifact of artifacts) {
301
- if (artifact.kind === 'sourcemap') maps.set(artifact.path, await artifact.text());
302
- }
303
- const outputs: BuiltOutput[] = [];
304
- for (const artifact of artifacts) {
305
- if (artifact.kind !== 'entry-point' && artifact.kind !== 'chunk') continue;
306
- const key = outputKey(artifact.path);
307
- const file = artifact.kind === 'entry-point' ? byStem.get(withoutExtension(key)) : undefined;
308
- const map = maps.get(`${artifact.path}.map`);
309
- const parsed: unknown = map === undefined ? undefined : JSON.parse(map);
310
- const sources = parsed === undefined ? undefined : sourcesContentOf(parsed, true);
311
- sourcePaths.set(key, await sourcesOnDisk(root, parsed));
312
- if (sources === undefined || (artifact.kind === 'entry-point' && file === undefined)) {
313
- throw new IslandBuildFailedError({
314
- file: file ?? key,
315
- logs: `the bundler emitted ${key} with no source map or no island behind it, so the output has no stable identity`,
316
- });
317
- }
318
- outputs.push({
319
- path: key,
320
- ...(file === undefined ? {} : { file }),
321
- code: stripDebugId(await artifact.text()),
322
- sources,
323
- });
324
- }
325
- return outputs;
326
- }
327
-
328
- /**
329
- * The entry's own file, added to sources the map resolved into the root. A pure re-export island
330
- * (`export { mountMenu as mount } from '../shared/menu'`) emits no code of its own, so its source
331
- * map names only what it re-exports: the store then recorded nothing that changes when the entry
332
- * is edited, and `writeIslandStore` refused it as a map whose paths left the root. A map that
333
- * resolved NOTHING into the root stays empty — that is the cwd failure, and it is still refused.
334
- */
335
- function withOwnFile(file: string, sources: SourcePaths): SourcePaths {
336
- return sources.length === 0 || sources.includes(file) ? sources : [...sources, file].sort();
337
- }
338
-
339
- /** The linked outputs, as the chunk table: the entries in `files` order, their chunks attached. */
340
- function entryChunks(
341
- files: readonly string[],
342
- linked: readonly LinkedFile[],
343
- sources: ReadonlyMap<string, SourcePaths>,
344
- ): readonly IslandChunk[] {
345
- const shared = new Map(
346
- linked
347
- .filter((one) => one.file === undefined)
348
- .map((one) => [sharedChunkName(one.identity), one]),
349
- );
350
- const closure = (start: readonly string[]): readonly string[] => {
351
- const seen = new Set<string>();
352
- const walk = (names: readonly string[]): void => {
353
- for (const name of names) {
354
- if (seen.has(name)) continue;
355
- seen.add(name);
356
- walk(shared.get(name)?.imports ?? []);
357
- }
358
- };
359
- walk(start);
360
- return [...seen].sort().map((name) => `${ISLAND_BASE_PATH}/${name}`);
361
- };
362
- const chunks: IslandChunk[] = [];
363
- for (const file of files) {
364
- const entry = linked.find((one) => one.file === file);
365
- if (entry === undefined) {
366
- throw new IslandBuildFailedError({ file, logs: 'the bundler emitted no entry point for it' });
367
- }
368
- const moduleId = islandModuleId(basename(file));
369
- chunks.push({
370
- file,
371
- moduleId,
372
- url: `${ISLAND_BASE_PATH}/${moduleId}-${entry.identity}.js`,
373
- // The FIRST bytes this process emitted for these inputs, so a URL served `immutable` answers
374
- // one byte string for as long as the process lives. Without it `x dev` re-mints the chunk on
375
- // every watcher tick and a browser holding the previous one under `max-age=31536000` has two
376
- // different files at one address. `bytes` is measured on THAT code, never on this build's.
377
- ...stableChunk(file, entry.identity, entry.code),
378
- imports: closure(entry.imports),
379
- sources: withOwnFile(file, sources.get(entry.path) ?? []),
380
- });
381
- }
382
- return chunks;
383
- }
384
-
385
- /** Every shared chunk the entries load, pinned the same way, with the islands that load it. */
386
- function sharedChunks(
387
- chunks: readonly IslandChunk[],
388
- linked: readonly LinkedFile[],
389
- sources: ReadonlyMap<string, SourcePaths>,
390
- ): readonly SharedChunk[] {
391
- const out: SharedChunk[] = [];
392
- for (const one of linked) {
393
- if (one.file !== undefined) continue;
394
- const url = `${ISLAND_BASE_PATH}/${sharedChunkName(one.identity)}`;
395
- out.push({
396
- url,
397
- ...stableChunk(url, one.identity, one.code),
398
- importers: chunks
399
- .filter((chunk) => chunk.imports.includes(url))
400
- .map((chunk) => chunk.file)
401
- .sort(),
402
- sources: sources.get(one.path) ?? [],
403
- });
404
- }
405
- return out.sort((a, b) => (a.url < b.url ? -1 : a.url > b.url ? 1 : 0));
299
+ /** What every group's build of one `buildIslands` call shares. */
300
+ interface BuildContext {
301
+ readonly runtimes: Runtimes;
302
+ /** One styles plugin per call: each sheet compiled once, however many groups load it. */
303
+ readonly styles: IslandStyles;
304
+ /** One realpath per file per call, however many groups' metafiles name it. */
305
+ readonly io: ModuleIdentityIo;
406
306
  }
407
307
 
408
308
  export interface BuildIslandsOptions {
@@ -418,10 +318,24 @@ export interface BuildIslandsOptions {
418
318
  readonly only?: string;
419
319
  /**
420
320
  * One split build over every island (`app.config.ts`'s `islands.sharedChunks`, off by default),
421
- * or one self-contained build per island. Passed, it overrides the app's config — the seam a test
422
- * asks both questions of one fixture through.
321
+ * or one build per route group (`island-groups.ts`). Passed, it overrides the app's config — the
322
+ * seam a test asks both questions of one fixture through.
423
323
  */
424
324
  readonly sharedChunks?: boolean;
325
+ /**
326
+ * Reuse a group's output from `.x/cache/islands/` while every file it read is unchanged
327
+ * (`island-group-cache.ts`) — on by default. `false` is the seam a determinism test builds
328
+ * through: a reused byte string proves nothing about the bundler that emitted it.
329
+ */
330
+ readonly reuse?: boolean;
331
+ /**
332
+ * Whether the app persists records (`appPersistsRecords`), asked only by a group one of whose
333
+ * islands reaches realtime, and once per call. `x dev` builds islands BESIDE the app load
334
+ * (`buildGeneration`), so it passes the answer the registry gives once the load settles; read
335
+ * any earlier it is the empty registry's `undefined`, and every reader islands is held. Absent,
336
+ * the registry is read as it stands: the caller loaded the app first.
337
+ */
338
+ readonly persists?: () => Promise<boolean | undefined>;
425
339
  }
426
340
 
427
341
  /** `islands.sharedChunks` off the one loader (`app-config-load.ts`) — `false` with no config file. */
@@ -441,17 +355,64 @@ export async function buildIslands(
441
355
  // an empty bundle here would surface two steps later, as a chunk table with no entry for a file
442
356
  // the caller can see on disk.
443
357
  if (only !== undefined && files.length === 0) throw onlyMissing(only, discovered);
444
- const runtimes = runtimeBuilder(root, ISLAND_BASE_PATH);
445
- if (options.sharedChunks ?? (await loadSharedChunks(root))) {
446
- const built = await buildAll(root, files, true, runtimes);
447
- return islandBundle(built.chunks, built.shared);
448
- }
449
- // One build per island, splitting off: each chunk is self-contained but for the page runtime,
450
- // the ONE file beside it every realtime island loads, counted once however many load it.
451
- const solo = await Promise.all(files.map((file) => buildAll(root, [file], false, runtimes)));
452
- return islandBundle(...mergeBuilds(solo));
358
+ const context: BuildContext = {
359
+ runtimes: runtimeBuilder(root, ISLAND_BASE_PATH),
360
+ styles: islandStylesPlugin(),
361
+ io: memoizedIo(hostIo()),
362
+ };
363
+ let asked: Promise<boolean | undefined> | undefined;
364
+ const persistsOnce = (): Promise<boolean | undefined> => {
365
+ asked ??= options.persists?.() ?? Promise.resolve(appPersistsRecords());
366
+ return asked;
367
+ };
368
+ // One build per group (`island-groups.ts`): islands every route renders together are one split
369
+ // build; every other island is alone, splitting off, self-contained but for the page runtime —
370
+ // the ONE file every realtime island loads, counted once however many load it.
371
+ // `islands.sharedChunks` is the one group of every island, split as it always was.
372
+ const everyIsland = files.length > 0 && (options.sharedChunks ?? (await loadSharedChunks(root)));
373
+ const groups = everyIsland ? [files] : files.length === 0 ? [] : await islandGroups(root, files);
374
+ const reuse = options.reuse ?? true;
375
+ const cache = {
376
+ environment: reuse ? await environmentDigest(root) : '',
377
+ digestOf: inputDigester(),
378
+ // One per call, shared by every read and write: a listing hashed before a build is the one
379
+ // its entry is stamped with.
380
+ listingOf: listingDigester(),
381
+ warned: false,
382
+ };
383
+ const build = async (group: readonly string[]): Promise<GroupBuild> => {
384
+ const splitting = everyIsland || group.length > 1;
385
+ // The registry's answer only where it changes the bytes: a group with no realtime island
386
+ // builds at once, while `x dev`'s app load is still running beside it. A probe that cannot
387
+ // parse reads as reaching, so `buildAll` raises the island's own coded refusal.
388
+ const reaches = await Promise.all(
389
+ group.map((file) => reachesRealtime(root, file).catch(() => true)),
390
+ );
391
+ const persists = reaches.includes(true) ? await persistsOnce() : undefined;
392
+ if (!reuse) return buildAll(root, group, splitting, context, persists);
393
+ const key = groupKey({ group, splitting, environment: cache.environment, persists });
394
+ const hit = await readGroup(root, key, cache.digestOf, cache.listingOf);
395
+ if (hit !== undefined) return hit;
396
+ // The wall clock as the filesystem stamps an mtime — never `Date.now()`, which a test may freeze.
397
+ const startedAt = performance.timeOrigin + performance.now();
398
+ const output = await buildAll(root, group, splitting, context, persists);
399
+ // Best effort: a read-only tree (a pod whose image skipped `x build --target prebuilt`) still
400
+ // serves what it just built — a cache it cannot write is a slower next boot, never a failed one.
401
+ await writeGroup(root, key, output, startedAt, cache.digestOf, cache.listingOf).catch(
402
+ (error: unknown) => {
403
+ if (!cache.warned) logger.warn(`island cache not written: ${renderThrowable(error)}`);
404
+ cache.warned = true;
405
+ },
406
+ );
407
+ return output;
408
+ };
409
+ if (reuse) await sweepOnce(root);
410
+ const width = navigator.hardwareConcurrency;
411
+ return islandBundle(...mergeBuilds(await boundedMap(groups, width, build)));
453
412
  }
454
413
 
414
+ type GroupBuild = Pick<GroupOutput, 'chunks' | 'shared'>;
415
+
455
416
  export function islandBundle(
456
417
  chunks: readonly IslandChunk[],
457
418
  shared: readonly SharedChunk[] = [],
@@ -0,0 +1,141 @@
1
+ // What an island group's cache entry is verified against besides its own files' bytes: the files
2
+ // the bundler read (`inputFiles`), the directory listings that decide how an import resolves
3
+ // (`resolutionDirs`), and the environment every group shares (`environmentDigest`: the lockfile,
4
+ // the tsconfig chain, the package manifests). Each is a digest, read at most once per build.
5
+
6
+ // why: Bun ships no directory listing; `readdir` answers the names a resolver chooses between.
7
+ import { readdir } from 'node:fs/promises';
8
+ // why: Bun ships no path API; the bundler names its inputs relative to the building process's cwd.
9
+ import { basename, dirname, join, resolve } from 'node:path';
10
+ import { contentHash } from '@ultimat3/render/server';
11
+ import { hasPathSegment } from './path-segments';
12
+
13
+ /** One path's digest, or `undefined` when it is gone — each path read once per `buildIslands`. */
14
+ export type InputDigester = (path: string) => Promise<string | undefined>;
15
+
16
+ /** File bytes, hashed once per path. */
17
+ export function inputDigester(): InputDigester {
18
+ const seen = new Map<string, Promise<string | undefined>>();
19
+ return (path) => {
20
+ let digest = seen.get(path);
21
+ if (digest === undefined) {
22
+ const file = Bun.file(path);
23
+ digest = file.exists().then(async (ok) => (ok ? contentHash(await file.text()) : undefined));
24
+ seen.set(path, digest);
25
+ }
26
+ return digest;
27
+ };
28
+ }
29
+
30
+ /** A directory's sorted entry names, hashed once per path — `undefined` when it is gone. */
31
+ export function listingDigester(): InputDigester {
32
+ const seen = new Map<string, Promise<string | undefined>>();
33
+ return (dir) => {
34
+ let digest = seen.get(dir);
35
+ if (digest === undefined) {
36
+ digest = readdir(dir).then(
37
+ (names) => contentHash([...names].sort().join('\n')),
38
+ () => undefined,
39
+ );
40
+ seen.set(dir, digest);
41
+ }
42
+ return digest;
43
+ };
44
+ }
45
+
46
+ /**
47
+ * Metafile inputs (cwd-relative, some virtual) → the files on disk, absolute. `node_modules` is
48
+ * left to the key: it changes only with an install, and the lockfile's digest is in it.
49
+ */
50
+ export async function inputFiles(listed: readonly string[]): Promise<readonly string[]> {
51
+ const cwd = process.cwd();
52
+ const paths = [...new Set(listed.map((one) => resolve(cwd, one)))].filter(
53
+ (path) => !hasPathSegment(path, 'node_modules'),
54
+ );
55
+ const present = await Promise.all(paths.map((path) => Bun.file(path).exists()));
56
+ return paths.filter((_, index) => present[index]).sort();
57
+ }
58
+
59
+ /**
60
+ * The directories whose listing decides what each input resolved AS: its own (a `util.ts` added
61
+ * beside `util/` takes `./util` from `util/index.ts`; a `.tsx` beside a `.ts` takes the stem), and
62
+ * for an `index.*` the parent too, where the shadowing file lands. A listing is the whole rule —
63
+ * any added or removed name there is a miss, which over-invalidates only that group.
64
+ */
65
+ export function resolutionDirs(inputs: readonly string[]): readonly string[] {
66
+ const dirs = new Set<string>();
67
+ for (const input of inputs) {
68
+ dirs.add(dirname(input));
69
+ if (basename(input).startsWith('index.')) dirs.add(dirname(dirname(input)));
70
+ }
71
+ return [...dirs].sort();
72
+ }
73
+
74
+ /** `extends` of a tsconfig, when it names a relative file: the chain a `paths` change lives in. */
75
+ async function tsconfigChain(file: string, seen: Set<string>): Promise<readonly string[]> {
76
+ if (seen.has(file) || !(await Bun.file(file).exists())) return [];
77
+ seen.add(file);
78
+ const text = await Bun.file(file).text();
79
+ const named = /"extends"\s*:\s*"(\.[^"]+)"/.exec(text)?.[1];
80
+ if (named === undefined) return [text];
81
+ const next = resolve(dirname(file), named.endsWith('.json') ? named : `${named}.json`);
82
+ return [text, ...(await tsconfigChain(next, seen))];
83
+ }
84
+
85
+ /** A manifest's `workspaces` globs — the array form or Bun's `{ packages }` — or none. */
86
+ function workspaceGlobs(text: string): readonly string[] {
87
+ let parsed: unknown;
88
+ try {
89
+ parsed = JSON.parse(text);
90
+ } catch {
91
+ return [];
92
+ }
93
+ const field =
94
+ typeof parsed === 'object' && parsed !== null ? Reflect.get(parsed, 'workspaces') : [];
95
+ const list = Array.isArray(field)
96
+ ? field
97
+ : typeof field === 'object' && field !== null
98
+ ? Reflect.get(field, 'packages')
99
+ : [];
100
+ return Array.isArray(list) ? list.filter((one): one is string => typeof one === 'string') : [];
101
+ }
102
+
103
+ /**
104
+ * Everything every group's resolution shares, hashed once per build: the nearest `bun.lock` (the
105
+ * third-party code installed), and each `package.json` (`imports`, `exports`, workspaces) and
106
+ * `tsconfig.json` (`paths`, with its relative `extends` chain) at the app root, each `apps/*`, the
107
+ * lockfile's directory, and every workspace member either root declares — a member's `exports`
108
+ * decides which of its files an island's `import 'lib'` reaches, and no bundler input says so.
109
+ */
110
+ export async function environmentDigest(root: string): Promise<string> {
111
+ let lockDir: string | undefined;
112
+ for (let dir = root; lockDir === undefined; dir = dirname(dir)) {
113
+ if (await Bun.file(join(dir, 'bun.lock')).exists()) lockDir = dir;
114
+ else if (dirname(dir) === dir) break;
115
+ }
116
+ const roots = [...new Set([root, ...(lockDir === undefined ? [] : [lockDir])])];
117
+ const members = new Set<string>();
118
+ for await (const one of new Bun.Glob('apps/*/package.json').scan({ cwd: root })) {
119
+ members.add(dirname(join(root, one)));
120
+ }
121
+ for (const dir of roots) {
122
+ const manifest = Bun.file(join(dir, 'package.json'));
123
+ if (!(await manifest.exists())) continue;
124
+ for (const pattern of workspaceGlobs(await manifest.text())) {
125
+ const glob = new Bun.Glob(`${pattern.replace(/\/+$/, '')}/package.json`);
126
+ for await (const one of glob.scan({ cwd: dir })) {
127
+ if (!hasPathSegment(one, 'node_modules')) members.add(dirname(join(dir, one)));
128
+ }
129
+ }
130
+ }
131
+ const dirs = [...roots, ...[...members].filter((dir) => !roots.includes(dir)).sort()];
132
+ const parts: string[] = [];
133
+ const seen = new Set<string>();
134
+ if (lockDir !== undefined) parts.push(await Bun.file(join(lockDir, 'bun.lock')).text());
135
+ for (const dir of dirs) {
136
+ const manifest = Bun.file(join(dir, 'package.json'));
137
+ parts.push(dir, (await manifest.exists()) ? await manifest.text() : '');
138
+ parts.push(...(await tsconfigChain(join(dir, 'tsconfig.json'), seen)));
139
+ }
140
+ return contentHash(parts.join('\0'));
141
+ }
@@ -40,6 +40,42 @@ export const hostIo = (): ModuleIdentityIo => ({
40
40
  },
41
41
  });
42
42
 
43
+ /**
44
+ * `io` with each realpath and each text asked once: one `buildIslands` judges every group's
45
+ * metafile, and the design system's files are in all of them — 2.3 s of `realpathSync` and
46
+ * `statSync` across the 159-island bench app's builds (one CPU profile, As of 2026-11-10). Made per
47
+ * call, never per process, so a link or a file changed between two `x dev` rebuilds is read again.
48
+ */
49
+ export function memoizedIo(io: ModuleIdentityIo): ModuleIdentityIo {
50
+ const reals = new Map<string, { readonly real: string } | { readonly missing: unknown }>();
51
+ const texts = new Map<string, Promise<string | undefined>>();
52
+ return {
53
+ ...io,
54
+ realpath: (path) => {
55
+ let known = reals.get(path);
56
+ if (known === undefined) {
57
+ try {
58
+ known = { real: io.realpath(path) };
59
+ } catch (missing) {
60
+ known = { missing };
61
+ }
62
+ reals.set(path, known);
63
+ }
64
+ // The same throw the unmemoized call raises: the caller reads "no file" from it.
65
+ if ('missing' in known) throw known.missing;
66
+ return known.real;
67
+ },
68
+ readText: (path) => {
69
+ let text = texts.get(path);
70
+ if (text === undefined) {
71
+ text = io.readText(path);
72
+ texts.set(path, text);
73
+ }
74
+ return text;
75
+ },
76
+ };
77
+ }
78
+
43
79
  /**
44
80
  * `path` as `island-package-dedupe.ts` spells every framework file it answers: the realpath. What a
45
81
  * resolver answered under another spelling (a Windows junction) is renamed through this before a