@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,318 @@
1
+ import { readdir, readFile } from "node:fs/promises";
2
+ import { join, relative, resolve, sep } from "node:path";
3
+ import { entryFromContent, } from "../content/content-type.js";
4
+ import { pageFromResource } from "../content/page.js";
5
+ import { paymentOf } from "../forms/index.js";
6
+ import { sectionFromResource } from "../content/section.js";
7
+ import { formSchema, pageSchema, sectionSchema, } from "../content/types.js";
8
+ import { contentRequired, settings } from "../node/env.js";
9
+ import { localiseMedia, pullMedia, } from "../node/media.js";
10
+ import { contentEntries, forgetSiteRecords, ofType, readSite, } from "../node/read.js";
11
+ /** Every JSON file under `dir`, with the id Astro's own glob loader would give it. */
12
+ async function gitEntries(dir) {
13
+ const names = [];
14
+ const walk = async (at) => {
15
+ let children;
16
+ try {
17
+ children = await readdir(at, { withFileTypes: true });
18
+ }
19
+ catch {
20
+ return;
21
+ }
22
+ for (const child of children.sort((a, b) => a.name.localeCompare(b.name))) {
23
+ const path = join(at, child.name);
24
+ if (child.isDirectory())
25
+ await walk(path);
26
+ else if (child.name.endsWith(".json"))
27
+ names.push(path);
28
+ }
29
+ };
30
+ await walk(dir);
31
+ return Promise.all(names.map(async (path) => ({
32
+ id: relative(dir, path)
33
+ .split(sep)
34
+ .join("/")
35
+ .replace(/\.json$/, ""),
36
+ data: JSON.parse(await readFile(path, "utf8")),
37
+ })));
38
+ }
39
+ let session;
40
+ /** Testing seam: the site and its media are read once per process and a test needs a clean slate. */
41
+ export function forgetSite() {
42
+ session = undefined;
43
+ forgetSiteRecords();
44
+ }
45
+ /** The record types that are collections of entries; the rest (Theme, Website) are the site's own. */
46
+ const COLLECTION_TYPES = new Set(["Page", "Section", "Form", "Content"]);
47
+ /**
48
+ * What the build renders: drafts and retired collection entries are not
49
+ * published by default. A Theme or Website is always counted, since its
50
+ * logo, favicon and share image are what the pruning must not remove.
51
+ */
52
+ function published(records, options) {
53
+ return records.filter((record) => options.includeInactive === true ||
54
+ !COLLECTION_TYPES.has(record.resourceType) ||
55
+ record.status === "active");
56
+ }
57
+ function openSession(api, options, gitDir) {
58
+ const key = `${api.base}|${api.website}`;
59
+ if (session?.key !== key) {
60
+ session = {
61
+ key,
62
+ value: (async () => {
63
+ const records = await readSite(api);
64
+ // Checked-in content may cite an asset too (`pull` writes
65
+ // `ContentAsset/{id}`); the whole content tree counts, so pruning
66
+ // never removes a file that git content renders.
67
+ const root = resolve(options.root ?? process.cwd());
68
+ const cited = (await Promise.all([...new Set([resolve(root, "src/content"), gitDir])].map(gitEntries))).flatMap((entries) => entries.map((entry) => entry.data));
69
+ const pulled = options.media === false
70
+ ? []
71
+ : await pullMedia(api, published(records, options), {
72
+ ...(options.root !== undefined && { root: options.root }),
73
+ ...options.media,
74
+ references: cited,
75
+ });
76
+ return {
77
+ records,
78
+ media: new Map(pulled.map((file) => [file.id, file])),
79
+ };
80
+ })(),
81
+ };
82
+ }
83
+ return session.value;
84
+ }
85
+ /**
86
+ * One collection, git first and OpenHI over the top.
87
+ *
88
+ * The collections differ only in what they ask for and how a record maps
89
+ * to the local shape; the ordering, the offline behaviour, the
90
+ * required-content rule and the logging are the same for all of them, and
91
+ * were worth writing once.
92
+ */
93
+ function openhiCollection(options) {
94
+ const env = options.loader.env ?? process.env;
95
+ const dir = resolve(options.loader.root ?? process.cwd(), options.dir);
96
+ return {
97
+ name: options.name,
98
+ load: async (context) => {
99
+ // Start clean: an entry cached by an earlier build that OpenHI no
100
+ // longer serves must not outlive the record.
101
+ context.store.clear?.();
102
+ // Git first, always. The site builds with no API reachable and no
103
+ // credentials, which is what keeps a deploy from depending on one.
104
+ // A checked-in file may cite `ContentAsset/{id}` (that is what `pull`
105
+ // writes), so it is stored again, localised, once the media is known.
106
+ const fromGit = await gitEntries(dir);
107
+ const storeGit = async (media) => {
108
+ for (const entry of fromGit) {
109
+ // A pulled draft or retired record is not published: git builds
110
+ // skip it as the API path does, unless the site asks for it.
111
+ const status = entry.data.status;
112
+ if (options.loader.includeInactive !== true &&
113
+ status !== undefined &&
114
+ status !== "active") {
115
+ continue;
116
+ }
117
+ const prepared = options.fromGit?.(entry.data) ?? entry.data;
118
+ const data = await context.parseData({
119
+ id: entry.id,
120
+ data: localiseMedia(prepared, media),
121
+ });
122
+ context.store.set({ id: entry.id, data });
123
+ }
124
+ };
125
+ await storeGit(new Map());
126
+ const api = settings(env);
127
+ if (api === undefined) {
128
+ if (contentRequired(env)) {
129
+ throw new Error("OpenHI content is required, but OPENHI_API_BASE and " +
130
+ "OPENHI_WEBSITE_ID are not both set.");
131
+ }
132
+ context.logger.info(`OPENHI_API_BASE and OPENHI_WEBSITE_ID unset — building from ${options.dir}`);
133
+ return;
134
+ }
135
+ let resources;
136
+ let withheld;
137
+ let media;
138
+ try {
139
+ const site = await openSession(api, options.loader, dir);
140
+ const everything = options.select(site.records);
141
+ const live = (resource) => options.loader.includeInactive === true ||
142
+ resource.status === "active";
143
+ resources = everything.filter(live);
144
+ withheld = everything.filter((resource) => !live(resource));
145
+ media = site.media;
146
+ }
147
+ catch (caught) {
148
+ const why = caught instanceof Error ? caught.message : String(caught);
149
+ // The next collection should try again rather than share a failure
150
+ // that may have been this one's alone.
151
+ session = undefined;
152
+ forgetSiteRecords();
153
+ if (api.required) {
154
+ // A production build asked for the API and did not get it.
155
+ // Serving whatever git happens to hold would publish stale
156
+ // content under a green build.
157
+ throw new Error(`OpenHI content is required and could not be read: ${why}`);
158
+ }
159
+ context.logger.warn(`Could not read ${options.name} from OpenHI (${why}) — building from ${options.dir}`);
160
+ return;
161
+ }
162
+ if (media.size > 0)
163
+ await storeGit(media);
164
+ // A record Studio drafted or retired is not published, and git's copy
165
+ // of the same id must not be published in its place.
166
+ for (const resource of withheld) {
167
+ context.store.delete(options.idOf(options.map(resource)));
168
+ }
169
+ for (const resource of resources) {
170
+ const local = localiseMedia(options.map(resource), media);
171
+ options.after?.(local, context);
172
+ const id = options.idOf(local);
173
+ const data = await context.parseData({ id, data: local });
174
+ context.store.set({ id, data });
175
+ }
176
+ context.logger.info(`Loaded ${resources.length} ${options.name} record(s) from OpenHI`);
177
+ },
178
+ };
179
+ }
180
+ export function openhiPages(options = {}) {
181
+ const known = options.blocks === undefined
182
+ ? undefined
183
+ : new Set([
184
+ ...Object.keys(options.blocks.standard),
185
+ ...options.blocks.blocks.map((block) => block.code),
186
+ ]);
187
+ return openhiCollection({
188
+ name: "openhi-pages",
189
+ dir: options.dir ?? "src/content/pages",
190
+ loader: options,
191
+ select: (records) => ofType(records, "Page"),
192
+ map: (resource) => {
193
+ const page = pageFromResource(resource);
194
+ return (options.transform?.(page) ?? page);
195
+ },
196
+ idOf: (page) => page.slug,
197
+ after: (page, context) => {
198
+ if (known === undefined)
199
+ return;
200
+ for (const section of page.layout) {
201
+ if (!known.has(section.component)) {
202
+ // Rendered by the site's fallback rather than dropped, but worth
203
+ // saying: a block type exists that this build cannot draw.
204
+ context.logger.warn(`${page.permalink}: no component for block "${section.component}"`);
205
+ }
206
+ }
207
+ },
208
+ });
209
+ }
210
+ export function openhiSections(options = {}) {
211
+ return openhiCollection({
212
+ name: "openhi-sections",
213
+ dir: options.dir ?? "src/content/sections",
214
+ loader: options,
215
+ select: (records) => ofType(records, "Section"),
216
+ map: (resource) => sectionFromResource(resource),
217
+ idOf: (section) => section.slug,
218
+ });
219
+ }
220
+ /**
221
+ * A form as a built page may carry it. A page's data is serialised into
222
+ * HTML a visitor can read, so the form's `integration` (recipients,
223
+ * connection refs, preview recipients) is reduced to the `payment` the
224
+ * client needs and the rest is dropped.
225
+ */
226
+ function publicForm(form) {
227
+ const { integration, ...rest } = form;
228
+ const payment = paymentOf({ integration });
229
+ return {
230
+ ...rest,
231
+ ...(payment !== undefined && { payment }),
232
+ };
233
+ }
234
+ /**
235
+ * The site's forms, by name. A form's `id` is the API's, which is what the
236
+ * site posts submissions to; built from git alone it has none.
237
+ */
238
+ export function openhiForms(options = {}) {
239
+ return openhiCollection({
240
+ name: "openhi-forms",
241
+ dir: options.dir ?? "src/content/forms",
242
+ loader: options,
243
+ select: (records) => ofType(records, "Form"),
244
+ map: (resource) => publicForm(resource),
245
+ fromGit: publicForm,
246
+ idOf: (form) => form.name,
247
+ });
248
+ }
249
+ /**
250
+ * A tenant-defined content type (`Content` of one `ContentDefinition`).
251
+ * Narrowed to the one definition rather than every entry the site has:
252
+ * `Content` is one resourceType covering all of them.
253
+ */
254
+ export function openhiContent(options) {
255
+ return openhiCollection({
256
+ name: `openhi-content:${options.definition}`,
257
+ dir: options.dir,
258
+ loader: options,
259
+ select: (records) => contentEntries(records, options.definition),
260
+ map: (resource) => {
261
+ const entry = entryFromContent(resource);
262
+ return (options.map?.(entry) ?? entry);
263
+ },
264
+ idOf: options.idOf,
265
+ });
266
+ }
267
+ /**
268
+ * The collections a site's `src/content.config.ts` exports, from one read
269
+ * of the site's export:
270
+ *
271
+ * ```ts
272
+ * import { openhiCollections } from "@openhi/sdk/astro";
273
+ * import blocks from "../openhi.blocks";
274
+ * export const collections = openhiCollections({ blocks, pages: { schema: pageSchema } });
275
+ * ```
276
+ *
277
+ * The site's own Zod schemas validate the content; the kit does not own the
278
+ * content model.
279
+ */
280
+ export function openhiCollections(options = {}) {
281
+ const shared = {
282
+ ...(options.root !== undefined && { root: options.root }),
283
+ ...(options.media !== undefined && { media: options.media }),
284
+ ...(options.includeInactive !== undefined && {
285
+ includeInactive: options.includeInactive,
286
+ }),
287
+ ...(options.env !== undefined && { env: options.env }),
288
+ };
289
+ return {
290
+ pages: {
291
+ loader: openhiPages({
292
+ ...shared,
293
+ ...(options.blocks !== undefined && { blocks: options.blocks }),
294
+ ...(options.pages?.dir !== undefined && { dir: options.pages.dir }),
295
+ ...(options.pages?.transform !== undefined && {
296
+ transform: options.pages.transform,
297
+ }),
298
+ }),
299
+ schema: options.pages?.schema ?? pageSchema,
300
+ },
301
+ sections: {
302
+ loader: openhiSections({
303
+ ...shared,
304
+ ...(options.sections?.dir !== undefined && {
305
+ dir: options.sections.dir,
306
+ }),
307
+ }),
308
+ schema: options.sections?.schema ?? sectionSchema,
309
+ },
310
+ forms: {
311
+ loader: openhiForms({
312
+ ...shared,
313
+ ...(options.forms?.dir !== undefined && { dir: options.forms.dir }),
314
+ }),
315
+ schema: options.forms?.schema ?? formSchema,
316
+ },
317
+ };
318
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * A site's images as `ContentAsset` records.
3
+ *
4
+ * A `ContentAsset` carries a `url`, and these files are already served from
5
+ * `public/` by the site itself, so the record points at where the bytes
6
+ * already are. Nothing is uploaded and nothing moves — an import that
7
+ * copied them would create a second copy of every image with no way to say
8
+ * which one a page meant.
9
+ *
10
+ * Not FHIR `Media`: that is the clinical resource, belonging to a patient
11
+ * and carrying `subject` and `bodySite`. A photograph on a marketing page
12
+ * is about nobody.
13
+ */
14
+ export interface OpenhiAsset {
15
+ readonly resourceType: "ContentAsset";
16
+ readonly id?: string;
17
+ readonly status: string;
18
+ readonly title: string;
19
+ readonly contentType: string;
20
+ readonly url: string;
21
+ readonly size?: number;
22
+ readonly width?: number;
23
+ readonly height?: number;
24
+ readonly altText?: string;
25
+ readonly website?: {
26
+ readonly reference?: string;
27
+ readonly type?: string;
28
+ };
29
+ }
30
+ export declare function mediaTypeFor(path: string): string | undefined;
31
+ /**
32
+ * Every site-relative image path the content refers to.
33
+ *
34
+ * Read out of the content rather than off the filesystem: `public/` holds
35
+ * favicons, social images and whatever else a site accumulates, and an
36
+ * asset library full of files nothing references is worse than none. What
37
+ * the content points at is what an author would expect to find.
38
+ */
39
+ export declare function assetPathsIn(value: unknown, found?: Set<string>): Set<string>;
40
+ /** A readable title from a file path: `/images/hero-banner.png`. */
41
+ export declare function titleFor(path: string): string;
42
+ export interface Dimensions {
43
+ readonly width: number;
44
+ readonly height: number;
45
+ }
46
+ /**
47
+ * A PNG's or JPEG's dimensions, read from its header.
48
+ *
49
+ * Worth the thirty lines: `ContentAsset` carries `width` and `height` so a
50
+ * page can reserve the space before the image arrives, and an importer that
51
+ * left them empty would put that job back on every author.
52
+ */
53
+ export declare function dimensionsOf(bytes: Uint8Array): Dimensions | undefined;
54
+ /**
55
+ * The media type a file's first bytes say it is, when they say one.
56
+ *
57
+ * The extension is what somebody named the file; the bytes are what it
58
+ * is, and the two disagree more than you would think: images saved under the wrong extension are
59
+ * common, a JPEG named `.png` for one. OpenHI checks the first bytes
60
+ * of every file against the type its record declares and refuses a
61
+ * mismatch, so the record has to declare what the bytes are.
62
+ */
63
+ export declare function mediaTypeOf(bytes: Uint8Array): string | undefined;
64
+ /** One image as the `ContentAsset` OpenHI stores. */
65
+ export declare function assetFromFile(input: {
66
+ readonly path: string;
67
+ readonly size: number;
68
+ readonly bytes?: Uint8Array;
69
+ }): OpenhiAsset;
@@ -0,0 +1,151 @@
1
+ /**
2
+ * A site's images as `ContentAsset` records.
3
+ *
4
+ * A `ContentAsset` carries a `url`, and these files are already served from
5
+ * `public/` by the site itself, so the record points at where the bytes
6
+ * already are. Nothing is uploaded and nothing moves — an import that
7
+ * copied them would create a second copy of every image with no way to say
8
+ * which one a page meant.
9
+ *
10
+ * Not FHIR `Media`: that is the clinical resource, belonging to a patient
11
+ * and carrying `subject` and `bodySite`. A photograph on a marketing page
12
+ * is about nobody.
13
+ */
14
+ /** IANA media types, by extension. */
15
+ const MEDIA_TYPES = {
16
+ ".png": "image/png",
17
+ ".jpg": "image/jpeg",
18
+ ".jpeg": "image/jpeg",
19
+ ".gif": "image/gif",
20
+ ".webp": "image/webp",
21
+ ".svg": "image/svg+xml",
22
+ ".avif": "image/avif",
23
+ };
24
+ export function mediaTypeFor(path) {
25
+ const dot = path.lastIndexOf(".");
26
+ return dot === -1 ? undefined : MEDIA_TYPES[path.slice(dot).toLowerCase()];
27
+ }
28
+ /**
29
+ * Every site-relative image path the content refers to.
30
+ *
31
+ * Read out of the content rather than off the filesystem: `public/` holds
32
+ * favicons, social images and whatever else a site accumulates, and an
33
+ * asset library full of files nothing references is worse than none. What
34
+ * the content points at is what an author would expect to find.
35
+ */
36
+ export function assetPathsIn(value, found = new Set()) {
37
+ if (typeof value === "string") {
38
+ if (value.startsWith("/") && mediaTypeFor(value) !== undefined) {
39
+ found.add(value);
40
+ }
41
+ return found;
42
+ }
43
+ if (Array.isArray(value)) {
44
+ for (const member of value)
45
+ assetPathsIn(member, found);
46
+ return found;
47
+ }
48
+ if (typeof value === "object" && value !== null) {
49
+ for (const member of Object.values(value))
50
+ assetPathsIn(member, found);
51
+ }
52
+ return found;
53
+ }
54
+ /** A readable title from a file path: `/images/hero-banner.png`. */
55
+ export function titleFor(path) {
56
+ const base = path.split("/").pop() ?? path;
57
+ const dot = base.lastIndexOf(".");
58
+ const stem = dot === -1 ? base : base.slice(0, dot);
59
+ return stem
60
+ .split(/[-_]/)
61
+ .filter((word) => word.length > 0)
62
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
63
+ .join(" ");
64
+ }
65
+ /**
66
+ * A PNG's or JPEG's dimensions, read from its header.
67
+ *
68
+ * Worth the thirty lines: `ContentAsset` carries `width` and `height` so a
69
+ * page can reserve the space before the image arrives, and an importer that
70
+ * left them empty would put that job back on every author.
71
+ */
72
+ export function dimensionsOf(bytes) {
73
+ if (isPng(bytes)) {
74
+ // IHDR is the first chunk, and its width and height are the two 32-bit
75
+ // big-endian numbers at byte 16.
76
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
77
+ return { width: view.getUint32(16), height: view.getUint32(20) };
78
+ }
79
+ if (bytes[0] === 0xff && bytes[1] === 0xd8)
80
+ return jpegDimensions(bytes);
81
+ return undefined;
82
+ }
83
+ const PNG_MAGIC = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
84
+ function isPng(bytes) {
85
+ return PNG_MAGIC.every((byte, index) => bytes[index] === byte);
86
+ }
87
+ /**
88
+ * The media type a file's first bytes say it is, when they say one.
89
+ *
90
+ * The extension is what somebody named the file; the bytes are what it
91
+ * is, and the two disagree more than you would think: images saved under the wrong extension are
92
+ * common, a JPEG named `.png` for one. OpenHI checks the first bytes
93
+ * of every file against the type its record declares and refuses a
94
+ * mismatch, so the record has to declare what the bytes are.
95
+ */
96
+ export function mediaTypeOf(bytes) {
97
+ if (isPng(bytes))
98
+ return "image/png";
99
+ if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {
100
+ return "image/jpeg";
101
+ }
102
+ const ascii = (from, to) => String.fromCharCode(...bytes.subarray(from, to));
103
+ if (ascii(0, 6) === "GIF87a" || ascii(0, 6) === "GIF89a")
104
+ return "image/gif";
105
+ if (ascii(0, 4) === "RIFF" && ascii(8, 12) === "WEBP")
106
+ return "image/webp";
107
+ return undefined;
108
+ }
109
+ function jpegDimensions(bytes) {
110
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
111
+ let offset = 2;
112
+ while (offset + 9 < bytes.length) {
113
+ if (bytes[offset] !== 0xff) {
114
+ offset += 1;
115
+ continue;
116
+ }
117
+ const marker = bytes[offset + 1];
118
+ // Every SOFn carries the size except the four that are not frame
119
+ // headers at all (DHT, JPG, DAC, and the restart markers).
120
+ const isFrameHeader = marker >= 0xc0 &&
121
+ marker <= 0xcf &&
122
+ marker !== 0xc4 &&
123
+ marker !== 0xc8 &&
124
+ marker !== 0xcc;
125
+ if (isFrameHeader) {
126
+ return {
127
+ height: view.getUint16(offset + 5),
128
+ width: view.getUint16(offset + 7),
129
+ };
130
+ }
131
+ offset += 2 + view.getUint16(offset + 2);
132
+ }
133
+ return undefined;
134
+ }
135
+ /** One image as the `ContentAsset` OpenHI stores. */
136
+ export function assetFromFile(input) {
137
+ // The bytes over the name, when the bytes are in hand.
138
+ const contentType = (input.bytes === undefined ? undefined : mediaTypeOf(input.bytes)) ??
139
+ mediaTypeFor(input.path) ??
140
+ "application/octet-stream";
141
+ const dimensions = input.bytes === undefined ? undefined : dimensionsOf(input.bytes);
142
+ return {
143
+ resourceType: "ContentAsset",
144
+ status: "active",
145
+ title: titleFor(input.path),
146
+ contentType,
147
+ url: input.path,
148
+ size: input.size,
149
+ ...(dimensions !== undefined && dimensions),
150
+ };
151
+ }
@@ -0,0 +1,11 @@
1
+ import type { BlockSet } from "./declare.js";
2
+ /**
3
+ * The site's catalogue, as the `CodeSystem` to publish.
4
+ *
5
+ * Every block is `global` in scope and belongs on a `page`: they are
6
+ * website sections, and offering one on an app's screen would be the wrong
7
+ * thing rather than a layout mistake.
8
+ */
9
+ export declare function blockCodeSystem(set: BlockSet): Record<string, unknown>;
10
+ /** The codes a catalogue (as published, or as committed) has concepts for. */
11
+ export declare function catalogueCodes(system: unknown): string[];
@@ -0,0 +1,71 @@
1
+ /**
2
+ * The property codes a block concept carries.
3
+ *
4
+ * These are OpenHI's, not the site's: they are what Studio's reader looks
5
+ * for, so they are spelled the way the published `CodeSystem/block-type`
6
+ * spells them. `prop` rather than `property` included.
7
+ */
8
+ const BLOCK_PROPERTY = {
9
+ SCOPE: "scope",
10
+ FIELD: "field",
11
+ PROPERTY: "prop",
12
+ SURFACE: "surface",
13
+ SIZE: "size",
14
+ LIST: "list",
15
+ ENTRY: "entry",
16
+ };
17
+ /**
18
+ * The site's catalogue, as the `CodeSystem` to publish.
19
+ *
20
+ * Every block is `global` in scope and belongs on a `page`: they are
21
+ * website sections, and offering one on an app's screen would be the wrong
22
+ * thing rather than a layout mistake.
23
+ */
24
+ export function blockCodeSystem(set) {
25
+ return {
26
+ resourceType: "CodeSystem",
27
+ url: set.system,
28
+ name: set.name,
29
+ title: set.title,
30
+ description: set.description,
31
+ status: "active",
32
+ content: "complete",
33
+ caseSensitive: true,
34
+ version: set.version,
35
+ count: set.blocks.length,
36
+ concept: set.blocks.map((block) => ({
37
+ code: block.code,
38
+ display: block.display,
39
+ definition: block.definition,
40
+ property: [
41
+ { code: BLOCK_PROPERTY.SCOPE, valueCode: "global" },
42
+ ...block.fields.map((field) => ({
43
+ code: BLOCK_PROPERTY.FIELD,
44
+ valueCode: field,
45
+ })),
46
+ ...block.props.map((name) => ({
47
+ code: BLOCK_PROPERTY.PROPERTY,
48
+ valueString: name,
49
+ })),
50
+ ...block.lists.flatMap((list) => [
51
+ { code: BLOCK_PROPERTY.LIST, valueString: list.name },
52
+ ...list.fields.map((field) => ({
53
+ code: BLOCK_PROPERTY.ENTRY,
54
+ valueString: `${list.name}.${field}`,
55
+ })),
56
+ ]),
57
+ { code: BLOCK_PROPERTY.SURFACE, valueCode: "page" },
58
+ {
59
+ code: BLOCK_PROPERTY.SIZE,
60
+ valueString: `${block.size[0]}x${block.size[1]}`,
61
+ },
62
+ ],
63
+ })),
64
+ };
65
+ }
66
+ /** The codes a catalogue (as published, or as committed) has concepts for. */
67
+ export function catalogueCodes(system) {
68
+ const concepts = system?.concept ??
69
+ [];
70
+ return concepts.flatMap((concept) => typeof concept.code === "string" ? [concept.code] : []);
71
+ }