@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
@@ -0,0 +1,8 @@
1
+ import assert from "node:assert/strict";
2
+
3
+ // The generated bundle does not exist when the build tools are typechecked.
4
+ const artifact = new URL("../../../target/solid-smoke.mjs", import.meta.url);
5
+ const { runSmoke }: { runSmoke: () => unknown } = await import(artifact.href);
6
+ assert.equal(runSmoke(), "solid-smoke:ok");
7
+ assert.equal(runSmoke(), "solid-smoke:ok");
8
+ console.log("solid-smoke:ok (two synchronous runs, cleanup verified)");
@@ -0,0 +1,701 @@
1
+ import path from "node:path";
2
+ import { realpathSync } from "node:fs";
3
+ import { realpath } from "node:fs/promises";
4
+ import {
5
+ transform as solidTransform,
6
+ type TransformOptions as SolidTransformOptions,
7
+ type TransformResult as SolidTransformResult,
8
+ } from "@solidjs/compiler";
9
+ import {
10
+ rolldown,
11
+ watch as watchCompiler,
12
+ type InputOptions,
13
+ type OutputAsset,
14
+ type OutputChunk,
15
+ type OutputOptions,
16
+ type Plugin,
17
+ type PluginContext,
18
+ type SourceDescription,
19
+ } from "rolldown";
20
+ import { parseSync } from "rolldown/utils";
21
+ import { styleSystem, transformStylesheet, validateStylesheet, type StyleSystem } from "./css.ts";
22
+ import { moduleIdentity } from "./identity.ts";
23
+ import {
24
+ validateImport,
25
+ validateWorkerImport,
26
+ validateModule,
27
+ validateGraph,
28
+ type CompilationGraph,
29
+ } from "./validate.ts";
30
+
31
+ export interface CompilationResult {
32
+ files: Map<string, Buffer>;
33
+ graph: CompilationGraph;
34
+ solidRuntime: string;
35
+ styleSystem: StyleSystem;
36
+ }
37
+
38
+ export type JsxTransform = (
39
+ source: string,
40
+ options: SolidTransformOptions,
41
+ ) =>
42
+ | Pick<SolidTransformResult, "code" | "map">
43
+ | null
44
+ | Promise<Pick<SolidTransformResult, "code" | "map"> | null>;
45
+
46
+ interface CompilerOptions {
47
+ root: string;
48
+ appDirectory?: string;
49
+ plugins?: Plugin[];
50
+ jsxTransform?: JsxTransform;
51
+ development?: boolean;
52
+ hoistComponentStyles?: boolean;
53
+ }
54
+
55
+ export interface CompileBundleOptions extends CompilerOptions {
56
+ hostEntry?: boolean;
57
+ filename?: string;
58
+ }
59
+
60
+ export interface WatchBundleOptions extends Omit<CompilerOptions, "plugins"> {
61
+ temporaryDirectory?: string;
62
+ filename?: string;
63
+ buildDelay?: number;
64
+ watchFiles?: string[];
65
+ onAttempt?: () => void | Promise<void>;
66
+ onCompile?: (result: CompilationResult) => void | Promise<void>;
67
+ onError?: (error: unknown) => void | Promise<void>;
68
+ }
69
+
70
+ export interface BundleWatcher {
71
+ close(): Promise<void>;
72
+ }
73
+
74
+ export interface StaticComponentSheet {
75
+ readonly name: string;
76
+ readonly className: string;
77
+ readonly css: string;
78
+ }
79
+
80
+ const GENERATED_STYLE_FILE =
81
+ /(?:^|[\\/])components[\\/]generated[\\/][A-Za-z0-9]+Style\.[cm]?[jt]s$/;
82
+
83
+ const JSX_SOURCE_FILE = /\.[cm]?[jt]sx$/i;
84
+
85
+ function computeLineStarts(source: string): number[] {
86
+ const starts = [0];
87
+ for (let i = 0; i < source.length; i++) {
88
+ if (source.charCodeAt(i) === 10) starts.push(i + 1);
89
+ }
90
+ return starts;
91
+ }
92
+
93
+ function offsetToLineCol(starts: readonly number[], offset: number): { line: number; col: number } {
94
+ let lo = 0;
95
+ let hi = starts.length - 1;
96
+ while (lo < hi) {
97
+ const mid = (lo + hi + 1) >> 1;
98
+ if (starts[mid]! <= offset) lo = mid;
99
+ else hi = mid - 1;
100
+ }
101
+ return { line: lo + 1, col: offset - starts[lo]! + 1 };
102
+ }
103
+
104
+ function injectDevJsxSourceLocations(source: string, filename: string, identity: string): string {
105
+ const parsed = parseSync(filename, source, {
106
+ sourceType: "module",
107
+ lang: /\.[cm]?tsx$/i.test(filename) ? "tsx" : "jsx",
108
+ });
109
+ if (parsed.errors.length > 0) return source;
110
+
111
+ const edits: { offset: number; text: string }[] = [];
112
+ const lineStarts = computeLineStarts(source);
113
+ const stack: unknown[] = [parsed.program];
114
+
115
+ while (stack.length > 0) {
116
+ const current = stack.pop();
117
+ if (!current || typeof current !== "object") continue;
118
+ if (Array.isArray(current)) {
119
+ for (const item of current) stack.push(item);
120
+ continue;
121
+ }
122
+ const node = current as Record<string, unknown>;
123
+ if (
124
+ node.type === "JSXOpeningElement" &&
125
+ node.name &&
126
+ typeof node.name === "object" &&
127
+ (node.name as Record<string, unknown>).type === "JSXIdentifier" &&
128
+ typeof (node.name as Record<string, unknown>).name === "string" &&
129
+ /^[a-z]/.test((node.name as Record<string, unknown>).name as string) &&
130
+ typeof node.start === "number" &&
131
+ typeof node.end === "number"
132
+ ) {
133
+ const attrs = Array.isArray(node.attributes) ? node.attributes : [];
134
+ const hasSource = attrs.some(
135
+ attr =>
136
+ attr &&
137
+ typeof attr === "object" &&
138
+ (attr as Record<string, unknown>).type === "JSXAttribute" &&
139
+ typeof (attr as Record<string, unknown>).name === "object" &&
140
+ ((attr as Record<string, unknown>).name as Record<string, unknown>)?.name ===
141
+ "data-zgui-source",
142
+ );
143
+ if (!hasSource) {
144
+ const selfClosing = node.selfClosing === true;
145
+ const insertAt = selfClosing ? node.end - 2 : node.end - 1;
146
+ const tail = source.slice(insertAt, node.end);
147
+ if ((selfClosing && tail === "/>") || (!selfClosing && tail === ">")) {
148
+ const { line, col } = offsetToLineCol(lineStarts, node.start);
149
+ edits.push({
150
+ offset: insertAt,
151
+ text: ` data-zgui-source=${JSON.stringify(`${identity}:${line}:${col}`)}`,
152
+ });
153
+ }
154
+ }
155
+ }
156
+ for (const [key, value] of Object.entries(node)) {
157
+ if (key === "start" || key === "end" || key === "type") continue;
158
+ if (value && typeof value === "object") stack.push(value);
159
+ }
160
+ }
161
+
162
+ if (edits.length === 0) return source;
163
+ edits.sort((a, b) => b.offset - a.offset);
164
+ let output = source;
165
+ for (const edit of edits) {
166
+ output = `${output.slice(0, edit.offset)}${edit.text}${output.slice(edit.offset)}`;
167
+ }
168
+ return output;
169
+ }
170
+
171
+ export function extractStaticComponentSheet(
172
+ source: string,
173
+ filename: string,
174
+ ): StaticComponentSheet | undefined {
175
+ if (!GENERATED_STYLE_FILE.test(filename)) return undefined;
176
+ const ast = parseSync(filename, source, {
177
+ sourceType: "module",
178
+ lang: /\.[cm]?ts$/i.test(filename) ? "ts" : "js",
179
+ });
180
+ if (ast.errors.length > 0 || ast.program.body.length !== 1) return undefined;
181
+ const statement = ast.program.body[0];
182
+ if (
183
+ statement?.type !== "ExportNamedDeclaration" ||
184
+ statement.declaration?.type !== "VariableDeclaration"
185
+ ) {
186
+ return undefined;
187
+ }
188
+ const decl = statement.declaration.declarations[0];
189
+ if (
190
+ statement.declaration.declarations.length !== 1 ||
191
+ decl?.id.type !== "Identifier" ||
192
+ decl.id.name !== "sheet" ||
193
+ !decl.init
194
+ ) {
195
+ return undefined;
196
+ }
197
+ const expr =
198
+ decl.init.type === "TSAsExpression" || decl.init.type === "TSSatisfiesExpression"
199
+ ? decl.init.expression
200
+ : decl.init;
201
+ if (expr.type !== "ObjectExpression") return undefined;
202
+ let name: string | undefined;
203
+ let className: string | undefined;
204
+ let css: string | undefined;
205
+ for (const prop of expr.properties) {
206
+ if (prop.type !== "Property" || prop.computed || prop.key.type !== "Identifier") {
207
+ return undefined;
208
+ }
209
+ if (prop.value.type !== "Literal" || typeof prop.value.value !== "string") return undefined;
210
+ if (prop.key.name === "name") name = prop.value.value;
211
+ else if (prop.key.name === "className") className = prop.value.value;
212
+ else if (prop.key.name === "css") css = prop.value.value;
213
+ else return undefined;
214
+ }
215
+ if (name === undefined || className === undefined || css === undefined) return undefined;
216
+ return { name, className, css };
217
+ }
218
+
219
+ interface CachedTransform {
220
+ source: string;
221
+ identity: string;
222
+ result: SourceDescription | null;
223
+ componentSheet?: StaticComponentSheet;
224
+ cssModuleCss?: string;
225
+ }
226
+
227
+ // Native Oxc Solid Universal JSX lowering + Rolldown TypeScript erasure + Lightning CSS Modules.
228
+ function compilerOptions(
229
+ entry: string,
230
+ {
231
+ root,
232
+ appDirectory = path.dirname(entry),
233
+ plugins = [],
234
+ jsxTransform = solidTransform,
235
+ development = false,
236
+ hoistComponentStyles = true,
237
+ }: CompilerOptions,
238
+ ): InputOptions {
239
+ const transforms = new Map<string, CachedTransform>();
240
+ function pruneTransforms(this: PluginContext): void {
241
+ const active = new Set<string>();
242
+ for (const id of this.getModuleIds()) {
243
+ active.add(id);
244
+ if (!id.startsWith("\0")) {
245
+ try {
246
+ active.add(realpathSync(id));
247
+ } catch {
248
+ // Ignore virtual or deleted module paths.
249
+ }
250
+ }
251
+ }
252
+ for (const filename of transforms.keys()) {
253
+ if (!active.has(filename)) transforms.delete(filename);
254
+ }
255
+ }
256
+ return {
257
+ cwd: appDirectory,
258
+ input: path.resolve(entry),
259
+ platform: "neutral",
260
+ experimental: { attachDebugInfo: "none" },
261
+ resolve: {
262
+ conditionNames: [development ? "development" : "production", "browser", "import", "default"],
263
+ mainFields: ["module", "main"],
264
+ modules: [
265
+ "node_modules",
266
+ path.join(appDirectory, "node_modules"),
267
+ path.join(root, "node_modules"),
268
+ ],
269
+ },
270
+ transform: {
271
+ target: "es2022",
272
+ define: { "process.env.NODE_ENV": development ? '"development"' : '"production"' },
273
+ typescript: { onlyRemoveTypeImports: true },
274
+ },
275
+ onwarn(warning, warn) {
276
+ if (warning.code === "UNRESOLVED_IMPORT") throw new Error(warning.message);
277
+ warn(warning);
278
+ },
279
+ plugins: [
280
+ {
281
+ name: "lightningcss-solid-universal-typescript",
282
+ resolveId(source) {
283
+ validateImport(source);
284
+ },
285
+ buildEnd: pruneTransforms,
286
+ outputOptions(options) {
287
+ return {
288
+ ...options,
289
+ sourcemapPathTransform(source, sourceMapPath) {
290
+ return moduleIdentity(path.resolve(path.dirname(sourceMapPath), source), {
291
+ root,
292
+ appDirectory,
293
+ });
294
+ },
295
+ };
296
+ },
297
+ generateBundle(_options, output) {
298
+ const reachable = new Set<string>();
299
+ for (const item of Object.values(output)) {
300
+ if (item.type !== "chunk") continue;
301
+ for (const id of item.moduleIds) {
302
+ if (id.startsWith("\0")) continue;
303
+ reachable.add(id);
304
+ try {
305
+ reachable.add(realpathSync(id));
306
+ } catch {
307
+ // Ignore virtual or non-filesystem module IDs.
308
+ }
309
+ }
310
+ }
311
+ const cssModuleParts = [...transforms.entries()]
312
+ .filter(
313
+ ([filename, record]) => record.cssModuleCss !== undefined && reachable.has(filename),
314
+ )
315
+ .map(([, record]) => record)
316
+ .sort((a, b) => (a.identity < b.identity ? -1 : a.identity > b.identity ? 1 : 0))
317
+ .map(record => record.cssModuleCss!)
318
+ .filter(part => part.length > 0);
319
+ const mergedModulesCss =
320
+ cssModuleParts.length > 0 ? `${cssModuleParts.join("\n\n")}\n` : "";
321
+ this.emitFile({ type: "asset", fileName: "app.css", source: mergedModulesCss });
322
+
323
+ if (hoistComponentStyles) {
324
+ const hoisted = new Map<string, string>();
325
+ for (const [filename, record] of transforms) {
326
+ if (!record.componentSheet || !reachable.has(filename)) continue;
327
+ if (record.componentSheet.css.trim().length === 0) continue;
328
+ hoisted.set(record.componentSheet.name, record.componentSheet.css);
329
+ }
330
+ if (hoisted.size > 0) {
331
+ const body = [...hoisted.entries()]
332
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
333
+ .map(([name, sheetCss]) => `/* ${name} */\n${sheetCss}`)
334
+ .join("\n");
335
+ const componentsCss = `${validateStylesheet(`@layer zgui.components {\n${body}\n}`, "components.css")}\n`;
336
+ this.emitFile({ type: "asset", fileName: "components.css", source: componentsCss });
337
+ }
338
+ }
339
+ },
340
+ closeWatcher() {
341
+ transforms.clear();
342
+ },
343
+ closeBundle() {
344
+ if (!this.meta.watchMode) transforms.clear();
345
+ },
346
+ async transform(source, filename) {
347
+ if (filename.startsWith("\0")) return null;
348
+ if (/\.module\.css$/i.test(filename)) {
349
+ const real = await realpath(filename);
350
+ const cached = transforms.get(real);
351
+ if (cached?.source === source) return cached.result;
352
+ const identity = moduleIdentity(real, { root, appDirectory });
353
+ const { css, exports: exportsMap } = transformStylesheet(source, {
354
+ filename: identity,
355
+ cssModules: true,
356
+ });
357
+ const code = `export default Object.freeze(${JSON.stringify(exportsMap, null, 2)});\n`;
358
+ const result: SourceDescription = {
359
+ code,
360
+ map: { version: 3, sources: [real], names: [], mappings: "AAAA" },
361
+ moduleType: "js",
362
+ };
363
+ transforms.set(real, {
364
+ source,
365
+ identity,
366
+ result,
367
+ cssModuleCss: css,
368
+ });
369
+ return result;
370
+ }
371
+ if (!/\.[cm]?[jt]sx?$/i.test(filename)) return null;
372
+ const real = await realpath(filename);
373
+ const cached = transforms.get(real);
374
+ if (cached?.source === source) return cached.result;
375
+ const identity = moduleIdentity(real, { root, appDirectory });
376
+ if (hoistComponentStyles) {
377
+ const componentSheet = extractStaticComponentSheet(source, real);
378
+ if (componentSheet) {
379
+ const code = `export const sheet = { name: ${JSON.stringify(componentSheet.name)}, className: ${JSON.stringify(componentSheet.className)}, css: "" };\n`;
380
+ const result: SourceDescription = {
381
+ code,
382
+ map: { version: 3, sources: [real], names: [], mappings: "AAAA" },
383
+ moduleType: "js",
384
+ };
385
+ transforms.set(real, {
386
+ source,
387
+ identity,
388
+ result,
389
+ componentSheet,
390
+ });
391
+ return result;
392
+ }
393
+ }
394
+ if (!JSX_SOURCE_FILE.test(real)) {
395
+ validateModule(source, { filename: real });
396
+ transforms.set(real, {
397
+ source,
398
+ identity,
399
+ result: null,
400
+ });
401
+ return null;
402
+ }
403
+ const jsxInput = development
404
+ ? injectDevJsxSourceLocations(source, real, identity)
405
+ : source;
406
+ const transformed = await jsxTransform(jsxInput, {
407
+ filename: real,
408
+ root: appDirectory,
409
+ generate: "universal",
410
+ moduleName: "@hewel/zgui/renderer",
411
+ dev: development,
412
+ sourceMap: true,
413
+ });
414
+ if (!transformed?.code || !transformed.map) {
415
+ throw new Error(`Solid compiler emitted no code or source map for ${real}`);
416
+ }
417
+ const isTypeScript = /\.[cm]?tsx$/i.test(real);
418
+ validateModule(transformed.code, {
419
+ filename: real,
420
+ lang: isTypeScript ? "ts" : "js",
421
+ });
422
+ const result: SourceDescription = {
423
+ code: transformed.code,
424
+ map: transformed.map,
425
+ moduleType: isTypeScript ? "ts" : "js",
426
+ };
427
+ transforms.set(real, {
428
+ source,
429
+ identity,
430
+ result,
431
+ });
432
+ return result;
433
+ },
434
+ } satisfies Plugin,
435
+ ...plugins,
436
+ ],
437
+ };
438
+ }
439
+
440
+ function outputOptions(filename = "app.mjs", { codeSplitting = true } = {}): OutputOptions {
441
+ return {
442
+ format: "esm",
443
+ entryFileNames: filename,
444
+ chunkFileNames: "chunks/[name]-[hash].mjs",
445
+ sourcemap: "hidden",
446
+ codeSplitting,
447
+ minify: false,
448
+ };
449
+ }
450
+
451
+ function compilationResult(
452
+ output: (OutputAsset | OutputChunk)[],
453
+ moduleIds: Iterable<string>,
454
+ { entry = true }: { entry?: boolean } = {},
455
+ ): CompilationResult {
456
+ const chunks = output.filter((item): item is OutputChunk => item.type === "chunk");
457
+ const graph: CompilationGraph = {
458
+ modules: [...moduleIds].filter(id => !id.startsWith("\0")).sort(),
459
+ chunks: chunks.map(chunk => ({
460
+ fileName: chunk.fileName,
461
+ modules: [...chunk.moduleIds].filter(id => !id.startsWith("\0")).sort(),
462
+ imports: [...chunk.imports],
463
+ dynamicImports: [...chunk.dynamicImports],
464
+ exports: [...chunk.exports].sort(),
465
+ })),
466
+ };
467
+ const solidRuntime = validateGraph(graph, { allowMultipleChunks: entry });
468
+ const allowedChunks = new Set(chunks.map(chunk => chunk.fileName));
469
+ const files = new Map<string, Buffer>();
470
+ for (const item of output) {
471
+ if (item.type === "chunk") {
472
+ if (!item.map) throw new Error(`Missing composed source map: ${item.fileName}`);
473
+ const code = `${item.code.trimEnd()}\n//# sourceMappingURL=${path.basename(item.fileName)}.map\n`;
474
+ validateModule(code, {
475
+ filename: item.fileName,
476
+ bundled: true,
477
+ entry: entry && item.isEntry,
478
+ allowedChunks,
479
+ });
480
+ files.set(item.fileName, Buffer.from(code));
481
+ files.set(`${item.fileName}.map`, Buffer.from(item.map.toString()));
482
+ } else files.set(item.fileName, Buffer.from(item.source));
483
+ }
484
+ if (!files.has("app.css")) {
485
+ throw new Error("Missing Lightning CSS stylesheet output");
486
+ }
487
+ return { files, graph, solidRuntime, styleSystem: styleSystem() };
488
+ }
489
+
490
+ export async function compileBundle(
491
+ entry: string,
492
+ {
493
+ root,
494
+ appDirectory = path.dirname(entry),
495
+ hostEntry = true,
496
+ filename = "app.mjs",
497
+ development = false,
498
+ jsxTransform = solidTransform,
499
+ plugins = [],
500
+ }: CompileBundleOptions,
501
+ ): Promise<CompilationResult> {
502
+ let result!: CompilationResult;
503
+ const compiler = await rolldown(
504
+ compilerOptions(entry, {
505
+ root,
506
+ appDirectory,
507
+ development,
508
+ hoistComponentStyles: hostEntry,
509
+ jsxTransform,
510
+ plugins: [
511
+ {
512
+ name: "capture-native-graph",
513
+ generateBundle(_options, output) {
514
+ result = compilationResult(Object.values(output), this.getModuleIds(), {
515
+ entry: hostEntry,
516
+ });
517
+ },
518
+ } satisfies Plugin,
519
+ ...plugins,
520
+ ],
521
+ }),
522
+ );
523
+ try {
524
+ await compiler.generate(outputOptions(filename, { codeSplitting: hostEntry }));
525
+ return result;
526
+ } finally {
527
+ await compiler.close();
528
+ }
529
+ }
530
+
531
+ export interface CompiledWorkerBundle {
532
+ name: string;
533
+ path: string;
534
+ sourceMap: string;
535
+ files: Map<string, Buffer>;
536
+ }
537
+
538
+ export async function compileWorkerBundle(
539
+ entry: string,
540
+ {
541
+ root,
542
+ appDirectory = path.dirname(entry),
543
+ name,
544
+ development = false,
545
+ }: {
546
+ root: string;
547
+ appDirectory?: string;
548
+ name: string;
549
+ development?: boolean;
550
+ },
551
+ ): Promise<CompiledWorkerBundle> {
552
+ const filename = `workers/${name}.mjs`;
553
+ const files = new Map<string, Buffer>();
554
+ const compiler = await rolldown({
555
+ cwd: appDirectory,
556
+ input: path.resolve(entry),
557
+ platform: "neutral",
558
+ experimental: { attachDebugInfo: "none" },
559
+ resolve: {
560
+ conditionNames: [development ? "development" : "production", "import", "default"],
561
+ mainFields: ["module", "main"],
562
+ modules: [
563
+ "node_modules",
564
+ path.join(appDirectory, "node_modules"),
565
+ path.join(root, "node_modules"),
566
+ ],
567
+ },
568
+ transform: {
569
+ target: "es2022",
570
+ define: { "process.env.NODE_ENV": development ? '"development"' : '"production"' },
571
+ typescript: { onlyRemoveTypeImports: true },
572
+ },
573
+ onwarn(warning, warn) {
574
+ if (warning.code === "UNRESOLVED_IMPORT") throw new Error(warning.message);
575
+ warn(warning);
576
+ },
577
+ plugins: [
578
+ {
579
+ name: "zgui-compute-worker",
580
+ resolveId(source) {
581
+ validateWorkerImport(source);
582
+ },
583
+ outputOptions(options) {
584
+ return {
585
+ ...options,
586
+ sourcemapPathTransform(source, sourceMapPath) {
587
+ return moduleIdentity(path.resolve(path.dirname(sourceMapPath), source), {
588
+ root,
589
+ appDirectory,
590
+ });
591
+ },
592
+ };
593
+ },
594
+ generateBundle(_options, output) {
595
+ const chunks = Object.values(output).filter(
596
+ (item): item is OutputChunk => item.type === "chunk",
597
+ );
598
+ if (chunks.length !== 1) {
599
+ throw new Error(`Compute worker ${name} must emit a single self-contained ESM chunk`);
600
+ }
601
+ const chunk = chunks[0];
602
+ if (chunk.imports.length > 0 || chunk.dynamicImports.length > 0) {
603
+ throw new Error(
604
+ `Compute worker ${name} must have a closed module graph with no external imports`,
605
+ );
606
+ }
607
+ if (!chunk.map) {
608
+ throw new Error(`Missing source map for compute worker ${name}`);
609
+ }
610
+ validateModule(chunk.code, {
611
+ filename: chunk.fileName,
612
+ bundled: true,
613
+ entry: false,
614
+ worker: true,
615
+ });
616
+ files.set(chunk.fileName, Buffer.from(chunk.code));
617
+ files.set(`${chunk.fileName}.map`, Buffer.from(chunk.map.toString()));
618
+ },
619
+ } satisfies Plugin,
620
+ ],
621
+ });
622
+ try {
623
+ await compiler.generate({
624
+ format: "es",
625
+ codeSplitting: false,
626
+ sourcemap: true,
627
+ entryFileNames: filename,
628
+ });
629
+ return { name, path: filename, sourceMap: `${filename}.map`, files };
630
+ } finally {
631
+ await compiler.close();
632
+ }
633
+ }
634
+
635
+ export function watchBundle(
636
+ entry: string,
637
+ {
638
+ root,
639
+ appDirectory = path.dirname(entry),
640
+ temporaryDirectory,
641
+ filename = "app.mjs",
642
+ buildDelay = 80,
643
+ development = false,
644
+ jsxTransform = solidTransform,
645
+ watchFiles = [],
646
+ onAttempt,
647
+ onCompile,
648
+ onError,
649
+ }: WatchBundleOptions,
650
+ ): BundleWatcher {
651
+ let attemptError: unknown;
652
+ const preserve = async <T>(operation: () => T | Promise<T>): Promise<T> => {
653
+ try {
654
+ return await operation();
655
+ } catch (error) {
656
+ attemptError = error;
657
+ throw error;
658
+ }
659
+ };
660
+ const watcher = watchCompiler({
661
+ ...compilerOptions(entry, {
662
+ root,
663
+ appDirectory,
664
+ development,
665
+ hoistComponentStyles: true,
666
+ jsxTransform,
667
+ plugins: [
668
+ {
669
+ name: "immutable-native-compilation",
670
+ async buildStart() {
671
+ attemptError = undefined;
672
+ for (const file of watchFiles) this.addWatchFile(file);
673
+ if (onAttempt) return preserve(() => onAttempt());
674
+ },
675
+ async generateBundle(_options, output) {
676
+ // Consume output in memory and suppress bundler writes so no partial package lands on disk.
677
+ try {
678
+ const result = await preserve(() =>
679
+ compilationResult(Object.values(output), this.getModuleIds()),
680
+ );
681
+ if (onCompile) await preserve(() => onCompile(result));
682
+ } finally {
683
+ for (const name of Object.keys(output)) delete output[name];
684
+ }
685
+ },
686
+ } satisfies Plugin,
687
+ ],
688
+ }),
689
+ output: { ...outputOptions(filename), dir: temporaryDirectory },
690
+ watch: { buildDelay },
691
+ });
692
+ watcher.on("event", async event => {
693
+ if (event.code !== "BUNDLE_END" && event.code !== "ERROR") return;
694
+ try {
695
+ if (event.code === "ERROR") await onError?.(attemptError ?? event.error);
696
+ } finally {
697
+ await event.result?.close();
698
+ }
699
+ });
700
+ return { close: () => watcher.close() };
701
+ }