@tarve/core 0.4.0 → 0.6.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 (122) hide show
  1. package/CHANGELOG.md +126 -1
  2. package/README.md +121 -12
  3. package/dist/npm/build.js +1401 -85
  4. package/dist/npm/cli.js +1940 -117
  5. package/dist/npm/embedded-assets.js +22 -3
  6. package/dist/npm/index.js +5274 -975
  7. package/dist/npm/jsx-dev-runtime.js +1268 -0
  8. package/dist/npm/jsx-runtime.js +1268 -0
  9. package/dist/npm/native-runtime.json +3 -3
  10. package/dist/npm/node-build.js +1159 -0
  11. package/dist/npm/protocol.js +1 -1
  12. package/dist/npm/runtime.js +5 -5
  13. package/dist/npm/txiki/fetch.ts +228 -0
  14. package/dist/npm/txiki/intl-data.ts +7 -0
  15. package/dist/npm/txiki/intl.test.ts +53 -0
  16. package/dist/npm/txiki/intl.ts +249 -0
  17. package/dist/npm/txiki/prelude.ts +132 -0
  18. package/dist/npm/txiki/runtime.ts +6 -0
  19. package/dist/npm/txiki/shims/buffer.ts +112 -0
  20. package/dist/npm/txiki/shims/child-process.ts +151 -0
  21. package/dist/npm/txiki/shims/crypto.ts +30 -0
  22. package/dist/npm/txiki/shims/events.ts +75 -0
  23. package/dist/npm/txiki/shims/fs-promises.ts +77 -0
  24. package/dist/npm/txiki/shims/fs.ts +231 -0
  25. package/dist/npm/txiki/shims/module.ts +8 -0
  26. package/dist/npm/txiki/shims/net.ts +69 -0
  27. package/dist/npm/txiki/shims/os.ts +72 -0
  28. package/dist/npm/txiki/shims/path.ts +4 -0
  29. package/dist/npm/txiki/shims/timers-promises.ts +9 -0
  30. package/dist/npm/txiki/shims/zlib.ts +9 -0
  31. package/dist/npm/txiki/tjs.d.ts +58 -0
  32. package/dist/npm/txiki/unavailable.ts +10 -0
  33. package/dist/types/core/build.d.ts +24 -0
  34. package/dist/types/core/cli.d.ts +1 -1
  35. package/dist/types/core/esbuild-file-imports.d.ts +8 -0
  36. package/dist/types/core/jsx-compile.d.ts +7 -0
  37. package/dist/types/core/node-build.d.ts +7 -0
  38. package/dist/types/core/node-dev.d.ts +4 -0
  39. package/dist/types/core/node-target.d.ts +10 -0
  40. package/dist/types/core/package-metadata.d.ts +49 -0
  41. package/dist/types/core/runtime-select.d.ts +8 -0
  42. package/dist/types/core/src/advanced-controls.d.ts +1 -1
  43. package/dist/types/core/src/app/element-events.d.ts +18 -0
  44. package/dist/types/core/src/app/media.d.ts +15 -0
  45. package/dist/types/core/src/app/requests.d.ts +25 -0
  46. package/dist/types/core/src/app/shadow.d.ts +7 -0
  47. package/dist/types/core/src/app/stats.d.ts +12 -0
  48. package/dist/types/core/src/app/tray.d.ts +40 -0
  49. package/dist/types/core/src/app-metadata.d.ts +18 -0
  50. package/dist/types/core/src/app.d.ts +89 -2
  51. package/dist/types/core/src/assets.d.ts +4 -0
  52. package/dist/types/core/src/bridge/binding.d.ts +10 -34
  53. package/dist/types/core/src/bridge/index.d.ts +1 -1
  54. package/dist/types/core/src/canvas.d.ts +161 -0
  55. package/dist/types/core/src/chat-controls.d.ts +2 -1
  56. package/dist/types/core/src/components/button.d.ts +1 -1
  57. package/dist/types/core/src/components/glass.d.ts +52 -0
  58. package/dist/types/core/src/components/icon.d.ts +1 -1
  59. package/dist/types/core/src/components/image.d.ts +8 -4
  60. package/dist/types/core/src/components/layout.d.ts +5 -4
  61. package/dist/types/core/src/components/pressable.d.ts +3 -3
  62. package/dist/types/core/src/components/rich-content.d.ts +1 -1
  63. package/dist/types/core/src/components/scroll.d.ts +2 -2
  64. package/dist/types/core/src/components/svg.d.ts +1 -1
  65. package/dist/types/core/src/components/titlebar.d.ts +15 -1
  66. package/dist/types/core/src/components/window.d.ts +21 -1
  67. package/dist/types/core/src/components.d.ts +2 -0
  68. package/dist/types/core/src/css-shadow.d.ts +1 -1
  69. package/dist/types/core/src/desktop-controls.d.ts +2 -2
  70. package/dist/types/core/src/embedded-assets.d.ts +3 -2
  71. package/dist/types/core/src/extra-controls.d.ts +2 -2
  72. package/dist/types/core/src/form-controls.d.ts +1 -1
  73. package/dist/types/core/src/html-elements.d.ts +26 -0
  74. package/dist/types/core/src/index.d.ts +23 -11
  75. package/dist/types/core/src/inline-text.d.ts +25 -0
  76. package/dist/types/core/src/intrinsic-style.d.ts +1 -1
  77. package/dist/types/core/src/jsx-runtime.d.ts +182 -5
  78. package/dist/types/core/src/media-element.d.ts +70 -0
  79. package/dist/types/core/src/memo.d.ts +28 -0
  80. package/dist/types/core/src/motion.d.ts +1 -1
  81. package/dist/types/core/src/png.d.ts +29 -0
  82. package/dist/types/core/src/popups.d.ts +4 -3
  83. package/dist/types/core/src/protocol.d.ts +6 -0
  84. package/dist/types/core/src/reconciler/diff.d.ts +11 -0
  85. package/dist/types/core/src/reconciler/intrinsics.d.ts +24 -0
  86. package/dist/types/core/src/reconciler.d.ts +33 -10
  87. package/dist/types/core/src/render-scope.d.ts +8 -0
  88. package/dist/types/core/src/style.d.ts +1 -1
  89. package/dist/types/core/src/tailwind-palette.d.ts +1 -0
  90. package/dist/types/core/src/tailwind.d.ts +8 -0
  91. package/dist/types/core/src/test-renderer.d.ts +3 -1
  92. package/dist/types/core/src/text-search.d.ts +1 -1
  93. package/dist/types/core/src/theme.d.ts +10 -2
  94. package/dist/types/core/src/updates.d.ts +87 -0
  95. package/dist/types/core/src/virtual-list.d.ts +8 -2
  96. package/dist/types/core/txiki/fetch.d.ts +1 -0
  97. package/dist/types/core/txiki/intl-data.d.ts +6 -0
  98. package/dist/types/core/txiki/intl.d.ts +92 -0
  99. package/dist/types/core/txiki/prelude.d.ts +1 -0
  100. package/dist/types/core/txiki/runtime.d.ts +2 -0
  101. package/dist/types/core/txiki/shims/buffer.d.ts +37 -0
  102. package/dist/types/core/txiki/shims/child-process.d.ts +46 -0
  103. package/dist/types/core/txiki/shims/crypto.d.ts +16 -0
  104. package/dist/types/core/txiki/shims/events.d.ts +21 -0
  105. package/dist/types/core/txiki/shims/fs-promises.d.ts +41 -0
  106. package/dist/types/core/txiki/shims/fs.d.ts +44 -0
  107. package/dist/types/core/txiki/shims/module.d.ts +5 -0
  108. package/dist/types/core/txiki/shims/net.d.ts +22 -0
  109. package/dist/types/core/txiki/shims/os.d.ts +52 -0
  110. package/dist/types/core/txiki/shims/path.d.ts +3 -0
  111. package/dist/types/core/txiki/shims/timers-promises.d.ts +7 -0
  112. package/dist/types/core/txiki/shims/zlib.d.ts +11 -0
  113. package/dist/types/core/txiki/unavailable.d.ts +5 -0
  114. package/dist/types/core/txiki-build.d.ts +23 -0
  115. package/dist/types/core/updates-build.d.ts +35 -0
  116. package/dist/types/core/windows-executable.d.ts +16 -0
  117. package/dist/types/protocol/src/index.d.ts +344 -11
  118. package/native/linux-x64/libtarve_native.so +0 -0
  119. package/native/linux-x64/runtime.json +4 -4
  120. package/native/win32-x64/runtime.json +4 -4
  121. package/native/win32-x64/tarve_native.dll +0 -0
  122. package/package.json +13 -3
package/dist/npm/cli.js CHANGED
@@ -1,36 +1,405 @@
1
- #!/usr/bin/env bun
2
- // @bun
1
+ #!/usr/bin/env node
2
+ var __defProp = Object.defineProperty;
3
+ var __returnValue = (v) => v;
4
+ function __exportSetter(name, newValue) {
5
+ this[name] = __returnValue.bind(null, newValue);
6
+ }
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, {
10
+ get: all[name],
11
+ enumerable: true,
12
+ configurable: true,
13
+ set: __exportSetter.bind(all, name)
14
+ });
15
+ };
16
+ var __esm = (fn, res, err) => () => {
17
+ if (fn)
18
+ try {
19
+ res = fn(fn = 0);
20
+ } catch (e) {
21
+ err = [e];
22
+ }
23
+ if (err)
24
+ throw err[0];
25
+ return res;
26
+ };
3
27
 
4
- // packages/core/cli.ts
5
- import { parseArgs } from "util";
28
+ // packages/core/src/png.ts
29
+ import { deflateSync, inflateSync } from "node:zlib";
30
+ function isPng(bytes) {
31
+ return SIGNATURE.every((value, index) => bytes[index] === value);
32
+ }
33
+ function decodePng(bytes) {
34
+ if (!isPng(bytes))
35
+ throw new Error("not a PNG file");
36
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
37
+ let offset = 8;
38
+ let width = 0, height = 0, depth = 0, colour = 0, interlace = 0;
39
+ let palette;
40
+ let transparency;
41
+ const idat = [];
42
+ while (offset + 12 <= bytes.length) {
43
+ const length = view.getUint32(offset);
44
+ const type = String.fromCharCode(...bytes.subarray(offset + 4, offset + 8));
45
+ const data = bytes.subarray(offset + 8, offset + 8 + length);
46
+ if (offset + 12 + length > bytes.length)
47
+ throw new Error("PNG chunk runs past the end of the file");
48
+ if (type === "IHDR") {
49
+ width = view.getUint32(offset + 8);
50
+ height = view.getUint32(offset + 12);
51
+ depth = data[8];
52
+ colour = data[9];
53
+ interlace = data[12];
54
+ } else if (type === "PLTE")
55
+ palette = data;
56
+ else if (type === "tRNS")
57
+ transparency = data;
58
+ else if (type === "IDAT")
59
+ idat.push(data);
60
+ else if (type === "IEND")
61
+ break;
62
+ offset += 12 + length;
63
+ }
64
+ if (width <= 0 || height <= 0 || idat.length === 0)
65
+ throw new Error("PNG has no image data");
66
+ if (width * height > 16384 * 16384)
67
+ throw new Error("PNG is too large");
68
+ if (interlace !== 0)
69
+ throw new Error("interlaced PNGs are not supported; save it without interlacing");
70
+ const channels = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }[colour];
71
+ if (channels === undefined || ![1, 2, 4, 8, 16].includes(depth) || depth < 8 && colour !== 0 && colour !== 3 || depth === 16 && colour === 3) {
72
+ throw new Error(`unsupported PNG format (colour type ${colour}, bit depth ${depth})`);
73
+ }
74
+ const bitsPerPixel = channels * depth;
75
+ const bytesPerPixel = Math.max(1, bitsPerPixel >> 3);
76
+ const stride = Math.ceil(width * bitsPerPixel / 8);
77
+ const raw = inflateSync(Buffer.concat(idat.map((chunk) => Buffer.from(chunk))));
78
+ if (raw.length < height * (stride + 1))
79
+ throw new Error("PNG image data is truncated");
80
+ const lines = new Uint8Array(height * stride);
81
+ for (let y = 0;y < height; y++) {
82
+ const filter = raw[y * (stride + 1)];
83
+ const source = y * (stride + 1) + 1;
84
+ const target = y * stride;
85
+ for (let x = 0;x < stride; x++) {
86
+ const encoded = raw[source + x];
87
+ const left = x >= bytesPerPixel ? lines[target + x - bytesPerPixel] : 0;
88
+ const up = y > 0 ? lines[target - stride + x] : 0;
89
+ const upLeft = y > 0 && x >= bytesPerPixel ? lines[target - stride + x - bytesPerPixel] : 0;
90
+ let predictor = 0;
91
+ if (filter === 1)
92
+ predictor = left;
93
+ else if (filter === 2)
94
+ predictor = up;
95
+ else if (filter === 3)
96
+ predictor = left + up >> 1;
97
+ else if (filter === 4) {
98
+ const p = left + up - upLeft;
99
+ const pa = Math.abs(p - left), pb = Math.abs(p - up), pc = Math.abs(p - upLeft);
100
+ predictor = pa <= pb && pa <= pc ? left : pb <= pc ? up : upLeft;
101
+ } else if (filter !== 0)
102
+ throw new Error(`unsupported PNG filter ${filter}`);
103
+ lines[target + x] = encoded + predictor & 255;
104
+ }
105
+ }
106
+ const sample = (y, index) => {
107
+ const row = y * stride;
108
+ if (depth === 8)
109
+ return lines[row + index];
110
+ if (depth === 16)
111
+ return lines[row + index * 2];
112
+ const bit = index * depth;
113
+ return lines[row + (bit >> 3)] >> 8 - depth - (bit & 7) & (1 << depth) - 1;
114
+ };
115
+ const scale = depth < 8 && colour === 0 ? 255 / ((1 << depth) - 1) : 1;
116
+ const rgba = new Uint8Array(width * height * 4);
117
+ for (let y = 0;y < height; y++) {
118
+ for (let x = 0;x < width; x++) {
119
+ const out = (y * width + x) * 4;
120
+ const base = x * channels;
121
+ if (colour === 3) {
122
+ const index = sample(y, base);
123
+ rgba[out] = palette?.[index * 3] ?? 0;
124
+ rgba[out + 1] = palette?.[index * 3 + 1] ?? 0;
125
+ rgba[out + 2] = palette?.[index * 3 + 2] ?? 0;
126
+ rgba[out + 3] = transparency?.[index] ?? 255;
127
+ } else if (colour === 0 || colour === 4) {
128
+ const grey = Math.round(sample(y, base) * scale);
129
+ rgba[out] = rgba[out + 1] = rgba[out + 2] = grey;
130
+ rgba[out + 3] = colour === 4 ? sample(y, base + 1) : 255;
131
+ } else {
132
+ rgba[out] = sample(y, base);
133
+ rgba[out + 1] = sample(y, base + 1);
134
+ rgba[out + 2] = sample(y, base + 2);
135
+ rgba[out + 3] = colour === 6 ? sample(y, base + 3) : 255;
136
+ }
137
+ }
138
+ }
139
+ return { width, height, rgba };
140
+ }
141
+ function crc32(bytes) {
142
+ let crc = 4294967295;
143
+ for (const byte of bytes)
144
+ crc = CRC_TABLE[(crc ^ byte) & 255] ^ crc >>> 8;
145
+ return (crc ^ 4294967295) >>> 0;
146
+ }
147
+ function chunk(type, data) {
148
+ const out = Buffer.alloc(12 + data.length);
149
+ out.writeUInt32BE(data.length, 0);
150
+ out.write(type, 4, "ascii");
151
+ out.set(data, 8);
152
+ out.writeUInt32BE(crc32(out.subarray(4, 8 + data.length)), 8 + data.length);
153
+ return out;
154
+ }
155
+ function encodePng(rgba, width, height) {
156
+ const stride = width * 4;
157
+ const raw = Buffer.alloc((stride + 1) * height);
158
+ for (let y = 0;y < height; y++)
159
+ raw.set(rgba.subarray(y * stride, (y + 1) * stride), y * (stride + 1) + 1);
160
+ const header = Buffer.alloc(13);
161
+ header.writeUInt32BE(width, 0);
162
+ header.writeUInt32BE(height, 4);
163
+ header[8] = 8;
164
+ header[9] = 6;
165
+ return new Uint8Array(Buffer.concat([
166
+ Buffer.from(SIGNATURE),
167
+ chunk("IHDR", header),
168
+ chunk("IDAT", deflateSync(raw, { level: 9 })),
169
+ chunk("IEND", new Uint8Array)
170
+ ]));
171
+ }
172
+ function resizeSquare(image, size) {
173
+ const side = Math.max(image.width, image.height);
174
+ const offsetX = (side - image.width) / 2, offsetY = (side - image.height) / 2;
175
+ const out = new Uint8Array(size * size * 4);
176
+ const ratio = side / size;
177
+ for (let y = 0;y < size; y++) {
178
+ const y0 = y * ratio - offsetY, y1 = (y + 1) * ratio - offsetY;
179
+ for (let x = 0;x < size; x++) {
180
+ const x0 = x * ratio - offsetX, x1 = (x + 1) * ratio - offsetX;
181
+ let r = 0, g = 0, b = 0, a = 0;
182
+ for (let sy = Math.max(0, Math.floor(y0));sy < Math.min(image.height, Math.ceil(y1)); sy++) {
183
+ const wy = Math.min(y1, sy + 1) - Math.max(y0, sy);
184
+ for (let sx = Math.max(0, Math.floor(x0));sx < Math.min(image.width, Math.ceil(x1)); sx++) {
185
+ const w = wy * (Math.min(x1, sx + 1) - Math.max(x0, sx));
186
+ const i = (sy * image.width + sx) * 4;
187
+ const alpha = image.rgba[i + 3] * w;
188
+ r += image.rgba[i] * alpha;
189
+ g += image.rgba[i + 1] * alpha;
190
+ b += image.rgba[i + 2] * alpha;
191
+ a += alpha;
192
+ }
193
+ }
194
+ const area = ratio * ratio;
195
+ const o = (y * size + x) * 4;
196
+ if (a > 0) {
197
+ out[o] = Math.round(r / a);
198
+ out[o + 1] = Math.round(g / a);
199
+ out[o + 2] = Math.round(b / a);
200
+ }
201
+ out[o + 3] = Math.round(a / area);
202
+ }
203
+ }
204
+ return out;
205
+ }
206
+ function encodeIco(entries) {
207
+ const header = Buffer.alloc(6 + entries.length * 16);
208
+ header.writeUInt16LE(0, 0);
209
+ header.writeUInt16LE(1, 2);
210
+ header.writeUInt16LE(entries.length, 4);
211
+ let offset = header.length;
212
+ entries.forEach(({ size, png }, index) => {
213
+ const at = 6 + index * 16;
214
+ header[at] = size >= 256 ? 0 : size;
215
+ header[at + 1] = size >= 256 ? 0 : size;
216
+ header.writeUInt16LE(1, at + 4);
217
+ header.writeUInt16LE(32, at + 6);
218
+ header.writeUInt32LE(png.length, at + 8);
219
+ header.writeUInt32LE(offset, at + 12);
220
+ offset += png.length;
221
+ });
222
+ return new Uint8Array(Buffer.concat([header, ...entries.map((entry) => Buffer.from(entry.png))]));
223
+ }
224
+ function isIco(bytes) {
225
+ return bytes.length >= 6 && bytes[0] === 0 && bytes[1] === 0 && bytes[2] === 1 && bytes[3] === 0;
226
+ }
227
+ function largestIcoPng(bytes) {
228
+ if (!isIco(bytes))
229
+ return;
230
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
231
+ let best;
232
+ let bestSize = 0;
233
+ for (let index = 0;index < view.getUint16(4, true); index++) {
234
+ const at = 6 + index * 16;
235
+ if (at + 16 > bytes.length)
236
+ break;
237
+ const size = bytes[at] || 256;
238
+ const length = view.getUint32(at + 8, true), start = view.getUint32(at + 12, true);
239
+ const data = bytes.subarray(start, start + length);
240
+ if (isPng(data) && size > bestSize) {
241
+ best = data;
242
+ bestSize = size;
243
+ }
244
+ }
245
+ return best;
246
+ }
247
+ var SIGNATURE, CRC_TABLE;
248
+ var init_png = __esm(() => {
249
+ SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10];
250
+ CRC_TABLE = new Uint32Array(256).map((_, n) => {
251
+ let c = n;
252
+ for (let k = 0;k < 8; k++)
253
+ c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
254
+ return c >>> 0;
255
+ });
256
+ });
6
257
 
7
- // packages/core/build.ts
8
- import { existsSync as existsSync2 } from "fs";
9
- import { mkdir } from "fs/promises";
10
- import { basename as basename2, dirname as dirname2, join as join2, resolve } from "path";
11
- import { fileURLToPath } from "url";
12
- import { nativePath } from "#tarve/runtime";
258
+ // packages/core/package-metadata.ts
259
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
260
+ import { basename, dirname, extname, join, relative, resolve } from "node:path";
261
+ function fields(value, where) {
262
+ if (value === undefined)
263
+ return {};
264
+ if (!value || typeof value !== "object" || Array.isArray(value))
265
+ throw new TypeError(`${where} must be an object`);
266
+ const out = {};
267
+ for (const key of FIELDS) {
268
+ const field = value[key];
269
+ if (field === undefined)
270
+ continue;
271
+ if (typeof field !== "string" || !field.trim())
272
+ throw new TypeError(`${where}.${key} must be a non-empty string`);
273
+ out[key] = field.trim();
274
+ }
275
+ return out;
276
+ }
277
+ function author(value) {
278
+ if (typeof value === "string")
279
+ return value.replace(/\s*[<(].*$/, "").trim() || undefined;
280
+ if (value && typeof value === "object" && typeof value.name === "string")
281
+ return value.name;
282
+ return;
283
+ }
284
+ function validAppId(id) {
285
+ return id.length > 0 && id.length <= 128 && !/[\s\\]/.test(id);
286
+ }
287
+ function resolveAppMetadata(entrypoint, overrides = {}) {
288
+ const entry = resolve(entrypoint);
289
+ let directory = dirname(entry);
290
+ let manifest;
291
+ let root = directory;
292
+ for (;; ) {
293
+ const path = join(directory, "package.json");
294
+ if (existsSync(path)) {
295
+ manifest = JSON.parse(readFileSync(path, "utf8"));
296
+ root = directory;
297
+ break;
298
+ }
299
+ const parent = dirname(directory);
300
+ if (parent === directory)
301
+ break;
302
+ directory = parent;
303
+ }
304
+ const tarve = manifest?.tarve;
305
+ const shared = fields(tarve === undefined ? undefined : Object.fromEntries(Object.entries(tarve).filter(([key]) => key !== "apps")), "package.json tarve");
306
+ const apps = tarve?.apps;
307
+ const key = relative(root, entry).replaceAll("\\", "/");
308
+ const own = fields(apps?.[key] ?? apps?.["./" + key], `package.json tarve.apps["${key}"]`);
309
+ const fromPackage = tarve === undefined ? {} : {
310
+ ...typeof manifest?.version === "string" ? { version: manifest.version } : {},
311
+ ...typeof manifest?.description === "string" ? { description: manifest.description } : {},
312
+ ...author(manifest?.author) ? { publisher: author(manifest?.author) } : {}
313
+ };
314
+ const configured = { ...fromPackage, ...shared, ...own };
315
+ if (configured.icon)
316
+ configured.icon = resolve(root, configured.icon);
317
+ const flags = fields(Object.fromEntries(Object.entries(overrides).filter(([, value]) => value !== undefined)), "option");
318
+ if (flags.icon)
319
+ flags.icon = resolve(flags.icon);
320
+ const merged = { ...configured, ...flags };
321
+ const metadata = { name: merged.name ?? basename(entry).replace(/\.[^.]+$/, "") };
322
+ for (const field of FIELDS)
323
+ if (field !== "name" && merged[field] !== undefined)
324
+ metadata[field] = merged[field];
325
+ if (metadata.appId !== undefined && !validAppId(metadata.appId)) {
326
+ throw new TypeError(`appId must be 1-128 characters without spaces or backslashes: ${metadata.appId}`);
327
+ }
328
+ if (metadata.icon !== undefined) {
329
+ if (!existsSync(metadata.icon))
330
+ throw new Error(`App icon not found: ${metadata.icon}`);
331
+ if (![".png", ".ico"].includes(extname(metadata.icon).toLowerCase()))
332
+ throw new TypeError(`App icon must be a .png or .ico file: ${metadata.icon}`);
333
+ }
334
+ return metadata;
335
+ }
336
+ function appIconImages(path) {
337
+ const bytes = new Uint8Array(readFileSync(path));
338
+ if (isIco(bytes)) {
339
+ const png = largestIcoPng(bytes);
340
+ if (!png)
341
+ throw new Error(`${path} has no PNG-compressed image; Linux builds and the window icon need one. Use a .png icon instead.`);
342
+ return { ico: bytes, png };
343
+ }
344
+ if (!isPng(bytes))
345
+ throw new TypeError(`${path} is not a PNG or ICO file`);
346
+ let image;
347
+ try {
348
+ image = decodePng(bytes);
349
+ } catch (error) {
350
+ throw new Error(`App icon ${path}: ${error instanceof Error ? error.message : String(error)}`);
351
+ }
352
+ const side = Math.max(image.width, image.height);
353
+ const sizes = ICO_SIZES.filter((size) => size <= side);
354
+ if (!sizes.length)
355
+ sizes.push(16);
356
+ const entries = sizes.map((size) => ({ size, png: encodePng(resizeSquare(image, size), size, size) }));
357
+ return { ico: encodeIco(entries), png: entries.at(-1).png };
358
+ }
359
+ function buildMetadata(entrypoint, overrides) {
360
+ const metadata = resolveAppMetadata(entrypoint, overrides);
361
+ const images = metadata.icon ? appIconImages(metadata.icon) : undefined;
362
+ const icon = images ? `data:image/png;base64,${Buffer.from(images.png).toString("base64")}` : undefined;
363
+ return { metadata, images, define: { "process.env.TARVE_APP_METADATA": JSON.stringify(runtimeMetadata(metadata, icon)) } };
364
+ }
365
+ function runtimeMetadata(metadata, icon) {
366
+ return JSON.stringify({
367
+ name: metadata.name,
368
+ ...metadata.version ? { version: metadata.version } : {},
369
+ ...metadata.appId ? { appId: metadata.appId } : {},
370
+ ...icon ? { icon } : {}
371
+ });
372
+ }
373
+ function writeLinuxDesktopEntry(outfile, metadata, png) {
374
+ const id = metadata.appId ?? basename(outfile);
375
+ const escape = (value) => value.replace(/[\\\n\r\t]/g, (match) => ({ "\\": "\\\\", "\n": "\\n", "\r": "\\r", "\t": "\\t" })[match]);
376
+ const lines = [
377
+ "[Desktop Entry]",
378
+ "Type=Application",
379
+ `Name=${escape(metadata.name)}`,
380
+ ...metadata.description ? [`Comment=${escape(metadata.description)}`] : [],
381
+ `Exec="${outfile.replaceAll('"', "\\\"")}" %U`,
382
+ ...png ? [`Icon=${id}`] : [],
383
+ `StartupWMClass=${id}`,
384
+ "Terminal=false",
385
+ ""
386
+ ];
387
+ mkdirSync(dirname(outfile), { recursive: true });
388
+ const desktop = join(dirname(outfile), `${id}.desktop`);
389
+ writeFileSync(desktop, lines.join(`
390
+ `));
391
+ if (png)
392
+ writeFileSync(join(dirname(outfile), `${id}.png`), png);
393
+ return desktop;
394
+ }
395
+ var FIELDS, ICO_SIZES;
396
+ var init_package_metadata = __esm(() => {
397
+ init_png();
398
+ FIELDS = ["name", "version", "description", "publisher", "copyright", "icon", "appId"];
399
+ ICO_SIZES = [16, 20, 24, 32, 40, 48, 64, 96, 128, 256];
400
+ });
13
401
 
14
402
  // packages/core/targets.ts
15
- var BUILD_TARGETS = ["windows-x64", "linux-x64"];
16
- var TARGET_CONFIGS = {
17
- "windows-x64": {
18
- platform: "win32",
19
- arch: "x64",
20
- bunTarget: "bun-windows-x64",
21
- nativeDirectory: "win32-x64",
22
- nativeName: "tarve_native.dll",
23
- executableSuffix: ".exe"
24
- },
25
- "linux-x64": {
26
- platform: "linux",
27
- arch: "x64",
28
- bunTarget: "bun-linux-x64",
29
- nativeDirectory: "linux-x64",
30
- nativeName: "libtarve_native.so",
31
- executableSuffix: ""
32
- }
33
- };
34
403
  function isBuildTarget(value) {
35
404
  return BUILD_TARGETS.includes(value);
36
405
  }
@@ -43,34 +412,50 @@ function hostBuildTarget(platform = process.platform, arch = process.arch) {
43
412
  return config.platform === platform && config.arch === arch;
44
413
  });
45
414
  }
46
-
47
- // packages/core/native-runtime.ts
48
- import { createHash } from "crypto";
49
- import { existsSync } from "fs";
50
- import { readFile, writeFile } from "fs/promises";
51
- import { basename, dirname, join } from "path";
415
+ var BUILD_TARGETS, TARGET_CONFIGS;
416
+ var init_targets = __esm(() => {
417
+ BUILD_TARGETS = ["windows-x64", "linux-x64"];
418
+ TARGET_CONFIGS = {
419
+ "windows-x64": {
420
+ platform: "win32",
421
+ arch: "x64",
422
+ bunTarget: "bun-windows-x64",
423
+ nativeDirectory: "win32-x64",
424
+ nativeName: "tarve_native.dll",
425
+ executableSuffix: ".exe"
426
+ },
427
+ "linux-x64": {
428
+ platform: "linux",
429
+ arch: "x64",
430
+ bunTarget: "bun-linux-x64",
431
+ nativeDirectory: "linux-x64",
432
+ nativeName: "libtarve_native.so",
433
+ executableSuffix: ""
434
+ }
435
+ };
436
+ });
52
437
 
53
438
  // packages/protocol/src/index.ts
54
- var NATIVE_ABI_VERSION = 5;
55
- var PROTOCOL_VERSION = 48;
439
+ var NATIVE_ABI_VERSION = 5, PROTOCOL_VERSION = 59;
56
440
 
57
441
  // packages/core/native-runtime.ts
58
- var NATIVE_RUNTIME_MANIFEST_NAME = "runtime.json";
59
- var NATIVE_COMPATIBILITY_MANIFEST_NAME = "native-runtime.json";
60
- var NATIVE_RUNTIME_MANIFEST_SCHEMA = 1;
442
+ import { createHash } from "node:crypto";
443
+ import { existsSync as existsSync2 } from "node:fs";
444
+ import { readFile, writeFile, glob } from "node:fs/promises";
445
+ import { basename as basename2, dirname as dirname2, join as join2 } from "node:path";
61
446
  async function sha256File(path) {
62
447
  return createHash("sha256").update(await readFile(path)).digest("hex");
63
448
  }
64
449
  async function addGlobFiles(files, root, prefix, pattern) {
65
- const directory = join(root, "native", prefix);
66
- if (!existsSync(directory))
450
+ const directory = join2(root, "native", prefix);
451
+ if (!existsSync2(directory))
67
452
  return;
68
- for await (const relative of new Bun.Glob(pattern).scan({ cwd: directory, onlyFiles: true })) {
69
- files.push(join(prefix, relative).replaceAll("\\", "/"));
453
+ for await (const relative of glob(pattern, { cwd: directory })) {
454
+ files.push(join2(prefix, relative).replaceAll("\\", "/"));
70
455
  }
71
456
  }
72
457
  async function nativeSourceFingerprint(root) {
73
- const native = join(root, "native");
458
+ const native = join2(root, "native");
74
459
  const files = ["Cargo.toml", "Cargo.lock"];
75
460
  await addGlobFiles(files, root, "src", "**/*.rs");
76
461
  await addGlobFiles(files, root, "vendor", "**/*.rs");
@@ -78,8 +463,8 @@ async function nativeSourceFingerprint(root) {
78
463
  files.sort();
79
464
  const hash = createHash("sha256");
80
465
  for (const relative of files) {
81
- const path = join(native, ...relative.split("/"));
82
- if (!existsSync(path))
466
+ const path = join2(native, ...relative.split("/"));
467
+ if (!existsSync2(path))
83
468
  throw new Error(`Native source input is missing: ${path}`);
84
469
  hash.update(relative);
85
470
  hash.update("\x00");
@@ -91,8 +476,8 @@ async function nativeSourceFingerprint(root) {
91
476
  }
92
477
  async function createNativeCompatibilityManifest(root, packageVersion) {
93
478
  const [rustProtocol, rustBridge] = await Promise.all([
94
- readFile(join(root, "native", "src", "protocol.rs"), "utf8"),
95
- readFile(join(root, "native", "src", "bridge.rs"), "utf8")
479
+ readFile(join2(root, "native", "src", "protocol.rs"), "utf8"),
480
+ readFile(join2(root, "native", "src", "bridge.rs"), "utf8")
96
481
  ]);
97
482
  const rustProtocolVersion = Number(rustProtocol.match(/pub const VERSION: u32 = (\d+);/)?.[1]);
98
483
  const rustAbiVersion = Number(rustBridge.match(/pub const ABI_VERSION: u32 = (\d+);/)?.[1]);
@@ -119,7 +504,7 @@ function validateCompatibilityShape(value, path) {
119
504
  }
120
505
  }
121
506
  async function readNativeCompatibilityManifest(path) {
122
- if (!existsSync(path))
507
+ if (!existsSync2(path))
123
508
  throw new Error(`Tarve native compatibility metadata is missing: ${path}`);
124
509
  let value;
125
510
  try {
@@ -131,8 +516,8 @@ async function readNativeCompatibilityManifest(path) {
131
516
  return value;
132
517
  }
133
518
  async function assertNativeRuntimeCompatible(library, target, expected) {
134
- const path = join(dirname(library), NATIVE_RUNTIME_MANIFEST_NAME);
135
- if (!existsSync(path)) {
519
+ const path = join2(dirname2(library), NATIVE_RUNTIME_MANIFEST_NAME);
520
+ if (!existsSync2(path)) {
136
521
  throw new Error(`Tarve native runtime metadata missing for ${target}: ${path}. ` + "Rebuild/stage this target with `bun run package:native` on its native OS before cross-compiling.");
137
522
  }
138
523
  let value;
@@ -157,12 +542,883 @@ async function assertNativeRuntimeCompatible(library, target, expected) {
157
542
  }
158
543
  return manifest;
159
544
  }
545
+ var NATIVE_RUNTIME_MANIFEST_NAME = "runtime.json", NATIVE_COMPATIBILITY_MANIFEST_NAME = "native-runtime.json", NATIVE_RUNTIME_MANIFEST_SCHEMA = 1;
546
+ var init_native_runtime = __esm(() => {
547
+ init_targets();
548
+ });
549
+
550
+ // packages/core/jsx-compile.ts
551
+ var exports_jsx_compile = {};
552
+ __export(exports_jsx_compile, {
553
+ closeJsxCompiler: () => closeJsxCompiler,
554
+ compileJsx: () => compileJsx
555
+ });
556
+ async function loadParser() {
557
+ let modules;
558
+ try {
559
+ modules = await Promise.all([import("typescript/unstable/ast"), import("typescript/unstable/ast/is")]);
560
+ } catch (error) {
561
+ throw new Error(`compileJsx needs TypeScript 7 (npm install -D typescript@7): ${error instanceof Error ? error.message : String(error)}`);
562
+ }
563
+ const [ast, is] = modules;
564
+ const files = new Map([[CONFIG, JSON.stringify({ compilerOptions: { jsx: "preserve", noLib: true, noResolve: true, types: [] }, files: ["app.tsx"] })]]);
565
+ const normalize = (path) => path.replace(/\\/g, "/").replace(/^[A-Za-z]:/, "");
566
+ const options = {
567
+ cwd: ROOT,
568
+ fs: {
569
+ readFile: (path) => files.get(normalize(path)),
570
+ fileExists: (path) => files.has(normalize(path)),
571
+ directoryExists: (path) => {
572
+ const p = normalize(path).replace(/\/$/, "");
573
+ return p === "" || ROOT.startsWith(p);
574
+ },
575
+ getAccessibleEntries: (path) => normalize(path).replace(/\/$/, "") === ROOT ? { files: ["app.tsx", "tsconfig.json"], directories: [] } : { files: [], directories: [] },
576
+ realpath: (path) => path
577
+ }
578
+ };
579
+ const request = { openProject: CONFIG, fileChanges: { invalidateAll: true } };
580
+ if ((process.platform === "win32" || typeof Bun === "undefined") && process.env.TARVE_TSGO_ASYNC !== "1") {
581
+ const sync = await import("typescript/unstable/sync");
582
+ const api = new sync.API(options);
583
+ return {
584
+ ast,
585
+ is,
586
+ files,
587
+ parse: async () => {
588
+ api.clearSourceFileCache();
589
+ const snapshot = api.updateSnapshot(request);
590
+ try {
591
+ return snapshot.getProjects()[0].program.getSourceFile(FILE);
592
+ } finally {
593
+ snapshot.dispose();
594
+ }
595
+ },
596
+ close: async () => api.close()
597
+ };
598
+ }
599
+ const asyncApi = await import("typescript/unstable/async");
600
+ const api = new asyncApi.API(options);
601
+ return {
602
+ ast,
603
+ is,
604
+ files,
605
+ parse: async () => {
606
+ api.clearSourceFileCache();
607
+ const snapshot = await api.updateSnapshot(request);
608
+ try {
609
+ return await snapshot.getProjects()[0].program.getSourceFile(FILE);
610
+ } finally {
611
+ await snapshot.dispose();
612
+ }
613
+ },
614
+ close: () => api.close()
615
+ };
616
+ }
617
+ async function closeJsxCompiler() {
618
+ const current = parser;
619
+ parser = undefined;
620
+ if (current)
621
+ await (await current).close();
622
+ }
623
+ function constant(node, ast, ts) {
624
+ const isConstant = (child) => constant(child, ast, ts);
625
+ if (ts.isParenthesizedExpression(node))
626
+ return isConstant(node.expression);
627
+ if (ts.isNumericLiteral(node) || ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node))
628
+ return true;
629
+ if (node.kind === ast.SyntaxKind.TrueKeyword || node.kind === ast.SyntaxKind.FalseKeyword || node.kind === ast.SyntaxKind.NullKeyword)
630
+ return true;
631
+ if (ts.isIdentifier(node) && node.text === "undefined")
632
+ return true;
633
+ if (ts.isPrefixUnaryExpression(node) && (node.operator === ast.SyntaxKind.MinusToken || node.operator === ast.SyntaxKind.PlusToken))
634
+ return ts.isNumericLiteral(node.operand);
635
+ if (ts.isArrayLiteralExpression(node))
636
+ return node.elements.every((element) => !ts.isSpreadElement(element) && isConstant(element));
637
+ if (ts.isObjectLiteralExpression(node)) {
638
+ return node.properties.every((property) => ts.isPropertyAssignment(property) && (ts.isIdentifier(property.name) || ts.isStringLiteral(property.name) || ts.isNumericLiteral(property.name)) && isConstant(property.initializer));
639
+ }
640
+ return false;
641
+ }
642
+ async function compileJsx(source) {
643
+ if (!/<[A-Za-z>]/.test(source))
644
+ return { code: source, templates: 0 };
645
+ const loaded = await (parser ??= loadParser());
646
+ const turn = queue.then(async () => {
647
+ loaded.files.set(FILE, source);
648
+ const file = await loaded.parse();
649
+ if (!file || file.text !== source)
650
+ throw new Error("compileJsx: TypeScript returned a different parse of the file");
651
+ return compileFile(source, file, loaded.ast, loaded.is);
652
+ });
653
+ queue = turn.catch(() => {
654
+ return;
655
+ });
656
+ return turn;
657
+ }
658
+ function compileFile(source, file, ast, ts) {
659
+ const isConstant = (node) => constant(node, ast, ts);
660
+ const isJsx = (node) => ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node);
661
+ const core = new Set;
662
+ let lastImport = 0;
663
+ for (const statement of file.statements) {
664
+ if (!ts.isImportDeclaration(statement))
665
+ continue;
666
+ lastImport = statement.end;
667
+ if (!ts.isStringLiteral(statement.moduleSpecifier) || !CORE.test(statement.moduleSpecifier.text))
668
+ continue;
669
+ const bindings = statement.importClause?.namedBindings;
670
+ if (bindings && ts.isNamedImports(bindings) && statement.importClause.phaseModifier !== ast.SyntaxKind.TypeKeyword) {
671
+ for (const element of bindings.elements)
672
+ if (!element.isTypeOnly)
673
+ core.add(element.name.text);
674
+ }
675
+ }
676
+ const shadowed = new Set;
677
+ const scan = (node) => {
678
+ const name = node.kind === ast.SyntaxKind.Parameter || ts.isVariableDeclaration(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) ? node.name : undefined;
679
+ if (name && ts.isIdentifier(name) && core.has(name.text))
680
+ shadowed.add(name.text);
681
+ node.forEachChild(scan);
682
+ };
683
+ file.forEachChild(scan);
684
+ for (const name of shadowed)
685
+ core.delete(name);
686
+ const pure = (node) => {
687
+ if (ts.isJsxFragment(node))
688
+ return true;
689
+ const tag = ts.isJsxElement(node) ? node.openingElement.tagName : node.tagName;
690
+ if (ts.isIdentifier(tag))
691
+ return /^[a-z]/.test(tag.text) || core.has(tag.text);
692
+ return false;
693
+ };
694
+ const text = (start, end) => source.slice(start, end);
695
+ const declarations = [];
696
+ function rewrite(start, end, root) {
697
+ const roots = [];
698
+ const find = (node) => {
699
+ if (node.end <= start || node.pos >= end)
700
+ return;
701
+ if (isJsx(node) && node.getStart() >= start && node.end <= end) {
702
+ roots.push(node);
703
+ return;
704
+ }
705
+ node.forEachChild(find);
706
+ };
707
+ find(root);
708
+ let out = "";
709
+ let at = start;
710
+ for (const node of roots) {
711
+ out += text(at, node.getStart()) + compileRoot(node);
712
+ at = node.end;
713
+ }
714
+ return out + text(at, end);
715
+ }
716
+ function compileRoot(node) {
717
+ if (!pure(node))
718
+ return impure(node);
719
+ const holes = [];
720
+ const events = [];
721
+ let key;
722
+ const hole = (expression, event = false) => {
723
+ const name = "h" + holes.length;
724
+ holes.push(expression);
725
+ if (event)
726
+ events.push(name);
727
+ return "p." + name;
728
+ };
729
+ let elements = 0;
730
+ function body(element, isRoot) {
731
+ if (!pure(element))
732
+ return "{" + hole(impure(element)) + "}";
733
+ elements++;
734
+ let out = "";
735
+ let at = element.getStart();
736
+ const end = element.end;
737
+ const attributes = ts.isJsxElement(element) ? element.openingElement.attributes : ts.isJsxSelfClosingElement(element) ? element.attributes : undefined;
738
+ const children = ts.isJsxElement(element) || ts.isJsxFragment(element) ? element.children : undefined;
739
+ const parts = [];
740
+ for (const attribute of attributes?.properties ?? []) {
741
+ if (ts.isJsxSpreadAttribute(attribute)) {
742
+ parts.push({ start: attribute.expression.getStart(), end: attribute.expression.end, replacement: hole(rewrite(attribute.expression.getStart(), attribute.expression.end, attribute.expression)) });
743
+ continue;
744
+ }
745
+ const name = attribute.name.getText();
746
+ const initializer = attribute.initializer;
747
+ if (isRoot && name === "key") {
748
+ key = initializer ? ts.isJsxExpression(initializer) && initializer.expression ? rewrite(initializer.expression.getStart(), initializer.expression.end, initializer.expression) : initializer.getText() : "true";
749
+ parts.push({ start: attribute.getStart(), end: attribute.end, replacement: "" });
750
+ continue;
751
+ }
752
+ if (!initializer)
753
+ continue;
754
+ if (ts.isJsxExpression(initializer) && initializer.expression && !isConstant(initializer.expression)) {
755
+ const expression = initializer.expression;
756
+ parts.push({ start: expression.getStart(), end: expression.end, replacement: hole(rewrite(expression.getStart(), expression.end, expression), EVENT.test(name)) });
757
+ } else if (isJsx(initializer)) {
758
+ const value = initializer;
759
+ parts.push({ start: value.getStart(), end: value.end, replacement: "{" + hole(compileRoot(value)) + "}" });
760
+ }
761
+ }
762
+ for (const child of children ?? []) {
763
+ if (ts.isJsxExpression(child)) {
764
+ if (!child.expression)
765
+ continue;
766
+ if (isConstant(child.expression) && !ts.isObjectLiteralExpression(child.expression) && !ts.isArrayLiteralExpression(child.expression))
767
+ continue;
768
+ parts.push({ start: child.expression.getStart(), end: child.expression.end, replacement: hole(rewrite(child.expression.getStart(), child.expression.end, child.expression)) });
769
+ } else if (isJsx(child)) {
770
+ parts.push({ start: child.getStart(), end: child.end, replacement: body(child, false) });
771
+ }
772
+ }
773
+ parts.sort((a, b) => a.start - b.start);
774
+ for (const part of parts) {
775
+ out += text(at, part.start) + part.replacement;
776
+ at = part.end;
777
+ }
778
+ return out + text(at, end);
779
+ }
780
+ const template = body(node, true);
781
+ if (elements < 2)
782
+ return impure(node);
783
+ const name = "__tarveTemplate" + declarations.length;
784
+ declarations.push(`const ${name} = __tarveCompileTemplate((p: any) => (${template}), ${JSON.stringify(events)});`);
785
+ const props = holes.map((expression, index) => `h${index}={${expression}}`);
786
+ if (key !== undefined)
787
+ props.unshift(`key={${key}}`);
788
+ return `<${name} ${props.join(" ")} />`;
789
+ }
790
+ function impure(node) {
791
+ let out = "";
792
+ let at = node.getStart();
793
+ const visit = (child) => {
794
+ if (isJsx(child) && child !== node) {
795
+ out += text(at, child.getStart()) + compileRoot(child);
796
+ at = child.end;
797
+ return;
798
+ }
799
+ if (ts.isJsxExpression(child) && child.expression) {
800
+ out += text(at, child.expression.getStart()) + rewrite(child.expression.getStart(), child.expression.end, child.expression);
801
+ at = child.expression.end;
802
+ return;
803
+ }
804
+ if (ts.isJsxSpreadAttribute(child)) {
805
+ out += text(at, child.expression.getStart()) + rewrite(child.expression.getStart(), child.expression.end, child.expression);
806
+ at = child.expression.end;
807
+ return;
808
+ }
809
+ child.forEachChild(visit);
810
+ };
811
+ node.forEachChild(visit);
812
+ return out + text(at, node.end);
813
+ }
814
+ const body = rewrite(lastImport, source.length, file);
815
+ if (!declarations.length)
816
+ return { code: source, templates: 0 };
817
+ const code = text(0, lastImport) + `
818
+ import { template as __tarveCompileTemplate } from "@tarve/core";
819
+ ` + declarations.join(`
820
+ `) + `
821
+ ` + body;
822
+ return { code, templates: declarations.length };
823
+ }
824
+ var ROOT = "/tarve-jsx", FILE, CONFIG, parser, queue, CORE, EVENT;
825
+ var init_jsx_compile = __esm(() => {
826
+ FILE = ROOT + "/app.tsx";
827
+ CONFIG = ROOT + "/tsconfig.json";
828
+ queue = Promise.resolve();
829
+ CORE = /^(?:@tarve\/core|tarve)(?:\/.*)?$/;
830
+ EVENT = /^on[A-Z]/;
831
+ });
832
+
833
+ // packages/core/windows-executable.ts
834
+ var exports_windows_executable = {};
835
+ __export(exports_windows_executable, {
836
+ brandWindowsExecutable: () => brandWindowsExecutable
837
+ });
838
+ import { readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
839
+ import { Data, NtExecutable, NtExecutableResource, Resource } from "resedit";
840
+ function numericVersion(version) {
841
+ const parts = version.split(/[.+-]/).slice(0, 4).map((part) => Number.parseInt(part, 10));
842
+ return [0, 1, 2, 3].map((index) => {
843
+ const value = parts[index];
844
+ return Number.isInteger(value) && value >= 0 && value <= 65535 ? value : 0;
845
+ });
846
+ }
847
+ function brandWindowsExecutable(path, info) {
848
+ const executable = NtExecutable.from(readFileSync2(path), { ignoreCert: true });
849
+ const resources = NtExecutableResource.from(executable);
850
+ const versionInfo = Resource.VersionInfo.fromEntries(resources.entries)[0] ?? Resource.VersionInfo.createEmpty();
851
+ const languages = versionInfo.getAllLanguagesForStringValues();
852
+ if (languages.length === 0)
853
+ languages.push({ lang: 1033, codepage: 1200 });
854
+ const [major, minor, patch, revision] = numericVersion(info.version);
855
+ const text = `${major}.${minor}.${patch}.${revision}`;
856
+ for (const language of languages) {
857
+ for (const key of ["CompanyName", "LegalCopyright", "LegalTrademarks", "Comments", "PrivateBuild", "SpecialBuild"]) {
858
+ versionInfo.removeStringValue(language, key);
859
+ }
860
+ versionInfo.setStringValues(language, {
861
+ FileDescription: info.description ?? `${info.name} — native Tarve application`,
862
+ ...info.publisher ? { CompanyName: info.publisher } : {},
863
+ ...info.copyright ? { LegalCopyright: info.copyright } : {},
864
+ ProductName: info.name,
865
+ InternalName: info.name,
866
+ OriginalFilename: info.filename,
867
+ FileVersion: text,
868
+ ProductVersion: text
869
+ });
870
+ }
871
+ versionInfo.setFileVersion(major, minor, patch, revision);
872
+ versionInfo.setProductVersion(major, minor, patch, revision);
873
+ versionInfo.outputToResourceEntries(resources.entries);
874
+ if (info.ico) {
875
+ const groups = Resource.IconGroupEntry.fromEntries(resources.entries);
876
+ const group = groups[0];
877
+ const icons = Data.IconFile.from(info.ico).icons.map((icon) => icon.data);
878
+ Resource.IconGroupEntry.replaceIconsForResource(resources.entries, group?.id ?? 1, group?.lang ?? 1033, icons);
879
+ }
880
+ resources.outputResource(executable);
881
+ const output = Buffer.from(executable.generate());
882
+ output.writeUInt16LE(IMAGE_SUBSYSTEM_WINDOWS_GUI, output.readUInt32LE(60) + 24 + 68);
883
+ writeFileSync2(path, output);
884
+ }
885
+ var IMAGE_SUBSYSTEM_WINDOWS_GUI = 2;
886
+ var init_windows_executable = () => {};
887
+
888
+ // packages/core/txiki-build.ts
889
+ import { execFileSync } from "node:child_process";
890
+ import { createHash as createHash2 } from "node:crypto";
891
+ import { chmodSync, existsSync as existsSync3, mkdtempSync, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "node:fs";
892
+ import { mkdir, rm } from "node:fs/promises";
893
+ import { builtinModules } from "node:module";
894
+ import { tmpdir } from "node:os";
895
+ import { basename as basename3, dirname as dirname3, join as join3, relative as relative2, resolve as resolve2 } from "node:path";
896
+ import { gzipSync } from "node:zlib";
897
+ import { nativePath } from "#tarve/runtime";
898
+ function findTxiki(explicit) {
899
+ const candidate = explicit ?? process.env.TARVE_TXIKI ?? (process.versions.bun ? Bun.which("tjs") : undefined) ?? "tjs";
900
+ try {
901
+ execFileSync(candidate, ["--version"], { stdio: "pipe" });
902
+ } catch {
903
+ throw new Error(`txiki.js was not found (${candidate}). Install it (winget install Saghul.TxikiJS) or set TARVE_TXIKI.`);
904
+ }
905
+ return candidate;
906
+ }
907
+ function txikiBinary(tjs) {
908
+ return execFileSync(tjs, ["eval", "console.log(tjs.exePath)"], { encoding: "utf8" }).trim();
909
+ }
910
+ async function buildTxiki(options) {
911
+ const target = options.target ?? hostBuildTarget();
912
+ if (!target)
913
+ throw new Error(`Unsupported txiki.js build host: ${process.platform}-${process.arch}`);
914
+ const config = targetConfig(target);
915
+ const tjs = findTxiki(options.txikiExecutable);
916
+ const host = txikiBinary(tjs);
917
+ const base = options.targetExecutable ? resolve2(options.targetExecutable) : host;
918
+ if (target !== hostBuildTarget() && !options.targetExecutable) {
919
+ throw new Error(`Cross-compiling for ${target} needs targetExecutable: the txiki.js ${execFileSync(tjs, ["--version"], { encoding: "utf8" }).trim()} binary for that platform.`);
920
+ }
921
+ if (!existsSync3(base))
922
+ throw new Error(`txiki.js executable is missing: ${base}`);
923
+ const { metadata, images, define } = buildMetadata(options.entrypoint, metadataOverrides(options));
924
+ const outfile = resolve2(options.outfile ?? `dist/${metadata.name}${config.executableSuffix}`);
925
+ const library = resolve2(options.nativeLibrary ?? (target === hostBuildTarget() ? nativePath() : join3(import.meta.dirname, "../../native", config.nativeDirectory, config.nativeName)));
926
+ if (!existsSync3(library))
927
+ throw new Error(`Tarve native library missing: ${library}`);
928
+ const temporary = mkdtempSync(join3(tmpdir(), "tarve-txiki-build-"));
929
+ try {
930
+ const root = import.meta.dirname;
931
+ const source = existsSync3(join3(root, "src/index.ts"));
932
+ const assets = [];
933
+ const missing = new Map;
934
+ const importers = new Map;
935
+ const runtime = {
936
+ name: "tarve-txiki-runtime",
937
+ setup(build) {
938
+ build.onResolve({ filter: /^tjs:/ }, (args) => ({ path: args.path, external: true }));
939
+ build.onResolve({ filter: /^(?:node:)?[a-z_]+(?:\/[a-z_]+)?$/ }, (args) => {
940
+ const name = args.path.replace(/^node:/, "");
941
+ if (!NODE_SHIMS[name] && !args.path.startsWith("node:") && !builtinModules.includes(name))
942
+ return;
943
+ if (!importers.has(name))
944
+ importers.set(name, new Set);
945
+ importers.get(name).add(args.importer);
946
+ return { path: name, namespace: "tarve-node", sideEffects: false };
947
+ });
948
+ build.onResolve({ filter: /^#tarve\/runtime$/ }, () => ({ path: join3(root, "txiki/runtime.ts") }));
949
+ if (source) {
950
+ build.onResolve({ filter: /^(?:@tarve\/core(?:-internal)?|tarve)(?:\/(?:jsx-runtime|jsx-dev-runtime))?$/ }, (args) => {
951
+ const entry = args.path.replace(/^(?:@tarve\/core(?:-internal)?|tarve)/, "") || "/index";
952
+ return { path: join3(root, "src", `${entry.slice(1)}.ts`) };
953
+ });
954
+ }
955
+ build.onResolve({ filter: /.*/ }, (args) => {
956
+ const type = args.with?.type ?? (ASSET.test(args.path) && args.kind === "import-statement" ? "file" : undefined);
957
+ if (type !== "file" && type !== "text")
958
+ return;
959
+ return { path: resolve2(dirname3(args.importer), args.path), namespace: `tarve-${type}` };
960
+ });
961
+ build.onLoad({ filter: /.*/, namespace: "tarve-node" }, (args) => {
962
+ const shim = NODE_SHIMS[args.path] && JSON.stringify(join3(root, "txiki/shims", `${NODE_SHIMS[args.path]}.ts`));
963
+ const placeholder = (api) => `/* @__PURE__ */ unavailable(${JSON.stringify(`${UNAVAILABLE}node:${api}`)})`;
964
+ return {
965
+ contents: [
966
+ `import { unavailable } from ${JSON.stringify(join3(root, "txiki/unavailable.ts"))};`,
967
+ ...shim ? [`export * from ${shim};`, `export { default } from ${shim};`] : [`export default ${placeholder(args.path)};`],
968
+ ...[...missing.get(args.path) ?? []].map((name) => `export const ${name} = ${placeholder(`${args.path}.${name}`)};`)
969
+ ].join(`
970
+ `),
971
+ loader: "js",
972
+ resolveDir: root
973
+ };
974
+ });
975
+ if (options.compileJsx) {
976
+ build.onLoad({ filter: /\.[jt]sx$/ }, async (args) => {
977
+ if (/[\\/]node_modules[\\/]/.test(args.path) || args.path.startsWith(join3(root, "src")))
978
+ return;
979
+ await Promise.resolve().then(() => init_jsx_compile());
980
+ return { contents: (await compileJsx(readFileSync3(args.path, "utf8"))).code, loader: args.path.endsWith(".jsx") ? "jsx" : "tsx", resolveDir: dirname3(args.path) };
981
+ });
982
+ }
983
+ build.onLoad({ filter: /.*/, namespace: "tarve-text" }, (args) => ({ contents: readFileSync3(args.path, "utf8"), loader: "text" }));
984
+ build.onLoad({ filter: /.*/, namespace: "tarve-file" }, (args) => {
985
+ const data = readFileSync3(args.path);
986
+ const name = `${createHash2("sha256").update(data).digest("hex").slice(0, 12)}-${basename3(args.path)}`;
987
+ if (!assets.some((asset) => asset.name === name))
988
+ assets.push({ name, data, gzip: false });
989
+ return { contents: `export default globalThis.__tarveAssets[${JSON.stringify(name)}];`, loader: "js" };
990
+ });
991
+ }
992
+ };
993
+ const entry = join3(temporary, "entry.ts");
994
+ writeFileSync3(entry, [
995
+ `import ${JSON.stringify(join3(root, "txiki/prelude.ts"))};`,
996
+ `import ${JSON.stringify(resolve2(options.entrypoint))};`
997
+ ].join(`
998
+ `));
999
+ const bundle = join3(temporary, "app.js");
1000
+ const { build: esbuild } = await import("esbuild");
1001
+ const bundleApp = () => esbuild({
1002
+ entryPoints: [entry],
1003
+ outfile: bundle,
1004
+ bundle: true,
1005
+ platform: "neutral",
1006
+ mainFields: ["module", "main"],
1007
+ format: "esm",
1008
+ target: "es2023",
1009
+ minify: !process.env.TARVE_TXIKI_DEBUG,
1010
+ jsx: "automatic",
1011
+ jsxImportSource: "@tarve/core",
1012
+ logLevel: "silent",
1013
+ define: {
1014
+ ...define,
1015
+ "process.env.NODE_ENV": JSON.stringify("production"),
1016
+ "import.meta.dirname": "globalThis.__tarveDirname",
1017
+ TARVE_TXIKI_PLATFORM: JSON.stringify(config.platform),
1018
+ TARVE_TXIKI_NATIVE_NAME: JSON.stringify(config.nativeName)
1019
+ },
1020
+ plugins: [runtime],
1021
+ metafile: !!process.env.TARVE_TXIKI_DEBUG
1022
+ });
1023
+ for (let attempt = 0;; attempt++) {
1024
+ try {
1025
+ const result = await bundleApp();
1026
+ if (process.env.TARVE_TXIKI_DEBUG)
1027
+ writeFileSync3(`${process.env.TARVE_TXIKI_DEBUG}.meta.json`, JSON.stringify(result.metafile));
1028
+ break;
1029
+ } catch (error) {
1030
+ const errors = error.errors ?? [];
1031
+ const lacking = errors.map(({ text }) => /^No matching export in "tarve-node:([^"]+)" for import "([^"]+)"$/.exec(text));
1032
+ if (!lacking.length || lacking.some((match) => !match) || attempt > 3)
1033
+ throw error;
1034
+ for (const match of lacking) {
1035
+ if (!missing.has(match[1]))
1036
+ missing.set(match[1], new Set);
1037
+ missing.get(match[1]).add(match[2]);
1038
+ }
1039
+ }
1040
+ }
1041
+ assertAvailable(readFileSync3(bundle, "utf8"), importers);
1042
+ if (process.env.TARVE_TXIKI_DEBUG)
1043
+ writeFileSync3(process.env.TARVE_TXIKI_DEBUG, readFileSync3(bundle));
1044
+ const compiled = join3(temporary, `compiled${config.executableSuffix}`);
1045
+ execFileSync(tjs, ["compile", bundle, compiled], { stdio: "pipe" });
1046
+ const payload = txikiPayload(readFileSync3(compiled), readFileSync3(host).byteLength);
1047
+ const executable = join3(temporary, `base${config.executableSuffix}`);
1048
+ writeFileSync3(executable, readFileSync3(base));
1049
+ if (config.platform === "win32") {
1050
+ const tarveVersion = JSON.parse(readFileSync3(resolve2(root, "../../package.json"), "utf8")).version;
1051
+ (await Promise.resolve().then(() => (init_windows_executable(), exports_windows_executable))).brandWindowsExecutable(executable, {
1052
+ name: metadata.name,
1053
+ version: metadata.version ?? tarveVersion,
1054
+ filename: basename3(outfile),
1055
+ description: metadata.description,
1056
+ publisher: metadata.publisher,
1057
+ copyright: metadata.copyright,
1058
+ ico: images?.ico
1059
+ });
1060
+ }
1061
+ const files = [{ name: config.nativeName, data: readFileSync3(library), gzip: true }, ...assets];
1062
+ await mkdir(dirname3(outfile), { recursive: true });
1063
+ await rm(outfile, { force: true });
1064
+ writeFileSync3(outfile, fuse(readFileSync3(executable), files, payload));
1065
+ if (config.platform !== "win32")
1066
+ chmodSync(outfile, 493);
1067
+ if (config.platform === "linux" && (metadata.icon || metadata.appId))
1068
+ writeLinuxDesktopEntry(outfile, metadata, images?.png);
1069
+ return outfile;
1070
+ } finally {
1071
+ if (options.compileJsx)
1072
+ await (await Promise.resolve().then(() => (init_jsx_compile(), exports_jsx_compile))).closeJsxCompiler();
1073
+ await rm(temporary, { recursive: true, force: true });
1074
+ }
1075
+ }
1076
+ function assertAvailable(bundle, importers = new Map) {
1077
+ const apis = [...new Set([...bundle.matchAll(new RegExp(`${UNAVAILABLE}node:([\\w/.-]+)`, "g"))].map((match) => match[1]))].sort();
1078
+ const bun = [...new Set([...bundle.matchAll(/(?<![\w$.])Bun\.([A-Za-z_$][\w$]*)/g)].filter((match) => !bundle.slice(Math.max(0, match.index - 400), match.index).includes("typeof Bun")).map((match) => `Bun.${match[1]}`))].sort();
1079
+ if (!apis.length && !bun.length)
1080
+ return;
1081
+ const lines = apis.map((api) => {
1082
+ const [module, name] = api.split(".");
1083
+ const users = [...importers.get(module) ?? []].filter((file) => !name || !existsSync3(file) || new RegExp(`\\b${name}\\b`).test(readFileSync3(file, "utf8"))).map((file) => relative2(process.cwd(), file).replaceAll("\\", "/"));
1084
+ return ` node:${api}${users.length ? ` (imported by ${users.slice(0, 3).join(", ")}${users.length > 3 ? ", …" : ""})` : ""}`;
1085
+ });
1086
+ throw new Error([
1087
+ "This app reaches APIs the txiki.js runtime does not provide:",
1088
+ ...lines,
1089
+ ...bun.map((api) => ` ${api} (the Bun global; guard it with typeof Bun !== "undefined")`),
1090
+ "Remove those calls from code the app can run, or build with --runtime bun or --runtime node."
1091
+ ].join(`
1092
+ `));
1093
+ }
1094
+ function txikiPayload(compiled, hostSize) {
1095
+ const trailer = compiled.subarray(compiled.length - 12);
1096
+ const offset = new DataView(trailer.buffer, trailer.byteOffset, 12).getUint32(8, true);
1097
+ if (new TextDecoder().decode(trailer.subarray(0, 8)) !== TXIKI_MAGIC || offset !== hostSize) {
1098
+ throw new Error("Unrecognized `tjs compile` output; this txiki.js version is not supported.");
1099
+ }
1100
+ return compiled.subarray(offset, compiled.length - 12);
1101
+ }
1102
+ function fuse(executable, files, payload) {
1103
+ const parts = [executable];
1104
+ const index = [];
1105
+ let offset = executable.length;
1106
+ for (const file of files) {
1107
+ const stored = file.gzip ? gzipSync(file.data, { level: 9 }) : file.data;
1108
+ index.push({ name: file.name, offset, length: stored.length, size: file.data.length, sha256: createHash2("sha256").update(file.data).digest("hex"), gzip: file.gzip });
1109
+ parts.push(stored);
1110
+ offset += stored.length;
1111
+ }
1112
+ const json = new TextEncoder().encode(JSON.stringify(index));
1113
+ const header = new Uint8Array(16);
1114
+ new DataView(header.buffer).setUint32(0, json.length, true);
1115
+ header.set(new TextEncoder().encode(BLOB_MAGIC), 8);
1116
+ parts.push(json, header);
1117
+ const payloadOffset = offset + json.length + header.length;
1118
+ const trailer = new Uint8Array(12);
1119
+ trailer.set(new TextEncoder().encode(TXIKI_MAGIC));
1120
+ new DataView(trailer.buffer).setUint32(8, payloadOffset, true);
1121
+ parts.push(payload, trailer);
1122
+ const out = new Uint8Array(parts.reduce((size, part) => size + part.length, 0));
1123
+ let position = 0;
1124
+ for (const part of parts) {
1125
+ out.set(part, position);
1126
+ position += part.length;
1127
+ }
1128
+ return out;
1129
+ }
1130
+ var TXIKI_MAGIC = "tx1k1.js", BLOB_MAGIC = "TARVEBLB", NODE_SHIMS, ASSET, UNAVAILABLE = "tarve-txiki-unavailable:";
1131
+ var init_txiki_build = __esm(() => {
1132
+ init_build();
1133
+ init_package_metadata();
1134
+ init_targets();
1135
+ NODE_SHIMS = {
1136
+ fs: "fs",
1137
+ "fs/promises": "fs-promises",
1138
+ path: "path",
1139
+ os: "os",
1140
+ crypto: "crypto",
1141
+ net: "net",
1142
+ module: "module",
1143
+ zlib: "zlib",
1144
+ events: "events",
1145
+ child_process: "child-process",
1146
+ "timers/promises": "timers-promises"
1147
+ };
1148
+ ASSET = /\.(?:png|jpe?g|webp|gif|svg|ico|ttf|otf|woff2?)$/i;
1149
+ });
1150
+
1151
+ // packages/core/esbuild-file-imports.ts
1152
+ import { readFileSync as readFileSync4 } from "node:fs";
1153
+ import { dirname as dirname4, resolve as resolve3 } from "node:path";
1154
+ var ASSET2, fileImportAttributes;
1155
+ var init_esbuild_file_imports = __esm(() => {
1156
+ ASSET2 = /\.(?:png|jpe?g|webp|gif|svg)$/i;
1157
+ fileImportAttributes = {
1158
+ name: "tarve-file-import-attributes",
1159
+ setup(build) {
1160
+ build.onResolve({ filter: /.*/ }, (args) => {
1161
+ if (args.namespace === "tarve-file") {
1162
+ return args.path.startsWith("node:") ? { path: args.path, external: true } : { path: args.path, namespace: "tarve-file-copy" };
1163
+ }
1164
+ const type = args.with?.type ?? (ASSET2.test(args.path) && args.kind === "import-statement" ? "file" : undefined);
1165
+ if (type !== "file" && type !== "text")
1166
+ return;
1167
+ return { path: resolve3(dirname4(args.importer), args.path), namespace: `tarve-${type}` };
1168
+ });
1169
+ build.onLoad({ filter: /.*/, namespace: "tarve-text" }, (args) => ({ contents: readFileSync4(args.path, "utf8"), loader: "text" }));
1170
+ build.onLoad({ filter: /.*/, namespace: "tarve-file" }, (args) => ({
1171
+ contents: [
1172
+ `import relative from ${JSON.stringify(args.path)};`,
1173
+ `import { join } from "node:path";`,
1174
+ `export default join(import.meta.dirname, relative);`
1175
+ ].join(`
1176
+ `),
1177
+ loader: "js",
1178
+ resolveDir: dirname4(args.path)
1179
+ }));
1180
+ build.onLoad({ filter: /.*/, namespace: "tarve-file-copy" }, (args) => ({
1181
+ contents: readFileSync4(args.path),
1182
+ loader: "file"
1183
+ }));
1184
+ }
1185
+ };
1186
+ });
1187
+
1188
+ // packages/core/node-target.ts
1189
+ import { createHash as createHash3, randomUUID } from "node:crypto";
1190
+ import { chmodSync as chmodSync2, existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync5, renameSync, rmSync, writeFileSync as writeFileSync4 } from "node:fs";
1191
+ import { homedir } from "node:os";
1192
+ import { join as join4 } from "node:path";
1193
+ import { gunzipSync } from "node:zlib";
1194
+ function distribution(target, version) {
1195
+ return target === "windows-x64" ? { file: "win-x64/node.exe", executable: "node.exe" } : { file: `node-v${version}-linux-x64.tar.gz`, member: `node-v${version}-linux-x64/bin/node`, executable: "node" };
1196
+ }
1197
+ function cacheRoot() {
1198
+ if (process.env.TARVE_CACHE_DIR)
1199
+ return process.env.TARVE_CACHE_DIR;
1200
+ if (process.platform === "win32")
1201
+ return join4(process.env.LOCALAPPDATA ?? join4(homedir(), "AppData", "Local"), "tarve", "cache");
1202
+ return join4(process.env.XDG_CACHE_HOME ?? join4(homedir(), ".cache"), "tarve");
1203
+ }
1204
+ function mirror() {
1205
+ return (process.env.NODEJS_ORG_MIRROR ?? "https://nodejs.org/dist").replace(/\/+$/, "");
1206
+ }
1207
+ async function download(url) {
1208
+ const response = await fetch(url);
1209
+ if (!response.ok)
1210
+ throw new Error(`Could not download ${url}: HTTP ${response.status}`);
1211
+ return Buffer.from(await response.arrayBuffer());
1212
+ }
1213
+ function extractTarMember(archive, member) {
1214
+ let offset = 0;
1215
+ let longName;
1216
+ while (offset + 512 <= archive.length) {
1217
+ const header = archive.subarray(offset, offset + 512);
1218
+ if (header.every((byte) => byte === 0))
1219
+ break;
1220
+ const field = (start, length) => header.toString("utf8", start, start + length).replace(/\0.*$/s, "");
1221
+ const size = Number.parseInt(field(124, 12).trim() || "0", 8);
1222
+ const type = field(156, 1) || "0";
1223
+ const prefix = field(345, 155);
1224
+ const name = longName ?? (prefix ? `${prefix}/${field(0, 100)}` : field(0, 100));
1225
+ const body = archive.subarray(offset + 512, offset + 512 + size);
1226
+ longName = undefined;
1227
+ if (type === "L")
1228
+ longName = body.toString("utf8").replace(/\0.*$/s, "");
1229
+ else if (type === "x")
1230
+ longName = /\d+ path=([^\n]*)\n/.exec(body.toString("utf8"))?.[1];
1231
+ else if ((type === "0" || type === "\x00") && name.replace(/^\.\//, "") === member)
1232
+ return Buffer.from(body);
1233
+ offset += 512 + Math.ceil(size / 512) * 512;
1234
+ }
1235
+ throw new Error(`${member} not found in the Node.js archive`);
1236
+ }
1237
+ function assertNodeVersion(executable, version) {
1238
+ if (!readFileSync5(executable).includes(`node-v${version}`)) {
1239
+ throw new Error(`${executable} is not Node.js v${version}; the target executable must match the Node.js that builds the app`);
1240
+ }
1241
+ }
1242
+ async function targetNodeExecutable(target, version) {
1243
+ const { file, member, executable } = distribution(target, version);
1244
+ const directory = join4(cacheRoot(), "node", `v${version}`, target);
1245
+ const path = join4(directory, executable);
1246
+ if (existsSync4(path))
1247
+ return path;
1248
+ const base = `${mirror()}/v${version}`;
1249
+ const sums = (await download(`${base}/SHASUMS256.txt`)).toString("utf8");
1250
+ const expected = sums.split(/\r?\n/).find((line) => line.endsWith(` ${file}`))?.split(/\s+/)[0];
1251
+ if (!expected)
1252
+ throw new Error(`${file} is not listed in the Node.js v${version} SHASUMS256.txt`);
1253
+ const payload = await download(`${base}/${file}`);
1254
+ const actual = createHash3("sha256").update(payload).digest("hex");
1255
+ if (actual !== expected)
1256
+ throw new Error(`Checksum mismatch for ${file}: expected ${expected}, got ${actual}`);
1257
+ const binary = member ? extractTarMember(gunzipSync(payload), member) : payload;
1258
+ mkdirSync2(directory, { recursive: true });
1259
+ const temporary = join4(directory, `${executable}.${randomUUID()}.tmp`);
1260
+ try {
1261
+ writeFileSync4(temporary, binary, { mode: 493 });
1262
+ try {
1263
+ renameSync(temporary, path);
1264
+ } catch (error) {
1265
+ if (!existsSync4(path))
1266
+ throw error;
1267
+ }
1268
+ } finally {
1269
+ rmSync(temporary, { force: true });
1270
+ }
1271
+ if (process.platform !== "win32")
1272
+ chmodSync2(path, 493);
1273
+ return path;
1274
+ }
1275
+ var init_node_target = () => {};
1276
+
1277
+ // packages/core/node-build.ts
1278
+ import { execFileSync as execFileSync2 } from "node:child_process";
1279
+ import { existsSync as existsSync5, mkdtempSync as mkdtempSync2, writeFileSync as writeFileSync5, readFileSync as readFileSync6 } from "node:fs";
1280
+ import { mkdir as mkdir2, rm as rm2 } from "node:fs/promises";
1281
+ import { tmpdir as tmpdir2 } from "node:os";
1282
+ import { basename as basename4, dirname as dirname5, join as join5, relative as relative3, resolve as resolve4 } from "node:path";
1283
+ import { nativePath as nativePath2 } from "#tarve/runtime";
1284
+ async function buildNode(options) {
1285
+ const target = options.target ?? hostBuildTarget();
1286
+ if (!target)
1287
+ throw new Error(`Unsupported Node.js build host: ${process.platform}-${process.arch}`);
1288
+ const config = targetConfig(target);
1289
+ const node = options.nodeExecutable ?? (process.versions.bun ? Bun.which("node") ?? "node" : process.execPath);
1290
+ const version = execFileSync2(node, ["--version"], { encoding: "utf8" }).trim();
1291
+ const match = /^v(\d+)\.(\d+)\./.exec(version);
1292
+ if (!match || Number(match[1]) < 26 || Number(match[1]) === 26 && Number(match[2]) < 10) {
1293
+ throw new Error(`Node.js 26.10+ is required for node:ffi inside a SEA (found ${version})`);
1294
+ }
1295
+ const { metadata, images, define } = buildMetadata(options.entrypoint, metadataOverrides(options));
1296
+ const outfile = resolve4(options.outfile ?? `dist/${metadata.name}${config.executableSuffix}`);
1297
+ let executable;
1298
+ if (options.targetExecutable) {
1299
+ executable = resolve4(options.targetExecutable);
1300
+ if (!existsSync5(executable))
1301
+ throw new Error(`Target Node.js executable is missing: ${executable}`);
1302
+ assertNodeVersion(executable, version.slice(1));
1303
+ }
1304
+ const library = resolve4(options.nativeLibrary ?? (target === hostBuildTarget() ? nativePath2() : join5(import.meta.dirname, "../../native", config.nativeDirectory, config.nativeName)));
1305
+ if (!existsSync5(library))
1306
+ throw new Error(`Tarve native library missing: ${library}`);
1307
+ const temporary = mkdtempSync2(join5(tmpdir2(), "tarve-node-build-"));
1308
+ try {
1309
+ const root = import.meta.dirname;
1310
+ const source = existsSync5(join5(root, "src/index.ts"));
1311
+ if (!options.nativeLibrary && (!source || target !== hostBuildTarget())) {
1312
+ const expected = source ? await createNativeCompatibilityManifest(resolve4(root, "../.."), JSON.parse(readFileSync6(resolve4(root, "../../package.json"), "utf8")).version) : await readNativeCompatibilityManifest(join5(root, NATIVE_COMPATIBILITY_MANIFEST_NAME));
1313
+ await assertNativeRuntimeCompatible(library, target, expected);
1314
+ }
1315
+ if (!executable && target !== hostBuildTarget()) {
1316
+ executable = await targetNodeExecutable(target, version.slice(1));
1317
+ }
1318
+ const { build: bundle } = await import("esbuild");
1319
+ const result = await bundle({
1320
+ entryPoints: [resolve4(options.entrypoint)],
1321
+ outfile: join5(temporary, "app.mjs"),
1322
+ bundle: true,
1323
+ platform: "node",
1324
+ format: "esm",
1325
+ target: "node26",
1326
+ jsx: "automatic",
1327
+ jsxImportSource: "@tarve/core",
1328
+ loader: { ".png": "file", ".jpg": "file", ".jpeg": "file", ".webp": "file", ".gif": "file", ".svg": "file" },
1329
+ metafile: true,
1330
+ define,
1331
+ external: ["esbuild"],
1332
+ plugins: [fileImportAttributes, {
1333
+ name: "tarve-node-runtime",
1334
+ setup(build) {
1335
+ if (options.compileJsx) {
1336
+ build.onLoad({ filter: /\.[jt]sx$/ }, async (args) => {
1337
+ if (/[\\/]node_modules[\\/]/.test(args.path) || args.path.startsWith(join5(root, "src")))
1338
+ return;
1339
+ await Promise.resolve().then(() => init_jsx_compile());
1340
+ return { contents: (await compileJsx(readFileSync6(args.path, "utf8"))).code, loader: args.path.endsWith(".jsx") ? "jsx" : "tsx", resolveDir: dirname5(args.path) };
1341
+ });
1342
+ }
1343
+ if (source) {
1344
+ build.onResolve({ filter: /^@tarve\/core(?:\/(?:jsx-runtime|jsx-dev-runtime))?$/ }, (args) => {
1345
+ const entry = args.path.slice("@tarve/core".length) || "/index";
1346
+ return { path: join5(root, "src", `${entry.slice(1)}.ts`) };
1347
+ });
1348
+ }
1349
+ build.onResolve({ filter: /^#tarve\/runtime$/ }, () => ({ path: "native-runtime", namespace: "tarve-node" }));
1350
+ build.onLoad({ filter: /.*/, namespace: "tarve-node" }, () => ({
1351
+ contents: `import { join } from "node:path"; export function nativePath() { return join(import.meta.dirname, ${JSON.stringify(config.nativeName)}); }`,
1352
+ loader: "js"
1353
+ }));
1354
+ }
1355
+ }]
1356
+ });
1357
+ const assets = { [config.nativeName]: seaPath(library) };
1358
+ for (const [path, output] of Object.entries(result.metafile.outputs)) {
1359
+ if (!output.entryPoint)
1360
+ assets[relative3(temporary, resolve4(path)).replaceAll("\\", "/")] = seaPath(resolve4(path));
1361
+ }
1362
+ const sea = join5(temporary, "sea.json");
1363
+ writeFileSync5(sea, JSON.stringify({
1364
+ main: seaPath(join5(temporary, "app.mjs")),
1365
+ mainFormat: "module",
1366
+ output: seaPath(outfile),
1367
+ ...executable ? { executable: seaPath(executable) } : {},
1368
+ useVfs: true,
1369
+ useCodeCache: false,
1370
+ useSnapshot: false,
1371
+ assets,
1372
+ execArgv: ["--disable-warning=ExperimentalWarning"],
1373
+ execArgvExtension: "env"
1374
+ }));
1375
+ await mkdir2(dirname5(outfile), { recursive: true });
1376
+ await rm2(outfile, { force: true });
1377
+ execFileSync2(node, ["--build-sea", sea], { stdio: "pipe" });
1378
+ if (config.platform === "win32") {
1379
+ const tarveVersion = JSON.parse(readFileSync6(resolve4(root, "../../package.json"), "utf8")).version;
1380
+ (await Promise.resolve().then(() => (init_windows_executable(), exports_windows_executable))).brandWindowsExecutable(outfile, {
1381
+ name: metadata.name,
1382
+ version: metadata.version ?? tarveVersion,
1383
+ filename: basename4(outfile),
1384
+ description: metadata.description,
1385
+ publisher: metadata.publisher,
1386
+ copyright: metadata.copyright,
1387
+ ico: images?.ico
1388
+ });
1389
+ }
1390
+ if (config.platform === "linux" && (metadata.icon || metadata.appId))
1391
+ writeLinuxDesktopEntry(outfile, metadata, images?.png);
1392
+ return outfile;
1393
+ } finally {
1394
+ if (options.compileJsx)
1395
+ await (await Promise.resolve().then(() => (init_jsx_compile(), exports_jsx_compile))).closeJsxCompiler();
1396
+ await rm2(temporary, { recursive: true, force: true });
1397
+ }
1398
+ }
1399
+ function seaPath(path) {
1400
+ return path.replaceAll("\\", "/");
1401
+ }
1402
+ var init_node_build = __esm(() => {
1403
+ init_esbuild_file_imports();
1404
+ init_targets();
1405
+ init_build();
1406
+ init_package_metadata();
1407
+ init_native_runtime();
1408
+ init_node_target();
1409
+ });
160
1410
 
161
1411
  // packages/core/build.ts
1412
+ import { existsSync as existsSync6, mkdtempSync as mkdtempSync3, writeFileSync as writeFileSync6 } from "node:fs";
1413
+ import { mkdir as mkdir3, rm as rm3 } from "node:fs/promises";
1414
+ import { tmpdir as tmpdir3 } from "node:os";
1415
+ import { dirname as dirname6, join as join6, resolve as resolve5 } from "node:path";
1416
+ import { fileURLToPath } from "node:url";
1417
+ import { nativePath as nativePath3 } from "#tarve/runtime";
162
1418
  function resolveNativeLibrary(target, override) {
163
1419
  if (override) {
164
- const path = resolve(override);
165
- if (!existsSync2(path))
1420
+ const path = resolve5(override);
1421
+ if (!existsSync6(path))
166
1422
  throw new Error(`Tarve native library does not exist: ${path}`);
167
1423
  return path;
168
1424
  }
@@ -170,37 +1426,46 @@ function resolveNativeLibrary(target, override) {
170
1426
  const hostTarget = hostBuildTarget();
171
1427
  if (hostTarget === target) {
172
1428
  try {
173
- return nativePath();
1429
+ return nativePath3();
174
1430
  } catch {}
175
1431
  }
176
1432
  const candidates = [
177
- join2(import.meta.dir, config.nativeName),
178
- resolve(import.meta.dir, "../../native", config.nativeDirectory, config.nativeName)
1433
+ join6(import.meta.dir, config.nativeName),
1434
+ resolve5(import.meta.dir, "../../native", config.nativeDirectory, config.nativeName)
179
1435
  ];
180
- const found = candidates.find(existsSync2);
1436
+ const found = candidates.find(existsSync6);
181
1437
  if (found)
182
1438
  return found;
183
1439
  throw new Error(`Tarve native library missing for ${target}. Expected ${config.nativeName} in native/${config.nativeDirectory}. ` + "Use a Tarve package containing that target runtime or pass nativeLibrary explicitly.");
184
1440
  }
185
1441
  async function build(options) {
1442
+ if (options.runtime === "txiki") {
1443
+ await Promise.resolve().then(() => init_txiki_build());
1444
+ return buildTxiki(options);
1445
+ }
1446
+ if (options.runtime === "node") {
1447
+ await Promise.resolve().then(() => init_node_build());
1448
+ return buildNode(options);
1449
+ }
186
1450
  const target = options.target ?? hostBuildTarget();
187
1451
  if (!target)
188
1452
  throw new Error(`Tarve executable distribution is not supported for ${process.platform}-${process.arch}. Pass an explicit supported target when cross-compiling.`);
189
1453
  if (!isBuildTarget(target))
190
1454
  throw new TypeError(`Unsupported Tarve build target: ${String(target)}. Expected ${BUILD_TARGETS.join(" or ")}.`);
191
1455
  const config = targetConfig(target);
192
- const entrypoint = resolve(options.entrypoint);
193
- const packageMetadata = await Bun.file(resolve(import.meta.dir, "../../package.json")).json();
1456
+ const entrypoint = resolve5(options.entrypoint);
1457
+ const packageMetadata = await Bun.file(resolve5(import.meta.dir, "../../package.json")).json();
194
1458
  if (typeof packageMetadata.version !== "string" || packageMetadata.version.length === 0) {
195
1459
  throw new Error("Tarve package version is missing.");
196
1460
  }
197
- const name = options.name ?? basename2(entrypoint).replace(/\.[^.]+$/, "");
198
- const outfile = resolve(options.outfile ?? `dist/${name}${config.executableSuffix}`);
1461
+ const { metadata, images, define } = buildMetadata(entrypoint, metadataOverrides(options));
1462
+ const name = metadata.name;
1463
+ const outfile = resolve5(options.outfile ?? `dist/${name}${config.executableSuffix}`);
199
1464
  const library = resolveNativeLibrary(target, options.nativeLibrary);
200
1465
  const assetsModule = fileURLToPath(import.meta.resolve("#tarve/assets"));
201
- const sourceDirectory = join2(import.meta.dir, "src");
202
- const repositorySource = existsSync2(join2(sourceDirectory, "index.ts"));
203
- const expectedCompatibility = repositorySource ? await createNativeCompatibilityManifest(resolve(import.meta.dir, "../.."), packageMetadata.version) : await readNativeCompatibilityManifest(join2(import.meta.dir, NATIVE_COMPATIBILITY_MANIFEST_NAME));
1466
+ const sourceDirectory = join6(import.meta.dir, "src");
1467
+ const repositorySource = existsSync6(join6(sourceDirectory, "index.ts"));
1468
+ const expectedCompatibility = repositorySource ? await createNativeCompatibilityManifest(resolve5(import.meta.dir, "../.."), packageMetadata.version) : await readNativeCompatibilityManifest(join6(import.meta.dir, NATIVE_COMPATIBILITY_MANIFEST_NAME));
204
1469
  const requireRuntimeManifest = target !== hostBuildTarget() || !options.nativeLibrary && !repositorySource;
205
1470
  if (requireRuntimeManifest) {
206
1471
  await assertNativeRuntimeCompatible(library, target, expectedCompatibility);
@@ -210,82 +1475,640 @@ async function build(options) {
210
1475
  sha256: new Bun.CryptoHasher("sha256").update(libraryBytes).digest("hex"),
211
1476
  size: libraryBytes.byteLength
212
1477
  };
1478
+ const packDirectory = mkdtempSync3(join6(tmpdir3(), "tarve-native-"));
1479
+ const packedLibrary = join6(packDirectory, `${config.nativeName}.zst`);
1480
+ writeFileSync6(packedLibrary, Bun.zstdCompressSync(libraryBytes, { level: NATIVE_ZSTD_LEVEL }));
213
1481
  const runtime = {
214
1482
  name: "tarve-native-runtime",
215
1483
  setup(builder) {
216
1484
  if (repositorySource) {
217
- builder.onResolve({ filter: /^tarve$/ }, () => ({ path: join2(sourceDirectory, "index.ts") }));
218
- builder.onResolve({ filter: /^tarve\/jsx-runtime$/ }, () => ({ path: join2(sourceDirectory, "jsx-runtime.ts") }));
219
- builder.onResolve({ filter: /^tarve\/jsx-dev-runtime$/ }, () => ({ path: join2(sourceDirectory, "jsx-dev-runtime.ts") }));
1485
+ builder.onResolve({ filter: /^tarve$/ }, () => ({ path: join6(sourceDirectory, "index.ts") }));
1486
+ builder.onResolve({ filter: /^tarve\/jsx-runtime$/ }, () => ({ path: join6(sourceDirectory, "jsx-runtime.ts") }));
1487
+ builder.onResolve({ filter: /^tarve\/jsx-dev-runtime$/ }, () => ({ path: join6(sourceDirectory, "jsx-dev-runtime.ts") }));
1488
+ }
1489
+ if (options.compileJsx) {
1490
+ builder.onLoad({ filter: /\.[jt]sx$/ }, async (args) => {
1491
+ if (/[\\/]node_modules[\\/]/.test(args.path) || args.path.startsWith(join6(import.meta.dir, "src")))
1492
+ return;
1493
+ await Promise.resolve().then(() => init_jsx_compile());
1494
+ return { contents: (await compileJsx(await Bun.file(args.path).text())).code, loader: args.path.endsWith(".jsx") ? "jsx" : "tsx" };
1495
+ });
220
1496
  }
221
1497
  builder.onResolve({ filter: /^#tarve\/runtime$/ }, () => ({ path: "runtime", namespace: "tarve" }));
222
1498
  builder.onLoad({ filter: /^runtime$/, namespace: "tarve" }, () => ({
223
1499
  loader: "ts",
224
1500
  contents: [
225
- `import library from ${JSON.stringify(library)} with { type: "file" };`,
1501
+ `import library from ${JSON.stringify(packedLibrary)} with { type: "file" };`,
226
1502
  `import { materializeAsset } from ${JSON.stringify(assetsModule)};`,
227
1503
  `const digest = ${JSON.stringify(libraryDigest)};`,
228
- `export function nativePath() { return materializeAsset(library, ${JSON.stringify(config.nativeName)}, digest); }`
1504
+ `export function nativePath() { return materializeAsset(library, ${JSON.stringify(config.nativeName)}, digest, "zstd"); }`
229
1505
  ].join(`
230
1506
  `)
231
1507
  }));
232
1508
  }
233
1509
  };
234
- await mkdir(dirname2(outfile), { recursive: true });
235
- const result = await Bun.build({
236
- entrypoints: [entrypoint],
237
- target: "bun",
238
- plugins: [runtime],
239
- define: { "process.env.NODE_ENV": JSON.stringify("production") },
240
- minify: true,
241
- compile: {
242
- target: config.bunTarget,
243
- outfile,
244
- autoloadDotenv: false,
245
- autoloadBunfig: false,
246
- ...config.platform === "win32" ? {
247
- windows: { hideConsole: true, title: name, version: options.version ?? packageMetadata.version, description: `${name} \u2014 native Tarve application` }
248
- } : {}
249
- }
250
- });
251
- if (!result.success)
252
- throw new AggregateError(result.logs, "Could not compile the Tarve application");
1510
+ await mkdir3(dirname6(outfile), { recursive: true });
1511
+ const iconDirectory = images && config.platform === "win32" ? mkdtempSync3(join6(tmpdir3(), "tarve-icon-")) : undefined;
1512
+ const icoPath = iconDirectory ? join6(iconDirectory, "app.ico") : undefined;
1513
+ if (icoPath)
1514
+ writeFileSync6(icoPath, images.ico);
1515
+ try {
1516
+ const result = await Bun.build({
1517
+ entrypoints: [entrypoint],
1518
+ target: "bun",
1519
+ plugins: [runtime],
1520
+ define: { "process.env.NODE_ENV": JSON.stringify("production"), ...define },
1521
+ minify: true,
1522
+ compile: {
1523
+ target: config.bunTarget,
1524
+ outfile,
1525
+ autoloadDotenv: false,
1526
+ autoloadBunfig: false,
1527
+ ...config.platform === "win32" ? {
1528
+ windows: {
1529
+ hideConsole: true,
1530
+ title: name,
1531
+ version: metadata.version ?? packageMetadata.version,
1532
+ description: metadata.description ?? `${name} — native Tarve application`,
1533
+ ...metadata.publisher ? { publisher: metadata.publisher } : {},
1534
+ ...metadata.copyright ? { copyright: metadata.copyright } : {},
1535
+ ...icoPath ? { icon: icoPath } : {}
1536
+ }
1537
+ } : {}
1538
+ }
1539
+ });
1540
+ if (!result.success)
1541
+ throw new AggregateError(result.logs, "Could not compile the Tarve application");
1542
+ } finally {
1543
+ if (options.compileJsx)
1544
+ await (await Promise.resolve().then(() => (init_jsx_compile(), exports_jsx_compile))).closeJsxCompiler();
1545
+ await rm3(packDirectory, { recursive: true, force: true });
1546
+ if (iconDirectory)
1547
+ await rm3(iconDirectory, { recursive: true, force: true });
1548
+ }
1549
+ if (config.platform === "linux" && (metadata.icon || metadata.appId))
1550
+ writeLinuxDesktopEntry(outfile, metadata, images?.png);
253
1551
  return outfile;
254
1552
  }
1553
+ function metadataOverrides(options) {
1554
+ return { name: options.name, version: options.version, description: options.description, publisher: options.publisher, copyright: options.copyright, icon: options.icon, appId: options.appId };
1555
+ }
1556
+ var NATIVE_ZSTD_LEVEL = 12;
1557
+ var init_build = __esm(() => {
1558
+ init_package_metadata();
1559
+ init_targets();
1560
+ init_native_runtime();
1561
+ init_targets();
1562
+ });
255
1563
 
256
1564
  // packages/core/cli.ts
257
- async function main() {
1565
+ init_package_metadata();
1566
+ init_build();
1567
+ import { spawn } from "node:child_process";
1568
+ import { resolve as resolve8 } from "node:path";
1569
+ import { parseArgs } from "node:util";
1570
+
1571
+ // packages/core/node-dev.ts
1572
+ init_esbuild_file_imports();
1573
+ import { fork, spawnSync } from "node:child_process";
1574
+ import { mkdtempSync as mkdtempSync4, rmSync as rmSync2, writeFileSync as writeFileSync7 } from "node:fs";
1575
+ import { tmpdir as tmpdir4 } from "node:os";
1576
+ import { join as join7, resolve as resolve6 } from "node:path";
1577
+ import { context, build as build2 } from "esbuild";
1578
+ import { nativePath as nativePath4 } from "#tarve/runtime";
1579
+ var installedBuildApi = {
1580
+ name: "tarve-installed-build-api",
1581
+ setup(build) {
1582
+ build.onResolve({ filter: /^@tarve\/core\/build$/ }, () => ({ path: import.meta.resolve("@tarve/core/build"), external: true }));
1583
+ }
1584
+ };
1585
+ async function devNode(entrypoint) {
1586
+ const directory = mkdtempSync4(join7(tmpdir4(), "tarve-node-dev-"));
1587
+ const app = join7(directory, "app.mjs");
1588
+ const bootstrap = join7(directory, "bootstrap.mjs");
1589
+ writeFileSync7(bootstrap, `
1590
+ import { pathToFileURL } from "node:url";
1591
+ const entry = pathToFileURL(process.argv[2]).href;
1592
+ let version = 0;
1593
+ async function load() {
1594
+ await import(entry + "?v=" + version++);
1595
+ process.send?.({ type: "loaded", version });
1596
+ }
1597
+ function showError(error) {
1598
+ console.error(error);
1599
+ globalThis[Symbol.for("tarve.devApp")]?.remount(() => { throw error; });
1600
+ }
1601
+ let queue = Promise.resolve().then(load).catch(error => { console.error(error); process.exit(1); });
1602
+ process.on("message", message => {
1603
+ if (message === "reload") queue = queue.then(load).catch(showError);
1604
+ if (message?.type === "build-error") showError(new Error(message.error));
1605
+ });
1606
+ process.on("disconnect", () => process.exit(0));
1607
+ `);
1608
+ let child;
1609
+ let readyToReload = false;
1610
+ let builds = 0;
1611
+ const compiler = await context({
1612
+ entryPoints: [resolve6(entrypoint)],
1613
+ outfile: app,
1614
+ bundle: true,
1615
+ platform: "node",
1616
+ format: "esm",
1617
+ target: "node26",
1618
+ jsx: "automatic",
1619
+ jsxImportSource: "@tarve/core",
1620
+ loader: { ".png": "file", ".jpg": "file", ".jpeg": "file", ".webp": "file", ".gif": "file", ".svg": "file" },
1621
+ plugins: [installedBuildApi, fileImportAttributes, {
1622
+ name: "tarve-node-hot",
1623
+ setup(build) {
1624
+ build.onEnd((result) => {
1625
+ if (++builds <= 2 || !readyToReload || !child?.connected)
1626
+ return;
1627
+ if (result.errors.length) {
1628
+ child.send({ type: "build-error", error: result.errors.map((error) => error.text).join(`
1629
+ `) });
1630
+ } else {
1631
+ child.send("reload");
1632
+ }
1633
+ });
1634
+ }
1635
+ }]
1636
+ });
258
1637
  try {
259
- const { values, positionals } = parseArgs({
260
- args: process.argv.slice(2),
261
- allowPositionals: true,
262
- options: {
263
- outfile: { type: "string" },
264
- name: { type: "string" },
265
- version: { type: "string" },
266
- target: { type: "string" },
267
- help: { type: "boolean", short: "h" }
1638
+ await compiler.rebuild();
1639
+ await compiler.watch();
1640
+ child = fork(bootstrap, [app], {
1641
+ execPath: nodeExecutable(),
1642
+ stdio: ["inherit", "inherit", "inherit", "ipc"],
1643
+ execArgv: ["--disable-warning=ExperimentalWarning"],
1644
+ env: { ...process.env, TARVE_DEV: "1", TARVE_HOT: "1", TARVE_NATIVE: nativePath4(), TARVE_ENTRY: resolve6(entrypoint) }
1645
+ });
1646
+ child.on("message", (message) => {
1647
+ if (typeof message === "object" && message && "version" in message) {
1648
+ if (Number(message.version) === 1)
1649
+ readyToReload = true;
1650
+ console.log(Number(message.version) === 1 ? "tarve dev: ready" : "tarve dev: remounted");
268
1651
  }
269
1652
  });
270
- if (values.help || positionals.length === 0) {
271
- const defaultTarget = values.target && isBuildTarget(values.target) ? values.target : hostBuildTarget();
272
- const defaultOutput = `dist/App${defaultTarget ? targetConfig(defaultTarget).executableSuffix : ""}`;
273
- console.log(`Usage: tarve build <app.tsx> [--target ${BUILD_TARGETS.join("|")}] [--outfile ${defaultOutput}] [--name App] [--version 1.0.0]`);
274
- } else if (positionals[0] === "build" && positionals.length === 2) {
275
- if (values.target !== undefined && !isBuildTarget(values.target)) {
276
- throw new Error(`Unsupported target: ${values.target}. Expected ${BUILD_TARGETS.join(" or ")}.`);
1653
+ const running = child;
1654
+ let stopping = false;
1655
+ const stop = () => {
1656
+ stopping = true;
1657
+ running.kill();
1658
+ };
1659
+ process.on("SIGINT", stop);
1660
+ process.on("SIGTERM", stop);
1661
+ try {
1662
+ const code = await new Promise((resolve, reject) => {
1663
+ running.once("error", reject);
1664
+ running.once("exit", (code, signal) => resolve(code ?? (signal ? 1 : 0)));
1665
+ });
1666
+ if (code !== 0 && !stopping)
1667
+ throw new Error(`Node application exited with code ${code}`);
1668
+ } finally {
1669
+ process.off("SIGINT", stop);
1670
+ process.off("SIGTERM", stop);
1671
+ }
1672
+ } finally {
1673
+ if (child && !child.killed && child.exitCode === null)
1674
+ child.kill();
1675
+ await compiler.dispose();
1676
+ rmSync2(directory, { recursive: true, force: true });
1677
+ }
1678
+ }
1679
+ function nodeExecutable() {
1680
+ return process.versions.bun ? Bun.which("node") ?? "node" : process.execPath;
1681
+ }
1682
+ async function runNode(entrypoint) {
1683
+ const directory = mkdtempSync4(join7(tmpdir4(), "tarve-node-run-"));
1684
+ try {
1685
+ const app = join7(directory, "app.mjs");
1686
+ await build2({
1687
+ entryPoints: [resolve6(entrypoint)],
1688
+ outfile: app,
1689
+ bundle: true,
1690
+ platform: "node",
1691
+ format: "esm",
1692
+ target: "node26",
1693
+ jsx: "automatic",
1694
+ jsxImportSource: "@tarve/core",
1695
+ loader: { ".png": "file", ".jpg": "file", ".jpeg": "file", ".webp": "file", ".gif": "file", ".svg": "file" },
1696
+ plugins: [installedBuildApi, fileImportAttributes]
1697
+ });
1698
+ const result = spawnSync(nodeExecutable(), ["--disable-warning=ExperimentalWarning", app], {
1699
+ stdio: "inherit",
1700
+ env: { ...process.env, TARVE_NATIVE: nativePath4(), TARVE_ENTRY: resolve6(entrypoint) }
1701
+ });
1702
+ if (result.error)
1703
+ throw result.error;
1704
+ return result.status ?? 1;
1705
+ } finally {
1706
+ rmSync2(directory, { recursive: true, force: true });
1707
+ }
1708
+ }
1709
+
1710
+ // packages/core/runtime-select.ts
1711
+ function selectRuntime(flag, versions = process.versions, userAgent = process.env.npm_config_user_agent) {
1712
+ if (flag !== undefined) {
1713
+ if (flag !== "bun" && flag !== "node")
1714
+ throw new Error(`Unsupported runtime: ${flag}. Expected bun or node.`);
1715
+ return flag;
1716
+ }
1717
+ const launcher = /^(?:npm|pnpm|yarn)\/.*?\bnode\/v(\S+)/.exec(userAgent ?? "");
1718
+ if (launcher && supportsNodeRuntime(launcher[1]))
1719
+ return "node";
1720
+ if (versions.bun || /^bun\//.test(userAgent ?? ""))
1721
+ return "bun";
1722
+ return supportsNodeRuntime(versions.node) ? "node" : "bun";
1723
+ }
1724
+ function supportsNodeRuntime(version) {
1725
+ const [major = 0, minor = 0] = (version ?? "").split(".").map(Number);
1726
+ return major > 26 || major === 26 && minor >= 10;
1727
+ }
1728
+
1729
+ // packages/core/updates-build.ts
1730
+ import { spawnSync as spawnSync2 } from "node:child_process";
1731
+ import { createHash as createHash5, createPrivateKey, createPublicKey as createPublicKey2, generateKeyPairSync, sign } from "node:crypto";
1732
+ import { copyFileSync, existsSync as existsSync7, mkdirSync as mkdirSync3, readFileSync as readFileSync7, statSync, writeFileSync as writeFileSync8 } from "node:fs";
1733
+ import { basename as basename5, extname as extname2, join as join8, resolve as resolve7 } from "node:path";
1734
+
1735
+ // packages/core/src/updates.ts
1736
+ import { createHash as createHash4, createPublicKey, verify } from "node:crypto";
1737
+
1738
+ // packages/core/src/embedded-assets.ts
1739
+ var materialized = new Map;
1740
+
1741
+ // packages/core/src/app-metadata.ts
1742
+ init_png();
1743
+
1744
+ // packages/core/src/updates.ts
1745
+ var SPKI_ED25519 = "302a300506032b6570032100";
1746
+ var MAX_MANIFEST_BYTES = 1 << 20;
1747
+ var VERSION = /^v?\d+(\.\d+){0,3}(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/;
1748
+ var PLATFORM = /^[a-z0-9]+-[a-z0-9]+$/;
1749
+ function isValidVersion(version) {
1750
+ return typeof version === "string" && version.length <= 128 && VERSION.test(version);
1751
+ }
1752
+ function isValidPlatform(platform) {
1753
+ return PLATFORM.test(platform);
1754
+ }
1755
+ function isLoopback(host) {
1756
+ return host === "localhost" || host === "[::1]" || /^127\.\d+\.\d+\.\d+$/.test(host);
1757
+ }
1758
+ function assertUpdateUrl(url, allowInsecure = false) {
1759
+ let parsed;
1760
+ try {
1761
+ parsed = new URL(url);
1762
+ } catch {
1763
+ throw new TypeError(`Invalid update URL: ${url}`);
1764
+ }
1765
+ if (parsed.protocol === "https:")
1766
+ return parsed;
1767
+ if (parsed.protocol === "http:" && (allowInsecure || isLoopback(parsed.hostname)))
1768
+ return parsed;
1769
+ throw new Error(`Update URL must use HTTPS: ${url}`);
1770
+ }
1771
+ function invalid(reason) {
1772
+ throw new TypeError(`Invalid update manifest: ${reason}`);
1773
+ }
1774
+ function validateUpdateManifest(value) {
1775
+ if (!value || typeof value !== "object" || Array.isArray(value))
1776
+ invalid("not an object");
1777
+ const m = value;
1778
+ if (typeof m.version !== "string" || !isValidVersion(m.version))
1779
+ invalid("version");
1780
+ if (typeof m.pubDate !== "string" || Number.isNaN(Date.parse(m.pubDate)))
1781
+ invalid("pubDate");
1782
+ if (m.name !== undefined && (typeof m.name !== "string" || !m.name))
1783
+ invalid("name");
1784
+ if (m.notes !== undefined && typeof m.notes !== "string")
1785
+ invalid("notes");
1786
+ if (!m.platforms || typeof m.platforms !== "object" || Array.isArray(m.platforms))
1787
+ invalid("platforms");
1788
+ for (const [platform, artifact] of Object.entries(m.platforms)) {
1789
+ if (!isValidPlatform(platform))
1790
+ invalid(`platform ${platform}`);
1791
+ const a = artifact;
1792
+ if (!a || typeof a !== "object")
1793
+ invalid(`platforms.${platform}`);
1794
+ if (typeof a.url !== "string" || !a.url)
1795
+ invalid(`platforms.${platform}.url`);
1796
+ if (typeof a.sha256 !== "string" || !/^[0-9a-f]{64}$/i.test(a.sha256))
1797
+ invalid(`platforms.${platform}.sha256`);
1798
+ if (typeof a.size !== "number" || !Number.isSafeInteger(a.size) || a.size <= 0)
1799
+ invalid(`platforms.${platform}.size`);
1800
+ }
1801
+ return value;
1802
+ }
1803
+ function verifyUpdateManifest(signed, publicKey) {
1804
+ if (typeof signed?.payload !== "string" || typeof signed.signature !== "string")
1805
+ invalid("expected { payload, signature }");
1806
+ if (Buffer.byteLength(signed.payload) > MAX_MANIFEST_BYTES)
1807
+ invalid("too large");
1808
+ const raw = Buffer.from(publicKey.trim(), "base64");
1809
+ if (raw.length !== 32)
1810
+ throw new TypeError("Update public key must be 32 bytes of base64 (tarve keygen)");
1811
+ const signature = Buffer.from(signed.signature, "base64");
1812
+ const key = createPublicKey({ key: Buffer.concat([Buffer.from(SPKI_ED25519, "hex"), raw]), format: "der", type: "spki" });
1813
+ if (signature.length !== 64 || !verify(null, Buffer.from(signed.payload, "utf8"), key, signature)) {
1814
+ throw new Error("Update manifest signature is invalid");
1815
+ }
1816
+ let parsed;
1817
+ try {
1818
+ parsed = JSON.parse(signed.payload);
1819
+ } catch {
1820
+ invalid("payload is not JSON");
1821
+ }
1822
+ return validateUpdateManifest(parsed);
1823
+ }
1824
+ function executableMagic(platform) {
1825
+ if (platform.startsWith("win32-"))
1826
+ return Uint8Array.of(77, 90);
1827
+ if (platform.startsWith("linux-"))
1828
+ return Uint8Array.of(127, 69, 76, 70);
1829
+ return;
1830
+ }
1831
+ function looksExecutable(bytes, platform) {
1832
+ const magic = executableMagic(platform);
1833
+ return !magic || bytes.length >= magic.length && magic.every((byte, i) => bytes[i] === byte);
1834
+ }
1835
+
1836
+ // packages/core/updates-build.ts
1837
+ function generateUpdateKeys() {
1838
+ const { publicKey, privateKey } = generateKeyPairSync("ed25519");
1839
+ const spki = publicKey.export({ format: "der", type: "spki" });
1840
+ return {
1841
+ publicKey: Buffer.from(spki.subarray(spki.length - 32)).toString("base64"),
1842
+ privateKey: Buffer.from(privateKey.export({ format: "der", type: "pkcs8" })).toString("base64")
1843
+ };
1844
+ }
1845
+ function privateKeyObject(privateKey) {
1846
+ try {
1847
+ return createPrivateKey({ key: Buffer.from(privateKey.trim(), "base64"), format: "der", type: "pkcs8" });
1848
+ } catch {
1849
+ throw new Error("Invalid update private key: expected the base64 PKCS#8 key written by tarve keygen");
1850
+ }
1851
+ }
1852
+ function updatePublicKey(privateKey) {
1853
+ const spki = createPublicKey2(privateKeyObject(privateKey)).export({ format: "der", type: "spki" });
1854
+ return Buffer.from(spki.subarray(spki.length - 32)).toString("base64");
1855
+ }
1856
+ function signUpdateManifest(manifest, privateKey) {
1857
+ const key = privateKeyObject(privateKey);
1858
+ if (key.asymmetricKeyType !== "ed25519")
1859
+ throw new Error("Update private key must be Ed25519 (tarve keygen)");
1860
+ const payload = JSON.stringify(manifest);
1861
+ return { payload, signature: sign(null, Buffer.from(payload, "utf8"), key).toString("base64") };
1862
+ }
1863
+ function signFile(command, file) {
1864
+ const quoted = `"${file.replaceAll('"', "\\\"")}"`;
1865
+ const line = command.includes("{file}") ? command.replaceAll("{file}", quoted) : `${command} ${quoted}`;
1866
+ const result = spawnSync2(line, { shell: true, stdio: "inherit" });
1867
+ if (result.error)
1868
+ throw result.error;
1869
+ if (result.status !== 0)
1870
+ throw new Error(`Signing ${basename5(file)} failed (exit ${result.status}): ${line}`);
1871
+ }
1872
+ function release(options) {
1873
+ if (!options.artifacts.length)
1874
+ throw new Error("tarve release needs at least one --artifact platform=path");
1875
+ if (!isValidVersion(options.version))
1876
+ throw new Error(`Invalid --version ${options.version}: expected e.g. 1.2.3 or 1.2.3-beta.1`);
1877
+ if (options.baseUrl)
1878
+ assertUpdateUrl(options.baseUrl);
1879
+ const key = existsSync7(options.privateKey) ? readFileSync7(options.privateKey, "utf8") : options.privateKey;
1880
+ const publicKey = updatePublicKey(key);
1881
+ if (options.publicKey && options.publicKey.trim() !== publicKey) {
1882
+ throw new Error(`The private key does not match --public-key: apps built with ${options.publicKey.trim()} would reject this release`);
1883
+ }
1884
+ const entries = options.artifacts.map((pair) => {
1885
+ const at = pair.indexOf("=");
1886
+ if (at <= 0)
1887
+ throw new Error(`Expected --artifact platform=path, got ${pair}`);
1888
+ const platform = pair.slice(0, at), source = resolve7(pair.slice(at + 1));
1889
+ if (!isValidPlatform(platform))
1890
+ throw new Error(`Invalid platform ${platform}, expected e.g. win32-x64`);
1891
+ if (!existsSync7(source) || !statSync(source).isFile())
1892
+ throw new Error(`Artifact not found: ${source}`);
1893
+ if (statSync(source).size === 0)
1894
+ throw new Error(`Artifact is empty: ${source}`);
1895
+ if (!looksExecutable(readFileSync7(source).subarray(0, 4), platform))
1896
+ throw new Error(`${source} is not a ${platform} executable`);
1897
+ return { platform, source };
1898
+ });
1899
+ const seen = new Set;
1900
+ for (const { platform } of entries) {
1901
+ if (seen.has(platform))
1902
+ throw new Error(`Platform ${platform} is listed twice`);
1903
+ seen.add(platform);
1904
+ }
1905
+ const outDir = resolve7(options.outDir ?? "dist/updates");
1906
+ mkdirSync3(outDir, { recursive: true });
1907
+ const platforms = {};
1908
+ for (const { platform, source } of entries) {
1909
+ const stem = basename5(source, extname2(source));
1910
+ const file = `${stem}-${options.version}-${platform}${extname2(source)}`;
1911
+ const target = join8(outDir, file);
1912
+ if (resolve7(target) === source)
1913
+ throw new Error(`Artifact ${source} is already in --out; build it elsewhere`);
1914
+ copyFileSync(source, target);
1915
+ if (options.sign && platform.startsWith("win32-")) {
1916
+ const before = createHash5("sha256").update(readFileSync7(target)).digest("hex");
1917
+ signFile(options.sign, target);
1918
+ if (createHash5("sha256").update(readFileSync7(target)).digest("hex") === before) {
1919
+ throw new Error(`The sign command left ${file} unchanged: it was not signed`);
277
1920
  }
278
- console.log(await build({
279
- entrypoint: positionals[1],
280
- ...values,
281
- target: values.target
282
- }));
283
- } else {
284
- throw new Error("Expected: tarve build <app.tsx>. Use --help for options.");
285
1921
  }
286
- } catch (error) {
287
- console.error(`error: ${error instanceof Error ? error.message : String(error)}`);
288
- process.exitCode = 1;
1922
+ const bytes = readFileSync7(target);
1923
+ if (!looksExecutable(bytes.subarray(0, 4), platform))
1924
+ throw new Error(`The sign command broke ${file}: it is no longer an executable`);
1925
+ platforms[platform] = {
1926
+ url: options.baseUrl ? options.baseUrl.replace(/\/?$/, "/") + encodeURIComponent(file) : encodeURIComponent(file),
1927
+ sha256: createHash5("sha256").update(bytes).digest("hex"),
1928
+ size: bytes.length
1929
+ };
289
1930
  }
1931
+ const manifest = {
1932
+ ...options.name ? { name: options.name } : {},
1933
+ version: options.version,
1934
+ ...options.notes ? { notes: options.notes } : {},
1935
+ pubDate: new Date().toISOString(),
1936
+ platforms
1937
+ };
1938
+ const signed = signUpdateManifest(manifest, key);
1939
+ verifyUpdateManifest(signed, publicKey);
1940
+ const path = join8(outDir, "latest.json");
1941
+ writeFileSync8(path, JSON.stringify(signed, null, 2) + `
1942
+ `);
1943
+ return path;
1944
+ }
1945
+
1946
+ // packages/core/cli.ts
1947
+ init_targets();
1948
+ import { existsSync as existsSync8, writeFileSync as writeFileSync9 } from "node:fs";
1949
+ var COMMANDS = ["run", "dev", "build"];
1950
+ var KEY_FILE = "tarve-update.key";
1951
+ function usage(target) {
1952
+ const output = `dist/App${target ? targetConfig(target).executableSuffix : ""}`;
1953
+ return [
1954
+ "Usage: tarve <run|dev|build> <app.tsx> [options]",
1955
+ " tarve keygen",
1956
+ " tarve release --version 1.2.0 --artifact win32-x64=dist/App.exe [...]",
1957
+ "",
1958
+ " run run the app",
1959
+ " dev run with hot reload into the same window",
1960
+ " build compile a standalone executable",
1961
+ ` keygen create an update signing key pair (writes ${KEY_FILE}, prints the public key)`,
1962
+ " release copy built executables to --out and write the signed latest.json",
1963
+ "",
1964
+ "Options:",
1965
+ " --runtime bun|node|txiki defaults to the runtime that launched tarve; txiki: build only",
1966
+ ` --target ${BUILD_TARGETS.join("|")} build: target OS (cross-compiles)`,
1967
+ ` --outfile ${output} build: output path`,
1968
+ " --compile-jsx build: compile JSX into reusable templates (needs typescript 7)",
1969
+ " --name App, --version 1.0.0 app metadata (executable, window, app identity)",
1970
+ " --icon icon.png app icon: .png (square, 256 px+) or .ico",
1971
+ " --app-id Acme.App Windows AppUserModelID / Linux app id",
1972
+ " --description, --publisher, --copyright build: executable details",
1973
+ ' each defaults to the "tarve" field of package.json',
1974
+ " --target-executable path build (node): target OS Node binary for offline cross-builds",
1975
+ " --artifact platform=path release: repeatable, platform is <os>-<arch> (win32-x64, linux-x64)",
1976
+ ` --key ${KEY_FILE} release: private key file or base64 (default: TARVE_UPDATE_PRIVATE_KEY, then ./${KEY_FILE})`,
1977
+ " --public-key base64 release: verify the signed manifest before writing it",
1978
+ " --out dist/updates release: output directory; keygen: where the key goes",
1979
+ " --base-url https://host/path/ release: artifact URL prefix (default: relative to latest.json)",
1980
+ " --notes text release: release notes",
1981
+ ' --sign "signtool sign … {file}" release: Authenticode command per Windows artifact, before hashing',
1982
+ " (default: TARVE_SIGN_COMMAND)"
1983
+ ].join(`
1984
+ `);
1985
+ }
1986
+ function forward(command, args, env = process.env) {
1987
+ return new Promise((resolveCode, reject) => {
1988
+ const child = spawn(command, args, { stdio: "inherit", env });
1989
+ const stop = () => child.kill();
1990
+ process.on("SIGINT", stop);
1991
+ process.on("SIGTERM", stop);
1992
+ child.once("error", (error) => {
1993
+ reject(error.code === "ENOENT" ? new Error(command === "bun" ? "Bun was not found. Install Bun, or run with Node.js 26.10+ and --runtime node." : `${command} was not found. Install it or choose the other runtime with --runtime.`) : error);
1994
+ });
1995
+ child.once("exit", (code, signal) => {
1996
+ process.off("SIGINT", stop);
1997
+ process.off("SIGTERM", stop);
1998
+ resolveCode(code ?? (signal ? 1 : 0));
1999
+ });
2000
+ });
2001
+ }
2002
+ async function main() {
2003
+ const { values, positionals } = parseArgs({
2004
+ args: process.argv.slice(2),
2005
+ allowPositionals: true,
2006
+ options: {
2007
+ outfile: { type: "string" },
2008
+ name: { type: "string" },
2009
+ version: { type: "string" },
2010
+ icon: { type: "string" },
2011
+ "app-id": { type: "string" },
2012
+ description: { type: "string" },
2013
+ publisher: { type: "string" },
2014
+ copyright: { type: "string" },
2015
+ target: { type: "string" },
2016
+ runtime: { type: "string" },
2017
+ "compile-jsx": { type: "boolean" },
2018
+ "target-executable": { type: "string" },
2019
+ artifact: { type: "string", multiple: true },
2020
+ key: { type: "string" },
2021
+ "public-key": { type: "string" },
2022
+ out: { type: "string" },
2023
+ "base-url": { type: "string" },
2024
+ notes: { type: "string" },
2025
+ sign: { type: "string" },
2026
+ help: { type: "boolean", short: "h" }
2027
+ }
2028
+ });
2029
+ const [command, entrypoint] = positionals;
2030
+ if (values.help || positionals.length === 0) {
2031
+ console.log(usage(values.target && isBuildTarget(values.target) ? values.target : hostBuildTarget()));
2032
+ return 0;
2033
+ }
2034
+ if (command === "keygen")
2035
+ return keygen(values.out);
2036
+ if (command === "release") {
2037
+ if (!values.version)
2038
+ throw new Error("tarve release needs --version.");
2039
+ const privateKey = values.key ?? process.env.TARVE_UPDATE_PRIVATE_KEY ?? (existsSync8(KEY_FILE) ? KEY_FILE : undefined);
2040
+ if (!privateKey)
2041
+ throw new Error(`tarve release needs --key, TARVE_UPDATE_PRIVATE_KEY or ./${KEY_FILE} (tarve keygen).`);
2042
+ console.log(release({
2043
+ version: values.version,
2044
+ artifacts: values.artifact ?? [],
2045
+ privateKey,
2046
+ publicKey: values["public-key"],
2047
+ outDir: values.out,
2048
+ baseUrl: values["base-url"],
2049
+ name: values.name,
2050
+ notes: values.notes,
2051
+ sign: values.sign ?? process.env.TARVE_SIGN_COMMAND
2052
+ }));
2053
+ return 0;
2054
+ }
2055
+ if (!COMMANDS.includes(command) || !entrypoint || positionals.length !== 2) {
2056
+ throw new Error("Expected: tarve <run|dev|build> <app.tsx>. Use --help for options.");
2057
+ }
2058
+ if (values.target !== undefined && !isBuildTarget(values.target)) {
2059
+ throw new Error(`Unsupported target: ${values.target}. Expected ${BUILD_TARGETS.join(" or ")}.`);
2060
+ }
2061
+ const txiki = values.runtime === "txiki";
2062
+ if (txiki && command !== "build")
2063
+ throw new Error("--runtime txiki is only supported by tarve build.");
2064
+ const runtime = txiki ? "txiki" : selectRuntime(values.runtime);
2065
+ if (runtime === "bun" && !process.versions.bun) {
2066
+ return forward("bun", [process.argv[1], ...process.argv.slice(2), "--runtime", "bun"]);
2067
+ }
2068
+ if (command === "build") {
2069
+ console.log(await build({
2070
+ entrypoint,
2071
+ outfile: values.outfile,
2072
+ name: values.name,
2073
+ version: values.version,
2074
+ icon: values.icon,
2075
+ appId: values["app-id"],
2076
+ description: values.description,
2077
+ publisher: values.publisher,
2078
+ copyright: values.copyright,
2079
+ target: values.target,
2080
+ runtime,
2081
+ compileJsx: values["compile-jsx"],
2082
+ targetExecutable: values["target-executable"]
2083
+ }));
2084
+ return 0;
2085
+ }
2086
+ const metadata = resolveAppMetadata(entrypoint, { name: values.name, icon: values.icon, appId: values["app-id"] });
2087
+ process.env.TARVE_APP_METADATA = runtimeMetadata(metadata, metadata.icon);
2088
+ if (runtime === "node") {
2089
+ if (command === "dev") {
2090
+ await devNode(entrypoint);
2091
+ return 0;
2092
+ }
2093
+ return runNode(entrypoint);
2094
+ }
2095
+ const app = resolve8(entrypoint);
2096
+ return command === "dev" ? forward(process.execPath, ["--hot", app], { ...process.env, TARVE_DEV: process.env.TARVE_DEV ?? "1" }) : forward(process.execPath, [app]);
2097
+ }
2098
+ try {
2099
+ process.exitCode = await main();
2100
+ } catch (error) {
2101
+ console.error(`error: ${error instanceof Error ? error.message : String(error)}`);
2102
+ process.exitCode = 1;
2103
+ }
2104
+ function keygen(outDir = ".") {
2105
+ const path = resolve8(outDir, KEY_FILE);
2106
+ if (existsSync8(path))
2107
+ throw new Error(`${path} already exists; delete it to replace the key (installed apps reject updates signed with a new one).`);
2108
+ const keys = generateUpdateKeys();
2109
+ writeFileSync9(path, keys.privateKey + `
2110
+ `, { mode: 384 });
2111
+ console.log(`private key: ${path} (keep it secret and out of git)`);
2112
+ console.log(`public key: ${keys.publicKey}`);
2113
+ return 0;
290
2114
  }
291
- await main();