@intellectual-frontiers/libraries 0.4.0 → 0.4.1

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,87 @@
1
+ /**
2
+ * What is really vendored in this repository: the files that are not ours and the license each is under, as data (commons 0035-licensing FR-008). `../license.ts` makes `THIRD_PARTY_NOTICES.md` from it, and its check names an
3
+ * item whose path is gone. Where a license was not checked against its source the item says `unverified: <what to check>` and never a guess.
4
+ *
5
+ * @remarks
6
+ * Packages installed from a registry (TypeScript, fast-check, `@types/node` and the others in `bun.lock`) are not vendored: nothing of them is in this repository, and a package's license is its own. Mermaid is
7
+ * copied into a built site and not into this repository, so its item has no path.
8
+ *
9
+ * Spec: 0001-libraries FR-019
10
+ *
11
+ * @module
12
+ */
13
+
14
+ /** One third-party item: what it is, where it came from, whose it is and the license it is under. */
15
+ export type ThirdPartyItem = {
16
+ /** The path in the repository, or `undefined` for an item that is copied only into a built output. */
17
+ readonly path: string | undefined;
18
+ readonly what: string;
19
+ readonly source: string;
20
+ readonly owner: string;
21
+ readonly license: string;
22
+ /** What was checked, or `unverified: <what to check>`. */
23
+ readonly checked: string;
24
+ };
25
+
26
+ /** The items, in the order the notices list them. */
27
+ export const THIRD_PARTY: readonly ThirdPartyItem[] = [
28
+ {
29
+ path: "commons/libraries/src/workflows/schema/github-workflow.schema.json",
30
+ what: "The JSON Schema of GitHub Actions workflows, the copy fetched on 2026-11-19, which the tests validate the generated workflows against",
31
+ source: "https://json.schemastore.org/github-workflow.json (the SchemaStore project, https://github.com/SchemaStore/schemastore)",
32
+ owner: "The SchemaStore authors",
33
+ license: "Apache-2.0",
34
+ checked:
35
+ "The license is that of the SchemaStore repository (its LICENSE is the Apache License 2.0, read on 2026-11-20). unverified: whether the Apache-2.0 text must travel with this one file, which is named here by its address; ask counsel",
36
+ },
37
+ {
38
+ path: "commons/data/sql/extensions/osquery/schema/osquery-5.24.1.auto.json",
39
+ what: "The tables of osquery 5.24.1 (names, columns, types, descriptions), trimmed to the fields the importer reads",
40
+ source: "https://github.com/osquery/osquery-site, commit 055097f8d8fb45c0c33a83c9ed7c56a7df3d7b5f, path src/data/osquery_schema_versions/5.24.1.json",
41
+ owner: "The osquery authors",
42
+ license: "CC-BY-4.0, as the file's own `source.license` records for the osquery-site documentation data; the osquery project is Apache-2.0 OR GPL-2.0-only",
43
+ checked:
44
+ "Taken from the record in the file itself. unverified: the license file of osquery-site at that commit (the address of a LICENSE file at the root returned 404), so check where the CC-BY-4.0 statement comes from and the attribution it asks for",
45
+ },
46
+ {
47
+ path: "commons/ontology/src/standards/nist-sp-800-53/controls.auto.ts",
48
+ what: "The titles and groups of twelve controls of NIST SP 800-53 Rev. 5.2.0, imported from the OSCAL catalog and held to its SHA-256",
49
+ source: "https://github.com/usnistgov/oscal-content, commit f0de6d8d8c059d374f15e0ae07508d82e370fc1d (import manifest commons/libraries/src/imports/nist-sp-800-53.import.ts)",
50
+ owner: "The National Institute of Standards and Technology",
51
+ license: "Public domain (a work of the United States Government, 17 U.S.C. 105)",
52
+ checked: "Taken from the import manifest, which records it with the SHA-256 of the source.",
53
+ },
54
+ {
55
+ path: "commons/ontology/src/supply-chain/packaging/schema.auto.ts",
56
+ what: "The slice of schema.org 30.1 that the packaging ontology specializes, imported and held to its SHA-256",
57
+ source: "https://schema.org/version/30.1/schemaorg-current-https.ttl (import manifest commons/libraries/src/imports/schema-org.import.ts)",
58
+ owner: "The Schema.org Community Group and contributors",
59
+ license: "CC-BY-SA-3.0",
60
+ checked:
61
+ "Taken from the import manifest. unverified: whether the ShareAlike term of CC-BY-SA-3.0 reaches this generated module and what it asks of the files that use it; ask counsel",
62
+ },
63
+ {
64
+ path: "commons/ontology/src/supply-chain/packaging/managers.ts",
65
+ what: "The table of package managers, seeded from the tables of upt (the families file, `families.ts`, is seeded from the same)",
66
+ source: "https://github.com/sigoden/upt, kept as a fixture in tests/fixtures/upt/",
67
+ owner: "The authors of upt",
68
+ license: "MIT OR Apache-2.0, at the user's option",
69
+ checked: "Taken from the files' own headers and from tests/fixtures/upt/README.md. unverified: the license files of the pinned upt commit, which are not kept in this repository",
70
+ },
71
+ {
72
+ path: "commons/ontology/src/supply-chain/packaging/families.ts",
73
+ what: "The families of package managers, seeded from the tables of upt",
74
+ source: "https://github.com/sigoden/upt, kept as a fixture in tests/fixtures/upt/",
75
+ owner: "The authors of upt",
76
+ license: "MIT OR Apache-2.0, at the user's option",
77
+ checked: "Taken from the file's own header and from tests/fixtures/upt/README.md. unverified: the license files of the pinned upt commit, which are not kept in this repository",
78
+ },
79
+ {
80
+ path: undefined,
81
+ what: "Mermaid 11.17.2, the script the generated documentation site serves on a page with a diagram; it is copied into the built site from the package `mermaid` and is not in this repository",
82
+ source: "https://www.npmjs.com/package/mermaid",
83
+ owner: "Knut Sveidqvist and contributors",
84
+ license: "MIT",
85
+ checked: "The LICENSE of the installed package 11.17.2 was read on 2026-11-20: The MIT License (MIT), Copyright (c) 2014 - 2022 Knut Sveidqvist.",
86
+ },
87
+ ] as const;
package/src/license.ts ADDED
@@ -0,0 +1,222 @@
1
+ /**
2
+ * The license of the repository and of every library in it, written and checked from one place (commons 0035-licensing). One official text, the PolyForm Noncommercial License 1.0.0
3
+ * (`license/PolyForm-Noncommercial-1.0.0.md`, held to the SHA-256 of its standard), and one `Required Notice:` line for the licensor make the `LICENSE` of the root and of each library folder; the third-party
4
+ * notices are made from the record of what is vendored.
5
+ *
6
+ * bun commons/libraries/src/license.ts write every LICENSE and THIRD_PARTY_NOTICES.md again
7
+ * bun commons/libraries/src/license.ts --check write nothing and exit 1 where any file is not what the manifests and the official text make
8
+ * other flags: --repo DIR (the repository, the working folder by default)
9
+ *
10
+ * @remarks
11
+ * What is written: `LICENSE` at the root and in each `commons/<name>/` that holds a manifest (`library.ts`), and `THIRD_PARTY_NOTICES.md`. What is only checked, because a person writes it: `LICENSING.md`, `COMMERCIAL.md`,
12
+ * `NOTICE`, `CONTRIBUTING.md`, `CITATION.cff`, the License section of `README.md` and the `license` of the root `package.json`. A library with a folder and no `LICENSE` is a finding that names the command above, so a new
13
+ * library runs it once. The packer writes the same identifier into the `package.json` it publishes ({@link licenseOf}).
14
+ *
15
+ * @limits
16
+ * It does not fetch anything: the official text is the copy in `license/`, checked against the SHA-256 its standard records. It does not judge what the hand-written files say beyond the few facts named in {@link Finding}.
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * import { licenseFileText } from "./license.ts";
21
+ * licenseFileText("TEXT\n").startsWith("Required Notice: Copyright Intellectual Frontiers LLC"); // true
22
+ * ```
23
+ *
24
+ * Spec: 0001-libraries FR-019
25
+ *
26
+ * @module
27
+ */
28
+ import process from "node:process";
29
+ import { absurd, err, ok, type Result } from "@intellectual-frontiers/core";
30
+ import { sha256 } from "@intellectual-frontiers/crypto/sha256";
31
+ import { stdio } from "@intellectual-frontiers/system";
32
+ import { existsSync, readTextFileSync, writeTextFileSync } from "@intellectual-frontiers/system/fs";
33
+ import { fromFileUrl, join, resolve } from "@intellectual-frontiers/system/path";
34
+ import { type Library, readLibraries } from "./libraries.ts";
35
+ import { COMMERCIAL_ISSUES_URL, DEFAULT_LICENSE, LICENSE_STANDARDS, LICENSOR, REPOSITORY_URL, type SpdxId } from "./license/standard.ts";
36
+ import { THIRD_PARTY, type ThirdPartyItem } from "./license/third-party.ts";
37
+
38
+ /** The command that writes what the check finds wrong. */
39
+ export const COMMAND = "bun commons/libraries/src/license.ts";
40
+
41
+ /** The license of a library: its manifest's `license`, else the default of the repository. */
42
+ export function licenseOf(library: Pick<Library, "license"> | undefined): SpdxId {
43
+ return library?.license ?? DEFAULT_LICENSE;
44
+ }
45
+
46
+ /** The line every `LICENSE` begins with, as the license asks of its licensor (its section Notices). */
47
+ export const REQUIRED_NOTICE = `Required Notice: Copyright ${LICENSOR} (${REPOSITORY_URL})`;
48
+
49
+ /** The text of a `LICENSE`: the required notice, a blank line and the official text exactly as it is. */
50
+ export function licenseFileText(official: string): string {
51
+ return `${REQUIRED_NOTICE}\n\n${official}`;
52
+ }
53
+
54
+ /** What is wrong, one case for each sentence. */
55
+ export type Finding =
56
+ | { readonly kind: "text-missing"; readonly id: SpdxId; readonly file: string }
57
+ | { readonly kind: "text-changed"; readonly id: SpdxId; readonly want: string; readonly have: string }
58
+ | { readonly kind: "manifest"; readonly dir: string; readonly problem: string }
59
+ | { readonly kind: "missing"; readonly path: string; readonly why: string }
60
+ | { readonly kind: "stale"; readonly path: string }
61
+ | { readonly kind: "lacks"; readonly path: string; readonly what: string }
62
+ | { readonly kind: "vendored-gone"; readonly path: string };
63
+
64
+ /** The one sentence of a finding. */
65
+ export function sentence(f: Finding): string {
66
+ switch (f.kind) {
67
+ case "text-missing":
68
+ return `the official text of ${f.id} is not at commons/libraries/src/license/${f.file}`;
69
+ case "text-changed":
70
+ return `commons/libraries/src/license/ is not the official text of the standard: its SHA-256 is ${f.have} and the standard records ${f.want}`;
71
+ case "manifest":
72
+ return `commons/${f.dir}/library.ts cannot be read: ${f.problem}`;
73
+ case "missing":
74
+ return `${f.path} is missing: ${f.why}`;
75
+ case "stale":
76
+ return `${f.path} is not what the official text and the manifest make; run: ${COMMAND}`;
77
+ case "lacks":
78
+ return `${f.path} does not ${f.what}`;
79
+ case "vendored-gone":
80
+ return `${f.path} is named as vendored in commons/libraries/src/license/third-party.ts and is not in the repository`;
81
+ default:
82
+ return absurd(f);
83
+ }
84
+ }
85
+
86
+ /** A file this module writes: its path from the repository and its whole text. */
87
+ export type Made = { readonly path: string; readonly text: string };
88
+
89
+ const lf = (t: string): string => t.replaceAll("\r\n", "\n");
90
+ const here = resolve(fromFileUrl(new URL(".", import.meta.url)));
91
+
92
+ /** The official text of a license, held to the SHA-256 of its standard. */
93
+ export async function officialText(id: SpdxId, folder: string = join(here, "license")): Promise<Result<string, Finding>> {
94
+ const std = LICENSE_STANDARDS[id];
95
+ const file = join(folder, std.file);
96
+ if (!existsSync(file)) return err({ kind: "text-missing", id, file: std.file });
97
+ const text = lf(readTextFileSync(file));
98
+ const have = await sha256(text);
99
+ return have === std.sha256 ? ok(text) : err({ kind: "text-changed", id, want: std.sha256, have });
100
+ }
101
+
102
+ /** `THIRD_PARTY_NOTICES.md` made from the items. */
103
+ export function thirdPartyNotices(items: readonly ThirdPartyItem[]): string {
104
+ const body = items.map((i) =>
105
+ [
106
+ `## ${i.path === undefined ? i.what.split(",")[0] ?? i.what : `\`${i.path}\``}`,
107
+ "",
108
+ `- **What**: ${i.what}.`,
109
+ `- **Source**: ${i.source}.`,
110
+ `- **Owner**: ${i.owner}.`,
111
+ `- **License**: ${i.license}.`,
112
+ `- **Checked**: ${i.checked}`,
113
+ "",
114
+ ].join("\n"),
115
+ );
116
+ return [
117
+ "# Third-party notices",
118
+ "",
119
+ "<!-- Generated by `bun commons/libraries/src/license.ts` from `commons/libraries/src/license/third-party.ts`: change that file and run the command, never this one. -->",
120
+ "",
121
+ "Intellectual Frontiers LLC owns the code of this repository, which is under the PolyForm Noncommercial License 1.0.0 (see [`LICENSE`](LICENSE)). The items below are not its own: each is under the license named, which is not changed by this repository's.",
122
+ "Where an item says `unverified:` the license was recorded from a secondary source and has not been checked against the original; that is for the owner to settle, and nothing here is a statement that it is settled.",
123
+ "",
124
+ "Packages installed from a registry (listed in `bun.lock`) are not vendored: nothing of them is in this repository, and each package carries its own license.",
125
+ "",
126
+ ...body,
127
+ ].join("\n");
128
+ }
129
+
130
+ /** The result of looking at a repository: what it should hold and what is wrong. */
131
+ export type Judged = { readonly made: readonly Made[]; readonly findings: readonly Finding[] };
132
+
133
+ const read = (repo: string, path: string): string | undefined => (existsSync(join(repo, path)) ? lf(readTextFileSync(join(repo, path))) : undefined);
134
+
135
+ const HAND_WRITTEN: readonly { readonly path: string; readonly why: string }[] = [
136
+ { path: "LICENSING.md", why: "it says in plain words what is free and what needs a commercial license" },
137
+ { path: "COMMERCIAL.md", why: "it says what a commercial license covers and how it is obtained" },
138
+ { path: "NOTICE", why: "it carries the copyright of the licensor" },
139
+ { path: "CONTRIBUTING.md", why: "it carries the sign-off and the contributor's agreement" },
140
+ { path: "CITATION.cff", why: "it says how to cite the software and under what license" },
141
+ ];
142
+
143
+ /** Whether `text` contains `needle`, as a finding where it does not. */
144
+ const must = (path: string, text: string | undefined, needle: string, what: string): readonly Finding[] =>
145
+ text === undefined || text.includes(needle) ? [] : [{ kind: "lacks", path, what }];
146
+
147
+ /** The files this module makes for a repository and what is wrong with the rest, read from the files and the manifests; nothing is written. */
148
+ export async function judge(repo: string, folder?: string): Promise<Judged> {
149
+ const root = repo.replace(/[\\/]$/, "");
150
+ const findings: Finding[] = [];
151
+ const made: Made[] = [];
152
+ const texts = new Map<SpdxId, string>();
153
+ const reported = new Set<SpdxId>();
154
+ const textOf = async (id: SpdxId): Promise<string | undefined> => {
155
+ const have = texts.get(id);
156
+ if (have !== undefined) return have;
157
+ const r = await officialText(id, folder);
158
+ if (r.kind === "err") {
159
+ if (!reported.has(id)) findings.push(r.error);
160
+ reported.add(id);
161
+ return undefined;
162
+ }
163
+ texts.set(id, r.value);
164
+ return r.value;
165
+ };
166
+ const rootText = await textOf(DEFAULT_LICENSE);
167
+ if (rootText !== undefined) made.push({ path: "LICENSE", text: licenseFileText(rootText) });
168
+ for (const f of readLibraries(root)) {
169
+ if ("problem" in f) {
170
+ findings.push({ kind: "manifest", dir: f.dir, problem: f.problem });
171
+ continue;
172
+ }
173
+ const t = await textOf(licenseOf(f.library));
174
+ if (t !== undefined) made.push({ path: `commons/${f.dir}/LICENSE`, text: licenseFileText(t) });
175
+ }
176
+ made.push({ path: "THIRD_PARTY_NOTICES.md", text: thirdPartyNotices(THIRD_PARTY) });
177
+ for (const m of made) {
178
+ const have = read(root, m.path);
179
+ if (have === undefined) findings.push({ kind: "missing", path: m.path, why: m.path === "THIRD_PARTY_NOTICES.md" ? "it lists what is vendored and its licenses" : `it is the license of ${m.path === "LICENSE" ? "the repository" : "the library"}; run: ${COMMAND}` });
180
+ else if (have !== m.text) findings.push({ kind: "stale", path: m.path });
181
+ }
182
+ for (const h of HAND_WRITTEN) {
183
+ const t = read(root, h.path);
184
+ if (t === undefined || t.trim() === "") findings.push({ kind: "missing", path: h.path, why: h.why });
185
+ }
186
+ findings.push(...must("NOTICE", read(root, "NOTICE"), `Copyright ${LICENSOR}`, `name the copyright of ${LICENSOR}`));
187
+ findings.push(...must("CONTRIBUTING.md", read(root, "CONTRIBUTING.md"), "git commit -s", "ask for a sign-off with `git commit -s`"));
188
+ findings.push(...must("LICENSING.md", read(root, "LICENSING.md"), DEFAULT_LICENSE, `name ${DEFAULT_LICENSE}`));
189
+ findings.push(...must("LICENSING.md", read(root, "LICENSING.md"), COMMERCIAL_ISSUES_URL, `say where to ask for a commercial license (${COMMERCIAL_ISSUES_URL})`));
190
+ findings.push(...must("CITATION.cff", read(root, "CITATION.cff"), `license: ${DEFAULT_LICENSE}`, `carry \`license: ${DEFAULT_LICENSE}\``));
191
+ const readme = read(root, "README.md");
192
+ if (readme !== undefined) {
193
+ const at = readme.indexOf("\n## License\n");
194
+ const rest = at < 0 ? "" : readme.slice(at + 1);
195
+ const next = rest.indexOf("\n## ", 1);
196
+ const section = next < 0 ? rest : rest.slice(0, next);
197
+ if (at < 0 || !section.includes(DEFAULT_LICENSE)) findings.push({ kind: "lacks", path: "README.md", what: `have a License section that names ${DEFAULT_LICENSE}` });
198
+ }
199
+ const pkg = read(root, "package.json");
200
+ if (pkg !== undefined && !pkg.includes(`"license": "${DEFAULT_LICENSE}"`)) findings.push({ kind: "lacks", path: "package.json", what: `declare "license": "${DEFAULT_LICENSE}"` });
201
+ for (const i of THIRD_PARTY) if (i.path !== undefined && !existsSync(join(root, i.path))) findings.push({ kind: "vendored-gone", path: i.path });
202
+ return { made, findings };
203
+ }
204
+
205
+ /** The command line: 0, or 1 where a finding exists (with `--check`) or a file could not be made. Without `--check` the files are written. */
206
+ export async function main(argv: readonly string[]): Promise<number> {
207
+ const at = argv.indexOf("--repo");
208
+ const repo = at >= 0 ? (argv[at + 1] ?? ".") : ".";
209
+ const check = argv.includes("--check");
210
+ let j = await judge(repo);
211
+ if (!check) {
212
+ for (const m of j.made) {
213
+ const have = read(repo, m.path);
214
+ if (have !== m.text) writeTextFileSync(join(repo.replace(/[\\/]$/, ""), m.path), m.text);
215
+ }
216
+ j = await judge(repo);
217
+ }
218
+ for (const f of j.findings) stdio.stderr.writeSync(`${sentence(f)}\n`);
219
+ return j.findings.length > 0 ? 1 : 0;
220
+ }
221
+
222
+ if (import.meta.main) process.exitCode = await main(process.argv.slice(2));
@@ -24,6 +24,8 @@
24
24
  */
25
25
  import { chmod, readTextFile, writeTextFile } from "@intellectual-frontiers/system/fs";
26
26
  import { existsSync, mkdirSync, readDirSync, readTextFileSync, removeSync, writeTextFileSync } from "@intellectual-frontiers/system/fs";
27
+ import { decodeLibrarySource, type Library, LIBRARY_FILE } from "./libraries.ts";
28
+ import { COMMAND as LICENSE_COMMAND, licenseOf } from "./license.ts";
27
29
  import { basename, dirname, join, relative, resolve, toPosix } from "@intellectual-frontiers/system/path";
28
30
  import { env, run, which } from "@intellectual-frontiers/system/proc";
29
31
 
@@ -277,6 +279,7 @@ function commonsPaths(commons: string, dist: string): Record<string, readonly st
277
279
  return out;
278
280
  }
279
281
 
282
+ /** What packing a library made: the staging folder, the tarball, the findings and the manifest. */
280
283
  export type Packed = { readonly stage: string; readonly tarball: string | undefined; readonly findings: Findings; readonly manifest: Json };
281
284
 
282
285
  /** What a package adds to the common form. */
@@ -292,6 +295,7 @@ function namesNodeTypes(folder: string): boolean {
292
295
  return false;
293
296
  }
294
297
 
298
+ /** What packing a library is told: its folder, where to stage it and whether to make the tarball. */
295
299
  export type PackOptions = {
296
300
  /** Types the compiler is given (`["node"]` for a library that names Node's). */
297
301
  readonly types?: readonly string[];
@@ -307,6 +311,14 @@ export type PackOptions = {
307
311
  };
308
312
  };
309
313
 
314
+ /** The manifest of the library at `root`, where it has one that can be read. */
315
+ function manifestOf(root: string): Library | undefined {
316
+ const file = join(root, LIBRARY_FILE);
317
+ if (!existsSync(file)) return undefined;
318
+ const r = decodeLibrarySource(readTextFileSync(file));
319
+ return r.kind === "ok" ? r.value : undefined;
320
+ }
321
+
310
322
  /** Builds and stages the package of the library at `root` (a folder `commons/<name>/` with a `package.json` and sources in `src/`), inspects it and, where nothing is wrong, packs it. */
311
323
  export async function packLibrary(root: string, options: PackOptions = {}): Promise<Packed> {
312
324
  const own = JSON.parse(readTextFileSync(join(root, "package.json"))) as Json;
@@ -461,7 +473,7 @@ export async function packLibrary(root: string, options: PackOptions = {}): Prom
461
473
  name,
462
474
  version: text(own["version"]),
463
475
  description: text(own["description"]),
464
- license: "MIT",
476
+ license: licenseOf(manifestOf(root)),
465
477
  type: "module",
466
478
  engines: { node: ">=26" },
467
479
  sideEffects: false,
@@ -503,7 +515,8 @@ export async function packLibrary(root: string, options: PackOptions = {}): Prom
503
515
  "",
504
516
  ].join("\n"),
505
517
  );
506
- copyFileSync(existsSync(join(root, "LICENSE")) ? join(root, "LICENSE") : join(commons, "ergonex", "LICENSE"), join(stage, "LICENSE"));
518
+ if (existsSync(join(root, "LICENSE"))) copyFileSync(join(root, "LICENSE"), join(stage, "LICENSE"));
519
+ else findings.push(`commons/${short} has no LICENSE; run: ${LICENSE_COMMAND}`);
507
520
  findings.push(...inspectPackage(stage));
508
521
  if (findings.length > 0) return { stage, tarball: undefined, findings, manifest };
509
522
  const packed = await run([bun, "pm", "pack", "--destination", dist], { cwd: stage });
package/src/pins.ts CHANGED
@@ -1,20 +1,21 @@
1
1
  /**
2
- * Commons' pins as the tools read them (commons 0005-typescript-runtime FR-026): the `KEY=value` lines of `pins.auto.env`, and which of
3
- * Bun's release assets and pin keys belong to a platform.
2
+ * Commons' pins as the tools read them (commons 0005-typescript-runtime FR-026, 0002-packaging FR-019): the `KEY=value` lines of `pins.auto.env`, the suffix of a platform's
3
+ * variables, and the download of a pin on a platform (its version, address, SHA-256, format and folder), all taken from the file and written nowhere else.
4
4
  *
5
5
  * Spec: 0001-libraries FR-006
6
6
  *
7
7
  * @module
8
8
  */
9
+ import { err, ok, type Result } from "@intellectual-frontiers/core";
9
10
 
10
- /** The target name of Bun's release asset and the suffix of commons' pin key for a platform (by the names `proc.build` gives); undefined where Bun has no build. */
11
- export function bunTarget(os: string, arch: string): { readonly target: string; readonly key: string } | undefined {
12
- const table: Readonly<Record<string, { readonly target: string; readonly key: string }>> = {
13
- "linux/x86_64": { target: "linux-x64", key: "X86_64" },
14
- "linux/aarch64": { target: "linux-aarch64", key: "AARCH64" },
15
- "darwin/x86_64": { target: "darwin-x64", key: "MACOS_X64" },
16
- "darwin/aarch64": { target: "darwin-aarch64", key: "MACOS_ARM64" },
17
- "windows/x86_64": { target: "windows-x64", key: "WINDOWS_X64" },
11
+ /** The suffix of commons' pin variables for a platform (by the names `proc.build` gives); undefined where commons pins no download for it. */
12
+ export function pinSuffix(os: string, arch: string): string | undefined {
13
+ const table: Readonly<Record<string, string>> = {
14
+ "linux/x86_64": "X86_64",
15
+ "linux/aarch64": "AARCH64",
16
+ "darwin/x86_64": "MACOS_X64",
17
+ "darwin/aarch64": "MACOS_ARM64",
18
+ "windows/x86_64": "WINDOWS_X64",
18
19
  };
19
20
  return Object.hasOwn(table, `${os}/${arch}`) ? table[`${os}/${arch}`] : undefined;
20
21
  }
@@ -28,3 +29,47 @@ export function readEnvFile(text: string): ReadonlyMap<string, string> {
28
29
  }
29
30
  return out;
30
31
  }
32
+
33
+ /** The formats of what a pinned address gives. */
34
+ export type PinFormat = "zip" | "tar" | "file";
35
+
36
+ /** What a download of a pin on a platform needs. */
37
+ export type PinDownload = {
38
+ readonly version: string;
39
+ readonly url: string;
40
+ readonly sha256: string;
41
+ readonly format: PinFormat;
42
+ /** The folder of the programs inside the unpacked artifact; empty for the root. */
43
+ readonly binPath: string;
44
+ };
45
+
46
+ /** Why a pin has no download on a platform. */
47
+ export type PinProblem =
48
+ | { readonly kind: "no-version"; readonly key: string }
49
+ | { readonly kind: "not-pinned"; readonly key: string; readonly suffix: string }
50
+ | { readonly kind: "bad-format"; readonly key: string; readonly suffix: string; readonly format: string };
51
+
52
+ /** The sentence a problem is told in. */
53
+ export function describePinProblem(p: PinProblem): string {
54
+ switch (p.kind) {
55
+ case "no-version":
56
+ return `commons pins no ${p.key}`;
57
+ case "not-pinned":
58
+ return `commons pins no download of ${p.key} for ${p.suffix}`;
59
+ case "bad-format":
60
+ return `commons pins ${p.key} for ${p.suffix} as ${JSON.stringify(p.format)}, which is no format (zip, tar, file)`;
61
+ }
62
+ }
63
+
64
+ /** The download of the pin `key` (`BUN`) for the platform `suffix` (`X86_64`) as `pins.auto.env` states it, or why it has none. */
65
+ export function pinDownload(env: ReadonlyMap<string, string>, key: string, suffix: string): Result<PinDownload, PinProblem> {
66
+ const version = env.get(`${key}_VERSION`);
67
+ if (version === undefined) return err({ kind: "no-version", key });
68
+ const url = env.get(`${key}_URL_${suffix}`);
69
+ const sha256 = env.get(`${key}_SHA256_${suffix}`);
70
+ const format = env.get(`${key}_FORMAT_${suffix}`);
71
+ const binPath = env.get(`${key}_BINPATH_${suffix}`);
72
+ if (url === undefined || sha256 === undefined || format === undefined || binPath === undefined) return err({ kind: "not-pinned", key, suffix });
73
+ if (format !== "zip" && format !== "tar" && format !== "file") return err({ kind: "bad-format", key, suffix, format });
74
+ return ok({ version, url, sha256, format, binPath });
75
+ }