@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.
- package/CHANGELOG.md +126 -1
- package/README.md +121 -12
- package/dist/npm/build.js +1401 -85
- package/dist/npm/cli.js +1940 -117
- package/dist/npm/embedded-assets.js +22 -3
- package/dist/npm/index.js +5274 -975
- package/dist/npm/jsx-dev-runtime.js +1268 -0
- package/dist/npm/jsx-runtime.js +1268 -0
- package/dist/npm/native-runtime.json +3 -3
- package/dist/npm/node-build.js +1159 -0
- package/dist/npm/protocol.js +1 -1
- package/dist/npm/runtime.js +5 -5
- package/dist/npm/txiki/fetch.ts +228 -0
- package/dist/npm/txiki/intl-data.ts +7 -0
- package/dist/npm/txiki/intl.test.ts +53 -0
- package/dist/npm/txiki/intl.ts +249 -0
- package/dist/npm/txiki/prelude.ts +132 -0
- package/dist/npm/txiki/runtime.ts +6 -0
- package/dist/npm/txiki/shims/buffer.ts +112 -0
- package/dist/npm/txiki/shims/child-process.ts +151 -0
- package/dist/npm/txiki/shims/crypto.ts +30 -0
- package/dist/npm/txiki/shims/events.ts +75 -0
- package/dist/npm/txiki/shims/fs-promises.ts +77 -0
- package/dist/npm/txiki/shims/fs.ts +231 -0
- package/dist/npm/txiki/shims/module.ts +8 -0
- package/dist/npm/txiki/shims/net.ts +69 -0
- package/dist/npm/txiki/shims/os.ts +72 -0
- package/dist/npm/txiki/shims/path.ts +4 -0
- package/dist/npm/txiki/shims/timers-promises.ts +9 -0
- package/dist/npm/txiki/shims/zlib.ts +9 -0
- package/dist/npm/txiki/tjs.d.ts +58 -0
- package/dist/npm/txiki/unavailable.ts +10 -0
- package/dist/types/core/build.d.ts +24 -0
- package/dist/types/core/cli.d.ts +1 -1
- package/dist/types/core/esbuild-file-imports.d.ts +8 -0
- package/dist/types/core/jsx-compile.d.ts +7 -0
- package/dist/types/core/node-build.d.ts +7 -0
- package/dist/types/core/node-dev.d.ts +4 -0
- package/dist/types/core/node-target.d.ts +10 -0
- package/dist/types/core/package-metadata.d.ts +49 -0
- package/dist/types/core/runtime-select.d.ts +8 -0
- package/dist/types/core/src/advanced-controls.d.ts +1 -1
- package/dist/types/core/src/app/element-events.d.ts +18 -0
- package/dist/types/core/src/app/media.d.ts +15 -0
- package/dist/types/core/src/app/requests.d.ts +25 -0
- package/dist/types/core/src/app/shadow.d.ts +7 -0
- package/dist/types/core/src/app/stats.d.ts +12 -0
- package/dist/types/core/src/app/tray.d.ts +40 -0
- package/dist/types/core/src/app-metadata.d.ts +18 -0
- package/dist/types/core/src/app.d.ts +89 -2
- package/dist/types/core/src/assets.d.ts +4 -0
- package/dist/types/core/src/bridge/binding.d.ts +10 -34
- package/dist/types/core/src/bridge/index.d.ts +1 -1
- package/dist/types/core/src/canvas.d.ts +161 -0
- package/dist/types/core/src/chat-controls.d.ts +2 -1
- package/dist/types/core/src/components/button.d.ts +1 -1
- package/dist/types/core/src/components/glass.d.ts +52 -0
- package/dist/types/core/src/components/icon.d.ts +1 -1
- package/dist/types/core/src/components/image.d.ts +8 -4
- package/dist/types/core/src/components/layout.d.ts +5 -4
- package/dist/types/core/src/components/pressable.d.ts +3 -3
- package/dist/types/core/src/components/rich-content.d.ts +1 -1
- package/dist/types/core/src/components/scroll.d.ts +2 -2
- package/dist/types/core/src/components/svg.d.ts +1 -1
- package/dist/types/core/src/components/titlebar.d.ts +15 -1
- package/dist/types/core/src/components/window.d.ts +21 -1
- package/dist/types/core/src/components.d.ts +2 -0
- package/dist/types/core/src/css-shadow.d.ts +1 -1
- package/dist/types/core/src/desktop-controls.d.ts +2 -2
- package/dist/types/core/src/embedded-assets.d.ts +3 -2
- package/dist/types/core/src/extra-controls.d.ts +2 -2
- package/dist/types/core/src/form-controls.d.ts +1 -1
- package/dist/types/core/src/html-elements.d.ts +26 -0
- package/dist/types/core/src/index.d.ts +23 -11
- package/dist/types/core/src/inline-text.d.ts +25 -0
- package/dist/types/core/src/intrinsic-style.d.ts +1 -1
- package/dist/types/core/src/jsx-runtime.d.ts +182 -5
- package/dist/types/core/src/media-element.d.ts +70 -0
- package/dist/types/core/src/memo.d.ts +28 -0
- package/dist/types/core/src/motion.d.ts +1 -1
- package/dist/types/core/src/png.d.ts +29 -0
- package/dist/types/core/src/popups.d.ts +4 -3
- package/dist/types/core/src/protocol.d.ts +6 -0
- package/dist/types/core/src/reconciler/diff.d.ts +11 -0
- package/dist/types/core/src/reconciler/intrinsics.d.ts +24 -0
- package/dist/types/core/src/reconciler.d.ts +33 -10
- package/dist/types/core/src/render-scope.d.ts +8 -0
- package/dist/types/core/src/style.d.ts +1 -1
- package/dist/types/core/src/tailwind-palette.d.ts +1 -0
- package/dist/types/core/src/tailwind.d.ts +8 -0
- package/dist/types/core/src/test-renderer.d.ts +3 -1
- package/dist/types/core/src/text-search.d.ts +1 -1
- package/dist/types/core/src/theme.d.ts +10 -2
- package/dist/types/core/src/updates.d.ts +87 -0
- package/dist/types/core/src/virtual-list.d.ts +8 -2
- package/dist/types/core/txiki/fetch.d.ts +1 -0
- package/dist/types/core/txiki/intl-data.d.ts +6 -0
- package/dist/types/core/txiki/intl.d.ts +92 -0
- package/dist/types/core/txiki/prelude.d.ts +1 -0
- package/dist/types/core/txiki/runtime.d.ts +2 -0
- package/dist/types/core/txiki/shims/buffer.d.ts +37 -0
- package/dist/types/core/txiki/shims/child-process.d.ts +46 -0
- package/dist/types/core/txiki/shims/crypto.d.ts +16 -0
- package/dist/types/core/txiki/shims/events.d.ts +21 -0
- package/dist/types/core/txiki/shims/fs-promises.d.ts +41 -0
- package/dist/types/core/txiki/shims/fs.d.ts +44 -0
- package/dist/types/core/txiki/shims/module.d.ts +5 -0
- package/dist/types/core/txiki/shims/net.d.ts +22 -0
- package/dist/types/core/txiki/shims/os.d.ts +52 -0
- package/dist/types/core/txiki/shims/path.d.ts +3 -0
- package/dist/types/core/txiki/shims/timers-promises.d.ts +7 -0
- package/dist/types/core/txiki/shims/zlib.d.ts +11 -0
- package/dist/types/core/txiki/unavailable.d.ts +5 -0
- package/dist/types/core/txiki-build.d.ts +23 -0
- package/dist/types/core/updates-build.d.ts +35 -0
- package/dist/types/core/windows-executable.d.ts +16 -0
- package/dist/types/protocol/src/index.d.ts +344 -11
- package/native/linux-x64/libtarve_native.so +0 -0
- package/native/linux-x64/runtime.json +4 -4
- package/native/win32-x64/runtime.json +4 -4
- package/native/win32-x64/tarve_native.dll +0 -0
- package/package.json +13 -3
package/dist/npm/build.js
CHANGED
|
@@ -1,31 +1,405 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
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
|
+
};
|
|
8
27
|
|
|
9
|
-
// packages/core/
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
28
|
+
// packages/core/src/png.ts
|
|
29
|
+
import { deflateSync, inflateSync } from "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;
|
|
27
63
|
}
|
|
28
|
-
|
|
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
|
+
});
|
|
257
|
+
|
|
258
|
+
// packages/core/package-metadata.ts
|
|
259
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
260
|
+
import { basename, dirname, extname, join, relative, resolve } from "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
|
+
});
|
|
401
|
+
|
|
402
|
+
// packages/core/targets.ts
|
|
29
403
|
function isBuildTarget(value) {
|
|
30
404
|
return BUILD_TARGETS.includes(value);
|
|
31
405
|
}
|
|
@@ -45,34 +419,50 @@ function nativeRelativePath(target) {
|
|
|
45
419
|
const config = TARGET_CONFIGS[target];
|
|
46
420
|
return `native/${config.nativeDirectory}/${config.nativeName}`;
|
|
47
421
|
}
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
422
|
+
var BUILD_TARGETS, TARGET_CONFIGS;
|
|
423
|
+
var init_targets = __esm(() => {
|
|
424
|
+
BUILD_TARGETS = ["windows-x64", "linux-x64"];
|
|
425
|
+
TARGET_CONFIGS = {
|
|
426
|
+
"windows-x64": {
|
|
427
|
+
platform: "win32",
|
|
428
|
+
arch: "x64",
|
|
429
|
+
bunTarget: "bun-windows-x64",
|
|
430
|
+
nativeDirectory: "win32-x64",
|
|
431
|
+
nativeName: "tarve_native.dll",
|
|
432
|
+
executableSuffix: ".exe"
|
|
433
|
+
},
|
|
434
|
+
"linux-x64": {
|
|
435
|
+
platform: "linux",
|
|
436
|
+
arch: "x64",
|
|
437
|
+
bunTarget: "bun-linux-x64",
|
|
438
|
+
nativeDirectory: "linux-x64",
|
|
439
|
+
nativeName: "libtarve_native.so",
|
|
440
|
+
executableSuffix: ""
|
|
441
|
+
}
|
|
442
|
+
};
|
|
443
|
+
});
|
|
54
444
|
|
|
55
445
|
// packages/protocol/src/index.ts
|
|
56
|
-
var NATIVE_ABI_VERSION = 5;
|
|
57
|
-
var PROTOCOL_VERSION = 48;
|
|
446
|
+
var NATIVE_ABI_VERSION = 5, PROTOCOL_VERSION = 59;
|
|
58
447
|
|
|
59
448
|
// packages/core/native-runtime.ts
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
449
|
+
import { createHash } from "crypto";
|
|
450
|
+
import { existsSync as existsSync2 } from "fs";
|
|
451
|
+
import { readFile, writeFile, glob } from "fs/promises";
|
|
452
|
+
import { basename as basename2, dirname as dirname2, join as join2 } from "path";
|
|
63
453
|
async function sha256File(path) {
|
|
64
454
|
return createHash("sha256").update(await readFile(path)).digest("hex");
|
|
65
455
|
}
|
|
66
456
|
async function addGlobFiles(files, root, prefix, pattern) {
|
|
67
|
-
const directory =
|
|
68
|
-
if (!
|
|
457
|
+
const directory = join2(root, "native", prefix);
|
|
458
|
+
if (!existsSync2(directory))
|
|
69
459
|
return;
|
|
70
|
-
for await (const relative of
|
|
71
|
-
files.push(
|
|
460
|
+
for await (const relative of glob(pattern, { cwd: directory })) {
|
|
461
|
+
files.push(join2(prefix, relative).replaceAll("\\", "/"));
|
|
72
462
|
}
|
|
73
463
|
}
|
|
74
464
|
async function nativeSourceFingerprint(root) {
|
|
75
|
-
const native =
|
|
465
|
+
const native = join2(root, "native");
|
|
76
466
|
const files = ["Cargo.toml", "Cargo.lock"];
|
|
77
467
|
await addGlobFiles(files, root, "src", "**/*.rs");
|
|
78
468
|
await addGlobFiles(files, root, "vendor", "**/*.rs");
|
|
@@ -80,8 +470,8 @@ async function nativeSourceFingerprint(root) {
|
|
|
80
470
|
files.sort();
|
|
81
471
|
const hash = createHash("sha256");
|
|
82
472
|
for (const relative of files) {
|
|
83
|
-
const path =
|
|
84
|
-
if (!
|
|
473
|
+
const path = join2(native, ...relative.split("/"));
|
|
474
|
+
if (!existsSync2(path))
|
|
85
475
|
throw new Error(`Native source input is missing: ${path}`);
|
|
86
476
|
hash.update(relative);
|
|
87
477
|
hash.update("\x00");
|
|
@@ -93,8 +483,8 @@ async function nativeSourceFingerprint(root) {
|
|
|
93
483
|
}
|
|
94
484
|
async function createNativeCompatibilityManifest(root, packageVersion) {
|
|
95
485
|
const [rustProtocol, rustBridge] = await Promise.all([
|
|
96
|
-
readFile(
|
|
97
|
-
readFile(
|
|
486
|
+
readFile(join2(root, "native", "src", "protocol.rs"), "utf8"),
|
|
487
|
+
readFile(join2(root, "native", "src", "bridge.rs"), "utf8")
|
|
98
488
|
]);
|
|
99
489
|
const rustProtocolVersion = Number(rustProtocol.match(/pub const VERSION: u32 = (\d+);/)?.[1]);
|
|
100
490
|
const rustAbiVersion = Number(rustBridge.match(/pub const ABI_VERSION: u32 = (\d+);/)?.[1]);
|
|
@@ -121,7 +511,7 @@ function validateCompatibilityShape(value, path) {
|
|
|
121
511
|
}
|
|
122
512
|
}
|
|
123
513
|
async function readNativeCompatibilityManifest(path) {
|
|
124
|
-
if (!
|
|
514
|
+
if (!existsSync2(path))
|
|
125
515
|
throw new Error(`Tarve native compatibility metadata is missing: ${path}`);
|
|
126
516
|
let value;
|
|
127
517
|
try {
|
|
@@ -133,8 +523,8 @@ async function readNativeCompatibilityManifest(path) {
|
|
|
133
523
|
return value;
|
|
134
524
|
}
|
|
135
525
|
async function assertNativeRuntimeCompatible(library, target, expected) {
|
|
136
|
-
const path =
|
|
137
|
-
if (!
|
|
526
|
+
const path = join2(dirname2(library), NATIVE_RUNTIME_MANIFEST_NAME);
|
|
527
|
+
if (!existsSync2(path)) {
|
|
138
528
|
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.");
|
|
139
529
|
}
|
|
140
530
|
let value;
|
|
@@ -159,12 +549,883 @@ async function assertNativeRuntimeCompatible(library, target, expected) {
|
|
|
159
549
|
}
|
|
160
550
|
return manifest;
|
|
161
551
|
}
|
|
552
|
+
var NATIVE_RUNTIME_MANIFEST_NAME = "runtime.json", NATIVE_COMPATIBILITY_MANIFEST_NAME = "native-runtime.json", NATIVE_RUNTIME_MANIFEST_SCHEMA = 1;
|
|
553
|
+
var init_native_runtime = __esm(() => {
|
|
554
|
+
init_targets();
|
|
555
|
+
});
|
|
556
|
+
|
|
557
|
+
// packages/core/jsx-compile.ts
|
|
558
|
+
var exports_jsx_compile = {};
|
|
559
|
+
__export(exports_jsx_compile, {
|
|
560
|
+
closeJsxCompiler: () => closeJsxCompiler,
|
|
561
|
+
compileJsx: () => compileJsx
|
|
562
|
+
});
|
|
563
|
+
async function loadParser() {
|
|
564
|
+
let modules;
|
|
565
|
+
try {
|
|
566
|
+
modules = await Promise.all([import("typescript/unstable/ast"), import("typescript/unstable/ast/is")]);
|
|
567
|
+
} catch (error) {
|
|
568
|
+
throw new Error(`compileJsx needs TypeScript 7 (npm install -D typescript@7): ${error instanceof Error ? error.message : String(error)}`);
|
|
569
|
+
}
|
|
570
|
+
const [ast, is] = modules;
|
|
571
|
+
const files = new Map([[CONFIG, JSON.stringify({ compilerOptions: { jsx: "preserve", noLib: true, noResolve: true, types: [] }, files: ["app.tsx"] })]]);
|
|
572
|
+
const normalize = (path) => path.replace(/\\/g, "/").replace(/^[A-Za-z]:/, "");
|
|
573
|
+
const options = {
|
|
574
|
+
cwd: ROOT,
|
|
575
|
+
fs: {
|
|
576
|
+
readFile: (path) => files.get(normalize(path)),
|
|
577
|
+
fileExists: (path) => files.has(normalize(path)),
|
|
578
|
+
directoryExists: (path) => {
|
|
579
|
+
const p = normalize(path).replace(/\/$/, "");
|
|
580
|
+
return p === "" || ROOT.startsWith(p);
|
|
581
|
+
},
|
|
582
|
+
getAccessibleEntries: (path) => normalize(path).replace(/\/$/, "") === ROOT ? { files: ["app.tsx", "tsconfig.json"], directories: [] } : { files: [], directories: [] },
|
|
583
|
+
realpath: (path) => path
|
|
584
|
+
}
|
|
585
|
+
};
|
|
586
|
+
const request = { openProject: CONFIG, fileChanges: { invalidateAll: true } };
|
|
587
|
+
if ((process.platform === "win32" || typeof Bun === "undefined") && process.env.TARVE_TSGO_ASYNC !== "1") {
|
|
588
|
+
const sync = await import("typescript/unstable/sync");
|
|
589
|
+
const api = new sync.API(options);
|
|
590
|
+
return {
|
|
591
|
+
ast,
|
|
592
|
+
is,
|
|
593
|
+
files,
|
|
594
|
+
parse: async () => {
|
|
595
|
+
api.clearSourceFileCache();
|
|
596
|
+
const snapshot = api.updateSnapshot(request);
|
|
597
|
+
try {
|
|
598
|
+
return snapshot.getProjects()[0].program.getSourceFile(FILE);
|
|
599
|
+
} finally {
|
|
600
|
+
snapshot.dispose();
|
|
601
|
+
}
|
|
602
|
+
},
|
|
603
|
+
close: async () => api.close()
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
const asyncApi = await import("typescript/unstable/async");
|
|
607
|
+
const api = new asyncApi.API(options);
|
|
608
|
+
return {
|
|
609
|
+
ast,
|
|
610
|
+
is,
|
|
611
|
+
files,
|
|
612
|
+
parse: async () => {
|
|
613
|
+
api.clearSourceFileCache();
|
|
614
|
+
const snapshot = await api.updateSnapshot(request);
|
|
615
|
+
try {
|
|
616
|
+
return await snapshot.getProjects()[0].program.getSourceFile(FILE);
|
|
617
|
+
} finally {
|
|
618
|
+
await snapshot.dispose();
|
|
619
|
+
}
|
|
620
|
+
},
|
|
621
|
+
close: () => api.close()
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
async function closeJsxCompiler() {
|
|
625
|
+
const current = parser;
|
|
626
|
+
parser = undefined;
|
|
627
|
+
if (current)
|
|
628
|
+
await (await current).close();
|
|
629
|
+
}
|
|
630
|
+
function constant(node, ast, ts) {
|
|
631
|
+
const isConstant = (child) => constant(child, ast, ts);
|
|
632
|
+
if (ts.isParenthesizedExpression(node))
|
|
633
|
+
return isConstant(node.expression);
|
|
634
|
+
if (ts.isNumericLiteral(node) || ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node))
|
|
635
|
+
return true;
|
|
636
|
+
if (node.kind === ast.SyntaxKind.TrueKeyword || node.kind === ast.SyntaxKind.FalseKeyword || node.kind === ast.SyntaxKind.NullKeyword)
|
|
637
|
+
return true;
|
|
638
|
+
if (ts.isIdentifier(node) && node.text === "undefined")
|
|
639
|
+
return true;
|
|
640
|
+
if (ts.isPrefixUnaryExpression(node) && (node.operator === ast.SyntaxKind.MinusToken || node.operator === ast.SyntaxKind.PlusToken))
|
|
641
|
+
return ts.isNumericLiteral(node.operand);
|
|
642
|
+
if (ts.isArrayLiteralExpression(node))
|
|
643
|
+
return node.elements.every((element) => !ts.isSpreadElement(element) && isConstant(element));
|
|
644
|
+
if (ts.isObjectLiteralExpression(node)) {
|
|
645
|
+
return node.properties.every((property) => ts.isPropertyAssignment(property) && (ts.isIdentifier(property.name) || ts.isStringLiteral(property.name) || ts.isNumericLiteral(property.name)) && isConstant(property.initializer));
|
|
646
|
+
}
|
|
647
|
+
return false;
|
|
648
|
+
}
|
|
649
|
+
async function compileJsx(source) {
|
|
650
|
+
if (!/<[A-Za-z>]/.test(source))
|
|
651
|
+
return { code: source, templates: 0 };
|
|
652
|
+
const loaded = await (parser ??= loadParser());
|
|
653
|
+
const turn = queue.then(async () => {
|
|
654
|
+
loaded.files.set(FILE, source);
|
|
655
|
+
const file = await loaded.parse();
|
|
656
|
+
if (!file || file.text !== source)
|
|
657
|
+
throw new Error("compileJsx: TypeScript returned a different parse of the file");
|
|
658
|
+
return compileFile(source, file, loaded.ast, loaded.is);
|
|
659
|
+
});
|
|
660
|
+
queue = turn.catch(() => {
|
|
661
|
+
return;
|
|
662
|
+
});
|
|
663
|
+
return turn;
|
|
664
|
+
}
|
|
665
|
+
function compileFile(source, file, ast, ts) {
|
|
666
|
+
const isConstant = (node) => constant(node, ast, ts);
|
|
667
|
+
const isJsx = (node) => ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node);
|
|
668
|
+
const core = new Set;
|
|
669
|
+
let lastImport = 0;
|
|
670
|
+
for (const statement of file.statements) {
|
|
671
|
+
if (!ts.isImportDeclaration(statement))
|
|
672
|
+
continue;
|
|
673
|
+
lastImport = statement.end;
|
|
674
|
+
if (!ts.isStringLiteral(statement.moduleSpecifier) || !CORE.test(statement.moduleSpecifier.text))
|
|
675
|
+
continue;
|
|
676
|
+
const bindings = statement.importClause?.namedBindings;
|
|
677
|
+
if (bindings && ts.isNamedImports(bindings) && statement.importClause.phaseModifier !== ast.SyntaxKind.TypeKeyword) {
|
|
678
|
+
for (const element of bindings.elements)
|
|
679
|
+
if (!element.isTypeOnly)
|
|
680
|
+
core.add(element.name.text);
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
const shadowed = new Set;
|
|
684
|
+
const scan = (node) => {
|
|
685
|
+
const name = node.kind === ast.SyntaxKind.Parameter || ts.isVariableDeclaration(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) ? node.name : undefined;
|
|
686
|
+
if (name && ts.isIdentifier(name) && core.has(name.text))
|
|
687
|
+
shadowed.add(name.text);
|
|
688
|
+
node.forEachChild(scan);
|
|
689
|
+
};
|
|
690
|
+
file.forEachChild(scan);
|
|
691
|
+
for (const name of shadowed)
|
|
692
|
+
core.delete(name);
|
|
693
|
+
const pure = (node) => {
|
|
694
|
+
if (ts.isJsxFragment(node))
|
|
695
|
+
return true;
|
|
696
|
+
const tag = ts.isJsxElement(node) ? node.openingElement.tagName : node.tagName;
|
|
697
|
+
if (ts.isIdentifier(tag))
|
|
698
|
+
return /^[a-z]/.test(tag.text) || core.has(tag.text);
|
|
699
|
+
return false;
|
|
700
|
+
};
|
|
701
|
+
const text = (start, end) => source.slice(start, end);
|
|
702
|
+
const declarations = [];
|
|
703
|
+
function rewrite(start, end, root) {
|
|
704
|
+
const roots = [];
|
|
705
|
+
const find = (node) => {
|
|
706
|
+
if (node.end <= start || node.pos >= end)
|
|
707
|
+
return;
|
|
708
|
+
if (isJsx(node) && node.getStart() >= start && node.end <= end) {
|
|
709
|
+
roots.push(node);
|
|
710
|
+
return;
|
|
711
|
+
}
|
|
712
|
+
node.forEachChild(find);
|
|
713
|
+
};
|
|
714
|
+
find(root);
|
|
715
|
+
let out = "";
|
|
716
|
+
let at = start;
|
|
717
|
+
for (const node of roots) {
|
|
718
|
+
out += text(at, node.getStart()) + compileRoot(node);
|
|
719
|
+
at = node.end;
|
|
720
|
+
}
|
|
721
|
+
return out + text(at, end);
|
|
722
|
+
}
|
|
723
|
+
function compileRoot(node) {
|
|
724
|
+
if (!pure(node))
|
|
725
|
+
return impure(node);
|
|
726
|
+
const holes = [];
|
|
727
|
+
const events = [];
|
|
728
|
+
let key;
|
|
729
|
+
const hole = (expression, event = false) => {
|
|
730
|
+
const name = "h" + holes.length;
|
|
731
|
+
holes.push(expression);
|
|
732
|
+
if (event)
|
|
733
|
+
events.push(name);
|
|
734
|
+
return "p." + name;
|
|
735
|
+
};
|
|
736
|
+
let elements = 0;
|
|
737
|
+
function body(element, isRoot) {
|
|
738
|
+
if (!pure(element))
|
|
739
|
+
return "{" + hole(impure(element)) + "}";
|
|
740
|
+
elements++;
|
|
741
|
+
let out = "";
|
|
742
|
+
let at = element.getStart();
|
|
743
|
+
const end = element.end;
|
|
744
|
+
const attributes = ts.isJsxElement(element) ? element.openingElement.attributes : ts.isJsxSelfClosingElement(element) ? element.attributes : undefined;
|
|
745
|
+
const children = ts.isJsxElement(element) || ts.isJsxFragment(element) ? element.children : undefined;
|
|
746
|
+
const parts = [];
|
|
747
|
+
for (const attribute of attributes?.properties ?? []) {
|
|
748
|
+
if (ts.isJsxSpreadAttribute(attribute)) {
|
|
749
|
+
parts.push({ start: attribute.expression.getStart(), end: attribute.expression.end, replacement: hole(rewrite(attribute.expression.getStart(), attribute.expression.end, attribute.expression)) });
|
|
750
|
+
continue;
|
|
751
|
+
}
|
|
752
|
+
const name = attribute.name.getText();
|
|
753
|
+
const initializer = attribute.initializer;
|
|
754
|
+
if (isRoot && name === "key") {
|
|
755
|
+
key = initializer ? ts.isJsxExpression(initializer) && initializer.expression ? rewrite(initializer.expression.getStart(), initializer.expression.end, initializer.expression) : initializer.getText() : "true";
|
|
756
|
+
parts.push({ start: attribute.getStart(), end: attribute.end, replacement: "" });
|
|
757
|
+
continue;
|
|
758
|
+
}
|
|
759
|
+
if (!initializer)
|
|
760
|
+
continue;
|
|
761
|
+
if (ts.isJsxExpression(initializer) && initializer.expression && !isConstant(initializer.expression)) {
|
|
762
|
+
const expression = initializer.expression;
|
|
763
|
+
parts.push({ start: expression.getStart(), end: expression.end, replacement: hole(rewrite(expression.getStart(), expression.end, expression), EVENT.test(name)) });
|
|
764
|
+
} else if (isJsx(initializer)) {
|
|
765
|
+
const value = initializer;
|
|
766
|
+
parts.push({ start: value.getStart(), end: value.end, replacement: "{" + hole(compileRoot(value)) + "}" });
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
for (const child of children ?? []) {
|
|
770
|
+
if (ts.isJsxExpression(child)) {
|
|
771
|
+
if (!child.expression)
|
|
772
|
+
continue;
|
|
773
|
+
if (isConstant(child.expression) && !ts.isObjectLiteralExpression(child.expression) && !ts.isArrayLiteralExpression(child.expression))
|
|
774
|
+
continue;
|
|
775
|
+
parts.push({ start: child.expression.getStart(), end: child.expression.end, replacement: hole(rewrite(child.expression.getStart(), child.expression.end, child.expression)) });
|
|
776
|
+
} else if (isJsx(child)) {
|
|
777
|
+
parts.push({ start: child.getStart(), end: child.end, replacement: body(child, false) });
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
parts.sort((a, b) => a.start - b.start);
|
|
781
|
+
for (const part of parts) {
|
|
782
|
+
out += text(at, part.start) + part.replacement;
|
|
783
|
+
at = part.end;
|
|
784
|
+
}
|
|
785
|
+
return out + text(at, end);
|
|
786
|
+
}
|
|
787
|
+
const template = body(node, true);
|
|
788
|
+
if (elements < 2)
|
|
789
|
+
return impure(node);
|
|
790
|
+
const name = "__tarveTemplate" + declarations.length;
|
|
791
|
+
declarations.push(`const ${name} = __tarveCompileTemplate((p: any) => (${template}), ${JSON.stringify(events)});`);
|
|
792
|
+
const props = holes.map((expression, index) => `h${index}={${expression}}`);
|
|
793
|
+
if (key !== undefined)
|
|
794
|
+
props.unshift(`key={${key}}`);
|
|
795
|
+
return `<${name} ${props.join(" ")} />`;
|
|
796
|
+
}
|
|
797
|
+
function impure(node) {
|
|
798
|
+
let out = "";
|
|
799
|
+
let at = node.getStart();
|
|
800
|
+
const visit = (child) => {
|
|
801
|
+
if (isJsx(child) && child !== node) {
|
|
802
|
+
out += text(at, child.getStart()) + compileRoot(child);
|
|
803
|
+
at = child.end;
|
|
804
|
+
return;
|
|
805
|
+
}
|
|
806
|
+
if (ts.isJsxExpression(child) && child.expression) {
|
|
807
|
+
out += text(at, child.expression.getStart()) + rewrite(child.expression.getStart(), child.expression.end, child.expression);
|
|
808
|
+
at = child.expression.end;
|
|
809
|
+
return;
|
|
810
|
+
}
|
|
811
|
+
if (ts.isJsxSpreadAttribute(child)) {
|
|
812
|
+
out += text(at, child.expression.getStart()) + rewrite(child.expression.getStart(), child.expression.end, child.expression);
|
|
813
|
+
at = child.expression.end;
|
|
814
|
+
return;
|
|
815
|
+
}
|
|
816
|
+
child.forEachChild(visit);
|
|
817
|
+
};
|
|
818
|
+
node.forEachChild(visit);
|
|
819
|
+
return out + text(at, node.end);
|
|
820
|
+
}
|
|
821
|
+
const body = rewrite(lastImport, source.length, file);
|
|
822
|
+
if (!declarations.length)
|
|
823
|
+
return { code: source, templates: 0 };
|
|
824
|
+
const code = text(0, lastImport) + `
|
|
825
|
+
import { template as __tarveCompileTemplate } from "@tarve/core";
|
|
826
|
+
` + declarations.join(`
|
|
827
|
+
`) + `
|
|
828
|
+
` + body;
|
|
829
|
+
return { code, templates: declarations.length };
|
|
830
|
+
}
|
|
831
|
+
var ROOT = "/tarve-jsx", FILE, CONFIG, parser, queue, CORE, EVENT;
|
|
832
|
+
var init_jsx_compile = __esm(() => {
|
|
833
|
+
FILE = ROOT + "/app.tsx";
|
|
834
|
+
CONFIG = ROOT + "/tsconfig.json";
|
|
835
|
+
queue = Promise.resolve();
|
|
836
|
+
CORE = /^(?:@tarve\/core|tarve)(?:\/.*)?$/;
|
|
837
|
+
EVENT = /^on[A-Z]/;
|
|
838
|
+
});
|
|
839
|
+
|
|
840
|
+
// packages/core/windows-executable.ts
|
|
841
|
+
var exports_windows_executable = {};
|
|
842
|
+
__export(exports_windows_executable, {
|
|
843
|
+
brandWindowsExecutable: () => brandWindowsExecutable
|
|
844
|
+
});
|
|
845
|
+
import { readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
846
|
+
import { Data, NtExecutable, NtExecutableResource, Resource } from "resedit";
|
|
847
|
+
function numericVersion(version) {
|
|
848
|
+
const parts = version.split(/[.+-]/).slice(0, 4).map((part) => Number.parseInt(part, 10));
|
|
849
|
+
return [0, 1, 2, 3].map((index) => {
|
|
850
|
+
const value = parts[index];
|
|
851
|
+
return Number.isInteger(value) && value >= 0 && value <= 65535 ? value : 0;
|
|
852
|
+
});
|
|
853
|
+
}
|
|
854
|
+
function brandWindowsExecutable(path, info) {
|
|
855
|
+
const executable = NtExecutable.from(readFileSync2(path), { ignoreCert: true });
|
|
856
|
+
const resources = NtExecutableResource.from(executable);
|
|
857
|
+
const versionInfo = Resource.VersionInfo.fromEntries(resources.entries)[0] ?? Resource.VersionInfo.createEmpty();
|
|
858
|
+
const languages = versionInfo.getAllLanguagesForStringValues();
|
|
859
|
+
if (languages.length === 0)
|
|
860
|
+
languages.push({ lang: 1033, codepage: 1200 });
|
|
861
|
+
const [major, minor, patch, revision] = numericVersion(info.version);
|
|
862
|
+
const text = `${major}.${minor}.${patch}.${revision}`;
|
|
863
|
+
for (const language of languages) {
|
|
864
|
+
for (const key of ["CompanyName", "LegalCopyright", "LegalTrademarks", "Comments", "PrivateBuild", "SpecialBuild"]) {
|
|
865
|
+
versionInfo.removeStringValue(language, key);
|
|
866
|
+
}
|
|
867
|
+
versionInfo.setStringValues(language, {
|
|
868
|
+
FileDescription: info.description ?? `${info.name} \u2014 native Tarve application`,
|
|
869
|
+
...info.publisher ? { CompanyName: info.publisher } : {},
|
|
870
|
+
...info.copyright ? { LegalCopyright: info.copyright } : {},
|
|
871
|
+
ProductName: info.name,
|
|
872
|
+
InternalName: info.name,
|
|
873
|
+
OriginalFilename: info.filename,
|
|
874
|
+
FileVersion: text,
|
|
875
|
+
ProductVersion: text
|
|
876
|
+
});
|
|
877
|
+
}
|
|
878
|
+
versionInfo.setFileVersion(major, minor, patch, revision);
|
|
879
|
+
versionInfo.setProductVersion(major, minor, patch, revision);
|
|
880
|
+
versionInfo.outputToResourceEntries(resources.entries);
|
|
881
|
+
if (info.ico) {
|
|
882
|
+
const groups = Resource.IconGroupEntry.fromEntries(resources.entries);
|
|
883
|
+
const group = groups[0];
|
|
884
|
+
const icons = Data.IconFile.from(info.ico).icons.map((icon) => icon.data);
|
|
885
|
+
Resource.IconGroupEntry.replaceIconsForResource(resources.entries, group?.id ?? 1, group?.lang ?? 1033, icons);
|
|
886
|
+
}
|
|
887
|
+
resources.outputResource(executable);
|
|
888
|
+
const output = Buffer.from(executable.generate());
|
|
889
|
+
output.writeUInt16LE(IMAGE_SUBSYSTEM_WINDOWS_GUI, output.readUInt32LE(60) + 24 + 68);
|
|
890
|
+
writeFileSync2(path, output);
|
|
891
|
+
}
|
|
892
|
+
var IMAGE_SUBSYSTEM_WINDOWS_GUI = 2;
|
|
893
|
+
var init_windows_executable = () => {};
|
|
894
|
+
|
|
895
|
+
// packages/core/txiki-build.ts
|
|
896
|
+
import { execFileSync } from "child_process";
|
|
897
|
+
import { createHash as createHash2 } from "crypto";
|
|
898
|
+
import { chmodSync, existsSync as existsSync3, mkdtempSync, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "fs";
|
|
899
|
+
import { mkdir, rm } from "fs/promises";
|
|
900
|
+
import { builtinModules } from "module";
|
|
901
|
+
import { tmpdir } from "os";
|
|
902
|
+
import { basename as basename3, dirname as dirname3, join as join3, relative as relative2, resolve as resolve2 } from "path";
|
|
903
|
+
import { gzipSync } from "zlib";
|
|
904
|
+
import { nativePath } from "#tarve/runtime";
|
|
905
|
+
function findTxiki(explicit) {
|
|
906
|
+
const candidate = explicit ?? process.env.TARVE_TXIKI ?? (process.versions.bun ? Bun.which("tjs") : undefined) ?? "tjs";
|
|
907
|
+
try {
|
|
908
|
+
execFileSync(candidate, ["--version"], { stdio: "pipe" });
|
|
909
|
+
} catch {
|
|
910
|
+
throw new Error(`txiki.js was not found (${candidate}). Install it (winget install Saghul.TxikiJS) or set TARVE_TXIKI.`);
|
|
911
|
+
}
|
|
912
|
+
return candidate;
|
|
913
|
+
}
|
|
914
|
+
function txikiBinary(tjs) {
|
|
915
|
+
return execFileSync(tjs, ["eval", "console.log(tjs.exePath)"], { encoding: "utf8" }).trim();
|
|
916
|
+
}
|
|
917
|
+
async function buildTxiki(options) {
|
|
918
|
+
const target = options.target ?? hostBuildTarget();
|
|
919
|
+
if (!target)
|
|
920
|
+
throw new Error(`Unsupported txiki.js build host: ${process.platform}-${process.arch}`);
|
|
921
|
+
const config = targetConfig(target);
|
|
922
|
+
const tjs = findTxiki(options.txikiExecutable);
|
|
923
|
+
const host = txikiBinary(tjs);
|
|
924
|
+
const base = options.targetExecutable ? resolve2(options.targetExecutable) : host;
|
|
925
|
+
if (target !== hostBuildTarget() && !options.targetExecutable) {
|
|
926
|
+
throw new Error(`Cross-compiling for ${target} needs targetExecutable: the txiki.js ${execFileSync(tjs, ["--version"], { encoding: "utf8" }).trim()} binary for that platform.`);
|
|
927
|
+
}
|
|
928
|
+
if (!existsSync3(base))
|
|
929
|
+
throw new Error(`txiki.js executable is missing: ${base}`);
|
|
930
|
+
const { metadata, images, define } = buildMetadata(options.entrypoint, metadataOverrides(options));
|
|
931
|
+
const outfile = resolve2(options.outfile ?? `dist/${metadata.name}${config.executableSuffix}`);
|
|
932
|
+
const library = resolve2(options.nativeLibrary ?? (target === hostBuildTarget() ? nativePath() : join3(import.meta.dirname, "../../native", config.nativeDirectory, config.nativeName)));
|
|
933
|
+
if (!existsSync3(library))
|
|
934
|
+
throw new Error(`Tarve native library missing: ${library}`);
|
|
935
|
+
const temporary = mkdtempSync(join3(tmpdir(), "tarve-txiki-build-"));
|
|
936
|
+
try {
|
|
937
|
+
const root = import.meta.dirname;
|
|
938
|
+
const source = existsSync3(join3(root, "src/index.ts"));
|
|
939
|
+
const assets = [];
|
|
940
|
+
const missing = new Map;
|
|
941
|
+
const importers = new Map;
|
|
942
|
+
const runtime = {
|
|
943
|
+
name: "tarve-txiki-runtime",
|
|
944
|
+
setup(build) {
|
|
945
|
+
build.onResolve({ filter: /^tjs:/ }, (args) => ({ path: args.path, external: true }));
|
|
946
|
+
build.onResolve({ filter: /^(?:node:)?[a-z_]+(?:\/[a-z_]+)?$/ }, (args) => {
|
|
947
|
+
const name = args.path.replace(/^node:/, "");
|
|
948
|
+
if (!NODE_SHIMS[name] && !args.path.startsWith("node:") && !builtinModules.includes(name))
|
|
949
|
+
return;
|
|
950
|
+
if (!importers.has(name))
|
|
951
|
+
importers.set(name, new Set);
|
|
952
|
+
importers.get(name).add(args.importer);
|
|
953
|
+
return { path: name, namespace: "tarve-node", sideEffects: false };
|
|
954
|
+
});
|
|
955
|
+
build.onResolve({ filter: /^#tarve\/runtime$/ }, () => ({ path: join3(root, "txiki/runtime.ts") }));
|
|
956
|
+
if (source) {
|
|
957
|
+
build.onResolve({ filter: /^(?:@tarve\/core(?:-internal)?|tarve)(?:\/(?:jsx-runtime|jsx-dev-runtime))?$/ }, (args) => {
|
|
958
|
+
const entry = args.path.replace(/^(?:@tarve\/core(?:-internal)?|tarve)/, "") || "/index";
|
|
959
|
+
return { path: join3(root, "src", `${entry.slice(1)}.ts`) };
|
|
960
|
+
});
|
|
961
|
+
}
|
|
962
|
+
build.onResolve({ filter: /.*/ }, (args) => {
|
|
963
|
+
const type = args.with?.type ?? (ASSET.test(args.path) && args.kind === "import-statement" ? "file" : undefined);
|
|
964
|
+
if (type !== "file" && type !== "text")
|
|
965
|
+
return;
|
|
966
|
+
return { path: resolve2(dirname3(args.importer), args.path), namespace: `tarve-${type}` };
|
|
967
|
+
});
|
|
968
|
+
build.onLoad({ filter: /.*/, namespace: "tarve-node" }, (args) => {
|
|
969
|
+
const shim = NODE_SHIMS[args.path] && JSON.stringify(join3(root, "txiki/shims", `${NODE_SHIMS[args.path]}.ts`));
|
|
970
|
+
const placeholder = (api) => `/* @__PURE__ */ unavailable(${JSON.stringify(`${UNAVAILABLE}node:${api}`)})`;
|
|
971
|
+
return {
|
|
972
|
+
contents: [
|
|
973
|
+
`import { unavailable } from ${JSON.stringify(join3(root, "txiki/unavailable.ts"))};`,
|
|
974
|
+
...shim ? [`export * from ${shim};`, `export { default } from ${shim};`] : [`export default ${placeholder(args.path)};`],
|
|
975
|
+
...[...missing.get(args.path) ?? []].map((name) => `export const ${name} = ${placeholder(`${args.path}.${name}`)};`)
|
|
976
|
+
].join(`
|
|
977
|
+
`),
|
|
978
|
+
loader: "js",
|
|
979
|
+
resolveDir: root
|
|
980
|
+
};
|
|
981
|
+
});
|
|
982
|
+
if (options.compileJsx) {
|
|
983
|
+
build.onLoad({ filter: /\.[jt]sx$/ }, async (args) => {
|
|
984
|
+
if (/[\\/]node_modules[\\/]/.test(args.path) || args.path.startsWith(join3(root, "src")))
|
|
985
|
+
return;
|
|
986
|
+
await Promise.resolve().then(() => init_jsx_compile());
|
|
987
|
+
return { contents: (await compileJsx(readFileSync3(args.path, "utf8"))).code, loader: args.path.endsWith(".jsx") ? "jsx" : "tsx", resolveDir: dirname3(args.path) };
|
|
988
|
+
});
|
|
989
|
+
}
|
|
990
|
+
build.onLoad({ filter: /.*/, namespace: "tarve-text" }, (args) => ({ contents: readFileSync3(args.path, "utf8"), loader: "text" }));
|
|
991
|
+
build.onLoad({ filter: /.*/, namespace: "tarve-file" }, (args) => {
|
|
992
|
+
const data = readFileSync3(args.path);
|
|
993
|
+
const name = `${createHash2("sha256").update(data).digest("hex").slice(0, 12)}-${basename3(args.path)}`;
|
|
994
|
+
if (!assets.some((asset) => asset.name === name))
|
|
995
|
+
assets.push({ name, data, gzip: false });
|
|
996
|
+
return { contents: `export default globalThis.__tarveAssets[${JSON.stringify(name)}];`, loader: "js" };
|
|
997
|
+
});
|
|
998
|
+
}
|
|
999
|
+
};
|
|
1000
|
+
const entry = join3(temporary, "entry.ts");
|
|
1001
|
+
writeFileSync3(entry, [
|
|
1002
|
+
`import ${JSON.stringify(join3(root, "txiki/prelude.ts"))};`,
|
|
1003
|
+
`import ${JSON.stringify(resolve2(options.entrypoint))};`
|
|
1004
|
+
].join(`
|
|
1005
|
+
`));
|
|
1006
|
+
const bundle = join3(temporary, "app.js");
|
|
1007
|
+
const { build: esbuild } = await import("esbuild");
|
|
1008
|
+
const bundleApp = () => esbuild({
|
|
1009
|
+
entryPoints: [entry],
|
|
1010
|
+
outfile: bundle,
|
|
1011
|
+
bundle: true,
|
|
1012
|
+
platform: "neutral",
|
|
1013
|
+
mainFields: ["module", "main"],
|
|
1014
|
+
format: "esm",
|
|
1015
|
+
target: "es2023",
|
|
1016
|
+
minify: !process.env.TARVE_TXIKI_DEBUG,
|
|
1017
|
+
jsx: "automatic",
|
|
1018
|
+
jsxImportSource: "@tarve/core",
|
|
1019
|
+
logLevel: "silent",
|
|
1020
|
+
define: {
|
|
1021
|
+
...define,
|
|
1022
|
+
"process.env.NODE_ENV": JSON.stringify("production"),
|
|
1023
|
+
"import.meta.dirname": "globalThis.__tarveDirname",
|
|
1024
|
+
TARVE_TXIKI_PLATFORM: JSON.stringify(config.platform),
|
|
1025
|
+
TARVE_TXIKI_NATIVE_NAME: JSON.stringify(config.nativeName)
|
|
1026
|
+
},
|
|
1027
|
+
plugins: [runtime],
|
|
1028
|
+
metafile: !!process.env.TARVE_TXIKI_DEBUG
|
|
1029
|
+
});
|
|
1030
|
+
for (let attempt = 0;; attempt++) {
|
|
1031
|
+
try {
|
|
1032
|
+
const result = await bundleApp();
|
|
1033
|
+
if (process.env.TARVE_TXIKI_DEBUG)
|
|
1034
|
+
writeFileSync3(`${process.env.TARVE_TXIKI_DEBUG}.meta.json`, JSON.stringify(result.metafile));
|
|
1035
|
+
break;
|
|
1036
|
+
} catch (error) {
|
|
1037
|
+
const errors = error.errors ?? [];
|
|
1038
|
+
const lacking = errors.map(({ text }) => /^No matching export in "tarve-node:([^"]+)" for import "([^"]+)"$/.exec(text));
|
|
1039
|
+
if (!lacking.length || lacking.some((match) => !match) || attempt > 3)
|
|
1040
|
+
throw error;
|
|
1041
|
+
for (const match of lacking) {
|
|
1042
|
+
if (!missing.has(match[1]))
|
|
1043
|
+
missing.set(match[1], new Set);
|
|
1044
|
+
missing.get(match[1]).add(match[2]);
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
assertAvailable(readFileSync3(bundle, "utf8"), importers);
|
|
1049
|
+
if (process.env.TARVE_TXIKI_DEBUG)
|
|
1050
|
+
writeFileSync3(process.env.TARVE_TXIKI_DEBUG, readFileSync3(bundle));
|
|
1051
|
+
const compiled = join3(temporary, `compiled${config.executableSuffix}`);
|
|
1052
|
+
execFileSync(tjs, ["compile", bundle, compiled], { stdio: "pipe" });
|
|
1053
|
+
const payload = txikiPayload(readFileSync3(compiled), readFileSync3(host).byteLength);
|
|
1054
|
+
const executable = join3(temporary, `base${config.executableSuffix}`);
|
|
1055
|
+
writeFileSync3(executable, readFileSync3(base));
|
|
1056
|
+
if (config.platform === "win32") {
|
|
1057
|
+
const tarveVersion = JSON.parse(readFileSync3(resolve2(root, "../../package.json"), "utf8")).version;
|
|
1058
|
+
(await Promise.resolve().then(() => (init_windows_executable(), exports_windows_executable))).brandWindowsExecutable(executable, {
|
|
1059
|
+
name: metadata.name,
|
|
1060
|
+
version: metadata.version ?? tarveVersion,
|
|
1061
|
+
filename: basename3(outfile),
|
|
1062
|
+
description: metadata.description,
|
|
1063
|
+
publisher: metadata.publisher,
|
|
1064
|
+
copyright: metadata.copyright,
|
|
1065
|
+
ico: images?.ico
|
|
1066
|
+
});
|
|
1067
|
+
}
|
|
1068
|
+
const files = [{ name: config.nativeName, data: readFileSync3(library), gzip: true }, ...assets];
|
|
1069
|
+
await mkdir(dirname3(outfile), { recursive: true });
|
|
1070
|
+
await rm(outfile, { force: true });
|
|
1071
|
+
writeFileSync3(outfile, fuse(readFileSync3(executable), files, payload));
|
|
1072
|
+
if (config.platform !== "win32")
|
|
1073
|
+
chmodSync(outfile, 493);
|
|
1074
|
+
if (config.platform === "linux" && (metadata.icon || metadata.appId))
|
|
1075
|
+
writeLinuxDesktopEntry(outfile, metadata, images?.png);
|
|
1076
|
+
return outfile;
|
|
1077
|
+
} finally {
|
|
1078
|
+
if (options.compileJsx)
|
|
1079
|
+
await (await Promise.resolve().then(() => (init_jsx_compile(), exports_jsx_compile))).closeJsxCompiler();
|
|
1080
|
+
await rm(temporary, { recursive: true, force: true });
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
function assertAvailable(bundle, importers = new Map) {
|
|
1084
|
+
const apis = [...new Set([...bundle.matchAll(new RegExp(`${UNAVAILABLE}node:([\\w/.-]+)`, "g"))].map((match) => match[1]))].sort();
|
|
1085
|
+
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();
|
|
1086
|
+
if (!apis.length && !bun.length)
|
|
1087
|
+
return;
|
|
1088
|
+
const lines = apis.map((api) => {
|
|
1089
|
+
const [module, name] = api.split(".");
|
|
1090
|
+
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("\\", "/"));
|
|
1091
|
+
return ` node:${api}${users.length ? ` (imported by ${users.slice(0, 3).join(", ")}${users.length > 3 ? ", \u2026" : ""})` : ""}`;
|
|
1092
|
+
});
|
|
1093
|
+
throw new Error([
|
|
1094
|
+
"This app reaches APIs the txiki.js runtime does not provide:",
|
|
1095
|
+
...lines,
|
|
1096
|
+
...bun.map((api) => ` ${api} (the Bun global; guard it with typeof Bun !== "undefined")`),
|
|
1097
|
+
"Remove those calls from code the app can run, or build with --runtime bun or --runtime node."
|
|
1098
|
+
].join(`
|
|
1099
|
+
`));
|
|
1100
|
+
}
|
|
1101
|
+
function txikiPayload(compiled, hostSize) {
|
|
1102
|
+
const trailer = compiled.subarray(compiled.length - 12);
|
|
1103
|
+
const offset = new DataView(trailer.buffer, trailer.byteOffset, 12).getUint32(8, true);
|
|
1104
|
+
if (new TextDecoder().decode(trailer.subarray(0, 8)) !== TXIKI_MAGIC || offset !== hostSize) {
|
|
1105
|
+
throw new Error("Unrecognized `tjs compile` output; this txiki.js version is not supported.");
|
|
1106
|
+
}
|
|
1107
|
+
return compiled.subarray(offset, compiled.length - 12);
|
|
1108
|
+
}
|
|
1109
|
+
function fuse(executable, files, payload) {
|
|
1110
|
+
const parts = [executable];
|
|
1111
|
+
const index = [];
|
|
1112
|
+
let offset = executable.length;
|
|
1113
|
+
for (const file of files) {
|
|
1114
|
+
const stored = file.gzip ? gzipSync(file.data, { level: 9 }) : file.data;
|
|
1115
|
+
index.push({ name: file.name, offset, length: stored.length, size: file.data.length, sha256: createHash2("sha256").update(file.data).digest("hex"), gzip: file.gzip });
|
|
1116
|
+
parts.push(stored);
|
|
1117
|
+
offset += stored.length;
|
|
1118
|
+
}
|
|
1119
|
+
const json = new TextEncoder().encode(JSON.stringify(index));
|
|
1120
|
+
const header = new Uint8Array(16);
|
|
1121
|
+
new DataView(header.buffer).setUint32(0, json.length, true);
|
|
1122
|
+
header.set(new TextEncoder().encode(BLOB_MAGIC), 8);
|
|
1123
|
+
parts.push(json, header);
|
|
1124
|
+
const payloadOffset = offset + json.length + header.length;
|
|
1125
|
+
const trailer = new Uint8Array(12);
|
|
1126
|
+
trailer.set(new TextEncoder().encode(TXIKI_MAGIC));
|
|
1127
|
+
new DataView(trailer.buffer).setUint32(8, payloadOffset, true);
|
|
1128
|
+
parts.push(payload, trailer);
|
|
1129
|
+
const out = new Uint8Array(parts.reduce((size, part) => size + part.length, 0));
|
|
1130
|
+
let position = 0;
|
|
1131
|
+
for (const part of parts) {
|
|
1132
|
+
out.set(part, position);
|
|
1133
|
+
position += part.length;
|
|
1134
|
+
}
|
|
1135
|
+
return out;
|
|
1136
|
+
}
|
|
1137
|
+
var TXIKI_MAGIC = "tx1k1.js", BLOB_MAGIC = "TARVEBLB", NODE_SHIMS, ASSET, UNAVAILABLE = "tarve-txiki-unavailable:";
|
|
1138
|
+
var init_txiki_build = __esm(() => {
|
|
1139
|
+
init_build();
|
|
1140
|
+
init_package_metadata();
|
|
1141
|
+
init_targets();
|
|
1142
|
+
NODE_SHIMS = {
|
|
1143
|
+
fs: "fs",
|
|
1144
|
+
"fs/promises": "fs-promises",
|
|
1145
|
+
path: "path",
|
|
1146
|
+
os: "os",
|
|
1147
|
+
crypto: "crypto",
|
|
1148
|
+
net: "net",
|
|
1149
|
+
module: "module",
|
|
1150
|
+
zlib: "zlib",
|
|
1151
|
+
events: "events",
|
|
1152
|
+
child_process: "child-process",
|
|
1153
|
+
"timers/promises": "timers-promises"
|
|
1154
|
+
};
|
|
1155
|
+
ASSET = /\.(?:png|jpe?g|webp|gif|svg|ico|ttf|otf|woff2?)$/i;
|
|
1156
|
+
});
|
|
1157
|
+
|
|
1158
|
+
// packages/core/esbuild-file-imports.ts
|
|
1159
|
+
import { readFileSync as readFileSync4 } from "fs";
|
|
1160
|
+
import { dirname as dirname4, resolve as resolve3 } from "path";
|
|
1161
|
+
var ASSET2, fileImportAttributes;
|
|
1162
|
+
var init_esbuild_file_imports = __esm(() => {
|
|
1163
|
+
ASSET2 = /\.(?:png|jpe?g|webp|gif|svg)$/i;
|
|
1164
|
+
fileImportAttributes = {
|
|
1165
|
+
name: "tarve-file-import-attributes",
|
|
1166
|
+
setup(build) {
|
|
1167
|
+
build.onResolve({ filter: /.*/ }, (args) => {
|
|
1168
|
+
if (args.namespace === "tarve-file") {
|
|
1169
|
+
return args.path.startsWith("node:") ? { path: args.path, external: true } : { path: args.path, namespace: "tarve-file-copy" };
|
|
1170
|
+
}
|
|
1171
|
+
const type = args.with?.type ?? (ASSET2.test(args.path) && args.kind === "import-statement" ? "file" : undefined);
|
|
1172
|
+
if (type !== "file" && type !== "text")
|
|
1173
|
+
return;
|
|
1174
|
+
return { path: resolve3(dirname4(args.importer), args.path), namespace: `tarve-${type}` };
|
|
1175
|
+
});
|
|
1176
|
+
build.onLoad({ filter: /.*/, namespace: "tarve-text" }, (args) => ({ contents: readFileSync4(args.path, "utf8"), loader: "text" }));
|
|
1177
|
+
build.onLoad({ filter: /.*/, namespace: "tarve-file" }, (args) => ({
|
|
1178
|
+
contents: [
|
|
1179
|
+
`import relative from ${JSON.stringify(args.path)};`,
|
|
1180
|
+
`import { join } from "node:path";`,
|
|
1181
|
+
`export default join(import.meta.dirname, relative);`
|
|
1182
|
+
].join(`
|
|
1183
|
+
`),
|
|
1184
|
+
loader: "js",
|
|
1185
|
+
resolveDir: dirname4(args.path)
|
|
1186
|
+
}));
|
|
1187
|
+
build.onLoad({ filter: /.*/, namespace: "tarve-file-copy" }, (args) => ({
|
|
1188
|
+
contents: readFileSync4(args.path),
|
|
1189
|
+
loader: "file"
|
|
1190
|
+
}));
|
|
1191
|
+
}
|
|
1192
|
+
};
|
|
1193
|
+
});
|
|
1194
|
+
|
|
1195
|
+
// packages/core/node-target.ts
|
|
1196
|
+
import { createHash as createHash3, randomUUID } from "crypto";
|
|
1197
|
+
import { chmodSync as chmodSync2, existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync5, renameSync, rmSync, writeFileSync as writeFileSync4 } from "fs";
|
|
1198
|
+
import { homedir } from "os";
|
|
1199
|
+
import { join as join4 } from "path";
|
|
1200
|
+
import { gunzipSync } from "zlib";
|
|
1201
|
+
function distribution(target, version) {
|
|
1202
|
+
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" };
|
|
1203
|
+
}
|
|
1204
|
+
function cacheRoot() {
|
|
1205
|
+
if (process.env.TARVE_CACHE_DIR)
|
|
1206
|
+
return process.env.TARVE_CACHE_DIR;
|
|
1207
|
+
if (process.platform === "win32")
|
|
1208
|
+
return join4(process.env.LOCALAPPDATA ?? join4(homedir(), "AppData", "Local"), "tarve", "cache");
|
|
1209
|
+
return join4(process.env.XDG_CACHE_HOME ?? join4(homedir(), ".cache"), "tarve");
|
|
1210
|
+
}
|
|
1211
|
+
function mirror() {
|
|
1212
|
+
return (process.env.NODEJS_ORG_MIRROR ?? "https://nodejs.org/dist").replace(/\/+$/, "");
|
|
1213
|
+
}
|
|
1214
|
+
async function download(url) {
|
|
1215
|
+
const response = await fetch(url);
|
|
1216
|
+
if (!response.ok)
|
|
1217
|
+
throw new Error(`Could not download ${url}: HTTP ${response.status}`);
|
|
1218
|
+
return Buffer.from(await response.arrayBuffer());
|
|
1219
|
+
}
|
|
1220
|
+
function extractTarMember(archive, member) {
|
|
1221
|
+
let offset = 0;
|
|
1222
|
+
let longName;
|
|
1223
|
+
while (offset + 512 <= archive.length) {
|
|
1224
|
+
const header = archive.subarray(offset, offset + 512);
|
|
1225
|
+
if (header.every((byte) => byte === 0))
|
|
1226
|
+
break;
|
|
1227
|
+
const field = (start, length) => header.toString("utf8", start, start + length).replace(/\0.*$/s, "");
|
|
1228
|
+
const size = Number.parseInt(field(124, 12).trim() || "0", 8);
|
|
1229
|
+
const type = field(156, 1) || "0";
|
|
1230
|
+
const prefix = field(345, 155);
|
|
1231
|
+
const name = longName ?? (prefix ? `${prefix}/${field(0, 100)}` : field(0, 100));
|
|
1232
|
+
const body = archive.subarray(offset + 512, offset + 512 + size);
|
|
1233
|
+
longName = undefined;
|
|
1234
|
+
if (type === "L")
|
|
1235
|
+
longName = body.toString("utf8").replace(/\0.*$/s, "");
|
|
1236
|
+
else if (type === "x")
|
|
1237
|
+
longName = /\d+ path=([^\n]*)\n/.exec(body.toString("utf8"))?.[1];
|
|
1238
|
+
else if ((type === "0" || type === "\x00") && name.replace(/^\.\//, "") === member)
|
|
1239
|
+
return Buffer.from(body);
|
|
1240
|
+
offset += 512 + Math.ceil(size / 512) * 512;
|
|
1241
|
+
}
|
|
1242
|
+
throw new Error(`${member} not found in the Node.js archive`);
|
|
1243
|
+
}
|
|
1244
|
+
function assertNodeVersion(executable, version) {
|
|
1245
|
+
if (!readFileSync5(executable).includes(`node-v${version}`)) {
|
|
1246
|
+
throw new Error(`${executable} is not Node.js v${version}; the target executable must match the Node.js that builds the app`);
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
async function targetNodeExecutable(target, version) {
|
|
1250
|
+
const { file, member, executable } = distribution(target, version);
|
|
1251
|
+
const directory = join4(cacheRoot(), "node", `v${version}`, target);
|
|
1252
|
+
const path = join4(directory, executable);
|
|
1253
|
+
if (existsSync4(path))
|
|
1254
|
+
return path;
|
|
1255
|
+
const base = `${mirror()}/v${version}`;
|
|
1256
|
+
const sums = (await download(`${base}/SHASUMS256.txt`)).toString("utf8");
|
|
1257
|
+
const expected = sums.split(/\r?\n/).find((line) => line.endsWith(` ${file}`))?.split(/\s+/)[0];
|
|
1258
|
+
if (!expected)
|
|
1259
|
+
throw new Error(`${file} is not listed in the Node.js v${version} SHASUMS256.txt`);
|
|
1260
|
+
const payload = await download(`${base}/${file}`);
|
|
1261
|
+
const actual = createHash3("sha256").update(payload).digest("hex");
|
|
1262
|
+
if (actual !== expected)
|
|
1263
|
+
throw new Error(`Checksum mismatch for ${file}: expected ${expected}, got ${actual}`);
|
|
1264
|
+
const binary = member ? extractTarMember(gunzipSync(payload), member) : payload;
|
|
1265
|
+
mkdirSync2(directory, { recursive: true });
|
|
1266
|
+
const temporary = join4(directory, `${executable}.${randomUUID()}.tmp`);
|
|
1267
|
+
try {
|
|
1268
|
+
writeFileSync4(temporary, binary, { mode: 493 });
|
|
1269
|
+
try {
|
|
1270
|
+
renameSync(temporary, path);
|
|
1271
|
+
} catch (error) {
|
|
1272
|
+
if (!existsSync4(path))
|
|
1273
|
+
throw error;
|
|
1274
|
+
}
|
|
1275
|
+
} finally {
|
|
1276
|
+
rmSync(temporary, { force: true });
|
|
1277
|
+
}
|
|
1278
|
+
if (process.platform !== "win32")
|
|
1279
|
+
chmodSync2(path, 493);
|
|
1280
|
+
return path;
|
|
1281
|
+
}
|
|
1282
|
+
var init_node_target = () => {};
|
|
1283
|
+
|
|
1284
|
+
// packages/core/node-build.ts
|
|
1285
|
+
import { execFileSync as execFileSync2 } from "child_process";
|
|
1286
|
+
import { existsSync as existsSync5, mkdtempSync as mkdtempSync2, writeFileSync as writeFileSync5, readFileSync as readFileSync6 } from "fs";
|
|
1287
|
+
import { mkdir as mkdir2, rm as rm2 } from "fs/promises";
|
|
1288
|
+
import { tmpdir as tmpdir2 } from "os";
|
|
1289
|
+
import { basename as basename4, dirname as dirname5, join as join5, relative as relative3, resolve as resolve4 } from "path";
|
|
1290
|
+
import { nativePath as nativePath2 } from "#tarve/runtime";
|
|
1291
|
+
async function buildNode(options) {
|
|
1292
|
+
const target = options.target ?? hostBuildTarget();
|
|
1293
|
+
if (!target)
|
|
1294
|
+
throw new Error(`Unsupported Node.js build host: ${process.platform}-${process.arch}`);
|
|
1295
|
+
const config = targetConfig(target);
|
|
1296
|
+
const node = options.nodeExecutable ?? (process.versions.bun ? Bun.which("node") ?? "node" : process.execPath);
|
|
1297
|
+
const version = execFileSync2(node, ["--version"], { encoding: "utf8" }).trim();
|
|
1298
|
+
const match = /^v(\d+)\.(\d+)\./.exec(version);
|
|
1299
|
+
if (!match || Number(match[1]) < 26 || Number(match[1]) === 26 && Number(match[2]) < 10) {
|
|
1300
|
+
throw new Error(`Node.js 26.10+ is required for node:ffi inside a SEA (found ${version})`);
|
|
1301
|
+
}
|
|
1302
|
+
const { metadata, images, define } = buildMetadata(options.entrypoint, metadataOverrides(options));
|
|
1303
|
+
const outfile = resolve4(options.outfile ?? `dist/${metadata.name}${config.executableSuffix}`);
|
|
1304
|
+
let executable;
|
|
1305
|
+
if (options.targetExecutable) {
|
|
1306
|
+
executable = resolve4(options.targetExecutable);
|
|
1307
|
+
if (!existsSync5(executable))
|
|
1308
|
+
throw new Error(`Target Node.js executable is missing: ${executable}`);
|
|
1309
|
+
assertNodeVersion(executable, version.slice(1));
|
|
1310
|
+
}
|
|
1311
|
+
const library = resolve4(options.nativeLibrary ?? (target === hostBuildTarget() ? nativePath2() : join5(import.meta.dirname, "../../native", config.nativeDirectory, config.nativeName)));
|
|
1312
|
+
if (!existsSync5(library))
|
|
1313
|
+
throw new Error(`Tarve native library missing: ${library}`);
|
|
1314
|
+
const temporary = mkdtempSync2(join5(tmpdir2(), "tarve-node-build-"));
|
|
1315
|
+
try {
|
|
1316
|
+
const root = import.meta.dirname;
|
|
1317
|
+
const source = existsSync5(join5(root, "src/index.ts"));
|
|
1318
|
+
if (!options.nativeLibrary && (!source || target !== hostBuildTarget())) {
|
|
1319
|
+
const expected = source ? await createNativeCompatibilityManifest(resolve4(root, "../.."), JSON.parse(readFileSync6(resolve4(root, "../../package.json"), "utf8")).version) : await readNativeCompatibilityManifest(join5(root, NATIVE_COMPATIBILITY_MANIFEST_NAME));
|
|
1320
|
+
await assertNativeRuntimeCompatible(library, target, expected);
|
|
1321
|
+
}
|
|
1322
|
+
if (!executable && target !== hostBuildTarget()) {
|
|
1323
|
+
executable = await targetNodeExecutable(target, version.slice(1));
|
|
1324
|
+
}
|
|
1325
|
+
const { build: bundle } = await import("esbuild");
|
|
1326
|
+
const result = await bundle({
|
|
1327
|
+
entryPoints: [resolve4(options.entrypoint)],
|
|
1328
|
+
outfile: join5(temporary, "app.mjs"),
|
|
1329
|
+
bundle: true,
|
|
1330
|
+
platform: "node",
|
|
1331
|
+
format: "esm",
|
|
1332
|
+
target: "node26",
|
|
1333
|
+
jsx: "automatic",
|
|
1334
|
+
jsxImportSource: "@tarve/core",
|
|
1335
|
+
loader: { ".png": "file", ".jpg": "file", ".jpeg": "file", ".webp": "file", ".gif": "file", ".svg": "file" },
|
|
1336
|
+
metafile: true,
|
|
1337
|
+
define,
|
|
1338
|
+
external: ["esbuild"],
|
|
1339
|
+
plugins: [fileImportAttributes, {
|
|
1340
|
+
name: "tarve-node-runtime",
|
|
1341
|
+
setup(build) {
|
|
1342
|
+
if (options.compileJsx) {
|
|
1343
|
+
build.onLoad({ filter: /\.[jt]sx$/ }, async (args) => {
|
|
1344
|
+
if (/[\\/]node_modules[\\/]/.test(args.path) || args.path.startsWith(join5(root, "src")))
|
|
1345
|
+
return;
|
|
1346
|
+
await Promise.resolve().then(() => init_jsx_compile());
|
|
1347
|
+
return { contents: (await compileJsx(readFileSync6(args.path, "utf8"))).code, loader: args.path.endsWith(".jsx") ? "jsx" : "tsx", resolveDir: dirname5(args.path) };
|
|
1348
|
+
});
|
|
1349
|
+
}
|
|
1350
|
+
if (source) {
|
|
1351
|
+
build.onResolve({ filter: /^@tarve\/core(?:\/(?:jsx-runtime|jsx-dev-runtime))?$/ }, (args) => {
|
|
1352
|
+
const entry = args.path.slice("@tarve/core".length) || "/index";
|
|
1353
|
+
return { path: join5(root, "src", `${entry.slice(1)}.ts`) };
|
|
1354
|
+
});
|
|
1355
|
+
}
|
|
1356
|
+
build.onResolve({ filter: /^#tarve\/runtime$/ }, () => ({ path: "native-runtime", namespace: "tarve-node" }));
|
|
1357
|
+
build.onLoad({ filter: /.*/, namespace: "tarve-node" }, () => ({
|
|
1358
|
+
contents: `import { join } from "node:path"; export function nativePath() { return join(import.meta.dirname, ${JSON.stringify(config.nativeName)}); }`,
|
|
1359
|
+
loader: "js"
|
|
1360
|
+
}));
|
|
1361
|
+
}
|
|
1362
|
+
}]
|
|
1363
|
+
});
|
|
1364
|
+
const assets = { [config.nativeName]: seaPath(library) };
|
|
1365
|
+
for (const [path, output] of Object.entries(result.metafile.outputs)) {
|
|
1366
|
+
if (!output.entryPoint)
|
|
1367
|
+
assets[relative3(temporary, resolve4(path)).replaceAll("\\", "/")] = seaPath(resolve4(path));
|
|
1368
|
+
}
|
|
1369
|
+
const sea = join5(temporary, "sea.json");
|
|
1370
|
+
writeFileSync5(sea, JSON.stringify({
|
|
1371
|
+
main: seaPath(join5(temporary, "app.mjs")),
|
|
1372
|
+
mainFormat: "module",
|
|
1373
|
+
output: seaPath(outfile),
|
|
1374
|
+
...executable ? { executable: seaPath(executable) } : {},
|
|
1375
|
+
useVfs: true,
|
|
1376
|
+
useCodeCache: false,
|
|
1377
|
+
useSnapshot: false,
|
|
1378
|
+
assets,
|
|
1379
|
+
execArgv: ["--disable-warning=ExperimentalWarning"],
|
|
1380
|
+
execArgvExtension: "env"
|
|
1381
|
+
}));
|
|
1382
|
+
await mkdir2(dirname5(outfile), { recursive: true });
|
|
1383
|
+
await rm2(outfile, { force: true });
|
|
1384
|
+
execFileSync2(node, ["--build-sea", sea], { stdio: "pipe" });
|
|
1385
|
+
if (config.platform === "win32") {
|
|
1386
|
+
const tarveVersion = JSON.parse(readFileSync6(resolve4(root, "../../package.json"), "utf8")).version;
|
|
1387
|
+
(await Promise.resolve().then(() => (init_windows_executable(), exports_windows_executable))).brandWindowsExecutable(outfile, {
|
|
1388
|
+
name: metadata.name,
|
|
1389
|
+
version: metadata.version ?? tarveVersion,
|
|
1390
|
+
filename: basename4(outfile),
|
|
1391
|
+
description: metadata.description,
|
|
1392
|
+
publisher: metadata.publisher,
|
|
1393
|
+
copyright: metadata.copyright,
|
|
1394
|
+
ico: images?.ico
|
|
1395
|
+
});
|
|
1396
|
+
}
|
|
1397
|
+
if (config.platform === "linux" && (metadata.icon || metadata.appId))
|
|
1398
|
+
writeLinuxDesktopEntry(outfile, metadata, images?.png);
|
|
1399
|
+
return outfile;
|
|
1400
|
+
} finally {
|
|
1401
|
+
if (options.compileJsx)
|
|
1402
|
+
await (await Promise.resolve().then(() => (init_jsx_compile(), exports_jsx_compile))).closeJsxCompiler();
|
|
1403
|
+
await rm2(temporary, { recursive: true, force: true });
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
function seaPath(path) {
|
|
1407
|
+
return path.replaceAll("\\", "/");
|
|
1408
|
+
}
|
|
1409
|
+
var init_node_build = __esm(() => {
|
|
1410
|
+
init_esbuild_file_imports();
|
|
1411
|
+
init_targets();
|
|
1412
|
+
init_build();
|
|
1413
|
+
init_package_metadata();
|
|
1414
|
+
init_native_runtime();
|
|
1415
|
+
init_node_target();
|
|
1416
|
+
});
|
|
162
1417
|
|
|
163
1418
|
// packages/core/build.ts
|
|
1419
|
+
import { existsSync as existsSync6, mkdtempSync as mkdtempSync3, writeFileSync as writeFileSync6 } from "fs";
|
|
1420
|
+
import { mkdir as mkdir3, rm as rm3 } from "fs/promises";
|
|
1421
|
+
import { tmpdir as tmpdir3 } from "os";
|
|
1422
|
+
import { dirname as dirname6, join as join6, resolve as resolve5 } from "path";
|
|
1423
|
+
import { fileURLToPath } from "url";
|
|
1424
|
+
import { nativePath as nativePath3 } from "#tarve/runtime";
|
|
164
1425
|
function resolveNativeLibrary(target, override) {
|
|
165
1426
|
if (override) {
|
|
166
|
-
const path =
|
|
167
|
-
if (!
|
|
1427
|
+
const path = resolve5(override);
|
|
1428
|
+
if (!existsSync6(path))
|
|
168
1429
|
throw new Error(`Tarve native library does not exist: ${path}`);
|
|
169
1430
|
return path;
|
|
170
1431
|
}
|
|
@@ -172,37 +1433,46 @@ function resolveNativeLibrary(target, override) {
|
|
|
172
1433
|
const hostTarget = hostBuildTarget();
|
|
173
1434
|
if (hostTarget === target) {
|
|
174
1435
|
try {
|
|
175
|
-
return
|
|
1436
|
+
return nativePath3();
|
|
176
1437
|
} catch {}
|
|
177
1438
|
}
|
|
178
1439
|
const candidates = [
|
|
179
|
-
|
|
180
|
-
|
|
1440
|
+
join6(import.meta.dir, config.nativeName),
|
|
1441
|
+
resolve5(import.meta.dir, "../../native", config.nativeDirectory, config.nativeName)
|
|
181
1442
|
];
|
|
182
|
-
const found = candidates.find(
|
|
1443
|
+
const found = candidates.find(existsSync6);
|
|
183
1444
|
if (found)
|
|
184
1445
|
return found;
|
|
185
1446
|
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.");
|
|
186
1447
|
}
|
|
187
1448
|
async function build(options) {
|
|
1449
|
+
if (options.runtime === "txiki") {
|
|
1450
|
+
await Promise.resolve().then(() => init_txiki_build());
|
|
1451
|
+
return buildTxiki(options);
|
|
1452
|
+
}
|
|
1453
|
+
if (options.runtime === "node") {
|
|
1454
|
+
await Promise.resolve().then(() => init_node_build());
|
|
1455
|
+
return buildNode(options);
|
|
1456
|
+
}
|
|
188
1457
|
const target = options.target ?? hostBuildTarget();
|
|
189
1458
|
if (!target)
|
|
190
1459
|
throw new Error(`Tarve executable distribution is not supported for ${process.platform}-${process.arch}. Pass an explicit supported target when cross-compiling.`);
|
|
191
1460
|
if (!isBuildTarget(target))
|
|
192
1461
|
throw new TypeError(`Unsupported Tarve build target: ${String(target)}. Expected ${BUILD_TARGETS.join(" or ")}.`);
|
|
193
1462
|
const config = targetConfig(target);
|
|
194
|
-
const entrypoint =
|
|
195
|
-
const packageMetadata = await Bun.file(
|
|
1463
|
+
const entrypoint = resolve5(options.entrypoint);
|
|
1464
|
+
const packageMetadata = await Bun.file(resolve5(import.meta.dir, "../../package.json")).json();
|
|
196
1465
|
if (typeof packageMetadata.version !== "string" || packageMetadata.version.length === 0) {
|
|
197
1466
|
throw new Error("Tarve package version is missing.");
|
|
198
1467
|
}
|
|
199
|
-
const
|
|
200
|
-
const
|
|
1468
|
+
const { metadata, images, define } = buildMetadata(entrypoint, metadataOverrides(options));
|
|
1469
|
+
const name = metadata.name;
|
|
1470
|
+
const outfile = resolve5(options.outfile ?? `dist/${name}${config.executableSuffix}`);
|
|
201
1471
|
const library = resolveNativeLibrary(target, options.nativeLibrary);
|
|
202
1472
|
const assetsModule = fileURLToPath(import.meta.resolve("#tarve/assets"));
|
|
203
|
-
const sourceDirectory =
|
|
204
|
-
const repositorySource =
|
|
205
|
-
const expectedCompatibility = repositorySource ? await createNativeCompatibilityManifest(
|
|
1473
|
+
const sourceDirectory = join6(import.meta.dir, "src");
|
|
1474
|
+
const repositorySource = existsSync6(join6(sourceDirectory, "index.ts"));
|
|
1475
|
+
const expectedCompatibility = repositorySource ? await createNativeCompatibilityManifest(resolve5(import.meta.dir, "../.."), packageMetadata.version) : await readNativeCompatibilityManifest(join6(import.meta.dir, NATIVE_COMPATIBILITY_MANIFEST_NAME));
|
|
206
1476
|
const requireRuntimeManifest = target !== hostBuildTarget() || !options.nativeLibrary && !repositorySource;
|
|
207
1477
|
if (requireRuntimeManifest) {
|
|
208
1478
|
await assertNativeRuntimeCompatible(library, target, expectedCompatibility);
|
|
@@ -212,53 +1482,99 @@ async function build(options) {
|
|
|
212
1482
|
sha256: new Bun.CryptoHasher("sha256").update(libraryBytes).digest("hex"),
|
|
213
1483
|
size: libraryBytes.byteLength
|
|
214
1484
|
};
|
|
1485
|
+
const packDirectory = mkdtempSync3(join6(tmpdir3(), "tarve-native-"));
|
|
1486
|
+
const packedLibrary = join6(packDirectory, `${config.nativeName}.zst`);
|
|
1487
|
+
writeFileSync6(packedLibrary, Bun.zstdCompressSync(libraryBytes, { level: NATIVE_ZSTD_LEVEL }));
|
|
215
1488
|
const runtime = {
|
|
216
1489
|
name: "tarve-native-runtime",
|
|
217
1490
|
setup(builder) {
|
|
218
1491
|
if (repositorySource) {
|
|
219
|
-
builder.onResolve({ filter: /^tarve$/ }, () => ({ path:
|
|
220
|
-
builder.onResolve({ filter: /^tarve\/jsx-runtime$/ }, () => ({ path:
|
|
221
|
-
builder.onResolve({ filter: /^tarve\/jsx-dev-runtime$/ }, () => ({ path:
|
|
1492
|
+
builder.onResolve({ filter: /^tarve$/ }, () => ({ path: join6(sourceDirectory, "index.ts") }));
|
|
1493
|
+
builder.onResolve({ filter: /^tarve\/jsx-runtime$/ }, () => ({ path: join6(sourceDirectory, "jsx-runtime.ts") }));
|
|
1494
|
+
builder.onResolve({ filter: /^tarve\/jsx-dev-runtime$/ }, () => ({ path: join6(sourceDirectory, "jsx-dev-runtime.ts") }));
|
|
1495
|
+
}
|
|
1496
|
+
if (options.compileJsx) {
|
|
1497
|
+
builder.onLoad({ filter: /\.[jt]sx$/ }, async (args) => {
|
|
1498
|
+
if (/[\\/]node_modules[\\/]/.test(args.path) || args.path.startsWith(join6(import.meta.dir, "src")))
|
|
1499
|
+
return;
|
|
1500
|
+
await Promise.resolve().then(() => init_jsx_compile());
|
|
1501
|
+
return { contents: (await compileJsx(await Bun.file(args.path).text())).code, loader: args.path.endsWith(".jsx") ? "jsx" : "tsx" };
|
|
1502
|
+
});
|
|
222
1503
|
}
|
|
223
1504
|
builder.onResolve({ filter: /^#tarve\/runtime$/ }, () => ({ path: "runtime", namespace: "tarve" }));
|
|
224
1505
|
builder.onLoad({ filter: /^runtime$/, namespace: "tarve" }, () => ({
|
|
225
1506
|
loader: "ts",
|
|
226
1507
|
contents: [
|
|
227
|
-
`import library from ${JSON.stringify(
|
|
1508
|
+
`import library from ${JSON.stringify(packedLibrary)} with { type: "file" };`,
|
|
228
1509
|
`import { materializeAsset } from ${JSON.stringify(assetsModule)};`,
|
|
229
1510
|
`const digest = ${JSON.stringify(libraryDigest)};`,
|
|
230
|
-
`export function nativePath() { return materializeAsset(library, ${JSON.stringify(config.nativeName)}, digest); }`
|
|
1511
|
+
`export function nativePath() { return materializeAsset(library, ${JSON.stringify(config.nativeName)}, digest, "zstd"); }`
|
|
231
1512
|
].join(`
|
|
232
1513
|
`)
|
|
233
1514
|
}));
|
|
234
1515
|
}
|
|
235
1516
|
};
|
|
236
|
-
await
|
|
237
|
-
const
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
target:
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
1517
|
+
await mkdir3(dirname6(outfile), { recursive: true });
|
|
1518
|
+
const iconDirectory = images && config.platform === "win32" ? mkdtempSync3(join6(tmpdir3(), "tarve-icon-")) : undefined;
|
|
1519
|
+
const icoPath = iconDirectory ? join6(iconDirectory, "app.ico") : undefined;
|
|
1520
|
+
if (icoPath)
|
|
1521
|
+
writeFileSync6(icoPath, images.ico);
|
|
1522
|
+
try {
|
|
1523
|
+
const result = await Bun.build({
|
|
1524
|
+
entrypoints: [entrypoint],
|
|
1525
|
+
target: "bun",
|
|
1526
|
+
plugins: [runtime],
|
|
1527
|
+
define: { "process.env.NODE_ENV": JSON.stringify("production"), ...define },
|
|
1528
|
+
minify: true,
|
|
1529
|
+
compile: {
|
|
1530
|
+
target: config.bunTarget,
|
|
1531
|
+
outfile,
|
|
1532
|
+
autoloadDotenv: false,
|
|
1533
|
+
autoloadBunfig: false,
|
|
1534
|
+
...config.platform === "win32" ? {
|
|
1535
|
+
windows: {
|
|
1536
|
+
hideConsole: true,
|
|
1537
|
+
title: name,
|
|
1538
|
+
version: metadata.version ?? packageMetadata.version,
|
|
1539
|
+
description: metadata.description ?? `${name} \u2014 native Tarve application`,
|
|
1540
|
+
...metadata.publisher ? { publisher: metadata.publisher } : {},
|
|
1541
|
+
...metadata.copyright ? { copyright: metadata.copyright } : {},
|
|
1542
|
+
...icoPath ? { icon: icoPath } : {}
|
|
1543
|
+
}
|
|
1544
|
+
} : {}
|
|
1545
|
+
}
|
|
1546
|
+
});
|
|
1547
|
+
if (!result.success)
|
|
1548
|
+
throw new AggregateError(result.logs, "Could not compile the Tarve application");
|
|
1549
|
+
} finally {
|
|
1550
|
+
if (options.compileJsx)
|
|
1551
|
+
await (await Promise.resolve().then(() => (init_jsx_compile(), exports_jsx_compile))).closeJsxCompiler();
|
|
1552
|
+
await rm3(packDirectory, { recursive: true, force: true });
|
|
1553
|
+
if (iconDirectory)
|
|
1554
|
+
await rm3(iconDirectory, { recursive: true, force: true });
|
|
1555
|
+
}
|
|
1556
|
+
if (config.platform === "linux" && (metadata.icon || metadata.appId))
|
|
1557
|
+
writeLinuxDesktopEntry(outfile, metadata, images?.png);
|
|
255
1558
|
return outfile;
|
|
256
1559
|
}
|
|
1560
|
+
function metadataOverrides(options) {
|
|
1561
|
+
return { name: options.name, version: options.version, description: options.description, publisher: options.publisher, copyright: options.copyright, icon: options.icon, appId: options.appId };
|
|
1562
|
+
}
|
|
1563
|
+
var NATIVE_ZSTD_LEVEL = 12;
|
|
1564
|
+
var init_build = __esm(() => {
|
|
1565
|
+
init_package_metadata();
|
|
1566
|
+
init_targets();
|
|
1567
|
+
init_native_runtime();
|
|
1568
|
+
init_targets();
|
|
1569
|
+
});
|
|
1570
|
+
init_build();
|
|
1571
|
+
|
|
257
1572
|
export {
|
|
258
1573
|
BUILD_TARGETS,
|
|
259
1574
|
build,
|
|
260
1575
|
hostBuildTarget,
|
|
261
1576
|
isBuildTarget,
|
|
1577
|
+
metadataOverrides,
|
|
262
1578
|
nativeDirectoryForBuildTarget,
|
|
263
1579
|
nativeRelativePath,
|
|
264
1580
|
targetConfig
|