@dogsbay/commands 0.2.0-beta.175 → 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.
- package/README.md +53 -1
- package/dist/commands/content.d.ts +2 -7
- package/dist/commands/content.js +2 -8
- package/dist/config-variables.d.ts +12 -0
- package/dist/config-variables.js +78 -0
- package/dist/index.d.ts +5 -3
- package/dist/index.js +4 -2
- package/dist/indexes-entry.d.ts +15 -0
- package/dist/indexes-entry.js +15 -0
- package/dist/indexes.d.ts +33 -0
- package/dist/indexes.js +158 -27
- package/dist/node-storage.d.ts +42 -0
- package/dist/node-storage.js +154 -0
- package/dist/sha256.d.ts +6 -0
- package/dist/sha256.js +6 -0
- package/dist/storage.d.ts +2 -38
- package/dist/storage.js +2 -150
- package/dist/variables.d.ts +117 -0
- package/dist/variables.js +509 -0
- package/package.json +12 -6
package/dist/indexes.js
CHANGED
|
@@ -9,11 +9,13 @@
|
|
|
9
9
|
*
|
|
10
10
|
* Everything here is pure over `Storage` — no node:fs, browser-safe.
|
|
11
11
|
*/
|
|
12
|
-
import { dogsbayMdToTree,
|
|
12
|
+
import { dogsbayMdToTree, headingIds, pageId, isMinjaProcessedFence, transformCodeRegions, authoredAnchor, authoredInlineAnchor, anchorLabel, findAnchorSpan } from "@dogsbay/format-dogsbay-md/browser";
|
|
13
13
|
import { includeDirectiveRe } from "@dogsbay/minja/browser";
|
|
14
14
|
import { parseTopicMap, isTopicMapPath, isExternalHref, normalizePath, dirname, joinPath, } from "@dogsbay/format-topicmap";
|
|
15
15
|
import { load as loadYaml } from "js-yaml";
|
|
16
|
-
import { contentHash } from "./
|
|
16
|
+
import { contentHash } from "./sha256.js";
|
|
17
|
+
import { appliesIn, scanFileVariables, scanParams, variableKey } from "./variables.js";
|
|
18
|
+
import { CONFIG_FILES, inFolder, readConfigVariables } from "./config-variables.js";
|
|
17
19
|
const isKeysFilePath = (path) => path.endsWith(".keys.yaml") || path.endsWith(".keys.yml") || /(^|\/)keys\.ya?ml$/.test(path);
|
|
18
20
|
const isDocPath = (path) => path.endsWith(".md");
|
|
19
21
|
/**
|
|
@@ -48,6 +50,48 @@ const inlineText = (nodes) => {
|
|
|
48
50
|
.join("");
|
|
49
51
|
};
|
|
50
52
|
const HTML_ANCHOR_RE = /<a\s[^>]*id\s*=\s*["']([^"']+)["']/gi;
|
|
53
|
+
const blockRange = (node) => {
|
|
54
|
+
const meta = node.meta;
|
|
55
|
+
if (typeof meta?.line !== "number")
|
|
56
|
+
return undefined;
|
|
57
|
+
return [meta.line - 1, (typeof meta.endLine === "number" ? meta.endLine : meta.line) - 1];
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* The lines a block's `{#id}` can be written on: a table's is on the line after its last row; a
|
|
61
|
+
* code block's on its fence and a container's on its opener (not in what they hold — an id from a
|
|
62
|
+
* props block has no attribute line, and so no range); a heading's or paragraph's on its lines.
|
|
63
|
+
*/
|
|
64
|
+
const idLines = (node, range) => {
|
|
65
|
+
if (!range)
|
|
66
|
+
return undefined;
|
|
67
|
+
if (node.type === "table")
|
|
68
|
+
return [range[1], range[1] + 1];
|
|
69
|
+
if (node.type === "code" || node.children?.length || node.type !== "heading" && node.type !== "paragraph" && !node.inline)
|
|
70
|
+
return [range[0], range[0]];
|
|
71
|
+
return range;
|
|
72
|
+
};
|
|
73
|
+
/** `written` is the `{#id}` as the source has it (its range); `id` the page's (a heading's `{#fn-x}` is `h-fn-x`). */
|
|
74
|
+
const addTarget = (state, written, kind, label, range, id = written) => {
|
|
75
|
+
const at = state.lines && range ? findAnchorSpan(state.lines, range[0], range[1], written, state.taken) : undefined;
|
|
76
|
+
state.entry.targets.push({ id, kind, ...(label ? { label } : {}), authored: true, ...(at ?? {}) });
|
|
77
|
+
};
|
|
78
|
+
/** `id="x"` of a raw HTML anchor, in the block's lines: the value's columns. */
|
|
79
|
+
const findHtmlIdSpan = (state, id) => {
|
|
80
|
+
if (!state.lines || !state.range)
|
|
81
|
+
return undefined;
|
|
82
|
+
for (let i = state.range[0]; i <= Math.min(state.range[1], state.lines.length - 1); i++) {
|
|
83
|
+
const text = state.lines[i];
|
|
84
|
+
// an `id` attribute (not `data-id`), spaces around `=` allowed, as HTML_ANCHOR_RE reads it
|
|
85
|
+
for (const m of text.matchAll(/(?:^|[\s<])id\s*=\s*(["'])([^"']*)\1/gi)) {
|
|
86
|
+
const at = (m.index ?? 0) + m[0].length - 1 - m[2].length;
|
|
87
|
+
if (m[2] !== id || state.taken?.has(`${i}:${at}`))
|
|
88
|
+
continue;
|
|
89
|
+
state.taken?.add(`${i}:${at}`);
|
|
90
|
+
return { line: i + 1, from: at, to: at + id.length };
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return undefined;
|
|
94
|
+
};
|
|
51
95
|
const recordHref = (state, href, kind) => {
|
|
52
96
|
if (href.startsWith("key:")) {
|
|
53
97
|
const name = href.slice("key:".length).split("#")[0];
|
|
@@ -97,12 +141,18 @@ const recordHref = (state, href, kind) => {
|
|
|
97
141
|
const scanHtmlAnchors = (state, html) => {
|
|
98
142
|
for (const match of html.matchAll(HTML_ANCHOR_RE)) {
|
|
99
143
|
state.entry.anchors.push(match[1]);
|
|
144
|
+
state.entry.targets.push({ id: match[1], kind: "html", authored: true, ...(findHtmlIdSpan(state, match[1]) ?? {}) });
|
|
100
145
|
}
|
|
101
146
|
};
|
|
102
147
|
const scanInline = (state, nodes) => {
|
|
103
148
|
if (!nodes)
|
|
104
149
|
return;
|
|
105
150
|
for (const node of nodes) {
|
|
151
|
+
const inlineId = authoredInlineAnchor(node);
|
|
152
|
+
if (inlineId) {
|
|
153
|
+
state.entry.anchors.push(inlineId);
|
|
154
|
+
addTarget(state, inlineId, node.type, anchorLabel(node), state.range);
|
|
155
|
+
}
|
|
106
156
|
switch (node.type) {
|
|
107
157
|
case "link":
|
|
108
158
|
recordHref(state, node.href, "link");
|
|
@@ -124,6 +174,9 @@ const scanInline = (state, nodes) => {
|
|
|
124
174
|
};
|
|
125
175
|
/** Explicit anchor on a node — the parser stores `{#id}` as props.slug on headings, props.id elsewhere. */
|
|
126
176
|
const explicitAnchor = (node) => {
|
|
177
|
+
// `::youtube{#…}` carries the video's YouTube id: no element has it
|
|
178
|
+
if (node.type === "youtube")
|
|
179
|
+
return undefined;
|
|
127
180
|
if (typeof node.props?.id === "string")
|
|
128
181
|
return node.props.id;
|
|
129
182
|
if (typeof node.props?.slug === "string")
|
|
@@ -132,21 +185,26 @@ const explicitAnchor = (node) => {
|
|
|
132
185
|
};
|
|
133
186
|
/**
|
|
134
187
|
* Walk the tree collecting headings, EXPLICIT anchors, links, and key
|
|
135
|
-
* uses.
|
|
136
|
-
*
|
|
137
|
-
*
|
|
138
|
-
*
|
|
139
|
-
*
|
|
140
|
-
*
|
|
188
|
+
* uses. Heading ids come from `state.pageIds` (format-dogsbay-md headingIds,
|
|
189
|
+
* THE slug pass render-html and the Astro build use — every heading, nested
|
|
190
|
+
* ones too, -1/-2 dedupe around every id already on the page, an author's
|
|
191
|
+
* id as the page writes it), so validate and link targets agree with what
|
|
192
|
+
* the site emits. The tree is never changed, so authored `{#id}`s stay
|
|
193
|
+
* distinguishable from generated slugs.
|
|
141
194
|
*/
|
|
142
195
|
const scanTree = (state, nodes) => {
|
|
196
|
+
const outer = state.range;
|
|
143
197
|
for (const node of nodes) {
|
|
198
|
+
state.range = blockRange(node) ?? outer;
|
|
144
199
|
if (node.type === "heading") {
|
|
145
200
|
const text = inlineText(node.inline);
|
|
146
201
|
const id = explicitAnchor(node);
|
|
147
202
|
const level = Number(node.props?.level ?? 0) || 0;
|
|
148
203
|
state.entry.headings.push({ level, text, ...(id ? { id } : {}) });
|
|
149
204
|
}
|
|
205
|
+
const target = authoredAnchor(node);
|
|
206
|
+
if (target)
|
|
207
|
+
addTarget(state, target, node.type, anchorLabel(node, node.type === "heading" ? inlineText(node.inline) : undefined), idLines(node, state.range), node.type === "heading" ? state.pageIds?.get(node)?.id || pageId(target) : target);
|
|
150
208
|
if (node.type === "image") {
|
|
151
209
|
const src = node.props?.src;
|
|
152
210
|
if (typeof src === "string" && src.length > 0)
|
|
@@ -157,11 +215,12 @@ const scanTree = (state, nodes) => {
|
|
|
157
215
|
}
|
|
158
216
|
const anchor = explicitAnchor(node);
|
|
159
217
|
if (anchor)
|
|
160
|
-
state.entry.anchors.push(anchor);
|
|
218
|
+
state.entry.anchors.push(node.type === "heading" ? state.pageIds?.get(node)?.id || pageId(anchor) : anchor);
|
|
161
219
|
scanInline(state, node.inline);
|
|
162
220
|
if (node.children)
|
|
163
221
|
scanTree(state, node.children);
|
|
164
222
|
}
|
|
223
|
+
state.range = outer;
|
|
165
224
|
};
|
|
166
225
|
/**
|
|
167
226
|
* Everything `validate` needs to know about the frontmatter BLOCK (as opposed
|
|
@@ -197,24 +256,47 @@ const scanFrontmatter = (source) => {
|
|
|
197
256
|
frontmatterEmpty: closed ? empty : true,
|
|
198
257
|
};
|
|
199
258
|
};
|
|
200
|
-
const
|
|
259
|
+
const TEMPLATE_PAGE = /^template:[ \t]*["']?jinja["']?[ \t]*$/m;
|
|
260
|
+
const NOT_TEMPLATE = /^template:[ \t]*false[ \t]*$/m;
|
|
261
|
+
const NO_PREPROCESS = /^preprocess:[ \t]*false[ \t]*$/m;
|
|
262
|
+
const indexDoc = (path, source, templateSource = false) => {
|
|
263
|
+
const front = scanFrontmatter(source);
|
|
264
|
+
// where the body starts: past the closing `---` line of a terminated block
|
|
265
|
+
let bodyStart = 0;
|
|
266
|
+
if (front.frontmatterBlock === "block") {
|
|
267
|
+
const m = /\n(?:---|\.\.\.)[ \t]*\r?(?:\n|$)/.exec(source.slice(source.indexOf("\n")));
|
|
268
|
+
if (m)
|
|
269
|
+
bodyStart = source.indexOf("\n") + m.index + m[0].length;
|
|
270
|
+
}
|
|
271
|
+
const fmText = source.slice(0, bodyStart);
|
|
272
|
+
const masked = blankCodeRegions(source);
|
|
273
|
+
// as the build decides (TemplatePages.isTemplatePage): `template: jinja`, or a `templates: jinja`
|
|
274
|
+
// source unless the page says `template: false`; `preprocess: false` is never evaluated
|
|
275
|
+
// a partial declaring `params:` is included by template pages, so it is read as one
|
|
276
|
+
const template = TEMPLATE_PAGE.test(fmText) || /^params:/m.test(fmText) || (templateSource && !NOT_TEMPLATE.test(fmText));
|
|
277
|
+
const variables = NO_PREPROCESS.test(fmText)
|
|
278
|
+
? { definitions: [], uses: [] }
|
|
279
|
+
// an ordinary page is rendered front matter and all; a template page's body only
|
|
280
|
+
: scanFileVariables(path, source, masked, template ? bodyStart : 0, { template });
|
|
281
|
+
variables.definitions.unshift(...scanParams(path, source, bodyStart));
|
|
201
282
|
const entry = {
|
|
202
283
|
path,
|
|
203
284
|
frontmatter: {},
|
|
204
285
|
headings: [],
|
|
205
286
|
anchors: [],
|
|
287
|
+
targets: [],
|
|
206
288
|
links: [],
|
|
207
289
|
includes: [],
|
|
208
290
|
keyUses: [],
|
|
209
291
|
hash: contentHash(source),
|
|
210
|
-
|
|
292
|
+
variables,
|
|
293
|
+
...front,
|
|
211
294
|
};
|
|
212
|
-
const state = { entry, docDir: dirname(path) };
|
|
295
|
+
const state = { entry, docDir: dirname(path), lines: source.split("\n"), taken: new Set() };
|
|
213
296
|
// Includes come from the RAW source (code regions masked): the
|
|
214
297
|
// markdown parser's attrs plugin mangles `{% include %}` lines into
|
|
215
298
|
// element attributes, so the tree never sees them. The raw scan is
|
|
216
299
|
// exactly what the build preprocessor will execute anyway.
|
|
217
|
-
const masked = blankCodeRegions(source);
|
|
218
300
|
// line starts once; lineAt is a binary search (O(links × log lines), not O(links × bytes))
|
|
219
301
|
const lineStarts = [0];
|
|
220
302
|
for (let i = 0; i < masked.length; i++)
|
|
@@ -285,10 +367,12 @@ const indexDoc = (path, source) => {
|
|
|
285
367
|
entry.includes.push({ raw: match[1], target: joinPath(state.docDir, match[1]), line: lineAt(match.index ?? 0) });
|
|
286
368
|
}
|
|
287
369
|
try {
|
|
288
|
-
const { tree, frontmatter } = dogsbayMdToTree(source);
|
|
370
|
+
const { tree, frontmatter } = dogsbayMdToTree(source, { sourceLines: true });
|
|
289
371
|
entry.frontmatter = frontmatter;
|
|
290
372
|
if (typeof frontmatter.title === "string")
|
|
291
373
|
entry.title = frontmatter.title;
|
|
374
|
+
// THE slug pass, read without changing the tree (render-html's ids, the Astro build's)
|
|
375
|
+
state.pageIds = headingIds(tree);
|
|
292
376
|
scanTree(state, tree);
|
|
293
377
|
// Lines for links: each href's successive occurrences in the code-masked source, in
|
|
294
378
|
// document order (the tree carries no positions) — a repeated href maps to the next
|
|
@@ -298,20 +382,25 @@ const indexDoc = (path, source) => {
|
|
|
298
382
|
if (at >= 0)
|
|
299
383
|
link.line = lineAt(at);
|
|
300
384
|
}
|
|
301
|
-
// Renderer-parity auto anchors: exactly the ids the site build
|
|
302
|
-
//
|
|
303
|
-
//
|
|
304
|
-
for (const heading of extractHeadings(tree)) {
|
|
305
|
-
if (heading.slug)
|
|
306
|
-
entry.anchors.push(heading.slug);
|
|
307
|
-
}
|
|
308
|
-
// extractHeadings backfilled props.slug on the heading NODES; read them back in the same tree order
|
|
309
|
-
// scanTree used, so each scanned heading learns the anchor the site renders for it
|
|
385
|
+
// Renderer-parity auto anchors: exactly the ids the site build assigns (and only those), on every
|
|
386
|
+
// heading and generated side sheet — scanTree above already captured authored ones. Read in the
|
|
387
|
+
// same tree order scanTree used, so each scanned heading learns the anchor the site renders for it
|
|
310
388
|
const slugs = [];
|
|
389
|
+
const sheetIds = [];
|
|
311
390
|
const walkSlugs = (nodes) => {
|
|
312
391
|
for (const node of nodes) {
|
|
313
|
-
|
|
314
|
-
|
|
392
|
+
const given = state.pageIds?.get(node);
|
|
393
|
+
if (node.type === "heading") {
|
|
394
|
+
const generated = given?.generated && given.id ? given.id : undefined;
|
|
395
|
+
slugs.push(generated);
|
|
396
|
+
if (generated)
|
|
397
|
+
entry.anchors.push(generated);
|
|
398
|
+
}
|
|
399
|
+
else if (given?.generated && given.id) {
|
|
400
|
+
// a side sheet's id from its title, opened by a link as a heading's is
|
|
401
|
+
entry.anchors.push(given.id);
|
|
402
|
+
sheetIds.push({ id: given.id, label: anchorLabel(node) });
|
|
403
|
+
}
|
|
315
404
|
if (node.children)
|
|
316
405
|
walkSlugs(node.children);
|
|
317
406
|
}
|
|
@@ -319,6 +408,12 @@ const indexDoc = (path, source) => {
|
|
|
319
408
|
walkSlugs(tree);
|
|
320
409
|
entry.headings.forEach((h, i) => { const slug = slugs[i]; if (slug && !h.id)
|
|
321
410
|
h.slug = slug; });
|
|
411
|
+
// headings with no `{#id}`: the slug the site gives them, after the authored targets
|
|
412
|
+
for (const h of entry.headings)
|
|
413
|
+
if (!h.id && h.slug)
|
|
414
|
+
entry.targets.push({ id: h.slug, kind: "heading", ...(h.text ? { label: h.text } : {}), authored: false });
|
|
415
|
+
for (const s of sheetIds)
|
|
416
|
+
entry.targets.push({ id: s.id, kind: "details", ...(s.label ? { label: s.label } : {}), authored: false });
|
|
322
417
|
entry.anchors = [...new Set(entry.anchors)];
|
|
323
418
|
}
|
|
324
419
|
catch (error) {
|
|
@@ -443,6 +538,35 @@ export function anchorAliases(headings) {
|
|
|
443
538
|
}
|
|
444
539
|
return out;
|
|
445
540
|
}
|
|
541
|
+
/** The variables table: definitions and uses by lookup name, and where each definition applies. */
|
|
542
|
+
const variableTable = (configDefs, docs, variants) => {
|
|
543
|
+
const table = new Map();
|
|
544
|
+
const entry = (name) => {
|
|
545
|
+
const key = variableKey(name);
|
|
546
|
+
let e = table.get(key);
|
|
547
|
+
if (!e)
|
|
548
|
+
table.set(key, (e = { kind: "variable", name: key, definitions: [], uses: [] }));
|
|
549
|
+
return e;
|
|
550
|
+
};
|
|
551
|
+
const sorted = [...docs].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
|
552
|
+
const fileDefs = sorted.flatMap((d) => d.variables.definitions);
|
|
553
|
+
const setNames = new Set(fileDefs.filter((d) => d.via === "set" || d.via === "with").map((d) => variableKey(d.name)));
|
|
554
|
+
for (const def of [...configDefs, ...fileDefs]) {
|
|
555
|
+
const out = variants.length ? { ...def, variants: Object.fromEntries(variants.map((v) => [v.id, applies(def, v, setNames)])) } : def;
|
|
556
|
+
entry(def.name).definitions.push(out);
|
|
557
|
+
}
|
|
558
|
+
for (const d of sorted)
|
|
559
|
+
for (const use of d.variables.uses)
|
|
560
|
+
entry(use.name).uses.push(use);
|
|
561
|
+
return table;
|
|
562
|
+
};
|
|
563
|
+
const applies = (def, v, setNames) => {
|
|
564
|
+
if (def.via === "config")
|
|
565
|
+
return def.context.scope === "site" || def.context.source === v.id;
|
|
566
|
+
if (!inFolder(def.file, v.path))
|
|
567
|
+
return false;
|
|
568
|
+
return appliesIn(def.conditions, v.attributes, setNames);
|
|
569
|
+
};
|
|
446
570
|
/** Build every index in one pass over the workspace (or patch a previous one — see BuildIndexOptions). */
|
|
447
571
|
export async function buildWorkspaceIndex(storage, options = {}) {
|
|
448
572
|
const files = (await storage.list()).map(normalizePath);
|
|
@@ -460,8 +584,12 @@ export async function buildWorkspaceIndex(storage, options = {}) {
|
|
|
460
584
|
if (current.has(path) && !changed.has(path))
|
|
461
585
|
maps.set(path, map);
|
|
462
586
|
}
|
|
587
|
+
// the config first: its sources decide which pages are template pages
|
|
588
|
+
const configFile = CONFIG_FILES.find((f) => current.has(f));
|
|
589
|
+
const config = readConfigVariables(configFile, configFile ? await storage.read(configFile) : undefined);
|
|
590
|
+
const configChanged = changed !== null && CONFIG_FILES.some((f) => changed.has(f));
|
|
463
591
|
for (const path of files) {
|
|
464
|
-
const reuse = changed !== null && !changed.has(path);
|
|
592
|
+
const reuse = changed !== null && !changed.has(path) && !configChanged;
|
|
465
593
|
if (isTopicMapPath(path)) {
|
|
466
594
|
if (!(reuse && maps.has(path)))
|
|
467
595
|
maps.set(path, indexMap(path, await storage.read(path)));
|
|
@@ -471,7 +599,7 @@ export async function buildWorkspaceIndex(storage, options = {}) {
|
|
|
471
599
|
}
|
|
472
600
|
else if (isDocPath(path)) {
|
|
473
601
|
if (!(reuse && docs.has(path)))
|
|
474
|
-
docs.set(path, indexDoc(path, await storage.read(path)));
|
|
602
|
+
docs.set(path, indexDoc(path, await storage.read(path), config.templateSources.some((dir) => inFolder(path, dir))));
|
|
475
603
|
}
|
|
476
604
|
}
|
|
477
605
|
// ---- inverted graphs --------------------------------------------------
|
|
@@ -514,6 +642,7 @@ export async function buildWorkspaceIndex(storage, options = {}) {
|
|
|
514
642
|
}
|
|
515
643
|
}
|
|
516
644
|
}
|
|
645
|
+
const variables = variableTable(config.definitions, [...docs.values()], config.variants);
|
|
517
646
|
return {
|
|
518
647
|
files: current,
|
|
519
648
|
docs,
|
|
@@ -522,6 +651,8 @@ export async function buildWorkspaceIndex(storage, options = {}) {
|
|
|
522
651
|
keyFileErrors,
|
|
523
652
|
inbound,
|
|
524
653
|
keyUses,
|
|
654
|
+
variables,
|
|
655
|
+
variants: config.variants,
|
|
525
656
|
stats: {
|
|
526
657
|
files: files.length,
|
|
527
658
|
docs: docs.size,
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Real-filesystem `Storage` (Node only). Kept out of storage.ts so a browser bundle that wants
|
|
3
|
+
* only MemoryStorage and the index (`@dogsbay/commands/indexes`) never reaches node:fs, even
|
|
4
|
+
* through a dynamic import (the playground's item 26).
|
|
5
|
+
*/
|
|
6
|
+
import { type Storage } from "./storage.js";
|
|
7
|
+
/**
|
|
8
|
+
* Real-filesystem storage rooted at a directory. Node-only (dynamic
|
|
9
|
+
* fs imports keep the module loadable in browser bundles that only
|
|
10
|
+
* use MemoryStorage).
|
|
11
|
+
*/
|
|
12
|
+
export interface NodeStorageOptions {
|
|
13
|
+
/**
|
|
14
|
+
* Refuse symlinks whose target resolves OUTSIDE the workspace root
|
|
15
|
+
* (list skips them; read/write/delete/exists throw). Default false —
|
|
16
|
+
* pnpm/monorepo layouts legitimately symlink content in, and the CLI
|
|
17
|
+
* runs on the user's own tree. Turn it on where the tree is UNTRUSTED
|
|
18
|
+
* and the verbs are reachable by an agent (the IDE sidecar does):
|
|
19
|
+
* a repo containing `docs/x -> ~/.ssh` would otherwise expose those files
|
|
20
|
+
* to `where-used`/`validate`/`read`-style verbs.
|
|
21
|
+
*/
|
|
22
|
+
containSymlinks?: boolean;
|
|
23
|
+
}
|
|
24
|
+
export declare class NodeStorage implements Storage {
|
|
25
|
+
private root;
|
|
26
|
+
private readonly containSymlinks;
|
|
27
|
+
private rootReal;
|
|
28
|
+
constructor(root: string, options?: NodeStorageOptions);
|
|
29
|
+
private fs;
|
|
30
|
+
private abs;
|
|
31
|
+
/** `abs()` plus, when contained, a realpath check that no symlink escapes the root. */
|
|
32
|
+
private safeAbs;
|
|
33
|
+
private isInsideRoot;
|
|
34
|
+
list(): Promise<string[]>;
|
|
35
|
+
read(path: string): Promise<string>;
|
|
36
|
+
readBytes(path: string, options?: {
|
|
37
|
+
maxBytes?: number;
|
|
38
|
+
}): Promise<Uint8Array>;
|
|
39
|
+
write(path: string, content: string): Promise<void>;
|
|
40
|
+
delete(path: string): Promise<void>;
|
|
41
|
+
exists(path: string): Promise<boolean>;
|
|
42
|
+
}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Real-filesystem `Storage` (Node only). Kept out of storage.ts so a browser bundle that wants
|
|
3
|
+
* only MemoryStorage and the index (`@dogsbay/commands/indexes`) never reaches node:fs, even
|
|
4
|
+
* through a dynamic import (the playground's item 26).
|
|
5
|
+
*/
|
|
6
|
+
import { normalizeStoragePath } from "./storage.js";
|
|
7
|
+
/** Directories never part of a content workspace. */
|
|
8
|
+
const IGNORED_DIRS = new Set([
|
|
9
|
+
"node_modules", ".git", ".dogsbay", "dist", ".astro", ".turbo",
|
|
10
|
+
]);
|
|
11
|
+
export class NodeStorage {
|
|
12
|
+
root;
|
|
13
|
+
containSymlinks;
|
|
14
|
+
rootReal;
|
|
15
|
+
constructor(root, options = {}) {
|
|
16
|
+
this.root = root;
|
|
17
|
+
this.containSymlinks = options.containSymlinks ?? false;
|
|
18
|
+
}
|
|
19
|
+
async fs() {
|
|
20
|
+
return import("node:fs/promises");
|
|
21
|
+
}
|
|
22
|
+
abs(path) {
|
|
23
|
+
const rel = normalizeStoragePath(path);
|
|
24
|
+
if (rel.startsWith("..")) {
|
|
25
|
+
throw new Error(`Path escapes the workspace root: ${path}`);
|
|
26
|
+
}
|
|
27
|
+
return `${this.root}/${rel}`;
|
|
28
|
+
}
|
|
29
|
+
/** `abs()` plus, when contained, a realpath check that no symlink escapes the root. */
|
|
30
|
+
async safeAbs(path) {
|
|
31
|
+
const abs = this.abs(path);
|
|
32
|
+
if (!this.containSymlinks)
|
|
33
|
+
return abs;
|
|
34
|
+
if (!(await this.isInsideRoot(abs))) {
|
|
35
|
+
throw new Error(`Path resolves outside the workspace root: ${path}`);
|
|
36
|
+
}
|
|
37
|
+
return abs;
|
|
38
|
+
}
|
|
39
|
+
async isInsideRoot(abs) {
|
|
40
|
+
const fs = await this.fs();
|
|
41
|
+
this.rootReal ??= fs.realpath(this.root).catch(() => this.root);
|
|
42
|
+
const rootReal = await this.rootReal;
|
|
43
|
+
// realpath the deepest existing ancestor (the target may not exist yet on write)
|
|
44
|
+
let probe = abs;
|
|
45
|
+
let suffix = "";
|
|
46
|
+
for (;;) {
|
|
47
|
+
try {
|
|
48
|
+
const real = await fs.realpath(probe);
|
|
49
|
+
const full = real + suffix;
|
|
50
|
+
return full === rootReal || full.startsWith(rootReal + "/");
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
const cut = probe.lastIndexOf("/");
|
|
54
|
+
if (cut <= 0)
|
|
55
|
+
return false;
|
|
56
|
+
suffix = probe.slice(cut) + suffix;
|
|
57
|
+
probe = probe.slice(0, cut);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
async list() {
|
|
62
|
+
const fs = await this.fs();
|
|
63
|
+
const out = [];
|
|
64
|
+
// Symlinked directories are walked (pnpm/monorepo layouts symlink
|
|
65
|
+
// content in); the realpath set breaks symlink cycles
|
|
66
|
+
const visited = new Set([await fs.realpath(this.root).catch(() => this.root)]);
|
|
67
|
+
const walk = async (dir, prefix) => {
|
|
68
|
+
let entries;
|
|
69
|
+
try {
|
|
70
|
+
entries = await fs.readdir(dir, { withFileTypes: true });
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
for (const entry of entries) {
|
|
76
|
+
const full = `${dir}/${entry.name}`;
|
|
77
|
+
let isDirectory = entry.isDirectory();
|
|
78
|
+
let isFile = entry.isFile();
|
|
79
|
+
if (entry.isSymbolicLink()) {
|
|
80
|
+
if (this.containSymlinks && !(await this.isInsideRoot(full)))
|
|
81
|
+
continue; // escapes the root
|
|
82
|
+
try {
|
|
83
|
+
const stat = await fs.stat(full); // follows the link
|
|
84
|
+
isDirectory = stat.isDirectory();
|
|
85
|
+
isFile = stat.isFile();
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
continue; // dangling symlink
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
if (isDirectory) {
|
|
92
|
+
if (IGNORED_DIRS.has(entry.name))
|
|
93
|
+
continue;
|
|
94
|
+
if (entry.isSymbolicLink()) {
|
|
95
|
+
try {
|
|
96
|
+
const real = await fs.realpath(full);
|
|
97
|
+
if (visited.has(real))
|
|
98
|
+
continue;
|
|
99
|
+
visited.add(real);
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
await walk(full, `${prefix}${entry.name}/`);
|
|
106
|
+
}
|
|
107
|
+
else if (isFile) {
|
|
108
|
+
out.push(`${prefix}${entry.name}`);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
await walk(this.root, "");
|
|
113
|
+
return out.sort();
|
|
114
|
+
}
|
|
115
|
+
async read(path) {
|
|
116
|
+
const fs = await this.fs();
|
|
117
|
+
return fs.readFile(await this.safeAbs(path), "utf-8");
|
|
118
|
+
}
|
|
119
|
+
async readBytes(path, options = {}) {
|
|
120
|
+
const fs = await this.fs();
|
|
121
|
+
// Contained whatever containSymlinks says: this reads binaries for a page that leaves
|
|
122
|
+
// the workspace, so a symlink out (docs/k.png -> ~/.ssh/key) must not be followed.
|
|
123
|
+
const abs = this.abs(path);
|
|
124
|
+
if (!(await this.isInsideRoot(abs)))
|
|
125
|
+
throw new Error(`Path resolves outside the workspace root: ${path}`);
|
|
126
|
+
const st = await fs.stat(abs);
|
|
127
|
+
if (!st.isFile())
|
|
128
|
+
throw new Error(`Not a file: ${path}`);
|
|
129
|
+
if (options.maxBytes !== undefined && st.size > options.maxBytes)
|
|
130
|
+
throw new Error(`File is over ${options.maxBytes} bytes: ${path}`);
|
|
131
|
+
return new Uint8Array(await fs.readFile(abs));
|
|
132
|
+
}
|
|
133
|
+
async write(path, content) {
|
|
134
|
+
const fs = await this.fs();
|
|
135
|
+
const abs = await this.safeAbs(path);
|
|
136
|
+
const dir = abs.slice(0, abs.lastIndexOf("/"));
|
|
137
|
+
await fs.mkdir(dir, { recursive: true });
|
|
138
|
+
await fs.writeFile(abs, content, "utf-8");
|
|
139
|
+
}
|
|
140
|
+
async delete(path) {
|
|
141
|
+
const fs = await this.fs();
|
|
142
|
+
await fs.unlink(await this.safeAbs(path));
|
|
143
|
+
}
|
|
144
|
+
async exists(path) {
|
|
145
|
+
const fs = await this.fs();
|
|
146
|
+
try {
|
|
147
|
+
await fs.access(await this.safeAbs(path));
|
|
148
|
+
return true;
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
return false;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
package/dist/sha256.d.ts
CHANGED
|
@@ -1 +1,7 @@
|
|
|
1
1
|
export declare function sha256Hex(text: string): string;
|
|
2
|
+
/**
|
|
3
|
+
* Divergence gate (plans/ide-change-review.md §3): a short content hash the agent gets from
|
|
4
|
+
* `topic-read` and hands back as `expect` on a mutation; the index records it per file. Here, not
|
|
5
|
+
* in commands/content.ts, so the index reaches no zod or engine.
|
|
6
|
+
*/
|
|
7
|
+
export declare const contentHash: (text: string) => string;
|
package/dist/sha256.js
CHANGED
|
@@ -58,3 +58,9 @@ export function sha256Hex(text) {
|
|
|
58
58
|
}
|
|
59
59
|
return Array.from(h, (x) => x.toString(16).padStart(8, "0")).join("");
|
|
60
60
|
}
|
|
61
|
+
/**
|
|
62
|
+
* Divergence gate (plans/ide-change-review.md §3): a short content hash the agent gets from
|
|
63
|
+
* `topic-read` and hands back as `expect` on a mutation; the index records it per file. Here, not
|
|
64
|
+
* in commands/content.ts, so the index reaches no zod or engine.
|
|
65
|
+
*/
|
|
66
|
+
export const contentHash = (text) => sha256Hex(text).slice(0, 16);
|
package/dist/storage.d.ts
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
* Injectable workspace storage — the only I/O boundary in the engine.
|
|
3
3
|
*
|
|
4
4
|
* Commands never touch node:fs: they see a `Storage` bound to a
|
|
5
|
-
* workspace root. Implementations: `NodeStorage` (real filesystem
|
|
6
|
-
* `MemoryStorage` (tests, browser). An Electron IPC-backed
|
|
5
|
+
* workspace root. Implementations: `NodeStorage` (real filesystem,
|
|
6
|
+
* in node-storage.ts so this module stays free of Node), `MemoryStorage` (tests, browser). An Electron IPC-backed
|
|
7
7
|
* implementation slots in the same way.
|
|
8
8
|
*
|
|
9
9
|
* All paths are workspace-root-relative posix paths ("a/b.md") — no
|
|
@@ -40,39 +40,3 @@ export declare class MemoryStorage implements Storage {
|
|
|
40
40
|
delete(path: string): Promise<void>;
|
|
41
41
|
exists(path: string): Promise<boolean>;
|
|
42
42
|
}
|
|
43
|
-
/**
|
|
44
|
-
* Real-filesystem storage rooted at a directory. Node-only (dynamic
|
|
45
|
-
* fs imports keep the module loadable in browser bundles that only
|
|
46
|
-
* use MemoryStorage).
|
|
47
|
-
*/
|
|
48
|
-
export interface NodeStorageOptions {
|
|
49
|
-
/**
|
|
50
|
-
* Refuse symlinks whose target resolves OUTSIDE the workspace root
|
|
51
|
-
* (list skips them; read/write/delete/exists throw). Default false —
|
|
52
|
-
* pnpm/monorepo layouts legitimately symlink content in, and the CLI
|
|
53
|
-
* runs on the user's own tree. Turn it on where the tree is UNTRUSTED
|
|
54
|
-
* and the verbs are reachable by an agent (the IDE sidecar does):
|
|
55
|
-
* a repo containing `docs/x -> ~/.ssh` would otherwise expose those files
|
|
56
|
-
* to `where-used`/`validate`/`read`-style verbs.
|
|
57
|
-
*/
|
|
58
|
-
containSymlinks?: boolean;
|
|
59
|
-
}
|
|
60
|
-
export declare class NodeStorage implements Storage {
|
|
61
|
-
private root;
|
|
62
|
-
private readonly containSymlinks;
|
|
63
|
-
private rootReal;
|
|
64
|
-
constructor(root: string, options?: NodeStorageOptions);
|
|
65
|
-
private fs;
|
|
66
|
-
private abs;
|
|
67
|
-
/** `abs()` plus, when contained, a realpath check that no symlink escapes the root. */
|
|
68
|
-
private safeAbs;
|
|
69
|
-
private isInsideRoot;
|
|
70
|
-
list(): Promise<string[]>;
|
|
71
|
-
read(path: string): Promise<string>;
|
|
72
|
-
readBytes(path: string, options?: {
|
|
73
|
-
maxBytes?: number;
|
|
74
|
-
}): Promise<Uint8Array>;
|
|
75
|
-
write(path: string, content: string): Promise<void>;
|
|
76
|
-
delete(path: string): Promise<void>;
|
|
77
|
-
exists(path: string): Promise<boolean>;
|
|
78
|
-
}
|