@openpresentation/opf 0.9.0 → 0.10.1

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 (42) hide show
  1. package/README.md +7 -1
  2. package/dist/{catalogs-BnnkUX9O.d.ts → catalogs-DoVmvDr7.d.ts} +6 -6
  3. package/dist/catalogs.d.ts +2 -2
  4. package/dist/catalogs.js +1 -1
  5. package/dist/{chunk-GQSK3T7X.js → chunk-D3GQIREP.js} +13 -4
  6. package/dist/chunk-EWJNRHXA.js +595 -0
  7. package/dist/{chunk-3GPZMY2W.js → chunk-FHGJX5QK.js} +24 -12
  8. package/dist/{chunk-JA5W5TVA.js → chunk-PQJRDNA6.js} +624 -73
  9. package/dist/{chunk-OZULJBSG.js → chunk-RS5GZ5RW.js} +14 -0
  10. package/dist/{chunk-TWMRZ43O.js → chunk-TU7I3KSB.js} +59 -21
  11. package/dist/{chunk-ZGV6I23P.js → chunk-ZIL7MGZU.js} +50 -5
  12. package/dist/composition.d.ts +257 -10
  13. package/dist/composition.js +1 -1
  14. package/dist/docs.js +58 -10
  15. package/dist/examples.js +2284 -1417
  16. package/dist/index.d.ts +4 -3
  17. package/dist/index.js +7 -6
  18. package/dist/lint.d.ts +70 -0
  19. package/dist/lint.js +5 -0
  20. package/dist/pagination.d.ts +4 -0
  21. package/dist/pagination.js +5 -5
  22. package/dist/{schemas--QRVBhU1.d.ts → schemas-BYe5y8-i.d.ts} +1 -1
  23. package/dist/schemas.d.ts +1 -1
  24. package/dist/schemas.js +1 -1
  25. package/dist/spec/catalogs/layouts/extract/canonical.json +45 -21
  26. package/dist/spec/catalogs/layouts/index.json +10 -0
  27. package/dist/spec/catalogs/layouts/number-1x.json +1 -1
  28. package/dist/spec/catalogs/layouts/number-2x.json +2 -2
  29. package/dist/spec/catalogs/layouts/number-3x.json +3 -3
  30. package/dist/spec/catalogs/layouts/number-4x.json +4 -4
  31. package/dist/spec/catalogs/layouts/number-5x.json +5 -5
  32. package/dist/spec/catalogs/layouts/number-6x.json +6 -6
  33. package/dist/spec/catalogs/layouts/quote-1x.json +13 -0
  34. package/dist/spec/catalogs/layouts/timeline-1x.json +13 -0
  35. package/dist/spec/schemas/layout.schema.json +12 -3
  36. package/dist/spec/schemas/narrative.schema.json +1 -1
  37. package/dist/spec-files.d.ts +1 -1
  38. package/dist/spec-files.js +1 -1
  39. package/dist/types.d.ts +2 -2
  40. package/dist/validator.d.ts +2 -2
  41. package/dist/validator.js +4 -4
  42. package/package.json +11 -6
@@ -0,0 +1,595 @@
1
+ import { validatePresentation, validationDefinition, validateCatalogRecord } from './chunk-ZIL7MGZU.js';
2
+ import { schemas, schemaEntries } from './chunk-D3GQIREP.js';
3
+ import { catalogKinds, catalogEntries, catalogSchemaNames } from './chunk-TU7I3KSB.js';
4
+ import { parseTree, printParseErrorCode, getNodePath } from 'jsonc-parser';
5
+
6
+ var own = (value, key) => Object.hasOwn(value, key);
7
+ var object = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
8
+ var primitive = (value) => value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
9
+ var pointer = (parts2) => parts2.length ? "/" + parts2.map((part) => String(part).replaceAll("~", "~0").replaceAll("/", "~1")).join("/") : "";
10
+ function parts(path) {
11
+ if (path === "") return [];
12
+ if (!path.startsWith("/") || /~(?![01])/.test(path))
13
+ throw new TypeError(`Invalid lint contract JSON Pointer: ${path}`);
14
+ return path.slice(1).split("/").map((part) => part.replaceAll("~1", "/").replaceAll("~0", "~"));
15
+ }
16
+ function at(value, path) {
17
+ return parts(path).reduce(
18
+ (current, key) => object(current) || Array.isArray(current) ? own(current, key) ? current[key] : void 0 : void 0,
19
+ value
20
+ );
21
+ }
22
+ function optionsChecked(options) {
23
+ if (!object(options) || Object.keys(options).some((key) => !["catalogs", "contracts"].includes(key)))
24
+ throw new TypeError("Lint options accept only catalogs and contracts.");
25
+ if (options.catalogs !== void 0 && (!object(options.catalogs) || Object.entries(options.catalogs).some(
26
+ ([kind, records]) => !catalogKinds.includes(kind) || !Array.isArray(records)
27
+ )))
28
+ throw new TypeError(
29
+ "Lint catalogs must map known catalog kinds to arrays of loaded records."
30
+ );
31
+ if (options.contracts !== void 0 && !Array.isArray(options.contracts))
32
+ throw new TypeError("Lint contracts must be an array.");
33
+ for (const contract of options.contracts ?? []) {
34
+ if (!object(contract) || Object.keys(contract).some(
35
+ (key) => ![
36
+ "path",
37
+ "allowedValues",
38
+ "severity",
39
+ "message",
40
+ "documentation"
41
+ ].includes(key)
42
+ ) || typeof contract.path !== "string" || !Array.isArray(contract.allowedValues) || !contract.allowedValues.every(primitive) || contract.severity !== void 0 && (typeof contract.severity !== "string" || !["error", "warning", "info"].includes(contract.severity)) || contract.message !== void 0 && typeof contract.message !== "string" || contract.documentation !== void 0 && typeof contract.documentation !== "string")
43
+ throw new TypeError(
44
+ "Invalid lint contract: provide a path and primitive allowedValues, with optional severity, message and documentation."
45
+ );
46
+ parts(contract.path);
47
+ }
48
+ }
49
+ function report(diagnostics, schemaValid, syntax) {
50
+ const counts = { error: 0, warning: 0, info: 0 };
51
+ for (const diagnostic of diagnostics) counts[diagnostic.severity]++;
52
+ return {
53
+ valid: counts.error === 0,
54
+ schemaValid,
55
+ diagnostics,
56
+ counts,
57
+ checks: {
58
+ syntax,
59
+ schema: schemaValid === null ? "not-run" : "checked",
60
+ catalogReferences: schemaValid === null ? "not-run" : "local-context",
61
+ assetReferences: schemaValid === null ? "not-run" : "registry-only",
62
+ contracts: schemaValid === null ? "not-run" : "checked",
63
+ layout: "not-checked",
64
+ fonts: "not-checked",
65
+ nativeExport: "not-checked"
66
+ }
67
+ };
68
+ }
69
+ function schemaDiagnostic(issue, schemaName = "presentation", prefix = "", scope = "document") {
70
+ const path = prefix + (issue.path === "/" ? "" : issue.path) + (issue.keyword === "additionalProperties" && typeof issue.params.additionalProperty === "string" ? pointer([issue.params.additionalProperty]) : ""), entry = schemaEntries.find((entry2) => entry2.name === schemaName);
71
+ if (!entry) throw new TypeError(`Unknown schema ${schemaName}`);
72
+ const precise = validationDefinition(issue);
73
+ const definition = precise?.uri ?? (issue.keyword === "opf" ? "packages/javascript/src/validator.ts" : issue.schemaPath.startsWith("#") ? entry.schema.$id + issue.schemaPath : issue.schemaPath);
74
+ const lookup = [
75
+ "opf",
76
+ "schema",
77
+ precise?.schemaName ?? schemaName,
78
+ precise?.pointer ?? (issue.keyword !== "opf" && issue.schemaPath.startsWith("#") ? issue.schemaPath.slice(1) : "")
79
+ ];
80
+ let help = "Inspect this schema constraint and preserve unrelated content. Errors inside oneOf/anyOf branches may describe alternatives; retain the intended form.";
81
+ if (issue.keyword === "required")
82
+ help = `Add the required ${JSON.stringify(issue.params.missingProperty)} field in this object, using the intended schema form.`;
83
+ else if (issue.keyword === "additionalProperties")
84
+ help = `Review ${JSON.stringify(issue.params.additionalProperty)} against this object's schema. Preserve custom metadata in document.extensions where appropriate; do not delete authored content to clear this error.`;
85
+ else if (issue.keyword === "enum")
86
+ help = "Choose one of this schema branch\u2019s allowed values; inspect the other alternatives if the field uses another form.";
87
+ else if (issue.keyword === "opf")
88
+ help = "Resolve the reported structural conflict while preserving every content field. Preview the result after editing.";
89
+ const allowed = Array.isArray(issue.params.allowedValues) ? issue.params.allowedValues.filter(primitive) : [];
90
+ return {
91
+ ruleId: "opf/schema",
92
+ severity: "error",
93
+ path,
94
+ scope,
95
+ message: issue.message,
96
+ help,
97
+ definition,
98
+ lookup,
99
+ validation: issue,
100
+ ...allowed.length ? {
101
+ suggestions: allowed.map((value) => ({
102
+ value,
103
+ label: String(value),
104
+ origin: "schema",
105
+ definition
106
+ }))
107
+ } : {}
108
+ };
109
+ }
110
+ function resolve(cursor, seen = /* @__PURE__ */ new Set()) {
111
+ const ref = cursor.schema.$ref;
112
+ if (typeof ref !== "string") return cursor;
113
+ const id = String(cursor.root.$id ?? "") + ref;
114
+ if (seen.has(id)) return { ...cursor, schema: {} };
115
+ seen.add(id);
116
+ const [base, fragment = ""] = ref.split("#"), root = base ? schemaEntries.find((entry) => entry.schema.$id === base)?.schema : cursor.root;
117
+ if (!root) return { ...cursor, schema: {} };
118
+ const target = at(root, fragment);
119
+ if (!object(target)) return { ...cursor, schema: {} };
120
+ const resolved = resolve(
121
+ { schema: target, root, path: fragment },
122
+ seen
123
+ );
124
+ const { $ref, ...rest } = cursor.schema;
125
+ return { ...resolved, schema: { ...resolved.schema, ...rest } };
126
+ }
127
+ function score(schema, value) {
128
+ const type = schema.type;
129
+ if (typeof type === "string" && (type === "array" ? !Array.isArray(value) : type === "object" ? !object(value) : type === "null" ? value !== null : type === "integer" ? !Number.isInteger(value) : typeof value !== type))
130
+ return -1e4;
131
+ if (own(schema, "const")) return schema.const === value ? 100 : -1e4;
132
+ let result = 1;
133
+ if (object(value) && object(schema.properties)) {
134
+ for (const [key, child] of Object.entries(schema.properties))
135
+ if (own(value, key) && object(child))
136
+ result += own(child, "const") ? child.const === value[key] ? 100 : -1e3 : 1;
137
+ }
138
+ if (Array.isArray(schema.required)) {
139
+ for (const key of schema.required)
140
+ if (typeof key === "string" && (!object(value) || !own(value, key)))
141
+ result -= 2;
142
+ }
143
+ return result;
144
+ }
145
+ function active(cursor, value) {
146
+ const resolved = resolve(cursor), alternatives = resolved.schema.oneOf ?? resolved.schema.anyOf;
147
+ if (!Array.isArray(alternatives)) return resolved;
148
+ const keyword = resolved.schema.oneOf ? "oneOf" : "anyOf";
149
+ const candidates = alternatives.filter(object).map(
150
+ (schema, index) => active(
151
+ {
152
+ schema,
153
+ root: resolved.root,
154
+ path: `${resolved.path}/${keyword}/${index}`
155
+ },
156
+ value
157
+ )
158
+ );
159
+ const selected = candidates.sort((a, b) => score(b.schema, value) - score(a.schema, value))[0];
160
+ return selected ? { ...selected, baseSchemas: [...selected.baseSchemas ?? [], resolved] } : resolved;
161
+ }
162
+ function catalogIn(schema) {
163
+ const text = String(schema.description ?? "");
164
+ if (/\bfont-scheme id\b/.test(text)) return "fontSchemes";
165
+ return catalogKinds.find(
166
+ (kind) => text.includes(`catalogs.${kind}`) || new RegExp(`\\b${kind}['\u2019]? catalog`).test(text)
167
+ );
168
+ }
169
+ var languageTagSyntax = new RegExp(
170
+ "^(?:(?:[a-z]{2,3}(?:-[a-z]{3}){0,3}|[a-z]{4}|[a-z]{5,8})(?:-[a-z]{4})?(?:-(?:[a-z]{2}|[0-9]{3}))?(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*(?:-x(?:-[a-z0-9]{1,8})+)?|x(?:-[a-z0-9]{1,8})+)$",
171
+ "i"
172
+ );
173
+ var irregularLanguageTags = /* @__PURE__ */ new Set([
174
+ "en-gb-oed",
175
+ "i-ami",
176
+ "i-bnn",
177
+ "i-default",
178
+ "i-enochian",
179
+ "i-hak",
180
+ "i-klingon",
181
+ "i-lux",
182
+ "i-mingo",
183
+ "i-navajo",
184
+ "i-pwn",
185
+ "i-tao",
186
+ "i-tay",
187
+ "i-tsu",
188
+ "sgn-be-fr",
189
+ "sgn-be-nl",
190
+ "sgn-ch-de"
191
+ ]);
192
+ function childCursor(cursors, key) {
193
+ for (const keyword of [
194
+ "properties",
195
+ "patternProperties",
196
+ "additionalProperties"
197
+ ]) {
198
+ for (const cursor of cursors) {
199
+ const declarations = cursor.schema[keyword];
200
+ if (!object(declarations)) continue;
201
+ const name = keyword === "properties" ? key : keyword === "patternProperties" ? Object.keys(declarations).find(
202
+ (pattern) => new RegExp(pattern).test(key)
203
+ ) : void 0;
204
+ const schema = keyword === "additionalProperties" ? declarations : name === void 0 ? void 0 : declarations[name];
205
+ if (object(schema))
206
+ return {
207
+ schema,
208
+ root: cursor.root,
209
+ path: `${cursor.path}/${keyword}${name === void 0 ? "" : pointer([name])}`
210
+ };
211
+ }
212
+ }
213
+ return void 0;
214
+ }
215
+ function fields(document) {
216
+ const result = [], stack = [
217
+ {
218
+ value: document,
219
+ path: [],
220
+ cursor: {
221
+ schema: schemas.presentation,
222
+ root: schemas.presentation,
223
+ path: ""
224
+ },
225
+ ancestors: []
226
+ }
227
+ ];
228
+ while (stack.length) {
229
+ const entry = stack.pop();
230
+ if (!entry) break;
231
+ if (entry.ancestors.includes(entry.value)) continue;
232
+ const resolved = resolve(entry.cursor), selected = active(entry.cursor, entry.value), description = String(resolved.schema.description ?? "");
233
+ const assetReference = [resolved, selected].some(
234
+ (cursor) => cursor.root.$id === schemas.presentation.$id && (cursor.path === "/$defs/Asset" || cursor.path === "/$defs/Asset/oneOf/0" || cursor.path === "/$defs/Watermark/properties/src") || String(cursor.schema.description ?? "").includes("asset:") || Array.isArray(cursor.schema.examples) && cursor.schema.examples.some(
235
+ (example) => typeof example === "string" && example.startsWith("asset:")
236
+ )
237
+ );
238
+ result.push({
239
+ path: pointer(entry.path),
240
+ value: entry.value,
241
+ cursor: resolved,
242
+ kind: catalogIn(resolved.schema),
243
+ description,
244
+ assetReference
245
+ });
246
+ const ancestors = [...entry.ancestors, entry.value];
247
+ const cursors = [selected, ...selected.baseSchemas ?? [], resolved];
248
+ const arrayCursor = cursors.find((cursor) => object(cursor.schema.items));
249
+ if (Array.isArray(entry.value) && arrayCursor)
250
+ entry.value.forEach((value, index) => {
251
+ stack.push({
252
+ value,
253
+ path: [...entry.path, index],
254
+ cursor: {
255
+ schema: arrayCursor.schema.items,
256
+ root: arrayCursor.root,
257
+ path: `${arrayCursor.path}/items`
258
+ },
259
+ ancestors
260
+ });
261
+ });
262
+ else if (object(entry.value))
263
+ for (const [key, value] of Object.entries(entry.value)) {
264
+ if (entry.path.length === 0 && key === "catalogs") continue;
265
+ const cursor = childCursor(cursors, key);
266
+ if (!cursor) continue;
267
+ stack.push({
268
+ value,
269
+ path: [...entry.path, key],
270
+ cursor,
271
+ ancestors
272
+ });
273
+ }
274
+ }
275
+ return result;
276
+ }
277
+ function catalogContext(document, options, diagnostics) {
278
+ const result = /* @__PURE__ */ new Map();
279
+ for (const entry of catalogEntries) {
280
+ const kind = entry.kind, map = /* @__PURE__ */ new Map();
281
+ result.set(kind, map);
282
+ for (const record of entry.records)
283
+ map.set(record.id, {
284
+ value: record.id,
285
+ label: String(
286
+ record.name ?? record.id
287
+ ),
288
+ origin: "built-in",
289
+ definition: `spec/${entry.dir}/${entry.index.records.find((item) => item.id === record.id)?.file ?? `${record.id}.json`}`
290
+ });
291
+ const local = object(document) && object(document.catalogs) && object(document.catalogs[kind]) ? document.catalogs[kind] : {};
292
+ if (local.source !== void 0)
293
+ diagnostics.push({
294
+ ruleId: "opf/catalog-source",
295
+ severity: "info",
296
+ scope: "document",
297
+ path: `/catalogs/${kind}/source`,
298
+ message: "External catalog source was not fetched.",
299
+ help: "This lint run checks built-in, supplied and inline records only. Load external catalogs in the host and pass their records explicitly to verify that context."
300
+ });
301
+ for (const group of [
302
+ {
303
+ records: options.catalogs?.[kind] ?? [],
304
+ origin: "loaded",
305
+ scope: "context",
306
+ path: `/catalogs/${kind}`
307
+ },
308
+ {
309
+ records: Array.isArray(local.records) ? local.records : [],
310
+ origin: "document",
311
+ scope: "document",
312
+ path: `/catalogs/${kind}/records`
313
+ }
314
+ ]) {
315
+ const seen = /* @__PURE__ */ new Set();
316
+ group.records.forEach((value, index) => {
317
+ const path = `${group.path}/${index}`, schemaName = catalogSchemaNames[kind], record = object(value) ? { $schema: schemas[schemaName].$id, ...value } : value;
318
+ const validation = validateCatalogRecord(kind, record);
319
+ for (const issue of validation.errors)
320
+ diagnostics.push({
321
+ ...schemaDiagnostic(issue, schemaName, path, group.scope),
322
+ ruleId: "opf/catalog-record"
323
+ });
324
+ if (!object(value) || typeof value.id !== "string") return;
325
+ if (seen.has(value.id))
326
+ diagnostics.push({
327
+ ruleId: "opf/catalog-record",
328
+ severity: "error",
329
+ scope: group.scope,
330
+ path: `${path}/id`,
331
+ message: `Duplicate ${kind} record id ${JSON.stringify(value.id)} in this catalog.`,
332
+ help: "Give distinct records distinct IDs, or combine the intended override explicitly. Preserve their authored content."
333
+ });
334
+ seen.add(value.id);
335
+ if (!validation.valid) {
336
+ map.delete(value.id);
337
+ return;
338
+ }
339
+ map.set(value.id, {
340
+ value: value.id,
341
+ label: typeof value.name === "string" ? value.name : value.id,
342
+ origin: group.origin,
343
+ definition: `${group.scope}#${path}`
344
+ });
345
+ });
346
+ }
347
+ }
348
+ return result;
349
+ }
350
+ function distance(a, b) {
351
+ a = a.slice(0, 128);
352
+ b = b.slice(0, 128);
353
+ let row = Array.from({ length: b.length + 1 }, (_, i) => i);
354
+ for (let i = 0; i < a.length; i++) {
355
+ const next = [i + 1];
356
+ for (let j = 0; j < b.length; j++)
357
+ next.push(
358
+ Math.min(
359
+ (next[j] ?? Infinity) + 1,
360
+ (row[j + 1] ?? Infinity) + 1,
361
+ (row[j] ?? Infinity) + (a[i] === b[j] ? 0 : 1)
362
+ )
363
+ );
364
+ row = next;
365
+ }
366
+ return row[b.length] ?? Math.max(a.length, b.length);
367
+ }
368
+ function lintPresentation(document, options = {}) {
369
+ optionsChecked(options);
370
+ const validation = validatePresentation(document), diagnostics = validation.errors.map((issue) => schemaDiagnostic(issue));
371
+ const catalogs = catalogContext(document, options, diagnostics), seen = /* @__PURE__ */ new Set();
372
+ const assetValues = object(document) && object(document.assets) ? document.assets : {};
373
+ for (const field of fields(document)) {
374
+ if (typeof field.value === "string" && field.value.startsWith("asset:") && field.assetReference) {
375
+ const id = field.value.slice(6);
376
+ if (!own(assetValues, id))
377
+ diagnostics.push({
378
+ ruleId: "opf/asset-reference",
379
+ severity: "error",
380
+ scope: "document",
381
+ path: field.path,
382
+ message: `Asset ${JSON.stringify(id)} is missing from the document registry.`,
383
+ help: "Supply the intended asset in document.assets or choose the correct existing asset ID. External files and URLs are not fetched or verified.",
384
+ definition: schemas.presentation.$id + "#/$defs/Assets",
385
+ lookup: ["opf", "schema", "presentation", "/$defs/Assets"],
386
+ suggestions: Object.keys(assetValues).sort(
387
+ (a, b) => distance(id, a) - distance(id, b) || (a < b ? -1 : a > b ? 1 : 0)
388
+ ).slice(0, 5).map((id2) => ({
389
+ value: `asset:${id2}`,
390
+ label: id2,
391
+ origin: "document",
392
+ definition: `document#${pointer(["assets", id2])}`
393
+ }))
394
+ });
395
+ }
396
+ if (!field.path || !field.kind) continue;
397
+ const { kind } = field;
398
+ if (kind === "languages" && field.path === "/language" && typeof field.value === "string" && (languageTagSyntax.test(field.value) || irregularLanguageTags.has(field.value.toLowerCase())))
399
+ continue;
400
+ if (kind !== "layouts" && /free-form/i.test(field.description)) continue;
401
+ if (kind === "narratives" && (object(field.value) || field.cursor.root.$id === schemas.presentation.$id && field.cursor.path === "/$defs/Narrative/properties/id"))
402
+ continue;
403
+ const value = object(field.value) ? field.value.id : field.value, path = object(field.value) ? `${field.path}/id` : field.path;
404
+ if (typeof value !== "string" || !value || /^(?:https?:|pkg:)/i.test(value) || catalogs.get(kind)?.has(value) || seen.has(path))
405
+ continue;
406
+ seen.add(path);
407
+ const suggestions = [...catalogs.get(kind)?.values() ?? []].sort(
408
+ (a, b) => distance(value, String(a.value)) - distance(value, String(b.value)) || (String(a.value) < String(b.value) ? -1 : String(a.value) > String(b.value) ? 1 : 0)
409
+ ).slice(0, 5);
410
+ const definition = String(field.cursor.root.$id) + `#${field.cursor.path}`;
411
+ diagnostics.push({
412
+ ruleId: "opf/catalog-reference",
413
+ severity: "warning",
414
+ scope: "document",
415
+ path,
416
+ message: `Unknown ${kind} catalog id ${JSON.stringify(value)} in the available local context.`,
417
+ help: kind === "layouts" ? "Choose an available layout or supply the intended custom record. Engine-defined layouts may be valid; preview with the target renderer before changing content." : "Choose an available record or supply the intended custom catalog context. External references and native rendering are not verified by this check.",
418
+ definition,
419
+ lookup: ["opf", "catalog", kind],
420
+ suggestions
421
+ });
422
+ }
423
+ const reportedCycles = /* @__PURE__ */ new Set();
424
+ for (const id of Object.keys(assetValues)) {
425
+ const chain = [], seenIds = /* @__PURE__ */ new Set();
426
+ let current = id;
427
+ while (current !== void 0 && own(assetValues, current)) {
428
+ if (seenIds.has(current)) {
429
+ const cycle = chain.slice(chain.indexOf(current));
430
+ if (!cycle.some((id2) => reportedCycles.has(id2))) {
431
+ for (const id2 of cycle) reportedCycles.add(id2);
432
+ diagnostics.push({
433
+ ruleId: "opf/asset-cycle",
434
+ severity: "error",
435
+ scope: "document",
436
+ path: pointer(["assets", current]),
437
+ message: `Asset references form a cycle: ${[...cycle, current].map((id2) => JSON.stringify(id2)).join(" \u2192 ")}.`,
438
+ help: "Replace one link with the intended concrete source. Preserve the original asset metadata; no files or URLs were fetched."
439
+ });
440
+ }
441
+ break;
442
+ }
443
+ seenIds.add(current);
444
+ chain.push(current);
445
+ const value = assetValues[current], source = object(value) ? value.src : value;
446
+ current = typeof source === "string" && source.startsWith("asset:") ? source.slice(6) : void 0;
447
+ }
448
+ }
449
+ for (const issue of validation.warnings) {
450
+ const kind = issue.params.kind, id = issue.params.id;
451
+ if (seen.has(issue.path) || typeof id === "string" && catalogs.get(kind)?.has(id))
452
+ continue;
453
+ diagnostics.push({
454
+ ...schemaDiagnostic(issue),
455
+ ruleId: "opf/catalog-reference",
456
+ severity: "warning",
457
+ help: "Inspect the referenced catalog and supply the intended record if this is a custom context."
458
+ });
459
+ }
460
+ for (const [index, contract] of (options.contracts ?? []).entries()) {
461
+ const pattern = parts(contract.path), stack = [{ value: document, path: [], depth: 0 }];
462
+ while (stack.length) {
463
+ const entry = stack.pop();
464
+ if (!entry) break;
465
+ if (entry.depth === pattern.length) {
466
+ if (contract.allowedValues.some((value) => Object.is(value, entry.value)))
467
+ continue;
468
+ const path = pointer(entry.path), definition = contract.documentation ?? `context#/contracts/${index}`, values = {
469
+ path,
470
+ value: JSON.stringify(entry.value),
471
+ allowed: contract.allowedValues.map((value) => JSON.stringify(value)).join(", "),
472
+ file: definition
473
+ };
474
+ const message = (contract.message ?? "This value is outside the allowed values for {{path}}.").replace(
475
+ /\{\{(path|value|allowed|file)\}\}/g,
476
+ (_, key) => values[key] ?? ""
477
+ );
478
+ diagnostics.push({
479
+ ruleId: "opf/contract",
480
+ severity: contract.severity ?? "error",
481
+ scope: "document",
482
+ path,
483
+ message,
484
+ help: `Use one of the configured values: ${values.allowed}. This is an explicit host policy; no source was changed.`,
485
+ definition,
486
+ suggestions: contract.allowedValues.map((value) => ({
487
+ value,
488
+ label: String(value),
489
+ origin: "contract",
490
+ definition
491
+ }))
492
+ });
493
+ } else if (object(entry.value) || Array.isArray(entry.value)) {
494
+ const key = pattern[entry.depth];
495
+ for (const [name, value] of Object.entries(entry.value))
496
+ if (key === "*" || key === name)
497
+ stack.push({
498
+ value,
499
+ path: [...entry.path, name],
500
+ depth: entry.depth + 1
501
+ });
502
+ }
503
+ }
504
+ }
505
+ return report(diagnostics, validation.valid, "not-applicable");
506
+ }
507
+ function lintSource(source, options = {}) {
508
+ optionsChecked(options);
509
+ const errors = [], tree = parseTree(
510
+ source.startsWith("\uFEFF") ? " " + source.slice(1) : source,
511
+ errors,
512
+ {
513
+ disallowComments: true,
514
+ allowTrailingComma: false,
515
+ allowEmptyContent: false
516
+ }
517
+ );
518
+ const lineStarts = [0];
519
+ for (let i = 0; i < source.length; i++) {
520
+ if (source[i] === "\r") {
521
+ if (source[i + 1] === "\n") i++;
522
+ lineStarts.push(i + 1);
523
+ } else if (source[i] === "\n") lineStarts.push(i + 1);
524
+ }
525
+ const location = (offset, length) => {
526
+ let lo = 0, hi = lineStarts.length;
527
+ while (lo + 1 < hi) {
528
+ const mid = lo + hi >> 1;
529
+ if ((lineStarts[mid] ?? 0) <= offset) lo = mid;
530
+ else hi = mid;
531
+ }
532
+ return {
533
+ offset,
534
+ length,
535
+ line: lo + 1,
536
+ column: offset - (lineStarts[lo] ?? 0) + 1
537
+ };
538
+ };
539
+ if (errors.length || !tree)
540
+ return report(
541
+ errors.map((error) => ({
542
+ ruleId: "json/syntax",
543
+ severity: "error",
544
+ scope: "document",
545
+ path: "",
546
+ message: printParseErrorCode(error.error),
547
+ help: "Repair the JSON syntax at this source range. No content or whitespace has been rewritten.",
548
+ location: location(error.offset, error.length)
549
+ })),
550
+ null,
551
+ "checked"
552
+ );
553
+ const diagnostics = [], stack = [tree];
554
+ while (stack.length) {
555
+ const node = stack.pop();
556
+ if (!node) break;
557
+ if (node.type === "object") {
558
+ const keys = /* @__PURE__ */ new Set();
559
+ for (const property of node.children ?? []) {
560
+ const key = property.children?.[0];
561
+ if (!key) continue;
562
+ if (keys.has(key.value))
563
+ diagnostics.push({
564
+ ruleId: "json/duplicate-key",
565
+ severity: "error",
566
+ scope: "document",
567
+ path: pointer(getNodePath(key)),
568
+ message: `Duplicate JSON property ${JSON.stringify(key.value)}.`,
569
+ help: "Resolve the duplicate explicitly, preserving the intended content from both occurrences. JSON.parse would otherwise hide an earlier value.",
570
+ location: location(key.offset, key.length)
571
+ });
572
+ keys.add(key.value);
573
+ }
574
+ }
575
+ stack.push(...node.children ?? []);
576
+ }
577
+ const result = lintPresentation(
578
+ JSON.parse(source.replace(/^\uFEFF/, "")),
579
+ options
580
+ );
581
+ for (const diagnostic of result.diagnostics) {
582
+ if (diagnostic.scope === "document") {
583
+ let node = tree;
584
+ for (const part of parts(diagnostic.path))
585
+ node = node?.type === "array" ? node.children?.[Number(part)] : node?.type === "object" ? node.children?.find(
586
+ (property) => property.children?.[0]?.value === part
587
+ )?.children?.[1] : void 0;
588
+ if (node) diagnostic.location = location(node.offset, node.length);
589
+ }
590
+ diagnostics.push(diagnostic);
591
+ }
592
+ return report(diagnostics, result.schemaValid, "checked");
593
+ }
594
+
595
+ export { lintPresentation, lintSource };
@@ -1,6 +1,6 @@
1
- import { assertValidPresentation } from './chunk-ZGV6I23P.js';
2
- import { resolveFontFamilies, resolveCanvasDimensions, composeSlide, tableRowBoundaries } from './chunk-JA5W5TVA.js';
3
- import { catalogs } from './chunk-TWMRZ43O.js';
1
+ import { assertValidPresentation } from './chunk-ZIL7MGZU.js';
2
+ import { resolveFontFamilies, resolveCanvasDimensions, composeSlide, tableRowBoundaries } from './chunk-PQJRDNA6.js';
3
+ import { catalogs } from './chunk-TU7I3KSB.js';
4
4
 
5
5
  // src/pagination.ts
6
6
  var OPFPaginationError = class extends Error {
@@ -83,14 +83,23 @@ function paginateSlide(input, options = {}) {
83
83
  };
84
84
  source = withReadability(source);
85
85
  let evaluations = 0;
86
- const geometry = (slide) => {
86
+ const geometry = (slide, pageIndex = 0) => {
87
87
  if (++evaluations > 2e4) throw new OPFPaginationError("Pagination exceeded its layout evaluation limit. Split the input into smaller sections.");
88
- return composeSlide(withReadability(slide, true), options);
88
+ return composeSlide(withReadability(slide, true), { ...options, slideNumber: (options.slideNumber ?? sourceIndex + 1) + pageIndex });
89
89
  };
90
90
  const initial = geometry(source);
91
- if (!initial.diagnostics.length) return { slides: [source], pages: [{ slideIndex: sourceIndex, mappings: initial.items.map((item) => ({ sourcePath: item.path, outputPath: item.path })) }] };
92
- const headerIssues = initial.diagnostics.filter((issue) => headingFields.has(issue.path.slice(sourceBase.length + 1)));
93
- if (headerIssues.length) throw new OPFPaginationError("The repeated heading does not fit. Shorten it or change the slide design before pagination.", headerIssues);
91
+ const repeatedMappings = (pageIndex) => {
92
+ if (!initial.furniture) return [];
93
+ const paths = new Set(initial.items.filter((item) => headingFields.has(item.field)).map((item) => item.path));
94
+ for (const part of initial.furniture?.parts ?? []) {
95
+ paths.add(part.path);
96
+ if (part.sourcePath) paths.add(part.sourcePath);
97
+ }
98
+ return [...paths].map((sourcePath) => ({ sourcePath, outputPath: sourcePath.startsWith(`${sourceBase}.`) ? `slides.${sourceIndex + pageIndex}${sourcePath.slice(sourceBase.length)}` : sourcePath }));
99
+ };
100
+ if (!initial.diagnostics.length) return { slides: [source], pages: [{ slideIndex: sourceIndex, mappings: initial.items.map((item) => ({ sourcePath: item.path, outputPath: item.path })), ...initial.furniture ? { repeatedMappings: repeatedMappings(0) } : {} }] };
101
+ const headerIssues = initial.diagnostics.filter((issue) => headingFields.has(issue.path.slice(sourceBase.length + 1)) || initial.furniture?.diagnostics.includes(issue));
102
+ if (headerIssues.length) throw new OPFPaginationError("Repeated headings or header/footer content cannot fit or resolve. Change the repeated content or slide design before pagination.", headerIssues);
94
103
  const leaves = initial.items.filter((item) => !headingFields.has(item.field)).map((item) => leafFor(item.path, item.field, item.value));
95
104
  const leafPaths = new Set(leaves.map((leaf) => leaf.path));
96
105
  const slides = [], pages = [];
@@ -135,11 +144,13 @@ function paginateSlide(input, options = {}) {
135
144
  if (pageIndex > 0) delete slide.notes;
136
145
  return { slide, mappings };
137
146
  };
138
- const diagnosticsFor = (portions) => geometry(project(portions, slides.length).slide).diagnostics;
147
+ const diagnosticsFor = (portions) => geometry(project(portions, slides.length).slide, slides.length).diagnostics;
139
148
  const finish = () => {
140
149
  if (!selected.size) return;
141
150
  if (slides.length >= maxSlides) throw new OPFPaginationError(`Pagination needs more than ${maxSlides} slides. No partial result was returned.`);
142
151
  const { slide, mappings } = project(selected, slides.length);
152
+ const issues = geometry(slide, slides.length).diagnostics;
153
+ if (issues.length) throw new OPFPaginationError("A continuation page does not fit at its final page number. No partial result was returned.", issues);
143
154
  if (slides.length && typeof source.id === "string") {
144
155
  let suffix = slides.length + 1, id = `${source.id}--${suffix}`;
145
156
  while (reservedIds.has(id)) id = `${source.id}--${++suffix}`;
@@ -148,7 +159,7 @@ function paginateSlide(input, options = {}) {
148
159
  }
149
160
  assertValidPresentation({ slides: [slide] });
150
161
  slides.push(slide);
151
- pages.push({ slideIndex: sourceIndex + slides.length - 1, mappings });
162
+ pages.push({ slideIndex: sourceIndex + slides.length - 1, mappings, ...initial.furniture ? { repeatedMappings: repeatedMappings(slides.length - 1) } : {} });
152
163
  selected = /* @__PURE__ */ new Map();
153
164
  };
154
165
  for (const leaf of leaves) {
@@ -218,10 +229,11 @@ function paginatePresentation(input, options = {}) {
218
229
  const fontReference = design.fontScheme ?? theme.fontScheme ?? "roboto";
219
230
  const fontScheme = typeof fontReference === "string" ? resolve("fontSchemes", fontReference) : { ...resolve("fontSchemes", fontReference.id), ...fontReference };
220
231
  const fonts = resolveFontFamilies(fontScheme);
221
- const result = paginateSlide(slide, { ...resolveCanvasDimensions(design.dimensions ?? theme.dimensions), layout, fonts, textMeasurement: options.textMeasurement, ...overrides, slideIndex: index, maxSlides: maxSlides - output.length, minFontSize: options.minFontSize, reservedIds });
232
+ const result = paginateSlide(slide, { ...resolveCanvasDimensions(design.dimensions ?? theme.dimensions), layout, fonts, contentAlignment: design.contentAlignment, titleAlignment: design.titleAlignment, contentBox: design.contentBox, textMeasurement: options.textMeasurement, textRasterPadding: options.textRasterPadding, ...overrides, presentation, slideIndex: index, slideNumber: output.length + 1, maxSlides: maxSlides - output.length, minFontSize: options.minFontSize, reservedIds });
222
233
  const outputStart = output.length;
223
234
  result.pages.forEach((page, pageIndex) => {
224
- pages.push({ sourceSlideIndex: index, slideIndex: outputStart + pageIndex, mappings: page.mappings.map((mapping) => ({ ...mapping, outputPath: mapping.outputPath.replace(/^slides\.\d+/, `slides.${outputStart + pageIndex}`) })) });
235
+ const remap = (mapping) => ({ ...mapping, outputPath: mapping.outputPath.replace(/^slides\.\d+/, `slides.${outputStart + pageIndex}`) });
236
+ pages.push({ sourceSlideIndex: index, slideIndex: outputStart + pageIndex, mappings: page.mappings.map(remap), ...page.repeatedMappings ? { repeatedMappings: page.repeatedMappings.map(remap) } : {} });
225
237
  });
226
238
  output.push(...result.slides);
227
239
  reservedIds.push(...result.slides.map((slide2) => slide2.id).filter(Boolean));