@jskit-ai/jskit-catalog 0.2.80 → 0.2.82
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/catalog/packages.json +138 -138
- package/nix/package.nix.in +96 -0
- package/package.json +3 -2
- package/scripts/jskit.mjs +59 -4
- package/scripts/nix-app.mjs +185 -0
- package/scripts/package-nix.mjs +186 -0
- package/scripts/project-packages.mjs +81 -1
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
@MARKER@ (@jskit-ai/jskit-catalog). Do not edit it: run that command again.
|
|
2
|
+
# This JSKIT app as one Nix package, built with no network access from package.json and package-lock.json alone. Each
|
|
3
|
+
# npm download is fetched by the integrity hash package-lock.json gives it, so a changed lock file needs no change here
|
|
4
|
+
# and no hash to update. npm installs the lock from those files, runs the install scripts (node-gyp compiles a native
|
|
5
|
+
# addon against this Node), then the build script; the package keeps the app with its production dependencies and,
|
|
6
|
+
# in bin/, its programs. The JSKIT guide's "Package an App with Nix" describes them.
|
|
7
|
+
{ pkgs }:
|
|
8
|
+
let
|
|
9
|
+
inherit (pkgs) lib;
|
|
10
|
+
manifest = lib.importJSON ./package.json;
|
|
11
|
+
lock = lib.importJSON ./package-lock.json;
|
|
12
|
+
scripts = manifest.scripts or { };
|
|
13
|
+
# package.json's name without its scope, as a program name.
|
|
14
|
+
name = lib.stringAsChars (c: if builtins.match "[a-z0-9-]" c == null then "-" else c)
|
|
15
|
+
(lib.toLower (lib.last (lib.splitString "/" manifest.name)));
|
|
16
|
+
# The Node.js major version engines.node names first (26 in "26.x"), else Nixpkgs' default Node.js.
|
|
17
|
+
nodeMajor = builtins.match "[^0-9]*([0-9]+).*" (manifest.engines.node or "");
|
|
18
|
+
nodejs = if nodeMajor == null then pkgs.nodejs else pkgs."nodejs_${builtins.head nodeMajor}";
|
|
19
|
+
# Every package npm downloads, each fetched by the first hash of its integrity: not a workspace link, nor a package
|
|
20
|
+
# bundled inside another.
|
|
21
|
+
downloads = lib.filterAttrs (key: entry: builtins.match "https?://.*" (entry.resolved or "") != null && entry ? integrity)
|
|
22
|
+
lock.packages;
|
|
23
|
+
fetch = entry: pkgs.fetchurl {
|
|
24
|
+
name = lib.strings.sanitizeDerivationName (baseNameOf entry.resolved);
|
|
25
|
+
url = entry.resolved;
|
|
26
|
+
hash = builtins.head (lib.splitString " " entry.integrity);
|
|
27
|
+
};
|
|
28
|
+
tarballs = pkgs.writeText "${name}-npm-tarballs"
|
|
29
|
+
(lib.concatStrings (lib.unique (lib.mapAttrsToList (key: entry: "${entry.integrity} ${fetch entry}\n") downloads)));
|
|
30
|
+
# The app's sources, without what a checkout may hold that the build must not see: installed and built files, local
|
|
31
|
+
# state and secrets.
|
|
32
|
+
root = toString ./.;
|
|
33
|
+
source = lib.cleanSourceWith {
|
|
34
|
+
name = "${name}-source";
|
|
35
|
+
src = ./.;
|
|
36
|
+
filter = file: type:
|
|
37
|
+
let
|
|
38
|
+
base = baseNameOf file;
|
|
39
|
+
top = dirOf (toString file) == root;
|
|
40
|
+
in
|
|
41
|
+
!(builtins.elem base [ "node_modules" ".git" ]
|
|
42
|
+
|| (top && builtins.elem base [ "dist" ".jskit" "coverage" "test-results" "playwright-report" ])
|
|
43
|
+
|| (top && type == "symlink" && lib.hasPrefix "result" base)
|
|
44
|
+
|| (top && (base == ".env" || (lib.hasPrefix ".env." base && base != ".env.example"))));
|
|
45
|
+
};
|
|
46
|
+
# @jskit-ai/jskit-catalog's scripts/nix-app.mjs, which the programs run (and the build, to fill npm's cache).
|
|
47
|
+
launcher = pkgs.writeText "jskit-app.mjs" ''
|
|
48
|
+
@LAUNCHER@
|
|
49
|
+
'';
|
|
50
|
+
in
|
|
51
|
+
pkgs.stdenv.mkDerivation {
|
|
52
|
+
pname = name;
|
|
53
|
+
version = manifest.version or "0.0.0";
|
|
54
|
+
src = source;
|
|
55
|
+
nativeBuildInputs = [ nodejs pkgs.python3 pkgs.makeWrapper ];
|
|
56
|
+
env = {
|
|
57
|
+
npm_config_offline = "true";
|
|
58
|
+
npm_config_audit = "false";
|
|
59
|
+
npm_config_fund = "false";
|
|
60
|
+
npm_config_update_notifier = "false";
|
|
61
|
+
npm_config_nodedir = "${nodejs}";
|
|
62
|
+
};
|
|
63
|
+
dontStrip = true;
|
|
64
|
+
configurePhase = ''
|
|
65
|
+
runHook preConfigure
|
|
66
|
+
export HOME="$TMPDIR" npm_config_cache="$TMPDIR/npm-cache"
|
|
67
|
+
node ${launcher} npm-cache ${tarballs} "$npm_config_cache"
|
|
68
|
+
npm ci --ignore-scripts
|
|
69
|
+
patchShebangs node_modules
|
|
70
|
+
npm rebuild
|
|
71
|
+
patchShebangs node_modules
|
|
72
|
+
runHook postConfigure
|
|
73
|
+
'';
|
|
74
|
+
buildPhase = ''
|
|
75
|
+
runHook preBuild
|
|
76
|
+
${lib.optionalString (scripts ? build) "npm run build"}
|
|
77
|
+
runHook postBuild
|
|
78
|
+
'';
|
|
79
|
+
installPhase = ''
|
|
80
|
+
runHook preInstall
|
|
81
|
+
npm prune --omit=dev
|
|
82
|
+
mkdir -p "$out/lib" "$out/libexec/${name}"
|
|
83
|
+
cp -r . "$out/lib/${name}"
|
|
84
|
+
cp ${launcher} "$out/libexec/${name}/jskit-app.mjs"
|
|
85
|
+
program() {
|
|
86
|
+
makeWrapper ${lib.getExe nodejs} "$out/bin/$1" --add-flags \
|
|
87
|
+
"$out/libexec/${name}/jskit-app.mjs $2 --app $out/lib/${name} --shell ${pkgs.runtimeShell}"
|
|
88
|
+
}
|
|
89
|
+
program ${name} serve
|
|
90
|
+
program ${name}-check check
|
|
91
|
+
program ${name}-prepare prepare
|
|
92
|
+
${lib.optionalString (scripts ? "db:migrate") "program ${name}-migrate migrate"}
|
|
93
|
+
runHook postInstall
|
|
94
|
+
'';
|
|
95
|
+
meta.mainProgram = name;
|
|
96
|
+
}
|
package/package.json
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/jskit-catalog",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.82",
|
|
4
4
|
"description": "Published metadata catalog for JSKIT package metadata.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"files": [
|
|
7
7
|
"catalog",
|
|
8
|
-
"scripts"
|
|
8
|
+
"scripts",
|
|
9
|
+
"nix"
|
|
9
10
|
],
|
|
10
11
|
"bin": {
|
|
11
12
|
"jskit": "scripts/jskit.mjs"
|
package/scripts/jskit.mjs
CHANGED
|
@@ -14,6 +14,7 @@ import {
|
|
|
14
14
|
import { checkDataAccess, formatDataAccessReport } from "./data-access.mjs";
|
|
15
15
|
import { checkManifestCapabilities, formatManifestCapabilitiesReport } from "./manifest-capabilities.mjs";
|
|
16
16
|
import { checkMaterial3, formatMaterial3Report } from "./material3.mjs";
|
|
17
|
+
import { checkPackageNix, formatPackageNixReport, packageNix } from "./package-nix.mjs";
|
|
17
18
|
import { checkProject, updateProject } from "./project-packages.mjs";
|
|
18
19
|
import { runTests } from "./test-command.mjs";
|
|
19
20
|
import { checkTestRuns, formatTestRunsReport } from "./test-runs.mjs";
|
|
@@ -31,6 +32,7 @@ function usage() {
|
|
|
31
32
|
" jskit check m3 [<path> ...] [--root <path>]",
|
|
32
33
|
" jskit i18n export <locale> [--root <path>]",
|
|
33
34
|
" jskit i18n check <locale> [--root <path>]",
|
|
35
|
+
" jskit package nix [--root <path>]",
|
|
34
36
|
" jskit test [node options] [files or globs]",
|
|
35
37
|
"",
|
|
36
38
|
"Commands:",
|
|
@@ -54,7 +56,10 @@ function usage() {
|
|
|
54
56
|
" data-access lint rules for review. It fails when an application package's manifest",
|
|
55
57
|
" (jskit.capabilities) misses a capability its features (server providers) provide or require, or",
|
|
56
58
|
" provides one none of them does (manifest/capabilities), and lists each requirement no feature has,",
|
|
57
|
-
" which only install time may need, for review.",
|
|
59
|
+
" which only install time may need, for review. When the app has a package.nix that jskit package nix",
|
|
60
|
+
" wrote, it fails when that file is not the one this release writes (package/nix-current), when",
|
|
61
|
+
" package.json lacks what the package needs (package/nix-manifest), or when package-lock.json names a",
|
|
62
|
+
" dependency a build with no network cannot fetch by its hash (package/nix-offline).",
|
|
58
63
|
" check m3 Check application UI source against the JSKIT Material 3 guide alone, with each finding's guide",
|
|
59
64
|
" section and every exception: the whole app, or only the given files and directories (a section,",
|
|
60
65
|
" or a task's changed files). Plain jskit check applies the same rules to the whole app.",
|
|
@@ -62,6 +67,13 @@ function usage() {
|
|
|
62
67
|
" for translators, keeping existing translations and extra keys.",
|
|
63
68
|
" i18n check Compare src/locales/<locale>/jskit.json with the installed packages' English; fail on missing keys,",
|
|
64
69
|
" invalid messages or placeholder mismatches, and list extra keys and untranslated messages.",
|
|
70
|
+
" package nix Write package.nix, which builds the app as one Nix package with no network access: npm installs",
|
|
71
|
+
" package-lock.json from tarballs Nix fetched by their integrity hashes, runs the install scripts",
|
|
72
|
+
" and the build script, and the package keeps the app with its production dependencies. Its bin/",
|
|
73
|
+
" holds <name> (the start script), <name>-check, <name>-prepare and, with a db:migrate script,",
|
|
74
|
+
" <name>-migrate. The file is the same for every app, so a changed lock file needs no new one. It",
|
|
75
|
+
" writes nothing when the lock names a dependency it cannot fetch that way (git, a local file, no",
|
|
76
|
+
" integrity hash), the app has no start script, or a package.nix it did not write is there.",
|
|
65
77
|
" test Run node --test with these arguments, test files in parallel within the machine's test budget:",
|
|
66
78
|
" V64_TEST_CONCURRENCY when it is a positive whole number, otherwise half of the machine's CPUs",
|
|
67
79
|
" (at least 1). A file whose first line is `// jskit-test: alone - <reason>` runs after the others,",
|
|
@@ -98,7 +110,7 @@ function parseArgs(argv = []) {
|
|
|
98
110
|
options.help = true;
|
|
99
111
|
continue;
|
|
100
112
|
}
|
|
101
|
-
if ((command === "i18n" || command === "check") && argument && !argument.startsWith("-")) {
|
|
113
|
+
if ((command === "i18n" || command === "check" || command === "package") && argument && !argument.startsWith("-")) {
|
|
102
114
|
positionals.push(argument);
|
|
103
115
|
continue;
|
|
104
116
|
}
|
|
@@ -133,6 +145,9 @@ function parseArgs(argv = []) {
|
|
|
133
145
|
if (command === "i18n") {
|
|
134
146
|
return parseI18nArgs(options, positionals);
|
|
135
147
|
}
|
|
148
|
+
if (command === "package") {
|
|
149
|
+
return parsePackageArgs(options, positionals);
|
|
150
|
+
}
|
|
136
151
|
if (command === "check" && positionals.length > 0) {
|
|
137
152
|
return parseMaterial3Args(options, positionals);
|
|
138
153
|
}
|
|
@@ -189,6 +204,40 @@ function parseMaterial3Args(options, positionals) {
|
|
|
189
204
|
};
|
|
190
205
|
}
|
|
191
206
|
|
|
207
|
+
function parsePackageArgs(options, positionals) {
|
|
208
|
+
const [kind, unexpected] = positionals;
|
|
209
|
+
if (!kind) {
|
|
210
|
+
throw new Error(usage());
|
|
211
|
+
}
|
|
212
|
+
if (kind !== "nix") {
|
|
213
|
+
throw new Error(`Unknown argument: ${kind}`);
|
|
214
|
+
}
|
|
215
|
+
if (unexpected !== undefined) {
|
|
216
|
+
throw new Error(`Unknown argument: ${unexpected}`);
|
|
217
|
+
}
|
|
218
|
+
if (options.additionalManifests) {
|
|
219
|
+
throw new Error("--manifest is only valid with jskit update and jskit check.");
|
|
220
|
+
}
|
|
221
|
+
if (!options.install) {
|
|
222
|
+
throw new Error("--no-install is only valid with jskit update.");
|
|
223
|
+
}
|
|
224
|
+
return { command: "package-nix", projectRoot: options.projectRoot };
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
async function runPackageNix({ projectRoot }) {
|
|
228
|
+
const result = await packageNix({ projectRoot });
|
|
229
|
+
if (!result.ok) {
|
|
230
|
+
throw new Error(`jskit package nix wrote nothing:\n- ${result.issues.join("\n- ")}`);
|
|
231
|
+
}
|
|
232
|
+
const node = result.node ? `Node.js ${result.node}` : "Nixpkgs' default Node.js (package.json names no engines.node)";
|
|
233
|
+
process.stdout.write([
|
|
234
|
+
`${result.changed ? "Wrote package.nix" : "package.nix is already current"}: ${result.name} ${result.version} on ${node}, ` +
|
|
235
|
+
`${result.downloads} npm downloads pinned by package-lock.json. Commit it; it needs no change when the lock does.`,
|
|
236
|
+
"Its programs, in the package's bin/:",
|
|
237
|
+
...result.programs.map(({ name, does }) => `- ${name} ${does}`)
|
|
238
|
+
].join("\n") + "\n");
|
|
239
|
+
}
|
|
240
|
+
|
|
192
241
|
async function runMaterial3({ projectRoot, paths }) {
|
|
193
242
|
const result = await checkMaterial3({ projectRoot, paths });
|
|
194
243
|
const report = formatMaterial3Report(result);
|
|
@@ -230,6 +279,10 @@ async function main(argv = process.argv.slice(2)) {
|
|
|
230
279
|
await runMaterial3(options);
|
|
231
280
|
return;
|
|
232
281
|
}
|
|
282
|
+
if (options.command === "package-nix") {
|
|
283
|
+
await runPackageNix(options);
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
233
286
|
if (options.command === "test") {
|
|
234
287
|
process.exitCode = await runTests(options.args);
|
|
235
288
|
return;
|
|
@@ -280,6 +333,7 @@ async function main(argv = process.argv.slice(2)) {
|
|
|
280
333
|
const tests = await checkTestRuns({ projectRoot: options.projectRoot, manifests: result.manifests });
|
|
281
334
|
const data = await checkDataAccess({ projectRoot: options.projectRoot });
|
|
282
335
|
const capabilities = await checkManifestCapabilities({ projectRoot: options.projectRoot, manifests: result.manifests });
|
|
336
|
+
const nixPackage = await checkPackageNix({ projectRoot: options.projectRoot });
|
|
283
337
|
// The data rules first: a graph that fails on many pin versions would otherwise bury them.
|
|
284
338
|
const reports = [
|
|
285
339
|
formatDataAccessReport(data),
|
|
@@ -289,9 +343,10 @@ async function main(argv = process.argv.slice(2)) {
|
|
|
289
343
|
: `JSKIT project graph is inconsistent:\n- ${result.issues.join("\n- ")}`,
|
|
290
344
|
formatMaterial3Report(ui),
|
|
291
345
|
formatTestRunsReport(tests),
|
|
292
|
-
formatManifestCapabilitiesReport(capabilities)
|
|
346
|
+
formatManifestCapabilitiesReport(capabilities),
|
|
347
|
+
formatPackageNixReport(nixPackage)
|
|
293
348
|
];
|
|
294
|
-
if (!result.ok || !ui.ok || !tests.ok || !data.ok || !capabilities.ok) {
|
|
349
|
+
if (!result.ok || !ui.ok || !tests.ok || !data.ok || !capabilities.ok || !nixPackage.ok) {
|
|
295
350
|
throw new Error(reports.join("\n"));
|
|
296
351
|
}
|
|
297
352
|
process.stdout.write(`${reports.join("\n")}\n`);
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
// The programs of a JSKIT app that `jskit package nix` packaged. The package.nix it writes embeds this file whole, so
|
|
2
|
+
// it imports only Node's own modules. The package's bin/ runs it with the app's folder (--app) and a shell (--shell):
|
|
3
|
+
//
|
|
4
|
+
// <app> [--env FILE] [--migrate] serve: the app's start script, in place of this process
|
|
5
|
+
// <app>-migrate [--env FILE] migrate: its db:migrate script, in place of this process
|
|
6
|
+
// <app>-check [--env FILE] check: exits 0 once GET /api/health answers 200, 1 after --wait seconds (60)
|
|
7
|
+
// <app>-prepare --settings JSON --env FILE [--user NAME]
|
|
8
|
+
// prepare: the settings, one JSON object, written as FILE for NAME alone
|
|
9
|
+
//
|
|
10
|
+
// A script runs as `npm run` would run it, with no npm: from the app's folder, by the shell, with node_modules/.bin
|
|
11
|
+
// and this Node first on PATH, NODE_ENV=production unless the environment or the env file says otherwise, and the
|
|
12
|
+
// env file's variables (Node's .env format) over the environment's. The option is --env, not --env-file: Node reads
|
|
13
|
+
// an --env-file anywhere on its command line, even after the script, and fails when the file is not there yet.
|
|
14
|
+
// The package's build runs `npm-cache LIST DIR`:
|
|
15
|
+
// it files each tarball LIST names (one `<integrity> <file>` line each) in npm's cache at DIR, by every hash of its
|
|
16
|
+
// integrity, where `npm ci` looks before it would download, so npm installs package-lock.json with no network.
|
|
17
|
+
import { spawnSync } from "node:child_process";
|
|
18
|
+
import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
|
19
|
+
import path from "node:path";
|
|
20
|
+
import process from "node:process";
|
|
21
|
+
import { fileURLToPath } from "node:url";
|
|
22
|
+
import { parseArgs, parseEnv } from "node:util";
|
|
23
|
+
|
|
24
|
+
const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/u;
|
|
25
|
+
// The quotes a value can be written in, as Node's .env parser reads them back: single quotes and backticks keep it
|
|
26
|
+
// as written; double quotes turn \n into a new line, so they hold only a value without a backslash.
|
|
27
|
+
const QUOTES = Object.freeze(["'", "`", "\""]);
|
|
28
|
+
const HEALTH_PATH = "/api/health";
|
|
29
|
+
const MODES = Object.freeze(["serve", "migrate", "check", "prepare", "npm-cache"]);
|
|
30
|
+
|
|
31
|
+
class Refusal extends Error {}
|
|
32
|
+
|
|
33
|
+
const isObject = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The settings as an env file Node reads back exactly (`process.loadEnvFile`, `util.parseEnv`), one quoted line each.
|
|
37
|
+
* @param {unknown} settings one JSON object: an environment variable's name to a string, a number or true or false
|
|
38
|
+
*/
|
|
39
|
+
function formatEnvFile(settings) {
|
|
40
|
+
if (!isObject(settings)) throw new Refusal("The settings must be one JSON object of environment variables.");
|
|
41
|
+
return Object.entries(settings).map(([name, value]) => {
|
|
42
|
+
if (!ENV_NAME.test(name)) {
|
|
43
|
+
throw new Refusal(`The setting ${name} is not an environment variable name (letters, digits and _, not first a digit).`);
|
|
44
|
+
}
|
|
45
|
+
if (!["string", "number", "boolean"].includes(typeof value)) {
|
|
46
|
+
throw new Refusal(`The setting ${name} must be a string, a number or true or false.`);
|
|
47
|
+
}
|
|
48
|
+
const text = String(value);
|
|
49
|
+
const quote = QUOTES.find((mark) => !text.includes(mark) && (mark !== "\"" || !text.includes("\\")));
|
|
50
|
+
if (!quote) throw new Refusal(`The setting ${name} holds ', \` and " together, which an env file cannot hold.`);
|
|
51
|
+
return `${name}=${quote}${text}${quote}\n`;
|
|
52
|
+
}).join("");
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The environment a script of the app runs with. */
|
|
56
|
+
function scriptEnvironment({ app, envFile }) {
|
|
57
|
+
const env = { ...process.env, ...(envFile ? parseEnv(readFileSync(envFile, "utf8")) : {}) };
|
|
58
|
+
env.NODE_ENV ||= "production";
|
|
59
|
+
env.PATH = [path.join(app, "node_modules", ".bin"), path.dirname(process.execPath), env.PATH].filter(Boolean).join(":");
|
|
60
|
+
return env;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function scriptOf(app, name) {
|
|
64
|
+
const manifest = JSON.parse(readFileSync(path.join(app, "package.json"), "utf8"));
|
|
65
|
+
const script = manifest.scripts?.[name];
|
|
66
|
+
if (typeof script !== "string" || !script.trim()) throw new Refusal(`${manifest.name ?? app} has no ${name} script.`);
|
|
67
|
+
return script;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Runs the app's script `name` in place of this process; with `first`, runs that script before it and stops on failure. */
|
|
71
|
+
function replaceWithScript({ app, shell, envFile, name, first }) {
|
|
72
|
+
const env = scriptEnvironment({ app, envFile });
|
|
73
|
+
const script = scriptOf(app, name);
|
|
74
|
+
if (first) {
|
|
75
|
+
const ran = spawnSync(shell, ["-c", scriptOf(app, first)], { cwd: app, env: { ...env, npm_lifecycle_event: first }, stdio: "inherit" });
|
|
76
|
+
if (ran.error) throw ran.error;
|
|
77
|
+
if (ran.status !== 0) return ran.status ?? 1;
|
|
78
|
+
}
|
|
79
|
+
process.chdir(app);
|
|
80
|
+
process.execve(shell, [shell, "-c", script], { ...env, npm_lifecycle_event: name });
|
|
81
|
+
return 1;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async function check({ envFile, wait }) {
|
|
85
|
+
const env = envFile ? { ...process.env, ...parseEnv(readFileSync(envFile, "utf8")) } : process.env;
|
|
86
|
+
const port = Number.parseInt(String(env.PORT ?? ""), 10) || 3000;
|
|
87
|
+
const host = !env.HOST || env.HOST === "0.0.0.0" || env.HOST === "::" ? "127.0.0.1" : env.HOST;
|
|
88
|
+
const url = `http://${host.includes(":") ? `[${host}]` : host}:${port}${HEALTH_PATH}`;
|
|
89
|
+
const deadline = Date.now() + wait * 1000;
|
|
90
|
+
let last = "no answer";
|
|
91
|
+
do {
|
|
92
|
+
try {
|
|
93
|
+
const response = await fetch(url, { signal: AbortSignal.timeout(5000) });
|
|
94
|
+
const body = (await response.text()).slice(0, 2000);
|
|
95
|
+
if (response.status === 200) {
|
|
96
|
+
process.stdout.write(`${body}\n`);
|
|
97
|
+
return 0;
|
|
98
|
+
}
|
|
99
|
+
last = `${HEALTH_PATH} answered ${response.status}: ${body}`;
|
|
100
|
+
} catch (error) {
|
|
101
|
+
last = error.cause?.code ?? error.message;
|
|
102
|
+
}
|
|
103
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
104
|
+
} while (Date.now() < deadline);
|
|
105
|
+
process.stderr.write(`${url} did not answer 200 within ${wait} s: ${last}\n`);
|
|
106
|
+
return 1;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function prepare({ settings, envFile, user }) {
|
|
110
|
+
if (!settings || !envFile) throw new Refusal("prepare needs --settings FILE and --env FILE.");
|
|
111
|
+
const text = formatEnvFile(JSON.parse(readFileSync(settings, "utf8")));
|
|
112
|
+
mkdirSync(path.dirname(envFile), { recursive: true });
|
|
113
|
+
const temporary = `${envFile}.${process.pid}.tmp`;
|
|
114
|
+
try {
|
|
115
|
+
writeFileSync(temporary, text, { mode: 0o600 });
|
|
116
|
+
if (user) {
|
|
117
|
+
// The host's own chown names the user, through whichever account databases the host keeps.
|
|
118
|
+
const owned = spawnSync("chown", ["--", `${user}:`, temporary], { encoding: "utf8" });
|
|
119
|
+
if (owned.error || owned.status !== 0) throw new Refusal(`chown ${user}: ${owned.stderr || owned.error?.message}`.trim());
|
|
120
|
+
}
|
|
121
|
+
renameSync(temporary, envFile);
|
|
122
|
+
} finally {
|
|
123
|
+
rmSync(temporary, { force: true });
|
|
124
|
+
}
|
|
125
|
+
return 0;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function npmCache(list, cache) {
|
|
129
|
+
for (const line of readFileSync(list, "utf8").split("\n")) {
|
|
130
|
+
const words = line.split(/\s+/u).filter(Boolean);
|
|
131
|
+
const file = words.pop();
|
|
132
|
+
for (const hash of words) {
|
|
133
|
+
const separator = hash.indexOf("-");
|
|
134
|
+
const hex = Buffer.from(hash.slice(separator + 1), "base64").toString("hex");
|
|
135
|
+
const entry = path.join(cache, "_cacache", "content-v2", hash.slice(0, separator), hex.slice(0, 2), hex.slice(2, 4), hex.slice(4));
|
|
136
|
+
mkdirSync(path.dirname(entry), { recursive: true });
|
|
137
|
+
if (!existsSync(entry)) symlinkSync(file, entry);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return 0;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function main(argv = process.argv.slice(2)) {
|
|
144
|
+
const { values, positionals } = parseArgs({
|
|
145
|
+
args: argv,
|
|
146
|
+
allowPositionals: true,
|
|
147
|
+
options: {
|
|
148
|
+
app: { type: "string" },
|
|
149
|
+
shell: { type: "string", default: "/bin/sh" },
|
|
150
|
+
env: { type: "string" },
|
|
151
|
+
migrate: { type: "boolean", default: false },
|
|
152
|
+
settings: { type: "string" },
|
|
153
|
+
user: { type: "string" },
|
|
154
|
+
wait: { type: "string", default: "60" }
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
const [mode, ...rest] = positionals;
|
|
158
|
+
if (!MODES.includes(mode)) throw new Refusal(`The mode must be one of ${MODES.join(", ")}: ${mode}`);
|
|
159
|
+
const app = values.app ? path.resolve(values.app) : process.cwd();
|
|
160
|
+
const envFile = values.env ? path.resolve(values.env) : null;
|
|
161
|
+
if (mode === "serve") return replaceWithScript({ app, shell: values.shell, envFile, name: "start", first: values.migrate ? "db:migrate" : null });
|
|
162
|
+
if (mode === "migrate") return replaceWithScript({ app, shell: values.shell, envFile, name: "db:migrate" });
|
|
163
|
+
if (mode === "check") return check({ envFile, wait: Number(values.wait) || 60 });
|
|
164
|
+
if (mode === "prepare") return prepare({ settings: values.settings, envFile, user: values.user });
|
|
165
|
+
return npmCache(rest[0], rest[1]);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function isCliEntrypoint(argvPath = process.argv[1]) {
|
|
169
|
+
try {
|
|
170
|
+
return Boolean(argvPath) && realpathSync(argvPath) === realpathSync(fileURLToPath(import.meta.url));
|
|
171
|
+
} catch {
|
|
172
|
+
return false;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
if (isCliEntrypoint()) {
|
|
177
|
+
main().then((code) => {
|
|
178
|
+
process.exitCode = code;
|
|
179
|
+
}, (error) => {
|
|
180
|
+
process.stderr.write(`${error instanceof Refusal ? error.message : error.stack ?? error}\n`);
|
|
181
|
+
process.exitCode = 1;
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export { formatEnvFile, main };
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { readFile, writeFile } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
// `jskit package nix`, and its part of plain `jskit check`: the app as one Nix package that builds with no network
|
|
6
|
+
// access, for a host that runs apps only as Nix packages. package.nix is the same file for every app (it reads
|
|
7
|
+
// package.json and package-lock.json while Nix evaluates it), so this writes nothing about the app: it refuses an app
|
|
8
|
+
// the file cannot build, and never overwrites a package.nix it did not write. The template is nix/package.nix.in,
|
|
9
|
+
// which embeds scripts/nix-app.mjs, the package's programs.
|
|
10
|
+
|
|
11
|
+
const PACKAGE_NIX_MARKER = "# Generated by `jskit package nix`";
|
|
12
|
+
const GUIDE = "https://mobily-enterprises.github.io/jskit-ai/guide/app-setup/package-with-nix";
|
|
13
|
+
const TEMPLATE_URL = new URL("../nix/package.nix.in", import.meta.url);
|
|
14
|
+
const LAUNCHER_URL = new URL("./nix-app.mjs", import.meta.url);
|
|
15
|
+
const REMOTE = /^https?:\/\//u;
|
|
16
|
+
const GIT = /^(?:git\+|git:|github:|gitlab:|bitbucket:)/u;
|
|
17
|
+
|
|
18
|
+
const isObject = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
19
|
+
|
|
20
|
+
let rendered = null;
|
|
21
|
+
|
|
22
|
+
/** The package.nix this release writes, for every app. */
|
|
23
|
+
function renderPackageNix() {
|
|
24
|
+
if (rendered === null) {
|
|
25
|
+
// Nix's indented string: '' is written ''' and ${ is written ''${; the indentation every line shares is dropped.
|
|
26
|
+
const launcher = readFileSync(LAUNCHER_URL, "utf8").replace(/\n$/u, "")
|
|
27
|
+
.replace(/''/gu, "'''")
|
|
28
|
+
.replace(/\$\{/gu, "''${")
|
|
29
|
+
.split("\n")
|
|
30
|
+
.map((line) => (line ? ` ${line}` : line))
|
|
31
|
+
.join("\n");
|
|
32
|
+
rendered = readFileSync(TEMPLATE_URL, "utf8")
|
|
33
|
+
.replace("@MARKER@", () => PACKAGE_NIX_MARKER)
|
|
34
|
+
.replace("@LAUNCHER@", () => launcher);
|
|
35
|
+
}
|
|
36
|
+
return rendered;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** package.json's name without its scope, as a program name: what package.nix names the package and its programs. */
|
|
40
|
+
function nixPackageName(name) {
|
|
41
|
+
return String(name).split("/").at(-1).toLowerCase().replace(/[^a-z0-9-]/gu, "-");
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** What in package-lock.json's packages a build with no network cannot install: each a sentence. */
|
|
45
|
+
function lockIssues(packages) {
|
|
46
|
+
const issues = [];
|
|
47
|
+
for (const [key, entry] of Object.entries(packages)) {
|
|
48
|
+
// The root and the workspaces' own folders are the app's source; a bundled package comes inside its parent.
|
|
49
|
+
if (!key.startsWith("node_modules/") && !key.includes("/node_modules/")) continue;
|
|
50
|
+
if (!isObject(entry) || entry.inBundle) continue;
|
|
51
|
+
const resolved = typeof entry.resolved === "string" ? entry.resolved : "";
|
|
52
|
+
if (entry.link) {
|
|
53
|
+
if (path.isAbsolute(resolved) || resolved.split("/")[0] === "..") {
|
|
54
|
+
issues.push(`${key} links to ${resolved}, outside the app, and a build sees only the app's folder: make it one of the ` +
|
|
55
|
+
"app's workspaces, or publish it to a registry.");
|
|
56
|
+
}
|
|
57
|
+
} else if (GIT.test(resolved)) {
|
|
58
|
+
issues.push(`${key} comes from git (${resolved}), and a build with no network fetches only registry tarballs, by their ` +
|
|
59
|
+
"hash: publish it to a registry, or make it one of the app's workspaces.");
|
|
60
|
+
} else if (resolved.startsWith("file:")) {
|
|
61
|
+
issues.push(`${key} is a local file (${resolved}): make it one of the app's workspaces, or publish it to a registry.`);
|
|
62
|
+
} else if (!resolved) {
|
|
63
|
+
issues.push(`${key} has no resolved address in package-lock.json: run npm install to complete the lock file.`);
|
|
64
|
+
} else if (!REMOTE.test(resolved)) {
|
|
65
|
+
issues.push(`${key} comes from ${resolved}, which is not a tarball a build can fetch by its hash.`);
|
|
66
|
+
} else if (typeof entry.integrity !== "string" || !entry.integrity.trim()) {
|
|
67
|
+
issues.push(`${key} has no integrity hash in package-lock.json, and a build fetches each download by its hash: ` +
|
|
68
|
+
"reinstall it (npm install) so that npm records one.");
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return issues;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function readJson(file) {
|
|
75
|
+
try {
|
|
76
|
+
return { value: JSON.parse(await readFile(file, "utf8")) };
|
|
77
|
+
} catch (error) {
|
|
78
|
+
if (error.code === "ENOENT") return { missing: true };
|
|
79
|
+
return { error: `${path.basename(file)} is not JSON: ${error.message}` };
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The app's facts and what keeps package.nix from building it: `manifest` and `lock` issues apart. */
|
|
84
|
+
async function analyseApp(projectRoot) {
|
|
85
|
+
const manifest = await readJson(path.join(projectRoot, "package.json"));
|
|
86
|
+
const lock = await readJson(path.join(projectRoot, "package-lock.json"));
|
|
87
|
+
const issues = { manifest: [], lock: [] };
|
|
88
|
+
const app = isObject(manifest.value) ? manifest.value : {};
|
|
89
|
+
if (manifest.missing) issues.manifest.push(`The app has no package.json at ${projectRoot}.`);
|
|
90
|
+
else if (manifest.error) issues.manifest.push(manifest.error);
|
|
91
|
+
else {
|
|
92
|
+
if (typeof app.name !== "string" || !app.name.trim()) {
|
|
93
|
+
issues.manifest.push("package.json has no name: the package and its programs are named after it.");
|
|
94
|
+
}
|
|
95
|
+
if (typeof app.scripts?.start !== "string" || !app.scripts.start.trim()) {
|
|
96
|
+
issues.manifest.push("package.json has no start script: the package's main program runs it, as npm start does.");
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const packages = isObject(lock.value?.packages) ? lock.value.packages : {};
|
|
100
|
+
if (lock.missing) issues.lock.push("The app has no package-lock.json: run npm install to write it, as the package installs what it locks.");
|
|
101
|
+
else if (lock.error) issues.lock.push(lock.error);
|
|
102
|
+
else if (!(Number(lock.value?.lockfileVersion) >= 2) || !isObject(lock.value?.packages)) {
|
|
103
|
+
issues.lock.push(`package-lock.json is lockfileVersion ${lock.value?.lockfileVersion ?? "unknown"}, and the package reads ` +
|
|
104
|
+
"lockfileVersion 2 or 3 (npm 7 and later): run npm install --lockfile-version 3.");
|
|
105
|
+
} else {
|
|
106
|
+
issues.lock.push(...lockIssues(packages));
|
|
107
|
+
}
|
|
108
|
+
const downloads = new Set(Object.values(packages)
|
|
109
|
+
.filter((entry) => isObject(entry) && REMOTE.test(String(entry.resolved ?? "")) && typeof entry.integrity === "string")
|
|
110
|
+
.map((entry) => `${entry.integrity} ${entry.resolved}`));
|
|
111
|
+
const name = nixPackageName(app.name ?? "");
|
|
112
|
+
const programs = [
|
|
113
|
+
{ name, does: "[--env FILE] [--migrate]: the start script, from the app's folder, NODE_ENV=production by default" },
|
|
114
|
+
{ name: `${name}-check`, does: "[--env FILE]: exits 0 once GET /api/health answers 200 on PORT (3000)" },
|
|
115
|
+
{ name: `${name}-prepare`, does: "--settings JSON --env FILE [--user NAME]: the settings as an env file for that user" },
|
|
116
|
+
...(typeof app.scripts?.["db:migrate"] === "string" ? [{ name: `${name}-migrate`, does: "[--env FILE]: the db:migrate script" }] : [])
|
|
117
|
+
];
|
|
118
|
+
return {
|
|
119
|
+
issues,
|
|
120
|
+
name,
|
|
121
|
+
version: typeof app.version === "string" ? app.version : "0.0.0",
|
|
122
|
+
node: /^[^0-9]*([0-9]+)/u.exec(String(app.engines?.node ?? ""))?.[1] ?? null,
|
|
123
|
+
downloads: downloads.size,
|
|
124
|
+
programs
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async function readPackageNix(projectRoot) {
|
|
129
|
+
try {
|
|
130
|
+
return await readFile(path.join(projectRoot, "package.nix"), "utf8");
|
|
131
|
+
} catch (error) {
|
|
132
|
+
if (error.code === "ENOENT") return null;
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Writes the app's package.nix unless something keeps it from building the app, or a package.nix it did not write is
|
|
139
|
+
* there. Answers what it found, and `changed` when it wrote the file.
|
|
140
|
+
* @param {{ projectRoot: string }} options
|
|
141
|
+
*/
|
|
142
|
+
async function packageNix({ projectRoot }) {
|
|
143
|
+
const { issues, ...facts } = await analyseApp(projectRoot);
|
|
144
|
+
const file = path.join(projectRoot, "package.nix");
|
|
145
|
+
const existing = await readPackageNix(projectRoot);
|
|
146
|
+
const refusals = [...issues.manifest, ...issues.lock];
|
|
147
|
+
if (existing !== null && !existing.startsWith(PACKAGE_NIX_MARKER)) {
|
|
148
|
+
refusals.push("package.nix is not one jskit package nix wrote, so it stays: move it away for JSKIT to package the app.");
|
|
149
|
+
}
|
|
150
|
+
if (refusals.length > 0) return { ok: false, issues: refusals, file, changed: false, ...facts };
|
|
151
|
+
const text = renderPackageNix();
|
|
152
|
+
if (existing !== text) await writeFile(file, text);
|
|
153
|
+
return { ok: true, issues: [], file, changed: existing !== text, ...facts };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Plain `jskit check`'s part: a package.nix that jskit package nix wrote must be this release's, and the app must still
|
|
158
|
+
* build with it. A hand-written package.nix, or none, is left alone.
|
|
159
|
+
* @param {{ projectRoot: string }} options
|
|
160
|
+
*/
|
|
161
|
+
async function checkPackageNix({ projectRoot }) {
|
|
162
|
+
const existing = await readPackageNix(projectRoot);
|
|
163
|
+
if (existing === null || !existing.startsWith(PACKAGE_NIX_MARKER)) return { ok: true, packaged: false, findings: [] };
|
|
164
|
+
const { issues } = await analyseApp(projectRoot);
|
|
165
|
+
const findings = [
|
|
166
|
+
...(existing === renderPackageNix() ? [] : [{
|
|
167
|
+
file: "package.nix",
|
|
168
|
+
rule: "package/nix-current",
|
|
169
|
+
message: "package.nix is not the one this JSKIT release writes: run npx jskit package nix."
|
|
170
|
+
}]),
|
|
171
|
+
...issues.manifest.map((message) => ({ file: "package.json", rule: "package/nix-manifest", message })),
|
|
172
|
+
...issues.lock.map((message) => ({ file: "package-lock.json", rule: "package/nix-offline", message }))
|
|
173
|
+
];
|
|
174
|
+
return { ok: findings.length === 0, packaged: true, findings };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function formatPackageNixReport(result) {
|
|
178
|
+
if (!result.packaged) return "JSKIT Nix package: none (jskit package nix writes package.nix).";
|
|
179
|
+
const lines = result.findings.flatMap(({ file, rule, message }) => [`${file} ${rule} ${message}`, ` ${GUIDE}`]);
|
|
180
|
+
lines.push(result.ok
|
|
181
|
+
? "JSKIT Nix package: package.nix is current and package-lock.json builds offline."
|
|
182
|
+
: `JSKIT Nix package: ${result.findings.length} error(s); the app's package.nix cannot build it as it is.`);
|
|
183
|
+
return lines.join("\n");
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export { PACKAGE_NIX_MARKER, checkPackageNix, formatPackageNixReport, nixPackageName, packageNix, renderPackageNix };
|