@hewel/zgui-build 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/build.ts CHANGED
@@ -15,7 +15,12 @@ import path from "node:path";
15
15
  import { compileBundle, compileWorkerBundle, type CompilationResult } from "./compiler.ts";
16
16
  import { typecheckProject } from "./typecheck.ts";
17
17
  import { canonicalJson, sha256, moduleIdentity } from "./identity.ts";
18
- import { compileModuleBytecode, resolveNativeHost } from "./host.ts";
18
+ import {
19
+ compileModuleBytecode,
20
+ NativeHostUnavailableError,
21
+ preflightBundle,
22
+ resolveNativeHost,
23
+ } from "./host.ts";
19
24
  import { publishGeneration, resourcePath } from "./publication.ts";
20
25
  import { readManifestPolicy } from "./manifest-policy.ts";
21
26
  import { syncCssModuleTypes, validateStylesheet } from "./css.ts";
@@ -275,6 +280,7 @@ export async function buildApplication(
275
280
  appDirectory = path.join(root, "apps/examples", app),
276
281
  development = false,
277
282
  bytecode = false,
283
+ preflight,
278
284
  hostRoot,
279
285
  hostExecutable,
280
286
  hostSearchFrom,
@@ -285,7 +291,14 @@ export async function buildApplication(
285
291
  {
286
292
  signal,
287
293
  nativeHost,
288
- }: { signal?: AbortSignal | undefined; nativeHost?: ResolvedNativeHost | undefined } = {},
294
+ resolveHost,
295
+ onPreflightPassed,
296
+ }: {
297
+ signal?: AbortSignal | undefined;
298
+ nativeHost?: ResolvedNativeHost | undefined;
299
+ resolveHost?: ((allowCargoBuild: boolean) => Promise<ResolvedNativeHost>) | undefined;
300
+ onPreflightPassed?: ((packageDirectory: string) => void) | undefined;
301
+ } = {},
289
302
  ): Promise<PublishedApplication> {
290
303
  signal?.throwIfAborted();
291
304
  if (!/^[a-z][a-z0-9-]*$/.test(app)) throw new Error(`Invalid application name: ${app}`);
@@ -307,10 +320,13 @@ export async function buildApplication(
307
320
  appDirectory,
308
321
  development,
309
322
  bytecode,
323
+ preflight,
310
324
  hostRoot,
311
325
  hostExecutable,
312
326
  hostSearchFrom,
313
327
  nativeHost,
328
+ resolveHost,
329
+ onPreflightPassed,
314
330
  signal,
315
331
  extraCapabilities,
316
332
  capabilitiesFile,
@@ -326,22 +342,32 @@ export async function buildWithResolvedHost(
326
342
  signal,
327
343
  }: Pick<ResolveNativeHostOptions, "hostRoot" | "hostExecutable" | "signal">,
328
344
  ) {
329
- let host: Promise<ResolvedNativeHost> | undefined;
330
- const resolveHost = () =>
331
- (host ??= resolveNativeHost({
345
+ let host: ResolvedNativeHost | undefined;
346
+ const resolveHost = async (allowCargoBuild = true) =>
347
+ (host ??= await resolveNativeHost({
332
348
  hostExecutable,
333
349
  hostRoot,
334
350
  root: options.root,
335
351
  cwd: options.appDirectory,
336
352
  searchFrom: options.hostSearchFrom,
353
+ allowCargoBuild,
337
354
  signal,
338
355
  }));
356
+ let preflightedDirectory: string | undefined;
339
357
  // Bytecode needs the compiler early; packaging validates the manifest before resolving a runtime-only host.
340
- const application = await buildApplication(app, options, {
341
- signal,
342
- nativeHost: options.bytecode ? await resolveHost() : undefined,
343
- });
344
- return { application, resolveHost };
358
+ const application = await buildApplication(
359
+ app,
360
+ { ...options, hostRoot, hostExecutable },
361
+ {
362
+ signal,
363
+ nativeHost: options.bytecode ? await resolveHost() : undefined,
364
+ resolveHost,
365
+ onPreflightPassed: packageDirectory => {
366
+ preflightedDirectory = packageDirectory;
367
+ },
368
+ },
369
+ );
370
+ return { application, resolveHost, preflightedDirectory };
345
371
  }
346
372
 
347
373
  export async function publishApplication(
@@ -353,10 +379,13 @@ export async function publishApplication(
353
379
  signal,
354
380
  development = false,
355
381
  bytecode = false,
382
+ preflight = false,
356
383
  hostRoot,
357
384
  hostExecutable,
358
385
  hostSearchFrom,
359
386
  nativeHost,
387
+ resolveHost: resolveProvidedHost,
388
+ onPreflightPassed,
360
389
  extraCapabilities,
361
390
  capabilitiesFile,
362
391
  }: BuildApplicationOptions & {
@@ -364,6 +393,8 @@ export async function publishApplication(
364
393
  appDirectory: string;
365
394
  signal?: AbortSignal | undefined;
366
395
  nativeHost?: ResolvedNativeHost | undefined;
396
+ resolveHost?: ((allowCargoBuild: boolean) => Promise<ResolvedNativeHost>) | undefined;
397
+ onPreflightPassed?: ((packageDirectory: string) => void) | undefined;
367
398
  },
368
399
  ): Promise<PublishedApplication> {
369
400
  signal?.throwIfAborted();
@@ -389,6 +420,7 @@ export async function publishApplication(
389
420
  const {
390
421
  id,
391
422
  window: windowConfig,
423
+ resourceProfile,
392
424
  capabilities,
393
425
  workerEntries,
394
426
  fonts,
@@ -407,32 +439,60 @@ export async function publishApplication(
407
439
  }
408
440
  workers.push({ name: compiled.name, path: compiled.path, sourceMap: compiled.sourceMap });
409
441
  }
442
+ const chunks = result.graph.chunks
443
+ .map(chunk => chunk.fileName)
444
+ .filter(fileName => fileName !== "app.mjs")
445
+ .sort()
446
+ .map(chunkPath => ({ path: chunkPath, sourceMap: `${chunkPath}.map` }));
447
+ const modulePaths = [
448
+ "app.mjs",
449
+ ...chunks.map(chunk => chunk.path),
450
+ ...workers.map(worker => worker.path),
451
+ ];
452
+ const profile = resourceProfile ?? "standard";
453
+ const warningMiB = profile === "extended" ? 6 : 2;
454
+ const limitMiB = profile === "extended" ? 16 : 6;
455
+ const mib = 1024 * 1024;
456
+ for (const modulePath of modulePaths) {
457
+ const module = files.get(modulePath);
458
+ if (!module) throw new Error(`Missing compiled JS module: ${modulePath}`);
459
+ const bytes = module.byteLength;
460
+ if (bytes > limitMiB * mib) {
461
+ const profileAdvice =
462
+ profile === "standard" ? ' or select "resourceProfile": "extended"' : "";
463
+ throw new Error(
464
+ `${modulePath} (${bytes} bytes) exceeds the ${profile} resource profile limit of ${limitMiB} MiB. QuickJS parse/AST memory can be several times the module source size. Split the code, move static data to assets/${profileAdvice}.`,
465
+ );
466
+ }
467
+ if (bytes > warningMiB * mib) {
468
+ const message = `${modulePath} (${bytes} bytes) exceeds the ${profile} resource profile warning threshold of ${warningMiB} MiB. QuickJS parse/AST memory can be several times the module source size.`;
469
+ console.warn(message);
470
+ }
471
+ }
410
472
  files.set(
411
473
  "build-info.json",
412
474
  Buffer.from(
413
475
  JSON.stringify(await buildInfo(root, result, { appDirectory, development }), null, 2) + "\n",
414
476
  ),
415
477
  );
416
- const chunks = result.graph.chunks
417
- .map(chunk => chunk.fileName)
418
- .filter(fileName => fileName !== "app.mjs")
419
- .sort()
420
- .map(chunkPath => ({ path: chunkPath, sourceMap: `${chunkPath}.map` }));
421
478
  let entryPath = "app.mjs";
422
479
  let bytecodeMeta: { bytecodeFormat: "qjs-bytecode-v1"; quickjsAbi: string } | undefined;
423
480
  let finalChunks = chunks;
424
481
  let finalWorkers = workers;
482
+ let resolvedHost = nativeHost;
483
+ const resolveHost = (allowCargoBuild: boolean) =>
484
+ resolveProvidedHost?.(allowCargoBuild) ??
485
+ resolveNativeHost({
486
+ hostExecutable,
487
+ hostRoot,
488
+ root,
489
+ cwd: appDirectory,
490
+ searchFrom: hostSearchFrom,
491
+ allowCargoBuild,
492
+ signal,
493
+ });
425
494
  if (bytecode) {
426
- const host =
427
- nativeHost ??
428
- (await resolveNativeHost({
429
- hostExecutable,
430
- hostRoot,
431
- root,
432
- cwd: appDirectory,
433
- searchFrom: hostSearchFrom,
434
- signal,
435
- }));
495
+ const host = (resolvedHost ??= await resolveHost(true));
436
496
  const bytecodeFormat = host.abi?.bytecodeFormat;
437
497
  const quickjsAbi = host.abi?.quickjsAbi;
438
498
  if (bytecodeFormat !== "qjs-bytecode-v1" || !quickjsAbi) {
@@ -450,11 +510,6 @@ export async function publishApplication(
450
510
  };
451
511
  const sourceDir = path.join(tempDir, "src");
452
512
  const outDir = path.join(tempDir, "out");
453
- const modulePaths = [
454
- "app.mjs",
455
- ...chunks.map(chunk => chunk.path),
456
- ...workers.map(worker => worker.path),
457
- ];
458
513
  for (const jsPath of modulePaths) {
459
514
  const jsBytes = files.get(jsPath);
460
515
  if (!jsBytes) throw new Error(`Missing compiled JS module for bytecode: ${jsPath}`);
@@ -511,6 +566,7 @@ export async function publishApplication(
511
566
  assets: [...assets.keys()].sort(),
512
567
  fonts,
513
568
  ...(windowConfig ? { window: windowConfig } : {}),
569
+ ...(resourceProfile ? { resourceProfile } : {}),
514
570
  ...(capabilities ? { capabilities } : {}),
515
571
  styleSystem: result.styleSystem,
516
572
  artifactDigests: Object.fromEntries(
@@ -523,6 +579,27 @@ export async function publishApplication(
523
579
  signal?.throwIfAborted();
524
580
  files.set("manifest.json", Buffer.from(JSON.stringify(manifest, null, 2) + "\n"));
525
581
  signal?.throwIfAborted();
526
- const dist = await publishGeneration(appDirectory, files);
582
+ const dist = await publishGeneration(
583
+ appDirectory,
584
+ files,
585
+ preflight === false
586
+ ? undefined
587
+ : {
588
+ async verify(packageDirectory) {
589
+ if (!resolvedHost) {
590
+ try {
591
+ resolvedHost = await resolveHost(preflight === true);
592
+ } catch (error) {
593
+ if (preflight === true || !(error instanceof NativeHostUnavailableError))
594
+ throw error;
595
+ }
596
+ }
597
+ if (resolvedHost && (preflight === true || resolvedHost.abi?.preflight === true)) {
598
+ await preflightBundle(resolvedHost, packageDirectory, { signal });
599
+ onPreflightPassed?.(packageDirectory);
600
+ }
601
+ },
602
+ },
603
+ );
527
604
  return { dist, manifest };
528
605
  }
package/src/compiler.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import path from "node:path";
2
2
  import { realpathSync } from "node:fs";
3
- import { realpath } from "node:fs/promises";
3
+ import { realpath, stat } from "node:fs/promises";
4
4
  import {
5
5
  transform as solidTransform,
6
6
  type TransformOptions as SolidTransformOptions,
@@ -82,6 +82,25 @@ const GENERATED_STYLE_FILE =
82
82
 
83
83
  const JSX_SOURCE_FILE = /\.[cm]?[jt]sx$/i;
84
84
 
85
+ const MAX_JSON_BYTES = 128 * 1024;
86
+ const jsonBudgetPlugin: Plugin = {
87
+ name: "zgui-json-size-budget",
88
+ load: {
89
+ filter: { id: /\.json$/i },
90
+ async handler(id) {
91
+ if (!path.isAbsolute(id)) return null;
92
+ const { size } = await stat(id);
93
+ if (size > MAX_JSON_BYTES) {
94
+ this.addWatchFile(id);
95
+ throw new Error(
96
+ `JSON module ${id} is ${size} bytes and exceeds 128 KiB. Move large JSON data to assets/ and read or stream it via @hewel/zgui-services.`,
97
+ );
98
+ }
99
+ return null;
100
+ },
101
+ },
102
+ };
103
+
85
104
  function computeLineStarts(source: string): number[] {
86
105
  const starts = [0];
87
106
  for (let i = 0; i < source.length; i++) {
@@ -277,6 +296,7 @@ function compilerOptions(
277
296
  warn(warning);
278
297
  },
279
298
  plugins: [
299
+ jsonBudgetPlugin,
280
300
  {
281
301
  name: "lightningcss-solid-universal-typescript",
282
302
  resolveId(source) {
@@ -575,6 +595,7 @@ export async function compileWorkerBundle(
575
595
  warn(warning);
576
596
  },
577
597
  plugins: [
598
+ jsonBudgetPlugin,
578
599
  {
579
600
  name: "zgui-compute-worker",
580
601
  resolveId(source) {
package/src/dev.ts CHANGED
@@ -34,7 +34,9 @@ export async function devApplication(
34
34
  hostRoot,
35
35
  hostExecutable,
36
36
  hostSearchFrom,
37
+ preflight,
37
38
  strictTypecheck = false,
39
+ headless = false,
38
40
  mode = "desktop",
39
41
  extraCapabilities,
40
42
  capabilitiesFile,
@@ -87,11 +89,17 @@ export async function devApplication(
87
89
  if (controller.signal.aborted) return exitCode ?? 143;
88
90
  if (mode !== "desktop" && mode !== "preview")
89
91
  throw new Error(`Unknown development mode: ${String(mode)}`);
92
+ if (headless && mode !== "desktop")
93
+ throw new Error("--headless cannot be combined with preview development mode");
90
94
  watcher = watch(app, {
91
95
  root,
92
96
  appDirectory,
93
97
  development: mode === "desktop",
94
98
  strictTypecheck,
99
+ preflight,
100
+ hostRoot,
101
+ hostExecutable,
102
+ hostSearchFrom,
95
103
  extraCapabilities,
96
104
  capabilitiesFile,
97
105
  cssModuleInclude,
@@ -134,10 +142,12 @@ export async function devApplication(
134
142
  const dist = await Promise.race([published.promise, stopped.promise]);
135
143
  if (controller.signal.aborted) return;
136
144
  // Launch from this single startup path, never from a rebuild callback.
145
+ const extraHostArgs =
146
+ headless && !hostArgs.includes("--headless") ? ["--headless", ...hostArgs] : hostArgs;
137
147
  const args =
138
148
  mode === "preview"
139
- ? ["preview", "watch", "--bundle", dist!, ...hostArgs]
140
- : ["--bundle", dist!, "--watch", ...hostArgs];
149
+ ? ["preview", "watch", "--bundle", dist!, ...extraHostArgs]
150
+ : ["--bundle", dist!, "--watch", ...extraHostArgs];
141
151
  stop(await run(executable, args, { root: hostCwd ?? runRoot, signal: controller.signal }));
142
152
  } catch (error) {
143
153
  fail(error);
package/src/host.ts CHANGED
@@ -15,7 +15,7 @@ import {
15
15
  realpathSync,
16
16
  statSync,
17
17
  } from "node:fs";
18
- import { chmod, copyFile, mkdir, readFile, stat, writeFile } from "node:fs/promises";
18
+ import { chmod, copyFile, lstat, mkdir, readFile, stat, writeFile } from "node:fs/promises";
19
19
  import { createRequire } from "node:module";
20
20
  import { constants } from "node:os";
21
21
  import path from "node:path";
@@ -47,6 +47,10 @@ function hostFailure(message: string, exitCode = 1): Error & { exitCode: number
47
47
  return Object.assign(new Error(message), { exitCode });
48
48
  }
49
49
 
50
+ export class NativeHostUnavailableError extends Error {
51
+ readonly exitCode = 1;
52
+ }
53
+
50
54
  interface ProcessOptions {
51
55
  spawnProcess?: (
52
56
  executable: string,
@@ -225,6 +229,33 @@ export async function runNativeHost(
225
229
  return ownedProcess(executable, args, { root: path.resolve(root), signal }, processOptions);
226
230
  }
227
231
 
232
+ export async function preflightBundle(
233
+ host: ResolvedNativeHost,
234
+ bundleDir: string,
235
+ { signal }: { signal?: AbortSignal | undefined } = {},
236
+ ): Promise<void> {
237
+ signal?.throwIfAborted();
238
+ if (host.abi?.preflight !== true) {
239
+ throw new Error(
240
+ `Resolved zgui-host (${host.executable}) does not advertise "preflight": true; install or build a host with preflight support.`,
241
+ );
242
+ }
243
+ const capture = { stdout: [] as string[], stderr: [] as string[] };
244
+ const code = await ownedProcess(host.executable, ["preflight", "--bundle", bundleDir], {
245
+ root: host.runRoot,
246
+ signal,
247
+ capture,
248
+ });
249
+ signal?.throwIfAborted();
250
+ if (code !== 0) {
251
+ const detail = capture.stderr.join("").trim() || capture.stdout.join("").trim();
252
+ throw hostFailure(
253
+ `zgui-host preflight failed for ${bundleDir} (exit ${code})${detail ? `: ${detail}` : ""}`,
254
+ code,
255
+ );
256
+ }
257
+ }
258
+
228
259
  export function platformId(
229
260
  platform: string = process.platform,
230
261
  arch: string = process.arch,
@@ -286,6 +317,7 @@ function parseVersionText(text: string): NativeHostAbi | null {
286
317
  : {}),
287
318
  ...(typeof parsed.quickjsAbi === "string" ? { quickjsAbi: parsed.quickjsAbi } : {}),
288
319
  ...(typeof parsed.styleProfile === "string" ? { styleProfile: parsed.styleProfile } : {}),
320
+ preflight: typeof parsed.preflight === "boolean" ? parsed.preflight : undefined,
289
321
  };
290
322
  } catch {
291
323
  return null;
@@ -486,7 +518,7 @@ async function resolveCargoExecutable(
486
518
  `Explicit --host-root is not a zgui-js Cargo checkout (missing crates/zgui-host/Cargo.toml): ${cargoRoot}`,
487
519
  );
488
520
  }
489
- throw hostFailure(
521
+ throw new NativeHostUnavailableError(
490
522
  `Local Cargo checkout detected at ${cargoRoot}, but zgui-host has not been built yet. Run \`cargo build -p zgui-host\` or invoke \`zgui-js dev\`.`,
491
523
  );
492
524
  }
@@ -580,7 +612,7 @@ export async function resolveNativeHost({
580
612
  const installHint = packageName
581
613
  ? `Install the prebuilt host package (${packageName})`
582
614
  : `No prebuilt host package is published for ${currentPlatform}`;
583
- throw hostFailure(
615
+ throw new NativeHostUnavailableError(
584
616
  `Cannot locate a zgui-js zgui-host binary for ${currentPlatform}.\n` +
585
617
  ` 1. ${installHint} (included in @hewel/zgui-cli optionalDependencies on supported platforms), or\n` +
586
618
  ` 2. Pass --host-executable <PATH> or set ZGUI_JS_HOST_EXECUTABLE=<PATH>, or\n` +
@@ -616,6 +648,13 @@ export async function stageHostPackage({
616
648
  if (!existsSync(sourceBinary)) {
617
649
  throw hostFailure(`Source zgui-host binary not found: ${sourceBinary}`);
618
650
  }
651
+ const staticRenderSource =
652
+ platform === "linux-x64"
653
+ ? path.join(path.dirname(sourceBinary), "zgui-static-render")
654
+ : undefined;
655
+ if (staticRenderSource && !statSync(staticRenderSource, { throwIfNoEntry: false })?.isFile()) {
656
+ throw hostFailure(`Source zgui-static-render binary not found: ${staticRenderSource}`);
657
+ }
619
658
  const targetDir = path.resolve(
620
659
  packageDir ?? path.join(workspaceRoot, `packages/host-${platform}`),
621
660
  );
@@ -653,6 +692,11 @@ export async function stageHostPackage({
653
692
  await mkdir(binDir, { recursive: true });
654
693
  await copyFile(sourceBinary, destBinary);
655
694
  await chmod(destBinary, 0o755);
695
+ if (staticRenderSource) {
696
+ const destination = path.join(binDir, "zgui-static-render");
697
+ await copyFile(staticRenderSource, destination);
698
+ await chmod(destination, 0o755);
699
+ }
656
700
 
657
701
  const info = await stat(destBinary);
658
702
  const manifest: StagedHostManifest = {
@@ -692,6 +736,13 @@ export async function verifyHostPackage(
692
736
  const expectedPlatform = Object.entries(SUPPORTED_HOST_PACKAGES).find(
693
737
  ([, name]) => name === pkgJson.name,
694
738
  )?.[0];
739
+ if (expectedPlatform === "linux-x64") {
740
+ const renderer = path.join(dir, "bin", "zgui-static-render");
741
+ const info = await lstat(renderer).catch(() => undefined);
742
+ if (!info?.isFile() || (info.mode & 0o111) === 0) {
743
+ throw hostFailure(`Missing or non-executable staged binary: ${renderer}`);
744
+ }
745
+ }
695
746
  validateStagedManifest({
696
747
  manifest,
697
748
  binaryPath,
package/src/identity.ts CHANGED
@@ -6,15 +6,17 @@ export type JsonValue =
6
6
  | boolean
7
7
  | number
8
8
  | string
9
- | JsonValue[]
9
+ | readonly JsonValue[]
10
10
  | { [key: string]: JsonValue };
11
11
 
12
+ const isJsonArray: (value: JsonValue) => value is readonly JsonValue[] = Array.isArray;
13
+
12
14
  export function sha256(bytes: string | Uint8Array): string {
13
15
  return `sha256:${new Bun.CryptoHasher("sha256").update(bytes).digest("hex")}`;
14
16
  }
15
17
 
16
18
  export function canonicalJson(value: JsonValue): string {
17
- if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
19
+ if (isJsonArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
18
20
  if (value !== null && typeof value === "object") {
19
21
  return `{${Object.keys(value)
20
22
  .sort()
package/src/internal.ts CHANGED
@@ -5,6 +5,7 @@ export {
5
5
  buildSdkPackages,
6
6
  ensureSdkPackagesBuilt,
7
7
  hasCheckoutSdkSources,
8
+ listOxlintOutputFiles,
8
9
  type SdkPackageName,
9
10
  } from "./sdk-packages.ts";
10
11
  export { extractStaticComponentSheet, type StaticComponentSheet } from "./compiler.ts";
@@ -18,7 +18,7 @@ export async function readManifestPolicy(
18
18
  assets: ReadonlyMap<string, Uint8Array>,
19
19
  overlays: CapabilityOverlays,
20
20
  ): Promise<
21
- Pick<Manifest, "id" | "window" | "capabilities" | "fonts"> & {
21
+ Pick<Manifest, "id" | "window" | "resourceProfile" | "capabilities" | "fonts"> & {
22
22
  workerEntries: { name: string; entry: string }[];
23
23
  }
24
24
  > {
@@ -35,6 +35,7 @@ export async function readManifestPolicy(
35
35
  zgui?: {
36
36
  id?: unknown;
37
37
  window?: unknown;
38
+ resourceProfile?: unknown;
38
39
  capabilities?: unknown;
39
40
  workers?: unknown;
40
41
  fonts?: unknown;
@@ -44,6 +45,7 @@ export async function readManifestPolicy(
44
45
  const id = zgui?.id === undefined ? `dev.example.${app}` : zgui.id;
45
46
  requireManifestText(id, "zgui.id");
46
47
  const window = parseWindowDeclaration(zgui?.window);
48
+ const resourceProfile = parseResourceProfile(zgui?.resourceProfile);
47
49
  const capabilities = await mergeCapabilities(zgui?.capabilities, overlays);
48
50
  const workerEntries = parseWorkerDeclarations(zgui?.workers, appDirectory);
49
51
  const fonts = parseFonts(zgui?.fonts, assets);
@@ -52,6 +54,7 @@ export async function readManifestPolicy(
52
54
  workerEntries,
53
55
  fonts,
54
56
  ...(window ? { window } : {}),
57
+ ...(resourceProfile ? { resourceProfile } : {}),
55
58
  ...(capabilities ? { capabilities } : {}),
56
59
  };
57
60
  }
@@ -258,6 +261,36 @@ function parseDirectoryGrants(
258
261
  });
259
262
  }
260
263
 
264
+ const handoffKeys = ["unixSockets", "namedSockets", "commands"] as const;
265
+ type HandoffKey = (typeof handoffKeys)[number];
266
+
267
+ function parseHandoff(value: unknown, field: string): Capabilities["descriptorHandoff"] {
268
+ if (!value || typeof value !== "object" || Array.isArray(value))
269
+ throw new Error(`${field} must be an object`);
270
+ const recipients: Partial<Record<HandoffKey, string[]>> = {};
271
+ for (const [name, list] of Object.entries(value as Record<string, unknown>)) {
272
+ const key = handoffKeys.find(candidate => candidate === name);
273
+ if (!key) throw new Error(`Unknown capability: ${field}.${name}`);
274
+ if (!Array.isArray(list)) throw new Error(`${field}.${key} must be an array`);
275
+ const entries = new Set<string>();
276
+ for (const item of list as unknown[]) {
277
+ if (
278
+ !capabilityString(item) ||
279
+ (key === "unixSockets" && !capabilityPath(item, "host")) ||
280
+ (key === "namedSockets" && !HOST_NAME.test(item)) ||
281
+ (key === "commands" &&
282
+ (item === "." || item === ".." || (item.includes("/") && !item.startsWith("/"))))
283
+ ) {
284
+ throw new Error(`${field}.${key} contains invalid entries`);
285
+ }
286
+ if (entries.has(item)) throw new Error(`${field}.${key} contains duplicates`);
287
+ entries.add(item);
288
+ }
289
+ if (entries.size) recipients[key] = [...entries].sort();
290
+ }
291
+ return Object.keys(recipients).length ? recipients : undefined;
292
+ }
293
+
261
294
  /** Validate each source before any of its grants can enter the union. */
262
295
  function parseCapabilities(input: unknown, source: string): Capabilities {
263
296
  if (input !== undefined && (input === null || typeof input !== "object" || Array.isArray(input)))
@@ -269,11 +302,17 @@ function parseCapabilities(input: unknown, source: string): Capabilities {
269
302
  switch (key) {
270
303
  case "shellSurfaces":
271
304
  case "sessionLock":
305
+ case "offscreenCapture":
272
306
  case "controlChannel":
273
307
  case "singleInstance":
274
308
  if (typeof value !== "boolean") throw new Error(`${field} must be a boolean`);
275
309
  if (value) capabilities[key] = true;
276
310
  break;
311
+ case "descriptorHandoff": {
312
+ const recipients = parseHandoff(value, field);
313
+ if (recipients) capabilities.descriptorHandoff = recipients;
314
+ break;
315
+ }
277
316
  case "clipboard": {
278
317
  if (!value || typeof value !== "object" || Array.isArray(value))
279
318
  throw new Error(`${field} must be an object`);
@@ -450,13 +489,14 @@ function parseCapabilities(input: unknown, source: string): Capabilities {
450
489
  case "imagePrefixes":
451
490
  case "unixSockets":
452
491
  case "commands":
492
+ case "namedImagePrefixes":
453
493
  case "namedSockets": {
454
494
  if (!Array.isArray(value)) throw new Error(`${field} must be an array`);
455
495
  const entries = new Set<string>();
456
496
  for (const item of value as unknown[]) {
457
497
  if (
458
498
  !capabilityString(item) ||
459
- (key === "namedSockets" && !HOST_NAME.test(item)) ||
499
+ ((key === "namedSockets" || key === "namedImagePrefixes") && !HOST_NAME.test(item)) ||
460
500
  ((key === "imagePrefixes" || key === "unixSockets") && !capabilityPath(item, "host"))
461
501
  )
462
502
  throw new Error(`${field} contains invalid entries`);
@@ -470,6 +510,10 @@ function parseCapabilities(input: unknown, source: string): Capabilities {
470
510
  throw new Error(`Unknown capability: ${field}`);
471
511
  }
472
512
  }
513
+ for (const key of handoffKeys) {
514
+ if (capabilities.descriptorHandoff?.[key]?.some(entry => !capabilities[key]?.includes(entry)))
515
+ throw new Error(`${source}.descriptorHandoff.${key} must also be declared in ${key}`);
516
+ }
473
517
  return capabilities;
474
518
  }
475
519
 
@@ -506,11 +550,28 @@ async function mergeCapabilities(
506
550
  sources.push(capabilityOverlay(overlay, source));
507
551
  }
508
552
  const merged: Capabilities = {};
509
- for (const key of ["shellSurfaces", "controlChannel"] as const)
553
+ for (const source of sources.slice(1)) {
554
+ for (const key of handoffKeys) {
555
+ if (
556
+ source.descriptorHandoff?.[key]?.some(
557
+ entry => !base.descriptorHandoff?.[key]?.includes(entry),
558
+ )
559
+ )
560
+ throw new Error(`overlays cannot grant capabilities.descriptorHandoff.${key}`);
561
+ }
562
+ }
563
+ if (base.descriptorHandoff) merged.descriptorHandoff = base.descriptorHandoff;
564
+ for (const key of ["shellSurfaces", "offscreenCapture", "controlChannel"] as const)
510
565
  if (sources.some(source => source[key])) merged[key] = true;
511
566
  if (base.sessionLock) merged.sessionLock = true;
512
567
  if (base.singleInstance) merged.singleInstance = true;
513
- for (const key of ["imagePrefixes", "unixSockets", "namedSockets", "commands"] as const) {
568
+ for (const key of [
569
+ "imagePrefixes",
570
+ "namedImagePrefixes",
571
+ "unixSockets",
572
+ "namedSockets",
573
+ "commands",
574
+ ] as const) {
514
575
  const union = new Set(sources.flatMap(source => source[key] ?? []));
515
576
  if (union.size) merged[key] = [...union].sort();
516
577
  }
@@ -627,6 +688,12 @@ async function mergeCapabilities(
627
688
  return Object.keys(merged).length ? merged : undefined;
628
689
  }
629
690
 
691
+ function parseResourceProfile(input: unknown): "extended" | undefined {
692
+ if (input === undefined || input === "standard") return undefined;
693
+ if (input === "extended") return "extended";
694
+ throw new Error('package.json zgui.resourceProfile must be "standard" or "extended"');
695
+ }
696
+
630
697
  const WINDOW_KEYS = new Set(["title", "width", "height", "minWidth", "minHeight", "resizable"]);
631
698
 
632
699
  function parseWindowDeclaration(input: unknown): WindowDeclaration | undefined {