@hewel/zgui-build 0.0.0-stage → 0.1.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 (45) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +95 -0
  3. package/README.md +84 -2
  4. package/THIRD_PARTY_NOTICES.md +37 -0
  5. package/package.json +64 -4
  6. package/sdk/Cargo.lock +6813 -0
  7. package/sdk/LICENSE +202 -0
  8. package/sdk/NOTICE +95 -0
  9. package/sdk/THIRD_PARTY_NOTICES.md +37 -0
  10. package/sdk/bun.lock +539 -0
  11. package/sdk/package.json +60 -0
  12. package/sdk/preview/fixtures/empty.json +6 -0
  13. package/sdk/preview/fonts/NotoSans-LICENSE.txt +94 -0
  14. package/sdk/preview/fonts/NotoSans-Regular.ttf +0 -0
  15. package/sdk/preview/fonts/NotoSansCJK-LICENSE.txt +92 -0
  16. package/sdk/preview/fonts/NotoSansCJKsc-Regular.otf +0 -0
  17. package/sdk/preview/fonts/PROVENANCE.md +25 -0
  18. package/sdk/preview/fonts/fonts.json +60 -0
  19. package/sdk/preview/profiles/default.json +32 -0
  20. package/sdk/preview/scenarios/counter-capture.json +9 -0
  21. package/sdk/smoke/solid-smoke.ts +53 -0
  22. package/sdk/smoke/tsconfig.smoke.json +21 -0
  23. package/src/application.ts +70 -0
  24. package/src/build.ts +963 -0
  25. package/src/check-smoke.ts +8 -0
  26. package/src/compiler.ts +701 -0
  27. package/src/css.ts +337 -0
  28. package/src/dev.ts +164 -0
  29. package/src/host.ts +578 -0
  30. package/src/identity.ts +60 -0
  31. package/src/index.ts +27 -0
  32. package/src/internal.ts +20 -0
  33. package/src/native-process.ts +178 -0
  34. package/src/package-app.ts +178 -0
  35. package/src/preview-check.ts +267 -0
  36. package/src/preview.ts +69 -0
  37. package/src/public-api.d.ts +258 -0
  38. package/src/publication.ts +108 -0
  39. package/src/sdk-packages.ts +376 -0
  40. package/src/sdk.ts +11 -0
  41. package/src/smoke.ts +99 -0
  42. package/src/sync-ui-resources.ts +171 -0
  43. package/src/typecheck.ts +177 -0
  44. package/src/validate.ts +1085 -0
  45. package/src/watch.ts +531 -0
package/src/host.ts ADDED
@@ -0,0 +1,578 @@
1
+ import type { NativeHostAbi, ResolvedNativeHost, ResolveNativeHostOptions } from "./index.ts";
2
+ import { createHash } from "node:crypto";
3
+ import {
4
+ accessSync,
5
+ constants as fsConstants,
6
+ existsSync,
7
+ readFileSync,
8
+ realpathSync,
9
+ statSync,
10
+ } from "node:fs";
11
+ import { chmod, copyFile, mkdir, readFile, stat, writeFile } from "node:fs/promises";
12
+ import { createRequire } from "node:module";
13
+ import path from "node:path";
14
+ import { prepareNativeHost } from "./native-process.ts";
15
+ import { packagedSdkRoot, workspaceRoot } from "./sdk.ts";
16
+
17
+ export const EXPECTED_HOST_API_VERSION = 1;
18
+ export const EXPECTED_SCHEMA_VERSION = 2;
19
+
20
+ export const SUPPORTED_HOST_PACKAGES: Readonly<Record<string, string>> = Object.freeze({
21
+ "linux-x64": "@hewel/zgui-host-linux-x64",
22
+ "linux-arm64": "@hewel/zgui-host-linux-arm64",
23
+ });
24
+
25
+ export interface StagedHostManifest {
26
+ readonly schemaVersion: 1;
27
+ readonly package: string;
28
+ readonly platform: string;
29
+ readonly version: string;
30
+ readonly hostApiVersion: number;
31
+ readonly bundleSchemaVersion: number;
32
+ readonly sha256: string;
33
+ readonly bytes: number;
34
+ readonly libc?: "glibc" | undefined;
35
+ readonly glibcBaseline?: string | undefined;
36
+ }
37
+
38
+ function hostFailure(message: string, exitCode = 1): Error & { exitCode: number } {
39
+ return Object.assign(new Error(message), { exitCode });
40
+ }
41
+
42
+ export function platformId(
43
+ platform: string = process.platform,
44
+ arch: string = process.arch,
45
+ ): string {
46
+ return `${platform}-${arch}`;
47
+ }
48
+
49
+ export function platformHostPackageName(
50
+ platform: string = process.platform,
51
+ arch: string = process.arch,
52
+ ): string | undefined {
53
+ return SUPPORTED_HOST_PACKAGES[platformId(platform, arch)];
54
+ }
55
+
56
+ function hasCargoNativeHost(directory: string): boolean {
57
+ return (
58
+ existsSync(path.join(directory, "Cargo.toml")) &&
59
+ existsSync(path.join(directory, "crates/zgui-host/Cargo.toml"))
60
+ );
61
+ }
62
+
63
+ function findCargoCheckoutUpwards(startDir: string): string | undefined {
64
+ let current = path.resolve(startDir);
65
+ while (true) {
66
+ if (hasCargoNativeHost(current)) return current;
67
+ const parent = path.dirname(current);
68
+ if (parent === current) return undefined;
69
+ current = parent;
70
+ }
71
+ }
72
+
73
+ function parseVersionText(text: string): NativeHostAbi | null {
74
+ const trimmed = text.trim();
75
+ if (!trimmed) return null;
76
+ if (trimmed.startsWith("{")) {
77
+ try {
78
+ const parsed = JSON.parse(trimmed) as Record<string, unknown>;
79
+ if (
80
+ parsed.name !== "zgui-host" ||
81
+ typeof parsed.version !== "string" ||
82
+ typeof parsed.hostApiVersion !== "number" ||
83
+ typeof parsed.schemaVersion !== "number" ||
84
+ typeof parsed.platform !== "string"
85
+ ) {
86
+ return null;
87
+ }
88
+ return {
89
+ name: "zgui-host",
90
+ version: parsed.version,
91
+ hostApiVersion: parsed.hostApiVersion,
92
+ schemaVersion: parsed.schemaVersion,
93
+ platform: parsed.platform,
94
+ ...(typeof parsed.engine === "string" ? { engine: parsed.engine } : {}),
95
+ ...(typeof parsed.engineRevision === "string"
96
+ ? { engineRevision: parsed.engineRevision }
97
+ : {}),
98
+ ...(typeof parsed.bytecodeFormat === "string"
99
+ ? { bytecodeFormat: parsed.bytecodeFormat }
100
+ : {}),
101
+ ...(typeof parsed.quickjsAbi === "string" ? { quickjsAbi: parsed.quickjsAbi } : {}),
102
+ ...(typeof parsed.styleProfile === "string" ? { styleProfile: parsed.styleProfile } : {}),
103
+ };
104
+ } catch {
105
+ return null;
106
+ }
107
+ }
108
+ const match = trimmed.match(
109
+ /^zgui-host\s+(\S+)\s+\(hostApiVersion=(\d+)\s+schemaVersion=(\d+)(?:\s+platform=([^\s)]+))?\)$/,
110
+ );
111
+ if (!match) return null;
112
+ return {
113
+ name: "zgui-host",
114
+ version: match[1]!,
115
+ hostApiVersion: Number(match[2]),
116
+ schemaVersion: Number(match[3]),
117
+ platform: match[4] ?? platformId(),
118
+ };
119
+ }
120
+
121
+ export function probeNativeHost(
122
+ executable: string,
123
+ {
124
+ expectedHostApiVersion = EXPECTED_HOST_API_VERSION,
125
+ expectedSchemaVersion = EXPECTED_SCHEMA_VERSION,
126
+ }: {
127
+ expectedHostApiVersion?: number;
128
+ expectedSchemaVersion?: number;
129
+ } = {},
130
+ ): NativeHostAbi {
131
+ const resolved = path.resolve(executable);
132
+ if (!existsSync(resolved)) {
133
+ throw hostFailure(`zgui-host executable not found: ${resolved}`);
134
+ }
135
+ try {
136
+ accessSync(resolved, fsConstants.X_OK);
137
+ } catch {
138
+ throw hostFailure(`zgui-host executable is not executable: ${resolved}`);
139
+ }
140
+ const child = Bun.spawnSync([resolved, "--version", "--json"], {
141
+ stdin: "ignore",
142
+ stdout: "pipe",
143
+ stderr: "pipe",
144
+ timeout: 5000,
145
+ });
146
+ if (!child.success) {
147
+ const detail = `${child.stderr.toString()}${child.stdout.toString()}`.trim();
148
+ throw hostFailure(
149
+ `zgui-host ABI handshake failed (${resolved} --version --json exited with ${child.signalCode ?? child.exitCode})${detail ? `: ${detail}` : ""}`,
150
+ );
151
+ }
152
+ const stdout = child.stdout.toString("utf8").trim();
153
+ const abi = parseVersionText(stdout);
154
+ if (!abi) {
155
+ throw hostFailure(
156
+ `zgui-host ABI handshake returned unrecognized version metadata from ${resolved}: ${stdout || "(empty output)"}`,
157
+ );
158
+ }
159
+ if (
160
+ abi.hostApiVersion !== expectedHostApiVersion ||
161
+ abi.schemaVersion !== expectedSchemaVersion
162
+ ) {
163
+ throw hostFailure(
164
+ `zgui-host ABI mismatch at ${resolved}: host reports hostApiVersion=${abi.hostApiVersion} schemaVersion=${abi.schemaVersion}, expected hostApiVersion=${expectedHostApiVersion} schemaVersion=${expectedSchemaVersion}`,
165
+ );
166
+ }
167
+ return abi;
168
+ }
169
+
170
+ function sha256File(filename: string): string {
171
+ return `sha256:${createHash("sha256").update(readFileSync(filename)).digest("hex")}`;
172
+ }
173
+
174
+ function tryResolvePlatformPackage(
175
+ packageName: string,
176
+ searchFrom: readonly string[],
177
+ ): string | undefined {
178
+ for (const base of searchFrom) {
179
+ try {
180
+ const anchor = existsSync(path.join(base, "package.json"))
181
+ ? path.join(base, "package.json")
182
+ : base;
183
+ const req = createRequire(anchor);
184
+ return path.dirname(req.resolve(`${packageName}/package.json`));
185
+ } catch (error) {
186
+ const code = (error as NodeJS.ErrnoException).code;
187
+ if (code === "MODULE_NOT_FOUND" || code === "ERR_PACKAGE_PATH_NOT_EXPORTED") continue;
188
+ throw error;
189
+ }
190
+ }
191
+ return undefined;
192
+ }
193
+
194
+ function parseStagedManifest(manifestPath: string, label: string): StagedHostManifest {
195
+ if (!existsSync(manifestPath)) {
196
+ throw hostFailure(
197
+ `Missing host-manifest.json in ${label} (refusing to execute unverified binary)`,
198
+ );
199
+ }
200
+ let parsed: unknown;
201
+ try {
202
+ parsed = JSON.parse(readFileSync(manifestPath, "utf8"));
203
+ } catch (error) {
204
+ throw hostFailure(
205
+ `Malformed host-manifest.json in ${label}: ${error instanceof Error ? error.message : String(error)}`,
206
+ );
207
+ }
208
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
209
+ throw hostFailure(`Invalid host-manifest.json in ${label}: expected JSON object`);
210
+ }
211
+ return parsed as StagedHostManifest;
212
+ }
213
+
214
+ function validateStagedManifest({
215
+ manifest,
216
+ binaryPath,
217
+ expectedPackage,
218
+ expectedPlatform,
219
+ expectedVersion,
220
+ }: {
221
+ manifest: StagedHostManifest;
222
+ binaryPath: string;
223
+ expectedPackage: string;
224
+ expectedPlatform: string;
225
+ expectedVersion?: string;
226
+ }): void {
227
+ if (manifest.schemaVersion !== 1) {
228
+ throw hostFailure(
229
+ `Unsupported host-manifest.json schemaVersion in ${expectedPackage}: ${String(manifest.schemaVersion)}`,
230
+ );
231
+ }
232
+ if (manifest.package !== expectedPackage) {
233
+ throw hostFailure(
234
+ `Prebuilt host manifest package mismatch: expected ${expectedPackage}, got ${String(manifest.package)}`,
235
+ );
236
+ }
237
+ if (manifest.platform !== expectedPlatform) {
238
+ throw hostFailure(
239
+ `Prebuilt host manifest platform mismatch in ${expectedPackage}: expected ${expectedPlatform}, got ${String(manifest.platform)}`,
240
+ );
241
+ }
242
+ if (typeof manifest.version !== "string" || !manifest.version.trim()) {
243
+ throw hostFailure(`Prebuilt host manifest missing version in ${expectedPackage}`);
244
+ }
245
+ if (expectedVersion !== undefined && manifest.version !== expectedVersion) {
246
+ throw hostFailure(
247
+ `Prebuilt host manifest version mismatch in ${expectedPackage}: expected ${expectedVersion}, got ${manifest.version}`,
248
+ );
249
+ }
250
+ if (
251
+ manifest.hostApiVersion !== EXPECTED_HOST_API_VERSION ||
252
+ manifest.bundleSchemaVersion !== EXPECTED_SCHEMA_VERSION
253
+ ) {
254
+ throw hostFailure(
255
+ `Prebuilt host manifest ABI mismatch in ${expectedPackage}: hostApiVersion=${String(manifest.hostApiVersion)} bundleSchemaVersion=${String(manifest.bundleSchemaVersion)}, expected hostApiVersion=${EXPECTED_HOST_API_VERSION} bundleSchemaVersion=${EXPECTED_SCHEMA_VERSION}`,
256
+ );
257
+ }
258
+ const actualBytes = statSync(binaryPath).size;
259
+ if (typeof manifest.bytes !== "number" || manifest.bytes !== actualBytes) {
260
+ throw hostFailure(
261
+ `Prebuilt host integrity mismatch (size) in ${expectedPackage}: expected ${String(manifest.bytes)} bytes, got ${actualBytes}`,
262
+ );
263
+ }
264
+ const actualDigest = sha256File(binaryPath);
265
+ if (typeof manifest.sha256 !== "string" || manifest.sha256 !== actualDigest) {
266
+ throw hostFailure(
267
+ `Prebuilt host integrity mismatch in ${expectedPackage}: expected ${String(manifest.sha256)}, got ${actualDigest}`,
268
+ );
269
+ }
270
+ }
271
+
272
+ function resolveEntryScriptDir(): string | undefined {
273
+ const arg = process.argv[1];
274
+ if (typeof arg !== "string" || !arg || !existsSync(arg)) return undefined;
275
+ try {
276
+ return path.dirname(realpathSync(arg));
277
+ } catch {
278
+ return path.dirname(path.resolve(arg));
279
+ }
280
+ }
281
+
282
+ export async function resolveNativeHost({
283
+ hostExecutable,
284
+ hostRoot,
285
+ root = workspaceRoot,
286
+ cwd = process.cwd(),
287
+ env = process.env,
288
+ platform = process.platform,
289
+ arch = process.arch,
290
+ searchFrom = [],
291
+ verifyAbi = true,
292
+ allowCargoBuild = true,
293
+ signal,
294
+ }: ResolveNativeHostOptions = {}): Promise<ResolvedNativeHost> {
295
+ signal?.throwIfAborted();
296
+ const resolvedCwd = path.resolve(cwd);
297
+
298
+ // 1. Explicit --host-executable or ZGUI_JS_HOST_EXECUTABLE environment variable.
299
+ const explicitRaw = hostExecutable?.trim() || undefined;
300
+ const envRaw = env.ZGUI_JS_HOST_EXECUTABLE?.trim() || undefined;
301
+ if (explicitRaw !== undefined || envRaw !== undefined) {
302
+ const source = explicitRaw !== undefined ? "explicit" : "env";
303
+ const candidate = path.resolve(resolvedCwd, (explicitRaw ?? envRaw)!);
304
+ const abi = verifyAbi ? probeNativeHost(candidate) : undefined;
305
+ return {
306
+ executable: candidate,
307
+ source,
308
+ ...(abi ? { abi } : {}),
309
+ };
310
+ }
311
+
312
+ // 2. Installed platform package (@hewel/zgui-host-<os>-<arch>) with mandatory manifest + ABI checks.
313
+ const currentPlatform = platformId(platform, arch);
314
+ const packageName = platformHostPackageName(platform, arch);
315
+ if (packageName) {
316
+ const entryScript = resolveEntryScriptDir();
317
+ const searchBases = [
318
+ ...searchFrom,
319
+ resolvedCwd,
320
+ ...(entryScript ? [entryScript] : []),
321
+ path.resolve(root),
322
+ import.meta.url,
323
+ ];
324
+ const pkgDir = tryResolvePlatformPackage(packageName, searchBases);
325
+ if (pkgDir) {
326
+ const binaryPath = path.join(pkgDir, "bin", "zgui-host");
327
+ const manifestPath = path.join(pkgDir, "host-manifest.json");
328
+ if (existsSync(binaryPath)) {
329
+ const manifest = parseStagedManifest(manifestPath, packageName);
330
+ validateStagedManifest({
331
+ manifest,
332
+ binaryPath,
333
+ expectedPackage: packageName,
334
+ expectedPlatform: currentPlatform,
335
+ });
336
+ const abi = verifyAbi ? probeNativeHost(binaryPath) : undefined;
337
+ return {
338
+ executable: binaryPath,
339
+ source: "platform-package",
340
+ packageName,
341
+ ...(abi ? { abi } : {}),
342
+ };
343
+ }
344
+ if (existsSync(manifestPath)) {
345
+ throw hostFailure(
346
+ `Incomplete prebuilt host package ${packageName}: found host-manifest.json without bin/zgui-host`,
347
+ );
348
+ }
349
+ }
350
+ }
351
+
352
+ // 3. Local Cargo workspace build (--host-root or detected checkout containing crates/zgui-host).
353
+ const resolvedRoot = path.resolve(root);
354
+ const cargoRoot =
355
+ hostRoot !== undefined
356
+ ? path.resolve(resolvedCwd, hostRoot)
357
+ : resolvedRoot !== packagedSdkRoot && hasCargoNativeHost(resolvedRoot)
358
+ ? resolvedRoot
359
+ : findCargoCheckoutUpwards(resolvedCwd);
360
+
361
+ if (cargoRoot !== undefined) {
362
+ if (!allowCargoBuild) {
363
+ for (const rel of ["target/debug/zgui-host", "target/release/zgui-host"]) {
364
+ const built = path.join(cargoRoot, rel);
365
+ if (existsSync(built)) {
366
+ const abi = verifyAbi ? probeNativeHost(built) : undefined;
367
+ return {
368
+ executable: built,
369
+ source: "cargo",
370
+ cargoRoot,
371
+ ...(abi ? { abi } : {}),
372
+ };
373
+ }
374
+ }
375
+ throw hostFailure(
376
+ `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\`.`,
377
+ );
378
+ }
379
+ const executable = await prepareNativeHost({ root: cargoRoot, signal });
380
+ return {
381
+ executable,
382
+ source: "cargo",
383
+ cargoRoot,
384
+ };
385
+ }
386
+
387
+ // 4. Actionable error when no prebuilt host or Cargo checkout is available.
388
+ const installHint = packageName
389
+ ? `Install the prebuilt host package (${packageName})`
390
+ : `No prebuilt host package is published for ${currentPlatform}`;
391
+ throw hostFailure(
392
+ `Cannot locate a zgui-js zgui-host binary for ${currentPlatform}.\n` +
393
+ ` 1. ${installHint} (included in @hewel/zgui-cli optionalDependencies on supported platforms), or\n` +
394
+ ` 2. Pass --host-executable <PATH> or set ZGUI_JS_HOST_EXECUTABLE=<PATH>, or\n` +
395
+ ` 3. Pass --host-root <DIR> pointing to a zgui-js Cargo checkout containing crates/zgui-host.`,
396
+ );
397
+ }
398
+
399
+ export async function stageHostPackage({
400
+ platform,
401
+ binary,
402
+ packageDir,
403
+ skipProbe = false,
404
+ glibcBaseline,
405
+ }: {
406
+ platform: string;
407
+ binary: string;
408
+ packageDir?: string;
409
+ skipProbe?: boolean;
410
+ glibcBaseline?: string;
411
+ }): Promise<{
412
+ packageDir: string;
413
+ binaryPath: string;
414
+ manifestPath: string;
415
+ manifest: StagedHostManifest;
416
+ }> {
417
+ const packageName = SUPPORTED_HOST_PACKAGES[platform];
418
+ if (!packageName) {
419
+ throw hostFailure(
420
+ `Unsupported host platform "${platform}". Expected one of: ${Object.keys(SUPPORTED_HOST_PACKAGES).join(", ")}`,
421
+ );
422
+ }
423
+ const sourceBinary = path.resolve(binary);
424
+ if (!existsSync(sourceBinary)) {
425
+ throw hostFailure(`Source zgui-host binary not found: ${sourceBinary}`);
426
+ }
427
+ const targetDir = path.resolve(
428
+ packageDir ?? path.join(workspaceRoot, `packages/host-${platform}`),
429
+ );
430
+ const pkgJsonPath = path.join(targetDir, "package.json");
431
+ const pkgJson = JSON.parse(await readFile(pkgJsonPath, "utf8")) as {
432
+ name?: string;
433
+ version?: string;
434
+ };
435
+ if (pkgJson.name !== packageName || typeof pkgJson.version !== "string") {
436
+ throw hostFailure(`Invalid platform host package manifest at ${pkgJsonPath}`);
437
+ }
438
+
439
+ let version = pkgJson.version;
440
+ let hostApiVersion = EXPECTED_HOST_API_VERSION;
441
+ let bundleSchemaVersion = EXPECTED_SCHEMA_VERSION;
442
+ if (!skipProbe) {
443
+ const abi = probeNativeHost(sourceBinary);
444
+ if (abi.platform !== platform) {
445
+ throw hostFailure(
446
+ `Platform mismatch staging ${packageName}: binary reports platform=${abi.platform}, expected ${platform}`,
447
+ );
448
+ }
449
+ if (abi.version !== pkgJson.version) {
450
+ throw hostFailure(
451
+ `Version mismatch staging ${packageName}: binary reports version=${abi.version}, expected package.json version=${pkgJson.version}`,
452
+ );
453
+ }
454
+ version = abi.version;
455
+ hostApiVersion = abi.hostApiVersion;
456
+ bundleSchemaVersion = abi.schemaVersion;
457
+ }
458
+
459
+ const binDir = path.join(targetDir, "bin");
460
+ const destBinary = path.join(binDir, "zgui-host");
461
+ await mkdir(binDir, { recursive: true });
462
+ await copyFile(sourceBinary, destBinary);
463
+ await chmod(destBinary, 0o755);
464
+
465
+ const info = await stat(destBinary);
466
+ const manifest: StagedHostManifest = {
467
+ schemaVersion: 1,
468
+ package: packageName,
469
+ platform,
470
+ version,
471
+ hostApiVersion,
472
+ bundleSchemaVersion,
473
+ sha256: sha256File(destBinary),
474
+ bytes: info.size,
475
+ ...(platform.startsWith("linux-") ? { libc: "glibc" as const } : {}),
476
+ ...(glibcBaseline ? { glibcBaseline } : {}),
477
+ };
478
+ const manifestPath = path.join(targetDir, "host-manifest.json");
479
+ await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
480
+ return { packageDir: targetDir, binaryPath: destBinary, manifestPath, manifest };
481
+ }
482
+
483
+ export async function verifyHostPackage(
484
+ packageDir: string,
485
+ { verifyAbi = true }: { verifyAbi?: boolean } = {},
486
+ ): Promise<{ manifest: StagedHostManifest; binaryPath: string; abi?: NativeHostAbi }> {
487
+ const dir = path.resolve(packageDir);
488
+ const pkgJson = JSON.parse(await readFile(path.join(dir, "package.json"), "utf8")) as {
489
+ name?: string;
490
+ version?: string;
491
+ };
492
+ if (typeof pkgJson.name !== "string" || typeof pkgJson.version !== "string") {
493
+ throw hostFailure(`Invalid package.json in ${dir}`);
494
+ }
495
+ const binaryPath = path.join(dir, "bin", "zgui-host");
496
+ if (!existsSync(binaryPath)) {
497
+ throw hostFailure(`Missing staged binary: ${binaryPath}`);
498
+ }
499
+ const manifest = parseStagedManifest(path.join(dir, "host-manifest.json"), pkgJson.name);
500
+ const expectedPlatform = Object.entries(SUPPORTED_HOST_PACKAGES).find(
501
+ ([, name]) => name === pkgJson.name,
502
+ )?.[0];
503
+ validateStagedManifest({
504
+ manifest,
505
+ binaryPath,
506
+ expectedPackage: pkgJson.name,
507
+ expectedPlatform: expectedPlatform ?? manifest.platform,
508
+ expectedVersion: pkgJson.version,
509
+ });
510
+ const abi = verifyAbi ? probeNativeHost(binaryPath) : undefined;
511
+ if (abi && abi.version !== pkgJson.version) {
512
+ throw hostFailure(
513
+ `Staged host version mismatch in ${dir}: binary reports ${abi.version}, expected ${pkgJson.version}`,
514
+ );
515
+ }
516
+ if (abi && expectedPlatform && abi.platform !== expectedPlatform) {
517
+ throw hostFailure(
518
+ `Staged host platform mismatch in ${dir}: binary reports ${abi.platform}, expected ${expectedPlatform}`,
519
+ );
520
+ }
521
+ return { manifest, binaryPath, ...(abi ? { abi } : {}) };
522
+ }
523
+
524
+ export async function compileModuleBytecode(
525
+ hostExecutable: string,
526
+ {
527
+ input,
528
+ output,
529
+ moduleName,
530
+ sourceDir,
531
+ signal,
532
+ }: {
533
+ input: string;
534
+ output: string;
535
+ moduleName: string;
536
+ sourceDir?: string;
537
+ signal?: AbortSignal;
538
+ },
539
+ ): Promise<Buffer> {
540
+ signal?.throwIfAborted();
541
+ const child = Bun.spawn(
542
+ [
543
+ path.resolve(hostExecutable),
544
+ "compile-bytecode",
545
+ "--input",
546
+ path.resolve(input),
547
+ "--output",
548
+ path.resolve(output),
549
+ "--module-name",
550
+ moduleName,
551
+ ...(sourceDir ? ["--source-dir", path.resolve(sourceDir)] : []),
552
+ ],
553
+ {
554
+ stdin: "ignore",
555
+ stdout: "pipe",
556
+ stderr: "pipe",
557
+ },
558
+ );
559
+ const onAbort = () => child.kill("SIGTERM");
560
+ signal?.addEventListener("abort", onAbort, { once: true });
561
+ try {
562
+ const [code, stdout, stderr] = await Promise.all([
563
+ child.exited,
564
+ new Response(child.stdout).text(),
565
+ new Response(child.stderr).text(),
566
+ ]);
567
+ if (code !== 0 || child.signalCode) {
568
+ const detail = `${stderr}${stdout}`.trim();
569
+ throw hostFailure(
570
+ `zgui-host compile-bytecode failed for ${moduleName} (exit ${child.signalCode ?? code})${detail ? `: ${detail}` : ""}`,
571
+ );
572
+ }
573
+ return Buffer.from(await readFile(output));
574
+ } finally {
575
+ signal?.removeEventListener("abort", onAbort);
576
+ signal?.throwIfAborted();
577
+ }
578
+ }
@@ -0,0 +1,60 @@
1
+ import path from "node:path";
2
+ import { readFileSync, realpathSync } from "node:fs";
3
+
4
+ export type JsonValue =
5
+ | null
6
+ | boolean
7
+ | number
8
+ | string
9
+ | JsonValue[]
10
+ | { [key: string]: JsonValue };
11
+
12
+ export function sha256(bytes: string | Uint8Array): string {
13
+ return `sha256:${new Bun.CryptoHasher("sha256").update(bytes).digest("hex")}`;
14
+ }
15
+
16
+ export function canonicalJson(value: JsonValue): string {
17
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
18
+ if (value !== null && typeof value === "object") {
19
+ return `{${Object.keys(value)
20
+ .sort()
21
+ .map(key => `${JSON.stringify(key)}:${canonicalJson(value[key])}`)
22
+ .join(",")}}`;
23
+ }
24
+ return JSON.stringify(value);
25
+ }
26
+
27
+ const inside = (directory: string, filename: string) => {
28
+ const relative = path.relative(directory, filename);
29
+ return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
30
+ };
31
+ const posix = (filename: string) => filename.split(path.sep).join("/");
32
+
33
+ // Resolve links before assigning identities so symlinks cannot manufacture two origins.
34
+ export function moduleIdentity(
35
+ filename: string,
36
+ { root, appDirectory }: { root: string; appDirectory: string },
37
+ ): string {
38
+ const absolute = realpathSync(filename);
39
+ const application = realpathSync(appDirectory);
40
+ const appRelative = path.relative(application, absolute);
41
+ if (inside(application, absolute) && !appRelative.split(path.sep).includes("node_modules"))
42
+ return `app/${posix(appRelative)}`;
43
+ for (let directory = path.dirname(absolute); ;) {
44
+ try {
45
+ const pkg = JSON.parse(readFileSync(path.join(directory, "package.json"), "utf8")) as {
46
+ name?: unknown;
47
+ };
48
+ if (typeof pkg.name === "string" && pkg.name) {
49
+ return `packages/${pkg.name}/${posix(path.relative(directory, absolute))}`;
50
+ }
51
+ } catch (error) {
52
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
53
+ }
54
+ const parent = path.dirname(directory);
55
+ if (parent === directory) break;
56
+ directory = parent;
57
+ }
58
+ if (inside(root, absolute)) return `workspace/${posix(path.relative(root, absolute))}`;
59
+ throw new Error(`Cannot establish package-relative module identity: ${filename}`);
60
+ }
package/src/index.ts ADDED
@@ -0,0 +1,27 @@
1
+ import type * as Implementation from "./index.ts";
2
+ import type * as Public from "./public-api.d.ts";
3
+ import { resolveApplication as resolve } from "./application.ts";
4
+ import { buildApplication as build } from "./build.ts";
5
+ import { devApplication as dev } from "./dev.ts";
6
+ import { probeNativeHost as probe, resolveNativeHost as resolveHost } from "./host.ts";
7
+ import { prepareNativeHost as prepare, runNativeHost as run } from "./native-process.ts";
8
+ import { packageApplication as packApp } from "./package-app.ts";
9
+ import { previewApplication as preview } from "./preview.ts";
10
+ import { watchApplication as watch } from "./watch.ts";
11
+
12
+ export type * from "./public-api.d.ts";
13
+
14
+ export const buildApplication: typeof Public.buildApplication = build;
15
+ export const watchApplication: typeof Public.watchApplication = watch;
16
+ export const devApplication: typeof Public.devApplication = dev;
17
+ export const previewApplication: typeof Public.previewApplication = preview;
18
+ export const packageApplication: typeof Public.packageApplication = packApp;
19
+ export const resolveApplication: typeof Public.resolveApplication = resolve;
20
+ export const prepareNativeHost: typeof Public.prepareNativeHost = prepare;
21
+ export const probeNativeHost: typeof Public.probeNativeHost = probe;
22
+ export const resolveNativeHost: typeof Public.resolveNativeHost = resolveHost;
23
+ export const runNativeHost: typeof Public.runNativeHost = run;
24
+
25
+ type Assert<T extends true> = T;
26
+ type ExactKeys<A, B> = [A, B] extends [B, A] ? true : false;
27
+ type _ValueExportParity = Assert<ExactKeys<keyof typeof Implementation, keyof typeof Public>>;
@@ -0,0 +1,20 @@
1
+ export { workspaceRoot, packagedSdkRoot } from "./sdk.ts";
2
+ export { buildSmoke, resolveSmokeTsconfigPath } from "./smoke.ts";
3
+ export { typecheckProject } from "./typecheck.ts";
4
+ export {
5
+ buildSdkPackages,
6
+ ensureSdkPackagesBuilt,
7
+ hasCheckoutSdkSources,
8
+ type SdkPackageName,
9
+ } from "./sdk-packages.ts";
10
+ export { extractStaticComponentSheet, type StaticComponentSheet } from "./compiler.ts";
11
+ export {
12
+ EXPECTED_HOST_API_VERSION,
13
+ EXPECTED_SCHEMA_VERSION,
14
+ SUPPORTED_HOST_PACKAGES,
15
+ platformHostPackageName,
16
+ platformId,
17
+ stageHostPackage,
18
+ verifyHostPackage,
19
+ type StagedHostManifest,
20
+ } from "./host.ts";