@backmatter/core 0.0.32 → 0.0.34
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 +1 -1
- package/src/block.ts +10 -8
- package/src/color.ts +40 -0
- package/src/doc.ts +2 -0
- package/src/document-label.ts +24 -0
- package/src/fields.ts +264 -15
- package/src/index.ts +7 -1
- package/src/model.ts +11 -6
- package/src/node/cli.ts +10 -2
- package/src/node/create-backmatter.ts +15 -9
- package/src/node/eval-model.ts +109 -25
- package/src/node/generate.ts +14 -5
- package/src/node/index.ts +7 -1
- package/src/preview-channel.ts +44 -3
- package/src/query.ts +457 -78
- package/src/relation-match.ts +12 -0
- package/src/relation-problems.ts +189 -0
- package/src/schema-check.ts +199 -0
- package/src/sync-schema.ts +2 -0
- package/src/validate.ts +108 -21
- package/src/zod.ts +127 -10
package/src/node/eval-model.ts
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
// Sandbox-eval convention model and object files (GitHub import). The allowed
|
|
3
3
|
// surface is the same one `discoverModels` / `discoverObjects` run: `defineModel`,
|
|
4
4
|
// `defineObject`, and `field` from @backmatter/core or @backmatter/next, plus
|
|
5
|
-
// `import name from "../objects/<name>"
|
|
5
|
+
// `import name from "../objects/<name>"` and `import name from "./<model>"`.
|
|
6
|
+
// Never import() the customer checkout.
|
|
6
7
|
import { runInNewContext } from "node:vm";
|
|
7
8
|
import { defineModel, type ModelDef } from "../model";
|
|
8
9
|
import { defineObject, type ObjectDef } from "../object";
|
|
@@ -73,14 +74,26 @@ function stripAllowedImports(
|
|
|
73
74
|
return stripped;
|
|
74
75
|
}
|
|
75
76
|
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
77
|
+
type LocalImport = { local: string; stem: string };
|
|
78
|
+
|
|
79
|
+
/** `import name from "../objects/<file>"`. */
|
|
80
|
+
function takeObjectImports(source: string): { source: string; bindings: LocalImport[] } {
|
|
81
|
+
return takeLocalImports(
|
|
82
|
+
source,
|
|
83
|
+
/^\s*import\s+([A-Za-z_$][\w$]*)\s+from\s+["']\.\.\/objects\/([A-Za-z][A-Za-z0-9]*)(?:\.(?:ts|tsx|js|jsx|mjs))?["']\s*;?\s*$/gm,
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** `import name from "./<model>"` — another file in `models/`. */
|
|
88
|
+
function takeModelImports(source: string): { source: string; bindings: LocalImport[] } {
|
|
89
|
+
return takeLocalImports(
|
|
90
|
+
source,
|
|
91
|
+
/^\s*import\s+([A-Za-z_$][\w$]*)\s+from\s+["']\.\/([A-Za-z][A-Za-z0-9-]*)(?:\.(?:ts|tsx|js|jsx|mjs))?["']\s*;?\s*$/gm,
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function takeLocalImports(source: string, re: RegExp): { source: string; bindings: LocalImport[] } {
|
|
96
|
+
const bindings: LocalImport[] = [];
|
|
84
97
|
const next = source.replace(re, (_full, local: string, stem: string) => {
|
|
85
98
|
bindings.push({ local, stem });
|
|
86
99
|
return "";
|
|
@@ -88,6 +101,12 @@ function takeObjectImports(source: string): {
|
|
|
88
101
|
return { source: next, bindings };
|
|
89
102
|
}
|
|
90
103
|
|
|
104
|
+
function missingSiblingImport(err: unknown): string | null {
|
|
105
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
106
|
+
const match = message.match(/import "\.\/([^"]+)" was not found/);
|
|
107
|
+
return match?.[1] ?? null;
|
|
108
|
+
}
|
|
109
|
+
|
|
91
110
|
function assertNoForbidden(source: string, kind = "model"): void {
|
|
92
111
|
for (const { re, name } of FORBIDDEN) {
|
|
93
112
|
re.lastIndex = 0;
|
|
@@ -161,25 +180,33 @@ export function evalObjectSource(source: string, stem: string): ObjectDef {
|
|
|
161
180
|
/**
|
|
162
181
|
* Evaluate one convention model file. `stem` is the file name without extension
|
|
163
182
|
* and must equal `model.type`. `objects` supplies `import x from "../objects/<file>"`.
|
|
183
|
+
* `models` supplies `import x from "./<file>"`.
|
|
164
184
|
*/
|
|
165
185
|
export function evalModelSource(
|
|
166
186
|
source: string,
|
|
167
187
|
stem: string,
|
|
168
188
|
objects: Readonly<Record<string, ObjectDef>> = {},
|
|
189
|
+
models: Readonly<Record<string, ModelDef>> = {},
|
|
169
190
|
): ModelDef {
|
|
170
|
-
const
|
|
171
|
-
const
|
|
191
|
+
const takenObjects = takeObjectImports(source);
|
|
192
|
+
const takenModels = takeModelImports(takenObjects.source);
|
|
193
|
+
const body = rewriteDefaultExport(stripAllowedImports(takenModels.source));
|
|
172
194
|
assertNoForbidden(body);
|
|
173
195
|
const wrapped = `(function () {\n${body}\n})()`;
|
|
174
196
|
const js = transpile(wrapped);
|
|
175
197
|
const sandbox = Object.create(null) as Record<string, unknown>;
|
|
176
198
|
sandbox.defineModel = defineModel;
|
|
177
199
|
sandbox.field = field;
|
|
178
|
-
for (const binding of
|
|
200
|
+
for (const binding of takenObjects.bindings) {
|
|
179
201
|
const object = objects[binding.stem];
|
|
180
202
|
if (!object) throw new Error(`import "../objects/${binding.stem}" was not found`);
|
|
181
203
|
sandbox[binding.local] = object;
|
|
182
204
|
}
|
|
205
|
+
for (const binding of takenModels.bindings) {
|
|
206
|
+
const model = models[binding.stem];
|
|
207
|
+
if (!model) throw new Error(`import "./${binding.stem}" was not found`);
|
|
208
|
+
sandbox[binding.local] = model;
|
|
209
|
+
}
|
|
183
210
|
Object.freeze(sandbox);
|
|
184
211
|
|
|
185
212
|
let result: unknown;
|
|
@@ -204,6 +231,70 @@ export function evalModelSource(
|
|
|
204
231
|
return result;
|
|
205
232
|
}
|
|
206
233
|
|
|
234
|
+
/**
|
|
235
|
+
* Evaluate every flat model file. A file may import another model in the same
|
|
236
|
+
* folder; that dependency is evaluated first. One failure is returned, not thrown,
|
|
237
|
+
* so the caller can keep the files that did load.
|
|
238
|
+
*/
|
|
239
|
+
export function evalModelFiles(
|
|
240
|
+
files: Array<{ path: string; source: string }>,
|
|
241
|
+
objects: Readonly<Record<string, ObjectDef>> = {},
|
|
242
|
+
modelsDir = "models",
|
|
243
|
+
): {
|
|
244
|
+
models: ModelDef[];
|
|
245
|
+
failures: Array<{ path: string; stem: string; message: string; duplicate?: boolean }>;
|
|
246
|
+
} {
|
|
247
|
+
const models: ModelDef[] = [];
|
|
248
|
+
const failures: Array<{ path: string; stem: string; message: string; duplicate?: boolean }> = [];
|
|
249
|
+
const byStem = new Map<string, ModelDef>();
|
|
250
|
+
const types = new Set<string>();
|
|
251
|
+
const waiting = new Map(
|
|
252
|
+
files
|
|
253
|
+
.filter((file) => isModelSourcePath(file.path, modelsDir))
|
|
254
|
+
.sort((a, b) => a.path.localeCompare(b.path))
|
|
255
|
+
.map((file) => [stemOf(file.path), file] as const),
|
|
256
|
+
);
|
|
257
|
+
|
|
258
|
+
let progressed = true;
|
|
259
|
+
while (waiting.size > 0 && progressed) {
|
|
260
|
+
progressed = false;
|
|
261
|
+
for (const [stem, file] of [...waiting]) {
|
|
262
|
+
try {
|
|
263
|
+
const model = evalModelSource(file.source, stem, objects, Object.fromEntries(byStem));
|
|
264
|
+
if (types.has(model.type)) {
|
|
265
|
+
failures.push({
|
|
266
|
+
path: file.path,
|
|
267
|
+
stem,
|
|
268
|
+
message: `duplicate model type "${model.type}"`,
|
|
269
|
+
duplicate: true,
|
|
270
|
+
});
|
|
271
|
+
} else {
|
|
272
|
+
types.add(model.type);
|
|
273
|
+
byStem.set(stem, model);
|
|
274
|
+
models.push(model);
|
|
275
|
+
}
|
|
276
|
+
waiting.delete(stem);
|
|
277
|
+
progressed = true;
|
|
278
|
+
} catch (err) {
|
|
279
|
+
const missing = missingSiblingImport(err);
|
|
280
|
+
if (missing && waiting.has(missing)) continue;
|
|
281
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
282
|
+
failures.push({ path: file.path, stem, message });
|
|
283
|
+
waiting.delete(stem);
|
|
284
|
+
progressed = true;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
for (const [stem, file] of waiting) {
|
|
289
|
+
failures.push({
|
|
290
|
+
path: file.path,
|
|
291
|
+
stem,
|
|
292
|
+
message: `import "./${stem}" is part of a cycle`,
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
return { models, failures };
|
|
296
|
+
}
|
|
297
|
+
|
|
207
298
|
export function evalModelsFromTree(
|
|
208
299
|
files: Array<{ path: string; source: string }>,
|
|
209
300
|
modelsDir = "models",
|
|
@@ -213,19 +304,12 @@ export function evalModelsFromTree(
|
|
|
213
304
|
const stem = stemOf(file.path);
|
|
214
305
|
objects[stem] = evalObjectSource(file.source, stem);
|
|
215
306
|
}
|
|
216
|
-
const models
|
|
217
|
-
const
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
const stem = stemOf(file.path);
|
|
223
|
-
const model = evalModelSource(file.source, stem, objects);
|
|
224
|
-
if (types.has(model.type)) {
|
|
225
|
-
throw new Error(`duplicate model type "${model.type}" (${file.path})`);
|
|
226
|
-
}
|
|
227
|
-
types.add(model.type);
|
|
228
|
-
models.push(model);
|
|
307
|
+
const { models, failures } = evalModelFiles(files, objects, modelsDir);
|
|
308
|
+
const first = failures[0];
|
|
309
|
+
if (first) {
|
|
310
|
+
throw new Error(
|
|
311
|
+
first.duplicate ? `${first.message} (${first.path})` : first.message,
|
|
312
|
+
);
|
|
229
313
|
}
|
|
230
314
|
return models;
|
|
231
315
|
}
|
package/src/node/generate.ts
CHANGED
|
@@ -101,7 +101,7 @@ export function detectSdk(root: string): string {
|
|
|
101
101
|
return "@backmatter/core/node";
|
|
102
102
|
}
|
|
103
103
|
|
|
104
|
-
function renderCachedCmsClient(): string[] {
|
|
104
|
+
function renderCachedCmsClient(typeArgs: string): string[] {
|
|
105
105
|
return [
|
|
106
106
|
"const raw = createBackmatter({ ...config, models, sync: false });",
|
|
107
107
|
"",
|
|
@@ -136,7 +136,7 @@ function renderCachedCmsClient(): string[] {
|
|
|
136
136
|
" ...raw,",
|
|
137
137
|
" getDoc,",
|
|
138
138
|
" listDocs,",
|
|
139
|
-
` query: createQuery(models, { getDoc, listDocs }),`,
|
|
139
|
+
` query: createQuery${typeArgs}(models, { getDoc, listDocs }),`,
|
|
140
140
|
"};",
|
|
141
141
|
];
|
|
142
142
|
}
|
|
@@ -144,10 +144,13 @@ function renderCachedCmsClient(): string[] {
|
|
|
144
144
|
export function renderModelsBarrel(input: {
|
|
145
145
|
outDir: string;
|
|
146
146
|
models: ModelFile[];
|
|
147
|
+
blocks?: BlockFile[];
|
|
147
148
|
configFile: string | null;
|
|
148
149
|
sdk: string;
|
|
149
150
|
}): string {
|
|
150
151
|
const nextHost = input.sdk === "@backmatter/next";
|
|
152
|
+
const blocks = input.blocks ?? [];
|
|
153
|
+
const typeArgs = blocks.length > 0 ? "<typeof models, Blocks>" : "";
|
|
151
154
|
const lines = [GENERATED_HEADER, `import { createBackmatter } from "${input.sdk}";`];
|
|
152
155
|
if (nextHost) {
|
|
153
156
|
lines.push('import { contentCacheTags, createQuery, listCacheTags } from "@backmatter/core";');
|
|
@@ -162,15 +165,21 @@ export function renderModelsBarrel(input: {
|
|
|
162
165
|
for (const m of input.models) {
|
|
163
166
|
lines.push(`import ${m.importName} from "${importSpecifier(input.outDir, m.file)}";`);
|
|
164
167
|
}
|
|
168
|
+
for (const block of blocks) {
|
|
169
|
+
lines.push(`import type ${block.name} from "${importSpecifier(input.outDir, block.file)}";`);
|
|
170
|
+
}
|
|
165
171
|
lines.push("");
|
|
166
172
|
lines.push(`export const models = [${input.models.map((m) => m.importName).join(", ")}] as const;`);
|
|
167
173
|
lines.push("export type Models = typeof models;");
|
|
174
|
+
if (blocks.length > 0) {
|
|
175
|
+
lines.push(`type Blocks = readonly [${blocks.map((block) => `typeof ${block.name}`).join(", ")}];`);
|
|
176
|
+
}
|
|
168
177
|
lines.push("");
|
|
169
178
|
if (nextHost) {
|
|
170
|
-
lines.push(...renderCachedCmsClient());
|
|
179
|
+
lines.push(...renderCachedCmsClient(typeArgs));
|
|
171
180
|
} else {
|
|
172
181
|
lines.push("/** Typed content client: cms.query.{type}, cms.getDoc, cms.listDocs. */");
|
|
173
|
-
lines.push(
|
|
182
|
+
lines.push(`export const cms = createBackmatter${typeArgs}({ ...config, models });`);
|
|
174
183
|
}
|
|
175
184
|
return `${lines.join("\n")}\n`;
|
|
176
185
|
}
|
|
@@ -373,7 +382,7 @@ export function generate(options: GenerateOptions): GenerateResult {
|
|
|
373
382
|
const write = options.write ?? true;
|
|
374
383
|
|
|
375
384
|
const rendered: Record<(typeof REGISTRY_FILES)[number], string> = {
|
|
376
|
-
"index.ts": renderModelsBarrel({ outDir, models, configFile, sdk }),
|
|
385
|
+
"index.ts": renderModelsBarrel({ outDir, models, blocks, configFile, sdk }),
|
|
377
386
|
"blocks.ts": renderBlocksBarrel({ outDir, blocks }),
|
|
378
387
|
"block-fallbacks.ts": renderBlockFallbacksBarrel({ outDir, fallbacks }),
|
|
379
388
|
"mdx.ts": renderMdxBarrel({ outDir, mdx }),
|
package/src/node/index.ts
CHANGED
|
@@ -18,7 +18,13 @@ export {
|
|
|
18
18
|
toIdentifier,
|
|
19
19
|
} from "./discover";
|
|
20
20
|
export type { BlockFile, ModelFile } from "./discover";
|
|
21
|
-
export {
|
|
21
|
+
export {
|
|
22
|
+
evalModelFiles,
|
|
23
|
+
evalModelSource,
|
|
24
|
+
evalModelsFromTree,
|
|
25
|
+
evalObjectSource,
|
|
26
|
+
isModelSourcePath,
|
|
27
|
+
} from "./eval-model";
|
|
22
28
|
export {
|
|
23
29
|
evalBlockSource,
|
|
24
30
|
evalBlocksFromTree,
|
package/src/preview-channel.ts
CHANGED
|
@@ -59,11 +59,17 @@ export type PreviewPointMessage = Envelope & {
|
|
|
59
59
|
|
|
60
60
|
export type PreviewGrabMessage = Envelope & {
|
|
61
61
|
type: "backmatter:grab";
|
|
62
|
-
|
|
62
|
+
/** Null when the click is not inside a page block. */
|
|
63
|
+
blockId: string | null;
|
|
63
64
|
blockType: string | null;
|
|
64
65
|
blockIndex: number | null;
|
|
65
66
|
quote: string;
|
|
66
67
|
shift: boolean;
|
|
68
|
+
component?: string;
|
|
69
|
+
file?: string;
|
|
70
|
+
line?: number;
|
|
71
|
+
column?: number;
|
|
72
|
+
stack?: string[];
|
|
67
73
|
};
|
|
68
74
|
|
|
69
75
|
export type PreviewHighlightMessage = Envelope & {
|
|
@@ -119,6 +125,37 @@ function readEnvelope(value: Record<string, unknown>): Envelope | null {
|
|
|
119
125
|
return { v: PREVIEW_CHANNEL_VERSION, ref };
|
|
120
126
|
}
|
|
121
127
|
|
|
128
|
+
const GRAB_FILE = /^[\w./@+-]+\.(?:tsx|ts|jsx|js|mdx)$/;
|
|
129
|
+
|
|
130
|
+
function readGrabPlace(data: Record<string, unknown>): Pick<
|
|
131
|
+
PreviewGrabMessage,
|
|
132
|
+
"component" | "file" | "line" | "column" | "stack"
|
|
133
|
+
> {
|
|
134
|
+
const component =
|
|
135
|
+
typeof data.component === "string" && data.component.length > 0 && data.component.length <= 80
|
|
136
|
+
? data.component
|
|
137
|
+
: undefined;
|
|
138
|
+
const file =
|
|
139
|
+
typeof data.file === "string" && data.file.length <= 240 && GRAB_FILE.test(data.file) && !data.file.includes("..")
|
|
140
|
+
? data.file
|
|
141
|
+
: undefined;
|
|
142
|
+
const line = typeof data.line === "number" && Number.isInteger(data.line) && data.line > 0 ? data.line : undefined;
|
|
143
|
+
const column =
|
|
144
|
+
typeof data.column === "number" && Number.isInteger(data.column) && data.column > 0 ? data.column : undefined;
|
|
145
|
+
const stack = Array.isArray(data.stack)
|
|
146
|
+
? data.stack
|
|
147
|
+
.filter((item): item is string => typeof item === "string" && item.length > 0 && item.length <= 80)
|
|
148
|
+
.slice(0, 4)
|
|
149
|
+
: [];
|
|
150
|
+
return {
|
|
151
|
+
...(component ? { component } : {}),
|
|
152
|
+
...(file ? { file } : {}),
|
|
153
|
+
...(line ? { line } : {}),
|
|
154
|
+
...(column ? { column } : {}),
|
|
155
|
+
...(stack.length > 0 ? { stack } : {}),
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
122
159
|
/** Parse a channel payload. Legacy hotkey messages (no `v`) still parse. */
|
|
123
160
|
export function parsePreviewMessage(data: unknown): PreviewChannelMessage | null {
|
|
124
161
|
const hotkey = parsePreviewHotkey(data);
|
|
@@ -167,7 +204,8 @@ export function parsePreviewMessage(data: unknown): PreviewChannelMessage | null
|
|
|
167
204
|
return { type: "backmatter:point", ...envelope, on: data.on };
|
|
168
205
|
}
|
|
169
206
|
case "backmatter:grab": {
|
|
170
|
-
|
|
207
|
+
const blockId = data.blockId === null ? null : typeof data.blockId === "string" ? data.blockId : undefined;
|
|
208
|
+
if (blockId === undefined || blockId === "") return null;
|
|
171
209
|
if (data.blockType !== null && typeof data.blockType !== "string") return null;
|
|
172
210
|
if (
|
|
173
211
|
data.blockIndex !== null &&
|
|
@@ -176,14 +214,17 @@ export function parsePreviewMessage(data: unknown): PreviewChannelMessage | null
|
|
|
176
214
|
return null;
|
|
177
215
|
}
|
|
178
216
|
if (typeof data.quote !== "string" || typeof data.shift !== "boolean") return null;
|
|
217
|
+
const place = readGrabPlace(data);
|
|
218
|
+
if (blockId === null && !normalizePointerQuote(data.quote) && !place.component && !place.file) return null;
|
|
179
219
|
return {
|
|
180
220
|
type: "backmatter:grab",
|
|
181
221
|
...envelope,
|
|
182
|
-
blockId
|
|
222
|
+
blockId,
|
|
183
223
|
blockType: data.blockType,
|
|
184
224
|
blockIndex: data.blockIndex,
|
|
185
225
|
quote: normalizePointerQuote(data.quote),
|
|
186
226
|
shift: data.shift,
|
|
227
|
+
...place,
|
|
187
228
|
};
|
|
188
229
|
}
|
|
189
230
|
case "backmatter:highlight": {
|