@gjsify/cli 0.64.39 → 0.64.41-next.335

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,298 @@
1
+ // `gjsify flatpark` — the FlatPark package directory (ADR 0143).
2
+ //
3
+ // FlatPark (https://github.com/flatpark/flatpark) builds `extra-data` Flatpaks from
4
+ // an upstream tarball: a `registry/<app-id>/` directory of a manifest, a hook that
5
+ // unpacks the download, a few install files and a descriptor. This module renders
6
+ // that directory from what `gjsify ship` already produced — the stage's desktop
7
+ // entry, metainfo and icon, the stage manifest's settings, and the release record
8
+ // beside the tarball — and WRITES NOTHING ELSE: no network, no hashing, no clock.
9
+ //
10
+ // Two rules the rendering is shaped by, both measured in the Phase-0 spike:
11
+ //
12
+ // * `apply_extra.sh` never names a version. The tarball's top directory is
13
+ // `<bin>-<version>-linux-<arch>`, so a hook that hard-codes it breaks on the
14
+ // first update that FlatPark's resolver pins. The hook finds the one top-level
15
+ // directory and refuses anything else; the only path it asserts is
16
+ // `bin/<binaryName>`, which is stable.
17
+ // * The same inputs give the same bytes. Nothing here reads a path, a hostname
18
+ // or the time: the release date is the stage's build stamp (`mtime`), which is
19
+ // the one stamp every other file of that stage already shares.
20
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
21
+ import { join } from 'node:path';
22
+ import { RELEASE_RECORD_SUFFIX } from './release-record.js';
23
+ import { xmlEscape } from './xml.js';
24
+ /** The extra-data file name inside the Flatpak. Fixed: the hook and the resolver both name it. */
25
+ export const FLATPARK_EXTRA_FILE = 'app.tar.gz';
26
+ /** The only format whose archive is meant as an `extra-data` source (ADR 0142). */
27
+ export const FLATPARK_RECORD_FORMAT = 'linux-tar-flatpak';
28
+ /** `process.arch` spelling → Flatpak arch. */
29
+ const FLATPAK_ARCH = { x64: 'x86_64', arm64: 'aarch64' };
30
+ /** `owner/name` out of `owner/name`, a github.com URL, or a `git+https://….git` URL. */
31
+ export function parseGithubRepo(value) {
32
+ const trimmed = value.trim().replace(/^git\+/, '');
33
+ const bare = /^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/.exec(trimmed);
34
+ const url = /^(?:https?|ssh|git):\/\/(?:[^@/]+@)?github\.com[/:]([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/.exec(trimmed);
35
+ const hit = url ?? bare;
36
+ return hit === null ? undefined : `${hit[1]}/${hit[2].replace(/\.git$/, '')}`;
37
+ }
38
+ /** The UTC calendar date of a build stamp (seconds since the epoch). */
39
+ export function releaseDateOf(mtime) {
40
+ return new Date(mtime * 1000).toISOString().slice(0, 10);
41
+ }
42
+ /**
43
+ * The release records beside the artifacts in `dir`, as FlatPark sources.
44
+ *
45
+ * The URL is the only thing derived here and it is derived from the repository
46
+ * and the version, never fetched; `sha256` and `size` are the record's, which
47
+ * `gjsify ship` took from the bytes it wrote. A missing record is an error and
48
+ * not a reason to hash the file ourselves: a hash this command computed would
49
+ * describe whatever is on this disk, not what was published.
50
+ */
51
+ export function readFlatparkSources(input) {
52
+ const records = [];
53
+ if (existsSync(input.dir)) {
54
+ for (const file of readdirSync(input.dir).sort()) {
55
+ if (!file.endsWith(RELEASE_RECORD_SUFFIX))
56
+ continue;
57
+ const record = JSON.parse(readFileSync(join(input.dir, file), 'utf-8'));
58
+ if (record.format === FLATPARK_RECORD_FORMAT && record.os === 'linux')
59
+ records.push(record);
60
+ }
61
+ }
62
+ if (records.length === 0) {
63
+ throw new Error(`gjsify flatpark: no release record for \`${FLATPARK_RECORD_FORMAT}\` in ${input.dir}. The URL, sha256 ` +
64
+ `and size come from \`<artifact>${RELEASE_RECORD_SUFFIX}\`, which \`gjsify ship --target ` +
65
+ `${FLATPARK_RECORD_FORMAT}\` writes beside the archive. Run that first, or point --release-dir at ` +
66
+ 'the directory that holds the record.');
67
+ }
68
+ const tag = `${input.tagPrefix}${input.version}`;
69
+ const sources = records.map((record) => {
70
+ const arch = FLATPAK_ARCH[record.arch === 'noarch' ? (input.stageArch ?? record.arch) : record.arch];
71
+ if (arch === undefined) {
72
+ throw new Error(`gjsify flatpark: ${record.artifact} is built for \`${record.arch}\`, which has no Flatpak arch ` +
73
+ `(known: ${Object.keys(FLATPAK_ARCH).join(', ')}).`);
74
+ }
75
+ return {
76
+ arch,
77
+ artifact: record.artifact,
78
+ url: `https://github.com/${input.repo}/releases/download/${tag}/${record.artifact}`,
79
+ sha256: record.sha256,
80
+ size: record.size,
81
+ };
82
+ });
83
+ const seen = new Set();
84
+ for (const source of sources) {
85
+ if (seen.has(source.arch)) {
86
+ throw new Error(`gjsify flatpark: two release records for ${source.arch} in ${input.dir}; keep one.`);
87
+ }
88
+ seen.add(source.arch);
89
+ }
90
+ return sources.sort((a, b) => a.arch.localeCompare(b.arch));
91
+ }
92
+ /** The unpack hook. No version anywhere; the one asserted path derives from `binaryName`. */
93
+ export function renderApplyExtra(binaryName) {
94
+ return `#!/bin/sh
95
+ set -eu
96
+
97
+ extra_root="\${EXTRA_ROOT:-/app/extra}"
98
+ cd "$extra_root"
99
+
100
+ [ -f ${FLATPARK_EXTRA_FILE} ] || { echo "missing extra-data: ${FLATPARK_EXTRA_FILE}" >&2; exit 1; }
101
+
102
+ rm -rf stage app
103
+ mkdir stage
104
+ bsdtar --no-same-owner -xf ${FLATPARK_EXTRA_FILE} -C stage
105
+
106
+ top="$(find stage -mindepth 1 -maxdepth 1 -type d)"
107
+ [ "$(printf '%s\\n' "$top" | wc -l)" -eq 1 ] || { echo "expected one top-level directory" >&2; exit 1; }
108
+ mv "$top" app
109
+ [ -x app/bin/${shellWord(binaryName)} ] || { echo "${shellWord(binaryName)} launcher not found in the tarball" >&2; exit 1; }
110
+
111
+ rm -rf stage ${FLATPARK_EXTRA_FILE}
112
+ `;
113
+ }
114
+ export function renderWrapper(binaryName) {
115
+ return `#!/bin/sh
116
+ set -eu
117
+ exec /app/extra/app/bin/${shellWord(binaryName)} "$@"
118
+ `;
119
+ }
120
+ /** A binary name is a package name; anything outside this set would need quoting we do not do. */
121
+ function shellWord(value) {
122
+ if (!/^[A-Za-z0-9][A-Za-z0-9._+-]*$/.test(value)) {
123
+ throw new Error(`gjsify flatpark: binary name "${value}" is not a plain file name.`);
124
+ }
125
+ return value;
126
+ }
127
+ /** A YAML scalar: plain when that reads back as the same string, JSON-quoted otherwise. */
128
+ function yamlString(value) {
129
+ const plain = /^[A-Za-z0-9_./@+=-][A-Za-z0-9_./@+=: -]*$/.test(value) &&
130
+ !/^(?:true|false|null|yes|no|on|off|~)$/i.test(value) &&
131
+ !/^[-+]?(?:\d[\d_]*(?:\.\d*)?|\.\d+)(?:e[-+]?\d+)?$/i.test(value) &&
132
+ !/: |:$| $|^- /.test(value) &&
133
+ !/^0[xo]/i.test(value);
134
+ return plain ? value : JSON.stringify(value);
135
+ }
136
+ /**
137
+ * The Flatpak manifest. The `extra-data` sources sit between marker comments
138
+ * because FlatPark's updater rewrites exactly that block on every release.
139
+ */
140
+ export function renderManifest(input) {
141
+ const { appId, binaryName } = input;
142
+ const files = [
143
+ 'apply_extra.sh',
144
+ `${binaryName}-wrapper`,
145
+ `${appId}.desktop`,
146
+ `${appId}.metainfo.xml`,
147
+ `${appId}.png`,
148
+ ];
149
+ const lines = [
150
+ `id: ${yamlString(appId)}`,
151
+ `runtime: ${yamlString(input.flatpak.runtime)}`,
152
+ `runtime-version: ${JSON.stringify(input.flatpak.runtimeVersion)}`,
153
+ `sdk: ${yamlString(input.flatpak.sdk)}`,
154
+ `command: ${yamlString(binaryName)}`,
155
+ 'separate-locales: false',
156
+ 'build-options:',
157
+ ' no-debuginfo: true',
158
+ 'finish-args:',
159
+ ...input.flatpak.finishArgs.map((arg) => ` - ${yamlString(arg)}`),
160
+ 'modules:',
161
+ ` - name: ${yamlString(binaryName)}`,
162
+ ' buildsystem: simple',
163
+ ' build-commands:',
164
+ ' - install -Dm755 apply_extra.sh /app/bin/apply_extra',
165
+ ` - install -Dm755 ${binaryName}-wrapper /app/bin/${binaryName}`,
166
+ ` - install -Dm644 ${appId}.desktop /app/share/applications/${appId}.desktop`,
167
+ ` - install -Dm644 ${appId}.metainfo.xml /app/share/metainfo/${appId}.metainfo.xml`,
168
+ ` - install -Dm644 ${appId}.png /app/share/icons/hicolor/${input.icon.size}x${input.icon.size}/apps/${appId}.png`,
169
+ ' sources:',
170
+ ' # BEGIN MANAGED EXTRA-DATA',
171
+ ...input.sources.flatMap((source) => [
172
+ ' - type: extra-data',
173
+ ` filename: ${FLATPARK_EXTRA_FILE}`,
174
+ ' only-arches:',
175
+ ` - ${source.arch}`,
176
+ ` url: ${yamlString(source.url)}`,
177
+ ` sha256: ${source.sha256}`,
178
+ ` size: ${source.size}`,
179
+ ]),
180
+ ' # END MANAGED EXTRA-DATA',
181
+ ...files.flatMap((path) => [' - type: file', ` path: ${yamlString(path)}`]),
182
+ ];
183
+ return `${lines.join('\n')}\n`;
184
+ }
185
+ /** The first `<category>` of the metainfo — FlatPark's catalogue takes one. */
186
+ function firstCategory(metainfo) {
187
+ return /<category>([^<]+)<\/category>/.exec(metainfo)?.[1]?.trim() ?? 'Utility';
188
+ }
189
+ function keywords(metainfo) {
190
+ return [...metainfo.matchAll(/<keyword>([^<]+)<\/keyword>/g)].map((hit) => hit[1].trim());
191
+ }
192
+ export function renderDescriptor(input) {
193
+ const tags = keywords(input.metainfo);
194
+ const lines = [
195
+ `id: ${yamlString(input.appId)}`,
196
+ `name: ${yamlString(input.name)}`,
197
+ `summary: ${yamlString(input.summary)}`,
198
+ `website: ${yamlString(input.homepage ?? `https://github.com/${input.repo}`)}`,
199
+ `source_url: https://github.com/${input.repo}`,
200
+ 'build:',
201
+ ` manifest: ${input.appId}.yml`,
202
+ ' branch: stable',
203
+ ' mode: extra-data',
204
+ ` arches: [${input.sources.map((source) => source.arch).join(', ')}]`,
205
+ 'catalog:',
206
+ ` category: ${yamlString(firstCategory(input.metainfo))}`,
207
+ // The row in FlatPark's `upstream-approvals.md` is the maintainer's to add.
208
+ ' upstream_approved: false',
209
+ ...(tags.length === 0 ? [] : [' tags:', ...tags.map((tag) => ` - ${yamlString(tag)}`)]),
210
+ 'update:',
211
+ ' command: ./resolve-update.sh',
212
+ 'policy:',
213
+ ' proprietary: false',
214
+ ' dangerous_permissions: []',
215
+ ];
216
+ return `${lines.join('\n')}\n`;
217
+ }
218
+ /** `jq`'s regex (Oniguruma), for the asset name of one arch with the version abstracted. */
219
+ function assetPattern(source, version) {
220
+ const escaped = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
221
+ const at = source.artifact.indexOf(version);
222
+ if (at < 0) {
223
+ throw new Error(`gjsify flatpark: ${source.artifact} does not contain the version ${version}.`);
224
+ }
225
+ return `^${escaped(source.artifact.slice(0, at))}[0-9][0-9A-Za-z.+~-]*${escaped(source.artifact.slice(at + version.length))}$`;
226
+ }
227
+ export function renderResolveUpdate(input) {
228
+ const sourceVars = input.sources.map((source) => {
229
+ const key = source.arch.replace(/[^a-z0-9]/g, '_');
230
+ return { source, key, pattern: assetPattern(source, input.version).replace(/\\/g, '\\\\') };
231
+ });
232
+ const lookups = sourceVars.map(({ key, pattern }) => `url_${key}="$(jq -r '.assets[] | select(.name | test("${pattern}")) | .browser_download_url' <<<"$rel" | head -n1)"\n` +
233
+ `[ -n "$url_${key}" ] || { echo "no ${key} asset in this release" >&2; exit 1; }`);
234
+ const sources = sourceVars.map(({ source, key }) => `{filename:"${FLATPARK_EXTRA_FILE}", arch:"${source.arch}", url:$u_${key}}`);
235
+ const args = sourceVars.map(({ key }) => `--arg u_${key} "$url_${key}"`);
236
+ return `#!/usr/bin/env bash
237
+ # Update resolver for ${input.name}, written by \`gjsify flatpark\`.
238
+ #
239
+ # Prints the latest release on stdout as JSON:
240
+ # { "version": "…", "releaseDate": "YYYY-MM-DD",
241
+ # "sources": [ { "filename": "${FLATPARK_EXTRA_FILE}", "arch": "…", "url": "…" } ] }
242
+ # Logs go to stderr. No hashing and no manifest rewriting: FlatPark downloads
243
+ # each URL and computes the extra-data sha256 and size itself.
244
+ set -euo pipefail
245
+
246
+ repo="${input.repo}"
247
+
248
+ need() { command -v "$1" >/dev/null 2>&1 || { echo "missing command: $1" >&2; exit 1; }; }
249
+ need curl; need jq
250
+
251
+ rel="$(curl -fsSL \${GITHUB_TOKEN:+-H "Authorization: Bearer $GITHUB_TOKEN"} \\
252
+ "https://api.github.com/repos/$repo/releases/latest")"
253
+
254
+ version="$(jq -r '.tag_name | ltrimstr("v")' <<<"$rel")"
255
+ date="$(jq -r '.published_at' <<<"$rel" | cut -c1-10)"
256
+ [ -n "$version" ] && [ "$version" != "null" ] || { echo "failed to resolve the latest release of $repo" >&2; exit 1; }
257
+
258
+ ${lookups.join('\n')}
259
+ echo "resolved ${input.name} $version ($date)" >&2
260
+
261
+ jq -n --arg v "$version" --arg d "$date" ${args.join(' ')} \\
262
+ '{version:$v, releaseDate:$d, sources:[${sources.join(', ')}]}'
263
+ `;
264
+ }
265
+ /**
266
+ * The metainfo with a `<releases>` block carrying this version, unless it has
267
+ * one. FlatPark compares the resolver's version against the newest `<release>`
268
+ * here, and Flatpak ignores an undated one — so a package starts with exactly one.
269
+ */
270
+ export function withRelease(metainfo, version, date) {
271
+ if (/<releases[\s>]/.test(metainfo))
272
+ return metainfo;
273
+ const block = ` <releases>\n <release version="${xmlEscape(version)}" date="${date}" />\n </releases>\n`;
274
+ const close = metainfo.lastIndexOf('</component>');
275
+ if (close < 0)
276
+ throw new Error('gjsify flatpark: the staged metainfo has no </component>.');
277
+ return `${metainfo.slice(0, close)}${block}${metainfo.slice(close)}`;
278
+ }
279
+ /** Every file of the package directory, in a fixed order. */
280
+ export function renderFlatparkPackage(input) {
281
+ const { appId, binaryName } = input;
282
+ if (input.sources.length === 0)
283
+ throw new Error('gjsify flatpark: no sources to pin.');
284
+ return [
285
+ { path: `${appId}.yml`, mode: 0o644, data: renderManifest(input) },
286
+ { path: 'apply_extra.sh', mode: 0o755, data: renderApplyExtra(binaryName) },
287
+ { path: `${binaryName}-wrapper`, mode: 0o755, data: renderWrapper(binaryName) },
288
+ { path: `${appId}.desktop`, mode: 0o644, data: input.desktopEntry },
289
+ {
290
+ path: `${appId}.metainfo.xml`,
291
+ mode: 0o644,
292
+ data: withRelease(input.metainfo, input.version, input.releaseDate),
293
+ },
294
+ { path: `${appId}.png`, mode: 0o644, data: input.icon.bytes },
295
+ { path: 'flatpark.yml', mode: 0o644, data: renderDescriptor(input) },
296
+ { path: 'resolve-update.sh', mode: 0o755, data: renderResolveUpdate(input) },
297
+ ];
298
+ }
@@ -100,6 +100,15 @@ const APPIMAGE_ARCH = {
100
100
  function appImageArch(arch, _archIndependent) {
101
101
  return lookupArch(APPIMAGE_ARCH, arch, 'AppImage');
102
102
  }
103
+ /**
104
+ * `process.arch` → the `uname -m` spelling a tarball name carries (and the
105
+ * Flatpak arch the `-flatpak` variant is consumed under). `archIndependent` is
106
+ * IGNORED: the name is a download label and Flatpak has no `noarch`.
107
+ */
108
+ const LINUX_TAR_ARCH = { x64: 'x86_64', arm64: 'aarch64' };
109
+ function linuxTarArch(arch, _archIndependent) {
110
+ return lookupArch(LINUX_TAR_ARCH, arch, 'Linux tarball');
111
+ }
103
112
  /**
104
113
  * `process.arch` → the name Apple's tools use.
105
114
  *
@@ -505,6 +514,75 @@ export const FORMATS = {
505
514
  // build beside the tool gate rather than after it inside the packer.
506
515
  requiresDesktopEntry: true,
507
516
  },
517
+ // THE FIFTH CONTAINER OVER THE LINUX TREE, and the first with no install
518
+ // step and no prefix at all: a gzip'd tar whose single top directory is
519
+ // `<binaryName>-<version>-linux-<arch>/`. It is a download to unpack anywhere,
520
+ // and the launcher computes its own prefix, so the same `bin/<name>` works.
521
+ // It is NOT a replacement for `.deb`/`.rpm` and NOT self-contained: it takes
522
+ // its interpreter from the machine, like them, with no field to declare it.
523
+ //
524
+ // `finishOn: ['linux']` and not `'any'` although nothing is exec'd, and the
525
+ // reason is `defaultFormatIds`: `'any'` is what makes a bare `gjsify ship` on
526
+ // Linux build a row, and that set is exactly `deb` + `rpm` today. Opt-in
527
+ // through `--target` or `gjsify.ship.targets`, like `appimage` and `flatpak`.
528
+ 'linux-tar': {
529
+ id: 'linux-tar',
530
+ layoutOs: 'linux',
531
+ // No install prefix: the packer names the top directory. Unused by it.
532
+ prefix: '',
533
+ host: {
534
+ finishOn: ['linux'],
535
+ requiredTools: [],
536
+ oracle: {
537
+ // This tree's own `parseTar` reads the artifact back in the unit
538
+ // suite; the e2e suite reads it with GNU `tar`, which shares no code
539
+ // with the writer (ADR 0024 § A3).
540
+ readWith: ['tar'],
541
+ readOn: ['linux'],
542
+ selfReading: false,
543
+ },
544
+ },
545
+ depends: null,
546
+ interpreters: ['gjs', 'node'],
547
+ interpreterGap: 'a tarball carries the application and takes its interpreter from the host, exactly as a distro ' +
548
+ 'package does — but with no dependency field to declare it in',
549
+ licenseDest: SHARE_LICENSE_DEST,
550
+ licenseKind: 'plain',
551
+ archName: linuxTarArch,
552
+ fileName: (s, archLabel) => `${s.binaryName}-${s.version}-linux-${archLabel}.tar.gz`,
553
+ artifactKind: 'file',
554
+ },
555
+ // THE FLATPAK-OPTIMISED VARIANT, a second row and not a flag. The payload is
556
+ // identical; what differs is one pack-time step — `gschemas.compiled` is
557
+ // compiled and shipped (`appimage`'s precedent, and for its reason: the Linux
558
+ // stage is shared with `.deb`/`.rpm`, so no stage carries the cache) — and
559
+ // the CONTRACT: this archive is meant to be an `extra-data` source under
560
+ // `org.gnome.Platform`, which provides gjs and GTK, so nothing is bundled.
561
+ // A row keeps `defaultFormatIds`, `--target`, the closed vocabulary and
562
+ // `TARGETS` table-driven; a flag would need a second axis in all four.
563
+ 'linux-tar-flatpak': {
564
+ id: 'linux-tar-flatpak',
565
+ layoutOs: 'linux',
566
+ prefix: '',
567
+ host: {
568
+ finishOn: ['linux'],
569
+ requiredTools: [SCHEMA_COMPILER],
570
+ installHint: `The schema compiler is packaged: ${SCHEMA_COMPILER_HINT}`,
571
+ oracle: { readWith: ['tar'], readOn: ['linux'], selfReading: false },
572
+ },
573
+ depends: null,
574
+ // GJS ONLY, like the Flatpak row: the runtime ships `gjs`, not `node`.
575
+ interpreters: ['gjs'],
576
+ interpreterGap: 'the archive is meant to run under `org.gnome.Platform`, which ships `gjs` and no `node`, and it ' +
577
+ 'bundles no interpreter',
578
+ licenseDest: SHARE_LICENSE_DEST,
579
+ licenseKind: 'plain',
580
+ archName: linuxTarArch,
581
+ // A name of its own: both variants of one build must be able to sit in one
582
+ // `out/` directory.
583
+ fileName: (s, archLabel) => `${s.binaryName}-${s.version}-linux-${archLabel}-flatpak.tar.gz`,
584
+ artifactKind: 'file',
585
+ },
508
586
  // ── macOS (#1354 M2a) ────────────────────────────────────────────────
509
587
  //
510
588
  // TWO ROWS FOR ONE TREE, and the pair is what `layoutOs` was added for. The
@@ -1189,6 +1267,8 @@ export function canCarryTicket(id) {
1189
1267
  case 'rpm':
1190
1268
  case 'flatpak':
1191
1269
  case 'appimage':
1270
+ case 'linux-tar':
1271
+ case 'linux-tar-flatpak':
1192
1272
  case 'windows-dir':
1193
1273
  case 'windows-dir-zip':
1194
1274
  case 'msi':
@@ -0,0 +1,25 @@
1
+ import type { PayloadEntry } from './payload.js';
2
+ import type { PackSettings } from './types.js';
3
+ /** The single top directory: `<binaryName>-<version>-linux-<arch>`. */
4
+ export declare function tarballTopDir(settings: PackSettings, archLabel: string): string;
5
+ /**
6
+ * Refuse a payload that carries what a release archive must never hold.
7
+ *
8
+ * The payload is the staged closure, so these are guards against a stage that
9
+ * grew something nobody meant to publish — a `.env`, a `.git`, a log — rather
10
+ * than checks a normal build trips. `node_modules` is legitimate exactly when
11
+ * the app runs on Node and the stage copied its closure; for `--app gjs` there
12
+ * is no reason for one to exist.
13
+ */
14
+ export declare function assertTarballHygiene(payload: readonly PayloadEntry[], settings: PackSettings): void;
15
+ /**
16
+ * The archive: one directory entry per ancestor, then the payload, all under
17
+ * {@link tarballTopDir}. The file list is the payload's and nothing else — the
18
+ * stage's own sidecar was never payload.
19
+ */
20
+ export declare function buildLinuxTarball(input: {
21
+ settings: PackSettings;
22
+ payload: readonly PayloadEntry[];
23
+ archLabel: string;
24
+ mtime: number;
25
+ }): Promise<Uint8Array>;
@@ -0,0 +1,69 @@
1
+ // A deterministic `.tar.gz` of the Linux payload, in-tree, execing nothing.
2
+ //
3
+ // Same argument as the hand-written `.deb` and `.rpm` (ADR 0024 § A3): a format
4
+ // this tree writes itself needs no tool on the packing host, which keeps GNU
5
+ // `tar` an independent reader. Backs `linux-tar` and `linux-tar-flatpak` (ADR 0142).
6
+ import { posix } from 'node:path';
7
+ import { createTarball } from '@gjsify/tar';
8
+ import { gzipDeterministic } from './gzip.js';
9
+ /** The single top directory: `<binaryName>-<version>-linux-<arch>`. */
10
+ export function tarballTopDir(settings, archLabel) {
11
+ return `${settings.binaryName}-${settings.version}-linux-${archLabel}`;
12
+ }
13
+ /**
14
+ * Refuse a payload that carries what a release archive must never hold.
15
+ *
16
+ * The payload is the staged closure, so these are guards against a stage that
17
+ * grew something nobody meant to publish — a `.env`, a `.git`, a log — rather
18
+ * than checks a normal build trips. `node_modules` is legitimate exactly when
19
+ * the app runs on Node and the stage copied its closure; for `--app gjs` there
20
+ * is no reason for one to exist.
21
+ */
22
+ export function assertTarballHygiene(payload, settings) {
23
+ const problems = [];
24
+ for (const entry of payload) {
25
+ const segments = entry.path.split('/');
26
+ const base = segments[segments.length - 1];
27
+ if (base === '.env' || base.startsWith('.env.'))
28
+ problems.push(`${entry.path} (environment file)`);
29
+ else if (segments.includes('.git'))
30
+ problems.push(`${entry.path} (version-control data)`);
31
+ else if (base.endsWith('.log'))
32
+ problems.push(`${entry.path} (log file)`);
33
+ else if (segments.includes('node_modules') && settings.app !== 'node')
34
+ problems.push(`${entry.path} (node_modules in a non-Node payload)`);
35
+ }
36
+ if (problems.length === 0)
37
+ return;
38
+ throw new Error(`gjsify ship: refusing to pack a tarball that would contain ${problems.slice(0, 5).join(', ')}` +
39
+ `${problems.length > 5 ? ` and ${problems.length - 5} more` : ''}.`);
40
+ }
41
+ /**
42
+ * The archive: one directory entry per ancestor, then the payload, all under
43
+ * {@link tarballTopDir}. The file list is the payload's and nothing else — the
44
+ * stage's own sidecar was never payload.
45
+ */
46
+ export async function buildLinuxTarball(input) {
47
+ assertTarballHygiene(input.payload, input.settings);
48
+ const top = tarballTopDir(input.settings, input.archLabel);
49
+ const directories = new Set([`${top}/`]);
50
+ for (const entry of input.payload) {
51
+ const dir = posix.dirname(entry.path);
52
+ const parts = dir === '.' ? [] : dir.split('/');
53
+ let current = top;
54
+ for (const part of parts) {
55
+ current = `${current}/${part}`;
56
+ directories.add(`${current}/`);
57
+ }
58
+ }
59
+ const entries = [
60
+ ...[...directories].sort().map((name) => ({ name, mode: 0o755, mtime: input.mtime, directory: true })),
61
+ ...input.payload.map((entry) => ({
62
+ name: `${top}/${entry.path}`,
63
+ body: entry.data,
64
+ mode: entry.mode,
65
+ mtime: input.mtime,
66
+ })),
67
+ ];
68
+ return gzipDeterministic(createTarball(entries));
69
+ }
@@ -61,7 +61,7 @@ export interface ShipArtifact {
61
61
  * TEXTUALLY and fails if a comment gives it a second match, which is why this one
62
62
  * describes the union without quoting its head.
63
63
  */
64
- export type FormatId = 'deb' | 'rpm' | 'flatpak' | 'appimage' | 'macos-app' | 'macos-app-zip' | 'macos-app-dmg' | 'windows-dir' | 'windows-dir-zip' | 'msi';
64
+ export type FormatId = 'deb' | 'rpm' | 'flatpak' | 'appimage' | 'linux-tar' | 'linux-tar-flatpak' | 'macos-app' | 'macos-app-zip' | 'macos-app-dmg' | 'windows-dir' | 'windows-dir-zip' | 'msi';
65
65
  /**
66
66
  * The formats whose ARTIFACT carries a distro dependency list.
67
67
  *