@hewel/zgui-build 0.1.0 → 0.1.3

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
@@ -1,11 +1,10 @@
1
1
  import type {
2
2
  BuildApplicationOptions,
3
3
  BuildInfo,
4
- Capabilities,
5
- FontDeclaration,
6
4
  Manifest,
7
5
  PublishedApplication,
8
- WindowDeclaration,
6
+ ResolveNativeHostOptions,
7
+ ResolvedNativeHost,
9
8
  WorkerDeclaration,
10
9
  } from "./index.ts";
11
10
  import { readFileSync, realpathSync, type Dirent } from "node:fs";
@@ -18,6 +17,7 @@ import { typecheckProject } from "./typecheck.ts";
18
17
  import { canonicalJson, sha256, moduleIdentity } from "./identity.ts";
19
18
  import { compileModuleBytecode, resolveNativeHost } from "./host.ts";
20
19
  import { publishGeneration, resourcePath } from "./publication.ts";
20
+ import { readManifestPolicy } from "./manifest-policy.ts";
21
21
  import { syncCssModuleTypes, validateStylesheet } from "./css.ts";
22
22
  import { workspaceRoot } from "./sdk.ts";
23
23
  import { ensureSdkPackagesBuilt } from "./sdk-packages.ts";
@@ -280,13 +280,22 @@ export async function buildApplication(
280
280
  hostSearchFrom,
281
281
  extraCapabilities,
282
282
  capabilitiesFile,
283
+ cssModuleInclude,
283
284
  }: BuildApplicationOptions = {},
285
+ {
286
+ signal,
287
+ nativeHost,
288
+ }: { signal?: AbortSignal | undefined; nativeHost?: ResolvedNativeHost | undefined } = {},
284
289
  ): Promise<PublishedApplication> {
290
+ signal?.throwIfAborted();
285
291
  if (!/^[a-z][a-z0-9-]*$/.test(app)) throw new Error(`Invalid application name: ${app}`);
286
292
  root = path.resolve(root);
287
293
  appDirectory = path.resolve(appDirectory);
288
294
  await ensureSdkPackagesBuilt(root);
289
- await syncCssModuleTypes(appDirectory, { root });
295
+ await syncCssModuleTypes({
296
+ appDirectory,
297
+ include: cssModuleInclude,
298
+ });
290
299
  typecheckProject(path.join(appDirectory, "tsconfig.json"));
291
300
  const result = await bundle(path.join(appDirectory, "src/main.tsx"), {
292
301
  root,
@@ -301,459 +310,38 @@ export async function buildApplication(
301
310
  hostRoot,
302
311
  hostExecutable,
303
312
  hostSearchFrom,
313
+ nativeHost,
314
+ signal,
304
315
  extraCapabilities,
305
316
  capabilitiesFile,
306
317
  });
307
318
  }
308
319
 
309
- function isFontDeclaration(font: unknown): font is FontDeclaration {
310
- return (
311
- !!font &&
312
- typeof font === "object" &&
313
- "family" in font &&
314
- typeof font.family === "string" &&
315
- !!font.family.trim() &&
316
- font.family === font.family.trim() &&
317
- "path" in font &&
318
- typeof font.path === "string" &&
319
- Object.keys(font).every(key => key === "family" || key === "path")
320
- );
321
- }
322
-
323
- function capabilityString(value: unknown): value is string {
324
- if (typeof value !== "string") return false;
325
- let nonspace = false;
326
- for (const char of value) {
327
- const code = char.charCodeAt(0);
328
- if (
329
- code < 32 ||
330
- (code >= 127 && code <= 159) ||
331
- (char.length === 1 && code >= 0xd800 && code <= 0xdfff)
332
- )
333
- return false;
334
- nonspace ||= code !== 32;
335
- }
336
- return nonspace;
337
- }
338
-
339
- function capabilityPath(value: string): boolean {
340
- if (value === "/") return true;
341
- if (value.includes("\\")) return false;
342
- const parts = value.split("/");
343
- const root = parts.shift();
344
- const template = root === "$XDG_RUNTIME_DIR" || root === "$HOME" || root === "$XDG_DATA_HOME";
345
- return (
346
- (root === "" || template) &&
347
- parts.every(
348
- part =>
349
- part !== "" &&
350
- part !== "." &&
351
- part !== ".." &&
352
- (!template ||
353
- part === "$WAYLAND_DISPLAY" ||
354
- !part.replaceAll("${WAYLAND_DISPLAY}", "").includes("$")),
355
- )
356
- );
357
- }
358
-
359
- function fileDirectoryPath(value: string): boolean {
360
- if (value === "/") return true;
361
- if (value.includes("\\")) return false;
362
- const parts = value.split("/");
363
- const root = parts.shift();
364
- const template = root === "$HOME" || root === "$XDG_DATA_HOME" || root === "$XDG_DOCUMENTS_DIR";
365
- return (
366
- (root === "" || template) &&
367
- parts.every(part => part !== "" && part !== "." && part !== ".." && !part.includes("$"))
368
- );
369
- }
370
-
371
- function isPrivateIpv4(host: string): boolean {
372
- const parts = host.split(".");
373
- if (parts.length !== 4 || !parts.every(p => /^\d{1,3}$/.test(p))) return false;
374
- const nums = parts.map(Number);
375
- if (nums.some(n => n > 255)) return false;
376
- const [a, b] = nums as [number, number, number, number];
377
- return (
378
- a === 0 ||
379
- a === 10 ||
380
- a === 127 ||
381
- (a === 100 && b >= 64 && b <= 127) ||
382
- (a === 169 && b === 254) ||
383
- (a === 172 && b >= 16 && b <= 31) ||
384
- (a === 192 && b === 168) ||
385
- a >= 224
386
- );
387
- }
388
-
389
- function isPrivateHost(hostname: string): boolean {
390
- const bare =
391
- hostname.startsWith("[") && hostname.endsWith("]")
392
- ? hostname.slice(1, -1).toLowerCase()
393
- : hostname.toLowerCase();
394
- if (bare === "localhost" || bare.endsWith(".localhost")) return true;
395
- if (isPrivateIpv4(bare)) return true;
396
- if (bare.includes(":")) {
397
- // Reject loopback, unspecified, ULA (fc00::/7), link-local (fe80::/10), multicast (ff00::/8),
398
- // and IPv4-mapped IPv6 addresses unless allowPrivateNetworks is explicitly opted in.
399
- if (bare === "::1" || bare === "::") return true;
400
- const first = bare.split(":")[0] ?? "";
401
- const head = Number.parseInt(first || "0", 16);
402
- if (!Number.isNaN(head)) {
403
- if ((head & 0xfe00) === 0xfc00) return true;
404
- if ((head & 0xffc0) === 0xfe80) return true;
405
- if ((head & 0xff00) === 0xff00) return true;
406
- }
407
- if (bare.startsWith("::ffff:")) {
408
- const mapped = bare.slice("::ffff:".length);
409
- if (isPrivateIpv4(mapped)) return true;
410
- // Also handle hex form e.g. ::ffff:7f00:1 produced by WHATWG URL parser
411
- const hexParts = mapped.split(":");
412
- if (hexParts.length === 2) {
413
- const hi = Number.parseInt(hexParts[0]!, 16);
414
- const lo = Number.parseInt(hexParts[1]!, 16);
415
- if (!Number.isNaN(hi) && !Number.isNaN(lo)) {
416
- const ipv4 = `${(hi >> 8) & 255}.${hi & 255}.${(lo >> 8) & 255}.${lo & 255}`;
417
- if (isPrivateIpv4(ipv4)) return true;
418
- }
419
- }
420
- }
421
- }
422
- return false;
423
- }
424
-
425
- function parseNetworkOrigin(
426
- entry: unknown,
427
- field: string,
428
- ): {
429
- canonical: string;
430
- insecure: boolean;
431
- host: string;
432
- } {
433
- if (!capabilityString(entry) || entry !== entry.trim() || entry.includes("*")) {
434
- throw new Error(`${field} contains invalid origin ${JSON.stringify(entry)}`);
435
- }
436
- let parsed: URL;
437
- try {
438
- parsed = new URL(entry);
439
- } catch {
440
- throw new Error(`${field} contains invalid origin ${JSON.stringify(entry)}`);
441
- }
442
- const scheme = parsed.protocol.slice(0, -1).toLowerCase();
443
- if (scheme !== "https" && scheme !== "http" && scheme !== "wss" && scheme !== "ws") {
444
- throw new Error(`${field} origin scheme must be https, http, wss, or ws: ${entry}`);
445
- }
446
- if (parsed.username || parsed.password) {
447
- throw new Error(`${field} origin must not include userinfo: ${entry}`);
448
- }
449
- if (parsed.search || parsed.hash) {
450
- throw new Error(`${field} origin must not include query or fragment: ${entry}`);
451
- }
452
- const afterScheme = entry.slice(entry.indexOf("://") + 3);
453
- if (afterScheme.includes("/") || afterScheme.includes("?") || afterScheme.includes("#")) {
454
- throw new Error(`${field} origin must not include a path, query, or fragment: ${entry}`);
455
- }
456
- const host = parsed.hostname.toLowerCase();
457
- if (!host) {
458
- throw new Error(`${field} origin must include a host: ${entry}`);
459
- }
460
- const defaultPort = scheme === "https" || scheme === "wss" ? 443 : 80;
461
- const port = parsed.port ? Number(parsed.port) : defaultPort;
462
- if (!Number.isInteger(port) || port < 1 || port > 65535) {
463
- throw new Error(`${field} origin has invalid port: ${entry}`);
464
- }
465
- const canonical = port === defaultPort ? `${scheme}://${host}` : `${scheme}://${host}:${port}`;
466
- return { canonical, insecure: scheme === "http" || scheme === "ws", host };
467
- }
468
-
469
- function parseCapabilities(input: unknown, source: string): Capabilities {
470
- if (input !== undefined && (input === null || typeof input !== "object" || Array.isArray(input)))
471
- throw new Error(`${source} must be an object`);
472
-
473
- const capabilities = Object.create(null) as Capabilities;
474
- for (const [key, value] of Object.entries(input ?? {}) as [string, unknown][]) {
475
- const field = `${source}.${key}`;
476
- switch (key) {
477
- case "shellSurfaces":
478
- case "sessionLock":
479
- case "controlChannel":
480
- if (typeof value !== "boolean") throw new Error(`${field} must be a boolean`);
481
- if (value) capabilities[key] = true;
482
- break;
483
- case "clipboard": {
484
- if (!value || typeof value !== "object" || Array.isArray(value))
485
- throw new Error(`${field} must be an object`);
486
- for (const [subKey, subVal] of Object.entries(value as Record<string, unknown>)) {
487
- if (subKey !== "read") throw new Error(`Unknown capability: ${field}.${subKey}`);
488
- if (typeof subVal !== "boolean") throw new Error(`${field}.read must be a boolean`);
489
- if (subVal) capabilities.clipboard = { read: true };
490
- }
491
- break;
492
- }
493
- case "sqlite": {
494
- if (!value || typeof value !== "object" || Array.isArray(value))
495
- throw new Error(`${field} must be an object`);
496
- for (const [subKey, subVal] of Object.entries(value as Record<string, unknown>)) {
497
- if (subKey !== "databases") throw new Error(`Unknown capability: ${field}.${subKey}`);
498
- if (!Array.isArray(subVal)) throw new Error(`${field}.databases must be an array`);
499
- const names = new Set<string>();
500
- for (const item of subVal as unknown[]) {
501
- if (typeof item !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(item))
502
- throw new Error(`${field}.databases contains invalid entries`);
503
- if (names.has(item)) throw new Error(`${field}.databases contains duplicates`);
504
- names.add(item);
505
- }
506
- if (names.size) capabilities.sqlite = { databases: [...names] };
507
- }
508
- break;
509
- }
510
- case "files": {
511
- if (!value || typeof value !== "object" || Array.isArray(value))
512
- throw new Error(`${field} must be an object`);
513
- for (const [subKey, subVal] of Object.entries(value as Record<string, unknown>)) {
514
- if (subKey !== "directories") throw new Error(`Unknown capability: ${field}.${subKey}`);
515
- if (!Array.isArray(subVal)) throw new Error(`${field}.directories must be an array`);
516
- const seen = new Set<string>();
517
- const dirs: { path: string; mode: "read" | "readwrite" }[] = [];
518
- for (const item of subVal as unknown[]) {
519
- if (!item || typeof item !== "object" || Array.isArray(item))
520
- throw new Error(`${field}.directories entries must be objects`);
521
- const record = item as Record<string, unknown>;
522
- const keys = Object.keys(record);
523
- if (!keys.every(k => k === "path" || k === "mode"))
524
- throw new Error(`${field}.directories entry contains unknown keys`);
525
- if (
526
- !capabilityString(record.path) ||
527
- !fileDirectoryPath(record.path) ||
528
- (record.mode !== "read" && record.mode !== "readwrite")
529
- )
530
- throw new Error(`${field}.directories contains invalid entries`);
531
- if (seen.has(record.path))
532
- throw new Error(`${field}.directories contains duplicate path ${record.path}`);
533
- seen.add(record.path);
534
- dirs.push({ path: record.path, mode: record.mode });
535
- }
536
- if (dirs.length) capabilities.files = { directories: dirs };
537
- }
538
- break;
539
- }
540
- case "network": {
541
- if (!value || typeof value !== "object" || Array.isArray(value))
542
- throw new Error(`${field} must be an object`);
543
- const network: {
544
- origins?: string[];
545
- allowInsecureHttp?: boolean;
546
- allowPrivateNetworks?: boolean;
547
- } = {};
548
- for (const [subKey, subVal] of Object.entries(value as Record<string, unknown>)) {
549
- switch (subKey) {
550
- case "origins": {
551
- if (!Array.isArray(subVal)) throw new Error(`${field}.origins must be an array`);
552
- const origins = new Set<string>();
553
- for (const item of subVal as unknown[]) {
554
- const parsed = parseNetworkOrigin(item, `${field}.origins`);
555
- if (origins.has(parsed.canonical))
556
- throw new Error(`${field}.origins contains duplicate origin ${parsed.canonical}`);
557
- origins.add(parsed.canonical);
558
- }
559
- if (origins.size) network.origins = [...origins];
560
- break;
561
- }
562
- case "allowInsecureHttp":
563
- case "allowPrivateNetworks": {
564
- if (typeof subVal !== "boolean")
565
- throw new Error(`${field}.${subKey} must be a boolean`);
566
- if (subVal) network[subKey] = true;
567
- break;
568
- }
569
- default:
570
- throw new Error(`Unknown capability: ${field}.${subKey}`);
571
- }
572
- }
573
- if (Object.keys(network).length) capabilities.network = network;
574
- break;
575
- }
576
- case "imagePrefixes":
577
- case "unixSockets":
578
- case "commands":
579
- case "namedSockets": {
580
- if (!Array.isArray(value)) throw new Error(`${field} must be an array`);
581
- const entries = new Set<string>();
582
- for (const item of value as unknown[]) {
583
- if (
584
- !capabilityString(item) ||
585
- (key === "namedSockets" && !/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(item)) ||
586
- ((key === "imagePrefixes" || key === "unixSockets") && !capabilityPath(item))
587
- )
588
- throw new Error(`${field} contains invalid entries`);
589
- if (entries.has(item)) throw new Error(`${field} contains duplicates`);
590
- entries.add(item);
591
- }
592
- if (entries.size) capabilities[key] = [...entries];
593
- break;
594
- }
595
- default:
596
- throw new Error(`Unknown capability: ${field}`);
597
- }
598
- }
599
- return capabilities;
600
- }
601
-
602
- function capabilityOverlay(input: unknown, source: string): Capabilities {
603
- if (
604
- input !== null &&
605
- typeof input === "object" &&
606
- "sessionLock" in input &&
607
- input.sessionLock === true
608
- )
609
- throw new Error(`${source}.sessionLock: true may only be declared in base package.json`);
610
- return parseCapabilities(input, source);
611
- }
612
-
613
- async function mergeCapabilities(
614
- input: unknown,
320
+ export async function buildWithResolvedHost(
321
+ app: string,
322
+ options: BuildApplicationOptions & { root: string; appDirectory: string },
615
323
  {
616
- extraCapabilities,
617
- capabilitiesFile,
618
- }: Pick<BuildApplicationOptions, "extraCapabilities" | "capabilitiesFile">,
619
- ): Promise<Capabilities | undefined> {
620
- const base = parseCapabilities(input, "package.json zgui.capabilities");
621
- const sources = [base, capabilityOverlay(extraCapabilities, "extraCapabilities")];
622
- if (capabilitiesFile !== undefined) {
623
- const filename = path.resolve(capabilitiesFile);
624
- const source = `capabilitiesFile (${filename})`;
625
- let overlay: unknown;
626
- try {
627
- overlay = JSON.parse(await readFile(filename, "utf8"));
628
- } catch (error) {
629
- const message = error instanceof Error ? error.message : String(error);
630
- throw new Error(`${source}: cannot read JSON: ${message}`, { cause: error });
631
- }
632
- sources.push(capabilityOverlay(overlay, source));
633
- }
634
- const merged: Capabilities = {};
635
- for (const key of ["shellSurfaces", "controlChannel"] as const)
636
- if (sources.some(source => source[key])) merged[key] = true;
637
- if (base.sessionLock) merged.sessionLock = true;
638
- for (const key of ["imagePrefixes", "unixSockets", "namedSockets", "commands"] as const) {
639
- const union = new Set(sources.flatMap(source => source[key] ?? []));
640
- if (union.size) merged[key] = [...union].sort();
641
- }
642
- if (sources.some(source => source.clipboard?.read)) merged.clipboard = { read: true };
643
- const sqliteDatabases = new Set(sources.flatMap(source => source.sqlite?.databases ?? []));
644
- if (sqliteDatabases.size) merged.sqlite = { databases: [...sqliteDatabases].sort() };
645
- const fileDirs = new Map<string, "read" | "readwrite">();
646
- for (const grant of sources.flatMap(source => source.files?.directories ?? [])) {
647
- const existing = fileDirs.get(grant.path);
648
- if (!existing || grant.mode === "readwrite") fileDirs.set(grant.path, grant.mode);
649
- }
650
- if (fileDirs.size) {
651
- merged.files = {
652
- directories: [...fileDirs.entries()]
653
- .sort(([a], [b]) => a.localeCompare(b))
654
- .map(([dirPath, mode]) => ({ path: dirPath, mode })),
655
- };
656
- }
657
- const allowInsecureHttp = sources.some(source => source.network?.allowInsecureHttp);
658
- const allowPrivateNetworks = sources.some(source => source.network?.allowPrivateNetworks);
659
- const networkOrigins = new Set(sources.flatMap(source => source.network?.origins ?? []));
660
- for (const origin of networkOrigins) {
661
- const parsed = parseNetworkOrigin(origin, "capabilities.network.origins");
662
- if (parsed.insecure && !allowInsecureHttp) {
663
- throw new Error(
664
- `capabilities.network.origins contains insecure origin ${origin} without allowInsecureHttp: true`,
665
- );
666
- }
667
- if (isPrivateHost(parsed.host) && !allowPrivateNetworks) {
668
- throw new Error(
669
- `capabilities.network.origins contains private/loopback origin ${origin} without allowPrivateNetworks: true`,
670
- );
671
- }
672
- }
673
- if (networkOrigins.size || allowInsecureHttp || allowPrivateNetworks) {
674
- merged.network = {
675
- ...(networkOrigins.size ? { origins: [...networkOrigins].sort() } : {}),
676
- ...(allowInsecureHttp ? { allowInsecureHttp: true } : {}),
677
- ...(allowPrivateNetworks ? { allowPrivateNetworks: true } : {}),
678
- };
679
- }
680
- return Object.keys(merged).length ? merged : undefined;
681
- }
682
-
683
- const WINDOW_KEYS = new Set(["title", "width", "height", "minWidth", "minHeight", "resizable"]);
684
-
685
- function parseWindowDeclaration(input: unknown): WindowDeclaration | undefined {
686
- if (input === undefined) return undefined;
687
- if (!input || typeof input !== "object" || Array.isArray(input)) {
688
- throw new Error("package.json zgui.window must be an object");
689
- }
690
- const record = input as Record<string, unknown>;
691
- for (const key of Object.keys(record)) {
692
- if (!WINDOW_KEYS.has(key)) throw new Error(`Unknown package.json zgui.window key: ${key}`);
693
- }
694
- const result: WindowDeclaration = {};
695
- if (record.title !== undefined) {
696
- if (!capabilityString(record.title) || record.title !== record.title.trim()) {
697
- throw new Error(
698
- "package.json zgui.window.title must be a non-empty, trimmed string without control characters",
699
- );
700
- }
701
- result.title = record.title;
702
- }
703
- for (const key of ["width", "height", "minWidth", "minHeight"] as const) {
704
- const value = record[key];
705
- if (value !== undefined) {
706
- if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > 16384) {
707
- throw new Error(`package.json zgui.window.${key} must be an integer between 1 and 16384`);
708
- }
709
- result[key] = value;
710
- }
711
- }
712
- if (record.resizable !== undefined) {
713
- if (typeof record.resizable !== "boolean") {
714
- throw new Error("package.json zgui.window.resizable must be a boolean");
715
- }
716
- result.resizable = record.resizable;
717
- }
718
- return Object.keys(result).length ? result : undefined;
719
- }
720
-
721
- const WORKER_NAME_RE = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;
722
- const MAX_WORKERS = 32;
723
-
724
- function parseWorkerDeclarations(
725
- input: unknown,
726
- appDirectory: string,
727
- ): { name: string; entry: string }[] {
728
- if (input === undefined) return [];
729
- if (!input || typeof input !== "object" || Array.isArray(input)) {
730
- throw new Error(
731
- "package.json zgui.workers must be an object mapping worker names to relative entry paths",
732
- );
733
- }
734
- const entries = Object.entries(input as Record<string, unknown>);
735
- if (entries.length > MAX_WORKERS) {
736
- throw new Error(`package.json zgui.workers exceeds maximum of ${MAX_WORKERS} workers`);
737
- }
738
- const resolvedAppDir = path.resolve(appDirectory);
739
- const parsed: { name: string; entry: string }[] = [];
740
- for (const [name, relPath] of entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
741
- if (!WORKER_NAME_RE.test(name)) {
742
- throw new Error(`Invalid compute worker name: ${name}`);
743
- }
744
- if (typeof relPath !== "string" || !relPath.trim()) {
745
- throw new Error(`package.json zgui.workers.${name} must be a non-empty relative path`);
746
- }
747
- resourcePath(relPath);
748
- const fullPath = path.resolve(resolvedAppDir, relPath);
749
- if (!fullPath.startsWith(`${resolvedAppDir}${path.sep}`)) {
750
- throw new Error(
751
- `package.json zgui.workers.${name} escapes application directory: ${relPath}`,
752
- );
753
- }
754
- parsed.push({ name, entry: fullPath });
755
- }
756
- return parsed;
324
+ hostRoot,
325
+ hostExecutable,
326
+ signal,
327
+ }: Pick<ResolveNativeHostOptions, "hostRoot" | "hostExecutable" | "signal">,
328
+ ) {
329
+ let host: Promise<ResolvedNativeHost> | undefined;
330
+ const resolveHost = () =>
331
+ (host ??= resolveNativeHost({
332
+ hostExecutable,
333
+ hostRoot,
334
+ root: options.root,
335
+ cwd: options.appDirectory,
336
+ searchFrom: options.hostSearchFrom,
337
+ signal,
338
+ }));
339
+ // 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 };
757
345
  }
758
346
 
759
347
  export async function publishApplication(
@@ -768,9 +356,15 @@ export async function publishApplication(
768
356
  hostRoot,
769
357
  hostExecutable,
770
358
  hostSearchFrom,
359
+ nativeHost,
771
360
  extraCapabilities,
772
361
  capabilitiesFile,
773
- }: BuildApplicationOptions & { root: string; appDirectory: string; signal?: AbortSignal },
362
+ }: BuildApplicationOptions & {
363
+ root: string;
364
+ appDirectory: string;
365
+ signal?: AbortSignal | undefined;
366
+ nativeHost?: ResolvedNativeHost | undefined;
367
+ },
774
368
  ): Promise<PublishedApplication> {
775
369
  signal?.throwIfAborted();
776
370
  const files = new Map(result.files);
@@ -792,29 +386,13 @@ export async function publishApplication(
792
386
  files.set("app.css", Buffer.from(mergedAppCss, "utf8"));
793
387
  const assets = await collectAssets(path.join(appDirectory, "assets"));
794
388
  for (const item of assets) files.set(...item);
795
- const pkg = await optionalFile(path.join(appDirectory, "package.json"));
796
- const packageJson:
797
- | {
798
- zgui?: {
799
- id?: unknown;
800
- fonts?: unknown;
801
- capabilities?: unknown;
802
- window?: unknown;
803
- workers?: unknown;
804
- };
805
- }
806
- | undefined = pkg && JSON.parse(pkg.toString("utf8"));
807
- const id = packageJson?.zgui?.id === undefined ? `dev.example.${app}` : packageJson.zgui.id;
808
- if (!capabilityString(id) || id !== id.trim())
809
- throw new Error(
810
- "package.json zgui.id must be a non-empty, trimmed string without control characters",
811
- );
812
- const windowConfig = parseWindowDeclaration(packageJson?.zgui?.window);
813
- const capabilities = await mergeCapabilities(packageJson?.zgui?.capabilities, {
814
- extraCapabilities,
815
- capabilitiesFile,
816
- });
817
- const workerEntries = parseWorkerDeclarations(packageJson?.zgui?.workers, appDirectory);
389
+ const {
390
+ id,
391
+ window: windowConfig,
392
+ capabilities,
393
+ workerEntries,
394
+ fonts,
395
+ } = await readManifestPolicy(app, appDirectory, assets, { extraCapabilities, capabilitiesFile });
818
396
  const workers: WorkerDeclaration[] = [];
819
397
  for (const worker of workerEntries) {
820
398
  signal?.throwIfAborted();
@@ -829,21 +407,6 @@ export async function publishApplication(
829
407
  }
830
408
  workers.push({ name: compiled.name, path: compiled.path, sourceMap: compiled.sourceMap });
831
409
  }
832
- const declarations = packageJson?.zgui?.fonts ?? [];
833
- if (!Array.isArray(declarations))
834
- throw new Error("package.json zgui.fonts must be an array of {family,path}");
835
- const fonts: FontDeclaration[] = [];
836
- const families = new Set<string>();
837
- for (const font of declarations as unknown[]) {
838
- if (!isFontDeclaration(font))
839
- throw new Error("Invalid application font mapping; expected {family,path}");
840
- resourcePath(font.path);
841
- if (!assets.has(font.path)) throw new Error(`Font path must be a declared asset: ${font.path}`);
842
- const family = font.family.toLowerCase();
843
- if (families.has(family)) throw new Error(`Duplicate application font family: ${font.family}`);
844
- families.add(family);
845
- fonts.push(font);
846
- }
847
410
  files.set(
848
411
  "build-info.json",
849
412
  Buffer.from(
@@ -860,14 +423,16 @@ export async function publishApplication(
860
423
  let finalChunks = chunks;
861
424
  let finalWorkers = workers;
862
425
  if (bytecode) {
863
- const host = await resolveNativeHost({
864
- hostExecutable,
865
- hostRoot,
866
- root,
867
- cwd: appDirectory,
868
- searchFrom: [...(hostSearchFrom ?? []), import.meta.url],
869
- signal,
870
- });
426
+ const host =
427
+ nativeHost ??
428
+ (await resolveNativeHost({
429
+ hostExecutable,
430
+ hostRoot,
431
+ root,
432
+ cwd: appDirectory,
433
+ searchFrom: hostSearchFrom,
434
+ signal,
435
+ }));
871
436
  const bytecodeFormat = host.abi?.bytecodeFormat;
872
437
  const quickjsAbi = host.abi?.quickjsAbi;
873
438
  if (bytecodeFormat !== "qjs-bytecode-v1" || !quickjsAbi) {
@@ -901,7 +466,7 @@ export async function publishApplication(
901
466
  const bcPath = toBytecodePath(jsPath);
902
467
  const inPath = path.join(sourceDir, jsPath);
903
468
  const outPath = path.join(outDir, bcPath);
904
- const bcBytes = await compileModuleBytecode(host.executable, {
469
+ const bcBytes = await compileModuleBytecode(host, {
905
470
  input: inPath,
906
471
  output: outPath,
907
472
  moduleName: jsPath,