@hewel/zgui-build 0.1.2 → 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.
@@ -0,0 +1,648 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import type {
4
+ BuildApplicationOptions,
5
+ Capabilities,
6
+ FontDeclaration,
7
+ Manifest,
8
+ WindowDeclaration,
9
+ } from "./index.ts";
10
+ import { resourcePath } from "./publication.ts";
11
+
12
+ type CapabilityOverlays = Pick<BuildApplicationOptions, "extraCapabilities" | "capabilitiesFile">;
13
+
14
+ /** Read author declarations and build-time grants before compiling and sealing a package. */
15
+ export async function readManifestPolicy(
16
+ app: string,
17
+ appDirectory: string,
18
+ assets: ReadonlyMap<string, Uint8Array>,
19
+ overlays: CapabilityOverlays,
20
+ ): Promise<
21
+ Pick<Manifest, "id" | "window" | "capabilities" | "fonts"> & {
22
+ workerEntries: { name: string; entry: string }[];
23
+ }
24
+ > {
25
+ const text = await readFile(path.join(appDirectory, "package.json"), "utf8").catch(
26
+ (error: NodeJS.ErrnoException) => {
27
+ if (error.code === "ENOENT") return undefined;
28
+ throw error;
29
+ },
30
+ );
31
+ const pkg =
32
+ text === undefined
33
+ ? undefined
34
+ : (JSON.parse(text) as {
35
+ zgui?: {
36
+ id?: unknown;
37
+ window?: unknown;
38
+ capabilities?: unknown;
39
+ workers?: unknown;
40
+ fonts?: unknown;
41
+ };
42
+ });
43
+ const zgui = pkg?.zgui;
44
+ const id = zgui?.id === undefined ? `dev.example.${app}` : zgui.id;
45
+ requireManifestText(id, "zgui.id");
46
+ const window = parseWindowDeclaration(zgui?.window);
47
+ const capabilities = await mergeCapabilities(zgui?.capabilities, overlays);
48
+ const workerEntries = parseWorkerDeclarations(zgui?.workers, appDirectory);
49
+ const fonts = parseFonts(zgui?.fonts, assets);
50
+ return {
51
+ id,
52
+ workerEntries,
53
+ fonts,
54
+ ...(window ? { window } : {}),
55
+ ...(capabilities ? { capabilities } : {}),
56
+ };
57
+ }
58
+
59
+ function parseFonts(input: unknown, assets: ReadonlyMap<string, Uint8Array>): FontDeclaration[] {
60
+ const declarations = input ?? [];
61
+ if (!Array.isArray(declarations))
62
+ throw new Error("package.json zgui.fonts must be an array of {family,path}");
63
+ const fonts: FontDeclaration[] = [];
64
+ const families = new Set<string>();
65
+ for (const font of declarations as unknown[]) {
66
+ if (!isFontDeclaration(font))
67
+ throw new Error("Invalid application font mapping; expected {family,path}");
68
+ resourcePath(font.path);
69
+ if (!assets.has(font.path)) throw new Error(`Font path must be a declared asset: ${font.path}`);
70
+ const family = font.family.toLowerCase();
71
+ if (families.has(family)) throw new Error(`Duplicate application font family: ${font.family}`);
72
+ families.add(family);
73
+ fonts.push(font);
74
+ }
75
+ return fonts;
76
+ }
77
+
78
+ // Match Rust char::is_whitespace plus BOM for the two trimmed manifest fields.
79
+ const manifestTextEdge = /^[\p{White_Space}\uFEFF]|[\p{White_Space}\uFEFF]$/u;
80
+
81
+ function requireManifestText(value: unknown, field: string): asserts value is string {
82
+ if (!capabilityString(value) || manifestTextEdge.test(value)) {
83
+ throw new Error(
84
+ `package.json ${field} must be a non-empty, trimmed string without control characters`,
85
+ );
86
+ }
87
+ }
88
+
89
+ const HOST_NAME = /^[A-Za-z][A-Za-z0-9_-]{0,63}(?![\s\S])$/;
90
+
91
+ function isFontDeclaration(font: unknown): font is FontDeclaration {
92
+ return (
93
+ !!font &&
94
+ typeof font === "object" &&
95
+ "family" in font &&
96
+ typeof font.family === "string" &&
97
+ !!font.family.trim() &&
98
+ font.family === font.family.trim() &&
99
+ "path" in font &&
100
+ typeof font.path === "string" &&
101
+ Object.keys(font).every(key => key === "family" || key === "path")
102
+ );
103
+ }
104
+
105
+ /** Reject non-scalar strings and controls. Commands may contain significant non-ASCII spacing. */
106
+ function capabilityString(value: unknown): value is string {
107
+ if (typeof value !== "string") return false;
108
+ let nonspace = false;
109
+ for (const char of value) {
110
+ const code = char.charCodeAt(0);
111
+ if (
112
+ code < 32 ||
113
+ (code >= 127 && code <= 159) ||
114
+ (char.length === 1 && code >= 0xd800 && code <= 0xdfff)
115
+ )
116
+ return false;
117
+ nonspace ||= code !== 32;
118
+ }
119
+ return nonspace;
120
+ }
121
+
122
+ function capabilityPath(value: string, kind: "host" | "directory"): boolean {
123
+ if (value === "/") return true;
124
+ if (value.includes("\\")) return false;
125
+ const [root, ...parts] = value.split("/");
126
+ if (
127
+ root !== "" &&
128
+ root !== "$HOME" &&
129
+ root !== "$XDG_DATA_HOME" &&
130
+ root !== (kind === "host" ? "$XDG_RUNTIME_DIR" : "$XDG_DOCUMENTS_DIR")
131
+ ) {
132
+ return false;
133
+ }
134
+ return parts.every(part => {
135
+ if (part === "" || part === "." || part === "..") return false;
136
+ if (root === "") return true; // Literal paths do not substitute variables.
137
+ if (kind === "directory") return !part.includes("$");
138
+ return part === "$WAYLAND_DISPLAY" || !part.replaceAll("${WAYLAND_DISPLAY}", "").includes("$");
139
+ });
140
+ }
141
+
142
+ function isPrivateIpv4(host: string): boolean {
143
+ const parts = host.split(".");
144
+ if (parts.length !== 4 || !parts.every(p => /^\d{1,3}$/.test(p))) return false;
145
+ const nums = parts.map(Number);
146
+ if (nums.some(n => n > 255)) return false;
147
+ const [a, b, c, d] = nums as [number, number, number, number];
148
+ return (
149
+ a === 0 ||
150
+ a === 10 ||
151
+ a === 127 ||
152
+ (a === 100 && b >= 64 && b <= 127) ||
153
+ (a === 169 && b === 254) ||
154
+ (a === 172 && b >= 16 && b <= 31) ||
155
+ (a === 192 && b === 168) ||
156
+ (a >= 224 && a <= 239) ||
157
+ (a === 255 && b === 255 && c === 255 && d === 255) ||
158
+ (a === 192 && b === 0 && c === 2) ||
159
+ (a === 198 && b === 51 && c === 100) ||
160
+ (a === 203 && b === 0 && c === 113)
161
+ );
162
+ }
163
+
164
+ function isPrivateHost(hostname: string): boolean {
165
+ if (hostname.startsWith("[")) {
166
+ const bare = hostname.slice(1, -1);
167
+ if (bare.startsWith("::ffff:")) return isPrivateIpv4(bare.slice("::ffff:".length));
168
+ if (bare === "::1" || bare === "::") return true;
169
+ const head = Number.parseInt(bare, 16);
170
+ return (head & 0xfe00) === 0xfc00 || (head & 0xffc0) === 0xfe80 || (head & 0xff00) === 0xff00;
171
+ }
172
+ const bare = hostname.replace(/\.+$/, "");
173
+ return bare === "localhost" || bare.endsWith(".localhost") || isPrivateIpv4(bare);
174
+ }
175
+
176
+ function parseNetworkOrigin(
177
+ entry: unknown,
178
+ field: string,
179
+ ): {
180
+ canonical: string;
181
+ insecure: boolean;
182
+ host: string;
183
+ } {
184
+ if (
185
+ !capabilityString(entry) ||
186
+ /[\p{White_Space}\uFEFF*]/u.test(entry) ||
187
+ !entry.includes("://")
188
+ ) {
189
+ throw new Error(`${field} contains invalid origin ${JSON.stringify(entry)}`);
190
+ }
191
+ let parsed: URL;
192
+ try {
193
+ parsed = new URL(entry);
194
+ } catch {
195
+ throw new Error(`${field} contains invalid origin ${JSON.stringify(entry)}`);
196
+ }
197
+ const scheme = parsed.protocol.slice(0, -1).toLowerCase();
198
+ if (scheme !== "https" && scheme !== "http" && scheme !== "wss" && scheme !== "ws") {
199
+ throw new Error(`${field} origin scheme must be https, http, wss, or ws: ${entry}`);
200
+ }
201
+ const authority = entry.slice(entry.indexOf("://") + 3);
202
+ if (authority.includes("@")) {
203
+ throw new Error(`${field} origin must not include userinfo: ${entry}`);
204
+ }
205
+ if (/[/\\?#]/.test(authority)) {
206
+ throw new Error(`${field} origin must not include a path, query, or fragment: ${entry}`);
207
+ }
208
+ let host = parsed.hostname.toLowerCase();
209
+ if (!host) {
210
+ throw new Error(`${field} origin must include a host: ${entry}`);
211
+ }
212
+ // WHATWG URL uses hex for mapped addresses; Rust's Ipv6Addr displays dotted IPv4.
213
+ const mapped = /^\[::ffff:([a-f0-9]{1,4}):([a-f0-9]{1,4})\]$/.exec(host);
214
+ if (mapped) {
215
+ const high = Number.parseInt(mapped[1]!, 16);
216
+ const low = Number.parseInt(mapped[2]!, 16);
217
+ host = `[::ffff:${high >> 8}.${high & 255}.${low >> 8}.${low & 255}]`;
218
+ }
219
+ const defaultPort = scheme === "https" || scheme === "wss" ? 443 : 80;
220
+ const port = parsed.port ? Number(parsed.port) : defaultPort;
221
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
222
+ throw new Error(`${field} origin has invalid port: ${entry}`);
223
+ }
224
+ const canonical = port === defaultPort ? `${scheme}://${host}` : `${scheme}://${host}:${port}`;
225
+ return { canonical, insecure: scheme === "http" || scheme === "ws", host };
226
+ }
227
+
228
+ /** Validate each source before any of its grants can enter the union. */
229
+ function parseCapabilities(input: unknown, source: string): Capabilities {
230
+ if (input !== undefined && (input === null || typeof input !== "object" || Array.isArray(input)))
231
+ throw new Error(`${source} must be an object`);
232
+
233
+ const capabilities = Object.create(null) as Capabilities;
234
+ for (const [key, value] of Object.entries(input ?? {}) as [string, unknown][]) {
235
+ const field = `${source}.${key}`;
236
+ switch (key) {
237
+ case "shellSurfaces":
238
+ case "sessionLock":
239
+ case "controlChannel":
240
+ if (typeof value !== "boolean") throw new Error(`${field} must be a boolean`);
241
+ if (value) capabilities[key] = true;
242
+ break;
243
+ case "clipboard": {
244
+ if (!value || typeof value !== "object" || Array.isArray(value))
245
+ throw new Error(`${field} must be an object`);
246
+ for (const [subKey, subVal] of Object.entries(value as Record<string, unknown>)) {
247
+ if (subKey !== "read") throw new Error(`Unknown capability: ${field}.${subKey}`);
248
+ if (typeof subVal !== "boolean") throw new Error(`${field}.read must be a boolean`);
249
+ if (subVal) capabilities.clipboard = { read: true };
250
+ }
251
+ break;
252
+ }
253
+ case "sqlite": {
254
+ if (!value || typeof value !== "object" || Array.isArray(value))
255
+ throw new Error(`${field} must be an object`);
256
+ for (const [subKey, subVal] of Object.entries(value as Record<string, unknown>)) {
257
+ if (subKey !== "databases") throw new Error(`Unknown capability: ${field}.${subKey}`);
258
+ if (!Array.isArray(subVal)) throw new Error(`${field}.databases must be an array`);
259
+ const names = new Set<string>();
260
+ for (const item of subVal as unknown[]) {
261
+ if (typeof item !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(item))
262
+ throw new Error(`${field}.databases contains invalid entries`);
263
+ if (names.has(item)) throw new Error(`${field}.databases contains duplicates`);
264
+ names.add(item);
265
+ }
266
+ if (names.size) capabilities.sqlite = { databases: [...names] };
267
+ }
268
+ break;
269
+ }
270
+ case "files": {
271
+ if (!value || typeof value !== "object" || Array.isArray(value))
272
+ throw new Error(`${field} must be an object`);
273
+ for (const [subKey, subVal] of Object.entries(value as Record<string, unknown>)) {
274
+ if (subKey !== "directories") throw new Error(`Unknown capability: ${field}.${subKey}`);
275
+ if (!Array.isArray(subVal)) throw new Error(`${field}.directories must be an array`);
276
+ const seen = new Set<string>();
277
+ const dirs: { path: string; mode: "read" | "readwrite" }[] = [];
278
+ for (const item of subVal as unknown[]) {
279
+ if (!item || typeof item !== "object" || Array.isArray(item))
280
+ throw new Error(`${field}.directories entries must be objects`);
281
+ const record = item as Record<string, unknown>;
282
+ const keys = Object.keys(record);
283
+ if (!keys.every(k => k === "path" || k === "mode"))
284
+ throw new Error(`${field}.directories entry contains unknown keys`);
285
+ if (
286
+ !capabilityString(record.path) ||
287
+ !capabilityPath(record.path, "directory") ||
288
+ (record.mode !== "read" && record.mode !== "readwrite")
289
+ )
290
+ throw new Error(`${field}.directories contains invalid entries`);
291
+ if (seen.has(record.path))
292
+ throw new Error(`${field}.directories contains duplicate path ${record.path}`);
293
+ seen.add(record.path);
294
+ dirs.push({ path: record.path, mode: record.mode });
295
+ }
296
+ if (dirs.length) capabilities.files = { directories: dirs };
297
+ }
298
+ break;
299
+ }
300
+ case "network": {
301
+ if (!value || typeof value !== "object" || Array.isArray(value))
302
+ throw new Error(`${field} must be an object`);
303
+ const network: {
304
+ origins?: string[];
305
+ originRules?: {
306
+ origin: string;
307
+ allowInsecureHttp?: boolean;
308
+ allowPrivateNetworks?: boolean;
309
+ }[];
310
+ allowInsecureHttp?: boolean;
311
+ allowPrivateNetworks?: boolean;
312
+ } = {};
313
+ const originSet = new Set<string>();
314
+ const ruleSet = new Set<string>();
315
+ for (const [subKey, subVal] of Object.entries(value as Record<string, unknown>)) {
316
+ switch (subKey) {
317
+ case "origins": {
318
+ if (!Array.isArray(subVal)) throw new Error(`${field}.origins must be an array`);
319
+ for (const item of subVal as unknown[]) {
320
+ const parsed = parseNetworkOrigin(item, `${field}.origins`);
321
+ if (originSet.has(parsed.canonical))
322
+ throw new Error(`${field}.origins contains duplicate origin ${parsed.canonical}`);
323
+ originSet.add(parsed.canonical);
324
+ }
325
+ if (originSet.size) network.origins = [...originSet];
326
+ break;
327
+ }
328
+ case "originRules": {
329
+ if (!Array.isArray(subVal)) throw new Error(`${field}.originRules must be an array`);
330
+ const rules: {
331
+ origin: string;
332
+ allowInsecureHttp?: boolean;
333
+ allowPrivateNetworks?: boolean;
334
+ }[] = [];
335
+ for (const item of subVal as unknown[]) {
336
+ if (!item || typeof item !== "object" || Array.isArray(item))
337
+ throw new Error(`${field}.originRules entries must be objects`);
338
+ const record = item as Record<string, unknown>;
339
+ for (const ruleKey of Object.keys(record)) {
340
+ if (
341
+ ruleKey !== "origin" &&
342
+ ruleKey !== "allowInsecureHttp" &&
343
+ ruleKey !== "allowPrivateNetworks"
344
+ ) {
345
+ throw new Error(`${field}.originRules entry contains unknown key: ${ruleKey}`);
346
+ }
347
+ }
348
+ const parsed = parseNetworkOrigin(record.origin, `${field}.originRules`);
349
+ if (
350
+ record.allowInsecureHttp !== undefined &&
351
+ typeof record.allowInsecureHttp !== "boolean"
352
+ ) {
353
+ throw new Error(`${field}.originRules allowInsecureHttp must be a boolean`);
354
+ }
355
+ if (
356
+ record.allowPrivateNetworks !== undefined &&
357
+ typeof record.allowPrivateNetworks !== "boolean"
358
+ ) {
359
+ throw new Error(`${field}.originRules allowPrivateNetworks must be a boolean`);
360
+ }
361
+ const allowInsecureHttp = record.allowInsecureHttp === true;
362
+ const allowPrivateNetworks = record.allowPrivateNetworks === true;
363
+ if (parsed.insecure && !allowInsecureHttp) {
364
+ throw new Error(
365
+ `${field}.originRules contains insecure origin ${parsed.canonical} without allowInsecureHttp: true`,
366
+ );
367
+ }
368
+ if (isPrivateHost(parsed.host) && !allowPrivateNetworks) {
369
+ throw new Error(
370
+ `${field}.originRules contains private/loopback origin ${parsed.canonical} without allowPrivateNetworks: true`,
371
+ );
372
+ }
373
+ if (ruleSet.has(parsed.canonical)) {
374
+ throw new Error(
375
+ `${field}.originRules contains duplicate origin ${parsed.canonical}`,
376
+ );
377
+ }
378
+ ruleSet.add(parsed.canonical);
379
+ rules.push({
380
+ origin: parsed.canonical,
381
+ ...(allowInsecureHttp ? { allowInsecureHttp: true } : {}),
382
+ ...(allowPrivateNetworks ? { allowPrivateNetworks: true } : {}),
383
+ });
384
+ }
385
+ if (rules.length) network.originRules = rules;
386
+ break;
387
+ }
388
+ case "allowInsecureHttp":
389
+ case "allowPrivateNetworks": {
390
+ if (typeof subVal !== "boolean")
391
+ throw new Error(`${field}.${subKey} must be a boolean`);
392
+ if (subVal) network[subKey] = true;
393
+ break;
394
+ }
395
+ default:
396
+ throw new Error(`Unknown capability: ${field}.${subKey}`);
397
+ }
398
+ }
399
+ for (const origin of ruleSet) {
400
+ if (originSet.has(origin)) {
401
+ throw new Error(
402
+ `${field} declares duplicate origin in origins and originRules: ${origin}`,
403
+ );
404
+ }
405
+ }
406
+ if (Object.keys(network).length) capabilities.network = network;
407
+ break;
408
+ }
409
+ case "imagePrefixes":
410
+ case "unixSockets":
411
+ case "commands":
412
+ case "namedSockets": {
413
+ if (!Array.isArray(value)) throw new Error(`${field} must be an array`);
414
+ const entries = new Set<string>();
415
+ for (const item of value as unknown[]) {
416
+ if (
417
+ !capabilityString(item) ||
418
+ (key === "namedSockets" && !HOST_NAME.test(item)) ||
419
+ ((key === "imagePrefixes" || key === "unixSockets") && !capabilityPath(item, "host"))
420
+ )
421
+ throw new Error(`${field} contains invalid entries`);
422
+ if (entries.has(item)) throw new Error(`${field} contains duplicates`);
423
+ entries.add(item);
424
+ }
425
+ if (entries.size) capabilities[key] = [...entries];
426
+ break;
427
+ }
428
+ default:
429
+ throw new Error(`Unknown capability: ${field}`);
430
+ }
431
+ }
432
+ return capabilities;
433
+ }
434
+
435
+ /**
436
+ * Build-time overlays may grant `shellSurfaces: true`, sealing that grant into the package.
437
+ * Only the base package may grant `sessionLock: true`. Runtime `--extensions-overlay` is
438
+ * intentionally stricter: it may escalate neither shell surfaces nor session lock.
439
+ */
440
+ function capabilityOverlay(input: unknown, source: string): Capabilities {
441
+ if (
442
+ input !== null &&
443
+ typeof input === "object" &&
444
+ "sessionLock" in input &&
445
+ input.sessionLock === true
446
+ )
447
+ throw new Error(`${source}.sessionLock: true may only be declared in base package.json`);
448
+ return parseCapabilities(input, source);
449
+ }
450
+
451
+ async function mergeCapabilities(
452
+ input: unknown,
453
+ { extraCapabilities, capabilitiesFile }: CapabilityOverlays,
454
+ ): Promise<Capabilities | undefined> {
455
+ const base = parseCapabilities(input, "package.json zgui.capabilities");
456
+ const sources = [base, capabilityOverlay(extraCapabilities, "extraCapabilities")];
457
+ if (capabilitiesFile !== undefined) {
458
+ const filename = path.resolve(capabilitiesFile);
459
+ const source = `capabilitiesFile (${filename})`;
460
+ let overlay: unknown;
461
+ try {
462
+ overlay = JSON.parse(await readFile(filename, "utf8"));
463
+ } catch (error) {
464
+ const message = error instanceof Error ? error.message : String(error);
465
+ throw new Error(`${source}: cannot read JSON: ${message}`, { cause: error });
466
+ }
467
+ sources.push(capabilityOverlay(overlay, source));
468
+ }
469
+ const merged: Capabilities = {};
470
+ for (const key of ["shellSurfaces", "controlChannel"] as const)
471
+ if (sources.some(source => source[key])) merged[key] = true;
472
+ if (base.sessionLock) merged.sessionLock = true;
473
+ for (const key of ["imagePrefixes", "unixSockets", "namedSockets", "commands"] as const) {
474
+ const union = new Set(sources.flatMap(source => source[key] ?? []));
475
+ if (union.size) merged[key] = [...union].sort();
476
+ }
477
+ if (sources.some(source => source.clipboard?.read)) merged.clipboard = { read: true };
478
+ const sqliteDatabases = new Set(sources.flatMap(source => source.sqlite?.databases ?? []));
479
+ if (sqliteDatabases.size) merged.sqlite = { databases: [...sqliteDatabases].sort() };
480
+ const fileDirs = new Map<string, "read" | "readwrite">();
481
+ for (const grant of sources.flatMap(source => source.files?.directories ?? [])) {
482
+ const existing = fileDirs.get(grant.path);
483
+ if (!existing || grant.mode === "readwrite") fileDirs.set(grant.path, grant.mode);
484
+ }
485
+ if (fileDirs.size) {
486
+ merged.files = {
487
+ directories: [...fileDirs.entries()]
488
+ .sort(([a], [b]) => a.localeCompare(b))
489
+ .map(([dirPath, mode]) => ({ path: dirPath, mode })),
490
+ };
491
+ }
492
+ const networkSources = sources
493
+ .map(source => source.network)
494
+ .filter((net): net is NonNullable<Capabilities["network"]> => net !== undefined);
495
+ const usesLegacySingleSource =
496
+ networkSources.length === 1 &&
497
+ (networkSources[0]!.originRules === undefined || networkSources[0]!.originRules.length === 0);
498
+ if (usesLegacySingleSource) {
499
+ const only = networkSources[0]!;
500
+ const allowInsecureHttp = Boolean(only.allowInsecureHttp);
501
+ const allowPrivateNetworks = Boolean(only.allowPrivateNetworks);
502
+ const networkOrigins = [...new Set(only.origins ?? [])].sort();
503
+ for (const origin of networkOrigins) {
504
+ const parsed = parseNetworkOrigin(origin, "capabilities.network.origins");
505
+ if (parsed.insecure && !allowInsecureHttp) {
506
+ throw new Error(
507
+ `capabilities.network.origins contains insecure origin ${origin} without allowInsecureHttp: true`,
508
+ );
509
+ }
510
+ if (isPrivateHost(parsed.host) && !allowPrivateNetworks) {
511
+ throw new Error(
512
+ `capabilities.network.origins contains private/loopback origin ${origin} without allowPrivateNetworks: true`,
513
+ );
514
+ }
515
+ }
516
+ if (networkOrigins.length || allowInsecureHttp || allowPrivateNetworks) {
517
+ merged.network = {
518
+ ...(networkOrigins.length ? { origins: networkOrigins } : {}),
519
+ ...(allowInsecureHttp ? { allowInsecureHttp: true } : {}),
520
+ ...(allowPrivateNetworks ? { allowPrivateNetworks: true } : {}),
521
+ };
522
+ }
523
+ } else if (networkSources.length > 0) {
524
+ const byOrigin = new Map<
525
+ string,
526
+ { allowInsecureHttp: boolean; allowPrivateNetworks: boolean }
527
+ >();
528
+ for (const net of networkSources) {
529
+ const sourceInsecure = Boolean(net.allowInsecureHttp);
530
+ const sourcePrivate = Boolean(net.allowPrivateNetworks);
531
+ for (const origin of net.origins ?? []) {
532
+ const parsed = parseNetworkOrigin(origin, "capabilities.network.origins");
533
+ if (parsed.insecure && !sourceInsecure) {
534
+ throw new Error(
535
+ `capabilities.network.origins contains insecure origin ${origin} without allowInsecureHttp: true`,
536
+ );
537
+ }
538
+ if (isPrivateHost(parsed.host) && !sourcePrivate) {
539
+ throw new Error(
540
+ `capabilities.network.origins contains private/loopback origin ${origin} without allowPrivateNetworks: true`,
541
+ );
542
+ }
543
+ const prev = byOrigin.get(parsed.canonical) ?? {
544
+ allowInsecureHttp: false,
545
+ allowPrivateNetworks: false,
546
+ };
547
+ byOrigin.set(parsed.canonical, {
548
+ allowInsecureHttp: prev.allowInsecureHttp || sourceInsecure,
549
+ allowPrivateNetworks: prev.allowPrivateNetworks || sourcePrivate,
550
+ });
551
+ }
552
+ for (const rule of net.originRules ?? []) {
553
+ const parsed = parseNetworkOrigin(rule.origin, "capabilities.network.originRules");
554
+ const prev = byOrigin.get(parsed.canonical) ?? {
555
+ allowInsecureHttp: false,
556
+ allowPrivateNetworks: false,
557
+ };
558
+ byOrigin.set(parsed.canonical, {
559
+ allowInsecureHttp: prev.allowInsecureHttp || Boolean(rule.allowInsecureHttp),
560
+ allowPrivateNetworks: prev.allowPrivateNetworks || Boolean(rule.allowPrivateNetworks),
561
+ });
562
+ }
563
+ }
564
+ if (byOrigin.size > 0) {
565
+ merged.network = {
566
+ originRules: [...byOrigin.entries()]
567
+ .sort(([a], [b]) => a.localeCompare(b))
568
+ .map(([origin, flags]) => ({
569
+ origin,
570
+ ...(flags.allowInsecureHttp ? { allowInsecureHttp: true } : {}),
571
+ ...(flags.allowPrivateNetworks ? { allowPrivateNetworks: true } : {}),
572
+ })),
573
+ };
574
+ }
575
+ }
576
+ return Object.keys(merged).length ? merged : undefined;
577
+ }
578
+
579
+ const WINDOW_KEYS = new Set(["title", "width", "height", "minWidth", "minHeight", "resizable"]);
580
+
581
+ function parseWindowDeclaration(input: unknown): WindowDeclaration | undefined {
582
+ if (input === undefined) return undefined;
583
+ if (!input || typeof input !== "object" || Array.isArray(input)) {
584
+ throw new Error("package.json zgui.window must be an object");
585
+ }
586
+ const record = input as Record<string, unknown>;
587
+ for (const key of Object.keys(record)) {
588
+ if (!WINDOW_KEYS.has(key)) throw new Error(`Unknown package.json zgui.window key: ${key}`);
589
+ }
590
+ const result: WindowDeclaration = {};
591
+ if (record.title !== undefined) {
592
+ requireManifestText(record.title, "zgui.window.title");
593
+ result.title = record.title;
594
+ }
595
+ for (const key of ["width", "height", "minWidth", "minHeight"] as const) {
596
+ const value = record[key];
597
+ if (value !== undefined) {
598
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > 16384) {
599
+ throw new Error(`package.json zgui.window.${key} must be an integer between 1 and 16384`);
600
+ }
601
+ result[key] = value;
602
+ }
603
+ }
604
+ if (record.resizable !== undefined) {
605
+ if (typeof record.resizable !== "boolean") {
606
+ throw new Error("package.json zgui.window.resizable must be a boolean");
607
+ }
608
+ result.resizable = record.resizable;
609
+ }
610
+ return Object.keys(result).length ? result : undefined;
611
+ }
612
+
613
+ const MAX_WORKERS = 32;
614
+
615
+ function parseWorkerDeclarations(
616
+ input: unknown,
617
+ appDirectory: string,
618
+ ): { name: string; entry: string }[] {
619
+ if (input === undefined) return [];
620
+ if (!input || typeof input !== "object" || Array.isArray(input)) {
621
+ throw new Error(
622
+ "package.json zgui.workers must be an object mapping worker names to relative entry paths",
623
+ );
624
+ }
625
+ const entries = Object.entries(input as Record<string, unknown>);
626
+ if (entries.length > MAX_WORKERS) {
627
+ throw new Error(`package.json zgui.workers exceeds maximum of ${MAX_WORKERS} workers`);
628
+ }
629
+ const resolvedAppDir = path.resolve(appDirectory);
630
+ const parsed: { name: string; entry: string }[] = [];
631
+ for (const [name, relPath] of entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
632
+ if (!HOST_NAME.test(name)) {
633
+ throw new Error(`Invalid compute worker name: ${name}`);
634
+ }
635
+ if (typeof relPath !== "string" || !relPath.trim()) {
636
+ throw new Error(`package.json zgui.workers.${name} must be a non-empty relative path`);
637
+ }
638
+ resourcePath(relPath);
639
+ const fullPath = path.resolve(resolvedAppDir, relPath);
640
+ if (!fullPath.startsWith(`${resolvedAppDir}${path.sep}`)) {
641
+ throw new Error(
642
+ `package.json zgui.workers.${name} escapes application directory: ${relPath}`,
643
+ );
644
+ }
645
+ parsed.push({ name, entry: fullPath });
646
+ }
647
+ return parsed;
648
+ }