@shing.wong/sure-wasm-helper 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +134 -2
- package/bin/sure-pack.mjs +8 -0
- package/dist/bench-cold.d.ts +29 -0
- package/dist/bench-cold.js +155 -0
- package/dist/loopback-host.d.ts +59 -0
- package/dist/loopback-host.js +320 -0
- package/dist/packager.d.ts +66 -0
- package/dist/packager.js +453 -0
- package/dist/updater.d.ts +109 -0
- package/dist/updater.js +389 -0
- package/dist/wasi-socket.d.ts +77 -0
- package/dist/wasi-socket.js +218 -0
- package/dist/wasm-loader.d.ts +76 -0
- package/dist/wasm-loader.js +271 -0
- package/package.json +78 -4
package/dist/packager.js
ADDED
|
@@ -0,0 +1,453 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// Single-file packaging with Node SEA. Bundles an entry with esbuild, embeds
|
|
3
|
+
// UI/core/extra assets, injects a launcher prelude that extracts them to a
|
|
4
|
+
// content-addressed cache, and injects the SEA blob with postject.
|
|
5
|
+
import { execFileSync } from "node:child_process";
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync, } from "node:fs";
|
|
8
|
+
import { chmod, copyFile, mkdtemp, rm } from "node:fs/promises";
|
|
9
|
+
import { createRequire } from "node:module";
|
|
10
|
+
import { tmpdir } from "node:os";
|
|
11
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
12
|
+
import { build } from "esbuild";
|
|
13
|
+
import { HelperError } from "./wasm-loader.js";
|
|
14
|
+
const require = createRequire(import.meta.url);
|
|
15
|
+
const SEA_FUSE = "NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2";
|
|
16
|
+
function fail(message, cause) {
|
|
17
|
+
throw new HelperError("E_PACKAGE_INPUT", message, { cause });
|
|
18
|
+
}
|
|
19
|
+
function requireFile(label, path) {
|
|
20
|
+
const resolved = resolve(path);
|
|
21
|
+
if (!existsSync(resolved) || !statSync(resolved).isFile()) {
|
|
22
|
+
fail(`${label} not found: ${resolved}`);
|
|
23
|
+
}
|
|
24
|
+
return resolved;
|
|
25
|
+
}
|
|
26
|
+
function normalizeAssets(assets) {
|
|
27
|
+
if (!assets)
|
|
28
|
+
return [];
|
|
29
|
+
const entries = Array.isArray(assets)
|
|
30
|
+
? assets
|
|
31
|
+
: Object.entries(assets).map(([name, path]) => ({ name, path }));
|
|
32
|
+
return entries.map((asset) => ({
|
|
33
|
+
name: asset.name.replace(/\\/g, "/"),
|
|
34
|
+
path: requireFile(`asset '${asset.name}'`, asset.path),
|
|
35
|
+
}));
|
|
36
|
+
}
|
|
37
|
+
function assertAssetName(name) {
|
|
38
|
+
if (name.length === 0 ||
|
|
39
|
+
name.startsWith("/") ||
|
|
40
|
+
name.includes("\\") ||
|
|
41
|
+
name.split("/").includes("..") ||
|
|
42
|
+
name === "core/core.wasm" ||
|
|
43
|
+
name.startsWith("ui/")) {
|
|
44
|
+
fail(`invalid asset name '${name}' (reserved or unsafe)`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
function walkUi(root, prefix = "") {
|
|
48
|
+
const out = [];
|
|
49
|
+
for (const entry of readdirSync(join(root, prefix), { withFileTypes: true })) {
|
|
50
|
+
const relative = prefix.length === 0 ? entry.name : `${prefix}/${entry.name}`;
|
|
51
|
+
if (entry.isDirectory())
|
|
52
|
+
out.push(...walkUi(root, relative));
|
|
53
|
+
else if (entry.isFile() && !entry.name.endsWith(".map"))
|
|
54
|
+
out.push(relative);
|
|
55
|
+
}
|
|
56
|
+
return out.sort();
|
|
57
|
+
}
|
|
58
|
+
/** Validate inputs and compute the deterministic asset plan. */
|
|
59
|
+
export function resolvePackagePlan(options) {
|
|
60
|
+
const app = options.app;
|
|
61
|
+
if (typeof app !== "string" || !/^[A-Za-z0-9._-]+$/.test(app)) {
|
|
62
|
+
fail(`invalid app name '${String(app)}' (letters, digits, dot, underscore, hyphen)`);
|
|
63
|
+
}
|
|
64
|
+
const entry = requireFile("entry", options.entry);
|
|
65
|
+
const uiDir = resolve(options.uiDir);
|
|
66
|
+
if (!existsSync(uiDir) || !statSync(uiDir).isDirectory())
|
|
67
|
+
fail(`ui directory not found: ${uiDir}`);
|
|
68
|
+
if (!existsSync(join(uiDir, "index.html")))
|
|
69
|
+
fail(`ui directory has no index.html: ${uiDir}`);
|
|
70
|
+
const core = requireFile("core", options.core);
|
|
71
|
+
const out = resolve(options.out);
|
|
72
|
+
const uiFiles = walkUi(uiDir);
|
|
73
|
+
if (uiFiles.length === 0)
|
|
74
|
+
fail(`ui directory is empty: ${uiDir}`);
|
|
75
|
+
const extraAssets = normalizeAssets(options.assets);
|
|
76
|
+
const seen = new Set();
|
|
77
|
+
for (const asset of extraAssets) {
|
|
78
|
+
assertAssetName(asset.name);
|
|
79
|
+
if (seen.has(asset.name))
|
|
80
|
+
fail(`duplicate asset name '${asset.name}'`);
|
|
81
|
+
seen.add(asset.name);
|
|
82
|
+
}
|
|
83
|
+
const assetNames = [
|
|
84
|
+
...uiFiles.map((file) => `ui/${file}`),
|
|
85
|
+
"core/core.wasm",
|
|
86
|
+
...extraAssets.map((a) => a.name),
|
|
87
|
+
].sort();
|
|
88
|
+
const noArgsArgs = options.noArgsArgs === undefined
|
|
89
|
+
? null
|
|
90
|
+
: typeof options.noArgsArgs === "string"
|
|
91
|
+
? splitArgs(options.noArgsArgs)
|
|
92
|
+
: [...options.noArgsArgs];
|
|
93
|
+
return {
|
|
94
|
+
app,
|
|
95
|
+
entry,
|
|
96
|
+
uiDir,
|
|
97
|
+
core,
|
|
98
|
+
out,
|
|
99
|
+
uiFiles,
|
|
100
|
+
extraAssets,
|
|
101
|
+
assetNames,
|
|
102
|
+
envCore: options.envCore ?? "SURE_APP_CORE_WASM",
|
|
103
|
+
envBuild: options.envBuild ?? "SURE_APP_BUILD",
|
|
104
|
+
envUi: options.envUi ?? "SURE_APP_UI_DIR",
|
|
105
|
+
envLaunch: options.envLaunch ?? "SURE_APP_LAUNCH_ARGS",
|
|
106
|
+
noArgsArgs,
|
|
107
|
+
buildDate: new Date().toISOString(),
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
/** Whitespace split with single/double quote support (no shell expansion). */
|
|
111
|
+
export function splitArgs(input) {
|
|
112
|
+
const out = [];
|
|
113
|
+
let current = "";
|
|
114
|
+
let quote = null;
|
|
115
|
+
for (let index = 0; index < input.length; index += 1) {
|
|
116
|
+
const char = input[index];
|
|
117
|
+
if (quote) {
|
|
118
|
+
if (char === quote)
|
|
119
|
+
quote = null;
|
|
120
|
+
else
|
|
121
|
+
current += char;
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
if (char === '"' || char === "'") {
|
|
125
|
+
quote = char;
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
if (/\s/.test(char)) {
|
|
129
|
+
if (current.length > 0) {
|
|
130
|
+
out.push(current);
|
|
131
|
+
current = "";
|
|
132
|
+
}
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
current += char;
|
|
136
|
+
}
|
|
137
|
+
if (current.length > 0)
|
|
138
|
+
out.push(current);
|
|
139
|
+
return out;
|
|
140
|
+
}
|
|
141
|
+
function assetContents(plan) {
|
|
142
|
+
const contents = new Map();
|
|
143
|
+
for (const file of plan.uiFiles) {
|
|
144
|
+
contents.set(`ui/${file}`, readFileSync(join(plan.uiDir, file)));
|
|
145
|
+
}
|
|
146
|
+
contents.set("core/core.wasm", readFileSync(plan.core));
|
|
147
|
+
for (const asset of plan.extraAssets) {
|
|
148
|
+
contents.set(asset.name, readFileSync(asset.path));
|
|
149
|
+
}
|
|
150
|
+
return contents;
|
|
151
|
+
}
|
|
152
|
+
function entryDigest(code) {
|
|
153
|
+
return createHash("sha256").update(code).digest("hex");
|
|
154
|
+
}
|
|
155
|
+
/** Same algorithm the launcher prelude runs: names + bytes, then entry hash. */
|
|
156
|
+
export function computeStamp(plan, contents, entryHash) {
|
|
157
|
+
const hash = createHash("sha256");
|
|
158
|
+
for (const name of plan.assetNames) {
|
|
159
|
+
const bytes = contents.get(name);
|
|
160
|
+
if (!bytes)
|
|
161
|
+
fail(`missing planned asset '${name}'`);
|
|
162
|
+
hash.update(name);
|
|
163
|
+
hash.update(bytes);
|
|
164
|
+
}
|
|
165
|
+
hash.update(entryHash);
|
|
166
|
+
return hash.digest("hex").slice(0, 16);
|
|
167
|
+
}
|
|
168
|
+
function prelude(plan, entryHash) {
|
|
169
|
+
const values = {
|
|
170
|
+
app: plan.app,
|
|
171
|
+
envCore: plan.envCore,
|
|
172
|
+
envBuild: plan.envBuild,
|
|
173
|
+
envUi: plan.envUi,
|
|
174
|
+
envLaunch: plan.envLaunch,
|
|
175
|
+
assetNames: plan.assetNames,
|
|
176
|
+
entryHash,
|
|
177
|
+
noArgsArgs: plan.noArgsArgs,
|
|
178
|
+
};
|
|
179
|
+
return `// ---- sure-wasm-helper launcher (SEA only) ----
|
|
180
|
+
if (require("node:sea").isSea()) {
|
|
181
|
+
const fs = require("node:fs");
|
|
182
|
+
const path = require("node:path");
|
|
183
|
+
const os = require("node:os");
|
|
184
|
+
const { spawn } = require("node:child_process");
|
|
185
|
+
const { createHash } = require("node:crypto");
|
|
186
|
+
const sea = require("node:sea");
|
|
187
|
+
const CONFIG = ${JSON.stringify(values)};
|
|
188
|
+
|
|
189
|
+
const hash = createHash("sha256");
|
|
190
|
+
for (const name of CONFIG.assetNames) {
|
|
191
|
+
hash.update(name);
|
|
192
|
+
hash.update(Buffer.from(sea.getAsset(name)));
|
|
193
|
+
}
|
|
194
|
+
hash.update(CONFIG.entryHash);
|
|
195
|
+
const stamp = hash.digest("hex").slice(0, 16);
|
|
196
|
+
process.env[CONFIG.envBuild] = stamp;
|
|
197
|
+
|
|
198
|
+
const base = process.platform === "win32"
|
|
199
|
+
? (process.env.LOCALAPPDATA || path.join(os.homedir(), "AppData", "Local"))
|
|
200
|
+
: (process.env.XDG_CACHE_HOME || path.join(os.homedir(), ".cache"));
|
|
201
|
+
const uiDir = path.join(base, CONFIG.app, "ui-" + stamp);
|
|
202
|
+
const corePath = path.join(uiDir, "core.wasm");
|
|
203
|
+
const relativeOf = (name) =>
|
|
204
|
+
name === "core/core.wasm" ? "core.wasm" : name.startsWith("ui/") ? name.slice(3) : name;
|
|
205
|
+
|
|
206
|
+
if (!fs.existsSync(path.join(uiDir, "index.html")) || !fs.existsSync(corePath)) {
|
|
207
|
+
const tmp = uiDir + ".tmp-" + process.pid;
|
|
208
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
209
|
+
fs.mkdirSync(tmp, { recursive: true });
|
|
210
|
+
for (const name of CONFIG.assetNames) {
|
|
211
|
+
const target = path.join(tmp, relativeOf(name));
|
|
212
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
213
|
+
fs.writeFileSync(target, Buffer.from(sea.getAsset(name)));
|
|
214
|
+
}
|
|
215
|
+
fs.rmSync(uiDir, { recursive: true, force: true });
|
|
216
|
+
fs.mkdirSync(path.dirname(uiDir), { recursive: true });
|
|
217
|
+
fs.renameSync(tmp, uiDir);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
process.env[CONFIG.envUi] = uiDir;
|
|
221
|
+
process.env[CONFIG.envCore] = corePath;
|
|
222
|
+
|
|
223
|
+
const args = process.argv.slice(2);
|
|
224
|
+
process.env[CONFIG.envLaunch] = JSON.stringify(args);
|
|
225
|
+
if (args.length === 0 && CONFIG.noArgsArgs) {
|
|
226
|
+
const rewritten = CONFIG.noArgsArgs.map((arg) => arg.split("{uiDir}").join(uiDir));
|
|
227
|
+
process.argv = [process.argv[0], process.argv[1], ...rewritten];
|
|
228
|
+
if (!rewritten.includes("--no-open")) {
|
|
229
|
+
setTimeout(() => {
|
|
230
|
+
const url = "http://127.0.0.1:" + (rewritten.includes("--port") ? rewritten[rewritten.indexOf("--port") + 1] : "8788") + "/";
|
|
231
|
+
const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
|
|
232
|
+
const argv = process.platform === "win32" ? ["/c", "start", "", url] : [url];
|
|
233
|
+
try {
|
|
234
|
+
spawn(command, argv, { detached: true, stdio: "ignore" }).unref();
|
|
235
|
+
} catch {
|
|
236
|
+
// Opening a browser is a courtesy; failing to is not fatal.
|
|
237
|
+
}
|
|
238
|
+
}, 500).unref();
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
// ---- end launcher ----------------------------
|
|
243
|
+
`;
|
|
244
|
+
}
|
|
245
|
+
function seaConfigPath(work) {
|
|
246
|
+
return join(work, "sea-config.json");
|
|
247
|
+
}
|
|
248
|
+
/** Package one executable. Exported for tests; the CLI is a thin wrapper. */
|
|
249
|
+
export async function packageApp(options) {
|
|
250
|
+
const plan = resolvePackagePlan(options);
|
|
251
|
+
const log = options.log ?? (() => { });
|
|
252
|
+
const contents = assetContents(plan);
|
|
253
|
+
const work = await mkdtemp(join(tmpdir(), "sure-pack-"));
|
|
254
|
+
try {
|
|
255
|
+
// Build without the prelude so the entry hash is stable and the final
|
|
256
|
+
// bundle is prelude + code, with the hash covering the code.
|
|
257
|
+
const built = await build({
|
|
258
|
+
entryPoints: [plan.entry],
|
|
259
|
+
bundle: true,
|
|
260
|
+
write: false,
|
|
261
|
+
platform: "node",
|
|
262
|
+
format: "cjs",
|
|
263
|
+
target: "node22",
|
|
264
|
+
logLevel: "warning",
|
|
265
|
+
define: { "import.meta.url": "__seaImportMetaUrl" },
|
|
266
|
+
banner: {
|
|
267
|
+
js: `const __seaImportMetaUrl = require("node:url").pathToFileURL(process.execPath).href;`,
|
|
268
|
+
},
|
|
269
|
+
});
|
|
270
|
+
const output = built.outputFiles?.[0];
|
|
271
|
+
if (!output)
|
|
272
|
+
throw new HelperError("E_PACKAGE_BUILD", "esbuild produced no output");
|
|
273
|
+
const code = new TextDecoder().decode(output.contents);
|
|
274
|
+
const hash = entryDigest(code);
|
|
275
|
+
const stamp = computeStamp(plan, contents, hash);
|
|
276
|
+
const bundle = join(work, "entry.cjs");
|
|
277
|
+
writeFileSync(bundle, prelude(plan, hash) + code);
|
|
278
|
+
const assets = {};
|
|
279
|
+
for (const file of plan.uiFiles)
|
|
280
|
+
assets[`ui/${file}`] = join(plan.uiDir, file);
|
|
281
|
+
assets["core/core.wasm"] = plan.core;
|
|
282
|
+
for (const asset of plan.extraAssets)
|
|
283
|
+
assets[asset.name] = asset.path;
|
|
284
|
+
const config = seaConfigPath(work);
|
|
285
|
+
const blob = join(work, "prep.blob");
|
|
286
|
+
writeFileSync(config, JSON.stringify({
|
|
287
|
+
main: bundle,
|
|
288
|
+
output: blob,
|
|
289
|
+
disableExperimentalSEAWarning: true,
|
|
290
|
+
assets,
|
|
291
|
+
}, null, 2));
|
|
292
|
+
try {
|
|
293
|
+
execFileSync(process.execPath, ["--experimental-sea-config", config], { stdio: "inherit" });
|
|
294
|
+
}
|
|
295
|
+
catch (error) {
|
|
296
|
+
throw new HelperError("E_PACKAGE_BUILD", `node --experimental-sea-config failed: ${String(error)}`, {
|
|
297
|
+
cause: error,
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
mkdirSync(dirname(plan.out), { recursive: true });
|
|
301
|
+
rmSync(plan.out, { force: true });
|
|
302
|
+
await copyFile(process.execPath, plan.out);
|
|
303
|
+
const postjectCli = join(dirname(require.resolve("postject/package.json")), "dist", "cli.js");
|
|
304
|
+
try {
|
|
305
|
+
execFileSync(process.execPath, [postjectCli, plan.out, "NODE_SEA_BLOB", blob, "--sentinel-fuse", SEA_FUSE], { stdio: "inherit" });
|
|
306
|
+
}
|
|
307
|
+
catch (error) {
|
|
308
|
+
throw new HelperError("E_PACKAGE_BUILD", `postject failed: ${String(error)}`, { cause: error });
|
|
309
|
+
}
|
|
310
|
+
if (process.platform !== "win32")
|
|
311
|
+
await chmod(plan.out, 0o755);
|
|
312
|
+
const size = statSync(plan.out).size;
|
|
313
|
+
log(`packaged ${plan.out} (${(size / 1024 / 1024).toFixed(1)} MB, ui-${stamp})`);
|
|
314
|
+
return {
|
|
315
|
+
ok: true,
|
|
316
|
+
out: plan.out,
|
|
317
|
+
size,
|
|
318
|
+
stamp,
|
|
319
|
+
uiFiles: plan.uiFiles.length,
|
|
320
|
+
assets: Object.keys(assets).length,
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
finally {
|
|
324
|
+
await rm(work, { recursive: true, force: true });
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
function takeValue(argv, index, flag) {
|
|
328
|
+
const value = argv[index + 1];
|
|
329
|
+
if (value === undefined)
|
|
330
|
+
fail(`${flag} needs a value`);
|
|
331
|
+
return value;
|
|
332
|
+
}
|
|
333
|
+
/** Parse CLI flags into PackageOptions, optionally seeded by --config JSON. */
|
|
334
|
+
export function parsePackageCli(argv) {
|
|
335
|
+
let options = {};
|
|
336
|
+
const configAt = argv.indexOf("--config");
|
|
337
|
+
if (configAt !== -1) {
|
|
338
|
+
const configPath = resolve(takeValue(argv, configAt, "--config"));
|
|
339
|
+
if (!existsSync(configPath))
|
|
340
|
+
fail(`config not found: ${configPath}`);
|
|
341
|
+
try {
|
|
342
|
+
options = JSON.parse(readFileSync(configPath, "utf8"));
|
|
343
|
+
}
|
|
344
|
+
catch (error) {
|
|
345
|
+
fail(`could not parse ${configPath}: ${String(error)}`);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
const assets = [];
|
|
349
|
+
if (Array.isArray(options.assets))
|
|
350
|
+
assets.push(...options.assets);
|
|
351
|
+
else if (options.assets && typeof options.assets === "object") {
|
|
352
|
+
for (const [name, path] of Object.entries(options.assets))
|
|
353
|
+
assets.push({ name, path });
|
|
354
|
+
}
|
|
355
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
356
|
+
const flag = argv[index];
|
|
357
|
+
switch (flag) {
|
|
358
|
+
case "--config":
|
|
359
|
+
index += 1;
|
|
360
|
+
break;
|
|
361
|
+
case "--app":
|
|
362
|
+
options.app = takeValue(argv, index, flag);
|
|
363
|
+
index += 1;
|
|
364
|
+
break;
|
|
365
|
+
case "--entry":
|
|
366
|
+
options.entry = takeValue(argv, index, flag);
|
|
367
|
+
index += 1;
|
|
368
|
+
break;
|
|
369
|
+
case "--ui-dir":
|
|
370
|
+
options.uiDir = takeValue(argv, index, flag);
|
|
371
|
+
index += 1;
|
|
372
|
+
break;
|
|
373
|
+
case "--core":
|
|
374
|
+
options.core = takeValue(argv, index, flag);
|
|
375
|
+
index += 1;
|
|
376
|
+
break;
|
|
377
|
+
case "--out":
|
|
378
|
+
options.out = takeValue(argv, index, flag);
|
|
379
|
+
index += 1;
|
|
380
|
+
break;
|
|
381
|
+
case "--no-args-args":
|
|
382
|
+
options.noArgsArgs = takeValue(argv, index, flag);
|
|
383
|
+
index += 1;
|
|
384
|
+
break;
|
|
385
|
+
case "--env-core":
|
|
386
|
+
options.envCore = takeValue(argv, index, flag);
|
|
387
|
+
index += 1;
|
|
388
|
+
break;
|
|
389
|
+
case "--env-build":
|
|
390
|
+
options.envBuild = takeValue(argv, index, flag);
|
|
391
|
+
index += 1;
|
|
392
|
+
break;
|
|
393
|
+
case "--env-ui":
|
|
394
|
+
options.envUi = takeValue(argv, index, flag);
|
|
395
|
+
index += 1;
|
|
396
|
+
break;
|
|
397
|
+
case "--env-launch":
|
|
398
|
+
options.envLaunch = takeValue(argv, index, flag);
|
|
399
|
+
index += 1;
|
|
400
|
+
break;
|
|
401
|
+
case "--asset": {
|
|
402
|
+
const pair = takeValue(argv, index, flag);
|
|
403
|
+
const at = pair.indexOf("=");
|
|
404
|
+
if (at <= 0 || at === pair.length - 1)
|
|
405
|
+
fail(`--asset needs name=path, got '${pair}'`);
|
|
406
|
+
assets.push({ name: pair.slice(0, at), path: pair.slice(at + 1) });
|
|
407
|
+
index += 1;
|
|
408
|
+
break;
|
|
409
|
+
}
|
|
410
|
+
default:
|
|
411
|
+
fail(`unknown argument '${flag}'`);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
if (assets.length > 0)
|
|
415
|
+
options.assets = assets;
|
|
416
|
+
if (typeof options.app !== "string" ||
|
|
417
|
+
typeof options.entry !== "string" ||
|
|
418
|
+
typeof options.uiDir !== "string" ||
|
|
419
|
+
typeof options.core !== "string" ||
|
|
420
|
+
typeof options.out !== "string") {
|
|
421
|
+
fail("need --app, --entry, --ui-dir, --core and --out (or --config)");
|
|
422
|
+
}
|
|
423
|
+
return options;
|
|
424
|
+
}
|
|
425
|
+
const USAGE = `usage: sure-pack --app <name> --entry <file> --ui-dir <dir> --core <wasm> --out <file>
|
|
426
|
+
[--asset name=path]... [--no-args-args "serve --ui"]
|
|
427
|
+
[--env-core NAME] [--env-build NAME] [--env-ui NAME] [--env-launch NAME]
|
|
428
|
+
[--config sure-pack.json]`;
|
|
429
|
+
/** CLI entry point. Returns an exit code; never calls process.exit. */
|
|
430
|
+
export async function runSurePackCli(argv = process.argv.slice(2)) {
|
|
431
|
+
if (argv.includes("--help") || argv.includes("-h")) {
|
|
432
|
+
console.log(USAGE);
|
|
433
|
+
return 0;
|
|
434
|
+
}
|
|
435
|
+
try {
|
|
436
|
+
const result = await packageApp(parsePackageCli(argv));
|
|
437
|
+
console.log(`packaged ${result.out}`);
|
|
438
|
+
console.log(` ${(result.size / 1024 / 1024).toFixed(1)} MB · ${result.uiFiles} UI files · ${result.assets} assets · ui-${result.stamp}`);
|
|
439
|
+
console.log(` run with no arguments to start the application`);
|
|
440
|
+
return 0;
|
|
441
|
+
}
|
|
442
|
+
catch (error) {
|
|
443
|
+
const code = error instanceof HelperError ? error.code : "E_PACKAGE_BUILD";
|
|
444
|
+
console.error(`${code}: ${error instanceof Error ? error.message : String(error)}`);
|
|
445
|
+
return 1;
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
/** Exported for the packaged binary's own `--version` diagnostics. */
|
|
449
|
+
export const packagerVersion = "0.1.0";
|
|
450
|
+
/** Exported for callers that need the default executable suffix. */
|
|
451
|
+
export function defaultExecutableName(app, platform = process.platform) {
|
|
452
|
+
return `${basename(app)}${platform === "win32" ? ".exe" : ""}`;
|
|
453
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
export interface UpdateAsset {
|
|
2
|
+
build?: string;
|
|
3
|
+
url: string;
|
|
4
|
+
sha256: string;
|
|
5
|
+
size?: number;
|
|
6
|
+
/** ISO timestamp of the published build, used to avoid downgrades. */
|
|
7
|
+
builtAt?: string;
|
|
8
|
+
}
|
|
9
|
+
export interface UpdateManifest {
|
|
10
|
+
version: string;
|
|
11
|
+
released?: string;
|
|
12
|
+
assets: Record<string, UpdateAsset>;
|
|
13
|
+
}
|
|
14
|
+
export type FetchLike = (input: string | URL, init?: RequestInit) => Promise<Response>;
|
|
15
|
+
export interface SelfUpdaterOptions {
|
|
16
|
+
appName: string;
|
|
17
|
+
manifestUrl: string;
|
|
18
|
+
currentVersion: string;
|
|
19
|
+
currentBuild: string;
|
|
20
|
+
/** ISO timestamp of the running build, when the packager recorded one. */
|
|
21
|
+
currentBuiltAt?: string;
|
|
22
|
+
downloadsDir?: string;
|
|
23
|
+
fetchImpl?: FetchLike;
|
|
24
|
+
env?: NodeJS.ProcessEnv;
|
|
25
|
+
platform?: string;
|
|
26
|
+
execPath?: string;
|
|
27
|
+
/** Environment variable that carries the original argv. */
|
|
28
|
+
launchEnv?: string;
|
|
29
|
+
/** Arguments used when relaunching after a swap. Defaults to argv/env. */
|
|
30
|
+
relaunchArgs?: string[];
|
|
31
|
+
}
|
|
32
|
+
export interface UpdateCheckResult {
|
|
33
|
+
ok: boolean;
|
|
34
|
+
current: string;
|
|
35
|
+
latest: string;
|
|
36
|
+
updateAvailable: boolean;
|
|
37
|
+
asset: UpdateAsset | null;
|
|
38
|
+
code?: string;
|
|
39
|
+
error?: string;
|
|
40
|
+
/** Human-readable reason when no update is offered. */
|
|
41
|
+
reason?: string;
|
|
42
|
+
}
|
|
43
|
+
export interface UpdateDownloadResult {
|
|
44
|
+
ok: boolean;
|
|
45
|
+
path?: string;
|
|
46
|
+
bytes?: number;
|
|
47
|
+
sha256?: string;
|
|
48
|
+
build?: string;
|
|
49
|
+
code?: string;
|
|
50
|
+
error?: string;
|
|
51
|
+
}
|
|
52
|
+
export interface UpdateApplyResult {
|
|
53
|
+
ok: boolean;
|
|
54
|
+
restarting?: boolean;
|
|
55
|
+
path?: string;
|
|
56
|
+
target?: string;
|
|
57
|
+
build?: string;
|
|
58
|
+
code?: string;
|
|
59
|
+
error?: string;
|
|
60
|
+
}
|
|
61
|
+
export interface ApplyUpdateSwapOptions {
|
|
62
|
+
/** Process that must exit before the running image can be replaced. */
|
|
63
|
+
pid: number;
|
|
64
|
+
/** Executable to replace. */
|
|
65
|
+
target: string;
|
|
66
|
+
/** Arguments the new build is started with. */
|
|
67
|
+
relaunchArgs?: string[];
|
|
68
|
+
waitMs?: number;
|
|
69
|
+
pollMs?: number;
|
|
70
|
+
/** The verified helper binary to copy into place. */
|
|
71
|
+
execPath?: string;
|
|
72
|
+
platform?: string;
|
|
73
|
+
}
|
|
74
|
+
export interface ApplyUpdateSwapResult {
|
|
75
|
+
ok: true;
|
|
76
|
+
backup: string;
|
|
77
|
+
}
|
|
78
|
+
export declare class SelfUpdater {
|
|
79
|
+
readonly options: Required<Pick<SelfUpdaterOptions, "appName" | "manifestUrl" | "currentVersion" | "currentBuild">> & SelfUpdaterOptions;
|
|
80
|
+
private readonly fetchImpl;
|
|
81
|
+
private readonly env;
|
|
82
|
+
private readonly platform;
|
|
83
|
+
private readonly execPath;
|
|
84
|
+
constructor(options: SelfUpdaterOptions);
|
|
85
|
+
/** Fetch the manifest and compare builds (or versions when no build). */
|
|
86
|
+
check(): Promise<UpdateCheckResult>;
|
|
87
|
+
/** Download and verify this platform's asset while hashing. */
|
|
88
|
+
download(): Promise<UpdateDownloadResult>;
|
|
89
|
+
/**
|
|
90
|
+
* Download, then start the verified helper to swap and relaunch.
|
|
91
|
+
*
|
|
92
|
+
* Refuses when the running executable is Node itself: a source checkout must
|
|
93
|
+
* not replace the interpreter it is running on.
|
|
94
|
+
*/
|
|
95
|
+
apply(): Promise<UpdateApplyResult>;
|
|
96
|
+
}
|
|
97
|
+
export declare function createSelfUpdater(options: SelfUpdaterOptions): SelfUpdater;
|
|
98
|
+
/**
|
|
99
|
+
* Wait for `pid`, then replace `target` with the running helper binary.
|
|
100
|
+
*
|
|
101
|
+
* Sequence: copy helper -> `.new`, rename target -> `.old`, rename `.new` ->
|
|
102
|
+
* target, chmod. Any failure after the target moves restores `.old`.
|
|
103
|
+
*/
|
|
104
|
+
export declare function applyUpdateSwap(options: ApplyUpdateSwapOptions): Promise<ApplyUpdateSwapResult>;
|
|
105
|
+
/**
|
|
106
|
+
* Entry point for the packaged binary's `apply-update <pid> <target>
|
|
107
|
+
* [--relaunch ...]` verb. Returns a process exit code; never calls exit().
|
|
108
|
+
*/
|
|
109
|
+
export declare function runApplyUpdateCli(argv?: string[]): Promise<number>;
|