@openhi/sdk 0.0.0 → 0.1.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 (90) hide show
  1. package/LICENSE +19 -0
  2. package/README.md +205 -1
  3. package/astro/OpenhiPreview.astro +59 -0
  4. package/lib/api-base.d.ts +2 -0
  5. package/lib/api-base.js +22 -0
  6. package/lib/astro/index.d.ts +8 -0
  7. package/lib/astro/index.js +8 -0
  8. package/lib/astro/loaders.d.ts +131 -0
  9. package/lib/astro/loaders.js +318 -0
  10. package/lib/content/asset.d.ts +69 -0
  11. package/lib/content/asset.js +151 -0
  12. package/lib/content/blocks/catalogue.d.ts +11 -0
  13. package/lib/content/blocks/catalogue.js +71 -0
  14. package/lib/content/blocks/declare.d.ts +143 -0
  15. package/lib/content/blocks/declare.js +210 -0
  16. package/lib/content/blocks/index.d.ts +2 -0
  17. package/lib/content/blocks/index.js +2 -0
  18. package/lib/content/content-type.d.ts +52 -0
  19. package/lib/content/content-type.js +97 -0
  20. package/lib/content/import-plan.d.ts +56 -0
  21. package/lib/content/import-plan.js +71 -0
  22. package/lib/content/index.d.ts +14 -0
  23. package/lib/content/index.js +14 -0
  24. package/lib/content/page.d.ts +91 -0
  25. package/lib/content/page.js +222 -0
  26. package/lib/content/sanitise-html.d.ts +36 -0
  27. package/lib/content/sanitise-html.js +92 -0
  28. package/lib/content/section.d.ts +60 -0
  29. package/lib/content/section.js +59 -0
  30. package/lib/content/shapes.d.ts +68 -0
  31. package/lib/content/shapes.js +9 -0
  32. package/lib/content/theme.d.ts +25 -0
  33. package/lib/content/theme.js +54 -0
  34. package/lib/content/types.d.ts +142 -0
  35. package/lib/content/types.js +121 -0
  36. package/lib/errors.d.ts +25 -0
  37. package/lib/errors.js +25 -0
  38. package/lib/forms/index.d.ts +107 -0
  39. package/lib/forms/index.js +201 -0
  40. package/lib/index.d.ts +10 -0
  41. package/lib/index.js +9 -0
  42. package/lib/node/bin.d.ts +2 -0
  43. package/lib/node/bin.js +14 -0
  44. package/lib/node/cli/api.d.ts +24 -0
  45. package/lib/node/cli/api.js +62 -0
  46. package/lib/node/cli/check.d.ts +26 -0
  47. package/lib/node/cli/check.js +265 -0
  48. package/lib/node/cli/context.d.ts +37 -0
  49. package/lib/node/cli/context.js +55 -0
  50. package/lib/node/cli/env-check.d.ts +4 -0
  51. package/lib/node/cli/env-check.js +47 -0
  52. package/lib/node/cli/init.d.ts +2 -0
  53. package/lib/node/cli/init.js +171 -0
  54. package/lib/node/cli/load-blocks.d.ts +15 -0
  55. package/lib/node/cli/load-blocks.js +109 -0
  56. package/lib/node/cli/local-content.d.ts +47 -0
  57. package/lib/node/cli/local-content.js +126 -0
  58. package/lib/node/cli/main.d.ts +3 -0
  59. package/lib/node/cli/main.js +58 -0
  60. package/lib/node/cli/optional-tool.d.ts +8 -0
  61. package/lib/node/cli/optional-tool.js +26 -0
  62. package/lib/node/cli/pull.d.ts +2 -0
  63. package/lib/node/cli/pull.js +113 -0
  64. package/lib/node/cli/push.d.ts +6 -0
  65. package/lib/node/cli/push.js +227 -0
  66. package/lib/node/env.d.ts +34 -0
  67. package/lib/node/env.js +66 -0
  68. package/lib/node/index.d.ts +9 -0
  69. package/lib/node/index.js +8 -0
  70. package/lib/node/media.d.ts +56 -0
  71. package/lib/node/media.js +176 -0
  72. package/lib/node/read.d.ts +19 -0
  73. package/lib/node/read.js +55 -0
  74. package/lib/paging.d.ts +14 -0
  75. package/lib/paging.js +41 -0
  76. package/lib/preview/apply-draft.d.ts +42 -0
  77. package/lib/preview/apply-draft.js +185 -0
  78. package/lib/preview/index.d.ts +7 -0
  79. package/lib/preview/index.js +4 -0
  80. package/lib/preview/marks.d.ts +25 -0
  81. package/lib/preview/marks.js +17 -0
  82. package/lib/preview/runtime.d.ts +17 -0
  83. package/lib/preview/runtime.js +85 -0
  84. package/lib/preview/studio-origin.d.ts +3 -0
  85. package/lib/preview/studio-origin.js +38 -0
  86. package/lib/transport.d.ts +25 -0
  87. package/lib/transport.js +58 -0
  88. package/lib/trim-slashes.d.ts +4 -0
  89. package/lib/trim-slashes.js +14 -0
  90. package/package.json +124 -3
package/lib/index.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * @openhi/sdk: a small client core with no framework, Node or browser
3
+ * dependency. Everything else is a separate entry point (`/forms`,
4
+ * `/preview`, `/content`, `/astro`, `/node`).
5
+ */
6
+ export { apiBaseProblems } from "./api-base.js";
7
+ export { OpenhiApiError } from "./errors.js";
8
+ export { entriesOf, nextPagePath, pages } from "./paging.js";
9
+ export { createClient, FHIR_ACCEPT } from "./transport.js";
10
+ export type { ClientOptions, OpenhiClient } from "./transport.js";
package/lib/index.js ADDED
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @openhi/sdk: a small client core with no framework, Node or browser
3
+ * dependency. Everything else is a separate entry point (`/forms`,
4
+ * `/preview`, `/content`, `/astro`, `/node`).
5
+ */
6
+ export { apiBaseProblems } from "./api-base.js";
7
+ export { OpenhiApiError } from "./errors.js";
8
+ export { entriesOf, nextPagePath, pages } from "./paging.js";
9
+ export { createClient, FHIR_ACCEPT } from "./transport.js";
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env node
2
+ import { main } from "./cli/main.js";
3
+ main(process.argv.slice(2), {
4
+ cwd: process.cwd(),
5
+ env: process.env,
6
+ out: (line) => process.stdout.write(`${line}\n`),
7
+ err: (line) => process.stderr.write(`${line}\n`),
8
+ fetch,
9
+ }).then((code) => {
10
+ process.exitCode = code;
11
+ }, (caught) => {
12
+ process.stderr.write(`✗ ${caught instanceof Error ? (caught.stack ?? caught.message) : String(caught)}\n`);
13
+ process.exitCode = 1;
14
+ });
@@ -0,0 +1,24 @@
1
+ import { type SiteRecord } from "../read.js";
2
+ import { type CliContext } from "./context.js";
3
+ /** The API, the website and the key a command works with. */
4
+ export interface Target {
5
+ readonly base: string;
6
+ readonly website: string;
7
+ readonly key: string;
8
+ }
9
+ /**
10
+ * What the CLI needs from the environment, or the reason it cannot go on.
11
+ *
12
+ * There is no default API: the base comes from `OPENHI_API_BASE`, since the
13
+ * kit names no stage and no internal endpoint.
14
+ */
15
+ export declare function targetFrom(ctx: CliContext): Target;
16
+ /** One request to the API as the website key; a refusal ends the command with its reason. */
17
+ export declare function api(ctx: CliContext, target: Target, path: string, init?: RequestInit): Promise<unknown>;
18
+ /**
19
+ * Everything the site has, in one read: the `Website` record first, then
20
+ * its content and catalogue. The read is also the guard: a key opens one
21
+ * website, so a wrong id fails here rather than by putting content
22
+ * somewhere nobody asked for.
23
+ */
24
+ export declare function exportSite(ctx: CliContext, target: Target): Promise<SiteRecord[]>;
@@ -0,0 +1,62 @@
1
+ import { OpenhiApiError } from "../../errors.js";
2
+ import { trimTrailingSlashes } from "../../trim-slashes.js";
3
+ import { createClient } from "../../transport.js";
4
+ import { blank } from "../env.js";
5
+ import { entriesOf } from "../read.js";
6
+ import { apiBaseProblems } from "./env-check.js";
7
+ import { CliError } from "./context.js";
8
+ /**
9
+ * What the CLI needs from the environment, or the reason it cannot go on.
10
+ *
11
+ * There is no default API: the base comes from `OPENHI_API_BASE`, since the
12
+ * kit names no stage and no internal endpoint.
13
+ */
14
+ export function targetFrom(ctx) {
15
+ const base = blank(ctx.env.OPENHI_API_BASE);
16
+ const website = blank(ctx.env.OPENHI_WEBSITE_ID) ?? blank(ctx.env.OPENHI_WEBSITE);
17
+ const key = blank(ctx.env.OPENHI_WEBSITE_KEY);
18
+ const missing = [
19
+ base === undefined && "OPENHI_API_BASE",
20
+ website === undefined && "OPENHI_WEBSITE_ID",
21
+ key === undefined && "OPENHI_WEBSITE_KEY",
22
+ ].filter((name) => name !== false);
23
+ if (base === undefined || website === undefined || key === undefined) {
24
+ throw new CliError(`${missing.join(", ")} ${missing.length === 1 ? "is" : "are"} not set. ` +
25
+ "Make a website key in the website's settings in Studio (read-write to push).");
26
+ }
27
+ // The key goes to this URL: refuse it before any request is made.
28
+ const problems = apiBaseProblems(base);
29
+ if (problems.length > 0)
30
+ throw new CliError(problems.join("; "));
31
+ return { base: trimTrailingSlashes(base), website, key };
32
+ }
33
+ /** One request to the API as the website key; a refusal ends the command with its reason. */
34
+ export async function api(ctx, target, path, init = {}) {
35
+ const client = createClient({
36
+ base: target.base,
37
+ key: target.key,
38
+ fetch: ctx.fetch,
39
+ });
40
+ try {
41
+ return await client.request(path, init);
42
+ }
43
+ catch (caught) {
44
+ if (caught instanceof OpenhiApiError)
45
+ throw new CliError(caught.message);
46
+ throw caught;
47
+ }
48
+ }
49
+ /**
50
+ * Everything the site has, in one read: the `Website` record first, then
51
+ * its content and catalogue. The read is also the guard: a key opens one
52
+ * website, so a wrong id fails here rather than by putting content
53
+ * somewhere nobody asked for.
54
+ */
55
+ export async function exportSite(ctx, target) {
56
+ const bundle = await api(ctx, target, `/Website/${encodeURIComponent(target.website)}/export`);
57
+ const records = entriesOf(bundle);
58
+ if (records[0]?.resourceType !== "Website" || records[0].id === undefined) {
59
+ throw new CliError(`Website ${target.website} came back without its record`);
60
+ }
61
+ return records;
62
+ }
@@ -0,0 +1,26 @@
1
+ import { type CliContext } from "./context.js";
2
+ /**
3
+ * `openhi-site check`, for CI. It fails when:
4
+ *
5
+ * 1. a declared block has no catalogue entry (the generated
6
+ * `openhi.catalogue.json` is missing it, is stale for it, or names a
7
+ * block that is no longer declared),
8
+ * 2. a declared field has no preview mark in the built HTML,
9
+ * 3. a referenced form is missing, or
10
+ * 4. the env settings are wrong,
11
+ *
12
+ * and for a block declaration that could not be published at all. Nothing
13
+ * is sent anywhere: `check` reads the working tree, the built site and the
14
+ * environment.
15
+ */
16
+ /** The generated catalogue, committed so a stale one is a failed build. */
17
+ export declare const CATALOGUE_FILE = "openhi.catalogue.json";
18
+ export type ProblemKind = "env" | "blocks" | "catalogue" | "preview" | "form";
19
+ export interface Problem {
20
+ readonly kind: ProblemKind;
21
+ readonly message: string;
22
+ }
23
+ export declare function checkSite(ctx: CliContext, options?: {
24
+ readonly dist?: string;
25
+ }): Promise<Problem[]>;
26
+ export declare function check(ctx: CliContext, argv: readonly string[]): Promise<number>;
@@ -0,0 +1,265 @@
1
+ import { trimSlashes } from "../../trim-slashes.js";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { resolve } from "node:path";
4
+ import { loadOptional } from "./optional-tool.js";
5
+ import { blockCodeSystem, catalogueCodes, } from "../../content/blocks/catalogue.js";
6
+ import { blockProblems, } from "../../content/blocks/declare.js";
7
+ import { BLOCK, ENTRY, FIELD, LIST } from "../../preview/apply-draft.js";
8
+ import { CliError, parseArgs } from "./context.js";
9
+ import { envProblems } from "./env-check.js";
10
+ import { localForms, localPageData } from "./local-content.js";
11
+ import { loadBlocks, readCatalogueFile } from "./load-blocks.js";
12
+ /**
13
+ * `openhi-site check`, for CI. It fails when:
14
+ *
15
+ * 1. a declared block has no catalogue entry (the generated
16
+ * `openhi.catalogue.json` is missing it, is stale for it, or names a
17
+ * block that is no longer declared),
18
+ * 2. a declared field has no preview mark in the built HTML,
19
+ * 3. a referenced form is missing, or
20
+ * 4. the env settings are wrong,
21
+ *
22
+ * and for a block declaration that could not be published at all. Nothing
23
+ * is sent anywhere: `check` reads the working tree, the built site and the
24
+ * environment.
25
+ */
26
+ /** The generated catalogue, committed so a stale one is a failed build. */
27
+ export const CATALOGUE_FILE = "openhi.catalogue.json";
28
+ /** The names a block's data is expected to mark: fields, props, lists and their entry fields. */
29
+ function expectedMarks(block) {
30
+ return {
31
+ // A link is not text, a form reference is a name the site looks up, and
32
+ // a block can say which other names it does not draw.
33
+ fields: [
34
+ ...block.fields.filter((name) => name !== "link"),
35
+ ...block.props,
36
+ ].filter((name) => !block.forms.includes(name) && !block.noPreview.includes(name)),
37
+ lists: block.lists.map((list) => ({
38
+ name: list.name,
39
+ fields: list.fields,
40
+ })),
41
+ };
42
+ }
43
+ const present = (value) => value !== undefined &&
44
+ value !== null &&
45
+ value !== "" &&
46
+ !(Array.isArray(value) && value.length === 0);
47
+ /** The built file for a permalink, if the build wrote one. */
48
+ function builtFile(dist, permalink) {
49
+ const trimmed = trimSlashes(permalink);
50
+ const candidates = trimmed === ""
51
+ ? [resolve(dist, "index.html")]
52
+ : [
53
+ resolve(dist, trimmed, "index.html"),
54
+ resolve(dist, `${trimmed}.html`),
55
+ ];
56
+ return candidates.find((path) => existsSync(path));
57
+ }
58
+ function catalogueProblems(set, committed) {
59
+ const problems = [];
60
+ const describe = (block, why) => ({
61
+ kind: "catalogue",
62
+ message: `block "${block}" has no catalogue entry in ${CATALOGUE_FILE}: ${why}`,
63
+ });
64
+ if (committed === undefined) {
65
+ return set.blocks.map((block) => describe(block.code, "the file is missing; run `openhi-site push --dry-run` to generate it"));
66
+ }
67
+ const have = new Set(catalogueCodes(committed));
68
+ const generated = blockCodeSystem(set);
69
+ const generatedConcepts = new Map(generated.concept.map((concept) => [
70
+ concept.code,
71
+ concept,
72
+ ]));
73
+ const committedConcepts = new Map((committed.concept ?? []).flatMap((concept) => concept.code === undefined ? [] : [[concept.code, concept]]));
74
+ for (const block of set.blocks) {
75
+ if (!have.has(block.code)) {
76
+ problems.push(describe(block.code, "it is declared but not in the file; run `openhi-site push --dry-run`"));
77
+ }
78
+ else if (JSON.stringify(committedConcepts.get(block.code)) !==
79
+ JSON.stringify(generatedConcepts.get(block.code))) {
80
+ problems.push({
81
+ kind: "catalogue",
82
+ message: `the catalogue entry for block "${block.code}" is out of date; run \`openhi-site push --dry-run\``,
83
+ });
84
+ }
85
+ }
86
+ const declared = new Set(set.blocks.map((block) => block.code));
87
+ for (const code of have) {
88
+ if (!declared.has(code)) {
89
+ problems.push({
90
+ kind: "catalogue",
91
+ message: `${CATALOGUE_FILE} has "${code}", which openhi.blocks.ts no longer declares; run \`openhi-site push --dry-run\``,
92
+ });
93
+ }
94
+ }
95
+ if (committed.url !== set.system) {
96
+ problems.push({
97
+ kind: "catalogue",
98
+ message: `${CATALOGUE_FILE} is for ${String(committed.url)}, not ${set.system}; run \`openhi-site push --dry-run\``,
99
+ });
100
+ }
101
+ return problems;
102
+ }
103
+ async function previewProblems(root, dist, set) {
104
+ const problems = [];
105
+ const byCode = new Map(set.blocks.map((block) => [block.code, block]));
106
+ const pages = localPageData(root).filter(({ page }) => page.status === "active");
107
+ const used = pages.flatMap(({ page }) => page.layout.filter((section) => byCode.has(section.component)));
108
+ if (used.length === 0)
109
+ return problems;
110
+ if (!existsSync(dist)) {
111
+ return [
112
+ {
113
+ kind: "preview",
114
+ message: `there is no built site at ${dist}; run the site's build before \`openhi-site check\`, or pass --dist`,
115
+ },
116
+ ];
117
+ }
118
+ const needsHtml = pages.some(({ page }) => page.layout.some((section) => byCode.has(section.component)));
119
+ const { parseHTML } = needsHtml
120
+ ? await loadOptional("linkedom", "check", () => import("linkedom"))
121
+ : { parseHTML: undefined };
122
+ for (const { page } of pages) {
123
+ const sections = page.layout.filter((section) => byCode.has(section.component));
124
+ if (sections.length === 0)
125
+ continue;
126
+ const file = builtFile(dist, page.permalink);
127
+ if (file === undefined) {
128
+ problems.push({
129
+ kind: "preview",
130
+ message: `page ${page.permalink} is in src/content but has no built HTML in ${dist}`,
131
+ });
132
+ continue;
133
+ }
134
+ const { document } = parseHTML(readFileSync(file, "utf8"));
135
+ for (const section of sections) {
136
+ const block = byCode.get(section.component);
137
+ const at = `page ${page.permalink}, block "${section.component}" (${section.identifier})`;
138
+ const wrapper = [...document.querySelectorAll(`[${BLOCK}]`)].find((element) => element.getAttribute(BLOCK) === section.identifier);
139
+ if (wrapper === undefined) {
140
+ problems.push({
141
+ kind: "preview",
142
+ message: `${at} is not wrapped in a ${BLOCK} mark`,
143
+ });
144
+ continue;
145
+ }
146
+ problems.push(...markProblems(wrapper, block, section, at));
147
+ }
148
+ }
149
+ return problems;
150
+ }
151
+ function markProblems(wrapper, block, section, at) {
152
+ const problems = [];
153
+ const marks = expectedMarks(block);
154
+ const fieldNames = new Set([...wrapper.querySelectorAll(`[${FIELD}]`)].map((element) => element.getAttribute(FIELD)));
155
+ for (const name of marks.fields) {
156
+ // A value the content leaves out has nothing to mark: the build omits it.
157
+ if (present(section.data[name]) && !fieldNames.has(name)) {
158
+ problems.push({
159
+ kind: "preview",
160
+ message: `${at}: field "${name}" has no ${FIELD} mark in the built HTML`,
161
+ });
162
+ }
163
+ }
164
+ for (const list of marks.lists) {
165
+ const items = section.data[list.name];
166
+ if (!present(items))
167
+ continue;
168
+ const holder = [...wrapper.querySelectorAll(`[${LIST}]`)].find((element) => element.getAttribute(LIST) === list.name);
169
+ if (holder === undefined) {
170
+ problems.push({
171
+ kind: "preview",
172
+ message: `${at}: list "${list.name}" has no ${LIST} mark in the built HTML`,
173
+ });
174
+ continue;
175
+ }
176
+ if (holder.querySelector(`[${ENTRY}]`) === null) {
177
+ problems.push({
178
+ kind: "preview",
179
+ message: `${at}: list "${list.name}" has no ${ENTRY} marks in the built HTML`,
180
+ });
181
+ }
182
+ const inside = new Set([...holder.querySelectorAll(`[${FIELD}]`)].map((element) => element.getAttribute(FIELD)));
183
+ const first = Array.isArray(items) ? items[0] : undefined;
184
+ for (const name of list.fields) {
185
+ const set = typeof first === "object" &&
186
+ first !== null &&
187
+ present(first[name]);
188
+ if (set && !inside.has(name)) {
189
+ problems.push({
190
+ kind: "preview",
191
+ message: `${at}: field "${list.name}.${name}" has no ${FIELD} mark in the built HTML`,
192
+ });
193
+ }
194
+ }
195
+ }
196
+ return problems;
197
+ }
198
+ function formProblems(root, set) {
199
+ const problems = [];
200
+ const have = new Set(localForms(root).map((form) => form.name));
201
+ const byCode = new Map(set.blocks.map((block) => [block.code, block]));
202
+ for (const { page } of localPageData(root)) {
203
+ for (const section of page.layout) {
204
+ const block = byCode.get(section.component);
205
+ if (block === undefined)
206
+ continue;
207
+ for (const name of block.forms) {
208
+ const value = section.data[name];
209
+ if (typeof value === "string" && value.length > 0 && !have.has(value)) {
210
+ problems.push({
211
+ kind: "form",
212
+ message: `page ${page.permalink}, block "${section.component}" (${section.identifier}) refers to form "${value}" (${name}), which is not in src/content/forms`,
213
+ });
214
+ }
215
+ }
216
+ }
217
+ }
218
+ return problems;
219
+ }
220
+ export async function checkSite(ctx, options = {}) {
221
+ const problems = envProblems(ctx.env).map((message) => ({
222
+ kind: "env",
223
+ message,
224
+ }));
225
+ let set;
226
+ try {
227
+ set = await loadBlocks(ctx.cwd, "check");
228
+ if (set === undefined) {
229
+ problems.push({
230
+ kind: "blocks",
231
+ message: "there is no openhi.blocks.ts; run `openhi-site init` to add one",
232
+ });
233
+ }
234
+ else {
235
+ problems.push(...blockProblems(set).map((message) => ({
236
+ kind: "blocks",
237
+ message,
238
+ })));
239
+ }
240
+ }
241
+ catch (caught) {
242
+ if (!(caught instanceof CliError))
243
+ throw caught;
244
+ problems.push({ kind: "blocks", message: caught.message });
245
+ }
246
+ if (set === undefined)
247
+ return problems;
248
+ problems.push(...catalogueProblems(set, readCatalogueFile(resolve(ctx.cwd, CATALOGUE_FILE))));
249
+ problems.push(...formProblems(ctx.cwd, set));
250
+ problems.push(...(await previewProblems(ctx.cwd, resolve(ctx.cwd, options.dist ?? "dist"), set)));
251
+ return problems;
252
+ }
253
+ export async function check(ctx, argv) {
254
+ const { flags } = parseArgs(argv, { valued: ["dist"] });
255
+ const dist = typeof flags.dist === "string" ? flags.dist : undefined;
256
+ const problems = await checkSite(ctx, dist === undefined ? {} : { dist });
257
+ for (const problem of problems)
258
+ ctx.err(`✗ [${problem.kind}] ${problem.message}`);
259
+ if (problems.length > 0) {
260
+ ctx.err(`\n${problems.length} problem(s). openhi-site check failed.`);
261
+ return 1;
262
+ }
263
+ ctx.out("✓ openhi-site check passed");
264
+ return 0;
265
+ }
@@ -0,0 +1,37 @@
1
+ import type { Env } from "../env.js";
2
+ /** What a command runs against; a test hands it a fixture and a fake API. */
3
+ export interface CliContext {
4
+ /** The project root: the site's directory. */
5
+ readonly cwd: string;
6
+ readonly env: Env;
7
+ out(line: string): void;
8
+ err(line: string): void;
9
+ readonly fetch: typeof fetch;
10
+ }
11
+ export interface Flags {
12
+ readonly [name: string]: string | boolean | undefined;
13
+ }
14
+ /** The flags a command knows; anything else is misuse. */
15
+ export interface FlagSpec {
16
+ /** Flags that stand alone: `--dry-run`. */
17
+ readonly boolean?: readonly string[];
18
+ /** Flags that take a value: `--dist <dir>` or `--dist=<dir>`. */
19
+ readonly valued?: readonly string[];
20
+ }
21
+ /** The command was used wrongly: main prints the usage and exits 2. */
22
+ export declare class UsageError extends Error {
23
+ readonly name = "UsageError";
24
+ }
25
+ /**
26
+ * `--name`, `--name value` and `--name=value` for the flags a command
27
+ * declares. An unknown flag, a stray positional, a valued flag with no
28
+ * value and a boolean flag given one are all a `UsageError`: a typo such
29
+ * as `--dryrun` must not run the real thing.
30
+ */
31
+ export declare function parseArgs(argv: readonly string[], spec?: FlagSpec): {
32
+ flags: Flags;
33
+ };
34
+ /** A command that cannot go on, with the message to print. */
35
+ export declare class CliError extends Error {
36
+ readonly name = "CliError";
37
+ }
@@ -0,0 +1,55 @@
1
+ /** The command was used wrongly: main prints the usage and exits 2. */
2
+ export class UsageError extends Error {
3
+ constructor() {
4
+ super(...arguments);
5
+ this.name = "UsageError";
6
+ }
7
+ }
8
+ /**
9
+ * `--name`, `--name value` and `--name=value` for the flags a command
10
+ * declares. An unknown flag, a stray positional, a valued flag with no
11
+ * value and a boolean flag given one are all a `UsageError`: a typo such
12
+ * as `--dryrun` must not run the real thing.
13
+ */
14
+ export function parseArgs(argv, spec = {}) {
15
+ const booleans = new Set(spec.boolean ?? []);
16
+ const valued = new Set(spec.valued ?? []);
17
+ const flags = {};
18
+ for (let at = 0; at < argv.length; at += 1) {
19
+ const arg = argv[at];
20
+ if (!arg.startsWith("--")) {
21
+ throw new UsageError(`unexpected argument "${arg}"`);
22
+ }
23
+ const [name, inline] = arg.slice(2).split(/=(.*)/s, 2);
24
+ if (booleans.has(name)) {
25
+ if (inline !== undefined) {
26
+ throw new UsageError(`--${name} does not take a value`);
27
+ }
28
+ flags[name] = true;
29
+ }
30
+ else if (valued.has(name)) {
31
+ const next = argv[at + 1];
32
+ if (inline !== undefined && inline.length > 0)
33
+ flags[name] = inline;
34
+ else if (inline === undefined &&
35
+ next !== undefined &&
36
+ !next.startsWith("--")) {
37
+ flags[name] = next;
38
+ at += 1;
39
+ }
40
+ else
41
+ throw new UsageError(`--${name} needs a value`);
42
+ }
43
+ else {
44
+ throw new UsageError(`unknown option "--${name}"`);
45
+ }
46
+ }
47
+ return { flags };
48
+ }
49
+ /** A command that cannot go on, with the message to print. */
50
+ export class CliError extends Error {
51
+ constructor() {
52
+ super(...arguments);
53
+ this.name = "CliError";
54
+ }
55
+ }
@@ -0,0 +1,4 @@
1
+ import { apiBaseProblems, type Env } from "../env.js";
2
+ export { apiBaseProblems };
3
+ /** What is wrong with a build's environment, if anything. */
4
+ export declare function envProblems(env: Env): string[];
@@ -0,0 +1,47 @@
1
+ import { apiBaseProblems, blank } from "../env.js";
2
+ export { apiBaseProblems };
3
+ /** What is wrong with a build's environment, if anything. */
4
+ export function envProblems(env) {
5
+ const problems = [];
6
+ const base = blank(env.OPENHI_API_BASE);
7
+ const website = blank(env.OPENHI_WEBSITE_ID) ?? blank(env.OPENHI_WEBSITE);
8
+ const key = blank(env.OPENHI_WEBSITE_KEY);
9
+ const required = env.OPENHI_CONTENT_REQUIRED;
10
+ if (base !== undefined)
11
+ problems.push(...apiBaseProblems(base));
12
+ if (base !== undefined && website === undefined) {
13
+ problems.push(blank(env.OPENHI_PROJECT_ID) !== undefined
14
+ ? "OPENHI_PROJECT_ID is not read: content belongs to a website, so set OPENHI_WEBSITE_ID"
15
+ : "OPENHI_API_BASE is set but OPENHI_WEBSITE_ID is not: the build would use git alone");
16
+ }
17
+ if (base === undefined && website !== undefined) {
18
+ problems.push("OPENHI_WEBSITE_ID is set but OPENHI_API_BASE is not: the build would use git alone");
19
+ }
20
+ if (blank(env.OPENHI_TOKEN) !== undefined) {
21
+ problems.push("OPENHI_TOKEN is not read: it is a signed-in person's session and expires in about an hour. Use a website key (OPENHI_WEBSITE_KEY)");
22
+ }
23
+ if (key !== undefined && !key.startsWith("ohi_wk_")) {
24
+ problems.push("OPENHI_WEBSITE_KEY is not a website key (it starts ohi_wk_)");
25
+ }
26
+ for (const name of Object.keys(env)) {
27
+ if (/^PUBLIC_.*OPENHI_(WEBSITE_)?KEY/.test(name) &&
28
+ blank(env[name]) !== undefined) {
29
+ problems.push(`${name} is inlined into the browser bundle: a website key is a build-time secret and must not start PUBLIC_`);
30
+ }
31
+ }
32
+ if (required !== undefined &&
33
+ required !== "" &&
34
+ required !== "1" &&
35
+ required !== "0") {
36
+ problems.push(`OPENHI_CONTENT_REQUIRED="${required}" is not read: the only value that requires content is 1`);
37
+ }
38
+ if (required === "1") {
39
+ if (base === undefined)
40
+ problems.push("OPENHI_CONTENT_REQUIRED=1 but OPENHI_API_BASE is not set");
41
+ if (website === undefined)
42
+ problems.push("OPENHI_CONTENT_REQUIRED=1 but OPENHI_WEBSITE_ID is not set");
43
+ if (key === undefined)
44
+ problems.push("OPENHI_CONTENT_REQUIRED=1 but OPENHI_WEBSITE_KEY is not set");
45
+ }
46
+ return problems;
47
+ }
@@ -0,0 +1,2 @@
1
+ import { type CliContext } from "./context.js";
2
+ export declare function init(ctx: CliContext, argv: readonly string[]): Promise<number>;