@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
@@ -0,0 +1,113 @@
1
+ import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
2
+ import { dirname, relative, resolve, sep } from "node:path";
3
+ import { pageFromResource } from "../../content/page.js";
4
+ import { sectionFromResource, } from "../../content/section.js";
5
+ import { ofType } from "../read.js";
6
+ import { exportSite, targetFrom } from "./api.js";
7
+ import { CliError, parseArgs } from "./context.js";
8
+ import { CONTENT_DIR } from "./local-content.js";
9
+ /**
10
+ * Write Studio's content back into `src/content`.
11
+ *
12
+ * The mapping is the loaders' own, so a pulled file is what a build from
13
+ * OpenHI would have used: committing it makes git the same as Studio.
14
+ * Files are named for the id the collections give the record (a page's
15
+ * slug, a section's name, a form's name), which is how git and OpenHI
16
+ * overlay. Form integrations are not written. Media stays as `ContentAsset/{id}` references, which the build
17
+ * localises. Only active records are written. A page or section Studio has
18
+ * drafted or retired loses its file here, so git does not keep publishing
19
+ * it; a file with no record at all is left for a person to decide on.
20
+ */
21
+ /** What a record may be called on disk: it is a path under `src/content`. */
22
+ const SAFE_NAME = /^[a-z0-9][a-z0-9_-]*(\/[a-z0-9][a-z0-9_-]*)*$/;
23
+ const json = (value) => `${JSON.stringify(value, null, 2)}\n`;
24
+ export async function pull(ctx, argv) {
25
+ const { flags } = parseArgs(argv, { boolean: ["dry-run"] });
26
+ const dryRun = flags["dry-run"] === true;
27
+ const target = targetFrom(ctx);
28
+ const records = await exportSite(ctx, target);
29
+ // Content keeps its `ContentAsset/{id}` references, exactly as Studio has
30
+ // them: the build turns them into files, and a push gives them back as
31
+ // references rather than as new assets.
32
+ const files = [];
33
+ // Only published records are written: a draft pulled as "inactive" would
34
+ // come back from a push as "retired".
35
+ const withheld = [];
36
+ const published = (items) => items.filter((item) => item.status === "active");
37
+ const pages = ofType(records, "Page");
38
+ const sections = ofType(records, "Section");
39
+ for (const resource of pages.filter((r) => r.status !== "active")) {
40
+ withheld.push(`pages/${pageFromResource(resource).slug}.json`);
41
+ }
42
+ for (const resource of sections.filter((r) => r.status !== "active")) {
43
+ withheld.push(`sections/${sectionFromResource(resource).slug}.json`);
44
+ }
45
+ for (const resource of published(pages)) {
46
+ const page = pageFromResource(resource);
47
+ files.push({ path: `pages/${page.slug}.json`, body: json(page) });
48
+ }
49
+ for (const resource of published(sections)) {
50
+ const section = sectionFromResource(resource);
51
+ files.push({ path: `sections/${section.slug}.json`, body: json(section) });
52
+ }
53
+ for (const stored of ofType(records, "Form")) {
54
+ // Integrations (recipients, connection refs) are Studio's and may name
55
+ // people: they stay out of git, and a later push leaves them alone.
56
+ const { integration: _studio, ...form } = stored;
57
+ files.push({ path: `forms/${form.name}.json`, body: json(form) });
58
+ }
59
+ // Every path is decided before the first is written: one bad name stops
60
+ // the pull with nothing on disk.
61
+ const contentRoot = resolve(ctx.cwd, CONTENT_DIR);
62
+ const seen = new Set();
63
+ for (const file of files) {
64
+ const [dir, ...rest] = file.path.replace(/\.json$/, "").split("/");
65
+ const name = rest.join("/");
66
+ if (!SAFE_NAME.test(name)) {
67
+ throw new CliError(`${dir} "${name}" cannot be written to ${CONTENT_DIR}: a name is lower-case letters, digits, "-" and "_", with "/" between folders`);
68
+ }
69
+ const full = resolve(contentRoot, file.path);
70
+ const inside = relative(contentRoot, full);
71
+ if (inside.startsWith("..") || inside.split(sep).includes("..")) {
72
+ throw new CliError(`${file.path} would be written outside ${CONTENT_DIR}`);
73
+ }
74
+ if (seen.has(file.path)) {
75
+ throw new CliError(`two records would both be written to ${CONTENT_DIR}/${file.path}`);
76
+ }
77
+ seen.add(file.path);
78
+ }
79
+ for (const file of files) {
80
+ ctx.out(`${dryRun ? "would write" : "wrote"} ${CONTENT_DIR}/${file.path}`);
81
+ if (dryRun)
82
+ continue;
83
+ const full = resolve(contentRoot, file.path);
84
+ mkdirSync(dirname(full), { recursive: true });
85
+ writeFileSync(full, file.body);
86
+ }
87
+ // A withheld record's twin in git would go on being published. A name that
88
+ // is also written (an active record wins) or is unsafe is never removed.
89
+ const removable = withheld.filter((path) => {
90
+ if (seen.has(path))
91
+ return false;
92
+ const full = resolve(contentRoot, path);
93
+ const inside = relative(contentRoot, full);
94
+ return (!inside.startsWith("..") &&
95
+ SAFE_NAME.test(path
96
+ .replace(/\.json$/, "")
97
+ .split("/")
98
+ .slice(1)
99
+ .join("/")) &&
100
+ existsSync(full));
101
+ });
102
+ for (const path of removable) {
103
+ ctx.out(`${dryRun ? "would remove" : "removed"} ${CONTENT_DIR}/${path}`);
104
+ if (!dryRun)
105
+ rmSync(resolve(contentRoot, path), { force: true });
106
+ }
107
+ if (dryRun) {
108
+ ctx.out("\n(dry run — nothing written)");
109
+ return 0;
110
+ }
111
+ ctx.out(`\n✓ ${files.length} file(s) written`);
112
+ return 0;
113
+ }
@@ -0,0 +1,6 @@
1
+ import { type SiteRecord } from "../read.js";
2
+ import { type CliContext } from "./context.js";
3
+ /** Records in Bundles that each fit the import's limit, in order. */
4
+ export declare function chunked(records: ReadonlyArray<Record<string, unknown>>): Record<string, unknown>[][];
5
+ export declare function push(ctx: CliContext, argv: readonly string[]): Promise<number>;
6
+ export type { SiteRecord };
@@ -0,0 +1,227 @@
1
+ import { writeFileSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { blockCodeSystem } from "../../content/blocks/catalogue.js";
4
+ import { describePlan, mergeFormIntegrations, planImport, } from "../../content/import-plan.js";
5
+ import { ofType } from "../read.js";
6
+ import { api, exportSite, targetFrom } from "./api.js";
7
+ import { CATALOGUE_FILE } from "./check.js";
8
+ import { CliError, parseArgs } from "./context.js";
9
+ import { localAssets, localForms, localPages, localSections, localTheme, } from "./local-content.js";
10
+ import { loadBlocks } from "./load-blocks.js";
11
+ /**
12
+ * Push a site's local content into OpenHI, for one website.
13
+ *
14
+ * A site whose content is in git, which is every site until somebody edits
15
+ * one in Studio, needs a way to get that content into the API the first
16
+ * time. This is that way, and it is re-runnable: every record is matched by
17
+ * address, so running it twice updates rather than duplicates.
18
+ *
19
+ * Two requests do the work: `GET /Website/{id}/export` says what the site
20
+ * already has, and `POST /Website/{id}/import` takes a Bundle of records to
21
+ * create or update. The server matches each record by id or by address and
22
+ * pins every one to this website, so nothing here can write anywhere else.
23
+ */
24
+ /** The largest Bundle sent with files in it; the import takes 25 MB. */
25
+ const IMPORT_CHUNK_BYTES = 8 * 1024 * 1024;
26
+ /** Records in Bundles that each fit the import's limit, in order. */
27
+ export function chunked(records) {
28
+ const chunks = [];
29
+ let current = [];
30
+ let size = 0;
31
+ for (const record of records) {
32
+ const bytes = JSON.stringify(record).length;
33
+ if (current.length > 0 && size + bytes > IMPORT_CHUNK_BYTES) {
34
+ chunks.push(current);
35
+ current = [];
36
+ size = 0;
37
+ }
38
+ current.push(record);
39
+ size += bytes;
40
+ }
41
+ if (current.length > 0)
42
+ chunks.push(current);
43
+ return chunks;
44
+ }
45
+ /**
46
+ * Send one Bundle to the site's import and report what happened to each
47
+ * record. A refused record is a bug in what was sent, so it is fatal after
48
+ * the report rather than quietly left out.
49
+ */
50
+ async function importRecords(ctx, target, records) {
51
+ if (records.length === 0)
52
+ return [];
53
+ const answer = (await api(ctx, target, `/Website/${encodeURIComponent(target.website)}/import`, {
54
+ method: "POST",
55
+ body: JSON.stringify({
56
+ resourceType: "Bundle",
57
+ type: "collection",
58
+ entry: records.map((resource) => ({ resource })),
59
+ }),
60
+ }));
61
+ const outcomes = answer.entry ?? [];
62
+ const refused = outcomes.filter((one) => one.outcome === "refused");
63
+ for (const one of refused) {
64
+ ctx.err(` ✗ ${one.resourceType}${one.id ? `/${one.id}` : ""}: ${one.reason ?? "refused"}`);
65
+ }
66
+ if (refused.length > 0)
67
+ throw new CliError(`${refused.length} record(s) refused`);
68
+ return outcomes;
69
+ }
70
+ /**
71
+ * Forms are matched by name rather than address, since a form has no url.
72
+ * The same plan shape as the rest, so the report reads the same.
73
+ */
74
+ function planForms(local, existing) {
75
+ return local.map((form) => {
76
+ const stored = existing.find((one) => one.name === form.name);
77
+ // A payment integration is Studio's to set, since it names a
78
+ // connection the workspace has; git's import keeps it.
79
+ const integration = mergeFormIntegrations(form.integration, stored?.integration);
80
+ const resource = {
81
+ ...form,
82
+ ...(integration !== undefined ? { integration } : {}),
83
+ };
84
+ if (integration === undefined)
85
+ delete resource.integration;
86
+ return stored?.id !== undefined
87
+ ? { kind: "update", resource, id: stored.id }
88
+ : { kind: "create", resource };
89
+ });
90
+ }
91
+ /** A plan's records as the import takes them: an update carries its id. */
92
+ function planned(actions) {
93
+ return actions.map((action) => {
94
+ const { id: _unused, ...resource } = action.resource;
95
+ return action.kind === "update" ? { ...resource, id: action.id } : resource;
96
+ });
97
+ }
98
+ export async function push(ctx, argv) {
99
+ const { flags } = parseArgs(argv, { boolean: ["dry-run", "catalogue"] });
100
+ const dryRun = flags["dry-run"] === true;
101
+ /**
102
+ * Publish the block catalogue and nothing else.
103
+ *
104
+ * The catalogue changes whenever a block grows a field, and far more
105
+ * often than the content does. Without this the only way to republish it
106
+ * was a full import, which overwrites every page with the git copy — so
107
+ * updating a catalogue meant discarding anything edited in Studio.
108
+ */
109
+ const catalogueOnly = flags.catalogue === true;
110
+ // The generated catalogue is local, so it is refreshed on a dry run too.
111
+ const blocks = await loadBlocks(ctx.cwd, "push");
112
+ const system = blocks === undefined ? undefined : blockCodeSystem(blocks);
113
+ if (system !== undefined) {
114
+ writeFileSync(resolve(ctx.cwd, CATALOGUE_FILE), `${JSON.stringify(system, null, 2)}\n`);
115
+ }
116
+ const target = targetFrom(ctx);
117
+ // Read even on a dry run. A preview that skipped this would call every
118
+ // record a create and tell you nothing about what the run would change.
119
+ const existing = await exportSite(ctx, target);
120
+ const website = existing[0];
121
+ ctx.out(`${target.base} · ${website.title ?? website.slug ?? "(untitled)"} (website ${target.website})\n`);
122
+ // The catalogue: the site's block types, and the website naming them.
123
+ // Adding rather than replacing: a site may draw on more than one system,
124
+ // and this one should not evict another.
125
+ const storedSystem = system === undefined
126
+ ? undefined
127
+ : ofType(existing, "CodeSystem").find((one) => one.url === system.url);
128
+ const named = website.blockCatalogue ?? [];
129
+ const theme = localTheme(ctx.cwd);
130
+ const storedTheme = theme === undefined
131
+ ? undefined
132
+ : ofType(existing, "Theme").find((one) => one.name === theme.name);
133
+ const catalogue = [
134
+ ...(system === undefined
135
+ ? []
136
+ : [
137
+ {
138
+ ...system,
139
+ ...(storedSystem?.id !== undefined && { id: storedSystem.id }),
140
+ },
141
+ ]),
142
+ ...(theme === undefined
143
+ ? []
144
+ : [
145
+ {
146
+ ...theme,
147
+ ...(storedTheme?.id !== undefined && { id: storedTheme.id }),
148
+ },
149
+ ]),
150
+ ];
151
+ if (blocks !== undefined)
152
+ ctx.out(`Block types: ${blocks.blocks.length} at ${blocks.system}`);
153
+ if (theme !== undefined)
154
+ ctx.out(`Theme: ${storedTheme === undefined ? "+ " : "~ "}${String(theme.name)}`);
155
+ /** The site's own record, once the catalogue and theme have ids to name. */
156
+ const websiteEntry = (themeId) => {
157
+ const wantsCatalogue = system !== undefined && !named.includes(String(system.url));
158
+ const wantsTheme = themeId !== undefined && website.theme?.reference !== `Theme/${themeId}`;
159
+ if (!wantsCatalogue && !wantsTheme)
160
+ return [];
161
+ return [
162
+ {
163
+ resourceType: "Website",
164
+ id: target.website,
165
+ ...(wantsCatalogue && {
166
+ blockCatalogue: [...named, String(system?.url)],
167
+ }),
168
+ ...(wantsTheme && { theme: { reference: `Theme/${themeId}` } }),
169
+ },
170
+ ];
171
+ };
172
+ if (catalogueOnly) {
173
+ if (dryRun) {
174
+ ctx.out("\n(dry run — nothing written)");
175
+ return 0;
176
+ }
177
+ const published = await importRecords(ctx, target, catalogue);
178
+ const themeId = storedTheme?.id ??
179
+ published.find((one) => one.resourceType === "Theme")?.id;
180
+ await importRecords(ctx, target, websiteEntry(themeId));
181
+ ctx.out("\n✓ catalogue published");
182
+ return 0;
183
+ }
184
+ const pages = planImport(localPages(ctx.cwd, blocks), ofType(existing, "Page"));
185
+ const sections = planImport(localSections(ctx.cwd), ofType(existing, "Section"));
186
+ const assets = planImport(localAssets(ctx.cwd, ctx.err), ofType(existing, "ContentAsset"));
187
+ const forms = planForms(localForms(ctx.cwd), ofType(existing, "Form"));
188
+ const report = (label, actions) => {
189
+ ctx.out(`${label}: ${describePlan(actions, label.toLowerCase().replace(/s$/, ""))}`);
190
+ for (const action of actions) {
191
+ ctx.out(` ${action.kind === "create" ? "+" : "~"} ${action.resource.url ?? ""}`);
192
+ }
193
+ };
194
+ report("Pages", pages);
195
+ report("Sections", sections);
196
+ report("Assets", assets);
197
+ ctx.out(`Forms: ${forms.length} form(s)`);
198
+ for (const action of forms) {
199
+ ctx.out(` ${action.kind === "create" ? "+" : "~"} ${action.resource.name}`);
200
+ }
201
+ if (dryRun) {
202
+ ctx.out("\n(dry run — nothing written)");
203
+ return 0;
204
+ }
205
+ // The catalogue and the theme first, so a page never lands citing codes
206
+ // nothing describes. Then the site's record naming them, then the
207
+ // content, with the files in Bundles of their own so none goes over the
208
+ // limit.
209
+ const first = await importRecords(ctx, target, catalogue);
210
+ const themeId = storedTheme?.id ?? first.find((one) => one.resourceType === "Theme")?.id;
211
+ const site = await importRecords(ctx, target, websiteEntry(themeId));
212
+ const rest = [];
213
+ for (const chunk of chunked([
214
+ ...planned(pages),
215
+ ...planned(sections),
216
+ ...forms.map((action) => action.kind === "update"
217
+ ? { ...action.resource, id: action.id }
218
+ : action.resource),
219
+ ...planned(assets),
220
+ ])) {
221
+ rest.push(...(await importRecords(ctx, target, chunk)));
222
+ }
223
+ const all = [...first, ...site, ...rest];
224
+ const created = all.filter((one) => one.outcome === "created").length;
225
+ ctx.out(`\n✓ ${all.length} record(s) written (${created} created, ${all.length - created} updated)`);
226
+ return 0;
227
+ }
@@ -0,0 +1,34 @@
1
+ import { apiBaseProblems } from "../api-base.js";
2
+ export { apiBaseProblems };
3
+ /**
4
+ * Where a build's content comes from, read from its environment.
5
+ *
6
+ * All build-time and deliberately not `PUBLIC_`: a `PUBLIC_` variable is
7
+ * inlined into the browser bundle, and the website key reads a tenant's
8
+ * unpublished content.
9
+ */
10
+ export type Env = Record<string, string | undefined>;
11
+ export interface ApiSettings {
12
+ readonly base: string;
13
+ /**
14
+ * The website whose content this is.
15
+ *
16
+ * Content belongs to the site that publishes it, not to the project that
17
+ * authored it: a project can publish more than one website and a build
18
+ * serves one hostname. So a build, like the importer, names the website.
19
+ */
20
+ readonly website: string;
21
+ /** The website key, which opens the site's export. */
22
+ readonly key: string | undefined;
23
+ /** Fail the build rather than quietly shipping what git happens to hold. */
24
+ readonly required: boolean;
25
+ }
26
+ /** A variable with nothing but spaces in it is an unset one. */
27
+ export declare function blank(value: string | undefined): string | undefined;
28
+ /** Whether a build is allowed to fall back to git. */
29
+ export declare function contentRequired(env?: Env): boolean;
30
+ /**
31
+ * Build-time settings, or `undefined` when none are configured, in which
32
+ * case a build reads only what is in git.
33
+ */
34
+ export declare function settings(env?: Env): ApiSettings | undefined;
@@ -0,0 +1,66 @@
1
+ import { apiBaseProblems } from "../api-base.js";
2
+ import { trimTrailingSlashes } from "../trim-slashes.js";
3
+ export { apiBaseProblems };
4
+ /** A variable with nothing but spaces in it is an unset one. */
5
+ export function blank(value) {
6
+ const trimmed = value?.trim();
7
+ return trimmed === undefined || trimmed.length === 0 ? undefined : trimmed;
8
+ }
9
+ /**
10
+ * The first of these names that is set, whichever the deployment used.
11
+ *
12
+ * `OPENHI_WEBSITE_ID` is the canonical spelling because the value is an id
13
+ * and not a name; `OPENHI_WEBSITE` keeps working so no existing deployment
14
+ * breaks. Two names for one value that a build resolved differently from
15
+ * its importer once shipped a site with no content under a green build.
16
+ */
17
+ function first(env, ...names) {
18
+ for (const name of names) {
19
+ const value = blank(env[name]);
20
+ if (value !== undefined)
21
+ return value;
22
+ }
23
+ return undefined;
24
+ }
25
+ /** Whether a build is allowed to fall back to git. */
26
+ export function contentRequired(env = process.env) {
27
+ // Read on its own, and not only off `ApiSettings`, because the case it
28
+ // has to cover is the one where there are no settings: a build whose
29
+ // variables are misspelled has nothing to put this flag on, and answering
30
+ // "no API configured" with an info log is how stale content ships.
31
+ return env.OPENHI_CONTENT_REQUIRED === "1";
32
+ }
33
+ /**
34
+ * Build-time settings, or `undefined` when none are configured, in which
35
+ * case a build reads only what is in git.
36
+ */
37
+ export function settings(env = process.env) {
38
+ const base = blank(env.OPENHI_API_BASE);
39
+ const website = first(env, "OPENHI_WEBSITE_ID", "OPENHI_WEBSITE");
40
+ if (website === undefined &&
41
+ first(env, "OPENHI_PROJECT_ID", "OPENHI_PROJECT")) {
42
+ // Read as "no API configured", this would quietly build from git.
43
+ throw new Error("OPENHI_PROJECT_ID is not read: content belongs to a website, so set " +
44
+ "OPENHI_WEBSITE_ID to the site this build is for.");
45
+ }
46
+ if (blank(env.OPENHI_TOKEN) !== undefined) {
47
+ // A signed-in session's token expires in about an hour and is a person's.
48
+ // Read as "no key", it would quietly build from git.
49
+ throw new Error("OPENHI_TOKEN is not read: a build uses a website key. Make one in the " +
50
+ "website's settings in Studio and set OPENHI_WEBSITE_KEY.");
51
+ }
52
+ if (base === undefined || website === undefined)
53
+ return undefined;
54
+ // The key is sent to this base on every build: a cleartext or malformed
55
+ // base must stop here, not leak the key.
56
+ const problems = apiBaseProblems(base);
57
+ if (problems.length > 0) {
58
+ throw new Error(`OPENHI_API_BASE cannot be used: ${problems.join("; ")}`);
59
+ }
60
+ return {
61
+ base: trimTrailingSlashes(base),
62
+ website,
63
+ key: blank(env.OPENHI_WEBSITE_KEY),
64
+ required: contentRequired(env),
65
+ };
66
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @openhi/sdk/node: filesystem-backed build and command-line operations.
3
+ * Node only; never import it from code that reaches a browser.
4
+ */
5
+ export * from "./env.js";
6
+ export * from "./media.js";
7
+ export * from "./read.js";
8
+ export { main as runCli } from "./cli/main.js";
9
+ export type { CliContext } from "./cli/context.js";
@@ -0,0 +1,8 @@
1
+ /**
2
+ * @openhi/sdk/node: filesystem-backed build and command-line operations.
3
+ * Node only; never import it from code that reaches a browser.
4
+ */
5
+ export * from "./env.js";
6
+ export * from "./media.js";
7
+ export * from "./read.js";
8
+ export { main as runCli } from "./cli/main.js";
@@ -0,0 +1,56 @@
1
+ import type { ApiSettings } from "./env.js";
2
+ import { type SiteRecord } from "./read.js";
3
+ /**
4
+ * A site's media, pulled into its build.
5
+ *
6
+ * OpenHI serves nothing publicly, media included: the build downloads what
7
+ * it renders and ships it in its own output, from the site's own host. A
8
+ * `ContentAsset` whose `url` is `ContentAsset/{id}/$content` has its bytes
9
+ * in OpenHI's private store; the website key asks for a short-lived URL
10
+ * for each (`GET /Website/{id}/assets/{assetId}`) and the file is fetched
11
+ * from that URL, never with the key. An asset whose `url` is a site path
12
+ * already lives in the site's own `public/` and is left alone.
13
+ */
14
+ export interface MediaOptions {
15
+ /**
16
+ * Where files are written, relative to the project root. The kit owns this
17
+ * directory and removes files in it that no content refers to.
18
+ * @default "public/openhi-media"
19
+ */
20
+ readonly dir?: string;
21
+ /** The URL path `dir` is served from. @default "/openhi-media" */
22
+ readonly publicPath?: string;
23
+ /** The project root. @default process.cwd() */
24
+ readonly root?: string;
25
+ /** Replaces the global `fetch`. */
26
+ readonly fetch?: typeof fetch;
27
+ /** Checked-in content whose asset references count as used, beside the records'. */
28
+ readonly references?: readonly unknown[];
29
+ }
30
+ export interface MediaFile {
31
+ readonly id: string;
32
+ /** Where the site serves it: `/openhi-media/{id}.png`. */
33
+ readonly path: string;
34
+ readonly contentType: string;
35
+ /** Whether the bytes were fetched on this build, or were already there. */
36
+ readonly fetched: boolean;
37
+ }
38
+ /** The id of an asset whose file OpenHI stores, from its `url`. */
39
+ export declare function storedAssetId(url: unknown): string | undefined;
40
+ export declare function extensionFor(contentType: string): string;
41
+ /**
42
+ * Download every stored active asset the export lists.
43
+ *
44
+ * A file already in place is kept when its size is the asset's: the bytes
45
+ * of an asset change only when its record is replaced, so a build that
46
+ * caches the directory fetches nothing it has.
47
+ */
48
+ export declare function pullMedia(api: ApiSettings, records: readonly SiteRecord[], options?: MediaOptions): Promise<MediaFile[]>;
49
+ /**
50
+ * Point content at the files that were pulled.
51
+ *
52
+ * A string that is exactly `ContentAsset/{id}` or `ContentAsset/{id}/$content`
53
+ * becomes the path the site serves that file from, wherever it sits in the
54
+ * value. Nothing else is touched.
55
+ */
56
+ export declare function localiseMedia<T>(value: T, media: ReadonlyMap<string, MediaFile>): T;