jsgotty 1.1.6 → 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.
package/gotty.js CHANGED
@@ -3323,3 +3323,8 @@ if (require.main === module) {
3323
3323
  process.exitCode = 1;
3324
3324
  });
3325
3325
  }
3326
+
3327
+ // The guard above is inlined to false once this file is bundled, because
3328
+ // the bundle entry point is single-exe/entry.mjs rather than this file.
3329
+ // Export the starter so that entry point can call it.
3330
+ module.exports.bootstrap = bootstrap;
package/package.json CHANGED
@@ -1,11 +1,16 @@
1
1
  {
2
2
  "name": "jsgotty",
3
- "version": "1.1.6",
3
+ "version": "1.1.7",
4
4
  "description": "Share your terminal as a web application: A JavaScript rewrite of GoTTY",
5
5
  "bin": {
6
6
  "jsgotty": "./gotty.js"
7
7
  },
8
8
  "type": "commonjs",
9
+ "assets": [
10
+ "static",
11
+ "README.md",
12
+ "README.en.md"
13
+ ],
9
14
  "dependencies": {
10
15
  "node-addon-api": "^7.1.1",
11
16
  "ws": "^8.18.3"
@@ -1,80 +1,346 @@
1
- # This is completely optional
2
- - I still recommend using the methods in the root README.md
3
- - Bun's Android build is currently not supported
1
+ # Single-file executable bootstrap
4
2
 
5
- # Usage
6
- - First run `bun ./packAssets.sh` to bundle the assets into `assets.tar`
7
- - Then run the build script like this
3
+ Bundles a project's runtime assets into one `bun build --compile` binary, so
4
+ the executable carries its own `static/`, templates, documentation and so on.
8
5
 
9
- ```shell
10
- bun build --compile --bytecode --minify ./entry.mjs --outfile=binname
11
- ```
6
+ Assets are declared once, in `package.json`:
12
7
 
13
- - You'll get a binname executable
8
+ ```json
9
+ {
10
+ "assets": ["static", "README.md", "README.en.md"]
11
+ }
12
+ ```
13
+
14
+ Paths are relative to the project root. Folders are packed recursively; only
15
+ regular files are stored, so symlinks and empty folders leave no trace.
16
+
17
+ ## The two back ends
18
+
19
+ The default packs everything into a gzipped `assets.tar` that is embedded as a
20
+ single file and unpacked into memory at startup. Setting `ASSETS_BUNFS=1` at
21
+ build time switches to `bun build --compile --asset`, which stores the files
22
+ individually inside the binary's virtual filesystem instead.
23
+
24
+ Reading code never sees the difference — `assetsHelper` answers the same keys
25
+ either way. The trade is binary size against startup cost:
26
+
27
+ | | tar (default) | `ASSETS_BUNFS=1` |
28
+ | --- | --- | --- |
29
+ | Stored as | one gzipped archive | individual files, uncompressed |
30
+ | Size, for jsgotty's 3.45 MB of assets | **0.70 MB** | 3.45 MB |
31
+ | Work before `main` runs | decode the archive, copy every file into memory | **none** |
32
+ | Startup cost, same assets | ~16 ms | **0 ms** |
33
+ | Resident memory | whole payload, always | only what is read |
34
+ | Maturity | in use | experimental |
14
35
 
15
- # Single Executable Intro
36
+ Text compresses well, so the tar usually wins on size by a wide margin — for
37
+ jsgotty most of the payload is `static/`, whose JavaScript and CSS shrink to a
38
+ fifth. What it costs is paid on every run, whether or not the program touches a
39
+ single asset. Reach for `ASSETS_BUNFS=1` when that startup work, or holding the
40
+ whole payload in memory, matters more than the extra megabytes on disk.
16
41
 
17
- This folder contains the Bun single-exe bootstrap used by the project.
42
+ ## Adopting it in another project
18
43
 
19
- ## Entry Flow
44
+ Copy `single-exe/` to the project root. Nothing inside it hard-codes its own
45
+ name or depth, so it can be renamed or moved — but the importing code has to
46
+ follow, so staying at the root is the easy path. Three edits point it at the
47
+ project around it.
20
48
 
21
- - `entry.mjs` imports `assetsLoader.mjs` first
22
- - `assetsLoader.mjs` loads `assets.tar` with `Bun.Archive` and mounts it as `globalThis.internalAssets`
23
- - `assetsLoaderPromise` is exposed on `globalThis`
24
- - The main program waits for `assetsLoaderPromise` if it exists
49
+ 1. **`assetsPacker.js`, the first two lines.** They are the only place the
50
+ asset root is written down, and a static import specifier cannot be
51
+ computed, so both must be literal:
25
52
 
26
- That keeps the main program bootable even if asset loading reports errors.
53
+ ```js
54
+ import pkg from "../package.json" with { type: "json" };
55
+ export const ASSETS_ROOT = "..";
56
+ ```
27
57
 
28
- ## Assets Loading
58
+ 2. **`entry.mjs`, the last import.** It names the program to start. Build
59
+ also reads this line to find the entry point for `ASSETS_BUNFS=1`, so keep
60
+ it as the final import in the file:
29
61
 
30
- - Bundled assets are loaded sequentially with `await file.bytes()`
31
- - Load failures are collected and printed to `stderr`
32
- - Asset loading never rejects the bootstrap promise
33
- - When loading succeeds, the archive is available through `globalThis.internalAssets`
62
+ ```js
63
+ await import("../src/index.js");
64
+ ```
34
65
 
35
- ## CLI Flags
66
+ 3. **`package.json`.** Add the `assets` array shown above.
36
67
 
37
- - `--assets-list`
38
- - Lists all entries inside bundled `assets.tar`
39
- - Exits early before the main program starts
68
+ Everything else — `compiled.js`, `assetsHelper.js`, `assetsLoader.mjs` — is
69
+ project independent, with one exception: `buildHtmlBundleImageMap` defaults its
70
+ attribute name to jsmdcui's `data-mdcui-src`, so pass your own.
40
71
 
41
- - `--assets-extract`
42
- - Extracts bundled assets to the same directory as the executable
43
- - Exits early before the main program starts
72
+ Node's own entry path must not import `assetsLoader.mjs` or `entry.mjs`; those
73
+ are Bun only. `assetsHelper.js` and `compiled.js` run under Node 20.11+.
44
74
 
45
- - `--assets-external`
46
- - Skips loading bundled assets into `globalThis.internalAssets`
47
- - Forces the main program and runtime helpers to use the external file tree
48
- - Keeps the bootstrap alive while leaving `internalAssets` falsy
75
+ ## Reading assets
49
76
 
50
- ## Adapting this folder
77
+ Import from `assetsHelper.js`. Keys are the same package-relative paths that
78
+ appear in `package.json`.
51
79
 
52
- This single-exe folder is intended for reuse by other projects. Usually you
53
- only need to edit these project-specific files first:
80
+ | Function | Returns |
81
+ | --- | --- |
82
+ | `readInternalAssetText(path)` | string, or `null` when not embedded |
83
+ | `readInternalAssetBytes(path)` | `Uint8Array`, or `null` |
84
+ | `readAssetText(path)` | string, falling back to the file on disk |
85
+ | `readAssetBytes(path)` | `Uint8Array`, same fallback |
86
+ | `hasInternalAssets()` | whether this package has anything embedded |
87
+ | `listInternalAssetPaths(prefix?)` | every embedded path under `prefix` |
88
+ | `listInternalAssetDirs(prefix?)` | the immediate child names under `prefix` |
89
+ | `assetPath(...parts)` | joins parts into a key |
90
+ | `SELF` | this package's namespace, `assets/<name>@<version>` |
54
91
 
55
- - `entry.mjs`
56
- - `packAssets.sh`
92
+ The read functions are synchronous for embedded assets on both back ends.
93
+ `readAssetText` / `readAssetBytes` are async only because of the disk
94
+ fallback, which is what makes the same code work from a source checkout.
57
95
 
58
- Then the main program can import `buildEarlyExit` from `compiled.js` and call
59
- it before normal CLI parsing. `--build-exe` and `--build-for <target>` will run
60
- `packAssets.sh` first, so `assets.tar` is generated as part of the build flow.
96
+ **Only the read functions fall back to disk.** The listing functions report
97
+ what is embedded and nothing else, so from a source checkout they return an
98
+ empty array. Branch on `hasInternalAssets()` and read the directory yourself:
61
99
 
62
100
  ```js
63
- const compiledHelper = await import("./single-exe/compiled.js").catch(() => null);
64
- await compiledHelper?.buildEarlyExit?.(process.argv, "my-bin");
101
+ import { readdirSync } from "node:fs";
102
+ import { join } from "node:path";
103
+ import { readAssetText, hasInternalAssets, listInternalAssetDirs } from "../single-exe/assetsHelper.js";
104
+ import { REPO_ROOT } from "../single-exe/compiled.js";
105
+
106
+ // Embedded or on disk, this one already works either way.
107
+ const index = await readAssetText("static/index.html");
108
+
109
+ // Listing does not, so pick the source.
110
+ const staticDirs = hasInternalAssets()
111
+ ? listInternalAssetDirs("static")
112
+ : readdirSync(join(REPO_ROOT, "static"));
65
113
  ```
66
114
 
67
- - `--build-exe` builds with no Bun target.
68
- - `--build-for <target>` passes `<target>` to `bun build --target=<target>`.
69
- - The second argument is the output filename. If omitted, it defaults to `single.exe`.
115
+ ## Building
70
116
 
71
- The main program should also switch its repo/resource root when running as a
72
- compiled binary. Use `IS_COMPILED` and `REPO_ROOT` from
73
- `compiled.js`; when compiled, treat the executable directory as the repo root
74
- used for external fallback files such as `static/`, `README.md`, or other files
75
- packed by `packAssets.sh`.
117
+ `compiled.js` exports the build entry points. Wire `buildEarlyExit` into the
118
+ CLI and it handles `--build-exe` and `--build-for <target>`:
76
119
 
77
120
  ```js
78
- const compiledHelper = await import("./single-exe/compiled.js").catch(() => null);
79
- const repoRoot = compiledHelper?.REPO_ROOT
121
+ import { buildEarlyExit, IS_COMPILED, REPO_ROOT } from "./single-exe/compiled.js";
122
+
123
+ await buildEarlyExit(process.argv, "myapp");
124
+ ```
125
+
126
+ `REPO_ROOT` is the project root in a checkout and the executable's own folder
127
+ once compiled, which is where `--assets-extract` writes. `IS_COMPILED` tells
128
+ the two apart.
129
+
130
+ ### Chaining file/folder assets across dependencies
131
+
132
+ A build first bundles once to write a metafile, then treats every
133
+ `assetsPacker.js` appearing in its `inputs` as a participant. Each package
134
+ vendors its own `single-exe/`, and its `assetsHelper` imports its
135
+ `assetsPacker`, so a packer lands in that graph exactly when the package is
136
+ reachable from the entry point. There is no registration step, and anything
137
+ tree-shaken away brings nothing with it.
138
+
139
+ The packers then run one after another, each adding its files under its own
140
+ `assets/<name>@<version>/` namespace — appending into the shared `assets.tar`
141
+ by default, or copying into the shared `build/assets` tree under
142
+ `ASSETS_BUNFS=1`. Only once every packer has finished does the real compile
143
+ run, so the archive is complete and, by default, compressed by then.
144
+
145
+ That namespace is why `ASSETS_BUNFS=1` stages every package into one fixed
146
+ `build/assets`. `--asset` keeps only the **basename** of the path it is given
147
+ and preserves everything below it, so the folder's own name becomes the root
148
+ inside the binary:
149
+
150
+ ```
151
+ --asset ./build/assets with build/assets/jsgotty@1.1.6/static/index.html
152
+ -> assets/jsgotty@1.1.6/static/index.html
153
+ ```
154
+
155
+ Pass `./build/assets/jsgotty@1.1.6` instead and `build/assets/` is gone: the
156
+ files land at `jsgotty@1.1.6/...` and every package gets its own root. One
157
+ folder named `assets`, everyone copying into it, is what makes the keys come
158
+ out the same as the ones the tar back end writes.
159
+
160
+ `assetsPacker.js` also runs standalone; `--help` documents its flags.
161
+
162
+ ## Why the loader hands over a Promise
163
+
164
+ `entry.mjs` imports `assetsLoader.mjs`, awaits `globalThis.assetsLoaderPromise`,
165
+ and only then imports the main program. The indirection is deliberate: the
166
+ loader carries a Bun-only import,
167
+
168
+ ```js
169
+ import assets from "./assets.tar" with { type: "file" };
170
+ ```
171
+
172
+ and if the main program imported the loader, that dependency would land in its
173
+ module graph. Node could then no longer load the program at all — not even to
174
+ fall back to reading the assets from disk.
175
+
176
+ Keeping the loader behind `entry.mjs` means the main program never mentions it,
177
+ so Node 20.11+ runs the same file directly against on-disk assets while Bun
178
+ runs it through the bootstrap. The Promise is that boundary, not a workaround
179
+ for missing top-level await.
180
+
181
+ `ASSETS_BUNFS=1` sidesteps the question: with no tar to load, the build skips
182
+ `entry.mjs` and compiles the main program as its own entry point.
183
+
184
+ ## Environment variables
185
+
186
+ | Variable | When | Effect |
187
+ | --- | --- | --- |
188
+ | `ASSETS_BUNFS=1` | build | use `--asset` instead of the tar |
189
+ | `ASSETS_NO_GZIP=1` | build | leave `assets.tar` uncompressed |
190
+ | `ASSETS_DEBUG=1` | run | print how long unpacking took |
191
+
192
+ ## Runtime flags
193
+
194
+ | Flag | Effect |
195
+ | --- | --- |
196
+ | `--assets-list` | print every embedded path and exit |
197
+ | `--assets-extract` | write the assets next to the executable and exit |
198
+ | `--assets-external` | ignore embedded assets and read from disk |
199
+
200
+ These are handled by `assetsLoader.mjs`, so they exist in tar builds only.
201
+
202
+ ## Advanced usage
203
+
204
+ ### Forwarding arguments to `bun build`
205
+
206
+ Anything after `--build-exe`, or after the target given to `--build-for`, is
207
+ passed straight through to `bun build`:
208
+
209
+ ```shell
210
+ bun ./gotty.js --build-exe --sourcemap
211
+ bun ./gotty.js --build-for bun-linux-x64 --sourcemap
212
+ ```
213
+
214
+ Order matters. The flags have to come after the build switch, or Bun consumes
215
+ them before the program ever starts:
216
+
217
+ ```shell
218
+ # Wrong: Bun parses this define before any of your code runs
219
+ bun --define MY_APP=../app.md ./gotty.js --build-exe
220
+
221
+ # Right
222
+ bun ./gotty.js --build-exe --define MY_APP=../app.md
223
+ ```
224
+
225
+ ### `--define` with a string value
226
+
227
+ **Bun expects `--define` values to be JSON literals, so a string has to arrive
228
+ already quoted.** A bare path is read as an identifier and the build fails or
229
+ inlines something unintended. Quoting it through a shell is awkward, so
230
+ `compiled.js` exports a helper that does it:
231
+
232
+ ```js
233
+ import { buildEarlyExit, stringifyNonPrimitiveDefineValues } from "./single-exe/compiled.js";
234
+
235
+ stringifyNonPrimitiveDefineValues(process.argv, "MY_APP");
236
+ await buildEarlyExit(process.argv, "my-bin");
237
+ ```
238
+
239
+ Call it before `buildEarlyExit`, once per define name you want treated as a
240
+ string. It rewrites the value in place:
241
+
242
+ ```js
243
+ ["--define", "MY_APP=../app.md"] // what the user typed
244
+ ["--define", 'MY_APP="../app.md"'] // what Bun receives
245
+ ```
246
+
247
+ `--define=MY_APP=../app.md` works the same way. Numbers, booleans, `null` and
248
+ `undefined` are left alone, so only genuine strings get quoted.
249
+
250
+ ### Images from an imported HTML bundle
251
+
252
+ A compiled binary exposes an imported HTML entry as a `homepage` object:
253
+ `homepage.index` is the compiled HTML and `homepage.files` lists the
254
+ content-hashed assets by their path inside the binary. `assetsHelper` can map
255
+ the *original* image references back to those paths, without copying any image
256
+ bytes into memory.
257
+
258
+ Bun rewrites `src` during the build, so keep the original reference in a custom
259
+ attribute of your own choosing:
260
+
261
+ ```html
262
+ <!-- source -->
263
+ <img src="./images/photo.jpg" data-original-image="./images/photo.jpg">
264
+
265
+ <!-- compiled -->
266
+ <img src="/photo-abcd1234.jpg" data-original-image="./images/photo.jpg">
267
+ ```
268
+
269
+ Then build the map once, in a compiled binary only:
270
+
271
+ ```js
272
+ import { buildHtmlBundleImageMap, canonicalHtmlBundleImageHref } from "../single-exe/assetsHelper.js";
273
+ import { IS_COMPILED } from "../single-exe/compiled.js";
274
+
275
+ const images = IS_COMPILED
276
+ ? await buildHtmlBundleImageMap(homepage, "data-original-image")
277
+ : null;
278
+
279
+ const path = images?.get(canonicalHtmlBundleImageHref(originalHref));
280
+ const bytes = path ? await Bun.file(path).bytes() : null;
281
+ ```
282
+
283
+ `buildHtmlBundleImageMap` returns a `Map` from canonical original reference to
284
+ the path inside the binary; it decodes HTML entities and percent encoding so a
285
+ reference written either way still matches. Reading stays lazy — the bytes are
286
+ only touched when you use the returned path.
287
+
288
+ Lower level, if you already hold a rewritten public path such as
289
+ `/photo-abcd1234.jpg`: `findHtmlBundleAsset(homepage, publicPath, options)`
290
+ finds its `homepage.files` entry, `findHtmlBundleImageAsset()` restricts that
291
+ to `image/*`, and `htmlBundleImageAssetPath()` returns just the path.
292
+
293
+ Never hard-code `/$bunfs/root/` or `B:/~BUN/`; always use the path that
294
+ `homepage.files` reports.
295
+
296
+ ## jsgotty specifics
297
+
298
+ The rest of this file is generic. These names belong to jsgotty itself and are
299
+ not reserved by the bootstrap — an adopting project picks its own.
300
+
301
+ Building is optional; running `bun gotty.js` from a checkout, as the root
302
+ `README.md` describes, remains the usual way to run jsgotty.
303
+
304
+ ```shell
305
+ bun ./gotty.js --build-exe
306
+ bun ./gotty.js --build-for bun-linux-x64
307
+ ```
308
+
309
+ Both produce `jsgt`: `gotty.js` calls `buildEarlyExit(process.argv, "jsgt")`
310
+ from `bootstrap()`, before any CLI parsing, so the build switches exit before
311
+ a server is ever started. Neither works from an already compiled binary.
312
+
313
+ The three packed entries — `static`, `README.md`, `README.en.md` — are what the
314
+ HTTP server hands out: `index.html`, `manifest.json`, `help.md`, the frontend
315
+ JavaScript and CSS, and the two READMEs behind the help pages.
316
+
317
+ ### The entry import calls an exported starter
318
+
319
+ `gotty.js` is CommonJS and starts itself from `require.main === module`. With
320
+ `entry.mjs` as the bundle's entry point that guard is inlined to `false`, so
321
+ the import cannot rely on it and calls the export instead:
322
+
323
+ ```js
324
+ const { bootstrap } = await import("../gotty.js");
325
+
326
+ await bootstrap();
327
+ ```
328
+
329
+ It is still the last import in the file, which is all `ASSETS_BUNFS=1` needs to
330
+ find the main program. In that mode `gotty.js` is compiled as the entry point
331
+ itself, Bun rewrites the guard to `import.meta.main` — true — and it starts
332
+ itself; the exported `bootstrap` then simply goes unused.
333
+
334
+ ### `packAssets.sh`
335
+
336
+ The original implementation, kept as a reference: a hand-written tar of the
337
+ three asset entries, from before `assetsPacker.js` and its `package.json`
338
+ declaration existed. `buildExecutable()` in `compiled.js` is the matching
339
+ build path and still runs it, but `buildExe` now points at `buildExeAssets`,
340
+ so nothing in the current flow calls either. It is the shortest way to see
341
+ what the packer produces, and it still packs an `assets.tar` by hand:
342
+
343
+ ```shell
344
+ bun ./single-exe/packAssets.sh
345
+ bun build --compile --bytecode --minify ./single-exe/entry.mjs --outfile=jsgt
80
346
  ```
@@ -1,8 +1,50 @@
1
+ import { join, posix, sep } from "node:path";
2
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
3
+ import { readFile } from "node:fs/promises";
4
+ import { IS_COMPILED, REPO_ROOT } from "./compiled.js";
5
+ import { pkg } from "./assetsPacker.js";
6
+
1
7
  const textDecoder = new TextDecoder();
2
8
  const textEncoder = new TextEncoder();
3
9
 
10
+ // This package own namespace inside a shared archive. Matches what
11
+ // `assetsPacker -p` writes, and what `--asset ./build/assets` lands at
12
+ // under /$bunfs/root, so one key reaches either back end.
13
+ export const SELF = `assets/${pkg.name}@${pkg.version}`;
14
+
15
+ // "" when this build packed flat keys, SELF when it packed namespaced
16
+ // ones. Detected from what is actually there rather than declared by a
17
+ // build flag, which can disagree with the packer and fail silently.
18
+ //
19
+ // NOTE: nothing reads this yet; the lookups below are still flat.
20
+ //
21
+ // Lazy because the tar back end fills globalThis.internalAssets
22
+ // asynchronously, so module-load time is too early to look.
23
+ let detectedPrefix;
24
+
25
+ export function assetPrefix() {
26
+ if (detectedPrefix === undefined) detectedPrefix = detectPrefix();
27
+ return detectedPrefix;
28
+ }
29
+
30
+ function detectPrefix() {
31
+ const store = getAssetStore();
32
+
33
+ if (store) {
34
+ const keys = store instanceof Map ? store.keys() : Object.keys(store);
35
+ for (const key of keys) if (key.startsWith(SELF + "/")) return SELF;
36
+ }
37
+
38
+ if (IS_COMPILED && existsSync(join(import.meta.dir, SELF))) return SELF;
39
+
40
+ return "";
41
+ }
42
+
43
+ // Whether THIS package has anything embedded. A bare store check was
44
+ // true even for an empty one, which sent every caller down the internal
45
+ // branch to find nothing and never try the disk fallback.
4
46
  export function hasInternalAssets() {
5
- return Boolean(getAssetStore());
47
+ return listInternalAssetPaths().length > 0;
6
48
  }
7
49
 
8
50
  export function assetPath(...parts) {
@@ -12,18 +54,162 @@ export function assetPath(...parts) {
12
54
  .join("/");
13
55
  }
14
56
 
57
+ export function decodeHtmlAttribute(value) {
58
+ return String(value ?? "").replace(
59
+ /&(?:amp|quot|apos|lt|gt|#39|#x27|#\d+|#x[\da-f]+);/gi,
60
+ (entity) => {
61
+ const named = {
62
+ "&amp;": "&",
63
+ "&quot;": "\"",
64
+ "&apos;": "'",
65
+ "&lt;": "<",
66
+ "&gt;": ">",
67
+ "&#39;": "'",
68
+ "&#x27;": "'",
69
+ }[entity.toLowerCase()];
70
+ if (named != null) return named;
71
+ const hex = /^&#x([\da-f]+);$/i.exec(entity);
72
+ const decimal = /^&#(\d+);$/.exec(entity);
73
+ const codePoint = Number.parseInt(hex?.[1] ?? decimal?.[1] ?? "", hex ? 16 : 10);
74
+ try {
75
+ return Number.isInteger(codePoint) ? String.fromCodePoint(codePoint) : entity;
76
+ } catch {
77
+ return entity;
78
+ }
79
+ },
80
+ );
81
+ }
82
+
83
+ export function canonicalHtmlBundleImageHref(input, { htmlAttribute = false } = {}) {
84
+ let value = String(input ?? "");
85
+ if (htmlAttribute) value = decodeHtmlAttribute(value);
86
+ try {
87
+ return decodeURIComponent(value);
88
+ } catch {
89
+ return value;
90
+ }
91
+ }
92
+
93
+ export function findHtmlBundleAsset(homepage, publicPath, {
94
+ contentTypePrefix = "",
95
+ } = {}) {
96
+ if (!Array.isArray(homepage?.files)) return null;
97
+ const name = posix.basename(String(publicPath ?? "").replace(/[?#].*$/, ""));
98
+ for (const file of homepage.files) {
99
+ if (file?.loader !== "file") continue;
100
+ const contentType = String(file.headers?.["content-type"] ?? "");
101
+ if (contentTypePrefix && !contentType.startsWith(contentTypePrefix)) continue;
102
+ if (posix.basename(String(file.path ?? "")) === name) return file;
103
+ }
104
+ return null;
105
+ }
106
+
107
+ export function findHtmlBundleImageAsset(homepage, publicPath) {
108
+ return findHtmlBundleAsset(homepage, publicPath, {
109
+ contentTypePrefix: "image/",
110
+ });
111
+ }
112
+
113
+ export function htmlBundleImageAssetPath(homepage, publicPath) {
114
+ return findHtmlBundleImageAsset(homepage, publicPath)?.path ?? null;
115
+ }
116
+
117
+ export async function buildHtmlBundleImageMap(
118
+ homepage,
119
+ sourceAttribute = "data-mdcui-src",
120
+ ) {
121
+ const images = new Map();
122
+ if (!homepage?.index || !Array.isArray(homepage.files)) return images;
123
+ const html = await Bun.file(homepage.index).text();
124
+ for (const tag of html.match(/<img\b[^>]*>/gi) ?? []) {
125
+ const rawHref = htmlTagAttribute(tag, sourceAttribute);
126
+ const publicPath = htmlTagAttribute(tag, "src");
127
+ if (rawHref == null || publicPath == null) continue;
128
+ const bundledPath = htmlBundleImageAssetPath(homepage, decodeHtmlAttribute(publicPath));
129
+ if (!bundledPath) continue;
130
+ images.set(
131
+ canonicalHtmlBundleImageHref(rawHref, { htmlAttribute: true }),
132
+ bundledPath,
133
+ );
134
+ }
135
+ return images;
136
+ }
137
+
138
+ // `bun build --compile --asset` puts the files at real paths under
139
+ // import.meta.dir instead of into the tar map. Only in a compiled
140
+ // binary: in the source tree this file sits in single-exe/, which is
141
+ // not the asset root.
142
+ function bunfsBase() {
143
+ return IS_COMPILED ? import.meta.dir : null;
144
+ }
145
+
146
+ // Store-space keys for every regular file under <base>/<sub>.
147
+ //
148
+ // NOTE: with no namespace, <sub> is "" and the scan starts at
149
+ // /$bunfs/root, which also holds the executable and any file-loader
150
+ // assets. Nothing marks those apart from real assets, so pack with -p
151
+ // when the --asset back end is in play.
152
+ function walkBunfs(base, sub) {
153
+ const dir = sub ? join(base, sub) : base;
154
+
155
+ let names;
156
+ try {
157
+ names = readdirSync(dir, { recursive: true });
158
+ } catch {
159
+ return [];
160
+ }
161
+
162
+ const out = [];
163
+
164
+ for (const name of names) {
165
+ const rel = String(name).split(sep).join("/");
166
+
167
+ try {
168
+ if (!statSync(join(dir, String(name))).isFile()) continue;
169
+ } catch {
170
+ continue;
171
+ }
172
+
173
+ out.push(sub ? `${sub}/${rel}` : rel);
174
+ }
175
+
176
+ return out;
177
+ }
178
+
179
+ // Callers always speak package-relative keys. This is the one place
180
+ // those become store keys, so the namespace stays invisible to them.
181
+ function storeKey(path) {
182
+ const key = assetPath(path);
183
+ const at = assetPrefix();
184
+ return at ? (key ? `${at}/${key}` : at) : key;
185
+ }
186
+
15
187
  export function listInternalAssetPaths(prefix = "") {
188
+ const at = assetPrefix();
189
+ const wanted = storeKey(prefix);
16
190
  const store = getAssetStore();
17
- if (!store) return [];
191
+ const found = new Set();
18
192
 
19
- const normalizedPrefix = assetPath(prefix);
20
- const entries = iterateAssetKeys(store);
21
- if (!normalizedPrefix) {
22
- return entries.sort();
193
+ if (store) for (const key of iterateAssetKeys(store)) found.add(key);
194
+
195
+ const base = bunfsBase();
196
+ if (base) for (const key of walkBunfs(base, wanted)) found.add(key);
197
+
198
+ let entries = [...found];
199
+
200
+ if (wanted) {
201
+ const base = `${wanted}/`;
202
+ entries = entries.filter((path) => path === wanted || path.startsWith(base));
203
+ }
204
+
205
+ // Hand the namespace back off on the way out, or every caller that
206
+ // matches on the returned paths would have to know about it.
207
+ if (at) {
208
+ const cut = at.length + 1;
209
+ entries = entries.filter((path) => path.startsWith(at + "/")).map((path) => path.slice(cut));
23
210
  }
24
211
 
25
- const base = `${normalizedPrefix}/`;
26
- return entries.filter((path) => path === normalizedPrefix || path.startsWith(base)).sort();
212
+ return entries.sort();
27
213
  }
28
214
 
29
215
  export function listInternalAssetDirs(prefix = "") {
@@ -41,11 +227,24 @@ export function listInternalAssetDirs(prefix = "") {
41
227
  }
42
228
 
43
229
  export function getInternalAsset(path) {
230
+ const key = storeKey(path);
231
+
44
232
  const store = getAssetStore();
45
- if (!store) return null;
46
- const key = assetPath(path);
47
- if (store instanceof Map) return store.get(key) ?? null;
48
- return store[key] ?? store[path] ?? null;
233
+ if (store) {
234
+ const hit = store instanceof Map ? store.get(key) : (store[key] ?? store[path]);
235
+ if (hit != null) return hit;
236
+ }
237
+
238
+ // Tar first so an existing build keeps its exact behaviour; the
239
+ // --asset back end answers whatever the tar does not hold.
240
+ const base = bunfsBase();
241
+ if (base) {
242
+ try {
243
+ return readFileSync(join(base, key));
244
+ } catch {}
245
+ }
246
+
247
+ return null;
49
248
  }
50
249
 
51
250
  export function readInternalAssetBytes(path) {
@@ -66,6 +265,30 @@ export function readInternalAssetText(path) {
66
265
  return textDecoder.decode(bytes);
67
266
  }
68
267
 
268
+ // The fallback reads through node:fs so the same call works under plain
269
+ // Node, which is the whole point of keeping the loader out of the main
270
+ // program's module graph.
271
+ export async function readAssetText(path) {
272
+ const internal = readInternalAssetText(path);
273
+ if (internal != null) return internal;
274
+
275
+ // TextDecoder drops a leading BOM, so the embedded path never returns
276
+ // one; readFile keeps it. Strip it here or the same file reads
277
+ // differently depending on whether it was embedded.
278
+ return (await readFile(join(REPO_ROOT, path), "utf8")).replace(/^\uFEFF/, "");
279
+ }
280
+
281
+ export async function readAssetBytes(path) {
282
+ const internal = readInternalAssetBytes(path);
283
+ if (internal) return internal;
284
+
285
+ const buf = await readFile(join(REPO_ROOT, path));
286
+
287
+ // Buffer is a Uint8Array, but hand back a plain one so callers cannot
288
+ // come to depend on the Buffer-only methods.
289
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
290
+ }
291
+
69
292
  export function internalAssetSource(path) {
70
293
  return {
71
294
  name: path.split("/").pop() ?? path,
@@ -88,3 +311,9 @@ function iterateAssetKeys(store) {
88
311
  if (store instanceof Map) return [...store.keys()].map(String);
89
312
  return Object.keys(store);
90
313
  }
314
+
315
+ function htmlTagAttribute(tag, name) {
316
+ const escapedName = String(name).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
317
+ const match = String(tag).match(new RegExp(`\\b${escapedName}\\s*=\\s*([\"'])(.*?)\\1`, "i"));
318
+ return match?.[2] ?? null;
319
+ }
@@ -2,7 +2,7 @@ import assets from "./assets.tar" with { type: "file" };
2
2
  import { getExeDirname, isCompiledBinary } from "./compiled.js";
3
3
 
4
4
  const forceExternalAssets = process.argv.includes("--assets-external");
5
- const debugAssetsLoader = Boolean(process.env.BUNMICRO_DEBUG);
5
+ const debugAssetsLoader = Boolean(process.env.ASSETS_DEBUG);
6
6
  if (forceExternalAssets) {
7
7
  const flagIndex = process.argv.indexOf("--assets-external");
8
8
  if (flagIndex >= 0) process.argv.splice(flagIndex, 1);
@@ -0,0 +1,218 @@
1
+ #!/usr/bin/env bun
2
+
3
+ // Change these 2 lines for
4
+ // the relative assets root if needed
5
+ import pkg from "../package.json" with { type: "json" };
6
+ export { pkg };
7
+ export const ASSETS_ROOT = "..";
8
+
9
+ import path from "node:path";
10
+ import { existsSync } from "node:fs";
11
+ import { cpSync, mkdirSync, readdirSync, rmSync, statSync } from "node:fs";
12
+
13
+ const PKG_ROOT = path.resolve(import.meta.dirname, ASSETS_ROOT);
14
+
15
+ if (import.meta.main) {
16
+ if (process.argv.includes("-h") || process.argv.includes("--help")) {
17
+ const help = `
18
+ # Single-file executable assets packer
19
+
20
+ Packs the \`assets\` list from \`package.json\`, folders recursively.
21
+ Reads \`${pkg.name}@${pkg.version}\` from \`../package.json\`.
22
+
23
+ ## Options
24
+
25
+ - \`-f PATH\` — where to pack to. Defaults to \`./assets.tar\`
26
+ - a \`.tar\` file picks tar mode
27
+ - an existing folder picks folder mode
28
+ - \`-r\` \`--append\` — merge into an existing archive instead of replacing it
29
+ - a repacked path *replaces* its member rather than duplicating it,
30
+ unlike real \`tar -r\`
31
+ - use it for every step of a multi-package relay
32
+ - \`-p [PREFIX]\` — namespace this package's members inside a shared archive
33
+ - bare \`-p\` means \`assets/${pkg.name}@${pkg.version}\`
34
+ - omit it for a single-project build, which keeps the flat key space
35
+ - \`--dry\` — print the resolved settings and exit without writing
36
+ - \`-h\` \`--help\` — this text
37
+
38
+ ## Two modes, one key space
39
+
40
+ - **tar mode** feeds \`import x from "./assets.tar" with { type: "file" }\`
41
+ - **folder mode** feeds \`bun build --compile --asset ./build/assets\`
42
+ - the folder must already exist
43
+ - \`--asset\` keeps only the basename of the path it is given, so pass the
44
+ assets root itself: \`-f /path/to/build/assets\` puts this package under
45
+ \`build/assets/${pkg.name}@${pkg.version}/\`
46
+
47
+ tar mode with \`-p\` and folder mode into \`build/assets\` produce the same keys,
48
+ so \`assetsHelper\` reads either back end with one set of paths.
49
+ `;
50
+
51
+ console.log(Bun?.markdown?.ansi?.(help) ?? help);
52
+ } else {
53
+ await main();
54
+ }
55
+ }
56
+
57
+ export async function main(argv = process.argv) {
58
+ console.log("Packing", pkg.name + "@" + pkg.version);
59
+
60
+ let aindex = argv.indexOf("-f");
61
+
62
+ const appendMode = argv.includes("-r") || argv.includes("--append");
63
+
64
+ // Namespace for this package's members inside a shared archive.
65
+ // "-p" alone means `assets/<name>@<version>`, matching what
66
+ // `bun build --compile --asset ./build/assets` puts in /$bunfs/root
67
+ // (that flag keeps only the basename of the path it is given), so
68
+ // both back ends answer to the same keys. Empty (the default) keeps
69
+ // the flat key space a single-project build expects.
70
+ let pindex = argv.indexOf("-p");
71
+ if (pindex == -1) pindex = argv.indexOf("--prefix");
72
+
73
+ const prefix =
74
+ pindex == -1
75
+ ? ""
76
+ : (argv[pindex + 1] ?? "").startsWith("-") || argv[pindex + 1] == null
77
+ ? `assets/${pkg.name}@${pkg.version}`
78
+ : argv[pindex + 1];
79
+
80
+ // A missing value would silently resolve the next flag as a filename
81
+ // ("-f -r" -> <cwd>/-r), so refuse it rather than pack somewhere odd.
82
+ if (aindex != -1 && (argv[aindex + 1] == null || argv[aindex + 1].startsWith("-"))) {
83
+ console.error("-f needs a file or folder path");
84
+ return 2;
85
+ }
86
+
87
+ // Resolved against the caller's cwd so every later consumer agrees on
88
+ // what it points at: `mkdir` runs in the process cwd while the copy
89
+ // loop runs in PKG_ROOT, and a relative -f would mean two places.
90
+ const archive = aindex == -1 ? path.join(import.meta.dir, "assets.tar") : path.resolve(argv[aindex + 1]);
91
+
92
+ const folderMode = existsSync(archive) && !(await Bun.file(archive).exists());
93
+
94
+ const folderPath = folderMode ? path.join(archive, pkg.name + "@" + pkg.version) : "";
95
+
96
+ console.log({
97
+ appendMode,
98
+ archive,
99
+ prefix,
100
+ folderMode,
101
+ folderPath,
102
+ PKG_ROOT,
103
+ assets: pkg.assets,
104
+ });
105
+
106
+ if (argv.includes("--dry")) return 0;
107
+
108
+ if (folderMode) await Bun.$`mkdir -p ${folderPath}`;
109
+
110
+ // No assets field in package.json
111
+ if (!Array.isArray(pkg.assets) || pkg.assets.length == 0) {
112
+ console.error("Nothing to pack!");
113
+
114
+ if (folderMode) {
115
+ console.error("Defaults to package.json");
116
+ await Bun.write(path.join(folderPath, "package.json"), JSON.stringify(pkg, null, 1));
117
+ } // assets.tar mode
118
+ else {
119
+ const file = Bun.file(archive);
120
+
121
+ // Leave a real archive alone; only stand one up when it is
122
+ // missing (or the zero-byte file that is not a valid tar), so
123
+ // entry.mjs's `with { type: "file" }` import still resolves.
124
+ if ((await file.exists()) && file.size > 0) return 0;
125
+
126
+ console.error("Writing a placeholder assets tar");
127
+
128
+ await Bun.Archive.write(archive, {
129
+ [`assets/${pkg.name}@${pkg.version}/package.json`]: JSON.stringify(pkg, null, 1),
130
+ });
131
+ }
132
+ } // assets present in package.json
133
+ else {
134
+ if (folderMode) {
135
+ // Mirror the asset's own relative path, so the folder layout
136
+ // matches the tar layout. `cp -R src/cui/server.mjs <dir>` would
137
+ // drop the src/cui/ prefix and land it as <dir>/server.mjs.
138
+ for (let i of pkg.assets) {
139
+ const dest = path.join(folderPath, i);
140
+
141
+ mkdirSync(path.dirname(dest), { recursive: true });
142
+ cpSync(path.join(PKG_ROOT, i), dest, { recursive: true });
143
+
144
+ console.log(i);
145
+ }
146
+ } // tar mode
147
+ else {
148
+ // Everything goes through Bun.Archive: system tar is not portable
149
+ // enough here (toybox has no -r at all, and its --xform exits 0
150
+ // while writing a corrupt file). Creating is appending to nothing.
151
+ if (!appendMode) rmSync(archive, { force: true });
152
+
153
+ return await tar_rvf(archive, pkg.assets, PKG_ROOT, prefix);
154
+ }
155
+ }
156
+ } // end of main
157
+
158
+ // Stands in for `tar -rvf`, which toybox tar does not implement.
159
+ // Reads the existing members, adds `filesArray` (paths relative to
160
+ // `cwd`, folders walked recursively), and writes the archive back.
161
+ // Unlike real tar -r, a repacked path replaces its member instead of
162
+ // becoming a second one with the same name.
163
+ //
164
+ // `prefix` is prepended to every member name. Member names are built
165
+ // here as plain strings, so this does not depend on tar's --transform
166
+ // (toybox's --xform is broken: it exits 0 and writes a corrupt file).
167
+ export async function tar_rvf(archive, filesArray, cwd, prefix = "") {
168
+ const entries = new Map();
169
+ const file = Bun.file(archive);
170
+ const at = prefix ? prefix.replace(/[\\/]+$/, "") + "/" : "";
171
+
172
+ if (await file.exists()) {
173
+ const bytes = await file.bytes();
174
+
175
+ if (bytes.byteLength > 0)
176
+ for (const [member, blob] of await new Bun.Archive(bytes).files()) entries.set(member, await blob.bytes());
177
+ }
178
+
179
+ for (const asset of filesArray) {
180
+ const full = path.join(cwd, asset);
181
+
182
+ // One unreadable path must not take the whole relay down.
183
+ let stat;
184
+ try {
185
+ stat = statSync(full);
186
+ } catch {
187
+ console.error(`Skipping unreadable asset: ${asset}`);
188
+ continue;
189
+ }
190
+
191
+ if (!stat.isDirectory()) {
192
+ entries.set(at + asset, await Bun.file(full).bytes());
193
+ console.log(at + asset);
194
+ continue;
195
+ }
196
+
197
+ for (const rel of readdirSync(full, { recursive: true })) {
198
+ const child = path.join(full, String(rel));
199
+
200
+ // statSync follows symlinks, so a dangling one throws here.
201
+ let childStat;
202
+ try {
203
+ childStat = statSync(child);
204
+ } catch {
205
+ continue;
206
+ }
207
+ if (!childStat.isFile()) continue;
208
+
209
+ const member = at + asset + "/" + String(rel).split(path.sep).join("/");
210
+ entries.set(member, await Bun.file(child).bytes());
211
+ console.log(member);
212
+ }
213
+ }
214
+
215
+ await Bun.Archive.write(archive, Object.fromEntries(entries));
216
+
217
+ return 0;
218
+ }
@@ -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();