@dogsbay/commands 0.2.0-beta.176 → 0.2.0-beta.177

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,509 @@
1
+ /**
2
+ * Variables in the workspace index (the playground's item 24): every definition and every use of a
3
+ * template variable, from the files alone, in every variant (plans/variables-in-the-index.md).
4
+ *
5
+ * Definitions: the config's `attributes:` (site-wide and per source), `{% set %}` (with the
6
+ * `{% if %}` / `{% switch %}` branches it sits under), `{% with %}` parameters, a partial's `params:`.
7
+ * Uses: every name read by `{{ … }}` and by a tag's expression, as a range.
8
+ *
9
+ * The shape is the one DITA keys and conrefs can take later: a `kind`, several definitions per
10
+ * name, ranges, and a resolution context (a source here; a root map and DITAVAL there).
11
+ *
12
+ * Pure and browser-safe. Linear in the text: tags are found with indexOf, never a backtracking
13
+ * pattern (a corpus is someone else's repo).
14
+ */
15
+ import { evaluateExpression, parseExpression, Context } from "@dogsbay/minja/browser";
16
+ import { ATTRIBUTE_BLOCK_OPEN } from "@dogsbay/format-dogsbay-md/browser";
17
+ /** The lookup form of a name: its root, hyphens as underscores (the build's `hyphenToUnderscore`). */
18
+ export const variableKey = (name) => name.split(".")[0].replace(/-/g, "_");
19
+ class Lines {
20
+ starts = [0];
21
+ constructor(text) {
22
+ for (let i = text.indexOf("\n"); i !== -1; i = text.indexOf("\n", i + 1))
23
+ this.starts.push(i + 1);
24
+ }
25
+ at(offset) {
26
+ let lo = 0;
27
+ let hi = this.starts.length - 1;
28
+ while (lo < hi) {
29
+ const mid = (lo + hi + 1) >> 1;
30
+ if (this.starts[mid] <= offset)
31
+ lo = mid;
32
+ else
33
+ hi = mid - 1;
34
+ }
35
+ return { line: lo + 1, col: offset - this.starts[lo] };
36
+ }
37
+ }
38
+ const KEYWORDS = new Set(["and", "or", "not", "in", "is", "if", "else", "true", "false", "none", "True", "False", "None", "loop", "recursive"]);
39
+ /**
40
+ * The root names an expression reads, with their offsets in `expr`. Not a name after `.` (a
41
+ * field), `|` (a filter), `is` (a test), before `(` (a function) or a keyword argument's `=`, nor
42
+ * inside a string. `hyphens`: content mode, where `product-title` is one name.
43
+ */
44
+ export const expressionNames = (expr, hyphens) => {
45
+ const names = [];
46
+ const filters = [];
47
+ const word = hyphens ? /[A-Za-z_][\w-]*/y : /[A-Za-z_]\w*/y;
48
+ let prev = ""; // the previous significant token
49
+ let i = 0;
50
+ while (i < expr.length) {
51
+ const c = expr[i];
52
+ if (c === '"' || c === "'") {
53
+ let j = i + 1;
54
+ while (j < expr.length && expr[j] !== c)
55
+ j += expr[j] === "\\" ? 2 : 1;
56
+ i = j + 1;
57
+ prev = "str";
58
+ continue;
59
+ }
60
+ if (/\s/.test(c)) {
61
+ i++;
62
+ continue;
63
+ }
64
+ if (/\d/.test(c)) {
65
+ while (i < expr.length && /[\w.]/.test(expr[i]))
66
+ i++;
67
+ prev = "num";
68
+ continue;
69
+ }
70
+ word.lastIndex = i;
71
+ const m = word.exec(expr);
72
+ if (!m) {
73
+ prev = c;
74
+ i++;
75
+ continue;
76
+ }
77
+ let end = i + m[0].length;
78
+ // a hyphen run at the end is an operator, not part of the name
79
+ while (hyphens && expr[end - 1] === "-")
80
+ end--;
81
+ const text = expr.slice(i, end);
82
+ let path = text;
83
+ let k = end;
84
+ // the `.field` path that follows
85
+ for (;;) {
86
+ word.lastIndex = k + 1;
87
+ const f = expr[k] === "." ? word.exec(expr) : null;
88
+ if (!f)
89
+ break;
90
+ path += `.${f[0]}`;
91
+ k += 1 + f[0].length;
92
+ }
93
+ let n = k;
94
+ while (n < expr.length && /\s/.test(expr[n]))
95
+ n++;
96
+ const next = expr[n];
97
+ const kwarg = next === "=" && expr[n + 1] !== "=";
98
+ // `x.split(".")`: a method of `x`, still a use of it; `range(3)`: a function
99
+ const call = next === "(" && path === text;
100
+ if (next === "(" && path !== text)
101
+ path = path.slice(0, path.lastIndexOf("."));
102
+ if (prev === "|")
103
+ filters.push(text);
104
+ else if (prev === "." || prev === "is" || prev === "not-after-is" || KEYWORDS.has(text) || call || kwarg) {
105
+ // a field, a test, a keyword, a call, a keyword argument's name
106
+ }
107
+ else
108
+ names.push({ name: path, start: i, end });
109
+ prev = text === "not" && (prev === "is") ? "not-after-is" : KEYWORDS.has(text) ? text : "name";
110
+ i = k;
111
+ }
112
+ return { names, filters };
113
+ };
114
+ const last = (stack, kind) => {
115
+ for (let k = stack.length - 1; k >= 0; k--)
116
+ if (stack[k].kind === kind)
117
+ return stack[k];
118
+ return undefined;
119
+ };
120
+ /** As deep as minja nests blocks (`MAX_BLOCK_NESTING`): past it the page does not build. */
121
+ const MAX_DEPTH = 32;
122
+ /**
123
+ * Where a tag closes. Content mode: the first closer. Template mode: the first outside a string
124
+ * and outside brackets (template mode's own `findClose`), so `{{ "}}" ~ x }}` is one tag. A closer
125
+ * missing once is never looked for again: linear on someone else's repo.
126
+ */
127
+ const findClose = (text, from, closer, missing, template) => {
128
+ if (missing.has(closer))
129
+ return -1;
130
+ if (!template) {
131
+ const at = text.indexOf(closer, from);
132
+ if (at === -1)
133
+ missing.add(closer);
134
+ return at;
135
+ }
136
+ let depth = 0;
137
+ for (let i = from; i < text.length; i++) {
138
+ const c = text[i];
139
+ if (c === '"' || c === "'") {
140
+ const end = text.indexOf(c, i + 1);
141
+ if (end === -1)
142
+ break;
143
+ i = end;
144
+ }
145
+ else if (c === "(" || c === "[")
146
+ depth++;
147
+ else if ((c === ")" || c === "]") && depth > 0)
148
+ depth--;
149
+ else if (depth === 0 && text.startsWith(closer, i))
150
+ return i;
151
+ else if (c === "{")
152
+ depth++;
153
+ else if (c === "}" && depth > 0)
154
+ depth--;
155
+ }
156
+ missing.add(closer);
157
+ return -1;
158
+ };
159
+ /** minja's case test: an operand with operators in brackets (parser.ts). */
160
+ const operand = (e) => (/^(?:[\w.]+|"[^"]*"|'[^']*')$/.test(e) ? e : `(${e})`);
161
+ /** The offset of a `for`'s ` in ` (the first `in` with space on both sides), or -1. */
162
+ const forIn = (rest) => {
163
+ for (let k = rest.indexOf("in"); k !== -1; k = rest.indexOf("in", k + 1)) {
164
+ if (k > 0 && /\s/.test(rest[k - 1]) && /\s/.test(rest[k + 2] ?? ""))
165
+ return k;
166
+ }
167
+ return -1;
168
+ };
169
+ const ENDRAW = /\{%-?\s*endraw\s*-?%\}/g;
170
+ /**
171
+ * The definitions and uses in one page or include. `masked` is `source` with code blanked to
172
+ * spaces (`blankCodeRegions`: same length, `{minja}` fences kept); `bodyStart` is where the front
173
+ * matter ends.
174
+ */
175
+ export function scanFileVariables(file, source, masked, bodyStart, options) {
176
+ const template = options.template;
177
+ const lines = new Lines(source);
178
+ const definitions = [];
179
+ const uses = [];
180
+ const stack = [];
181
+ const missing = new Set();
182
+ // one conditions array per state of the stack, shared by every symbol under it
183
+ let condsCache = null;
184
+ let overflow = 0; // blocks opened past MAX_DEPTH, not tracked
185
+ const changed = () => { condsCache = null; };
186
+ const push = (f) => {
187
+ if (stack.length >= MAX_DEPTH)
188
+ overflow++;
189
+ else
190
+ stack.push(f);
191
+ changed();
192
+ };
193
+ const conds = () => (condsCache ??= stack.flatMap((f) => (f.conditions ? [f.conditions] : [])));
194
+ const isLocal = (name) => stack.some((f) => f.locals?.has(variableKey(name)));
195
+ const inLoop = () => stack.some((f) => f.kind === "for");
196
+ const range = (start, end) => {
197
+ const a = lines.at(start);
198
+ return { file, line: a.line, from: a.col, to: a.line === lines.at(end).line ? lines.at(end).col : a.col + (end - start) };
199
+ };
200
+ const addUses = (expr, base, form, plain = false) => {
201
+ const { names, filters } = expressionNames(expr, !template);
202
+ const c = conds();
203
+ for (const n of names) {
204
+ if (isLocal(n.name))
205
+ continue;
206
+ uses.push({ kind: "variable", name: n.name, form, ...(filters.length && form === "output" ? { filters } : {}), plain, conditions: c, ...range(base + n.start, base + n.end) });
207
+ }
208
+ return filters;
209
+ };
210
+ const define = (name, start, via, value) => {
211
+ definitions.push({ kind: "variable", name, via, ...(value !== undefined ? { value } : {}), conditions: conds(), context: { scope: "file" }, ...(inLoop() ? { inLoop: true } : {}), ...range(start, start + name.length) });
212
+ };
213
+ /** `a = 1, b = "x"` → each name, its offset in `s`, and its value; top-level commas only. */
214
+ const assignments = (s) => {
215
+ const out = [];
216
+ let depth = 0;
217
+ let quote = "";
218
+ let start = 0;
219
+ const piece = (end) => {
220
+ const part = s.slice(start, end);
221
+ const m = /^(\s*)([A-Za-z_][\w-]*)\s*=(?!=)/.exec(part);
222
+ if (m) {
223
+ const raw = s.slice(start + m[0].length, end);
224
+ const valueAt = start + m[0].length + (raw.length - raw.trimStart().length);
225
+ out.push({ name: m[2], at: start + m[1].length, value: raw.trim(), valueAt });
226
+ }
227
+ start = end + 1;
228
+ };
229
+ for (let i = 0; i < s.length; i++) {
230
+ const c = s[i];
231
+ if (quote) {
232
+ if (c === "\\")
233
+ i++;
234
+ else if (c === quote)
235
+ quote = "";
236
+ continue;
237
+ }
238
+ if (c === '"' || c === "'")
239
+ quote = c;
240
+ else if ("([{".includes(c))
241
+ depth++;
242
+ else if (")]}".includes(c))
243
+ depth--;
244
+ else if (c === "," && depth === 0)
245
+ piece(i);
246
+ }
247
+ piece(s.length);
248
+ return out;
249
+ };
250
+ let i = bodyStart;
251
+ while (i < masked.length) {
252
+ const open = masked.indexOf("{", i);
253
+ if (open === -1 || open + 1 >= masked.length)
254
+ break;
255
+ const kind = masked[open + 1];
256
+ if (kind === "#") {
257
+ // Content mode has no comments (the build masks every `{#`). Template mode: a comment unless
258
+ // it is an attribute block (`{#id}`, `{#-d7v7g5suqg}`), by the build's own pattern.
259
+ ATTRIBUTE_BLOCK_OPEN.lastIndex = open;
260
+ const attribute = !template || ATTRIBUTE_BLOCK_OPEN.exec(masked)?.index === open;
261
+ const close = attribute ? -1 : findClose(masked, open + 2, "#}", missing, false);
262
+ i = close === -1 ? open + 2 : close + 2;
263
+ continue;
264
+ }
265
+ if (kind === "{") {
266
+ const close = findClose(masked, open + 2, "}}", missing, template);
267
+ if (close === -1) {
268
+ i = open + 2;
269
+ continue;
270
+ }
271
+ let s = open + 2;
272
+ let e = close;
273
+ if (masked[s] === "-")
274
+ s++;
275
+ if (masked[e - 1] === "-")
276
+ e--;
277
+ const inner = masked.slice(s, e);
278
+ const plain = /^\s*[A-Za-z_][\w.-]*\s*$/.test(inner) && (!template || !/-/.test(inner));
279
+ if (plain) {
280
+ const lead = inner.length - inner.trimStart().length;
281
+ const name = inner.trim();
282
+ // the range is the root name, what a rename changes (`page` of `page.title`)
283
+ const root = name.split(".")[0];
284
+ if (!isLocal(name))
285
+ uses.push({ kind: "variable", name, form: "output", plain: true, conditions: conds(), ...range(s + lead, s + lead + root.length) });
286
+ }
287
+ else if (template)
288
+ addUses(inner, s, "output");
289
+ // content mode: `{{ x | upper }}` is a lookup of the whole text, which nothing defines
290
+ i = close + 2;
291
+ continue;
292
+ }
293
+ if (kind !== "%") {
294
+ i = open + 1;
295
+ continue;
296
+ }
297
+ const close = findClose(masked, open + 2, "%}", missing, template);
298
+ if (close === -1) {
299
+ i = open + 2;
300
+ continue;
301
+ }
302
+ let s = open + 2;
303
+ let e = close;
304
+ if (masked[s] === "-")
305
+ s++;
306
+ if (masked[e - 1] === "-")
307
+ e--;
308
+ const body = masked.slice(s, e);
309
+ const lead = body.length - body.trimStart().length;
310
+ const stmt = body.trim();
311
+ const at = s + lead; // offset of stmt in the file
312
+ const word = /^[a-z]+/.exec(stmt)?.[0] ?? "";
313
+ const rest = stmt.slice(word.length);
314
+ const restAt = at + word.length;
315
+ const line = lines.at(open).line;
316
+ i = close + 2;
317
+ // tags only template mode has: on an ordinary page they stay as text
318
+ if (!template && (word === "for" || word === "endfor" || word === "with" || word === "endwith" || word === "endset"))
319
+ continue;
320
+ switch (word) {
321
+ case "raw": {
322
+ ENDRAW.lastIndex = i;
323
+ const end = ENDRAW.exec(masked);
324
+ i = end ? end.index + end[0].length : masked.length;
325
+ break;
326
+ }
327
+ case "if":
328
+ addUses(rest, restAt, "condition");
329
+ push({ kind: "if", conditions: { branch: "if", test: rest.trim(), line }, tests: [rest.trim()] });
330
+ break;
331
+ case "elif": {
332
+ const f = last(stack, "if");
333
+ addUses(rest, restAt, "condition");
334
+ if (f && !overflow) {
335
+ f.conditions = { branch: "elif", test: rest.trim(), after: [...f.tests], line };
336
+ f.tests.push(rest.trim());
337
+ changed();
338
+ }
339
+ break;
340
+ }
341
+ case "else": {
342
+ const f = stack[stack.length - 1];
343
+ if (!overflow && (f?.kind === "if" || f?.kind === "switch")) {
344
+ f.conditions = { branch: "else", after: [...f.tests], line };
345
+ changed();
346
+ }
347
+ break;
348
+ }
349
+ case "endif":
350
+ case "endswitch":
351
+ case "endfor":
352
+ case "endwith": {
353
+ if (overflow) {
354
+ overflow--;
355
+ break;
356
+ }
357
+ const want = word === "endif" ? "if" : word === "endswitch" ? "switch" : word === "endfor" ? "for" : "with";
358
+ const k = stack.map((f) => f.kind).lastIndexOf(want);
359
+ if (k !== -1)
360
+ stack.length = k;
361
+ changed();
362
+ break;
363
+ }
364
+ case "switch":
365
+ addUses(rest, restAt, "condition");
366
+ push({ kind: "switch", subject: rest.trim(), tests: [] });
367
+ break;
368
+ case "case": {
369
+ const f = last(stack, "switch");
370
+ if (f && !overflow) {
371
+ const test = `${operand(f.subject)} == ${operand(rest.trim())}`;
372
+ f.conditions = { branch: "case", test, ...(f.tests.length ? { after: [...f.tests] } : {}), line };
373
+ f.tests.push(test);
374
+ changed();
375
+ }
376
+ break;
377
+ }
378
+ case "for": {
379
+ const k = forIn(rest);
380
+ const locals = new Set(["loop", ...(k === -1 ? "" : rest.slice(0, k)).split(",").map((x) => variableKey(x.trim())).filter(Boolean)]);
381
+ if (k !== -1)
382
+ addUses(rest.slice(k + 2), restAt + k + 2, "expression");
383
+ push({ kind: "for", locals });
384
+ break;
385
+ }
386
+ case "with": {
387
+ const names = assignments(rest);
388
+ for (const a of names)
389
+ addUses(a.value, restAt + a.valueAt, "expression");
390
+ push({ kind: "with" });
391
+ for (const a of names)
392
+ define(a.name, restAt + a.at, "with", a.value);
393
+ break;
394
+ }
395
+ case "set": {
396
+ // minja's set names are `\w+` in both modes
397
+ const m = /^\s+([A-Za-z_]\w*(?:\s*,\s*[A-Za-z_]\w*)*)(\.[\w.]+)?\s*(=(?!=))?/.exec(rest);
398
+ if (m && !template && (m[1].includes(",") || m[2] || !m[3]))
399
+ break; // content mode: `set name = value` only
400
+ if (!m)
401
+ break;
402
+ const targetsAt = restAt + m[0].indexOf(m[1]);
403
+ if (m[2]) {
404
+ // `{% set ns.count = … %}`: writes a field of a namespace, a use of `ns`
405
+ addUses(m[1], targetsAt, "expression");
406
+ }
407
+ else {
408
+ let off = 0;
409
+ for (const t of m[1].split(",")) {
410
+ const lead2 = t.length - t.trimStart().length;
411
+ if (!isLocal(t.trim()))
412
+ define(t.trim(), targetsAt + off + lead2, "set", m[3] ? rest.slice(m[0].length).trim() : undefined);
413
+ off += t.length + 1;
414
+ }
415
+ }
416
+ if (m[3])
417
+ addUses(rest.slice(m[0].length), restAt + m[0].length, "expression");
418
+ break;
419
+ }
420
+ case "include":
421
+ // `{% include "x" with … %}` is not minja; only `ignore missing` and the path
422
+ break;
423
+ default:
424
+ break;
425
+ }
426
+ }
427
+ return { definitions, uses };
428
+ }
429
+ /**
430
+ * A partial's declared `params:` (`params: [platform, cli?]` or a block list), as definitions in its
431
+ * front matter. `frontmatter` is the block's text, starting at offset 0 of the file.
432
+ */
433
+ export function scanParams(file, source, frontmatterEnd) {
434
+ const lines = new Lines(source);
435
+ const fm = source.slice(0, frontmatterEnd);
436
+ const out = [];
437
+ const key = /^params:[ \t]*(.*)$/m.exec(fm);
438
+ if (!key)
439
+ return out;
440
+ const push = (name, at) => {
441
+ const a = lines.at(at);
442
+ out.push({ kind: "variable", name, via: "param", conditions: [], context: { scope: "file" }, file, line: a.line, from: a.col, to: a.col + name.length });
443
+ };
444
+ const valueAt = key.index + key[0].length - key[1].length;
445
+ if (key[1].trim().startsWith("[")) {
446
+ const inner = /\[([^\]\n]*)\]/.exec(key[1]);
447
+ if (!inner)
448
+ return out;
449
+ const innerAt = valueAt + key[1].indexOf("[") + 1;
450
+ for (const m of inner[1].matchAll(/[A-Za-z_][\w-]*/g))
451
+ push(m[0], innerAt + m.index);
452
+ return out;
453
+ }
454
+ // block list: `- name` lines right after
455
+ let at = fm.indexOf("\n", key.index) + 1;
456
+ while (at > 0 && at < fm.length) {
457
+ const end = fm.indexOf("\n", at);
458
+ const text = fm.slice(at, end === -1 ? fm.length : end);
459
+ const m = /^[ \t]+-[ \t]+["']?([A-Za-z_][\w-]*)/.exec(text);
460
+ if (!m)
461
+ break;
462
+ push(m[1], at + m[0].length - m[1].length);
463
+ if (end === -1)
464
+ break;
465
+ at = end + 1;
466
+ }
467
+ return out;
468
+ }
469
+ /**
470
+ * Does a definition apply in a variant: its conditions against the variant's attributes. A name the
471
+ * attributes lack is undefined (falsy, as the build reads it) unless `setNames` has it, which makes
472
+ * the answer `null` (a `{% set %}` elsewhere may give it).
473
+ */
474
+ export function appliesIn(conditions, attributes, setNames) {
475
+ const ctx = new Context(undefined, { hyphenToUnderscore: true });
476
+ for (const [k, v] of Object.entries(attributes))
477
+ ctx.set(k.replace(/-/g, "_"), v);
478
+ let unknown = false;
479
+ const test = (expr) => {
480
+ try {
481
+ for (const n of expressionNames(expr, true).names) {
482
+ const k = variableKey(n.name);
483
+ if (!(k in attributes) && !Object.keys(attributes).some((a) => variableKey(a) === k) && setNames.has(k))
484
+ return null;
485
+ }
486
+ return Boolean(evaluateExpression(parseExpression(expr), ctx));
487
+ }
488
+ catch {
489
+ return null;
490
+ }
491
+ };
492
+ for (const c of conditions) {
493
+ for (const t of c.after ?? []) {
494
+ const r = test(t);
495
+ if (r === true)
496
+ return false;
497
+ if (r === null)
498
+ unknown = true;
499
+ }
500
+ if (c.test !== undefined) {
501
+ const r = test(c.test);
502
+ if (r === false)
503
+ return false;
504
+ if (r === null)
505
+ unknown = true;
506
+ }
507
+ }
508
+ return unknown ? null : true;
509
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dogsbay/commands",
3
- "version": "0.2.0-beta.176",
3
+ "version": "0.2.0-beta.177",
4
4
  "description": "Typed, headless-first command engine for the Dogsbay platform — one zod-defined command yields CLI, JSON-RPC, and MCP surfaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -9,8 +9,13 @@
9
9
  ".": {
10
10
  "types": "./dist/index.d.ts",
11
11
  "import": "./dist/index.js"
12
+ },
13
+ "./indexes": {
14
+ "types": "./dist/indexes-entry.d.ts",
15
+ "import": "./dist/indexes-entry.js"
12
16
  }
13
17
  },
18
+ "sideEffects": false,
14
19
  "files": [
15
20
  "dist",
16
21
  "README.md"
@@ -24,12 +29,13 @@
24
29
  },
25
30
  "dependencies": {
26
31
  "js-yaml": "^5.2.1",
32
+ "yaml": "^2.9.0",
27
33
  "zod": "^4.4.3",
28
- "@dogsbay/format-dogsbay-md": "0.2.0-beta.176",
29
- "@dogsbay/minja": "0.2.0-beta.176",
30
- "@dogsbay/render": "0.2.0-beta.176",
31
- "@dogsbay/format-topicmap": "0.2.0-beta.176",
32
- "@dogsbay/types": "0.2.0-beta.176"
34
+ "@dogsbay/format-dogsbay-md": "0.2.0-beta.177",
35
+ "@dogsbay/minja": "0.2.0-beta.177",
36
+ "@dogsbay/render": "0.2.0-beta.177",
37
+ "@dogsbay/format-topicmap": "0.2.0-beta.177",
38
+ "@dogsbay/types": "0.2.0-beta.177"
33
39
  },
34
40
  "license": "MIT",
35
41
  "repository": {