@sublang/spex 4.2.0 → 5.0.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.
Files changed (100) hide show
  1. package/README.md +433 -89
  2. package/dist/cli.js +80 -42
  3. package/dist/commands/add.d.ts +12 -0
  4. package/dist/commands/add.js +138 -0
  5. package/dist/commands/auth-target.d.ts +11 -0
  6. package/dist/commands/auth-target.js +50 -0
  7. package/dist/commands/environment.d.ts +123 -0
  8. package/dist/commands/environment.js +411 -0
  9. package/dist/commands/export.d.ts +21 -0
  10. package/dist/commands/export.js +663 -0
  11. package/dist/commands/home.d.ts +56 -0
  12. package/dist/commands/home.js +215 -0
  13. package/dist/commands/install.d.ts +2 -0
  14. package/dist/commands/install.js +48 -0
  15. package/dist/commands/list.d.ts +2 -0
  16. package/dist/commands/list.js +87 -0
  17. package/dist/commands/login.d.ts +2 -0
  18. package/dist/commands/login.js +211 -0
  19. package/dist/commands/logout.d.ts +2 -0
  20. package/dist/commands/logout.js +74 -0
  21. package/dist/commands/publish.d.ts +2 -0
  22. package/dist/commands/publish.js +120 -0
  23. package/dist/commands/remove.d.ts +2 -0
  24. package/dist/commands/remove.js +34 -0
  25. package/dist/commands/run.d.ts +50 -0
  26. package/dist/commands/run.js +309 -0
  27. package/dist/commands/search.d.ts +2 -0
  28. package/dist/commands/search.js +34 -0
  29. package/dist/commands/settle.d.ts +124 -0
  30. package/dist/commands/settle.js +475 -0
  31. package/dist/commands/update.d.ts +2 -0
  32. package/dist/commands/update.js +37 -0
  33. package/dist/commands/whoami.d.ts +2 -0
  34. package/dist/commands/whoami.js +75 -0
  35. package/dist/lib/environment/agent-folders.d.ts +14 -0
  36. package/dist/lib/environment/agent-folders.js +11 -0
  37. package/dist/lib/environment/archive.d.ts +26 -0
  38. package/dist/lib/environment/archive.js +91 -0
  39. package/dist/lib/environment/builtins.d.ts +112 -0
  40. package/dist/lib/environment/builtins.js +539 -0
  41. package/dist/lib/environment/citations.d.ts +75 -0
  42. package/dist/lib/environment/citations.js +267 -0
  43. package/dist/lib/environment/exports.d.ts +190 -0
  44. package/dist/lib/environment/exports.js +1029 -0
  45. package/dist/lib/environment/format.d.ts +133 -0
  46. package/dist/lib/environment/format.js +651 -0
  47. package/dist/lib/environment/git-source.d.ts +41 -0
  48. package/dist/lib/environment/git-source.js +159 -0
  49. package/dist/lib/environment/index.d.ts +20 -0
  50. package/dist/lib/environment/index.js +27 -0
  51. package/dist/lib/environment/install.d.ts +140 -0
  52. package/dist/lib/environment/install.js +694 -0
  53. package/dist/lib/environment/layout.d.ts +15 -0
  54. package/dist/lib/environment/layout.js +50 -0
  55. package/dist/lib/environment/lock.d.ts +87 -0
  56. package/dist/lib/environment/lock.js +305 -0
  57. package/dist/lib/environment/marker.d.ts +15 -0
  58. package/dist/lib/environment/marker.js +31 -0
  59. package/dist/lib/environment/own-paths.d.ts +59 -0
  60. package/dist/lib/environment/own-paths.js +174 -0
  61. package/dist/lib/environment/placed-record.d.ts +32 -0
  62. package/dist/lib/environment/placed-record.js +72 -0
  63. package/dist/lib/environment/registries.d.ts +25 -0
  64. package/dist/lib/environment/registries.js +75 -0
  65. package/dist/lib/environment/registry.d.ts +173 -0
  66. package/dist/lib/environment/registry.js +390 -0
  67. package/dist/lib/environment/requests.d.ts +108 -0
  68. package/dist/lib/environment/requests.js +403 -0
  69. package/dist/lib/environment/resolve.d.ts +70 -0
  70. package/dist/lib/environment/resolve.js +451 -0
  71. package/dist/lib/environment/semver.d.ts +30 -0
  72. package/dist/lib/environment/semver.js +130 -0
  73. package/dist/lib/environment/store.d.ts +23 -0
  74. package/dist/lib/environment/store.js +123 -0
  75. package/dist/lib/environment/tar.d.ts +27 -0
  76. package/dist/lib/environment/tar.js +219 -0
  77. package/dist/lib/files.d.ts +66 -0
  78. package/dist/lib/files.js +233 -0
  79. package/dist/lib/git-host.d.ts +579 -0
  80. package/dist/lib/git-host.js +1363 -0
  81. package/dist/lib/home-file.d.ts +124 -0
  82. package/dist/lib/home-file.js +288 -0
  83. package/dist/lib/instance.d.ts +63 -0
  84. package/dist/lib/instance.js +130 -0
  85. package/dist/lib/words.d.ts +32 -0
  86. package/dist/lib/words.js +27 -0
  87. package/dist/lint.js +8 -0
  88. package/dist/testing/index.d.ts +1 -0
  89. package/dist/testing/index.js +7 -0
  90. package/dist/testing/standin-registry.d.ts +94 -0
  91. package/dist/testing/standin-registry.js +449 -0
  92. package/package.json +37 -3
  93. package/dist/attached-cli.d.ts +0 -13
  94. package/dist/attached-cli.js +0 -249
  95. package/dist/attached-client.d.ts +0 -53
  96. package/dist/attached-client.js +0 -237
  97. package/dist/generated-protocol.d.ts +0 -2
  98. package/dist/generated-protocol.js +0 -6
  99. package/dist/package-init.d.ts +0 -21
  100. package/dist/package-init.js +0 -442
@@ -0,0 +1,694 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
+ // Installing a locked environment (environments-7, DR-104, DR-165): the
4
+ // lock's selected files, verified by digest into the store, are linked
5
+ // under `<root>/.spex/packages/<org>/<pkg>/` at their release paths, the
6
+ // environment's root holding `.spex/` with a `.gitignore` of `*`, so Git
7
+ // ignores the installed tree (environments-26). A registry
8
+ // package is fetched from the first of the registries asked that serves
9
+ // its release at the locked version and checksum (DR-127); the built-in
10
+ // spec package is served first from this device's seed where its files
11
+ // carry the lock's digests, whatever archive checksum the lock records
12
+ // (environments-11). Where no seed and no registry serves the built-in,
13
+ // a host shipping no seed, as the command line, may leave it out as not
14
+ // installed, absent from the tree and its record, for the app's next use
15
+ // to install from its seed, while the rest installs; any other spec
16
+ // package nothing serves fails the install naming it. The new tree
17
+ // is complete before it replaces the old one; a failure leaves the last
18
+ // files in place. The swap happens only while the lock it installs still
19
+ // stands on disk at the version read and still matches `spex.yaml` and
20
+ // its path sources: an install overtaken meanwhile publishes nothing
21
+ // (DR-111). A path source copies nothing and is reported missing where
22
+ // the folder its path resolves to lacks it; your own group's path source
23
+ // must hold only what its clone's sync carries, checked before anything
24
+ // is installed or linked (environments-32); a stale lock installs
25
+ // nothing new.
26
+ // No code runs: what an install adds to the release files is the host's
27
+ // engine preparation where the host supplies an engine — the app's core
28
+ // gives each playbook artifact folder its engine links, a path source's
29
+ // in the working folder too, and bundles again a registry module bundled
30
+ // carrying its own engine, so every playbook runs on the app's engine
31
+ // (playbook-library-46). With no engine, as from the command line,
32
+ // nothing is prepared and nothing is linked (DR-165).
33
+ import { randomUUID } from "node:crypto";
34
+ import { chmodSync, copyFileSync, cpSync, existsSync, linkSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync, } from "node:fs";
35
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
36
+ import { dirname, join, relative } from "node:path";
37
+ import { seedServes } from "./builtins.js";
38
+ import { fileVersion, VersionConflictError } from "../files.js";
39
+ import { instanceFolder, parseOrigin } from "../instance.js";
40
+ import { BUILTIN_PACKAGE_NAME, writeExcludeBlock } from "./exports.js";
41
+ import { listReleaseFiles, parseManifestText, portablePathIssues, sha256Hex } from "./format.js";
42
+ import { isGitSource, isPathSource, isRegistrySource, lockStaleness, sourceValue } from "./lock.js";
43
+ import { ownFolderIssue, ownPathIssue, ownPathMessage } from "./own-paths.js";
44
+ import { readVersionResource, RegistryError, registryHost } from "./registry.js";
45
+ import { isVersion } from "./semver.js";
46
+ import { DigestError } from "./store.js";
47
+ import { gunzip, readTar } from "./tar.js";
48
+ import { ensureSpexDir, installedDir } from "./layout.js";
49
+ /** Where a working folder's Git is told to ignore every playbook
50
+ * artifact folder's engine links (playbook-library-12): a release-layout
51
+ * `playbooks/<language>/<id>/` folder anywhere in it. */
52
+ export const ENGINE_LINKS_EXCLUDE = "**/playbooks/*/*/node_modules/";
53
+ export class InstallError extends Error {
54
+ packageName;
55
+ cause;
56
+ confined;
57
+ constructor(packageName, message, cause,
58
+ /** The folder your own group's clone refuses, with its reason, for a
59
+ * host to phrase (environments-32). */
60
+ confined) {
61
+ super(message);
62
+ this.packageName = packageName;
63
+ this.cause = cause;
64
+ this.confined = confined;
65
+ this.name = "InstallError";
66
+ }
67
+ }
68
+ /** The installed tree's record of what it holds, beside the packages. */
69
+ export const INSTALL_RECORD = ".spex-install.json";
70
+ function readPathManifest(dir) {
71
+ const file = join(dir, "meta.yaml");
72
+ if (!existsSync(file))
73
+ return null;
74
+ const { manifest, issues } = parseManifestText(readFileSync(file, "utf8"));
75
+ if (!manifest)
76
+ throw new Error(issues.map((issue) => issue.message).join("; "));
77
+ return manifest;
78
+ }
79
+ /** The path sources of a lock this device lacks where their paths
80
+ * resolve (environments-7). */
81
+ export function missingPathSources(lock, pathRoot) {
82
+ const missing = [];
83
+ for (const name of Object.keys(lock.packages).sort()) {
84
+ const source = lock.packages[name].source;
85
+ if (!isPathSource(source))
86
+ continue;
87
+ if (pathRoot === null || !existsSync(join(pathRoot, ...source.path.split("/"), "meta.yaml")))
88
+ missing.push(name);
89
+ }
90
+ return missing;
91
+ }
92
+ const canonical = (value) => {
93
+ if (Array.isArray(value))
94
+ return value.map(canonical);
95
+ if (typeof value === "object" && value !== null) {
96
+ return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])]));
97
+ }
98
+ return value;
99
+ };
100
+ /** One spec package as the install record holds it: what the lock
101
+ * locks of it, in one order however the lock was read. */
102
+ function recordEntry(resolution) {
103
+ return canonical({
104
+ source: sourceValue(resolution.source),
105
+ files: [...resolution.files].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))
106
+ .map((file) => ({ path: file.path, sha256: file.sha256, executable: file.executable })),
107
+ artifacts: Object.fromEntries(Object.entries(resolution.artifacts).map(([id, artifact]) => [id, { language: artifact.language, fallback: artifact.fallback }])),
108
+ });
109
+ }
110
+ /** A lock without the spec packages named: what an install leaving them
111
+ * out places and records. */
112
+ function lockWithout(lock, names) {
113
+ return { ...lock, packages: Object.fromEntries(Object.entries(lock.packages).filter(([name]) => !names.includes(name))) };
114
+ }
115
+ function installRecord(lock) {
116
+ const packages = {};
117
+ for (const name of Object.keys(lock.packages).sort()) {
118
+ const resolution = lock.packages[name];
119
+ if (isPathSource(resolution.source))
120
+ continue;
121
+ packages[name] = recordEntry(resolution);
122
+ }
123
+ return { format: 1, packages };
124
+ }
125
+ function readInstallRecord(target) {
126
+ try {
127
+ const text = readFileSync(join(target, INSTALL_RECORD), "utf8");
128
+ const value = JSON.parse(text);
129
+ return { text, packages: typeof value.packages === "object" && value.packages !== null ? value.packages : {} };
130
+ }
131
+ catch {
132
+ return null;
133
+ }
134
+ }
135
+ function filesStand(target, name, resolution) {
136
+ return resolution.files.every((entry) => existsSync(join(target, ...name.split("/"), ...entry.path.split("/"))));
137
+ }
138
+ function treeMatches(target, lock, record) {
139
+ if (readInstallRecord(target)?.text !== JSON.stringify(record))
140
+ return false;
141
+ return Object.entries(lock.packages).every(([name, resolution]) => isPathSource(resolution.source) || filesStand(target, name, resolution));
142
+ }
143
+ /** The registry and Git packages the install record holds as the lock
144
+ * locks them, whether or not every file still stands: one recorded here
145
+ * that `installedPackages` lacks has files missing (environments-14). */
146
+ export function recordedPackages(root, lock) {
147
+ const record = readInstallRecord(installedDir(root));
148
+ const out = new Set();
149
+ if (!record)
150
+ return out;
151
+ for (const [name, resolution] of Object.entries(lock.packages)) {
152
+ if (!isPathSource(resolution.source) && JSON.stringify(record.packages[name]) === JSON.stringify(recordEntry(resolution)))
153
+ out.add(name);
154
+ }
155
+ return out;
156
+ }
157
+ /** The registry and Git sources of a lock whose files stand installed
158
+ * under the root's `.spex/` as the lock locks them: recorded by the
159
+ * install that placed them, the same source, files and artifacts, every
160
+ * file there. */
161
+ export function installedPackages(root, lock) {
162
+ const target = installedDir(root);
163
+ const record = readInstallRecord(target);
164
+ const out = new Set();
165
+ if (!record)
166
+ return out;
167
+ for (const [name, resolution] of Object.entries(lock.packages)) {
168
+ if (isPathSource(resolution.source))
169
+ continue;
170
+ if (JSON.stringify(record.packages[name]) === JSON.stringify(recordEntry(resolution)) && filesStand(target, name, resolution))
171
+ out.add(name);
172
+ }
173
+ return out;
174
+ }
175
+ /** Refuse a swap the files changed under (DR-111): the root gone, its
176
+ * lock no longer at the version installed,
177
+ * or the lock no longer matching `spex.yaml` or a path source's
178
+ * manifest. */
179
+ function assertCurrent(options) {
180
+ const { root, lock, pathRoot } = options;
181
+ const lockFile = join(root, "spex.lock");
182
+ if (!existsSync(root))
183
+ throw new VersionConflictError(root);
184
+ if (fileVersion(lockFile) !== options.lockVersion)
185
+ throw new VersionConflictError(lockFile);
186
+ const requestsFile = join(root, "spex.yaml");
187
+ const requestsText = existsSync(requestsFile) ? readFileSync(requestsFile, "utf8") : null;
188
+ let stale = false;
189
+ try {
190
+ stale = lockStaleness(lock, requestsText, (path) => (pathRoot === null ? null : readPathManifest(join(pathRoot, ...path.split("/"))))).stale;
191
+ }
192
+ catch {
193
+ stale = true;
194
+ }
195
+ if (stale)
196
+ throw new VersionConflictError(requestsFile);
197
+ }
198
+ const isChecksum = (value) => /^[0-9a-f]{64}$/.test(value);
199
+ /** A registry's folder under `cache/registry/`: its scheme's, holding
200
+ * its instance's folder, where its URL is an instance's origin — so two
201
+ * origins at one loopback host and port, apart by scheme alone, never
202
+ * share one — else one from its URL's digest, which no scheme's name
203
+ * begins as. */
204
+ function registryFolder(url) {
205
+ try {
206
+ return join(parseOrigin(url).scheme, instanceFolder(url));
207
+ }
208
+ catch {
209
+ return `_${sha256Hex(url).slice(0, 32)}`;
210
+ }
211
+ }
212
+ /** Where a registry's version resource is cached: per registry, since
213
+ * each answers for its own releases; none for a version no release may
214
+ * hold. */
215
+ function resourceFile(cache, registry, name, version) {
216
+ return isVersion(version) ? join(cache, "registry", registryFolder(registry.url), ...name.split("/"), `${version}.json`) : null;
217
+ }
218
+ /** Where a release archive is cached: by the checksum it was verified
219
+ * at, whichever registry served it. */
220
+ function archiveFile(cache, name, source) {
221
+ return isVersion(source.version) && isChecksum(source.checksum) ? join(cache, "archives", ...name.split("/"), source.version, `${source.checksum}.tgz`) : null;
222
+ }
223
+ /** A registry's version resource, from the cache where the answer kept
224
+ * there carries the locked checksum, else asked of the registry. */
225
+ async function cachedResource(cache, registry, name, source) {
226
+ const file = resourceFile(cache, registry, name, source.version);
227
+ if (file !== null && existsSync(file)) {
228
+ try {
229
+ const cached = readVersionResource(name, source.version, JSON.parse(await readFile(file, "utf8")));
230
+ if (cached.checksum === source.checksum)
231
+ return cached;
232
+ }
233
+ catch { /* refetch below */ }
234
+ }
235
+ const resource = await registry.version(name, source.version);
236
+ if (file !== null) {
237
+ await mkdir(dirname(file), { recursive: true });
238
+ await writeFile(file, JSON.stringify(resource));
239
+ }
240
+ return resource;
241
+ }
242
+ /** The release archive at the locked checksum, from the cache or the
243
+ * registry; null where the registry's archive is not that release, so
244
+ * its raw files serve instead. Only an archive at its checksum is kept. */
245
+ async function cachedArchive(cache, registry, name, source) {
246
+ const file = archiveFile(cache, name, source);
247
+ if (file !== null && existsSync(file)) {
248
+ const bytes = new Uint8Array(await readFile(file));
249
+ if (sha256Hex(bytes) === source.checksum)
250
+ return bytes;
251
+ rmSync(file, { force: true });
252
+ }
253
+ const bytes = await registry.archive(name, source.version);
254
+ if (sha256Hex(bytes) !== source.checksum)
255
+ return null;
256
+ if (file !== null) {
257
+ await mkdir(dirname(file), { recursive: true });
258
+ await writeFile(file, bytes);
259
+ }
260
+ return bytes;
261
+ }
262
+ function putVerified(store, name, file, bytes) {
263
+ try {
264
+ store.put(bytes, file.sha256, file.executable, `${name} ${file.path}`);
265
+ }
266
+ catch (error) {
267
+ if (error instanceof DigestError)
268
+ throw new InstallError(name, `${name}: ${file.path} does not match spex.lock; nothing was installed`, error);
269
+ throw error;
270
+ }
271
+ }
272
+ /** Fetch every selected file the store lacks, verified by digest: false
273
+ * where the install leaves the built-in spec package out, no seed and
274
+ * no registry serving it (environments-7). */
275
+ async function fetchMissing(options, name, resolution) {
276
+ const { store } = options;
277
+ const missing = [];
278
+ for (const file of resolution.files) {
279
+ if (store.has(file.sha256, file.executable))
280
+ continue;
281
+ // The same bytes in the other mode need no fetch.
282
+ if (store.has(file.sha256, !file.executable)) {
283
+ putVerified(store, name, file, readFileSync(store.pathOf(file.sha256, !file.executable)));
284
+ continue;
285
+ }
286
+ missing.push(file);
287
+ }
288
+ if (missing.length === 0)
289
+ return true;
290
+ const source = resolution.source;
291
+ if (isRegistrySource(source)) {
292
+ // The built-in from this device's seed, by its files' digests: the
293
+ // archive each device packs differs, its files do not.
294
+ if (name === BUILTIN_PACKAGE_NAME && options.seed && await fetchSeeded(options.seed, store, name, source, resolution))
295
+ return true;
296
+ // The first registry serving the release at the locked checksum
297
+ // serves what is still missing; any other answer moves on.
298
+ const reasons = [];
299
+ // The first registry's refusal, for a host to phrase by its kind.
300
+ let refusal;
301
+ for (const registry of options.registries ? options.registries(source) : [options.registry]) {
302
+ const left = missing.filter((file) => !store.has(file.sha256, file.executable));
303
+ if (left.length === 0)
304
+ return true;
305
+ try {
306
+ if (await fetchFrom(options, registry, name, source, resolution, left))
307
+ return true;
308
+ reasons.push(`${registryHost(registry.url)} has it, but not as spex.lock records it`);
309
+ }
310
+ catch (error) {
311
+ if (!(error instanceof RegistryError))
312
+ throw error;
313
+ refusal ??= error;
314
+ reasons.push(error.message.startsWith(`${name}: `) ? error.message.slice(name.length + 2) : error.message);
315
+ }
316
+ }
317
+ // The built-in nothing serves is the app's to install from its seed.
318
+ if (name === BUILTIN_PACKAGE_NAME && options.builtinUnserved === "leave")
319
+ return false;
320
+ throw new InstallError(name, `${name} ${source.version}: no registry has it as spex.lock records it${reasons.length > 0 ? `: ${reasons.join("; ")}` : ""}`, refusal);
321
+ }
322
+ if (isGitSource(source)) {
323
+ const credential = options.gitCredential ? await options.gitCredential(source.git) : undefined;
324
+ const { dir } = await options.git.fetch(source.git, source.commit, credential);
325
+ const root = source.path ? join(dir, ...source.path.split("/")) : dir;
326
+ for (const file of missing) {
327
+ const absolute = join(root, ...file.path.split("/"));
328
+ let stat;
329
+ try {
330
+ stat = lstatSync(absolute);
331
+ }
332
+ catch {
333
+ stat = undefined;
334
+ }
335
+ if (!stat?.isFile())
336
+ throw new InstallError(name, `${name}: ${file.path} is not a file at ${source.commit}`);
337
+ putVerified(store, name, file, readFileSync(absolute));
338
+ }
339
+ }
340
+ return true;
341
+ }
342
+ /** Serve the built-in spec package's missing files from this device's
343
+ * seed, each verified by digest: false where the seed lacks the locked
344
+ * version, holds a locked file at another digest, or cannot read one, so
345
+ * the registries are asked instead. */
346
+ async function fetchSeeded(seed, store, name, source, resolution) {
347
+ if (!(await seedServes(seed, source.version, resolution.files)))
348
+ return false;
349
+ for (const file of resolution.files) {
350
+ if (store.has(file.sha256, file.executable))
351
+ continue;
352
+ let bytes;
353
+ try {
354
+ bytes = await seed.file(name, source.version, file.path);
355
+ }
356
+ catch (error) {
357
+ if (error instanceof RegistryError)
358
+ return false;
359
+ throw error;
360
+ }
361
+ putVerified(store, name, file, bytes);
362
+ }
363
+ return true;
364
+ }
365
+ /** Fetch a registry package's missing files from one registry, each
366
+ * verified by digest: false where it holds the release at another
367
+ * checksum than the lock's. */
368
+ async function fetchFrom(options, registry, name, source, resolution, missing) {
369
+ const { store } = options;
370
+ const resource = await cachedResource(options.cache, registry, name, source);
371
+ if (resource.checksum !== source.checksum)
372
+ return false;
373
+ const total = resource.files?.length ?? resolution.files.length;
374
+ let remaining = missing;
375
+ if (missing.length > total / 2) {
376
+ // The archive holds the release whole: cheaper than many files.
377
+ const archive = await cachedArchive(options.cache, registry, name, source);
378
+ const pkg = name.split("/")[1];
379
+ const entries = new Map();
380
+ if (archive !== null) {
381
+ try {
382
+ for (const entry of readTar(gunzip(archive))) {
383
+ if (entry.type !== "file" || !entry.path.startsWith(`${pkg}/`))
384
+ continue;
385
+ entries.set(entry.path.slice(pkg.length + 1), entry.data);
386
+ }
387
+ }
388
+ catch {
389
+ const file = archiveFile(options.cache, name, source);
390
+ if (file !== null)
391
+ rmSync(file, { force: true });
392
+ entries.clear();
393
+ }
394
+ }
395
+ remaining = [];
396
+ for (const file of missing) {
397
+ const bytes = entries.get(file.path);
398
+ if (bytes)
399
+ putVerified(store, name, file, bytes);
400
+ else
401
+ remaining.push(file);
402
+ }
403
+ }
404
+ for (const file of remaining)
405
+ putVerified(store, name, file, await registry.file(name, source.version, file.path));
406
+ return true;
407
+ }
408
+ function linkOrCopy(from, to, executable) {
409
+ try {
410
+ linkSync(from, to);
411
+ }
412
+ catch {
413
+ copyFileSync(from, to);
414
+ chmodSync(to, executable ? 0o555 : 0o444);
415
+ }
416
+ }
417
+ /** The playbook artifact folders of a spec package's selected
418
+ * artifacts under `root`, with their ids. */
419
+ function playbookFolders(root, resolution) {
420
+ const out = [];
421
+ for (const [id, chosen] of Object.entries(resolution.artifacts)) {
422
+ if (chosen.language === null)
423
+ continue;
424
+ const folder = join(root, "playbooks", chosen.language, id);
425
+ if (existsSync(folder))
426
+ out.push({ id, folder });
427
+ }
428
+ return out;
429
+ }
430
+ /** Prepare every playbook artifact folder under `target` to run on the
431
+ * app's engine (playbook-library-46), collecting the modules kept as
432
+ * they are; each is named at `named`'s spelling of its folder. A tree
433
+ * standing installed already is `tolerant`: a folder it cannot prepare
434
+ * is logged and left, since the install itself places nothing. */
435
+ async function prepareInstalled(target, names, lock, engine, named, tolerant = false) {
436
+ const kept = [];
437
+ if (engine === undefined)
438
+ return kept;
439
+ for (const name of names) {
440
+ for (const { id, folder } of playbookFolders(join(target, ...name.split("/")), lock.packages[name])) {
441
+ let reason;
442
+ try {
443
+ reason = await engine.prepare(folder, id);
444
+ }
445
+ catch (error) {
446
+ if (!tolerant)
447
+ throw error;
448
+ console.error(`spex: ${named(folder)} was not prepared for the app's engine: ${String(error)}`);
449
+ continue;
450
+ }
451
+ if (reason !== null)
452
+ kept.push({ module: join(named(folder), `${id}.registry.mjs`), reason });
453
+ }
454
+ }
455
+ return kept;
456
+ }
457
+ /** Every playbook artifact folder of a lock's path sources where their
458
+ * paths resolve. */
459
+ function pathSourcePlaybooks(lock, pathRoot) {
460
+ if (pathRoot === null)
461
+ return [];
462
+ const folders = [];
463
+ for (const name of Object.keys(lock.packages).sort()) {
464
+ const resolution = lock.packages[name];
465
+ if (!isPathSource(resolution.source))
466
+ continue;
467
+ for (const { folder } of playbookFolders(join(pathRoot, ...resolution.source.path.split("/")), resolution))
468
+ folders.push(folder);
469
+ }
470
+ return folders;
471
+ }
472
+ /** The engine links of a path source's playbook folders are ignored by
473
+ * the Git of the working folder or of your own group's clone holding
474
+ * them before any is made, so a sync never carries one
475
+ * (playbook-library-46, DR-125): your own group's clone failing to list
476
+ * them fails the install, which makes none; a working folder's failure
477
+ * is logged and its folders are linked anyway, its Git being the
478
+ * reader's alone. */
479
+ function excludeEngineLinks(pathRoot, folders, confined) {
480
+ if (pathRoot === null || folders.length === 0)
481
+ return;
482
+ try {
483
+ writeExcludeBlock(pathRoot, [ENGINE_LINKS_EXCLUDE], "engine links");
484
+ }
485
+ catch (error) {
486
+ if (confined)
487
+ throw new InstallError(undefined, `${pathRoot}'s .git/info/exclude cannot list the engine links, so none is made: ${error.message}`, error);
488
+ console.error(`spex: ${pathRoot}'s engine links are not excluded: ${String(error)}`);
489
+ }
490
+ }
491
+ /** A path source's playbook folders get the engine links a compile
492
+ * provisions, their files left as they are; a folder that takes no link
493
+ * is logged, never failing the install. */
494
+ function linkPathSources(folders, engine) {
495
+ for (const folder of folders) {
496
+ try {
497
+ engine.link(folder);
498
+ }
499
+ catch (error) {
500
+ console.error(`spex: ${folder} takes no engine links: ${String(error)}`);
501
+ }
502
+ }
503
+ }
504
+ /** Refuse your own group's path source holding what its clone's sync
505
+ * drops or refuses (environments-32), before anything is installed or
506
+ * linked: a folder this device lacks is reported missing instead. */
507
+ async function assertConfined(lock, pathRoot) {
508
+ for (const name of Object.keys(lock.packages).sort()) {
509
+ const source = lock.packages[name].source;
510
+ if (!isPathSource(source))
511
+ continue;
512
+ const folder = join(pathRoot, ...source.path.split("/"));
513
+ if (!existsSync(join(folder, "meta.yaml")))
514
+ continue;
515
+ const issue = ownPathIssue(pathRoot, source.path)
516
+ ?? ownFolderIssue(pathRoot, source.path, (await listReleaseFiles(folder)).files.map((file) => file.path));
517
+ if (issue)
518
+ throw new InstallError(name, ownPathMessage(name, source.path, issue), undefined, { path: source.path, issue });
519
+ }
520
+ }
521
+ /** Install a lock's selected files (environments-7). */
522
+ export async function install(options) {
523
+ const { root, lock, store, pathRoot } = options;
524
+ const missingPaths = missingPathSources(lock, pathRoot);
525
+ const requestsText = options.requestsText !== undefined
526
+ ? options.requestsText
527
+ : existsSync(join(root, "spex.yaml")) ? readFileSync(join(root, "spex.yaml"), "utf8") : null;
528
+ const staleness = lockStaleness(lock, requestsText, (path) => (pathRoot === null ? null : readPathManifest(join(pathRoot, ...path.split("/")))));
529
+ if (staleness.stale)
530
+ return { installed: [], missingPaths, stale: staleness.reasons, unchanged: true, engineKept: [] };
531
+ const names = Object.keys(lock.packages).sort().filter((name) => !isPathSource(lock.packages[name].source));
532
+ for (const name of names) {
533
+ const issues = portablePathIssues(lock.packages[name].files.map((file) => file.path));
534
+ if (issues.length > 0)
535
+ throw new InstallError(name, `${name}: ${issues.map((issue) => `${issue.path} ${issue.message}`).join("; ")}`);
536
+ }
537
+ const confined = options.confined === true;
538
+ const { engine } = options;
539
+ const playbooks = engine === undefined ? [] : pathSourcePlaybooks(lock, pathRoot);
540
+ // The exclude first, so the check reads the engine links standing
541
+ // from an earlier install as Git ignores them.
542
+ excludeEngineLinks(pathRoot, playbooks, confined);
543
+ if (confined && pathRoot !== null)
544
+ await assertConfined(lock, pathRoot);
545
+ if (engine !== undefined)
546
+ linkPathSources(playbooks, engine);
547
+ const target = installedDir(root);
548
+ let record = installRecord(lock);
549
+ if (treeMatches(target, lock, record)) {
550
+ // Installed already, by this app or an earlier one: each playbook is
551
+ // prepared in place, where an earlier app left a module carrying the
552
+ // engine it was bundled with.
553
+ const engineKept = await prepareInstalled(target, names, lock, engine, (folder) => folder, true);
554
+ return { installed: [], missingPaths, unchanged: true, engineKept };
555
+ }
556
+ const left = [];
557
+ for (const name of names) {
558
+ try {
559
+ if (!(await fetchMissing(options, name, lock.packages[name])))
560
+ left.push(name);
561
+ }
562
+ catch (error) {
563
+ if (error instanceof InstallError)
564
+ throw error;
565
+ throw new InstallError(name, `${name}: ${error.message}`, error);
566
+ }
567
+ }
568
+ // The built-in left out stands neither in the tree nor in its record,
569
+ // so every host reads it not installed; a tree holding the rest as the
570
+ // lock locks it already is installed as it stands (environments-7).
571
+ const placed = left.length === 0 ? names : names.filter((name) => !left.includes(name));
572
+ if (left.length > 0) {
573
+ const kept = lockWithout(lock, left);
574
+ record = installRecord(kept);
575
+ if (treeMatches(target, kept, record)) {
576
+ const engineKept = await prepareInstalled(target, placed, lock, engine, (folder) => folder, true);
577
+ return { installed: [], missingPaths, unchanged: true, engineKept, left };
578
+ }
579
+ }
580
+ const id = randomUUID();
581
+ const staging = join(options.cache, "staging", id);
582
+ let engineKept;
583
+ try {
584
+ mkdirSync(staging, { recursive: true });
585
+ for (const name of placed) {
586
+ const resolution = lock.packages[name];
587
+ const root = join(staging, ...name.split("/"));
588
+ for (const file of resolution.files) {
589
+ const to = join(root, ...file.path.split("/"));
590
+ mkdirSync(dirname(to), { recursive: true });
591
+ linkOrCopy(store.pathOf(file.sha256, file.executable), to, file.executable);
592
+ }
593
+ }
594
+ engineKept = await prepareInstalled(staging, placed, lock, engine, (folder) => join(target, relative(staging, folder)));
595
+ writeFileSync(join(staging, INSTALL_RECORD), JSON.stringify(record));
596
+ await options.beforeReplace?.();
597
+ // Checked at the instant before the swap, nothing awaited between.
598
+ assertCurrent(options);
599
+ ensureSpexDir(root);
600
+ replaceTree(staging, target, join(options.cache, "trash", id));
601
+ }
602
+ catch (error) {
603
+ rmSync(staging, { recursive: true, force: true });
604
+ if (error instanceof InstallError || error instanceof VersionConflictError)
605
+ throw error;
606
+ throw new InstallError(undefined, `installing failed; the last files stay: ${error.message}`, error);
607
+ }
608
+ return { installed: placed, missingPaths, unchanged: false, engineKept, ...(left.length > 0 ? { left } : {}) };
609
+ }
610
+ /** Swap a complete staged tree in for the installed one. */
611
+ function replaceTree(staging, target, trash) {
612
+ let source = staging;
613
+ const hadOld = existsSync(target);
614
+ if (hadOld) {
615
+ mkdirSync(dirname(trash), { recursive: true });
616
+ try {
617
+ renameSync(target, trash);
618
+ }
619
+ catch (error) {
620
+ if (error.code !== "EXDEV")
621
+ throw error;
622
+ // The cache is on another file system: move the old tree aside
623
+ // next to itself instead.
624
+ trash = `${target}.old-${randomUUID()}`;
625
+ renameSync(target, trash);
626
+ }
627
+ }
628
+ try {
629
+ try {
630
+ renameSync(source, target);
631
+ }
632
+ catch (error) {
633
+ if (error.code !== "EXDEV")
634
+ throw error;
635
+ const near = `${target}.new-${randomUUID()}`;
636
+ cpSync(source, near, { recursive: true, verbatimSymlinks: true });
637
+ rmSync(source, { recursive: true, force: true });
638
+ source = near;
639
+ renameSync(source, target);
640
+ }
641
+ }
642
+ catch (error) {
643
+ if (hadOld)
644
+ renameSync(trash, target);
645
+ throw error;
646
+ }
647
+ // The complete new tree now stands at target: the install committed.
648
+ // Garbage collection cannot turn that success into a failed install,
649
+ // which would skip exports and falsely claim the old files still stand.
650
+ if (hadOld) {
651
+ try {
652
+ rmSync(trash, { recursive: true, force: true });
653
+ }
654
+ catch (error) {
655
+ console.error(`spex: installed files stand; obsolete tree ${trash} could not be removed: ${String(error)}`);
656
+ }
657
+ }
658
+ }
659
+ /** Remove every installed file of an environment (one emptied). */
660
+ export function removeInstalled(root) {
661
+ rmSync(installedDir(root), { recursive: true, force: true });
662
+ }
663
+ /**
664
+ * Prepare an environment's playbook artifact folders to run on the
665
+ * host's engine at a use that hands the launcher module locations
666
+ * (environments-7, environments-9, playbook-library-46): each installed
667
+ * as the lock locks it, and each path source's where its path resolves,
668
+ * so a playbook another host installed — the command line prepares
669
+ * none — runs. Nothing here fails the use: a folder that cannot be
670
+ * prepared is logged and left; a path source's links are made only once
671
+ * its Git lists them, your own group's clone otherwise taking none.
672
+ * Returns the registry modules kept carrying their own engine.
673
+ */
674
+ export async function prepareEnvironment(options) {
675
+ const { root, lock, pathRoot, engine } = options;
676
+ const installed = installedPackages(root, lock);
677
+ const names = Object.keys(lock.packages).sort().filter((name) => installed.has(name));
678
+ const kept = await prepareInstalled(installedDir(root), names, lock, engine, (folder) => folder, true);
679
+ const playbooks = pathSourcePlaybooks(lock, pathRoot);
680
+ try {
681
+ // Your own group's path sources are confined as an install confines
682
+ // them (environments-32): one refused takes no link, nothing linked
683
+ // outside what the clone syncs.
684
+ if (options.confined === true && pathRoot !== null)
685
+ await assertConfined(lock, pathRoot);
686
+ excludeEngineLinks(pathRoot, playbooks, options.confined === true);
687
+ linkPathSources(playbooks, engine);
688
+ }
689
+ catch (error) {
690
+ console.error(`spex: ${String(error.message ?? error)}`);
691
+ }
692
+ return kept;
693
+ }
694
+ //# sourceMappingURL=install.js.map