@teipublisher/oddity-language-server 0.0.0-stage → 0.2.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 (62) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +58 -2
  3. package/dist/edit.js +1211 -0
  4. package/dist/edit.js.map +7 -0
  5. package/dist/index.js +1701 -0
  6. package/dist/index.js.map +7 -0
  7. package/dist/node.cjs +45925 -0
  8. package/dist/node.cjs.map +7 -0
  9. package/package.json +74 -4
  10. package/schema/README.md +45 -0
  11. package/schema/docbook/docbook.rng +18457 -0
  12. package/schema/jats/BITS-embedded-index2.ent.rng +340 -0
  13. package/schema/jats/BITS-question-answer2.ent.rng +795 -0
  14. package/schema/jats/JATS-XHTMLtablesetup1-3.ent.rng +614 -0
  15. package/schema/jats/JATS-ali-namespace1-3.ent.rng +284 -0
  16. package/schema/jats/JATS-archivearticle1-3-mathml3.rng +1277 -0
  17. package/schema/jats/JATS-archivecustom-classes1-3.ent.rng +427 -0
  18. package/schema/jats/JATS-archivecustom-mixes1-3.ent.rng +630 -0
  19. package/schema/jats/JATS-archivecustom-models1-3.ent.rng +2205 -0
  20. package/schema/jats/JATS-articlemeta1-3.ent.rng +3138 -0
  21. package/schema/jats/JATS-backmatter1-3.ent.rng +601 -0
  22. package/schema/jats/JATS-chars1-3.ent.rng +715 -0
  23. package/schema/jats/JATS-common-atts1-3.ent.rng +367 -0
  24. package/schema/jats/JATS-common1-3.ent.rng +6007 -0
  25. package/schema/jats/JATS-default-classes1-3.ent.rng +1953 -0
  26. package/schema/jats/JATS-default-mixes1-3.ent.rng +583 -0
  27. package/schema/jats/JATS-display1-3.ent.rng +1669 -0
  28. package/schema/jats/JATS-format1-3.ent.rng +1256 -0
  29. package/schema/jats/JATS-funding1-3.ent.rng +1389 -0
  30. package/schema/jats/JATS-journalmeta1-3.ent.rng +691 -0
  31. package/schema/jats/JATS-link1-3.ent.rng +664 -0
  32. package/schema/jats/JATS-list1-3.ent.rng +747 -0
  33. package/schema/jats/JATS-math1-3.ent.rng +620 -0
  34. package/schema/jats/JATS-mathml3-mathmlsetup1-3.ent.rng +459 -0
  35. package/schema/jats/JATS-nlmcitation1-3.ent.rng +522 -0
  36. package/schema/jats/JATS-para1-3.ent.rng +780 -0
  37. package/schema/jats/JATS-phrase1-3.ent.rng +725 -0
  38. package/schema/jats/JATS-references1-3.ent.rng +1713 -0
  39. package/schema/jats/JATS-related-object1-3.ent.rng +453 -0
  40. package/schema/jats/JATS-section1-3.ent.rng +482 -0
  41. package/schema/jats/mathml3-qname1.mod.rng +61 -0
  42. package/schema/jats/mathml3.rng +4094 -0
  43. package/schema/jats/xhtml-inlstyle-1.mod.rng +37 -0
  44. package/schema/jats/xhtml-table-1.mod.rng +426 -0
  45. package/schema/odd/teipublisher_odds.rng +12769 -0
  46. package/schema/opm/opm.schema.json +402 -0
  47. package/schema/tei/tei_all.rng +23212 -0
  48. package/src/core/association.ts +155 -0
  49. package/src/core/complete.ts +147 -0
  50. package/src/core/elements.ts +86 -0
  51. package/src/core/opmToml.ts +432 -0
  52. package/src/core/outline.ts +156 -0
  53. package/src/core/schema.ts +55 -0
  54. package/src/core/tags.ts +104 -0
  55. package/src/core/toml.ts +64 -0
  56. package/src/core/tomlScan.ts +155 -0
  57. package/src/core/validate.ts +128 -0
  58. package/src/core/wellformed.ts +16 -0
  59. package/src/edit.ts +12 -0
  60. package/src/index.ts +17 -0
  61. package/src/node.ts +39 -0
  62. package/src/server/server.ts +322 -0
package/dist/edit.js ADDED
@@ -0,0 +1,1211 @@
1
+ // src/core/tags.ts
2
+ var SKIP = [["<!--", "-->"], ["<![CDATA[", "]]>"], ["<?", "?>"], ["<!", ">"]];
3
+ function scanTags(text) {
4
+ const tags = [];
5
+ let i = 0;
6
+ while ((i = text.indexOf("<", i)) >= 0) {
7
+ const skip = SKIP.find(([open]) => text.startsWith(open, i));
8
+ if (skip) {
9
+ const end = text.indexOf(skip[1], i + skip[0].length);
10
+ if (end < 0) break;
11
+ i = end + skip[1].length;
12
+ continue;
13
+ }
14
+ const closing = text[i + 1] === "/";
15
+ const nameFrom = i + (closing ? 2 : 1);
16
+ const name = text.slice(nameFrom).match(/^[^\s<>/="']*/)[0];
17
+ let j = nameFrom + name.length, quote = "";
18
+ for (; j < text.length; j++) {
19
+ const c = text[j];
20
+ if (quote) {
21
+ if (c === quote) quote = "";
22
+ } else if (c === '"' || c === "'") quote = c;
23
+ else if (c === ">" || c === "<") break;
24
+ }
25
+ const finished = text[j] === ">";
26
+ const to = finished ? j + 1 : j;
27
+ const kind = closing ? "close" : finished && text[j - 1] === "/" ? "empty" : "open";
28
+ tags.push({ kind, name, from: i, nameFrom, nameTo: nameFrom + name.length, to });
29
+ i = finished ? to : Math.max(j, i + 1);
30
+ }
31
+ return tags;
32
+ }
33
+ function pairs(tags) {
34
+ const stack = [];
35
+ const pair = /* @__PURE__ */ new Map();
36
+ tags.forEach((t, i) => {
37
+ if (t.kind === "open") stack.push(i);
38
+ else if (t.kind === "close") {
39
+ const k = stack.map((s) => tags[s].name).lastIndexOf(t.name);
40
+ if (k < 0) return;
41
+ pair.set(stack[k], i);
42
+ pair.set(i, stack[k]);
43
+ stack.length = k;
44
+ }
45
+ });
46
+ return pair;
47
+ }
48
+ function matchingTags(text, offset) {
49
+ const tags = scanTags(text);
50
+ const at = tags.findIndex((t) => t.kind !== "empty" && t.nameFrom <= offset && offset <= t.nameTo);
51
+ if (at < 0) return null;
52
+ const other = pairs(tags).get(at);
53
+ if (other === void 0) return null;
54
+ return [at, other].sort((a, b) => a - b).map((i) => ({ from: tags[i].nameFrom, to: tags[i].nameTo }));
55
+ }
56
+ function openElementAt(text, offset) {
57
+ const tags = scanTags(text.slice(0, offset));
58
+ const pair = pairs(tags);
59
+ for (let i = tags.length - 1; i >= 0; i--) {
60
+ if (tags[i].kind === "open" && !pair.has(i) && tags[i].to <= offset && text[tags[i].to - 1] === ">") return tags[i].name;
61
+ }
62
+ return void 0;
63
+ }
64
+ function closeTagAt(text, offset) {
65
+ const before = text.slice(0, offset);
66
+ if (before.endsWith("</")) {
67
+ const name = openElementAt(text, offset - 2);
68
+ if (!name) return void 0;
69
+ return text.slice(offset).startsWith(">") ? name : `${name}>`;
70
+ }
71
+ if (!before.endsWith(">") || before.endsWith("/>")) return void 0;
72
+ const tags = scanTags(before);
73
+ const last = tags[tags.length - 1];
74
+ if (!last || last.kind !== "open" || last.to !== offset || !last.name) return void 0;
75
+ const end = `</${last.name}>`;
76
+ if (text.slice(offset).startsWith(end)) return void 0;
77
+ return end;
78
+ }
79
+
80
+ // src/core/toml.ts
81
+ import { parse } from "smol-toml";
82
+ var q = (s) => JSON.stringify(s);
83
+ var sectionEnd = (lines, head) => {
84
+ for (let i = head + 1; i < lines.length; i++) if (/^\s*\[/.test(lines[i])) return i;
85
+ return lines.length;
86
+ };
87
+ function setToml(text, section, key, value) {
88
+ const line = `${key} = ${q(value)}`, lines = text ? text.split("\n") : [];
89
+ const head = lines.findIndex((l) => l.trim() === `[${section}]`);
90
+ if (head < 0) return (text && !text.endsWith("\n") ? text + "\n" : text) + (text ? "\n" : "") + `[${section}]
91
+ ${line}
92
+ `;
93
+ const end = sectionEnd(lines, head), re = new RegExp(`^\\s*${key}\\s*=`);
94
+ for (let i = head + 1; i < end; i++) if (re.test(lines[i])) {
95
+ lines[i] = line;
96
+ return lines.join("\n");
97
+ }
98
+ lines.splice(head + 1, 0, line);
99
+ return lines.join("\n");
100
+ }
101
+ function unsetToml(text, section, key) {
102
+ const lines = text.split("\n"), head = lines.findIndex((l) => l.trim() === `[${section}]`);
103
+ if (head < 0) return text;
104
+ const end = sectionEnd(lines, head), re = new RegExp(`^\\s*${key}\\s*=`);
105
+ for (let i = head + 1; i < end; i++) if (re.test(lines[i])) {
106
+ lines.splice(i, 1);
107
+ break;
108
+ }
109
+ return lines.join("\n");
110
+ }
111
+ function readToml(text) {
112
+ let doc;
113
+ try {
114
+ doc = parse(text);
115
+ } catch {
116
+ return {};
117
+ }
118
+ const cfg = {};
119
+ const walk = (table, path) => {
120
+ for (const [key, v] of Object.entries(table)) {
121
+ if (typeof v === "string" || Array.isArray(v) && v.length && v.every((x) => typeof x === "string")) {
122
+ (cfg[path.join(".")] ||= {})[key] = v;
123
+ } else if (Array.isArray(v) && !v.length) {
124
+ (cfg[path.join(".")] ||= {})[key] = [];
125
+ } else if (v && typeof v === "object" && !Array.isArray(v) && !(v instanceof Date)) {
126
+ walk(v, [...path, key]);
127
+ }
128
+ }
129
+ };
130
+ walk(doc, []);
131
+ return cfg;
132
+ }
133
+ var tomlString = (cfg, section, key) => {
134
+ const v = cfg[section]?.[key];
135
+ return typeof v === "string" ? v : "";
136
+ };
137
+
138
+ // src/core/association.ts
139
+ var RNG_NS = "http://relaxng.org/ns/structure/1.0";
140
+ var isOdd = (url) => /\.odd$/i.test(new URL(url).pathname);
141
+ var DEFAULT_SCHEMA_FILES = {
142
+ odd: "odd/teipublisher_odds.rng",
143
+ tei: "tei/tei_all.rng",
144
+ docbook: "docbook/docbook.rng",
145
+ jats: "jats/JATS-archivearticle1-3-mathml3.rng"
146
+ };
147
+ var PUBLIC_SCHEMA_URLS = {
148
+ tei: "https://tei-c.org/release/xml/tei/custom/schema/relaxng/tei_all.rng",
149
+ docbook: "https://cdn.docbook.org/schema/5.2/rng/docbook.rng",
150
+ jats: "https://jats.nlm.nih.gov/archiving/1.3/rng/JATS-archivearticle1-3-mathml3.rng"
151
+ };
152
+ function publicSchema(url) {
153
+ if (/^https?:\/\/(www\.)?tei-c\.org\/.*\/tei_all\.rng$/i.test(url)) return "tei";
154
+ if (/^https?:\/\/([\w-]+\.)?docbook\.org\/.*\/docbook\.rng$/i.test(url)) return "docbook";
155
+ if (/^https?:\/\/jats\.nlm\.nih\.gov\/.*\.rng$/i.test(url)) return "jats";
156
+ return void 0;
157
+ }
158
+ function vocabulary(text) {
159
+ const head = text.slice(0, 5e3);
160
+ if (head.includes("http://www.tei-c.org/ns/1.0") || /<(TEI|teiCorpus)[\s>]/.test(head)) return "tei";
161
+ if (head.includes("http://docbook.org/ns/docbook")) return "docbook";
162
+ if (/<!DOCTYPE\s+article\s+PUBLIC\s+"-\/\/NLM\/\/DTD/.test(head)) return "jats";
163
+ const article = head.match(/<article(?=[\s>])[^>]*>/)?.[0];
164
+ if (article && !/\sxmlns\s*=/.test(article) && (/\s(dtd-version|article-type)\s*=/.test(article) || /<front[\s>]/.test(head))) return "jats";
165
+ return "";
166
+ }
167
+ function xmlModels(text) {
168
+ const out = [];
169
+ for (const m of text.slice(0, 5e3).matchAll(/<\?xml-model\s([^?]*)\?>/g)) {
170
+ const pseudo = (name) => m[1].match(new RegExp(`\\b${name}\\s*=\\s*["']([^"']*)["']`))?.[1];
171
+ out.push({ from: m.index, to: m.index + m[0].length, href: pseudo("href"), schematypens: pseudo("schematypens"), raw: m[0] });
172
+ }
173
+ return out;
174
+ }
175
+ var isRngModel = (pi) => pi.schematypens === RNG_NS || !pi.schematypens && !!pi.href && /\.rng$/i.test(pi.href) && !/schematron/i.test(pi.raw);
176
+ function projectRoot(url, files, stops = []) {
177
+ let dir = new URL("./", url);
178
+ for (; ; ) {
179
+ if (files.exists(new URL("opm.toml", dir).href)) return dir.href;
180
+ const parent = new URL("../", dir);
181
+ if (parent.href === dir.href || stops.some((s) => sameDir(s, dir.href))) return void 0;
182
+ dir = parent;
183
+ }
184
+ }
185
+ var sameDir = (a, b) => a.replace(/\/?$/, "/") === b.replace(/\/?$/, "/");
186
+ function schemaFor(url, text, files, defaults, stops = []) {
187
+ for (const pi of xmlModels(text)) {
188
+ if (!isRngModel(pi) || !pi.href) continue;
189
+ if (/^(https?|ftp):/i.test(pi.href)) {
190
+ const bundled = defaults[publicSchema(pi.href) ?? ""];
191
+ if (bundled) return { url: bundled, via: "xml-model" };
192
+ continue;
193
+ }
194
+ const target = new URL(pi.href, url).href;
195
+ if (files.exists(target)) return { url: target, via: "xml-model" };
196
+ }
197
+ const odd = isOdd(url);
198
+ if (!odd) {
199
+ const root = projectRoot(url, files, stops);
200
+ const toml = root && files.read(new URL("opm.toml", root).href);
201
+ const configured = toml ? tomlString(readToml(toml), "editor", "schema") : "";
202
+ if (configured && /\.rng$/i.test(configured)) {
203
+ const bundled = defaults[publicSchema(configured) ?? ""];
204
+ if (bundled) return { url: bundled, via: "project" };
205
+ const target = new URL(configured, root).href;
206
+ if (files.exists(target)) return { url: target, via: "project" };
207
+ }
208
+ }
209
+ const fallback = defaults[odd ? "odd" : vocabulary(text)];
210
+ return fallback ? { url: fallback, via: "default" } : null;
211
+ }
212
+ function relativeHref(from, to) {
213
+ const a = new URL(from), b = new URL(to);
214
+ if (a.protocol !== b.protocol || a.host !== b.host) return to;
215
+ const dir = a.pathname.split("/").slice(0, -1), target = b.pathname.split("/");
216
+ let i = 0;
217
+ while (i < dir.length && i < target.length - 1 && dir[i] === target[i]) i++;
218
+ return [...Array(dir.length - i).fill(".."), ...target.slice(i)].join("/");
219
+ }
220
+ function xmlModelEdits(text, href) {
221
+ const nl = text.includes("\r\n") ? "\r\n" : "\n";
222
+ const models = xmlModels(text).filter(isRngModel);
223
+ const pi = href && `<?xml-model href="${href.replace(/&/g, "&amp;").replace(/"/g, "&quot;")}" type="application/xml" schematypens="${RNG_NS}"?>`;
224
+ const removal = (m) => {
225
+ const after = text.slice(m.to).match(/^\r?\n/)?.[0].length ?? 0;
226
+ return { from: m.from, to: m.to + after, insert: "" };
227
+ };
228
+ if (!pi) return models.map(removal);
229
+ if (models.length) return [{ from: models[0].from, to: models[0].to, insert: pi }, ...models.slice(1).map(removal)];
230
+ const decl = text.match(/^?<\?xml\s[^?]*\?>/);
231
+ if (decl) return [{ from: decl[0].length, to: decl[0].length, insert: nl + pi }];
232
+ const bom = text.startsWith("\uFEFF") ? 1 : 0;
233
+ return [{ from: bom, to: bom, insert: pi + nl }];
234
+ }
235
+
236
+ // src/core/opmToml.ts
237
+ import { parse as parse2, TomlError } from "smol-toml";
238
+
239
+ // schema/opm/opm.schema.json
240
+ var opm_schema_default = {
241
+ $schema: "http://json-schema.org/draft-07/schema#",
242
+ $id: "https://github.com/eeditiones/open-processing-model/opm.schema.json",
243
+ $comment: "SPDX-FileCopyrightText: 2026 e-editiones. SPDX-License-Identifier: CC0-1.0",
244
+ title: "opm.toml",
245
+ description: "Project configuration for the Open Processing Model. Relative paths resolve against the directory of opm.toml.",
246
+ type: "object",
247
+ additionalProperties: false,
248
+ properties: {
249
+ project: {
250
+ description: "Python paths and profiles of the project.",
251
+ type: "object",
252
+ additionalProperties: false,
253
+ properties: {
254
+ pythonpath: {
255
+ description: "Extra Python paths, relative to opm.toml, so the project's extension modules can be imported.",
256
+ $ref: "#/definitions/stringOrList",
257
+ default: ["."]
258
+ },
259
+ profiles: {
260
+ description: "Profiles to switch on: ready-made features such as registers, search or a facsimile viewer. `opm profile list` shows them.",
261
+ $ref: "#/definitions/profileList"
262
+ }
263
+ }
264
+ },
265
+ transform: { $ref: "#/definitions/transform" },
266
+ context: {
267
+ description: "Free-form values handed to every template as `context`. TOML types are kept. A [transform.<type>.context] table overlays this per output type.",
268
+ type: "object",
269
+ properties: {
270
+ site_name: { description: "Title of the site, shown in the menu bar of opm's page layout.", type: "string" },
271
+ logo: { description: "Logo shown in the menu bar, as a URL relative to the page.", type: "string" },
272
+ webcomponents_url: { description: "URL of the TEI Publisher web components bundle, to serve it yourself or pin another version.", type: "string" },
273
+ menu: {
274
+ description: "The menu bar of opm's page layout.",
275
+ type: "object",
276
+ properties: {
277
+ items: {
278
+ description: "Links in the menu bar, after the logo.",
279
+ type: "array",
280
+ items: {
281
+ type: "object",
282
+ properties: {
283
+ label: { description: "Text of the link.", type: "string" },
284
+ url: { description: "Target of the link.", type: "string" }
285
+ }
286
+ }
287
+ }
288
+ }
289
+ },
290
+ features: {
291
+ description: "Settings of profiles, one table per profile: [context.features.<name>]. They override the defaults in the profile's opm-profile.toml.",
292
+ type: "object",
293
+ additionalProperties: { type: "object" }
294
+ }
295
+ }
296
+ },
297
+ chunking: {
298
+ description: "How `opm chunk` splits documents into pages. A [chunking] table is one run; a [[chunking]] array declares several, run in order into one output directory.",
299
+ anyOf: [
300
+ { $ref: "#/definitions/chunkingRun" },
301
+ { type: "array", items: { $ref: "#/definitions/chunkingRun" } }
302
+ ]
303
+ },
304
+ pages: {
305
+ description: "Auxiliary pages of the chunked site, written by `opm chunk` after the chunking runs: an about page, register overviews, one page per register entry.",
306
+ type: "array",
307
+ items: { $ref: "#/definitions/page" }
308
+ },
309
+ index: { $ref: "#/definitions/index" },
310
+ document: {
311
+ description: "Makes this project an `opm odd document` site.",
312
+ type: "object",
313
+ additionalProperties: false,
314
+ properties: {
315
+ source: { description: "The ODD, compiled spec document or Specs directory to document.", type: "string" },
316
+ lang: { description: "xml:lang to prefer for gloss, desc and remarks.", type: "string" }
317
+ }
318
+ },
319
+ editor: {
320
+ description: "Settings for editors (opm studio, ODDity). opm itself ignores them.",
321
+ type: "object",
322
+ additionalProperties: false,
323
+ properties: {
324
+ schema: { description: "RELAX NG schema to check documents against when they have no <?xml-model?> of their own.", type: "string" }
325
+ }
326
+ },
327
+ web: { $ref: "#/definitions/webSection", deprecated: true, description: "Deprecated: use [transform.web]." },
328
+ print: { $ref: "#/definitions/printSection", deprecated: true, description: "Deprecated: use [transform.print]." },
329
+ epub: { $ref: "#/definitions/epubSection", deprecated: true, description: "Deprecated: use [transform.epub]." },
330
+ markdown: { $ref: "#/definitions/typeSection", deprecated: true, description: "Deprecated: use [transform.markdown]." },
331
+ docx: { $ref: "#/definitions/docxSection", deprecated: true, description: "Deprecated: use [transform.docx]." },
332
+ typst: { $ref: "#/definitions/typstSection", deprecated: true, description: "Deprecated: use [transform.typst]." },
333
+ json: { $ref: "#/definitions/typeSection", deprecated: true, description: "Deprecated: use [transform.json]." }
334
+ },
335
+ definitions: {
336
+ stringOrList: {
337
+ anyOf: [
338
+ { type: "string" },
339
+ { type: "array", items: { type: "string" } }
340
+ ]
341
+ },
342
+ profileList: {
343
+ anyOf: [
344
+ { $ref: "#/definitions/profileName" },
345
+ { type: "array", items: { $ref: "#/definitions/profileName" } }
346
+ ]
347
+ },
348
+ profileName: {
349
+ type: "string",
350
+ examples: ["edition-navigation", "iiif", "pagefind", "registers"]
351
+ },
352
+ outputType: {
353
+ type: "string",
354
+ enum: ["web", "print", "epub", "markdown", "docx", "typst", "json", "json-web", "json-print", "json-epub", "json-markdown", "json-docx", "json-typst"]
355
+ },
356
+ scalar: { type: ["string", "number", "boolean"] },
357
+ odd: { description: "ODD for this output type, overriding [transform] odd.", type: "string" },
358
+ typeContext: {
359
+ description: "Template context for this output type only, over [context].",
360
+ type: "object"
361
+ },
362
+ transform: {
363
+ description: "Settings shared by every output type, and one table per type.",
364
+ type: "object",
365
+ additionalProperties: false,
366
+ properties: {
367
+ odd: { description: "Default ODD for every output type, compiled on demand. Without one, the packaged teipublisher.odd is used.", type: "string" },
368
+ css: { description: "Base rules compiled into the ODD stylesheet for every output type, replacing the packaged defaults. Design CSS belongs in [transform.web] assets.", type: "string" },
369
+ documents: {
370
+ description: "XML documents loaded up front for XPath doc(), such as registers that most pages look things up in.",
371
+ $ref: "#/definitions/stringOrList"
372
+ },
373
+ document_roots: {
374
+ description: "Further folders doc() may open any XML file in, read the first time an expression asks for it. The project folder is always allowed.",
375
+ $ref: "#/definitions/stringOrList"
376
+ },
377
+ footnote_order: {
378
+ description: "Dotted path of a callable that orders each run's footnotes before they are placed (web, markdown).",
379
+ type: "string",
380
+ examples: ["opm.runtime.footnote_order.labelled_first"]
381
+ },
382
+ xpath_extensions: {
383
+ description: "Python modules whose functions the ODD calls as tp:\u2026(). [[transform.extensions]] does the same and more.",
384
+ $ref: "#/definitions/stringOrList"
385
+ },
386
+ extensions: {
387
+ description: "Python modules whose functions the ODD calls, one table each. A module may use its own prefix and define behaviours.",
388
+ type: "array",
389
+ items: { $ref: "#/definitions/extension" }
390
+ },
391
+ collections: {
392
+ description: "Documents returned by XPath collection() for a URI.",
393
+ type: "array",
394
+ items: {
395
+ type: "object",
396
+ additionalProperties: false,
397
+ required: ["uri"],
398
+ properties: {
399
+ uri: { description: "Absolute URI matched against the argument of collection(), e.g. urn:registers.", type: "string" },
400
+ documents: { description: "Files of the collection; an entry may be a glob such as data/*.xml.", $ref: "#/definitions/stringOrList" }
401
+ }
402
+ }
403
+ },
404
+ namespaces: {
405
+ description: "Namespace prefixes for XPath written in the ODD, as prefix = URI.",
406
+ type: "object",
407
+ additionalProperties: { type: "string" }
408
+ },
409
+ variables: {
410
+ description: "Values of XPath variables. A key straight under this table is $name; a sub-table named after a prefix from [transform.namespaces] holds that namespace's variables.",
411
+ type: "object",
412
+ additionalProperties: {
413
+ anyOf: [
414
+ { $ref: "#/definitions/scalar" },
415
+ { type: "object", additionalProperties: { $ref: "#/definitions/scalar" } }
416
+ ]
417
+ }
418
+ },
419
+ parameters: {
420
+ description: "Values of the ODD's $parameters, for every output type.",
421
+ type: "object",
422
+ additionalProperties: { $ref: "#/definitions/scalar" }
423
+ },
424
+ web: { $ref: "#/definitions/webSection" },
425
+ print: { $ref: "#/definitions/printSection" },
426
+ epub: { $ref: "#/definitions/epubSection" },
427
+ markdown: { $ref: "#/definitions/typeSection", description: "Markdown output." },
428
+ docx: { $ref: "#/definitions/docxSection" },
429
+ typst: { $ref: "#/definitions/typstSection" },
430
+ json: { $ref: "#/definitions/typeSection", description: "JSON data output, for every json-<type> channel." }
431
+ }
432
+ },
433
+ typeSection: {
434
+ type: "object",
435
+ additionalProperties: false,
436
+ properties: {
437
+ odd: { $ref: "#/definitions/odd" },
438
+ context: { $ref: "#/definitions/typeContext" }
439
+ }
440
+ },
441
+ webSection: {
442
+ description: "HTML output of a whole document, and the defaults for chunk pages.",
443
+ type: "object",
444
+ additionalProperties: false,
445
+ properties: {
446
+ odd: { $ref: "#/definitions/odd" },
447
+ context: { $ref: "#/definitions/typeContext" },
448
+ template: { description: "Jinks page template for HTML output (.html.tpl).", type: "string" },
449
+ webcomponents: { description: "Emit TEI Publisher web components and let the template load their bundle.", type: "boolean", default: false },
450
+ assets: {
451
+ description: "Stylesheets, images and fonts the template uses, copied into an assets/ folder beside the output. An entry may be a glob.",
452
+ type: "array",
453
+ items: { type: "string" }
454
+ },
455
+ pages: {
456
+ description: 'Show the document page by page: dotted path of a chunk selector, one <section class="opm-page"> per page.',
457
+ type: "string",
458
+ examples: ["opm.navigation.tei_pb_chunks"]
459
+ }
460
+ }
461
+ },
462
+ printSection: {
463
+ description: "Paged HTML for print.",
464
+ type: "object",
465
+ additionalProperties: false,
466
+ properties: {
467
+ odd: { $ref: "#/definitions/odd" },
468
+ context: { $ref: "#/definitions/typeContext" },
469
+ template: { description: "Jinks page template for print output (.html.tpl).", type: "string" }
470
+ }
471
+ },
472
+ epubSection: {
473
+ description: "EPUB output.",
474
+ type: "object",
475
+ additionalProperties: false,
476
+ properties: {
477
+ odd: { $ref: "#/definitions/odd" },
478
+ context: { $ref: "#/definitions/typeContext" },
479
+ css: { description: "Stylesheet for the EPUB, replacing the packaged one.", type: "string" },
480
+ skip_title: { description: "Leave out the generated title page.", type: "boolean", default: false },
481
+ xpath: { description: "XPath selecting the elements that become the EPUB's chapters, instead of [chunking] xpath.", type: "string" },
482
+ selector: { description: "Dotted path of a chunk selector for the chapters, instead of [chunking] selector.", type: "string" },
483
+ depth: { description: "Heading depth for chapters, instead of [chunking] depth.", type: "integer", minimum: 1 }
484
+ }
485
+ },
486
+ docxSection: {
487
+ description: "Word output.",
488
+ type: "object",
489
+ additionalProperties: false,
490
+ properties: {
491
+ odd: { $ref: "#/definitions/odd" },
492
+ context: { $ref: "#/definitions/typeContext" },
493
+ template: { description: "Word document whose styles the output uses (.docx).", type: "string" }
494
+ }
495
+ },
496
+ typstSection: {
497
+ description: "Typst output.",
498
+ type: "object",
499
+ additionalProperties: false,
500
+ properties: {
501
+ odd: { $ref: "#/definitions/odd" },
502
+ context: { $ref: "#/definitions/typeContext" },
503
+ template: { description: "Typst template (.typ.tpl).", type: "string" }
504
+ }
505
+ },
506
+ extension: {
507
+ type: "object",
508
+ additionalProperties: false,
509
+ required: ["module"],
510
+ properties: {
511
+ module: { description: "Dotted path of the Python module.", type: "string", examples: ["opm.runtime.common_xpath_functions"] },
512
+ prefix: { description: "Prefix the ODD calls the module's functions with.", type: "string", default: "tp" },
513
+ namespace: { description: "Namespace URI of the prefix. Not allowed for tp, whose namespace is fixed.", type: "string" },
514
+ output: {
515
+ description: "Output types the module is used for; all when empty.",
516
+ anyOf: [
517
+ { $ref: "#/definitions/outputType" },
518
+ { type: "array", items: { $ref: "#/definitions/outputType" } }
519
+ ]
520
+ }
521
+ }
522
+ },
523
+ fragment: {
524
+ description: "A piece of HTML rendered beside each chunk or once for the document, e.g. a table of contents or a register, available to templates by name.",
525
+ type: "object",
526
+ additionalProperties: false,
527
+ required: ["name"],
528
+ properties: {
529
+ name: { description: "Name templates use to place the fragment.", type: "string" },
530
+ scope: { description: "per-chunk: rendered for each chunk; global: once for the document.", type: "string", enum: ["per-chunk", "global"], default: "per-chunk" },
531
+ xpath: { description: "XPath selecting what the fragment renders, relative to the chunk root.", type: "string", default: "." },
532
+ xpath_dynamic: { description: "The xpath the consuming pb-view sends, when it differs from xpath (pb-view index keys only).", type: "string" },
533
+ parameters: { description: `Values of the ODD's $parameters for this fragment, e.g. { mode = "register" }.`, type: "object" },
534
+ odd: { description: "ODD to render the fragment with.", type: "string" },
535
+ mode: { description: "Output type the ODD is compiled for.", $ref: "#/definitions/outputType", default: "web" }
536
+ }
537
+ },
538
+ chunkingRun: {
539
+ type: "object",
540
+ additionalProperties: false,
541
+ properties: {
542
+ name: { description: "Label of the run, for [[chunking]] arrays: names it in manifest.json, progress and errors, and for `opm chunk --run`.", type: "string" },
543
+ input: { description: "What the run reads: an XML file, a directory or a glob pattern (** matches any number of subdirectories).", type: "string", examples: ["data/**/*.xml"] },
544
+ odd: { description: "ODD used for chunking; falls back to [transform] odd.", type: "string" },
545
+ xpath: { description: "XPath selecting the chunk root elements.", type: "string", examples: ["//text/body/div"] },
546
+ xpath_dynamic: { description: "The xpath the consuming pb-view sends, when it differs from xpath (pb-view index keys only).", type: "string" },
547
+ selector: { description: "Dotted path of a Python callable that selects the chunks, instead of xpath.", type: "string", examples: ["opm.navigation.tei_pb_chunks"] },
548
+ depth: { description: "Maximum heading depth for splitting.", type: "integer", minimum: 1, default: 1 },
549
+ output_dir: { description: "Output directory, relative to the project root. Only the first run may set it.", type: "string", default: "chunks" },
550
+ template: { description: "Page template for chunk pages; defaults to the [transform.web] template.", type: "string" },
551
+ index_template: { description: "Page template for the collection index written when chunking several documents.", type: "string" },
552
+ index_title: { description: "Heading of the collection index; defaults to the input directory name.", type: "string" },
553
+ assets: {
554
+ description: "Files copied into <output>/assets/ instead of the [transform.web] assets; [] for none. An entry may be a glob.",
555
+ type: "array",
556
+ items: { type: "string" }
557
+ },
558
+ file_pattern: { description: "File name of chunk pages, with {xml_id}, {ident}, {index} or {stem}. Default: 001.html, 002.html, \u2026", type: "string", examples: ["{xml_id}.html", "{index:03d}.html"] },
559
+ document_name: { description: "XPath naming each document's output directory (default: its file name); a / in the name nests it.", type: "string", examples: ["/TEI/@xml:id"] },
560
+ link_pattern: { description: "URL of cross-chunk links, with {file}, {stem}, {anchor}, {doc} or {doc_stem}. Default: {file}#{anchor}.", type: "string", examples: ["/{doc}/{file}"] },
561
+ webcomponents: { description: "Web components for this run's pages only; defaults to [transform.web] webcomponents.", type: "boolean" },
562
+ fragments: {
563
+ description: "Fragments rendered beside the chunks, such as a table of contents or a register.",
564
+ type: "array",
565
+ items: { $ref: "#/definitions/fragment" }
566
+ },
567
+ view: { description: "pb-view view mode in index keys (--format pb-view).", type: "string", enum: ["div", "page", "single"], default: "div" },
568
+ map: { description: "pb-view map parameter in index keys (--format pb-view).", type: "string" },
569
+ parameters: { description: "pb-view user parameters in index keys (--format pb-view), emitted as user.<key>=<value>.", type: "object" },
570
+ doc_path: { description: "Subdirectory for --format pb-view data; must match the path of the consuming pb-document.", type: "string" }
571
+ }
572
+ },
573
+ page: {
574
+ type: "object",
575
+ additionalProperties: false,
576
+ required: ["path"],
577
+ properties: {
578
+ path: { description: "Output path below the chunk output root. With {xml_id}, {ident}, {stem} or {index}, one page per node xpath selects.", type: "string", examples: ["about.html", "places/{xml_id}.html"] },
579
+ template: { description: "Page template; defaults to the first chunking run's.", type: "string" },
580
+ context: { description: "Template context for this page only, over [context].", type: "object" },
581
+ source: { description: "XML file or directory the page is generated from. Without one the page is static: only the template is rendered.", type: "string" },
582
+ xpath: { description: "XPath selecting the nodes rendered into the page, from source.", type: "string" },
583
+ selector: { description: "Dotted path of a chunk selector, instead of xpath.", type: "string" },
584
+ odd: { description: "ODD for this page; defaults to the first chunking run's.", type: "string" },
585
+ parameters: { description: "Values of the ODD's $parameters for this page, over [transform.parameters].", type: "object" },
586
+ fragments: {
587
+ description: "Fragments rendered into the page, as for chunks.",
588
+ type: "array",
589
+ items: { $ref: "#/definitions/fragment" }
590
+ },
591
+ enabled: { description: "false switches the page off, e.g. one a profile contributes with the same path.", type: "boolean", default: true }
592
+ }
593
+ },
594
+ index: {
595
+ description: "Search index written by `opm index`.",
596
+ type: "object",
597
+ additionalProperties: false,
598
+ properties: {
599
+ granularity: { description: "split: one record per unit, cut to max_chars, for vector search; page: one record per published page, for site search.", type: "string", enum: ["split", "page"], default: "split" },
600
+ max_chars: { description: "Maximum length of a passage.", type: "integer", minimum: 1, default: 1500 },
601
+ min_chars: { description: "Records shorter than this are not indexed on their own.", type: "integer", minimum: 0, default: 40 },
602
+ overlap: { description: "Records carried over from the end of one part into the next, for context (split only).", type: "integer", minimum: 0, default: 1 },
603
+ units: {
604
+ description: "JSON records that open a passage; declaring any replaces the default walk over titled divisions.",
605
+ type: "array",
606
+ items: {
607
+ type: "object",
608
+ additionalProperties: false,
609
+ required: ["name"],
610
+ properties: {
611
+ name: { type: "string" },
612
+ behaviours: { description: "ODD behaviours whose records open a unit.", $ref: "#/definitions/stringOrList" },
613
+ elements: { description: "Elements whose records open a unit.", $ref: "#/definitions/stringOrList" },
614
+ models: { description: "ODD models whose records open a unit.", $ref: "#/definitions/stringOrList" },
615
+ emit: { description: "false: use the match only as context, e.g. a heading for the following paragraph, and write no record of its own.", type: "boolean", default: true },
616
+ min_chars: { description: "Overrides [index] min_chars for this unit.", type: "integer", minimum: 0 }
617
+ }
618
+ }
619
+ },
620
+ fields: {
621
+ description: "Material pulled out of passages: a facet for filtering, a record of its own, or a chunking fragment copied onto every record of a page.",
622
+ type: "array",
623
+ items: {
624
+ type: "object",
625
+ additionalProperties: false,
626
+ required: ["name"],
627
+ properties: {
628
+ name: { type: "string" },
629
+ fragment: { description: "Name of a [[chunking.fragments]] entry, copied onto every record of its page. Cannot be mixed with behaviours, elements or models.", type: "string" },
630
+ behaviours: { description: "ODD behaviours whose records the field takes its text from.", $ref: "#/definitions/stringOrList" },
631
+ elements: { description: "Elements whose records the field takes its text from.", $ref: "#/definitions/stringOrList" },
632
+ models: { description: "ODD models whose records the field takes its text from.", $ref: "#/definitions/stringOrList" },
633
+ metadata: { description: "true: copy the text onto the passage, for filtering; false: write it as a record of its own.", type: "boolean", default: true },
634
+ inline: { description: "Whether the text stays in the passage's own text; defaults to metadata.", type: "boolean" }
635
+ }
636
+ }
637
+ }
638
+ }
639
+ }
640
+ }
641
+ };
642
+
643
+ // src/core/tomlScan.ts
644
+ var isBare = (c) => /[A-Za-z0-9_-]/.test(c);
645
+ var isSpace = (c) => c === " " || c === " ";
646
+ function readKey(text, i, stop) {
647
+ const parts = [];
648
+ for (; ; ) {
649
+ while (isSpace(text[i])) i++;
650
+ const c = text[i];
651
+ if (c === '"' || c === "'") {
652
+ let j = i + 1, part = "";
653
+ while (j < text.length && text[j] !== c && text[j] !== "\n") {
654
+ if (c === '"' && text[j] === "\\" && j + 1 < text.length) {
655
+ part += text[j + 1];
656
+ j += 2;
657
+ continue;
658
+ }
659
+ part += text[j++];
660
+ }
661
+ if (text[j] !== c) return null;
662
+ parts.push(part);
663
+ i = j + 1;
664
+ } else if (c !== void 0 && isBare(c)) {
665
+ const start = i;
666
+ while (i < text.length && isBare(text[i])) i++;
667
+ parts.push(text.slice(start, i));
668
+ } else {
669
+ return null;
670
+ }
671
+ while (isSpace(text[i])) i++;
672
+ if (text[i] === ".") {
673
+ i++;
674
+ continue;
675
+ }
676
+ return i < text.length && stop(text[i]) ? { parts, end: i } : null;
677
+ }
678
+ }
679
+ function skipValue(text, i) {
680
+ let depth = 0, contentEnd = -1;
681
+ while (i < text.length) {
682
+ const c = text[i];
683
+ if (c === '"' || c === "'") {
684
+ if (text.startsWith(c.repeat(3), i)) {
685
+ const end = text.indexOf(c.repeat(3), i + 3);
686
+ i = end < 0 ? text.length : end + 3;
687
+ while (text[i] === c) i++;
688
+ } else {
689
+ i++;
690
+ while (i < text.length && text[i] !== c && text[i] !== "\n") i += c === '"' && text[i] === "\\" ? 2 : 1;
691
+ if (text[i] === c) i++;
692
+ }
693
+ continue;
694
+ }
695
+ if (c === "#") {
696
+ if (depth === 0 && contentEnd < 0) contentEnd = i;
697
+ while (i < text.length && text[i] !== "\n") i++;
698
+ continue;
699
+ }
700
+ if (c === "\n" && depth === 0) break;
701
+ if (c === "[" || c === "{") depth++;
702
+ else if ((c === "]" || c === "}") && depth) depth--;
703
+ i++;
704
+ }
705
+ let valueTo = contentEnd < 0 ? i : contentEnd;
706
+ while (valueTo > 0 && /\s/.test(text[valueTo - 1])) valueTo--;
707
+ return { valueTo, next: i };
708
+ }
709
+ function scanToml(text) {
710
+ const tables = [], keys = [];
711
+ const counts = /* @__PURE__ */ new Map();
712
+ const id = (p) => JSON.stringify(p);
713
+ const resolve = (parts, array) => {
714
+ const path = [];
715
+ parts.forEach((part, n) => {
716
+ path.push(part);
717
+ const last = n === parts.length - 1;
718
+ if (last && array) {
719
+ const count = counts.get(id(path)) ?? 0;
720
+ counts.set(id(path), count + 1);
721
+ path.push(count);
722
+ } else if (!last && counts.has(id(path))) {
723
+ path.push(counts.get(id(path)) - 1);
724
+ }
725
+ });
726
+ return path;
727
+ };
728
+ let table = [];
729
+ let i = 0;
730
+ while (i < text.length) {
731
+ const c = text[i];
732
+ if (c === "\n" || isSpace(c) || c === "\r") {
733
+ i++;
734
+ continue;
735
+ }
736
+ const eol = () => {
737
+ const n = text.indexOf("\n", i);
738
+ return n < 0 ? text.length : n;
739
+ };
740
+ if (c === "#") {
741
+ i = eol();
742
+ continue;
743
+ }
744
+ if (c === "[") {
745
+ const array = text[i + 1] === "[";
746
+ const key2 = readKey(text, i + (array ? 2 : 1), (ch) => ch === "]");
747
+ if (key2 && (!array || text[key2.end + 1] === "]")) {
748
+ const end = key2.end + (array ? 2 : 1);
749
+ table = resolve(key2.parts, array);
750
+ tables.push({ path: table, from: i, to: end, array });
751
+ }
752
+ i = eol();
753
+ continue;
754
+ }
755
+ const key = readKey(text, i, (ch) => ch === "=");
756
+ if (!key) {
757
+ i = eol();
758
+ continue;
759
+ }
760
+ let keyTo = key.end;
761
+ while (keyTo > i && isSpace(text[keyTo - 1])) keyTo--;
762
+ let v = key.end + 1;
763
+ while (isSpace(text[v])) v++;
764
+ const { valueTo, next } = skipValue(text, v);
765
+ keys.push({ path: [...table, ...key.parts], from: i, to: keyTo, valueFrom: v, valueTo: Math.max(v, valueTo) });
766
+ i = Math.max(next, i + 1);
767
+ }
768
+ return { tables, keys };
769
+ }
770
+ function tableAt(scan, offset) {
771
+ let found;
772
+ for (const t of scan.tables) if (t.from <= offset) found = t;
773
+ else break;
774
+ return found;
775
+ }
776
+
777
+ // src/core/opmToml.ts
778
+ var OPM_SCHEMA = opm_schema_default;
779
+ var isOpmToml = (uri) => /(^|[/\\])opm\.toml$/.test(uri);
780
+ function deref(s, root) {
781
+ let seen = 0;
782
+ while (s.$ref && seen++ < 20) {
783
+ const target = s.$ref.replace(/^#\/definitions\//, "");
784
+ const { $ref: _, ...rest } = s;
785
+ s = { ...root.definitions?.[target], ...rest };
786
+ }
787
+ return s;
788
+ }
789
+ var typesOf = (s) => s.type === void 0 ? [] : Array.isArray(s.type) ? s.type : [s.type];
790
+ var branches = (s, root) => {
791
+ s = deref(s, root);
792
+ if (!s.anyOf) return [s];
793
+ const { anyOf, ...own } = s;
794
+ return anyOf.flatMap((b) => branches(b, root)).map((b) => ({ ...b, description: own.description ?? b.description, deprecated: own.deprecated ?? b.deprecated }));
795
+ };
796
+ function schemaAt(path, root = OPM_SCHEMA) {
797
+ let s = deref(root, root);
798
+ for (const seg of path) {
799
+ if (!s) return void 0;
800
+ const options = branches(s, root);
801
+ if (typeof seg === "number") {
802
+ const arr = options.find((b) => typesOf(b).includes("array"));
803
+ s = arr?.items && deref(arr.items, root);
804
+ } else {
805
+ const obj = options.find((b) => typesOf(b).includes("object") || b.properties);
806
+ const next = obj?.properties?.[seg] ?? obj?.additionalProperties;
807
+ s = next && typeof next === "object" ? { ...deref(next, root), ...obj?.properties?.[seg]?.description ? { description: obj.properties[seg].description } : {} } : void 0;
808
+ }
809
+ }
810
+ return s;
811
+ }
812
+ var kindOf = (v) => typeof v === "string" ? "string" : typeof v === "boolean" ? "boolean" : typeof v === "number" || typeof v === "bigint" ? Number.isInteger(Number(v)) ? "integer" : "number" : Array.isArray(v) ? "array" : v && typeof v === "object" && !(v instanceof Date) && !("toISOString" in v) ? "object" : "datetime";
813
+ var accepts = (type, kind) => type === kind || type === "number" && kind === "integer";
814
+ var NOUN = {
815
+ string: "a string",
816
+ integer: "a whole number",
817
+ number: "a number",
818
+ boolean: "true or false",
819
+ array: "a list",
820
+ object: "a table",
821
+ datetime: "a date"
822
+ };
823
+ function expected(options, root) {
824
+ const words = options.flatMap((b) => typesOf(b).map((t) => {
825
+ if (t === "array" && b.items) {
826
+ const item = typesOf(deref(b.items, root))[0];
827
+ return item ? `a list of ${NOUN[item].replace(/^an? /, "")}s` : NOUN.array;
828
+ }
829
+ return NOUN[t] ?? t;
830
+ }));
831
+ return [...new Set(words)].join(" or ");
832
+ }
833
+ function tableName(path) {
834
+ const names = path.filter((s) => typeof s === "string");
835
+ const array = typeof path[path.length - 1] === "number";
836
+ return names.length ? array ? `[[${names.join(".")}]]` : `[${names.join(".")}]` : "the top level";
837
+ }
838
+ var keyName = (path) => String(path.filter((s) => typeof s === "string").pop() ?? "");
839
+ function distance(a, b) {
840
+ const d = Array.from({ length: b.length + 1 }, (_, j) => j);
841
+ for (let i = 1; i <= a.length; i++) {
842
+ let prev = d[0];
843
+ d[0] = i;
844
+ for (let j = 1; j <= b.length; j++) {
845
+ const tmp = d[j];
846
+ d[j] = Math.min(d[j] + 1, d[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
847
+ prev = tmp;
848
+ }
849
+ }
850
+ return d[b.length];
851
+ }
852
+ function check(value, s, path, root, errors) {
853
+ const options = branches(s, root);
854
+ const kind = kindOf(value);
855
+ const fits = options.filter((b) => !typesOf(b).length || typesOf(b).some((t) => accepts(t, kind)));
856
+ if (!fits.length) {
857
+ const name = path.length ? `"${keyName(path)}"` : "opm.toml";
858
+ errors.push({ path, code: "type", severity: "error", message: `${name} should be ${expected(options, root)}, not ${NOUN[kind] ?? kind}.` });
859
+ return;
860
+ }
861
+ let chosen = fits[0];
862
+ if (fits.length > 1) {
863
+ for (const b of fits) {
864
+ const trial = [];
865
+ checkOne(value, b, path, root, trial);
866
+ if (!trial.some((e) => e.severity === "error")) {
867
+ chosen = b;
868
+ break;
869
+ }
870
+ }
871
+ }
872
+ checkOne(value, chosen, path, root, errors);
873
+ }
874
+ function checkOne(value, s, path, root, errors) {
875
+ if (s.deprecated && path.length) {
876
+ errors.push({ path, code: "deprecated", severity: "warning", message: s.description ?? `"${keyName(path)}" is deprecated.` });
877
+ }
878
+ if (s.enum && !s.enum.includes(value)) {
879
+ errors.push({ path, code: "enum", severity: "error", message: `"${keyName(path)}" should be one of ${s.enum.map((v) => JSON.stringify(v)).join(", ")}.` });
880
+ }
881
+ if (s.minimum !== void 0 && (typeof value === "number" || typeof value === "bigint") && Number(value) < s.minimum) {
882
+ errors.push({ path, code: "range", severity: "error", message: `"${keyName(path)}" should be at least ${s.minimum}.` });
883
+ }
884
+ if (Array.isArray(value) && s.items) {
885
+ value.forEach((item, n) => check(item, s.items, [...path, n], root, errors));
886
+ } else if (kindOf(value) === "object") {
887
+ const obj = value;
888
+ for (const req of s.required ?? []) {
889
+ if (!(req in obj)) errors.push({ path, code: "required", severity: "error", message: `${tableName(path)} needs "${req}".` });
890
+ }
891
+ for (const [k, v] of Object.entries(obj)) {
892
+ const prop = s.properties?.[k];
893
+ if (prop) {
894
+ check(v, prop, [...path, k], root, errors);
895
+ continue;
896
+ }
897
+ if (s.additionalProperties === false) {
898
+ const known = Object.keys(s.properties ?? {});
899
+ const close = known.map((n) => [n, distance(k, n)]).filter(([, d]) => d <= 2).sort((a, b) => a[1] - b[1])[0];
900
+ errors.push({
901
+ path: [...path, k],
902
+ code: "unknown",
903
+ severity: "warning",
904
+ message: `opm does not know "${k}" in ${tableName(path)}.${close ? ` Did you mean "${close[0]}"?` : ""}`
905
+ });
906
+ } else if (s.additionalProperties && typeof s.additionalProperties === "object") {
907
+ check(v, s.additionalProperties, [...path, k], root, errors);
908
+ }
909
+ }
910
+ }
911
+ }
912
+ var startsWith = (path, prefix) => prefix.length <= path.length && prefix.every((s, i) => path[i] === s);
913
+ var same = (a, b) => a.length === b.length && startsWith(a, b);
914
+ function rangeOf(scan, e) {
915
+ const key = scan.keys.find((k) => same(k.path, e.path));
916
+ if (key) return e.code === "unknown" || e.code === "deprecated" ? { from: key.from, to: key.to } : { from: key.valueFrom, to: key.valueTo };
917
+ const table = scan.tables.find((t) => same(t.path, e.path)) ?? scan.tables.find((t) => startsWith(t.path, e.path));
918
+ if (table) return { from: table.from, to: table.to };
919
+ const below = scan.keys.find((k) => startsWith(k.path, e.path));
920
+ if (below) return { from: below.from, to: below.to };
921
+ let holder;
922
+ for (const k of scan.keys) if (startsWith(e.path, k.path)) holder = { from: k.valueFrom, to: k.valueTo };
923
+ return holder ?? { from: 0, to: 0 };
924
+ }
925
+ function checkOpmToml(text, schema = OPM_SCHEMA) {
926
+ let data;
927
+ try {
928
+ data = parse2(text);
929
+ } catch (err) {
930
+ if (!(err instanceof TomlError)) throw err;
931
+ const lines = text.split("\n");
932
+ const line = Math.max(0, Math.min(lines.length - 1, err.line - 1));
933
+ const start = lines.slice(0, line).reduce((n, l) => n + l.length + 1, 0);
934
+ const from = start + Math.max(0, Math.min(lines[line].length, err.column - 1));
935
+ const message = err.message.split("\n")[0].replace(/^Invalid TOML document: /, "");
936
+ return [{ from, to: Math.max(from, start + lines[line].length), message: `Not valid TOML: ${message}.`, severity: "error", code: "syntax" }];
937
+ }
938
+ const errors = [];
939
+ check(data, schema, [], schema, errors);
940
+ const scan = scanToml(text);
941
+ return errors.map((e) => ({ ...rangeOf(scan, e), message: e.message, severity: e.severity, code: e.code }));
942
+ }
943
+ function summary(s, root) {
944
+ const options = branches(s, root);
945
+ if (options.length === 1 && options[0].enum) return options[0].enum.map((v) => JSON.stringify(v)).join(" | ");
946
+ return expected(options, root).replace(/^an? /, "").replace(/ or an? /g, " or ");
947
+ }
948
+ function template(s, root) {
949
+ const first = branches(s, root)[0] ?? {};
950
+ const t = typesOf(first)[0];
951
+ if (first.enum?.length) return { text: JSON.stringify(first.enum[0]), cursor: 1 };
952
+ if (t === "string") return { text: '""', cursor: 1 };
953
+ if (t === "array") {
954
+ const item = first.items && typesOf(deref(first.items, root))[0];
955
+ return item === "string" ? { text: '[""]', cursor: 2 } : { text: "[]", cursor: 1 };
956
+ }
957
+ if (t === "object") return { text: "{ }", cursor: 2 };
958
+ if (t === "boolean") return { text: String(first.default ?? true), cursor: String(first.default ?? true).length };
959
+ return { text: "", cursor: 0 };
960
+ }
961
+ var isTable = (s, root) => branches(s, root).some((b) => typesOf(b).includes("object") || b.properties);
962
+ var isTableArray = (s, root) => branches(s, root).some((b) => {
963
+ if (!typesOf(b).includes("array") || !b.items) return false;
964
+ return isTable(b.items, root);
965
+ });
966
+ var isHeaderOnly = (s, root) => branches(s, root).every((b) => typesOf(b).includes("object") && !!b.properties || typesOf(b).includes("array") && !!b.items && isTable(b.items, root));
967
+ function headers(root) {
968
+ const out = [];
969
+ const walk = (s, names, depth) => {
970
+ if (depth > 4) return;
971
+ for (const b of branches(s, root)) {
972
+ for (const [k, raw] of Object.entries(b.properties ?? {})) {
973
+ const p = deref(raw, root);
974
+ if (p.deprecated || raw.deprecated) continue;
975
+ const ns = [...names, k];
976
+ const desc = { ...p, description: raw.description ?? p.description };
977
+ if (isTable(p, root)) {
978
+ out.push({ name: ns.join("."), array: false, schema: desc });
979
+ walk(p, ns, depth + 1);
980
+ }
981
+ if (isTableArray(p, root)) {
982
+ out.push({ name: ns.join("."), array: true, schema: desc });
983
+ const items = branches(p, root).find((x) => typesOf(x).includes("array"))?.items;
984
+ if (items) walk(items, ns, depth + 1);
985
+ }
986
+ }
987
+ }
988
+ };
989
+ walk(root, [], 0);
990
+ return out;
991
+ }
992
+ function completeOpmToml(text, offset, schema = OPM_SCHEMA) {
993
+ const lineStart = text.lastIndexOf("\n", offset - 1) + 1;
994
+ const before = text.slice(lineStart, offset);
995
+ if (/^\s*#/.test(before) || /#[^"']*$/.test(before)) return null;
996
+ const scan = scanToml(text);
997
+ const header = /^\s*(\[\[?)\s*([A-Za-z0-9_.-]*)$/.exec(before);
998
+ if (header) {
999
+ const from2 = offset - header[2].length;
1000
+ const lineEnd = text.indexOf("\n", offset);
1001
+ const rest = text.slice(offset, lineEnd < 0 ? text.length : lineEnd);
1002
+ const closing = /^[A-Za-z0-9_.-]*\]{1,2}/.exec(rest);
1003
+ const to = closing ? offset + closing[0].length : offset;
1004
+ const double = header[1] === "[[";
1005
+ return {
1006
+ from: from2,
1007
+ to,
1008
+ options: headers(schema).filter((h) => h.array === double).map((h) => ({
1009
+ label: h.name,
1010
+ kind: "table",
1011
+ detail: h.array ? "array of tables" : "table",
1012
+ info: h.schema.description,
1013
+ apply: h.name + (double ? "]]" : "]")
1014
+ }))
1015
+ };
1016
+ }
1017
+ const table = tableAt(scan, offset);
1018
+ const tablePath = table?.path ?? [];
1019
+ const eq = before.indexOf("=");
1020
+ if (eq >= 0) {
1021
+ const key = readKey(before, 0, (ch) => ch === "=");
1022
+ if (!key) return null;
1023
+ let s2 = schemaAt([...tablePath, ...key.parts], schema);
1024
+ if (!s2) return null;
1025
+ let after = before.slice(eq + 1);
1026
+ if ((after.match(/\[/g)?.length ?? 0) > (after.match(/\]/g)?.length ?? 0)) {
1027
+ const arr = branches(s2, schema).find((b) => typesOf(b).includes("array"));
1028
+ if (!arr?.items) return null;
1029
+ s2 = deref(arr.items, schema);
1030
+ after = after.slice(after.lastIndexOf(",") >= 0 && after.lastIndexOf(",") > after.lastIndexOf("[") ? after.lastIndexOf(",") + 1 : after.lastIndexOf("[") + 1);
1031
+ }
1032
+ const word = /("?)([^"\s,[\]{}=]*)$/.exec(after);
1033
+ const quoted = word[1] === '"';
1034
+ const from2 = offset - word[2].length - (quoted ? 1 : 0);
1035
+ const values = /* @__PURE__ */ new Map();
1036
+ for (const b of branches(s2, schema)) {
1037
+ for (const v of b.enum ?? []) values.set(JSON.stringify(v), b.description);
1038
+ if (typesOf(b).includes("boolean")) {
1039
+ values.set("true", void 0);
1040
+ values.set("false", void 0);
1041
+ }
1042
+ for (const v of b.examples ?? []) values.set(JSON.stringify(v), "example");
1043
+ if (b.default !== void 0 && typeof b.default !== "object") values.set(JSON.stringify(b.default), "default");
1044
+ }
1045
+ if (!values.size) return null;
1046
+ const to = quoted && text[offset] === '"' ? offset + 1 : offset;
1047
+ return {
1048
+ from: from2,
1049
+ to,
1050
+ options: [...values].map(([v, note]) => ({ label: v, kind: "value", detail: note === "example" || note === "default" ? note : void 0, apply: v }))
1051
+ };
1052
+ }
1053
+ const typed = /^\s*([A-Za-z0-9_.-]*)$/.exec(before);
1054
+ if (!typed) return null;
1055
+ const dots = typed[1].split(".");
1056
+ const partial = dots.pop();
1057
+ const parent = [...tablePath, ...dots.filter(Boolean)];
1058
+ const s = schemaAt(parent, schema);
1059
+ const from = offset - partial.length;
1060
+ if (!table && !dots.filter(Boolean).length) {
1061
+ return {
1062
+ from,
1063
+ to: offset,
1064
+ options: headers(schema).map((h) => ({
1065
+ label: h.array ? `[[${h.name}]]` : `[${h.name}]`,
1066
+ kind: "table",
1067
+ detail: h.array ? "array of tables" : "table",
1068
+ info: h.schema.description,
1069
+ apply: h.array ? `[[${h.name}]]` : `[${h.name}]`
1070
+ }))
1071
+ };
1072
+ }
1073
+ if (!s) return null;
1074
+ const present = new Set(scan.keys.filter((k) => startsWith(k.path, parent) && k.path.length > parent.length).map((k) => k.path[parent.length]));
1075
+ for (const t of scan.tables) if (startsWith(t.path, parent) && t.path.length > parent.length) present.add(t.path[parent.length]);
1076
+ const options = [];
1077
+ for (const b of branches(s, schema)) {
1078
+ for (const [name, raw] of Object.entries(b.properties ?? {})) {
1079
+ const p = deref(raw, schema);
1080
+ if (present.has(name) || p.deprecated || raw.deprecated) continue;
1081
+ if (isHeaderOnly(p, schema)) continue;
1082
+ const value = template(p, schema);
1083
+ options.push({
1084
+ label: name,
1085
+ kind: "key",
1086
+ detail: summary(p, schema),
1087
+ info: raw.description ?? p.description,
1088
+ apply: `${name} = ${value.text}`,
1089
+ cursor: name.length + 3 + value.cursor
1090
+ });
1091
+ }
1092
+ }
1093
+ return { from, to: offset, options };
1094
+ }
1095
+ function describeOpmToml(text, offset, schema = OPM_SCHEMA) {
1096
+ const scan = scanToml(text);
1097
+ const table = scan.tables.find((t) => t.from <= offset && offset <= t.to);
1098
+ const key = table ? void 0 : scan.keys.find((k) => k.from <= offset && offset <= k.to);
1099
+ const hit = table ?? key;
1100
+ if (!hit) return null;
1101
+ let path = hit.path;
1102
+ if (key) {
1103
+ const parts = readKey(text, key.from, (ch) => ch === "=")?.parts ?? [];
1104
+ const prefixLen = key.path.length - parts.length;
1105
+ let at = key.from, n = 0;
1106
+ for (; n < parts.length - 1; n++) {
1107
+ at = text.indexOf(parts[n], at) + parts[n].length;
1108
+ if (offset <= at) break;
1109
+ }
1110
+ path = key.path.slice(0, prefixLen + n + 1);
1111
+ } else if (typeof path[path.length - 1] === "number") {
1112
+ path = path.slice(0, -1);
1113
+ }
1114
+ const s = schemaAt(path, schema);
1115
+ if (!s) return null;
1116
+ const extras = [summary(s, schema)];
1117
+ const def = branches(s, schema).find((b) => b.default !== void 0)?.default;
1118
+ if (def !== void 0) extras.push(`default ${JSON.stringify(def)}`);
1119
+ return {
1120
+ from: hit.from,
1121
+ to: hit.to,
1122
+ title: table ? tableName(table.path) : keyName(path),
1123
+ detail: extras.join(", "),
1124
+ info: s.description
1125
+ };
1126
+ }
1127
+
1128
+ // src/core/elements.ts
1129
+ function elements(text) {
1130
+ const tags = scanTags(text), pair = pairs(tags), out = [];
1131
+ tags.forEach((t, i) => {
1132
+ if (t.kind === "empty") out.push({ name: t.name, from: t.from, to: t.to, open: t });
1133
+ else if (t.kind === "open" && pair.has(i)) {
1134
+ const close = tags[pair.get(i)];
1135
+ out.push({ name: t.name, from: t.from, to: close.to, open: t, close });
1136
+ }
1137
+ });
1138
+ return out;
1139
+ }
1140
+ function elementsAround(text, from, to = from) {
1141
+ return elements(text).filter((e) => e.from <= from && e.to >= to).sort((a, b) => a.to - a.from - (b.to - b.from));
1142
+ }
1143
+ function elementAround(text, from, to, outer) {
1144
+ return elementsAround(text, from, to).find((e) => !outer || from === to || e.from < from || e.to > to);
1145
+ }
1146
+ function selectElement(text, from, to) {
1147
+ const e = elementAround(text, from, to, true);
1148
+ return e ? { changes: [], selection: { anchor: e.from, head: e.to } } : null;
1149
+ }
1150
+ function removeElementTags(text, from, to) {
1151
+ const e = elementAround(text, from, to, false);
1152
+ if (!e) return null;
1153
+ const { open, close } = e;
1154
+ if (!close) return { changes: [{ from: open.from, to: open.to, insert: "" }], selection: { anchor: open.from, head: open.from } };
1155
+ const length = open.to - open.from;
1156
+ return {
1157
+ changes: [{ from: open.from, to: open.to, insert: "" }, { from: close.from, to: close.to, insert: "" }],
1158
+ selection: { anchor: open.from, head: close.from - length }
1159
+ };
1160
+ }
1161
+ function splitElement(text, pos) {
1162
+ const e = elementsAround(text, pos).find((x) => x.close && pos >= x.open.to && pos <= x.close.from);
1163
+ if (!e) return null;
1164
+ const start = text.slice(e.open.from, e.open.to).replace(/\s(xml:)?id\s*=\s*("[^"]*"|'[^']*')/g, "");
1165
+ const insert = `</${e.name}>${start}`;
1166
+ return { changes: [{ from: pos, to: pos, insert }], selection: { anchor: pos + insert.length, head: pos + insert.length } };
1167
+ }
1168
+ function surroundWithElement(from, to, tag) {
1169
+ const start = `<${tag.trim()}>`, end = `</${tag.trim().split(/\s/)[0]}>`;
1170
+ return {
1171
+ changes: [{ from, to: from, insert: start }, { from: to, to, insert: end }],
1172
+ selection: { anchor: from + start.length, head: to + start.length }
1173
+ };
1174
+ }
1175
+ export {
1176
+ DEFAULT_SCHEMA_FILES,
1177
+ OPM_SCHEMA,
1178
+ PUBLIC_SCHEMA_URLS,
1179
+ RNG_NS,
1180
+ checkOpmToml,
1181
+ closeTagAt,
1182
+ completeOpmToml,
1183
+ describeOpmToml,
1184
+ elementAround,
1185
+ elements,
1186
+ elementsAround,
1187
+ isOdd,
1188
+ isOpmToml,
1189
+ isRngModel,
1190
+ matchingTags,
1191
+ openElementAt,
1192
+ pairs,
1193
+ projectRoot,
1194
+ publicSchema,
1195
+ readToml,
1196
+ relativeHref,
1197
+ removeElementTags,
1198
+ scanTags,
1199
+ schemaAt,
1200
+ schemaFor,
1201
+ selectElement,
1202
+ setToml,
1203
+ splitElement,
1204
+ surroundWithElement,
1205
+ tomlString,
1206
+ unsetToml,
1207
+ vocabulary,
1208
+ xmlModelEdits,
1209
+ xmlModels
1210
+ };
1211
+ //# sourceMappingURL=edit.js.map