jsgotty 1.1.5 → 1.1.7

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.
@@ -1,20 +1,27 @@
1
1
  import { basename, dirname, resolve } from "node:path";
2
- import { readFileSync } from "node:fs";
2
+ import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import child_process from "node:child_process";
5
+ import { ASSETS_ROOT } from "./assetsPacker.js";
5
6
 
6
7
 
7
8
  export const IS_COMPILED = isCompiledBinary();
8
9
  export const REPO_ROOT = IS_COMPILED
9
10
  ? getExeDirname()
10
- : resolve(import.meta.dirname, "..");
11
- const SINGLE_EXE_DIR = resolve(REPO_ROOT, "single-exe");
12
- const SINGLE_EXE_ENTRY = resolve(SINGLE_EXE_DIR, "entry.mjs");
11
+ : resolve(import.meta.dirname, ASSETS_ROOT);
12
+ // This file's own directory. Not derived from REPO_ROOT: the only user
13
+ // is buildExecutable(), which already refuses to run when IS_COMPILED,
14
+ // so REPO_ROOT there is always the source tree, and going back down
15
+ // through it would hard-code this folder name.
16
+ const SINGLE_EXE_DIR = import.meta.dirname;
13
17
 
14
18
 
15
- export function isCompiledBinary() {
16
- const argv = process.argv
17
- return Boolean(argv?.[1]?.startsWith?.("/$bunfs/"));
19
+ export function isCompiledBinary(argv = process.argv) {
20
+ const entry = argv?.[1];
21
+ return Boolean(
22
+ entry?.startsWith?.("/$bunfs/") ||
23
+ entry?.startsWith?.("B:/~BUN")
24
+ );
18
25
  }
19
26
 
20
27
  export function getExeDirname() {
@@ -35,10 +42,63 @@ export function getDirnameFromUrl(importMetaUrl) {
35
42
  return dirname(fileURLToPath(importMetaUrl));
36
43
  }
37
44
 
38
- export async function buildExecutable(target = "",build_outfile="single.exe") {
45
+ export function stringifyNonPrimitiveDefineValues(argv, name) {
46
+ const definePrefix = `${name}=`;
47
+ const numberLiteral = /^[+-]?(?:(?:0[xX][\dA-Fa-f](?:_?[\dA-Fa-f])*)|(?:0[bB][01](?:_?[01])*)|(?:0[oO][0-7](?:_?[0-7])*)|(?:(?:\d(?:_?\d)*)(?:\.(?:\d(?:_?\d)*)?)?|\.(?:\d(?:_?\d)*))(?:[eE][+-]?\d(?:_?\d)*)?)$/;
48
+
49
+ // Parse scalar literals as data. Never evaluate a user-provided expression.
50
+ const normalize = (definition) => {
51
+ if (!definition.startsWith(definePrefix)) return definition;
52
+ const source = definition.slice(definePrefix.length);
53
+ const trimmed = source.trim();
54
+ let value;
55
+ let parsed = false;
56
+
57
+ try {
58
+ value = JSON.parse(source);
59
+ parsed = true;
60
+ } catch {
61
+ try {
62
+ if (globalThis.Bun?.JSON5) {
63
+ value = globalThis.Bun.JSON5.parse(source);
64
+ parsed = true;
65
+ }
66
+ } catch {}
67
+ }
68
+
69
+ if (parsed && typeof value === "string") {
70
+ return definePrefix + JSON.stringify(value);
71
+ }
72
+ if (
73
+ (parsed && (
74
+ value === null
75
+ || typeof value === "number"
76
+ || typeof value === "boolean"
77
+ ))
78
+ || trimmed === "undefined"
79
+ || numberLiteral.test(trimmed)
80
+ ) {
81
+ return definition;
82
+ }
83
+ return definePrefix + JSON.stringify(source);
84
+ };
85
+
86
+ for (let i = 0; i < argv.length; i++) {
87
+ if (argv[i] === "--define" && typeof argv[i + 1] === "string") {
88
+ argv[i + 1] = normalize(argv[i + 1]);
89
+ } else if (argv[i]?.startsWith?.("--define=")) {
90
+ argv[i] = "--define="
91
+ + normalize(argv[i].slice("--define=".length));
92
+ }
93
+ }
94
+ return argv;
95
+ }
96
+
97
+ export async function buildExecutable(target = "",build_outfile="single.exe", bunArgs = []) {
39
98
 
40
- const outfile = resolve(process.cwd(), build_outfile);
99
+ let outfile = resolve(process.cwd(), build_outfile);
41
100
  const normalizedTarget = String(target || "").trim();
101
+ const extraBunArgs = Array.from(bunArgs ?? [], String);
42
102
  if(!globalThis.Bun || IS_COMPILED)
43
103
  {
44
104
  console.log("Build exe can only be run by Bun in the source tree");
@@ -56,16 +116,19 @@ export async function buildExecutable(target = "",build_outfile="single.exe") {
56
116
  },
57
117
  {
58
118
  label: "Compile executable",
59
- cwd: process.cwd(),
119
+ cwd: SINGLE_EXE_DIR,
60
120
  cmd: bunBin,
61
121
  args: [
62
122
  "build",
123
+ "--format=esm",
63
124
  "--compile",
64
- "--bytecode",
65
125
  "--minify",
66
- SINGLE_EXE_ENTRY,
67
- `--outfile=${build_outfile}`,
126
+ "--bytecode",
127
+ "./entry.mjs",
128
+ `--outfile=${outfile}`,
129
+ `--metafile-md=${outfile}.meta.md`,
68
130
  ...(normalizedTarget ? [`--target=${normalizedTarget}`] : []),
131
+ ...extraBunArgs,
69
132
  ],
70
133
  },
71
134
  ];
@@ -73,7 +136,9 @@ export async function buildExecutable(target = "",build_outfile="single.exe") {
73
136
  for (const step of steps) {
74
137
 
75
138
  console.log('');
76
- console.log(Bun?.markdown?.ansi?.('## '+step.label)||step.label);
139
+ console.log(Bun?.markdown?.ansi?.('## '+step.label)||step.label);
140
+
141
+ console.log("Running: ",step.cmd,step.args)
77
142
 
78
143
  const result = child_process.spawnSync(step.cmd, step.args, {
79
144
  cwd: step.cwd,
@@ -103,6 +168,12 @@ export async function buildExecutable(target = "",build_outfile="single.exe") {
103
168
 
104
169
  } // for steps of build
105
170
 
171
+ const isWindows = normalizedTarget
172
+ ? normalizedTarget.toLowerCase().includes("windows")
173
+ : process.platform === "win32";
174
+ if (isWindows && !outfile.toLowerCase().endsWith(".exe")) {
175
+ outfile += ".exe";
176
+ }
106
177
  if(await Bun.file(outfile).exists())
107
178
  {
108
179
  console.log(`Built executable: ${outfile}`);
@@ -115,24 +186,244 @@ export async function buildExecutable(target = "",build_outfile="single.exe") {
115
186
  }
116
187
  }
117
188
 
118
- export const buildExe = buildExecutable;
189
+ export const buildExe = buildExeAssets;
190
+
191
+ export async function buildEarlyExit(argv,build_outfile) {
192
+ argv = argv || process.argv
119
193
 
120
- export async function buildEarlyExit(argv = process.argv,build_outfile) {
121
194
  const buildExeIndex = argv.indexOf("--build-exe");
122
195
  const buildForIndex = argv.indexOf("--build-for");
123
196
 
124
197
  if (buildExeIndex === -1 && buildForIndex === -1) {
125
198
  return false;
126
199
  }
200
+
201
+ if (IS_COMPILED) {
202
+ console.error("--build-exe & --build-for are only available in the source tree");
203
+ process.exit(1);
204
+ }
127
205
 
128
206
  if (buildForIndex !== -1) {
129
207
  const target = argv[buildForIndex + 1];
130
208
  if (!target || target.startsWith("-")) {
131
- console.error("Missing value for --build-for");
209
+ console.error("Missing target value for --build-for");
132
210
  process.exit(2);
133
211
  }
134
- process.exit(await buildExe(target,build_outfile));
212
+ process.exit(await buildExe(target, build_outfile, argv.slice(buildForIndex + 2)));
213
+ }
214
+
215
+ process.exit(await buildExe(null, build_outfile, argv.slice(buildExeIndex + 1)));
216
+ }
217
+
218
+
219
+ // Multi-package variant of buildExecutable().
220
+ //
221
+ // Every package that ships assets vendors its own single-exe/, and its
222
+ // assetsHelper imports its assetsPacker, so a packer shows up in the
223
+ // bundle's module graph exactly when that package is actually reachable
224
+ // from this entry point. A scan build writes that graph to a metafile,
225
+ // and each packer found there appends its own namespaced members to one
226
+ // shared assets.tar before the real compile runs.
227
+ export async function buildExeAssets(target = "", build_outfile = "single.exe", bunArgs = []) {
228
+ let outfile = resolve(process.cwd(), build_outfile);
229
+ const normalizedTarget = String(target || "").trim();
230
+ const extraBunArgs = Array.from(bunArgs ?? [], String);
231
+
232
+ if (!globalThis.Bun || IS_COMPILED) {
233
+ console.log("Build exe can only be run by Bun in the source tree");
234
+ return 1;
235
+ }
236
+
237
+ const bunBin = Bun.which("bun") || process.argv0;
238
+ const ownPacker = resolve(SINGLE_EXE_DIR, "assetsPacker.js");
239
+ const archive = resolve(SINGLE_EXE_DIR, "assets.tar");
240
+ const metafile = `${outfile}.meta.json`;
241
+ const scanDir = `${outfile}.scan`;
242
+
243
+ // ASSETS_BUNFS swaps the tar for `--compile --asset`: every packer
244
+ // copies into one fixed build/assets, and --asset keeps only that
245
+ // folder's basename, so the members land at assets/<name>@<version>/
246
+ // exactly as the tar back end writes them.
247
+ const bunfs = Boolean(process.env.ASSETS_BUNFS);
248
+ const staging = resolve(REPO_ROOT, "build", "assets");
249
+
250
+ // Nothing loads a tar in bunfs mode, so entry.mjs and its asset loader
251
+ // are dead weight and the program becomes its own entry point. Which
252
+ // program that is stays declared in one place, the last import of
253
+ // entry.mjs, so adopting projects still edit only that file.
254
+ const mainSpec = bunfs ? lastEntryImport(resolve(SINGLE_EXE_DIR, "entry.mjs")) : "";
255
+
256
+ if (bunfs && !mainSpec) {
257
+ console.error("Could not read the main program from entry.mjs's last import");
258
+ return 1;
259
+ }
260
+
261
+ const compileEntry = bunfs ? resolve(SINGLE_EXE_DIR, mainSpec) : "./entry.mjs";
262
+
263
+ const step = (label, args, cwd) => {
264
+ console.log("");
265
+ console.log(Bun?.markdown?.ansi?.("## " + label) || label);
266
+ console.log("Running: ", bunBin, args);
267
+
268
+ const result = child_process.spawnSync(bunBin, args, {
269
+ cwd,
270
+ stdio: "inherit",
271
+ env: process.env,
272
+ });
273
+
274
+ console.log("");
275
+ console.log(Bun?.markdown?.ansi?.("- Status: " + result.status + " for " + label) || result.status);
276
+
277
+ if (result.error) console.error(result.error);
278
+ return result.status ?? 1;
279
+ };
280
+
281
+ // What each packer is told to write into, and in which mode.
282
+ const packInto = bunfs ? ["-f", staging] : ["-f", archive, "-p"];
283
+
284
+ if (bunfs) {
285
+ mkdirSync(staging, { recursive: true });
286
+ console.log("");
287
+ console.log(`Staging assets into ${staging}`);
288
+ } else if (step("Pack own assets", [ownPacker, ...packInto], SINGLE_EXE_DIR) !== 0) {
289
+ // Tar mode packs first: the scan below has to resolve entry.mjs's
290
+ // `with { type: "file" }` import of the archive.
291
+ console.error("Own assets failed to pack");
292
+ return 1;
293
+ }
294
+
295
+ // Bundle only. The binary is thrown away, so skip --compile, --minify
296
+ // and --bytecode; the module graph is the same and it is much faster.
297
+ if (step("Scan module graph", ["build", compileEntry, "--target=bun", `--metafile=${metafile}`, `--outdir=${scanDir}`], SINGLE_EXE_DIR) !== 0) {
298
+ console.error("Scan build failed");
299
+ return 1;
300
+ }
301
+
302
+ const packers = findAssetPackers(metafile, SINGLE_EXE_DIR, bunfs ? "" : ownPacker);
303
+ rmSync(scanDir, { recursive: true, force: true });
304
+
305
+ console.log("");
306
+ console.log(`Found ${packers.length} asset packer(s) to run`);
307
+
308
+ for (const packer of packers) {
309
+ const name = dirname(dirname(packer)).split("/").pop();
310
+
311
+ // Tar mode appends to a shared archive; folder mode needs no -r
312
+ // because each package owns its own <name>@<version> subtree.
313
+ const args = bunfs ? [packer, ...packInto] : [packer, ...packInto, "-r"];
314
+
315
+ if (step(`Pack ${name}`, args, dirname(packer)) !== 0) {
316
+ console.error(`Failed to pack assets from ${packer}`);
317
+ return 1;
318
+ }
319
+ }
320
+
321
+ // Compress last. Every packer above reads the archive and writes it
322
+ // back uncompressed, so this has to happen after the final append.
323
+ // libarchive sniffs the format on read, so assetsLoader needs no
324
+ // change to consume it. Nothing to compress in bunfs mode.
325
+ if (bunfs) {
326
+ // no archive in this mode
327
+ } else if (process.env.ASSETS_NO_GZIP) {
328
+ console.log("");
329
+ console.log("ASSETS_NO_GZIP is set, leaving the archive uncompressed");
330
+ } else {
331
+ console.log("");
332
+ console.log(Bun?.markdown?.ansi?.("## Compress assets") || "Compress assets");
333
+
334
+ try {
335
+ const raw = await Bun.file(archive).bytes();
336
+ const gzipped = Bun.gzipSync(raw, { level: 9 });
337
+
338
+ await Bun.write(archive, gzipped);
339
+
340
+ const pct = raw.byteLength ? Math.round((1 - gzipped.byteLength / raw.byteLength) * 100) : 0;
341
+ console.log(`${raw.byteLength} -> ${gzipped.byteLength} bytes (-${pct}%)`);
342
+ } catch (e) {
343
+ console.error("Could not compress the archive; continuing uncompressed");
344
+ console.error(e);
345
+ }
346
+ }
347
+
348
+ if (step("Compile executable", [
349
+ "build",
350
+ "--format=esm",
351
+ "--compile",
352
+ "--minify",
353
+ "--bytecode",
354
+ compileEntry,
355
+ ...(bunfs ? ["--asset", staging] : []),
356
+ `--outfile=${outfile}`,
357
+ `--metafile-md=${outfile}.meta.md`,
358
+ ...(normalizedTarget ? [`--target=${normalizedTarget}`] : []),
359
+ ...extraBunArgs,
360
+ ], SINGLE_EXE_DIR) !== 0) {
361
+ console.error("Compile failed");
362
+ }
363
+
364
+ const isWindows = normalizedTarget ? normalizedTarget.toLowerCase().includes("windows") : process.platform === "win32";
365
+ if (isWindows && !outfile.toLowerCase().endsWith(".exe")) {
366
+ outfile += ".exe";
367
+ }
368
+
369
+ if (await Bun.file(outfile).exists()) {
370
+ console.log(`Built executable: ${outfile}`);
371
+ return 0;
372
+ }
373
+
374
+ console.log(`Error while building executable: ${outfile}`);
375
+ return 1;
376
+ }
377
+
378
+
379
+ // The main program, as declared by the last import of entry.mjs. That
380
+ // file is already the one place an adopting project edits, so bunfs
381
+ // builds read it rather than adding a second declaration.
382
+ export function lastEntryImport(entryFile) {
383
+ let src;
384
+
385
+ try {
386
+ src = readFileSync(entryFile, "utf8");
387
+ } catch {
388
+ return "";
389
+ }
390
+
391
+ // Drop comments first, or a commented-out import would win.
392
+ src = src.replace(/\/\*[\s\S]*?\*\//g, "").replace(/^[ \t]*\/\/.*$/gm, "");
393
+
394
+ const re = /\bimport\b[^"'\n]*["']([^"']+)["']/g; // "
395
+ let last = "";
396
+
397
+ for (let m; (m = re.exec(src)) !== null; ) last = m[1];
398
+
399
+ return last;
400
+ }
401
+
402
+
403
+ // Absolute, de-duplicated paths of every assetsPacker.js in the metafile,
404
+ // minus `own`. Metafile input keys are relative to the build's cwd.
405
+ export function findAssetPackers(metafilePath, baseDir, own = "") {
406
+ if (!existsSync(metafilePath)) return [];
407
+
408
+ let meta;
409
+ try {
410
+ meta = JSON.parse(readFileSync(metafilePath, "utf8"));
411
+ } catch (e) {
412
+ console.error(`Could not read metafile ${metafilePath}`);
413
+ console.error(e);
414
+ return [];
415
+ }
416
+
417
+ const found = new Set();
418
+
419
+ for (const key of Object.keys(meta?.inputs ?? {})) {
420
+ if (basename(key) !== "assetsPacker.js") continue;
421
+
422
+ const abs = resolve(baseDir, key);
423
+ if (abs === own || !existsSync(abs)) continue;
424
+
425
+ found.add(abs);
135
426
  }
136
427
 
137
- process.exit(await buildExe(null,build_outfile));
428
+ return [...found].sort();
138
429
  }
@@ -3,7 +3,14 @@
3
3
  // 1. Injects assets to global.internalAssets
4
4
  // as { "./path/in/tar":file.bytes() }
5
5
  // 2. Sets global.assetsLoaderPromise
6
- import "./assetsLoader.mjs"
6
+ // 3. Starts the main program only after the assets are ready
7
+ import "./assetsLoader.mjs";
7
8
 
8
- import "../gotty.js"
9
+ await globalThis.assetsLoaderPromise;
9
10
 
11
+ // gotty.js starts itself from `require.main === module`, which the
12
+ // bundler inlines to false because this file is the entry point instead.
13
+ // Call its exported starter directly.
14
+ const { bootstrap } = await import("../gotty.js");
15
+
16
+ await bootstrap();
@@ -17,6 +17,8 @@
17
17
  user-select: none;
18
18
  transition: opacity 180ms ease-in;
19
19
  text-align: center;
20
+ z-index: 10;
21
+ pointer-events: auto;
20
22
  }
21
23
 
22
24
  .xterm-overlay-button {
@@ -29,4 +31,5 @@
29
31
  color: white;
30
32
  font: inherit;
31
33
  cursor: pointer;
34
+ pointer-events: auto;
32
35
  }
@@ -763,6 +763,9 @@
763
763
  if (state.contextMenu && state.contextMenu.root.contains(event.target)) {
764
764
  return;
765
765
  }
766
+ if (event.target instanceof Element && event.target.closest(".xterm-overlay")) {
767
+ return;
768
+ }
766
769
  const key = placementAtPoint(event.clientX, event.clientY);
767
770
  if (!key) {
768
771
  return;