@gjsify/cli 0.49.0 → 0.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,671 @@
1
+ // The AppImage packer — ADR 0024 § A24, issue JumpLink/Learn6502#93.
2
+ //
3
+ // ADR 0024 § 9 DEFERRED this format, and the deferral is what this module has to
4
+ // answer rather than quietly outlive. Its argument: an AppImage promises *one
5
+ // file, no install, any distro*, and that promise holds only if the file carries
6
+ // everything the target is not guaranteed to have — for a GJS application that is
7
+ // GTK4, libadwaita, GJS itself and the typelibs. No relocatable Linux closure
8
+ // exists (`packages/node-gi/gtk-runtime-*` covers darwin and win32 and
9
+ // deliberately not linux, because on Linux GTK has always come from the distro),
10
+ // so a file built today takes its runtime from the host. § 9 called that "a
11
+ // tarball with a launcher, wearing the name of something that promises more".
12
+ //
13
+ // WHAT CHANGED IS NOT THE CLOSURE, IT IS WHAT THE ARTIFACT SAYS ABOUT ITSELF.
14
+ // Two of the three promises hold with no closure at all — *no install* and *no
15
+ // root* — and they are the two a `.deb`, an `.rpm` and a Flatpak between them
16
+ // cannot make on a machine whose distro is not yours and whose sudo you do not
17
+ // have. The third is the one that would be a lie if it were silent, so it is not
18
+ // silent: {@link appImageHostRequirements} derives what the file does NOT carry
19
+ // from the same scan the `.deb` beside it derives its `Depends:` from, `ship`
20
+ // PRINTS it at pack time, and {@link renderAppRun} puts the interpreter half
21
+ // inside the artifact as a refusal that names the missing runtime before the app
22
+ // dies on its first import. The day `@gjsify/gtk-runtime-linux-<arch>` exists the
23
+ // list shrinks to nothing and nothing else here changes — which is exactly the
24
+ // shape § 9 said would unblock it.
25
+ //
26
+ // THE TOOL IS THE HOST'S, and that is the repository's existing line rather than
27
+ // a new one. `.deb` and `.rpm` are written by this tree because they are
28
+ // containers — a table of contents over bytes already in hand. An AppImage is an
29
+ // ELF runtime with a squashfs filesystem concatenated onto it, and a filesystem
30
+ // writer is what ADR 0024 § A6 rejects by name for the `.dmg`: a project rather
31
+ // than a target, every mistake silent. So `appimagetool` is required on PATH, the
32
+ // way `flatpak-builder` is for a Flatpak and WiX is for an `.msi` on Windows —
33
+ // including the part of that precedent that looks unattractive, since neither
34
+ // Fedora nor Debian packages `appimagetool` and the install hint has to name a
35
+ // GitHub release. VENDORING IT IS REFUSED for the reason ADR 0023 refuses a
36
+ // from-source GTK: a binary in this tree is this tree's to license, to update and
37
+ // to have audited, and appimagetool is GPL-3.0 while gjsify is MIT in 185
38
+ // manifests. DOWNLOADING THE TOOL AT PACK TIME is refused for a different one:
39
+ // every other packer here runs offline, and a pack step that fetches is a release
40
+ // step that fails when GitHub does. The tool fetches its RUNTIME on its own
41
+ // account, which nearly made that refusal untrue in practice — see the first
42
+ // measurement below, and the pin that answers it.
43
+ //
44
+ // MEASURED ON appimagetool 1.9.1 (build 296, 2025-12-04), because three of its
45
+ // behaviours decide this file and none of them are in its `--help`:
46
+ //
47
+ // * IT FETCHES THE RUNTIME — it does NOT embed one, which the first draft of
48
+ // this header recorded as measured and which is the opposite of what it does.
49
+ // Re-measured on the version `.docker/ci-fedora.Dockerfile` pins (1.9.1, build
50
+ // 296, git 8c8c91f): every invocation prints `Downloading runtime file from
51
+ // …/type2-runtime/releases/download/continuous/runtime-<arch>` BEFORE
52
+ // "Embedding ELF…", for the host's own architecture as much as for a foreign
53
+ // one, caching nothing — four consecutive packs, four downloads. With the
54
+ // network blocked it exits 1 having written no file, naming `--runtime-file`.
55
+ // So the ~940 KB of ELF a user DOWNLOADS AND EXECUTES came from a ROLLING tag
56
+ // with no digest behind it while the Dockerfile pinned the tool that fetched
57
+ // it by SHA-256 — a pin with a hole under it — and two packs of one build
58
+ // agreed only because `continuous` had not moved between them. It moves:
59
+ // `continuous`'s `runtime-x86_64` and the dated `20251108` release's are the
60
+ // same 944632 bytes and different content.
61
+ // SO THE RUNTIME IS PINNED TOO ({@link findPinnedRuntime},
62
+ // {@link appImageToolArgs}) and an architecture without one is ANNOUNCED
63
+ // rather than refused ({@link appImageRuntimeNotice}) — declare rather than
64
+ // imply, the rule {@link appImageHostRequirements} already follows. Measured
65
+ // with a pin: the pack succeeds with the network blocked and two packs are
66
+ // byte-identical.
67
+ // * IT CANNOT GUESS OUR ARCHITECTURE. appimagetool reads the AppDir's binaries
68
+ // to decide, and a `--app gjs` payload is JavaScript and a `/bin/sh`
69
+ // launcher: there is no ELF to read. `ARCH` in the environment is therefore
70
+ // REQUIRED here, not a hint — see {@link appImageToolEnv}.
71
+ // * IT IS REPRODUCIBLE, GIVEN mtimes. Two builds a second apart are
72
+ // byte-identical (measured, sha256), and the squashfs superblock's creation
73
+ // time is already pinned to epoch 0 — but `touch`ing the AppDir changes the
74
+ // output, because mksquashfs stores per-file mtimes. `ship` promises
75
+ // byte-identical artifacts from one build, so {@link stampAppDirTimes} sets
76
+ // every path in the AppDir to the run's `mtime`, the same value `deb.ts`, `rpm.ts`
77
+ // and `zip.ts` write into their own headers.
78
+ //
79
+ // FUSE IS THE CLASSIC TRAP AND IT IS TWO TRAPS, on opposite sides of the pack:
80
+ //
81
+ // * BUILDING. `appimagetool` is itself distributed as an AppImage, so running
82
+ // it mounts a squashfs through libfuse — which a CI container without
83
+ // `/dev/fuse` cannot do, and the failure is `dlopen(): libfuse.so.2` or a
84
+ // bare exit 1 rather than anything about FUSE. {@link appImageToolEnv} sets
85
+ // `APPIMAGE_EXTRACT_AND_RUN=1` unconditionally: the AppImage runtime reads it
86
+ // and extracts itself to a temp directory instead of mounting, and a native
87
+ // `appimagetool` binary ignores an environment variable it does not read. So
88
+ // the FUSE-less path is the DEFAULT here rather than something a CI author
89
+ // has to know.
90
+ // * RUNNING. The artifact this writes mounts itself the same way, so a user on
91
+ // a FUSE-less host needs `--appimage-extract-and-run` (or
92
+ // `--appimage-extract`). That is the runtime's own flag and nothing here can
93
+ // remove it; what this file can do is make sure nobody reads the resulting
94
+ // silence as a broken build, which is why {@link buildAppImage}'s failure
95
+ // names FUSE and both escape hatches.
96
+ import { existsSync, utimesSync } from 'node:fs';
97
+ import { join, posix, sep } from 'node:path';
98
+ import { describeExit, spawnToCompletion } from '../spawn.js';
99
+ import { encodeUtf8 } from './bytes.js';
100
+ import { DEFAULT_GJS_FLOOR, DEFAULT_NODE_FLOOR, hostProvidedNamespaces } from './depends.js';
101
+ import { LAYOUTS } from './layout.js';
102
+ import { SHARE } from './share-dirs.js';
103
+ /** The tool this packer execs. One spelling, read by this module AND by the format row. */
104
+ export const APPIMAGE_TOOL = 'appimagetool';
105
+ /**
106
+ * The environment variable the AppImage runtime reads to extract instead of mount.
107
+ *
108
+ * Named rather than inlined because two different programs read it for two
109
+ * different reasons — `appimagetool` when this packer runs it, and the artifact
110
+ * when a user runs that — and the spec asserts on the pair.
111
+ */
112
+ export const EXTRACT_AND_RUN = 'APPIMAGE_EXTRACT_AND_RUN';
113
+ /**
114
+ * Where a PINNED AppImage runtime is looked for, and the variable that moves it.
115
+ *
116
+ * THE RUNTIME IS THE HALF OF THE ARTIFACT THIS TREE DOES NOT WRITE, and until it
117
+ * was pinned nothing pinned it: appimagetool fetches `runtime-<arch>` from
118
+ * `type2-runtime`'s ROLLING `continuous` tag on every pack (module header), so
119
+ * the ~940 KB of ELF a user downloads and executes arrived with no digest behind
120
+ * it, while `.docker/ci-fedora.Dockerfile` carefully pinned the tool that fetched
121
+ * it. Measured, and not a theoretical drift: `continuous`'s `runtime-x86_64` and
122
+ * the dated `20251108` release's differ in content at the same 944632 bytes.
123
+ *
124
+ * A DIRECTORY AND AN ENVIRONMENT VARIABLE, rather than a download this packer
125
+ * performs, because that is ADR 0024 § A25's rule applied one level down — a
126
+ * pack step that fetches is a release step that fails when GitHub does. The CI
127
+ * image puts a digest-checked file here; a workstation either does the same or
128
+ * takes the announced path below. Arch-named, `runtime-<arch>`, which is
129
+ * type2-runtime's own asset name, so pinning one is a copy and not a rename.
130
+ */
131
+ export const APPIMAGE_RUNTIME_DIR_ENV = 'GJSIFY_APPIMAGE_RUNTIME_DIR';
132
+ /** The default home for {@link APPIMAGE_RUNTIME_DIR_ENV}, which the CI image fills. */
133
+ export const APPIMAGE_RUNTIME_DIR = '/usr/local/share/gjsify/appimage-runtime';
134
+ /** The directory name the AppImage specification gives the tree appimagetool packs. */
135
+ const APPDIR_NAME = 'AppDir';
136
+ /** The entry point the AppImage runtime execs inside the mounted image. */
137
+ const APPRUN_NAME = 'AppRun';
138
+ /**
139
+ * The AppDir's thumbnail, and the reason this packer writes it rather than
140
+ * letting appimagetool do it.
141
+ *
142
+ * MEASURED, AS A REPRODUCIBILITY DEFECT, and it is the kind only a byte
143
+ * comparison finds: appimagetool creates `.DirIcon` as a SYMLINK to the root icon
144
+ * when the AppDir does not already have one, and it does that AFTER
145
+ * {@link stampAppDirTimes} has run — so the link carries the wall clock, the
146
+ * AppDir root directory's own mtime moves with it, and mksquashfs stores both.
147
+ * Two `gjsify ship --target appimage` runs over ONE build then differ in sha256
148
+ * while every listing, mode, size and byte of content is identical (measured: 965
149
+ * differing bytes, the first inside `.digest_md5`, because the embedded digest
150
+ * follows the filesystem it covers). Four packs over the SAME AppDir are
151
+ * byte-identical, which is what makes this a mutation of the tree rather than a
152
+ * nondeterministic packer.
153
+ *
154
+ * A REGULAR FILE and not a symlink, for `dmg.ts`'s reason: `writePayload` writes
155
+ * regular files and nothing else — a property `tests/e2e/ship` asserts, and one
156
+ * `actions/upload-artifact` would silently dereference anyway. squashfs
157
+ * deduplicates the second copy, so it costs an inode and no data.
158
+ */
159
+ export const DIR_ICON_NAME = '.DirIcon';
160
+ /**
161
+ * The one directory the staged prefix goes under inside the AppDir.
162
+ *
163
+ * Exported because `stampAppDirTimes` and the e2e reader both address paths
164
+ * through it, and a second `'usr'` literal is the kind that stays right until
165
+ * somebody changes the first one.
166
+ */
167
+ export const APPDIR_PREFIX_DIR = 'usr';
168
+ /**
169
+ * The extensions an AppDir root icon may have — a SET, deliberately not an order.
170
+ *
171
+ * Which of two candidates wins is `rootIconRank`'s question and is answered by
172
+ * the hicolor CONTEXT, not by the file type; the first draft of this constant
173
+ * claimed "PNG before SVG" and the code below ranks a scalable SVG above every
174
+ * raster, so the comment described a preference nothing implemented. Both are
175
+ * accepted because both are what a GNOME application ships: `.xpm` and `.svgz`,
176
+ * which appimagetool also reads, are absent because `plan.ts` stages neither.
177
+ */
178
+ const ICON_EXTENSIONS = ['.png', '.svg'];
179
+ /**
180
+ * Where the AppDir is assembled, under the run's own output root.
181
+ *
182
+ * A directory of its own, never `out/`, for the reason `dmgVolumeDir` gives one
183
+ * format over: appimagetool packs everything it finds in the AppDir, so a stray
184
+ * sibling would ride into the image and the reader that would catch it is the
185
+ * same listing comparison that would then have to be relaxed to allow it.
186
+ */
187
+ export function appDirFor(outRoot) {
188
+ return join(outRoot, 'appimage', APPDIR_NAME);
189
+ }
190
+ /**
191
+ * What the AppImage does NOT carry, derived from the payload rather than authored.
192
+ *
193
+ * THE HONEST HALF OF ADR 0024 § 9, as data. The same scan that gives the `.deb`
194
+ * its `Depends: gir1.2-gtk-4.0` gives this its `Gtk-4.0`, so the two artifacts
195
+ * built from one payload cannot disagree about what the host has to provide —
196
+ * and the AppImage's version is distro-NEUTRAL on purpose, because there is no
197
+ * distribution to name package names in. A user reading `Gtk-4.0` can find it on
198
+ * any system; a user reading `gir1.2-gtk-4.0` on Fedora cannot.
199
+ *
200
+ * The interpreter is first and always present: it is the requirement that is
201
+ * never satisfied by accident, and the one {@link renderAppRun} can check from a
202
+ * shell script.
203
+ */
204
+ export function appImageHostRequirements(input) {
205
+ const floor = interpreterFloor(input);
206
+ return [
207
+ `${input.app} (>= ${floor})`,
208
+ ...hostProvidedNamespaces(input.namespaces, input.bundledTypelibs).map((ns) => `the ${ns} typelib`),
209
+ ];
210
+ }
211
+ /**
212
+ * The version this payload's interpreter must be at least, as the project declared it.
213
+ *
214
+ * ONE DECISION, TWO READERS, which is why it is a function and not two ternaries:
215
+ * {@link appImageHostRequirements} PRINTS this floor and {@link renderAppRun}
216
+ * CHECKS it, and an artifact whose message names 1.86 while its script compares
217
+ * against something else is worse than one that does neither.
218
+ */
219
+ export function interpreterFloor(input) {
220
+ return input.app === 'node'
221
+ ? (input.minNodeVersion ?? DEFAULT_NODE_FLOOR)
222
+ : (input.minGjsVersion ?? DEFAULT_GJS_FLOOR);
223
+ }
224
+ /**
225
+ * The `AppRun` the AppImage runtime execs, and the one check it makes first.
226
+ *
227
+ * IT EXECS THE STAGED LAUNCHER AND ADDS NOTHING TO IT. `bin/<name>` already
228
+ * resolves its own prefix — `readlink -f "$0"` then two `dirname`s
229
+ * (`renderPrefixLauncher`) — and exports `XDG_DATA_DIRS`, `GI_TYPELIB_PATH`,
230
+ * `GJSIFY_LOCALE_DIR` and `GJSIFY_FONT_DIR` relative to it. Inside a mounted
231
+ * image that resolves to `/tmp/.mount_xxxx/usr`, measured, so every locator the
232
+ * `.deb` sets up is already correct here. Re-exporting any of them from AppRun
233
+ * would be a second answer to a question the payload answers, and the copy that
234
+ * drifts is the one nothing tests: `tests/e2e/ship-layout` compares the staged
235
+ * trees, not this script.
236
+ *
237
+ * WHAT IT DOES ADD is the refusal ADR 0024 § 9 asks for. An AppImage whose
238
+ * interpreter is missing exits with the loader's own message — `gjs: not found`
239
+ * from a shell, or nothing at all when a desktop launches it — and the user
240
+ * concludes the download is broken. `command -v` costs one fork and turns that
241
+ * into a sentence naming the runtime, this file's promise and the escape hatch.
242
+ * The typelib half is deliberately NOT checked here: girepository's search path
243
+ * is not a shell-visible thing, and GJS's own "Typelib file for namespace 'Gtk'
244
+ * not found" is already precise. Listing them in the refusal is what this file
245
+ * can honestly do — checking them would be a probe that guesses.
246
+ *
247
+ * AND THE FLOOR IS CHECKED, FAIL-OPEN, which is the one design decision in this
248
+ * script. `command -v gjs` alone accepted GJS 1.70 while the message beside it
249
+ * said `gjs (>= 1.86)` — a floor the `.deb` enforces through `Depends:` and this
250
+ * artifact merely printed, so the failure it exists to prevent came back one
251
+ * import later. The check costs the same fork `command -v` already cost.
252
+ *
253
+ * FAIL-OPEN IS THE POINT AND NOT A HEDGE. A version comparison in `/bin/sh` that
254
+ * gets it wrong REFUSES A WORKING SYSTEM, which is strictly worse than not
255
+ * checking: the user cannot argue with an artifact. So the refusal fires only on
256
+ * two integers that were actually parsed out of the interpreter's own
257
+ * `--version`, and every other outcome — no output, a spelling this `sed` does
258
+ * not match, a distro build that prints something else entirely — RUNS THE
259
+ * APPLICATION. `gjs --version` prints `gjs 1.88.1` and `node --version` prints
260
+ * `v24.19.0`; both reduce to a major and a minor, and a floor with no minor
261
+ * (`24`) compares as `24.0`.
262
+ *
263
+ * EXIT 126 AND NOT 127 for the too-old case, because the shell's own vocabulary
264
+ * already separates them: 127 is "not found", 126 is "found and cannot be run".
265
+ * A wrapper script that wants to tell the two apart can, and the message says
266
+ * which it is either way.
267
+ */
268
+ export function renderAppRun(settings, hostRequirements) {
269
+ // `LAYOUTS.linux.dirs()` and not the literal `bin`: this path and the one
270
+ // `place()` stages the launcher at are ONE decision, and a second spelling here
271
+ // would break the day the layout map moves it — silently, because the AppDir
272
+ // would still build and only the mounted image would 127.
273
+ const launcherDir = LAYOUTS.linux.dirs(settings).launcher;
274
+ const floor = interpreterFloor(settings);
275
+ const [floorMajor = '0', floorMinor = '0'] = floor.split('.');
276
+ return [
277
+ '#!/bin/sh',
278
+ '# Generated by `gjsify ship` — do not edit.',
279
+ 'set -e',
280
+ 'here=$(dirname "$(readlink -f "$0")")',
281
+ `if ! command -v ${settings.app} >/dev/null 2>&1; then`,
282
+ ` echo "${shellSafe(settings.name)} needs ${settings.app}, and this system has none." >&2`,
283
+ ' echo "This AppImage carries the application, not its runtime. It needs:" >&2',
284
+ ...hostRequirements.map((need) => ` echo " - ${shellSafe(need)}" >&2`),
285
+ ' exit 127',
286
+ 'fi',
287
+ // The first `<major>.<minor>` anywhere in the interpreter's own version
288
+ // output. `2>/dev/null` and `|| true` because `set -e` is on and an
289
+ // interpreter that fails its own `--version` must not kill the launcher —
290
+ // that is the fail-open path, reached before any comparison.
291
+ `found=$(${settings.app} --version 2>/dev/null | sed -n 's/[^0-9]*\\([0-9][0-9]*\\)\\.\\([0-9][0-9]*\\).*/\\1 \\2/p' | head -n 1 || true)`,
292
+ 'major=${found% *}',
293
+ 'minor=${found#* }',
294
+ // THE FAIL-OPEN GATE, and it is this ONE test because the `sed` above can
295
+ // only ever emit two runs of digits or nothing at all — both captures are
296
+ // `[0-9][0-9]*`. A `case "$major$minor" in ""|*[!0-9]*)` stood here first
297
+ // and was deleted after the mutation that should have red it stayed green:
298
+ // it guarded a state nothing can produce, which is a guard that cannot
299
+ // fail. What DOES reach here is the empty parse, and that is what this
300
+ // sees.
301
+ 'if [ -n "$major" ]; then',
302
+ ` if [ "$major" -lt ${floorMajor} ] || { [ "$major" -eq ${floorMajor} ] && [ "$minor" -lt ${floorMinor} ]; }; then`,
303
+ ` echo "${shellSafe(settings.name)} needs ${settings.app} ${floor} or newer, and this system has $major.$minor." >&2`,
304
+ ' echo "This AppImage carries the application, not its runtime. It needs:" >&2',
305
+ ...hostRequirements.map((need) => ` echo " - ${shellSafe(need)}" >&2`),
306
+ ' exit 126',
307
+ ' fi',
308
+ 'fi',
309
+ `exec "$here/usr/${launcherDir}/${settings.binaryName}" "$@"`,
310
+ '',
311
+ ].join('\n');
312
+ }
313
+ /**
314
+ * A string that is safe between double quotes in `/bin/sh`.
315
+ *
316
+ * Narrow on purpose: the three characters the shell still expands inside double
317
+ * quotes, plus the quote itself. `settings.name` is a display name a project
318
+ * chose and `hostRequirements` is derived from GI namespaces, so neither is
319
+ * hostile — but a name containing `$` would otherwise produce a message with a
320
+ * variable expansion in it, and an AppRun is the one file here nobody reads
321
+ * until it has already failed.
322
+ */
323
+ function shellSafe(text) {
324
+ return text.replace(/(["$`\\])/g, '\\$1');
325
+ }
326
+ /**
327
+ * The icon appimagetool needs at the AppDir root, chosen from the payload.
328
+ *
329
+ * AN APPIMAGE NEEDS TWO FILES THE PREFIX ALREADY HAS, AT A PLACE IT DOES NOT:
330
+ * appimagetool refuses an AppDir without a `.desktop` at its root, and the file
331
+ * named by that entry's `Icon=` must sit beside it. `plan.ts` stages both — the
332
+ * entry at `share/applications/<appId>.desktop` and every icon renamed to
333
+ * `<appId>` under `share/icons/hicolor/…` — so this function is a SELECTION over
334
+ * the payload rather than anything new in the stage, which is ADR 0024 § 2's
335
+ * "one payload, a handful of layouts" holding for a fourth format.
336
+ *
337
+ * LARGEST RASTER WINS, and the size comes from the hicolor directory rather than
338
+ * from reading the file: `share/icons/hicolor/256x256/apps/<id>.png` says 256 in
339
+ * its path, and a PNG header read would be a decoder this packer would then own.
340
+ * `scalable` sorts above every raster size as the SVG fallback and `symbolic` is
341
+ * excluded outright — its staged name is `<appId>-symbolic`, which is not what
342
+ * the desktop entry's `Icon=` says, so shipping it as the root icon installs an
343
+ * icon nothing ever looks up (`plan.ts` documents the same rule for the theme).
344
+ */
345
+ /**
346
+ * The pinned runtime for this architecture, or `undefined` when none is staged here.
347
+ *
348
+ * PURE APART FROM ONE INJECTED PROBE, so both answers are testable on a host that
349
+ * has neither — the split {@link appImageToolArgs} draws for the flags. `exists`
350
+ * is a parameter for exactly that reason and defaults to the real one.
351
+ */
352
+ export function findPinnedRuntime(archLabel, env = process.env, exists = existsSync) {
353
+ const dir = env[APPIMAGE_RUNTIME_DIR_ENV] || APPIMAGE_RUNTIME_DIR;
354
+ // `posix.join`, not `join`: this path is a LINUX path by construction — the
355
+ // default is baked into the Linux CI image and the format is `finishOn:
356
+ // ['linux']`, so it never names a location on the host running this code.
357
+ // Composing it with the HOST's separator produced a backslash path on
358
+ // win32, where the unit suite runs: caught by CI as two red assertions,
359
+ // after every local run on Linux had agreed with itself.
360
+ const file = posix.join(dir, `runtime-${archLabel}`);
361
+ return exists(file) ? file : undefined;
362
+ }
363
+ /**
364
+ * What this pack is about to do about the runtime, as ONE sentence `ship` prints
365
+ * unconditionally.
366
+ *
367
+ * DECLARE RATHER THAN IMPLY — {@link appImageHostRequirements}'s rule, applied to
368
+ * the other half of the artifact. With a pin the claim is checkable: no network,
369
+ * and two packs of one build agree because the embedded bytes are fixed. Without
370
+ * one the pack still works and still produces a correct-architecture container —
371
+ * so refusing would cost the three architectures nothing here pins, for a
372
+ * property they never had. What it must not do is happen silently: an AppImage
373
+ * built this way carries bytes from a rolling tag that nothing in this tree can
374
+ * name, and the person who can fix that is the one reading this line.
375
+ */
376
+ export function appImageRuntimeNotice(archLabel, runtimeFile) {
377
+ if (runtimeFile !== undefined) {
378
+ return `the AppImage runtime is pinned: ${runtimeFile} — this pack needs no network`;
379
+ }
380
+ return (`NO pinned AppImage runtime for ${archLabel}: appimagetool will fetch runtime-${archLabel} from ` +
381
+ "type2-runtime's rolling `continuous` tag, so this pack NEEDS A NETWORK and the ~940 KB of runtime " +
382
+ `it embeds carries no digest from this tree. Pin one at ${APPIMAGE_RUNTIME_DIR}/runtime-${archLabel} ` +
383
+ `(or point ${APPIMAGE_RUNTIME_DIR_ENV} at a directory holding it).`);
384
+ }
385
+ export function selectAppDirIcon(payload, appId) {
386
+ let best;
387
+ for (const entry of payload) {
388
+ const rank = rootIconRank(entry.path, appId);
389
+ if (rank === undefined)
390
+ continue;
391
+ if (best === undefined || rank > best.rank)
392
+ best = { entry, rank };
393
+ }
394
+ return best?.entry;
395
+ }
396
+ /**
397
+ * How good a candidate a staged path is for the AppDir root icon, or `undefined`
398
+ * when it is not a candidate at all.
399
+ *
400
+ * Scalable outranks every raster because an SVG is every size; among rasters the
401
+ * pixel count decides. Both are ranks rather than a sort key so the caller stays
402
+ * a single pass — and so the `undefined` arm is the ONLY place a path is
403
+ * rejected, instead of a filter here and a guard there.
404
+ */
405
+ function rootIconRank(path, appId) {
406
+ const extension = ICON_EXTENSIONS.find((candidate) => path.endsWith(`${appId}${candidate}`));
407
+ if (extension === undefined)
408
+ return undefined;
409
+ if (!path.startsWith(`${SHARE.icons}/`))
410
+ return undefined;
411
+ // `scalable` and `symbolic` are contexts, not sizes — and only the first is
412
+ // wanted. `symbolic` cannot reach here anyway (its staged basename carries the
413
+ // suffix, so the `endsWith` above misses it), and the explicit refusal stays
414
+ // because the day a project names a plain icon `.../symbolic/apps/<id>.svg` is
415
+ // the day the implicit version silently ships a 16px monochrome glyph as the
416
+ // application's face.
417
+ if (path.includes('/symbolic/'))
418
+ return undefined;
419
+ if (path.includes('/scalable/'))
420
+ return Number.MAX_SAFE_INTEGER;
421
+ const size = /\/(\d+)x\1\//.exec(path);
422
+ return size === null ? 1 : Number(size[1]);
423
+ }
424
+ /**
425
+ * Refuse a payload that cannot become an AppImage, naming the missing half.
426
+ *
427
+ * BEFORE appimagetool RATHER THAN THROUGH IT, and the two refusals it replaces
428
+ * are why: a `kind: 'cli'` project stages no desktop entry at all, and
429
+ * appimagetool answers that with `Desktop file not found, aborting` — true, and
430
+ * about a file the author never wrote and cannot find. Same for the icon. Both
431
+ * failures are decided by the project's OWN configuration (`gjsify.ship.kind`,
432
+ * `gjsify.ship.icon`), so the message that helps is the one that names the key.
433
+ *
434
+ * Separate from `assertToolsInstalled` and `assertHostCanFinish` for the reason
435
+ * those two are separate from each other (ADR 0024 § A3): three failures, three
436
+ * different fixes — a different machine, a package, or a line in package.json.
437
+ */
438
+ export function assertAppImageIsPackable(payload, settings) {
439
+ const desktopEntry = `${SHARE.applications}/${settings.appId}.desktop`;
440
+ if (!payload.some((entry) => entry.path === desktopEntry)) {
441
+ throw new Error(`gjsify ship: an AppImage needs a desktop entry and this payload has no ${desktopEntry}. ` +
442
+ 'appimagetool refuses an AppDir without one, and the AppImage runtime has nothing to tell a ' +
443
+ 'desktop about the application it just mounted. A `kind: "cli"` project stages no entry by ' +
444
+ 'design — set `gjsify.ship.kind` to "app" if this is a GUI application, or ship it as a `.deb`, ' +
445
+ 'an `.rpm` or a Flatpak, none of which need one.');
446
+ }
447
+ if (selectAppDirIcon(payload, settings.appId) === undefined) {
448
+ throw new Error(`gjsify ship: an AppImage needs an icon called ${settings.appId} beside its desktop entry, and ` +
449
+ `this payload stages none under ${SHARE.icons}/. The entry's \`Icon=\` names the app id, so a ` +
450
+ 'file keeping its own basename is an icon nothing looks up — point `gjsify.ship.icon` at a PNG ' +
451
+ 'or an SVG and it is renamed into the theme for you.');
452
+ }
453
+ }
454
+ /**
455
+ * The whole AppDir as one payload: the prefix under `usr/`, plus the three files
456
+ * at its root.
457
+ *
458
+ * PURE, AND ONE LIST RATHER THAN A WRITER, which is the shape `msi.ts` and
459
+ * `dmg.ts` already have — `packOne` owns the single `writePayload` call for every
460
+ * format, and the packer module owns what goes in it. Two calls here would be two
461
+ * wipes, and the second would not clean the first: an AppDir root still holding
462
+ * the PREVIOUS app id's `.desktop` and icon is an AppDir appimagetool packs
463
+ * without complaint, because it looks for *a* desktop file and finds two.
464
+ *
465
+ * `usr/` AND NOT THE APPDIR ROOT — that prefix is the whole layout difference
466
+ * between this format and the `.deb` beside it, and it is why
467
+ * `FormatDescriptor.prefix` can stay `/usr`. The staged launcher walks up two
468
+ * directories from its own resolved path, so under a mount it computes
469
+ * `<mount>/usr` and every locator it exports is already right. A payload written
470
+ * at the root would make it compute the MOUNTPOINT, and the app would look for
471
+ * its schemas one directory too high — at exit 0, until the first
472
+ * `Gio.Settings.new()`.
473
+ */
474
+ export function appDirPayload(settings, payload, hostRequirements) {
475
+ assertAppImageIsPackable(payload, settings);
476
+ // Non-null by construction: the assertion above refuses a payload with
477
+ // neither, and both reads are the SAME selection it made.
478
+ const icon = selectAppDirIcon(payload, settings.appId);
479
+ const desktopPath = `${SHARE.applications}/${settings.appId}.desktop`;
480
+ const desktop = payload.find((entry) => entry.path === desktopPath);
481
+ return [
482
+ ...payload.map((entry) => ({ ...entry, path: `${APPDIR_PREFIX_DIR}/${entry.path}` })),
483
+ { path: APPRUN_NAME, mode: 0o755, data: encodeUtf8(renderAppRun(settings, hostRequirements)) },
484
+ // THE SAME BYTES, TWICE, and that is the AppImage specification rather
485
+ // than a duplication to lift: the entry under `usr/share/applications` is
486
+ // what a desktop reads after an install, and the copy at the AppDir root
487
+ // is what appimagetool reads to name the image. Rendering it a second
488
+ // time is what would drift; copying the staged bytes cannot.
489
+ { path: `${settings.appId}.desktop`, mode: 0o644, data: desktop.data },
490
+ { path: icon.path.slice(icon.path.lastIndexOf('/') + 1), mode: 0o644, data: icon.data },
491
+ // THE THIRD COPY OF THE SAME BYTES, and the one that is here to keep
492
+ // appimagetool from writing it — see {@link DIR_ICON_NAME}.
493
+ { path: DIR_ICON_NAME, mode: 0o644, data: icon.data },
494
+ ];
495
+ }
496
+ /**
497
+ * The argument vector, as data.
498
+ *
499
+ * Pure, so every flag is unit-testable on a host with no `appimagetool` — the
500
+ * same split `hdiutilCreateArgs` draws for `hdiutil` and `renderShipFlatpakManifest`
501
+ * for `flatpak-builder`: what the tool is TOLD is checkable everywhere, what the
502
+ * tool DOES needs the tool.
503
+ *
504
+ * `--no-appstream` IS A DECISION AND NOT A DEFAULT. appimagetool otherwise runs
505
+ * `appstreamcli validate-tree` over the AppDir, which would make the pack succeed
506
+ * or fail depending on whether a package unrelated to packaging is installed —
507
+ * green on a workstation with `appstream` and red in a container without it, over
508
+ * a payload that is byte-identical. A validator whose presence changes the
509
+ * outcome is the class this repository calls green-CI-that-checked-nothing, read
510
+ * backwards. The MetaInfo is still validated, by the tool that exists for it:
511
+ * `gjsify flatpak check --appstream` runs `appstreamcli validate --strict` on
512
+ * demand, where a missing `appstreamcli` is the point of the command rather than
513
+ * a surprise inside another one.
514
+ *
515
+ * `--comp zstd` is pinned for `hdiutilCreateArgs`' reason one format over: it is
516
+ * 1.9.1's current default, and a default is a thing that changes. The reader the
517
+ * oracle leg runs is `unsquashfs` from squashfs-tools, which needs its zstd
518
+ * support compiled in — measured present on Fedora 44 (4.6.1) and on
519
+ * ubuntu-24.04's 4.6.1. Pinning means the day appimagetool switches to something
520
+ * newer, this file changes and the reader is considered, instead of the reader
521
+ * silently losing the ability to open what we ship.
522
+ *
523
+ * `--runtime-file` IS PASSED WHEN THERE IS ONE TO PASS, and its absence is the
524
+ * only thing in this vector that is not a decision — see
525
+ * {@link findPinnedRuntime}. With it, the pack embeds bytes this tree pinned and
526
+ * needs no network (measured: the whole pack succeeds with the network blocked,
527
+ * and two packs are byte-identical). Without it appimagetool fetches its own, the
528
+ * pack is announced as doing so, and the artifact is still correct — just built
529
+ * from something nothing here can name.
530
+ */
531
+ export function appImageToolArgs(input) {
532
+ return [
533
+ '--no-appstream',
534
+ '--comp',
535
+ 'zstd',
536
+ ...(input.runtimeFile === undefined ? [] : ['--runtime-file', input.runtimeFile]),
537
+ input.appDir,
538
+ input.target,
539
+ ];
540
+ }
541
+ /**
542
+ * The environment appimagetool is run with — both entries REQUIRED, neither a hint.
543
+ *
544
+ * `ARCH` because appimagetool derives the architecture from the ELF binaries it
545
+ * finds in the AppDir, and a `--app gjs` payload has none: it is JavaScript and a
546
+ * `/bin/sh` launcher. Without this the tool exits 1 with "Could not determine
547
+ * architecture automatically", on a payload that is perfectly fine. The value is
548
+ * the format row's `archName`, so the architecture inside the file and the one in
549
+ * its name are one decision.
550
+ *
551
+ * `APPIMAGE_EXTRACT_AND_RUN` because appimagetool is itself an AppImage and
552
+ * mounts itself through libfuse to start — see the module header. Set
553
+ * unconditionally: a native `appimagetool` build ignores it, so there is no host
554
+ * for which this is wrong and no flag for a CI author to discover.
555
+ */
556
+ export function appImageToolEnv(archLabel) {
557
+ return { ARCH: archLabel, [EXTRACT_AND_RUN]: '1' };
558
+ }
559
+ /**
560
+ * What a non-zero `appimagetool` exit is, in the order a host actually hits them.
561
+ *
562
+ * PURE, so the one message a user reads at the worst moment is assertable without
563
+ * a container — the same split {@link appImageToolArgs} draws. It was inline until
564
+ * the list was found to be missing its FIRST entry, which is the shape a message
565
+ * that nothing reads back tends to have.
566
+ *
567
+ * THE FIRST CAUSE DEPENDS ON WHETHER A RUNTIME WAS PINNED, and getting that
568
+ * wrong is what this function existed to fix in the first place: with no pin the
569
+ * download is where an offline host fails (measured — exit 1, no file, `Failed to
570
+ * download runtime file`), and with one there is no download to fail, so naming
571
+ * it would send a reader with a working network to debug their firewall. So the
572
+ * pinned branch names the pinned FILE instead, which is the thing that is new in
573
+ * that configuration and the only one this tree chose.
574
+ */
575
+ export function appImageToolFailureMessage(exit, runtimeFile) {
576
+ const first = runtimeFile === undefined
577
+ ? 'the AppImage RUNTIME could not be downloaded — ' +
578
+ `${APPIMAGE_TOOL} fetches it from github.com/AppImage/type2-runtime when no runtime is pinned, ` +
579
+ 'so this pack needs a network and an offline host fails here having written nothing; or '
580
+ : `the pinned runtime at ${runtimeFile} is not an AppImage runtime — it is passed through to ` +
581
+ '`--runtime-file` unread, so a truncated or wrong-architecture file fails here; or ';
582
+ return (`gjsify ship: ${APPIMAGE_TOOL} failed with ${exit}. ` +
583
+ `Four causes, measured in this order: ${first}` +
584
+ '`file` is not installed — ' +
585
+ `${APPIMAGE_TOOL} requires file(1) and says so, even though this pack already tells it the ` +
586
+ 'architecture; or FUSE is unavailable and the tool on PATH is a wrapper that dropped ' +
587
+ `${EXTRACT_AND_RUN}=1, which this pack sets so the extract path is taken instead of a mount; ` +
588
+ 'or the work directory is full — the AppDir is copied into a squashfs image beside it.');
589
+ }
590
+ /**
591
+ * Run appimagetool over the AppDir.
592
+ *
593
+ * THE FAILURE PATHS ARE THE POINT. A packer that execs a foreign tool inherits
594
+ * that tool's silence, and appimagetool's container failures were MEASURED on
595
+ * `fedora:44` rather than guessed. Without `APPIMAGE_EXTRACT_AND_RUN=1` it exits
596
+ * **127** pointing at the AppImageKit FUSE wiki — which is why
597
+ * {@link appImageToolEnv} sets that variable and this branch should never see it.
598
+ * Without `file(1)` it exits **1** with "file command is missing but required",
599
+ * EVEN with `ARCH` set, which is the failure a minimal image really hits and
600
+ * which says nothing about packaging. And without a network it exits **1** having
601
+ * written nothing, because the runtime is fetched rather than embedded — see the
602
+ * module header. {@link appImageToolFailureMessage} names all four.
603
+ *
604
+ * AND THE ARTIFACT IS VERIFIED TO EXIST. appimagetool prints "Success" and a
605
+ * request to submit to AppImageHub; it does not guarantee the destination was
606
+ * written, and a packer whose contract is "there is a file at `target`" must not
607
+ * hand `statSync` a path that is not there and report the ENOENT as a `ship` bug.
608
+ */
609
+ export async function buildAppImage(input) {
610
+ const args = appImageToolArgs(input);
611
+ const env = appImageToolEnv(input.archLabel);
612
+ if (input.verbose) {
613
+ console.log(`[gjsify ship] ${Object.entries(env)
614
+ .map(([key, value]) => `${key}=${value}`)
615
+ .join(' ')} ${APPIMAGE_TOOL} ${args.join(' ')}`);
616
+ }
617
+ // `completion: 'return'`, matching the Flatpak and `.dmg` packers: `ship` packs
618
+ // the remaining formats and prints the artifact list afterwards, so it cannot
619
+ // end in `process.exit()`.
620
+ const result = await spawnToCompletion(APPIMAGE_TOOL, args, {
621
+ completion: 'return',
622
+ cwd: input.workDir,
623
+ stdio: 'inherit',
624
+ env: { ...process.env, ...env },
625
+ notFound: () => new Error(`gjsify ship: ${APPIMAGE_TOOL} is not on PATH. Unlike flatpak-builder and msitools it is not ` +
626
+ 'packaged by Fedora or Debian: take the release from ' +
627
+ 'https://github.com/AppImage/appimagetool/releases, `chmod +x` it and put it on PATH as ' +
628
+ `\`${APPIMAGE_TOOL}\`. \`gjsify ship linux --stage\` needs none of this — the payload is ` +
629
+ 'assembled by this CLI and only the container needs the tool.'),
630
+ });
631
+ if (result.code !== 0) {
632
+ throw new Error(appImageToolFailureMessage(describeExit(result), input.runtimeFile));
633
+ }
634
+ if (!existsSync(input.target)) {
635
+ throw new Error(`gjsify ship: ${APPIMAGE_TOOL} exited 0 and wrote no file at ${input.target}. ` +
636
+ 'An exit code is not an artifact — re-run with `--verbose` to see what it was told.');
637
+ }
638
+ }
639
+ /**
640
+ * Every path an AppDir holding this payload has, files and the directories above
641
+ * them, deepest LAST.
642
+ *
643
+ * Pure and separate from the stamping, so the "which paths" half is testable with
644
+ * no filesystem at all — and so the answer comes from the payload rather than
645
+ * from a directory walk, which would read back whatever the writer happened to
646
+ * leave rather than what it was told to write.
647
+ */
648
+ export function appDirPaths(payload) {
649
+ const directories = new Set();
650
+ for (const entry of payload) {
651
+ const parts = entry.path.split('/');
652
+ for (let depth = 1; depth < parts.length; depth++)
653
+ directories.add(parts.slice(0, depth).join('/'));
654
+ }
655
+ return [...[...directories].sort(), ...payload.map((entry) => entry.path)];
656
+ }
657
+ /**
658
+ * Give every path in the AppDir one mtime.
659
+ *
660
+ * See the module header: this is the single difference between two packs of one
661
+ * build, measured by sha256. `utimesSync` on a directory is legal and is where a
662
+ * squashfs directory inode's time comes from, so directories are stamped as well
663
+ * — `writePayload`'s `mkdir` gives them the wall clock and nothing else would
664
+ * take it away.
665
+ */
666
+ export function stampAppDirTimes(appDir, payload, mtime) {
667
+ for (const rel of appDirPaths(payload)) {
668
+ utimesSync(join(appDir, rel.split('/').join(sep)), mtime, mtime);
669
+ }
670
+ utimesSync(appDir, mtime, mtime);
671
+ }