@backmatter/core 0.0.41 → 0.0.43

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@backmatter/core",
3
- "version": "0.0.41",
3
+ "version": "0.0.43",
4
4
  "description": "Experimental Backmatter SDK. APIs will break. Not ready for production.",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -0,0 +1,124 @@
1
+ // packages/core/src/block-gallery.ts
2
+ // The block gallery: a page on the host, reachable only in draft mode, that
3
+ // renders blocks with their examples so Studio's block library can show the
4
+ // real components. Studio builds the URL and posts messages; the host reads
5
+ // both. This file is the contract between them.
6
+
7
+ /** Path the host's catch-all serves the gallery on. */
8
+ export const BLOCK_GALLERY_PATH = "/_backmatter/blocks";
9
+
10
+ /** Studio → gallery: render the single block with these props. */
11
+ export const BLOCK_GALLERY_PROPS_MESSAGE = "backmatter:block-gallery-props";
12
+
13
+ /** Gallery → Studio: the editor asked to open one block example. */
14
+ export const BLOCK_GALLERY_OPEN_MESSAGE = "backmatter:block-gallery-open";
15
+
16
+ const MAX_BLOCKS = 100;
17
+ const BLOCK_NAME = /^[A-Z][A-Za-z0-9]*$/;
18
+
19
+ export type BlockGalleryQuery = {
20
+ /** Block names in display order. One name with `example` set is the single view. */
21
+ blocks: string[];
22
+ /** Index into the block's examples. Set only in the single view. */
23
+ example?: number;
24
+ /** Props that replace the example's, from Studio's editor. Single view only. */
25
+ props?: Record<string, unknown>;
26
+ };
27
+
28
+ export type BlockGalleryPropsMessage = {
29
+ type: typeof BLOCK_GALLERY_PROPS_MESSAGE;
30
+ props: Record<string, unknown>;
31
+ };
32
+
33
+ export type BlockGalleryOpenMessage = {
34
+ type: typeof BLOCK_GALLERY_OPEN_MESSAGE;
35
+ block: string;
36
+ example: number;
37
+ };
38
+
39
+ /** True for the gallery path, with or without a trailing slash. */
40
+ export function isBlockGalleryPath(pathname: string): boolean {
41
+ return pathname.replace(/\/+$/, "") === BLOCK_GALLERY_PATH;
42
+ }
43
+
44
+ export function isBlockGallerySegments(segments: readonly string[] | undefined): boolean {
45
+ return isBlockGalleryPath(`/${(segments ?? []).join("/")}`);
46
+ }
47
+
48
+ function toBase64Url(text: string): string {
49
+ const bytes = new TextEncoder().encode(text);
50
+ let binary = "";
51
+ for (const byte of bytes) binary += String.fromCharCode(byte);
52
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
53
+ }
54
+
55
+ function fromBase64Url(value: string): string {
56
+ const base64 = value.replace(/-/g, "+").replace(/_/g, "/");
57
+ const binary = atob(base64 + "=".repeat((4 - (base64.length % 4)) % 4));
58
+ return new TextDecoder().decode(Uint8Array.from(binary, (c) => c.charCodeAt(0)));
59
+ }
60
+
61
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
62
+ return !!value && typeof value === "object" && !Array.isArray(value);
63
+ }
64
+
65
+ /** Gallery path and query for these blocks. */
66
+ export function blockGalleryPath(query: BlockGalleryQuery): string {
67
+ const params = new URLSearchParams();
68
+ params.set("blocks", query.blocks.join(","));
69
+ if (query.example !== undefined) params.set("example", String(query.example));
70
+ if (query.props) params.set("props", toBase64Url(JSON.stringify(query.props)));
71
+ return `${BLOCK_GALLERY_PATH}?${params}`;
72
+ }
73
+
74
+ type SearchInput = URLSearchParams | Record<string, string | string[] | undefined>;
75
+
76
+ function first(search: SearchInput, key: string): string | undefined {
77
+ if (search instanceof URLSearchParams) return search.get(key) ?? undefined;
78
+ const raw = search[key];
79
+ return Array.isArray(raw) ? raw[0] : raw;
80
+ }
81
+
82
+ /** The query a gallery request asks for. Unknown or malformed parts are dropped. */
83
+ export function readBlockGalleryQuery(search: SearchInput): BlockGalleryQuery {
84
+ const blocks = [
85
+ ...new Set(
86
+ (first(search, "blocks") ?? "")
87
+ .split(",")
88
+ .map((name) => name.trim())
89
+ .filter((name) => BLOCK_NAME.test(name)),
90
+ ),
91
+ ].slice(0, MAX_BLOCKS);
92
+ const query: BlockGalleryQuery = { blocks };
93
+ if (blocks.length !== 1) return query;
94
+ const example = Number(first(search, "example"));
95
+ if (Number.isInteger(example) && example >= 0) query.example = example;
96
+ const raw = first(search, "props");
97
+ if (raw && query.example !== undefined) {
98
+ try {
99
+ const props = JSON.parse(fromBase64Url(raw)) as unknown;
100
+ if (isPlainObject(props)) query.props = props;
101
+ } catch {
102
+ // A broken props value shows the example as declared.
103
+ }
104
+ }
105
+ return query;
106
+ }
107
+
108
+ export function isBlockGalleryPropsMessage(value: unknown): value is BlockGalleryPropsMessage {
109
+ return (
110
+ isPlainObject(value) && value.type === BLOCK_GALLERY_PROPS_MESSAGE && isPlainObject(value.props)
111
+ );
112
+ }
113
+
114
+ export function isBlockGalleryOpenMessage(value: unknown): value is BlockGalleryOpenMessage {
115
+ return (
116
+ isPlainObject(value) &&
117
+ value.type === BLOCK_GALLERY_OPEN_MESSAGE &&
118
+ typeof value.block === "string" &&
119
+ BLOCK_NAME.test(value.block) &&
120
+ typeof value.example === "number" &&
121
+ Number.isInteger(value.example) &&
122
+ value.example >= 0
123
+ );
124
+ }
package/src/block.ts CHANGED
@@ -33,6 +33,17 @@ export type BlockMeta = {
33
33
  * without one get a wireframe drawn from their fields.
34
34
  */
35
35
  preview?: string;
36
+ /**
37
+ * Named props that show the block in Studio's block library, one render per
38
+ * example. Never content: nothing reads them on a published page.
39
+ */
40
+ examples?: readonly BlockExample[];
41
+ };
42
+
43
+ /** One named set of props a block shows itself with in the block library. */
44
+ export type BlockExample = {
45
+ name: string;
46
+ props: Record<string, unknown>;
36
47
  };
37
48
 
38
49
  export type BlockDef<C = unknown> = BlockMeta & {
@@ -83,9 +94,63 @@ function readBlockMeta(value: Record<string, unknown>, strict: boolean): BlockMe
83
94
  bad('block.preview must be an https:// URL or a site path like "/block-previews/hero.png"');
84
95
  } else meta.preview = value.preview.trim();
85
96
  }
97
+ if (value.examples !== undefined) {
98
+ const examples = readBlockExamples(value.examples, strict);
99
+ if (examples === null) bad("block.examples must be a list of { name, props } with a name and an object of props");
100
+ else if (examples.length > 0) meta.examples = examples;
101
+ }
86
102
  return meta;
87
103
  }
88
104
 
105
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
106
+ return !!value && typeof value === "object" && !Array.isArray(value);
107
+ }
108
+
109
+ /** The examples in `value` that have a name and an object of props; the rest are dropped. */
110
+ export function validBlockExamples(value: unknown): BlockExample[] {
111
+ return readBlockExamples(value, false) ?? [];
112
+ }
113
+
114
+ /** Valid examples; null when `strict` and any entry is bad (otherwise bad ones are dropped). */
115
+ function readBlockExamples(value: unknown, strict: boolean): BlockExample[] | null {
116
+ if (!Array.isArray(value)) return strict ? null : [];
117
+ const out: BlockExample[] = [];
118
+ for (const entry of value) {
119
+ const name = isPlainObject(entry) && typeof entry.name === "string" ? entry.name.trim() : "";
120
+ if (!name || !isPlainObject(entry) || !isPlainObject(entry.props)) {
121
+ if (strict) return null;
122
+ continue;
123
+ }
124
+ out.push({ name, props: { ...entry.props } });
125
+ }
126
+ return out;
127
+ }
128
+
129
+ function humanize(name: string): string {
130
+ const words = name
131
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
132
+ .replace(/[_-]+/g, " ")
133
+ .trim()
134
+ .toLowerCase();
135
+ return words ? words[0]!.toUpperCase() + words.slice(1) : name;
136
+ }
137
+
138
+ /**
139
+ * Stand-in props for a block without examples: a label for text, the first
140
+ * option, the minimum, false. Richer fields stay unset.
141
+ */
142
+ export function placeholderBlockProps(
143
+ fields: Record<string, { kind: string; options?: readonly string[]; min?: number }>,
144
+ ): Record<string, unknown> {
145
+ const props: Record<string, unknown> = {};
146
+ for (const [name, field] of Object.entries(fields)) {
147
+ if (field.kind === "text") props[name] = field.options?.[0] ?? humanize(name);
148
+ else if (field.kind === "number") props[name] = field.min ?? 0;
149
+ else if (field.kind === "boolean") props[name] = false;
150
+ }
151
+ return props;
152
+ }
153
+
89
154
  /** An http(s) URL or a root-relative path (not protocol-relative). */
90
155
  export function isBlockPreviewSrc(value: string): boolean {
91
156
  if (value.startsWith("/")) return !value.startsWith("//") && !/\s/.test(value);
package/src/index.ts CHANGED
@@ -62,6 +62,7 @@ export type {
62
62
  BlockSnapshot,
63
63
  InferBlockProps,
64
64
  BlockMeta,
65
+ BlockExample,
65
66
  } from "./block";
66
67
  export type { BlockGroupInfo, BlockPlacement, BuiltinBlockGroup } from "./block-groups";
67
68
  export { BLOCK_GROUPS, blockGroupInfo, blockLayoutWarnings, blockRules } from "./block-groups";
@@ -70,6 +71,7 @@ export {
70
71
  serializeBlock,
71
72
  parseBlockSnapshot,
72
73
  isBlockPreviewSrc,
74
+ placeholderBlockProps,
73
75
  RESERVED_BLOCK_PROP,
74
76
  } from "./block";
75
77
 
@@ -233,3 +235,17 @@ export {
233
235
  linkSide,
234
236
  splitInternalLink,
235
237
  } from "./link-address";
238
+ export {
239
+ BLOCK_GALLERY_PATH,
240
+ BLOCK_GALLERY_PROPS_MESSAGE,
241
+ BLOCK_GALLERY_OPEN_MESSAGE,
242
+ blockGalleryPath,
243
+ readBlockGalleryQuery,
244
+ isBlockGalleryPath,
245
+ isBlockGallerySegments,
246
+ isBlockGalleryPropsMessage,
247
+ isBlockGalleryOpenMessage,
248
+ type BlockGalleryQuery,
249
+ type BlockGalleryPropsMessage,
250
+ type BlockGalleryOpenMessage,
251
+ } from "./block-gallery";
@@ -4,7 +4,7 @@
4
4
  // SaaS never loads customer React, Next, or the host checkout.
5
5
  import { runInNewContext } from "node:vm";
6
6
  import { field } from "../fields";
7
- import { defineBlock, type BlockDef } from "../block";
7
+ import { defineBlock, validBlockExamples, type BlockDef } from "../block";
8
8
  import { compileLocalModules, pickBindings, withLocalModules, type LocalModules } from "./local-modules";
9
9
 
10
10
  const SOURCE_EXT = /\.(ts|tsx|js|jsx|mjs)$/;
@@ -143,6 +143,17 @@ export type BlockSourceOptions = {
143
143
  files?: ReadonlyMap<string, string>;
144
144
  };
145
145
 
146
+ /**
147
+ * Examples only dress the block library. When a site helper that builds them
148
+ * comes back stubbed or wrong in the sandbox, drop the bad ones, not the block.
149
+ */
150
+ function defineBlockKeepingValidExamples(def: Record<string, unknown>): BlockDef {
151
+ if (def.examples === undefined) return defineBlock(def as Parameters<typeof defineBlock>[0]);
152
+ const { examples, ...rest } = def;
153
+ const valid = validBlockExamples(examples);
154
+ return defineBlock((valid.length > 0 ? { ...rest, examples: valid } : rest) as Parameters<typeof defineBlock>[0]);
155
+ }
156
+
146
157
  function transpile(source: string): string {
147
158
  const transpiler = new Bun.Transpiler({ loader: "tsx", target: "node" });
148
159
  return transpiler.transformSync(source);
@@ -171,7 +182,7 @@ export function evalBlockSource(
171
182
  jsxDEV: (...args: unknown[]) => null;
172
183
  };
173
184
  const el = () => null;
174
- sandbox.defineBlock = defineBlock;
185
+ sandbox.defineBlock = defineBlockKeepingValidExamples as typeof defineBlock;
175
186
  sandbox.field = field;
176
187
  sandbox.React = { createElement: el, Fragment: "Fragment" };
177
188
  sandbox.jsx = el;
@@ -3,6 +3,7 @@
3
3
  // files (`../lib/block-fields`). The block sandbox runs those files too, under
4
4
  // the same rules, so their exports carry real values instead of stubs. A file
5
5
  // that is missing, breaks a rule, or throws falls back to stubs for its names.
6
+ // A `.json` import (content a site reuses for block examples) is plain data.
6
7
 
7
8
  const SOURCE_EXTS = [".ts", ".tsx", ".js", ".jsx", ".mjs"];
8
9
  const INDEX_FILES = ["/index.ts", "/index.tsx", "/index.js"];
@@ -115,7 +116,9 @@ function compileModule(repoPath: string, ctx: CompileContext): number | null {
115
116
  // A cycle, or too many files: the importer gets stubs for this one.
116
117
  if (ctx.inProgress.has(repoPath) || ctx.indexes.size >= MAX_MODULES) return null;
117
118
  const source = ctx.files.get(repoPath);
118
- if (source === undefined || ctx.isForbidden(source)) return null;
119
+ if (source === undefined) return null;
120
+ if (repoPath.endsWith(".json")) return compileJson(repoPath, source, ctx);
121
+ if (ctx.isForbidden(source)) return null;
119
122
 
120
123
  let js: string;
121
124
  try {
@@ -151,6 +154,25 @@ function compileModule(repoPath: string, ctx: CompileContext): number | null {
151
154
  return index;
152
155
  }
153
156
 
157
+ /**
158
+ * A JSON file is data: its value is the default export, and an object's
159
+ * top-level keys are named exports, as bundlers do. Invalid JSON gets stubs.
160
+ */
161
+ function compileJson(repoPath: string, source: string, ctx: CompileContext): number | null {
162
+ let value: unknown;
163
+ try {
164
+ value = JSON.parse(source);
165
+ } catch {
166
+ return null;
167
+ }
168
+ const index = ctx.indexes.size;
169
+ ctx.indexes.set(repoPath, index);
170
+ ctx.chunks.push(
171
+ `__mods[${index}] = (function (d) { var m = d && typeof d === "object" && !Array.isArray(d) ? Object.assign({}, d) : {}; m["default"] = d; return m; })(${JSON.stringify(value)});`,
172
+ );
173
+ return index;
174
+ }
175
+
154
176
  /** Strip `export` keywords and list [exported name, local expression] pairs. */
155
177
  function collectExports(js: string): { body: string; names: Array<[string, string]> } {
156
178
  const names: Array<[string, string]> = [];