@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.
- package/LICENSE +19 -0
- package/README.md +205 -1
- package/astro/OpenhiPreview.astro +59 -0
- package/lib/api-base.d.ts +2 -0
- package/lib/api-base.js +22 -0
- package/lib/astro/index.d.ts +8 -0
- package/lib/astro/index.js +8 -0
- package/lib/astro/loaders.d.ts +131 -0
- package/lib/astro/loaders.js +318 -0
- package/lib/content/asset.d.ts +69 -0
- package/lib/content/asset.js +151 -0
- package/lib/content/blocks/catalogue.d.ts +11 -0
- package/lib/content/blocks/catalogue.js +71 -0
- package/lib/content/blocks/declare.d.ts +143 -0
- package/lib/content/blocks/declare.js +210 -0
- package/lib/content/blocks/index.d.ts +2 -0
- package/lib/content/blocks/index.js +2 -0
- package/lib/content/content-type.d.ts +52 -0
- package/lib/content/content-type.js +97 -0
- package/lib/content/import-plan.d.ts +56 -0
- package/lib/content/import-plan.js +71 -0
- package/lib/content/index.d.ts +14 -0
- package/lib/content/index.js +14 -0
- package/lib/content/page.d.ts +91 -0
- package/lib/content/page.js +222 -0
- package/lib/content/sanitise-html.d.ts +36 -0
- package/lib/content/sanitise-html.js +92 -0
- package/lib/content/section.d.ts +60 -0
- package/lib/content/section.js +59 -0
- package/lib/content/shapes.d.ts +68 -0
- package/lib/content/shapes.js +9 -0
- package/lib/content/theme.d.ts +25 -0
- package/lib/content/theme.js +54 -0
- package/lib/content/types.d.ts +142 -0
- package/lib/content/types.js +121 -0
- package/lib/errors.d.ts +25 -0
- package/lib/errors.js +25 -0
- package/lib/forms/index.d.ts +107 -0
- package/lib/forms/index.js +201 -0
- package/lib/index.d.ts +10 -0
- package/lib/index.js +9 -0
- package/lib/node/bin.d.ts +2 -0
- package/lib/node/bin.js +14 -0
- package/lib/node/cli/api.d.ts +24 -0
- package/lib/node/cli/api.js +62 -0
- package/lib/node/cli/check.d.ts +26 -0
- package/lib/node/cli/check.js +265 -0
- package/lib/node/cli/context.d.ts +37 -0
- package/lib/node/cli/context.js +55 -0
- package/lib/node/cli/env-check.d.ts +4 -0
- package/lib/node/cli/env-check.js +47 -0
- package/lib/node/cli/init.d.ts +2 -0
- package/lib/node/cli/init.js +171 -0
- package/lib/node/cli/load-blocks.d.ts +15 -0
- package/lib/node/cli/load-blocks.js +109 -0
- package/lib/node/cli/local-content.d.ts +47 -0
- package/lib/node/cli/local-content.js +126 -0
- package/lib/node/cli/main.d.ts +3 -0
- package/lib/node/cli/main.js +58 -0
- package/lib/node/cli/optional-tool.d.ts +8 -0
- package/lib/node/cli/optional-tool.js +26 -0
- package/lib/node/cli/pull.d.ts +2 -0
- package/lib/node/cli/pull.js +113 -0
- package/lib/node/cli/push.d.ts +6 -0
- package/lib/node/cli/push.js +227 -0
- package/lib/node/env.d.ts +34 -0
- package/lib/node/env.js +66 -0
- package/lib/node/index.d.ts +9 -0
- package/lib/node/index.js +8 -0
- package/lib/node/media.d.ts +56 -0
- package/lib/node/media.js +176 -0
- package/lib/node/read.d.ts +19 -0
- package/lib/node/read.js +55 -0
- package/lib/paging.d.ts +14 -0
- package/lib/paging.js +41 -0
- package/lib/preview/apply-draft.d.ts +42 -0
- package/lib/preview/apply-draft.js +185 -0
- package/lib/preview/index.d.ts +7 -0
- package/lib/preview/index.js +4 -0
- package/lib/preview/marks.d.ts +25 -0
- package/lib/preview/marks.js +17 -0
- package/lib/preview/runtime.d.ts +17 -0
- package/lib/preview/runtime.js +85 -0
- package/lib/preview/studio-origin.d.ts +3 -0
- package/lib/preview/studio-origin.js +38 -0
- package/lib/transport.d.ts +25 -0
- package/lib/transport.js +58 -0
- package/lib/trim-slashes.d.ts +4 -0
- package/lib/trim-slashes.js +14 -0
- package/package.json +124 -3
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync, } from "node:fs";
|
|
2
|
+
import { dirname, resolve } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { CliError, parseArgs } from "./context.js";
|
|
5
|
+
/**
|
|
6
|
+
* `openhi-site init`: add the SDK to an existing Astro site.
|
|
7
|
+
*
|
|
8
|
+
* Idempotent, and it never overwrites: a file that exists is left as it is
|
|
9
|
+
* and the step is reported as skipped, with what to add by hand when that
|
|
10
|
+
* matters. A site made in Studio from the standard template already has all
|
|
11
|
+
* of this; `init` is for sites that began elsewhere.
|
|
12
|
+
*/
|
|
13
|
+
const BLOCKS_STARTER = (system) => `import { defineBlocks } from "@openhi/sdk/content";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* This site's blocks: the component, its schema and its labels. The catalogue
|
|
17
|
+
* Studio edits is generated from this file (\`openhi-site push\`), so Studio and
|
|
18
|
+
* the site cannot disagree about which blocks exist.
|
|
19
|
+
*
|
|
20
|
+
* \`system\` is the URL the catalogue is published at. It is yours: change it
|
|
21
|
+
* once, before the first push, and leave it.
|
|
22
|
+
*/
|
|
23
|
+
export default defineBlocks({
|
|
24
|
+
system: "${system}",
|
|
25
|
+
blocks: [
|
|
26
|
+
// {
|
|
27
|
+
// code: "banner",
|
|
28
|
+
// display: "Banner",
|
|
29
|
+
// definition: "A full-width message with a call to action.",
|
|
30
|
+
// component: Banner,
|
|
31
|
+
// schema: z.object({ title: z.string(), content: z.string().optional() }),
|
|
32
|
+
// },
|
|
33
|
+
],
|
|
34
|
+
});
|
|
35
|
+
`;
|
|
36
|
+
const CONFIG_STARTER = `import { defineCollection } from "astro:content";
|
|
37
|
+
import { openhiCollections } from "@openhi/sdk/astro";
|
|
38
|
+
|
|
39
|
+
import blocks from "../openhi.blocks";
|
|
40
|
+
|
|
41
|
+
// Git first, then anything OpenHI serves laid over the top. With
|
|
42
|
+
// OPENHI_API_BASE and OPENHI_WEBSITE_ID unset this builds from src/content;
|
|
43
|
+
// OPENHI_CONTENT_REQUIRED=1 turns that fallback into a failure.
|
|
44
|
+
const { pages, sections, forms } = openhiCollections({ blocks });
|
|
45
|
+
|
|
46
|
+
export const collections = {
|
|
47
|
+
pages: defineCollection(pages),
|
|
48
|
+
sections: defineCollection(sections),
|
|
49
|
+
forms: defineCollection(forms),
|
|
50
|
+
};
|
|
51
|
+
`;
|
|
52
|
+
const ENV_EXAMPLE = `
|
|
53
|
+
# OpenHI (openhi-site). Build-time only; never PUBLIC_.
|
|
54
|
+
# Unset, the site builds from src/content.
|
|
55
|
+
OPENHI_API_BASE=
|
|
56
|
+
OPENHI_WEBSITE_ID=
|
|
57
|
+
# A website key from the website's settings in Studio (read-write to push).
|
|
58
|
+
OPENHI_WEBSITE_KEY=
|
|
59
|
+
# Production builds set this to 1, so a missing API fails instead of shipping git.
|
|
60
|
+
OPENHI_CONTENT_REQUIRED=
|
|
61
|
+
`;
|
|
62
|
+
const SCRIPTS = {
|
|
63
|
+
"openhi:push": "openhi-site push",
|
|
64
|
+
"openhi:pull": "openhi-site pull",
|
|
65
|
+
"openhi:check": "openhi-site check",
|
|
66
|
+
};
|
|
67
|
+
function kitVersion() {
|
|
68
|
+
try {
|
|
69
|
+
const own = JSON.parse(readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "package.json"), "utf8"));
|
|
70
|
+
return own.version ?? "latest";
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
return "latest";
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
export async function init(ctx, argv) {
|
|
77
|
+
const { flags } = parseArgs(argv, { valued: ["system"] });
|
|
78
|
+
const packagePath = resolve(ctx.cwd, "package.json");
|
|
79
|
+
if (!existsSync(packagePath)) {
|
|
80
|
+
throw new CliError("no package.json here: run `openhi-site init` in the site's directory");
|
|
81
|
+
}
|
|
82
|
+
const manifest = JSON.parse(readFileSync(packagePath, "utf8"));
|
|
83
|
+
if (manifest.dependencies?.astro === undefined &&
|
|
84
|
+
manifest.devDependencies?.astro === undefined) {
|
|
85
|
+
throw new CliError("this is not an Astro site: v1 of the SDK's site tooling is Astro only");
|
|
86
|
+
}
|
|
87
|
+
const done = [];
|
|
88
|
+
const skipped = [];
|
|
89
|
+
// package.json: the dependency and the scripts, keeping whatever is there.
|
|
90
|
+
const version = kitVersion();
|
|
91
|
+
let changed = false;
|
|
92
|
+
if (manifest.dependencies?.["@openhi/sdk"] === undefined &&
|
|
93
|
+
manifest.devDependencies?.["@openhi/sdk"] === undefined) {
|
|
94
|
+
manifest.dependencies = {
|
|
95
|
+
...manifest.dependencies,
|
|
96
|
+
"@openhi/sdk": version === "latest" ? "latest" : `^${version}`,
|
|
97
|
+
};
|
|
98
|
+
changed = true;
|
|
99
|
+
done.push("added @openhi/sdk to dependencies (install to fetch it)");
|
|
100
|
+
}
|
|
101
|
+
else
|
|
102
|
+
skipped.push("package.json already depends on @openhi/sdk");
|
|
103
|
+
for (const [name, command] of Object.entries(SCRIPTS)) {
|
|
104
|
+
if (manifest.scripts?.[name] === undefined) {
|
|
105
|
+
manifest.scripts = { ...manifest.scripts, [name]: command };
|
|
106
|
+
changed = true;
|
|
107
|
+
done.push(`added the ${name} script`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
if (changed)
|
|
111
|
+
writeFileSync(packagePath, `${JSON.stringify(manifest, null, 2)}\n`);
|
|
112
|
+
const write = (path, body, label) => {
|
|
113
|
+
const full = resolve(ctx.cwd, path);
|
|
114
|
+
if (existsSync(full)) {
|
|
115
|
+
skipped.push(`${path} already exists`);
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
mkdirSync(resolve(full, ".."), { recursive: true });
|
|
119
|
+
writeFileSync(full, body);
|
|
120
|
+
done.push(label);
|
|
121
|
+
};
|
|
122
|
+
const system = typeof flags.system === "string"
|
|
123
|
+
? flags.system
|
|
124
|
+
: "https://example.org/fhir/CodeSystem/block-type";
|
|
125
|
+
write("openhi.blocks.ts", BLOCKS_STARTER(system), "wrote openhi.blocks.ts");
|
|
126
|
+
const hasConfig = [
|
|
127
|
+
"src/content.config.ts",
|
|
128
|
+
"src/content/config.ts",
|
|
129
|
+
"src/content.config.mjs",
|
|
130
|
+
"src/content.config.js",
|
|
131
|
+
].some((path) => existsSync(resolve(ctx.cwd, path)));
|
|
132
|
+
if (hasConfig) {
|
|
133
|
+
skipped.push("a content config already exists: add the collections from `openhiCollections()` by hand (see the README)");
|
|
134
|
+
}
|
|
135
|
+
else {
|
|
136
|
+
write("src/content.config.ts", CONFIG_STARTER, "wrote src/content.config.ts");
|
|
137
|
+
}
|
|
138
|
+
for (const dir of ["pages", "sections", "forms"]) {
|
|
139
|
+
const full = resolve(ctx.cwd, "src/content", dir);
|
|
140
|
+
if (!existsSync(full)) {
|
|
141
|
+
mkdirSync(full, { recursive: true });
|
|
142
|
+
writeFileSync(resolve(full, ".gitkeep"), "");
|
|
143
|
+
done.push(`created src/content/${dir}`);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
const envPath = resolve(ctx.cwd, ".env.example");
|
|
147
|
+
if (!existsSync(envPath) ||
|
|
148
|
+
!readFileSync(envPath, "utf8").includes("OPENHI_API_BASE")) {
|
|
149
|
+
appendFileSync(envPath, existsSync(envPath) ? ENV_EXAMPLE : ENV_EXAMPLE.trimStart());
|
|
150
|
+
done.push("added the OPENHI_* settings to .env.example");
|
|
151
|
+
}
|
|
152
|
+
else
|
|
153
|
+
skipped.push(".env.example already lists the OPENHI_* settings");
|
|
154
|
+
const ignorePath = resolve(ctx.cwd, ".gitignore");
|
|
155
|
+
const ignore = existsSync(ignorePath) ? readFileSync(ignorePath, "utf8") : "";
|
|
156
|
+
if (!ignore.includes("public/openhi-media")) {
|
|
157
|
+
appendFileSync(ignorePath, `${ignore.length > 0 && !ignore.endsWith("\n") ? "\n" : ""}# Media pulled from OpenHI at build time\npublic/openhi-media/\n`);
|
|
158
|
+
done.push("ignored public/openhi-media/ (pulled at build time)");
|
|
159
|
+
}
|
|
160
|
+
for (const line of done)
|
|
161
|
+
ctx.out(`✓ ${line}`);
|
|
162
|
+
for (const line of skipped)
|
|
163
|
+
ctx.out(`· ${line}`);
|
|
164
|
+
ctx.out([
|
|
165
|
+
"",
|
|
166
|
+
"Two steps are yours:",
|
|
167
|
+
' 1. Add <OpenhiPreview /> to the layout\'s <head>: import OpenhiPreview from "@openhi/sdk/astro/OpenhiPreview.astro";',
|
|
168
|
+
" 2. Mark each block's markup with block(), field(), list() and entry() from @openhi/sdk/preview, then run `openhi-site check`.",
|
|
169
|
+
].join("\n"));
|
|
170
|
+
return 0;
|
|
171
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { type BlockSet } from "../../content/blocks/declare.js";
|
|
2
|
+
/** The file a site declares its blocks in, if it has one. */
|
|
3
|
+
export declare function blocksFile(root: string): string | undefined;
|
|
4
|
+
/**
|
|
5
|
+
* Read a site's `openhi.blocks.ts`.
|
|
6
|
+
*
|
|
7
|
+
* The file imports the site's components, which are `.astro` and `.tsx`
|
|
8
|
+
* files Node cannot load. It is bundled with those imports stubbed, since
|
|
9
|
+
* the CLI wants the declarations and never draws a block, and the SDK it
|
|
10
|
+
* imports is the one running (so there is one `defineBlocks`). The bundle
|
|
11
|
+
* is self-contained and goes to a scratch directory.
|
|
12
|
+
*/
|
|
13
|
+
export declare function loadBlocks(root: string, command: string): Promise<BlockSet | undefined>;
|
|
14
|
+
/** The committed, generated catalogue, if it is there. */
|
|
15
|
+
export declare function readCatalogueFile(path: string): unknown;
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { dirname, join, resolve } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { defineBlocks, } from "../../content/blocks/declare.js";
|
|
8
|
+
import { CliError } from "./context.js";
|
|
9
|
+
import { loadOptional } from "./optional-tool.js";
|
|
10
|
+
const NAMES = [
|
|
11
|
+
"openhi.blocks.ts",
|
|
12
|
+
"openhi.blocks.mts",
|
|
13
|
+
"openhi.blocks.js",
|
|
14
|
+
"openhi.blocks.mjs",
|
|
15
|
+
];
|
|
16
|
+
/** The file a site declares its blocks in, if it has one. */
|
|
17
|
+
export function blocksFile(root) {
|
|
18
|
+
return NAMES.map((name) => resolve(root, name)).find((path) => existsSync(path));
|
|
19
|
+
}
|
|
20
|
+
/** The SDK's own module for an entry, whether this runs from `lib/` or from source. */
|
|
21
|
+
function sdkEntry(subpath) {
|
|
22
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
23
|
+
const root = resolve(here, "..", "..");
|
|
24
|
+
const dir = subpath === "" ? root : resolve(root, subpath);
|
|
25
|
+
const found = ["index.ts", "index.js"]
|
|
26
|
+
.map((name) => resolve(dir, name))
|
|
27
|
+
.find((path) => existsSync(path));
|
|
28
|
+
if (found === undefined)
|
|
29
|
+
throw new CliError(`cannot find the SDK's own entry point "${subpath}"`);
|
|
30
|
+
return found;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Read a site's `openhi.blocks.ts`.
|
|
34
|
+
*
|
|
35
|
+
* The file imports the site's components, which are `.astro` and `.tsx`
|
|
36
|
+
* files Node cannot load. It is bundled with those imports stubbed, since
|
|
37
|
+
* the CLI wants the declarations and never draws a block, and the SDK it
|
|
38
|
+
* imports is the one running (so there is one `defineBlocks`). The bundle
|
|
39
|
+
* is self-contained and goes to a scratch directory.
|
|
40
|
+
*/
|
|
41
|
+
export async function loadBlocks(root, command) {
|
|
42
|
+
const file = blocksFile(root);
|
|
43
|
+
if (file === undefined)
|
|
44
|
+
return undefined;
|
|
45
|
+
const { build } = await loadOptional("esbuild", command, () => import("esbuild"));
|
|
46
|
+
const scratch = mkdtempSync(join(tmpdir(), "openhi-site-"));
|
|
47
|
+
const out = join(scratch, "blocks.cjs");
|
|
48
|
+
try {
|
|
49
|
+
const result = await build({
|
|
50
|
+
entryPoints: [file],
|
|
51
|
+
outfile: out,
|
|
52
|
+
bundle: true,
|
|
53
|
+
platform: "node",
|
|
54
|
+
format: "cjs",
|
|
55
|
+
logLevel: "silent",
|
|
56
|
+
write: false,
|
|
57
|
+
absWorkingDir: root,
|
|
58
|
+
plugins: [
|
|
59
|
+
{
|
|
60
|
+
name: "openhi-site-stubs",
|
|
61
|
+
setup(b) {
|
|
62
|
+
b.onResolve({
|
|
63
|
+
filter: /^@openhi\/sdk(\/(content|forms|preview|astro|node))?$/,
|
|
64
|
+
}, (args) => ({
|
|
65
|
+
path: sdkEntry(args.path.slice("@openhi/sdk/".length)),
|
|
66
|
+
}));
|
|
67
|
+
b.onResolve({ filter: /^astro:/ }, (args) => ({
|
|
68
|
+
path: args.path,
|
|
69
|
+
namespace: "stub",
|
|
70
|
+
}));
|
|
71
|
+
b.onResolve({
|
|
72
|
+
filter: /\.(astro|tsx|jsx|svelte|vue|css|scss|sass|less|svg|png|jpe?g|gif|webp|avif|woff2?|mdx?)(\?.*)?$/,
|
|
73
|
+
}, (args) => ({ path: args.path, namespace: "stub" }));
|
|
74
|
+
b.onLoad({ filter: /.*/, namespace: "stub" }, () => ({
|
|
75
|
+
contents: "export default {};",
|
|
76
|
+
loader: "js",
|
|
77
|
+
}));
|
|
78
|
+
},
|
|
79
|
+
},
|
|
80
|
+
],
|
|
81
|
+
});
|
|
82
|
+
writeFileSync(out, result.outputFiles[0]?.text ?? "");
|
|
83
|
+
const loaded = createRequire(import.meta.url)(out);
|
|
84
|
+
const declared = (loaded.default ?? loaded.blocks);
|
|
85
|
+
if (declared === undefined ||
|
|
86
|
+
typeof declared !== "object" ||
|
|
87
|
+
!("blocks" in declared)) {
|
|
88
|
+
throw new CliError(`${file} must export defineBlocks({ system, blocks }) as its default export`);
|
|
89
|
+
}
|
|
90
|
+
return defineBlocks(declared);
|
|
91
|
+
}
|
|
92
|
+
catch (caught) {
|
|
93
|
+
if (caught instanceof CliError)
|
|
94
|
+
throw caught;
|
|
95
|
+
throw new CliError(`could not read ${file}: ${caught instanceof Error ? caught.message : String(caught)}`);
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
rmSync(scratch, { recursive: true, force: true });
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
/** The committed, generated catalogue, if it is there. */
|
|
102
|
+
export function readCatalogueFile(path) {
|
|
103
|
+
try {
|
|
104
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
return undefined;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { type OpenhiAsset } from "../../content/asset.js";
|
|
2
|
+
import { type OpenhiPage } from "../../content/page.js";
|
|
3
|
+
import { type OpenhiSection } from "../../content/section.js";
|
|
4
|
+
import { type FormData, type PageData, type SectionData } from "../../content/types.js";
|
|
5
|
+
import type { BlockSet } from "../../content/blocks/declare.js";
|
|
6
|
+
/**
|
|
7
|
+
* What is in a site's `src/content`, read the way the importer and `check`
|
|
8
|
+
* both need it. Validated with the kit's own permissive schemas: the site's
|
|
9
|
+
* stricter ones run in its build, and the CLI only needs a shape it can map.
|
|
10
|
+
*/
|
|
11
|
+
export declare const CONTENT_DIR = "src/content";
|
|
12
|
+
/**
|
|
13
|
+
* Every JSON file in a content directory, subfolders included (a page at
|
|
14
|
+
* `pages/blog/post.json` is as much a page as `pages/home.json`), parsed,
|
|
15
|
+
* in name order.
|
|
16
|
+
*/
|
|
17
|
+
export declare function readJsonDir(root: string, dir: string): Array<{
|
|
18
|
+
name: string;
|
|
19
|
+
raw: unknown;
|
|
20
|
+
}>;
|
|
21
|
+
export declare function localPageData(root: string): Array<{
|
|
22
|
+
name: string;
|
|
23
|
+
page: PageData;
|
|
24
|
+
}>;
|
|
25
|
+
export declare function localPages(root: string, blocks?: BlockSet): OpenhiPage[];
|
|
26
|
+
export declare function localSectionData(root: string): Array<{
|
|
27
|
+
name: string;
|
|
28
|
+
section: SectionData;
|
|
29
|
+
}>;
|
|
30
|
+
export declare function localSections(root: string): OpenhiSection[];
|
|
31
|
+
export declare function localForms(root: string): Array<FormData & {
|
|
32
|
+
readonly resourceType: "Form";
|
|
33
|
+
}>;
|
|
34
|
+
/** An asset record with its file, base64, which the import stores. */
|
|
35
|
+
export type AssetWithBytes = OpenhiAsset & {
|
|
36
|
+
readonly data: string;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* Every image the content points at, as a `ContentAsset`.
|
|
40
|
+
*
|
|
41
|
+
* Read out of the content rather than off the filesystem: `public/` holds
|
|
42
|
+
* favicons and social images and whatever else accumulates, and an asset
|
|
43
|
+
* library full of files nothing references is worse than none.
|
|
44
|
+
*/
|
|
45
|
+
export declare function localAssets(root: string, warn: (line: string) => void): AssetWithBytes[];
|
|
46
|
+
/** The site's theme, from `src/content/theme.json`, when it has one. */
|
|
47
|
+
export declare function localTheme(root: string): Record<string, unknown> | undefined;
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
2
|
+
import { relative, resolve, sep } from "node:path";
|
|
3
|
+
import { assetFromFile, assetPathsIn, mediaTypeFor, } from "../../content/asset.js";
|
|
4
|
+
import { resourceFromPage } from "../../content/page.js";
|
|
5
|
+
import { resourceFromSection, } from "../../content/section.js";
|
|
6
|
+
import { formSchema, pageSchema, sectionSchema, } from "../../content/types.js";
|
|
7
|
+
import { CliError } from "./context.js";
|
|
8
|
+
/**
|
|
9
|
+
* What is in a site's `src/content`, read the way the importer and `check`
|
|
10
|
+
* both need it. Validated with the kit's own permissive schemas: the site's
|
|
11
|
+
* stricter ones run in its build, and the CLI only needs a shape it can map.
|
|
12
|
+
*/
|
|
13
|
+
export const CONTENT_DIR = "src/content";
|
|
14
|
+
/** The JSON files under `dir`, as paths relative to it, in name order. */
|
|
15
|
+
function jsonFilesUnder(full, prefix = "") {
|
|
16
|
+
return readdirSync(full, { withFileTypes: true })
|
|
17
|
+
.sort((a, b) => a.name.localeCompare(b.name))
|
|
18
|
+
.flatMap((entry) => entry.isDirectory()
|
|
19
|
+
? jsonFilesUnder(resolve(full, entry.name), `${prefix}${entry.name}/`)
|
|
20
|
+
: entry.name.endsWith(".json")
|
|
21
|
+
? [`${prefix}${entry.name}`]
|
|
22
|
+
: []);
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Every JSON file in a content directory, subfolders included (a page at
|
|
26
|
+
* `pages/blog/post.json` is as much a page as `pages/home.json`), parsed,
|
|
27
|
+
* in name order.
|
|
28
|
+
*/
|
|
29
|
+
export function readJsonDir(root, dir) {
|
|
30
|
+
const full = resolve(root, CONTENT_DIR, dir);
|
|
31
|
+
if (!existsSync(full))
|
|
32
|
+
return [];
|
|
33
|
+
return jsonFilesUnder(full).map((name) => {
|
|
34
|
+
try {
|
|
35
|
+
return {
|
|
36
|
+
name,
|
|
37
|
+
raw: JSON.parse(readFileSync(resolve(full, name), "utf8")),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
catch (caught) {
|
|
41
|
+
throw new CliError(`${dir}/${name} is not valid JSON: ${caught.message}`);
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
function parsed(dir, name, result) {
|
|
46
|
+
if (result.success)
|
|
47
|
+
return result.data;
|
|
48
|
+
const first = result.error.issues[0];
|
|
49
|
+
throw new CliError(`${dir}/${name} is not valid: ${first?.message ?? "unknown"}${first?.path.length ? ` (at ${first.path.map(String).join(".")})` : ""}`);
|
|
50
|
+
}
|
|
51
|
+
export function localPageData(root) {
|
|
52
|
+
return readJsonDir(root, "pages").map(({ name, raw }) => ({
|
|
53
|
+
name,
|
|
54
|
+
page: parsed("pages", name, pageSchema.safeParse(raw)),
|
|
55
|
+
}));
|
|
56
|
+
}
|
|
57
|
+
export function localPages(root, blocks) {
|
|
58
|
+
const declared = blocks === undefined
|
|
59
|
+
? undefined
|
|
60
|
+
: {
|
|
61
|
+
system: blocks.system,
|
|
62
|
+
codes: new Set(blocks.blocks.map((block) => block.code)),
|
|
63
|
+
};
|
|
64
|
+
return localPageData(root).map(({ page }) => resourceFromPage(page, declared));
|
|
65
|
+
}
|
|
66
|
+
export function localSectionData(root) {
|
|
67
|
+
return readJsonDir(root, "sections").map(({ name, raw }) => ({
|
|
68
|
+
name,
|
|
69
|
+
section: parsed("sections", name, sectionSchema.safeParse(raw)),
|
|
70
|
+
}));
|
|
71
|
+
}
|
|
72
|
+
export function localSections(root) {
|
|
73
|
+
return localSectionData(root).map(({ section }) => resourceFromSection(section));
|
|
74
|
+
}
|
|
75
|
+
export function localForms(root) {
|
|
76
|
+
return readJsonDir(root, "forms").map(({ name, raw }) => parsed("forms", name, formSchema.safeParse(raw)));
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Every image the content points at, as a `ContentAsset`.
|
|
80
|
+
*
|
|
81
|
+
* Read out of the content rather than off the filesystem: `public/` holds
|
|
82
|
+
* favicons and social images and whatever else accumulates, and an asset
|
|
83
|
+
* library full of files nothing references is worse than none.
|
|
84
|
+
*/
|
|
85
|
+
export function localAssets(root, warn) {
|
|
86
|
+
const referenced = new Set();
|
|
87
|
+
for (const dir of ["pages", "sections"]) {
|
|
88
|
+
for (const { raw } of readJsonDir(root, dir))
|
|
89
|
+
assetPathsIn(raw, referenced);
|
|
90
|
+
}
|
|
91
|
+
return [...referenced].sort().flatMap((path) => {
|
|
92
|
+
const publicDir = resolve(root, "public");
|
|
93
|
+
const file = resolve(publicDir, `.${path}`);
|
|
94
|
+
const inside = relative(publicDir, file);
|
|
95
|
+
// A path in content is the author's, and is read from disk: it must
|
|
96
|
+
// stay inside public/.
|
|
97
|
+
if (inside.startsWith("..") || inside.split(sep).includes("..")) {
|
|
98
|
+
warn(` ! ${path} is outside public/, skipping`);
|
|
99
|
+
return [];
|
|
100
|
+
}
|
|
101
|
+
let size;
|
|
102
|
+
try {
|
|
103
|
+
size = statSync(file).size;
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
warn(` ! ${path} is referenced but not in public/, skipping`);
|
|
107
|
+
return [];
|
|
108
|
+
}
|
|
109
|
+
const bytes = readFileSync(file);
|
|
110
|
+
const asset = assetFromFile({ path, size, bytes: new Uint8Array(bytes) });
|
|
111
|
+
const named = mediaTypeFor(path);
|
|
112
|
+
if (named !== undefined && named !== asset.contentType) {
|
|
113
|
+
warn(` ! ${path} is a ${asset.contentType} file; stored as one`);
|
|
114
|
+
}
|
|
115
|
+
return [{ ...asset, data: bytes.toString("base64") }];
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
/** The site's theme, from `src/content/theme.json`, when it has one. */
|
|
119
|
+
export function localTheme(root) {
|
|
120
|
+
try {
|
|
121
|
+
return JSON.parse(readFileSync(resolve(root, CONTENT_DIR, "theme.json"), "utf8"));
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { check } from "./check.js";
|
|
2
|
+
import { CliError, UsageError } from "./context.js";
|
|
3
|
+
import { init } from "./init.js";
|
|
4
|
+
import { pull } from "./pull.js";
|
|
5
|
+
import { push } from "./push.js";
|
|
6
|
+
const USAGE = `openhi-site: the OpenHI SDK's site command line
|
|
7
|
+
|
|
8
|
+
Usage: openhi-site <command> [options]
|
|
9
|
+
|
|
10
|
+
Commands:
|
|
11
|
+
push [--dry-run] [--catalogue] Send src/content, media and the block catalogue to OpenHI
|
|
12
|
+
pull [--dry-run] Write Studio's content back into src/content (media is fetched by the build)
|
|
13
|
+
check [--dist <dir>] For CI: fail on a missing catalogue entry, preview mark,
|
|
14
|
+
form, or a wrong environment setting
|
|
15
|
+
init [--system <url>] Add the SDK to an existing Astro site
|
|
16
|
+
|
|
17
|
+
Environment:
|
|
18
|
+
OPENHI_API_BASE The API's origin. No default.
|
|
19
|
+
OPENHI_WEBSITE_ID The website this site publishes.
|
|
20
|
+
OPENHI_WEBSITE_KEY A website key (read-write to push).
|
|
21
|
+
OPENHI_CONTENT_REQUIRED=1 Fail the build instead of falling back to src/content.
|
|
22
|
+
`;
|
|
23
|
+
/** Run a command and return its exit code: 0 done, 1 failed, 2 misused. */
|
|
24
|
+
export async function main(argv, ctx) {
|
|
25
|
+
const [command, ...rest] = argv;
|
|
26
|
+
if (command === undefined ||
|
|
27
|
+
command === "--help" ||
|
|
28
|
+
command === "-h" ||
|
|
29
|
+
command === "help") {
|
|
30
|
+
ctx.out(USAGE);
|
|
31
|
+
return command === undefined ? 2 : 0;
|
|
32
|
+
}
|
|
33
|
+
const commands = {
|
|
34
|
+
push,
|
|
35
|
+
pull,
|
|
36
|
+
check,
|
|
37
|
+
init,
|
|
38
|
+
};
|
|
39
|
+
const run = commands[command];
|
|
40
|
+
if (run === undefined) {
|
|
41
|
+
ctx.err(`unknown command "${command}"\n\n${USAGE}`);
|
|
42
|
+
return 2;
|
|
43
|
+
}
|
|
44
|
+
try {
|
|
45
|
+
return await run(ctx, rest);
|
|
46
|
+
}
|
|
47
|
+
catch (caught) {
|
|
48
|
+
if (caught instanceof UsageError) {
|
|
49
|
+
ctx.err(`${command}: ${caught.message}\n\n${USAGE}`);
|
|
50
|
+
return 2;
|
|
51
|
+
}
|
|
52
|
+
if (caught instanceof CliError) {
|
|
53
|
+
ctx.err(`✗ ${caught.message}`);
|
|
54
|
+
return 1;
|
|
55
|
+
}
|
|
56
|
+
throw caught;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Load a tool the SDK does not install for you.
|
|
3
|
+
*
|
|
4
|
+
* esbuild and linkedom are optional peers: a site that never runs the command
|
|
5
|
+
* needing one never installs it, and nothing is downloaded behind its back.
|
|
6
|
+
* When the command does run, say what to install and why.
|
|
7
|
+
*/
|
|
8
|
+
export declare function loadOptional<T>(name: string, command: string, load: () => Promise<T>): Promise<T>;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { CliError } from "./context.js";
|
|
2
|
+
/**
|
|
3
|
+
* Load a tool the SDK does not install for you.
|
|
4
|
+
*
|
|
5
|
+
* esbuild and linkedom are optional peers: a site that never runs the command
|
|
6
|
+
* needing one never installs it, and nothing is downloaded behind its back.
|
|
7
|
+
* When the command does run, say what to install and why.
|
|
8
|
+
*/
|
|
9
|
+
export async function loadOptional(name, command, load) {
|
|
10
|
+
try {
|
|
11
|
+
return await load();
|
|
12
|
+
}
|
|
13
|
+
catch (caught) {
|
|
14
|
+
const code = caught?.code;
|
|
15
|
+
const message = caught instanceof Error ? caught.message : String(caught);
|
|
16
|
+
if (code === "ERR_MODULE_NOT_FOUND" ||
|
|
17
|
+
code === "MODULE_NOT_FOUND" ||
|
|
18
|
+
message.includes(`Cannot find package '${name}'`) ||
|
|
19
|
+
message.includes(`Cannot find module '${name}'`)) {
|
|
20
|
+
throw new CliError(`\`openhi-site ${command}\` needs ${name}, which is not installed. ` +
|
|
21
|
+
`Add it to the site's dev dependencies (for example \`npm install --save-dev ${name}\`) and run the command again. ` +
|
|
22
|
+
"The SDK never installs tools for you.");
|
|
23
|
+
}
|
|
24
|
+
throw caught;
|
|
25
|
+
}
|
|
26
|
+
}
|