@teipublisher/oddity-language-server 0.1.0 → 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.
@@ -0,0 +1,432 @@
1
+ // ── opm.toml: checking, completion and hover from opm's JSON Schema ───────
2
+ // schema/opm/opm.schema.json ships with opm (npm run schemas copies it), so
3
+ // what the editor knows about opm.toml follows opm. The checker understands
4
+ // the part of JSON Schema that file uses: type, properties,
5
+ // additionalProperties, required, items, enum, anyOf, minimum, $ref and
6
+ // deprecated.
7
+ import { parse, TomlError } from 'smol-toml';
8
+ import opmSchema from '../../schema/opm/opm.schema.json' with { type: 'json' };
9
+ import { scanToml, tableAt, readKey, type Seg, type TomlScan } from './tomlScan.ts';
10
+
11
+ export interface Schema {
12
+ type?: string | string[];
13
+ description?: string;
14
+ properties?: Record<string, Schema>;
15
+ additionalProperties?: boolean | Schema;
16
+ required?: string[];
17
+ items?: Schema;
18
+ enum?: unknown[];
19
+ anyOf?: Schema[];
20
+ minimum?: number;
21
+ default?: unknown;
22
+ examples?: unknown[];
23
+ deprecated?: boolean;
24
+ $ref?: string;
25
+ definitions?: Record<string, Schema>;
26
+ }
27
+
28
+ export const OPM_SCHEMA = opmSchema as Schema;
29
+
30
+ /** Whether a document is an opm project config, by its name. */
31
+ export const isOpmToml = (uri: string): boolean => /(^|[/\\])opm\.toml$/.test(uri);
32
+
33
+ export interface TomlProblem {
34
+ from: number;
35
+ to: number;
36
+ message: string;
37
+ severity: 'error' | 'warning';
38
+ /** syntax, unknown, type, enum, required, range or deprecated. */
39
+ code: string;
40
+ }
41
+
42
+ // ── schema navigation ────────────────────────────────────────────────────
43
+
44
+ function deref(s: Schema, root: Schema): Schema {
45
+ let seen = 0;
46
+ while (s.$ref && seen++ < 20) {
47
+ const target = s.$ref.replace(/^#\/definitions\//, '');
48
+ const { $ref: _, ...rest } = s;
49
+ s = { ...root.definitions?.[target], ...rest };
50
+ }
51
+ return s;
52
+ }
53
+
54
+ const typesOf = (s: Schema): string[] => (s.type === undefined ? [] : Array.isArray(s.type) ? s.type : [s.type]);
55
+
56
+ /** The anyOf branches of s (or s itself), dereferenced. */
57
+ const branches = (s: Schema, root: Schema): Schema[] => {
58
+ s = deref(s, root);
59
+ if (!s.anyOf) return [s];
60
+ const { anyOf, ...own } = s;
61
+ return anyOf.flatMap(b => branches(b, root)).map(b => ({ ...b, description: own.description ?? b.description, deprecated: own.deprecated ?? b.deprecated }));
62
+ };
63
+
64
+ /** The schema of the value at path, or undefined where the schema says nothing. */
65
+ export function schemaAt(path: Seg[], root: Schema = OPM_SCHEMA): Schema | undefined {
66
+ let s: Schema | undefined = deref(root, root);
67
+ for (const seg of path) {
68
+ if (!s) return undefined;
69
+ const options = branches(s, root);
70
+ if (typeof seg === 'number') {
71
+ const arr = options.find(b => typesOf(b).includes('array'));
72
+ s = arr?.items && deref(arr.items, root);
73
+ } else {
74
+ const obj = options.find(b => typesOf(b).includes('object') || b.properties);
75
+ const next: Schema | boolean | undefined = obj?.properties?.[seg] ?? obj?.additionalProperties;
76
+ s = next && typeof next === 'object' ? { ...deref(next, root), ...(obj?.properties?.[seg]?.description ? { description: obj.properties[seg].description } : {}) } : undefined;
77
+ }
78
+ }
79
+ return s;
80
+ }
81
+
82
+ // ── checking ─────────────────────────────────────────────────────────────
83
+
84
+ interface SchemaError { path: Seg[]; message: string; code: string; severity: 'error' | 'warning' }
85
+
86
+ const kindOf = (v: unknown): string =>
87
+ typeof v === 'string' ? 'string' : typeof v === 'boolean' ? 'boolean'
88
+ : typeof v === 'number' || typeof v === 'bigint' ? (Number.isInteger(Number(v)) ? 'integer' : 'number')
89
+ : Array.isArray(v) ? 'array' : v && typeof v === 'object' && !(v instanceof Date) && !('toISOString' in (v as object)) ? 'object' : 'datetime';
90
+
91
+ const accepts = (type: string, kind: string) => type === kind || (type === 'number' && kind === 'integer');
92
+
93
+ const NOUN: Record<string, string> = {
94
+ string: 'a string', integer: 'a whole number', number: 'a number', boolean: 'true or false',
95
+ array: 'a list', object: 'a table', datetime: 'a date',
96
+ };
97
+
98
+ /** "a string or a list of strings", from the branches a value could have matched. */
99
+ function expected(options: Schema[], root: Schema): string {
100
+ const words = options.flatMap(b => typesOf(b).map(t => {
101
+ if (t === 'array' && b.items) {
102
+ const item = typesOf(deref(b.items, root))[0];
103
+ return item ? `a list of ${NOUN[item].replace(/^an? /, '')}s` : NOUN.array;
104
+ }
105
+ return NOUN[t] ?? t;
106
+ }));
107
+ return [...new Set(words)].join(' or ');
108
+ }
109
+
110
+ export function tableName(path: Seg[]): string {
111
+ const names = path.filter((s): s is string => typeof s === 'string');
112
+ const array = typeof path[path.length - 1] === 'number';
113
+ return names.length ? (array ? `[[${names.join('.')}]]` : `[${names.join('.')}]`) : 'the top level';
114
+ }
115
+
116
+ const keyName = (path: Seg[]) => String(path.filter(s => typeof s === 'string').pop() ?? '');
117
+
118
+ function distance(a: string, b: string): number {
119
+ const d = Array.from({ length: b.length + 1 }, (_, j) => j);
120
+ for (let i = 1; i <= a.length; i++) {
121
+ let prev = d[0];
122
+ d[0] = i;
123
+ for (let j = 1; j <= b.length; j++) {
124
+ const tmp = d[j];
125
+ d[j] = Math.min(d[j] + 1, d[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
126
+ prev = tmp;
127
+ }
128
+ }
129
+ return d[b.length];
130
+ }
131
+
132
+ function check(value: unknown, s: Schema, path: Seg[], root: Schema, errors: SchemaError[]): void {
133
+ const options = branches(s, root);
134
+ const kind = kindOf(value);
135
+ const fits = options.filter(b => !typesOf(b).length || typesOf(b).some(t => accepts(t, kind)));
136
+ if (!fits.length) {
137
+ const name = path.length ? `"${keyName(path)}"` : 'opm.toml';
138
+ errors.push({ path, code: 'type', severity: 'error', message: `${name} should be ${expected(options, root)}, not ${NOUN[kind] ?? kind}.` });
139
+ return;
140
+ }
141
+ let chosen = fits[0];
142
+ if (fits.length > 1) {
143
+ // the first branch the value passes, else the first that fits its kind
144
+ for (const b of fits) {
145
+ const trial: SchemaError[] = [];
146
+ checkOne(value, b, path, root, trial);
147
+ if (!trial.some(e => e.severity === 'error')) { chosen = b; break; }
148
+ }
149
+ }
150
+ checkOne(value, chosen, path, root, errors);
151
+ }
152
+
153
+ function checkOne(value: unknown, s: Schema, path: Seg[], root: Schema, errors: SchemaError[]): void {
154
+ if (s.deprecated && path.length) {
155
+ errors.push({ path, code: 'deprecated', severity: 'warning', message: s.description ?? `"${keyName(path)}" is deprecated.` });
156
+ }
157
+ if (s.enum && !s.enum.includes(value)) {
158
+ errors.push({ path, code: 'enum', severity: 'error', message: `"${keyName(path)}" should be one of ${s.enum.map(v => JSON.stringify(v)).join(', ')}.` });
159
+ }
160
+ if (s.minimum !== undefined && (typeof value === 'number' || typeof value === 'bigint') && Number(value) < s.minimum) {
161
+ errors.push({ path, code: 'range', severity: 'error', message: `"${keyName(path)}" should be at least ${s.minimum}.` });
162
+ }
163
+ if (Array.isArray(value) && s.items) {
164
+ value.forEach((item, n) => check(item, s.items!, [...path, n], root, errors));
165
+ } else if (kindOf(value) === 'object') {
166
+ const obj = value as Record<string, unknown>;
167
+ for (const req of s.required ?? []) {
168
+ if (!(req in obj)) errors.push({ path, code: 'required', severity: 'error', message: `${tableName(path)} needs "${req}".` });
169
+ }
170
+ for (const [k, v] of Object.entries(obj)) {
171
+ const prop = s.properties?.[k];
172
+ if (prop) { check(v, prop, [...path, k], root, errors); continue; }
173
+ if (s.additionalProperties === false) {
174
+ const known = Object.keys(s.properties ?? {});
175
+ const close = known.map(n => [n, distance(k, n)] as const).filter(([, d]) => d <= 2).sort((a, b) => a[1] - b[1])[0];
176
+ errors.push({
177
+ path: [...path, k], code: 'unknown', severity: 'warning',
178
+ message: `opm does not know "${k}" in ${tableName(path)}.${close ? ` Did you mean "${close[0]}"?` : ''}`,
179
+ });
180
+ } else if (s.additionalProperties && typeof s.additionalProperties === 'object') {
181
+ check(v, s.additionalProperties, [...path, k], root, errors);
182
+ }
183
+ }
184
+ }
185
+ }
186
+
187
+ const startsWith = (path: Seg[], prefix: Seg[]) => prefix.length <= path.length && prefix.every((s, i) => path[i] === s);
188
+ const same = (a: Seg[], b: Seg[]) => a.length === b.length && startsWith(a, b);
189
+
190
+ /** Where an error at path is shown: the key or header that writes it, or the value it sits inside. */
191
+ function rangeOf(scan: TomlScan, e: SchemaError): { from: number; to: number } {
192
+ const key = scan.keys.find(k => same(k.path, e.path));
193
+ if (key) return e.code === 'unknown' || e.code === 'deprecated' ? { from: key.from, to: key.to } : { from: key.valueFrom, to: key.valueTo };
194
+ const table = scan.tables.find(t => same(t.path, e.path)) ?? scan.tables.find(t => startsWith(t.path, e.path));
195
+ if (table) return { from: table.from, to: table.to };
196
+ const below = scan.keys.find(k => startsWith(k.path, e.path));
197
+ if (below) return { from: below.from, to: below.to };
198
+ // inside an inline table or array: the value that holds it
199
+ let holder: { from: number; to: number } | undefined;
200
+ for (const k of scan.keys) if (startsWith(e.path, k.path)) holder = { from: k.valueFrom, to: k.valueTo };
201
+ return holder ?? { from: 0, to: 0 };
202
+ }
203
+
204
+ /** Problems in an opm.toml: TOML syntax first, then what opm's schema says. */
205
+ export function checkOpmToml(text: string, schema: Schema = OPM_SCHEMA): TomlProblem[] {
206
+ let data: unknown;
207
+ try {
208
+ data = parse(text);
209
+ } catch (err) {
210
+ if (!(err instanceof TomlError)) throw err;
211
+ const lines = text.split('\n');
212
+ const line = Math.max(0, Math.min(lines.length - 1, err.line - 1));
213
+ const start = lines.slice(0, line).reduce((n, l) => n + l.length + 1, 0);
214
+ const from = start + Math.max(0, Math.min(lines[line].length, err.column - 1));
215
+ const message = err.message.split('\n')[0].replace(/^Invalid TOML document: /, '');
216
+ return [{ from, to: Math.max(from, start + lines[line].length), message: `Not valid TOML: ${message}.`, severity: 'error', code: 'syntax' }];
217
+ }
218
+ const errors: SchemaError[] = [];
219
+ check(data, schema, [], schema, errors);
220
+ const scan = scanToml(text);
221
+ return errors.map(e => ({ ...rangeOf(scan, e), message: e.message, severity: e.severity, code: e.code }));
222
+ }
223
+
224
+ // ── completion ───────────────────────────────────────────────────────────
225
+
226
+ export interface TomlOption {
227
+ label: string;
228
+ kind: 'table' | 'key' | 'value';
229
+ /** Short type summary, e.g. "string", "true or false". */
230
+ detail?: string;
231
+ /** The description from the schema. */
232
+ info?: string;
233
+ /** Text that replaces from…to. */
234
+ apply: string;
235
+ /** Where the cursor goes, as an offset into apply; the end when missing. */
236
+ cursor?: number;
237
+ }
238
+
239
+ export interface TomlCompletions { from: number; to: number; options: TomlOption[] }
240
+
241
+ function summary(s: Schema, root: Schema): string {
242
+ const options = branches(s, root);
243
+ if (options.length === 1 && options[0].enum) return options[0].enum.map(v => JSON.stringify(v)).join(' | ');
244
+ return expected(options, root).replace(/^an? /, '').replace(/ or an? /g, ' or ');
245
+ }
246
+
247
+ /** A starting value for a key, and where the cursor goes in it. */
248
+ function template(s: Schema, root: Schema): { text: string; cursor: number } {
249
+ const first = branches(s, root)[0] ?? {};
250
+ const t = typesOf(first)[0];
251
+ if (first.enum?.length) return { text: JSON.stringify(first.enum[0]), cursor: 1 };
252
+ if (t === 'string') return { text: '""', cursor: 1 };
253
+ if (t === 'array') {
254
+ const item = first.items && typesOf(deref(first.items, root))[0];
255
+ return item === 'string' ? { text: '[""]', cursor: 2 } : { text: '[]', cursor: 1 };
256
+ }
257
+ if (t === 'object') return { text: '{ }', cursor: 2 };
258
+ if (t === 'boolean') return { text: String(first.default ?? true), cursor: String(first.default ?? true).length };
259
+ return { text: '', cursor: 0 };
260
+ }
261
+
262
+ const isTable = (s: Schema, root: Schema) => branches(s, root).some(b => typesOf(b).includes('object') || b.properties);
263
+ const isTableArray = (s: Schema, root: Schema) => branches(s, root).some(b => {
264
+ if (!typesOf(b).includes('array') || !b.items) return false;
265
+ return isTable(b.items, root);
266
+ });
267
+
268
+ /** Whether a value is only ever written as a [header] or [[header]]: a table with known keys, or an array of tables. */
269
+ const isHeaderOnly = (s: Schema, root: Schema) => branches(s, root).every(b =>
270
+ (typesOf(b).includes('object') && !!b.properties) || (typesOf(b).includes('array') && !!b.items && isTable(b.items, root)));
271
+
272
+ /** Every table a header can name, as [path, array]: [transform.web], [[chunking]], [[chunking.fragments]], … */
273
+ function headers(root: Schema): { name: string; array: boolean; schema: Schema }[] {
274
+ const out: { name: string; array: boolean; schema: Schema }[] = [];
275
+ const walk = (s: Schema, names: string[], depth: number) => {
276
+ if (depth > 4) return;
277
+ for (const b of branches(s, root)) {
278
+ for (const [k, raw] of Object.entries(b.properties ?? {})) {
279
+ const p = deref(raw, root);
280
+ if (p.deprecated || raw.deprecated) continue;
281
+ const ns = [...names, k];
282
+ const desc = { ...p, description: raw.description ?? p.description };
283
+ if (isTable(p, root)) { out.push({ name: ns.join('.'), array: false, schema: desc }); walk(p, ns, depth + 1); }
284
+ if (isTableArray(p, root)) {
285
+ out.push({ name: ns.join('.'), array: true, schema: desc });
286
+ const items = branches(p, root).find(x => typesOf(x).includes('array'))?.items;
287
+ if (items) walk(items, ns, depth + 1);
288
+ }
289
+ }
290
+ }
291
+ };
292
+ walk(root, [], 0);
293
+ return out;
294
+ }
295
+
296
+ /** Suggestions at offset: table names in a header, keys at the start of a line, values after "=". */
297
+ export function completeOpmToml(text: string, offset: number, schema: Schema = OPM_SCHEMA): TomlCompletions | null {
298
+ const lineStart = text.lastIndexOf('\n', offset - 1) + 1;
299
+ const before = text.slice(lineStart, offset);
300
+ if (/^\s*#/.test(before) || /#[^"']*$/.test(before)) return null;
301
+ const scan = scanToml(text);
302
+
303
+ // a header: [transform.w| or [[chunk|
304
+ const header = /^\s*(\[\[?)\s*([A-Za-z0-9_.-]*)$/.exec(before);
305
+ if (header) {
306
+ const from = offset - header[2].length;
307
+ const lineEnd = text.indexOf('\n', offset);
308
+ const rest = text.slice(offset, lineEnd < 0 ? text.length : lineEnd);
309
+ const closing = /^[A-Za-z0-9_.-]*\]{1,2}/.exec(rest);
310
+ const to = closing ? offset + closing[0].length : offset;
311
+ const double = header[1] === '[[';
312
+ return {
313
+ from, to,
314
+ options: headers(schema).filter(h => h.array === double).map(h => ({
315
+ label: h.name, kind: 'table', detail: h.array ? 'array of tables' : 'table', info: h.schema.description,
316
+ apply: h.name + (double ? ']]' : ']'),
317
+ })),
318
+ };
319
+ }
320
+
321
+ const table = tableAt(scan, offset);
322
+ const tablePath = table?.path ?? [];
323
+
324
+ // a value: key = …|
325
+ const eq = before.indexOf('=');
326
+ if (eq >= 0) {
327
+ const key = readKey(before, 0, ch => ch === '=');
328
+ if (!key) return null;
329
+ let s = schemaAt([...tablePath, ...key.parts], schema);
330
+ if (!s) return null;
331
+ let after = before.slice(eq + 1);
332
+ // inside a list: the item's schema
333
+ if ((after.match(/\[/g)?.length ?? 0) > (after.match(/\]/g)?.length ?? 0)) {
334
+ const arr = branches(s, schema).find(b => typesOf(b).includes('array'));
335
+ if (!arr?.items) return null;
336
+ s = deref(arr.items, schema);
337
+ after = after.slice(after.lastIndexOf(',') >= 0 && after.lastIndexOf(',') > after.lastIndexOf('[') ? after.lastIndexOf(',') + 1 : after.lastIndexOf('[') + 1);
338
+ }
339
+ const word = /("?)([^"\s,[\]{}=]*)$/.exec(after)!;
340
+ const quoted = word[1] === '"';
341
+ const from = offset - word[2].length - (quoted ? 1 : 0);
342
+ const values = new Map<string, string | undefined>();
343
+ for (const b of branches(s, schema)) {
344
+ for (const v of b.enum ?? []) values.set(JSON.stringify(v), b.description);
345
+ if (typesOf(b).includes('boolean')) { values.set('true', undefined); values.set('false', undefined); }
346
+ for (const v of b.examples ?? []) values.set(JSON.stringify(v), 'example');
347
+ if (b.default !== undefined && typeof b.default !== 'object') values.set(JSON.stringify(b.default), 'default');
348
+ }
349
+ if (!values.size) return null;
350
+ // a closing quote the editor already typed is replaced too
351
+ const to = quoted && text[offset] === '"' ? offset + 1 : offset;
352
+ return {
353
+ from, to,
354
+ options: [...values].map(([v, note]) => ({ label: v, kind: 'value', detail: note === 'example' || note === 'default' ? note : undefined, apply: v })),
355
+ };
356
+ }
357
+
358
+ // a key at the start of a line
359
+ const typed = /^\s*([A-Za-z0-9_.-]*)$/.exec(before);
360
+ if (!typed) return null;
361
+ const dots = typed[1].split('.');
362
+ const partial = dots.pop()!;
363
+ const parent = [...tablePath, ...dots.filter(Boolean)];
364
+ const s = schemaAt(parent, schema);
365
+ const from = offset - partial.length;
366
+ if (!table && !dots.filter(Boolean).length) {
367
+ // before any header: offer the tables themselves
368
+ return {
369
+ from, to: offset,
370
+ options: headers(schema).map(h => ({
371
+ label: h.array ? `[[${h.name}]]` : `[${h.name}]`, kind: 'table' as const, detail: h.array ? 'array of tables' : 'table', info: h.schema.description,
372
+ apply: h.array ? `[[${h.name}]]` : `[${h.name}]`,
373
+ })),
374
+ };
375
+ }
376
+ if (!s) return null;
377
+ const present = new Set(scan.keys.filter(k => startsWith(k.path, parent) && k.path.length > parent.length).map(k => k.path[parent.length]));
378
+ for (const t of scan.tables) if (startsWith(t.path, parent) && t.path.length > parent.length) present.add(t.path[parent.length]);
379
+ const options: TomlOption[] = [];
380
+ for (const b of branches(s, schema)) {
381
+ for (const [name, raw] of Object.entries(b.properties ?? {})) {
382
+ const p = deref(raw, schema);
383
+ if (present.has(name) || p.deprecated || raw.deprecated) continue;
384
+ // tables with keys of their own, and arrays of them, are written as headers
385
+ if (isHeaderOnly(p, schema)) continue;
386
+ const value = template(p, schema);
387
+ options.push({
388
+ label: name, kind: 'key', detail: summary(p, schema), info: raw.description ?? p.description,
389
+ apply: `${name} = ${value.text}`, cursor: name.length + 3 + value.cursor,
390
+ });
391
+ }
392
+ }
393
+ return { from, to: offset, options };
394
+ }
395
+
396
+ // ── hover ────────────────────────────────────────────────────────────────
397
+
398
+ export interface TomlHover { from: number; to: number; title: string; detail: string; info?: string }
399
+
400
+ /** What the schema says about the key or table header at offset. */
401
+ export function describeOpmToml(text: string, offset: number, schema: Schema = OPM_SCHEMA): TomlHover | null {
402
+ const scan = scanToml(text);
403
+ const table = scan.tables.find(t => t.from <= offset && offset <= t.to);
404
+ const key = table ? undefined : scan.keys.find(k => k.from <= offset && offset <= k.to);
405
+ const hit = table ?? key;
406
+ if (!hit) return null;
407
+ let path = hit.path;
408
+ // a dotted key: the part under the cursor
409
+ if (key) {
410
+ const parts = readKey(text, key.from, ch => ch === '=')?.parts ?? [];
411
+ const prefixLen = key.path.length - parts.length;
412
+ let at = key.from, n = 0;
413
+ for (; n < parts.length - 1; n++) {
414
+ at = text.indexOf(parts[n], at) + parts[n].length;
415
+ if (offset <= at) break;
416
+ }
417
+ path = key.path.slice(0, prefixLen + n + 1);
418
+ } else if (typeof path[path.length - 1] === 'number') {
419
+ path = path.slice(0, -1);
420
+ }
421
+ const s = schemaAt(path, schema);
422
+ if (!s) return null;
423
+ const extras: string[] = [summary(s, schema)];
424
+ const def = branches(s, schema).find(b => b.default !== undefined)?.default;
425
+ if (def !== undefined) extras.push(`default ${JSON.stringify(def)}`);
426
+ return {
427
+ from: hit.from, to: hit.to,
428
+ title: table ? tableName(table.path) : keyName(path),
429
+ detail: extras.join(', '),
430
+ info: s.description,
431
+ };
432
+ }
@@ -0,0 +1,155 @@
1
+ // ── where things are in a TOML file ───────────────────────────────────────
2
+ // smol-toml tells whether a file is valid and what it holds, but not where a
3
+ // key or table is written. This scanner finds the headers and key/value lines
4
+ // with their offsets, and resolves each to the path its value has in the parsed
5
+ // document: [[chunking]] tables count up, so the fragments of the second run are
6
+ // chunking[1].fragments. It never throws: a line it cannot read is skipped.
7
+
8
+ export type Seg = string | number;
9
+
10
+ export interface TomlTable {
11
+ /** Path of the table in the parsed document, e.g. ['chunking', 1, 'fragments', 0]. */
12
+ path: Seg[];
13
+ /** The header, brackets included. */
14
+ from: number;
15
+ to: number;
16
+ /** Whether it is an array-of-tables header, [[…]]. */
17
+ array: boolean;
18
+ }
19
+
20
+ export interface TomlKey {
21
+ /** Path of the value, e.g. ['transform', 'web', 'template']. */
22
+ path: Seg[];
23
+ /** The whole (possibly dotted) key. */
24
+ from: number;
25
+ to: number;
26
+ /** The value, trimmed. */
27
+ valueFrom: number;
28
+ valueTo: number;
29
+ }
30
+
31
+ export interface TomlScan { tables: TomlTable[]; keys: TomlKey[] }
32
+
33
+ const isBare = (c: string) => /[A-Za-z0-9_-]/.test(c);
34
+ const isSpace = (c: string) => c === ' ' || c === '\t';
35
+
36
+ /** A dotted key starting at i: its parts and where it ends, or null. */
37
+ export function readKey(text: string, i: number, stop: (c: string) => boolean): { parts: string[]; end: number } | null {
38
+ const parts: string[] = [];
39
+ for (;;) {
40
+ while (isSpace(text[i])) i++;
41
+ const c = text[i];
42
+ if (c === '"' || c === "'") {
43
+ let j = i + 1, part = '';
44
+ while (j < text.length && text[j] !== c && text[j] !== '\n') {
45
+ if (c === '"' && text[j] === '\\' && j + 1 < text.length) { part += text[j + 1]; j += 2; continue; }
46
+ part += text[j++];
47
+ }
48
+ if (text[j] !== c) return null;
49
+ parts.push(part);
50
+ i = j + 1;
51
+ } else if (c !== undefined && isBare(c)) {
52
+ const start = i;
53
+ while (i < text.length && isBare(text[i])) i++;
54
+ parts.push(text.slice(start, i));
55
+ } else {
56
+ return null;
57
+ }
58
+ while (isSpace(text[i])) i++;
59
+ if (text[i] === '.') { i++; continue; }
60
+ return i < text.length && stop(text[i]) ? { parts, end: i } : null;
61
+ }
62
+ }
63
+
64
+ /**
65
+ * A value starting at i, past strings, arrays and inline tables, which may span lines:
66
+ * where its text ends (before a trailing comment and blanks) and where scanning goes on.
67
+ */
68
+ export function skipValue(text: string, i: number): { valueTo: number; next: number } {
69
+ let depth = 0, contentEnd = -1;
70
+ while (i < text.length) {
71
+ const c = text[i];
72
+ if (c === '"' || c === "'") {
73
+ if (text.startsWith(c.repeat(3), i)) {
74
+ const end = text.indexOf(c.repeat(3), i + 3);
75
+ i = end < 0 ? text.length : end + 3;
76
+ while (text[i] === c) i++;
77
+ } else {
78
+ i++;
79
+ while (i < text.length && text[i] !== c && text[i] !== '\n') i += c === '"' && text[i] === '\\' ? 2 : 1;
80
+ if (text[i] === c) i++;
81
+ }
82
+ continue;
83
+ }
84
+ if (c === '#') {
85
+ if (depth === 0 && contentEnd < 0) contentEnd = i;
86
+ while (i < text.length && text[i] !== '\n') i++;
87
+ continue;
88
+ }
89
+ if (c === '\n' && depth === 0) break;
90
+ if (c === '[' || c === '{') depth++;
91
+ else if ((c === ']' || c === '}') && depth) depth--;
92
+ i++;
93
+ }
94
+ let valueTo = contentEnd < 0 ? i : contentEnd;
95
+ while (valueTo > 0 && /\s/.test(text[valueTo - 1])) valueTo--;
96
+ return { valueTo, next: i };
97
+ }
98
+
99
+ export function scanToml(text: string): TomlScan {
100
+ const tables: TomlTable[] = [], keys: TomlKey[] = [];
101
+ const counts = new Map<string, number>();
102
+ const id = (p: Seg[]) => JSON.stringify(p);
103
+ // resolve a header's parts: a prefix that names an array of tables means its last element
104
+ const resolve = (parts: string[], array: boolean): Seg[] => {
105
+ const path: Seg[] = [];
106
+ parts.forEach((part, n) => {
107
+ path.push(part);
108
+ const last = n === parts.length - 1;
109
+ if (last && array) {
110
+ const count = counts.get(id(path)) ?? 0;
111
+ counts.set(id(path), count + 1);
112
+ path.push(count);
113
+ } else if (!last && counts.has(id(path))) {
114
+ path.push(counts.get(id(path))! - 1);
115
+ }
116
+ });
117
+ return path;
118
+ };
119
+ let table: Seg[] = [];
120
+ let i = 0;
121
+ while (i < text.length) {
122
+ const c = text[i];
123
+ if (c === '\n' || isSpace(c) || c === '\r') { i++; continue; }
124
+ const eol = () => { const n = text.indexOf('\n', i); return n < 0 ? text.length : n; };
125
+ if (c === '#') { i = eol(); continue; }
126
+ if (c === '[') {
127
+ const array = text[i + 1] === '[';
128
+ const key = readKey(text, i + (array ? 2 : 1), ch => ch === ']');
129
+ if (key && (!array || text[key.end + 1] === ']')) {
130
+ const end = key.end + (array ? 2 : 1);
131
+ table = resolve(key.parts, array);
132
+ tables.push({ path: table, from: i, to: end, array });
133
+ }
134
+ i = eol();
135
+ continue;
136
+ }
137
+ const key = readKey(text, i, ch => ch === '=');
138
+ if (!key) { i = eol(); continue; }
139
+ let keyTo = key.end;
140
+ while (keyTo > i && isSpace(text[keyTo - 1])) keyTo--;
141
+ let v = key.end + 1;
142
+ while (isSpace(text[v])) v++;
143
+ const { valueTo, next } = skipValue(text, v);
144
+ keys.push({ path: [...table, ...key.parts], from: i, to: keyTo, valueFrom: v, valueTo: Math.max(v, valueTo) });
145
+ i = Math.max(next, i + 1);
146
+ }
147
+ return { tables, keys };
148
+ }
149
+
150
+ /** The table a position belongs to: the path of the last header before it, [] before any. */
151
+ export function tableAt(scan: TomlScan, offset: number): TomlTable | undefined {
152
+ let found: TomlTable | undefined;
153
+ for (const t of scan.tables) if (t.from <= offset) found = t; else break;
154
+ return found;
155
+ }
package/src/edit.ts CHANGED
@@ -4,6 +4,7 @@ export {
4
4
  schemaFor, projectRoot, isOdd, xmlModels, isRngModel, xmlModelEdits, relativeHref, RNG_NS, DEFAULT_SCHEMA_FILES, PUBLIC_SCHEMA_URLS, publicSchema, vocabulary,
5
5
  type Files, type Defaults, type SchemaChoice, type TextEdit,
6
6
  } from './core/association.ts';
7
+ export { checkOpmToml, completeOpmToml, describeOpmToml, isOpmToml, schemaAt, OPM_SCHEMA, type TomlProblem, type TomlOption, type TomlCompletions, type TomlHover, type Schema } from './core/opmToml.ts';
7
8
  export { readToml, setToml, unsetToml, tomlString, type TomlConfig, type TomlValue } from './core/toml.ts';
8
9
  export {
9
10
  elements, elementsAround, elementAround, selectElement, removeElementTags, splitElement, surroundWithElement,
package/src/index.ts CHANGED
@@ -9,6 +9,7 @@ export {
9
9
  } from './core/association.ts';
10
10
  export { scanTags, pairs, matchingTags, openElementAt, closeTagAt, type Tag } from './core/tags.ts';
11
11
  export { oddOutline, teiOutline, elementOutline, Kind, type OutlineSymbol } from './core/outline.ts';
12
+ export { checkOpmToml, completeOpmToml, describeOpmToml, isOpmToml, schemaAt, OPM_SCHEMA, type TomlProblem, type TomlOption, type TomlCompletions, type TomlHover, type Schema } from './core/opmToml.ts';
12
13
  export { readToml, setToml, unsetToml, tomlString, type TomlConfig, type TomlValue } from './core/toml.ts';
13
14
  export {
14
15
  elements, elementsAround, elementAround, selectElement, removeElementTags, splitElement, surroundWithElement,