jsgotty 1.1.6 → 1.1.8

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,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
+ "&": "&",
63
+ """: "\"",
64
+ "'": "'",
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
+ }