@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 CHANGED
@@ -21,7 +21,11 @@ Storage (injected I/O) NodeStorage | MemoryStorage | (Electron IPC …)
21
21
  - **Browser-safe at import**: nothing reaches a Node built-in until a
22
22
  `NodeStorage` is used (it loads `node:fs` then). With `MemoryStorage`
23
23
  or a host's own `Storage`, the package bundles for a browser or Worker;
24
- `tests/browser-bundle.test.ts` checks it.
24
+ `tests/browser-bundle.test.ts` checks it. A bundler still makes a chunk
25
+ for every `import()` it finds, so the main entry brings `@dogsbay/render`'s
26
+ chunks and one that imports `node:fs/promises`, even when only the index is
27
+ used. A host that wants only the index imports `@dogsbay/commands/indexes`
28
+ (below).
25
29
  - **Indexes** are built in one pass: per-doc table (frontmatter,
26
30
  headings, anchors, links, includes, `key:` uses), topic-map table,
27
31
  key-definition table (from `*.keys.yaml`), and the inverted
@@ -97,6 +101,54 @@ const workspace = new Workspace(
97
101
  );
98
102
  ```
99
103
 
104
+ ### The index alone: `@dogsbay/commands/indexes`
105
+
106
+ For an editor in a browser (link completion, Go to Definition) that needs the
107
+ workspace index and no verbs:
108
+
109
+ ```ts
110
+ import { buildWorkspaceIndex, MemoryStorage, type DocTarget } from "@dogsbay/commands/indexes";
111
+
112
+ const index = await buildWorkspaceIndex(new MemoryStorage(files));
113
+ const targets: DocTarget[] = index.docs.get("guide.md")?.targets ?? [];
114
+ ```
115
+
116
+ It exports `buildWorkspaceIndex`, `Workspace`, `MemoryStorage`,
117
+ `normalizeStoragePath`, `contentHash`, `anchorAliases`, `anchorAliasTargets`,
118
+ `blankCodeRegions` and the index types, `DocTarget` included. They are the same
119
+ functions the main entry exports. It reaches no zod, no engine or verb, no
120
+ `@dogsbay/render` and no Node built-in, not even through `import()`, and it
121
+ bundles to one file; `tests/indexes-entry.test.ts` checks this. It does use
122
+ the parser through `@dogsbay/format-dogsbay-md/browser`. A host that imports
123
+ that entry too ships one copy, as long as both resolve to the same version.
124
+ `NodeStorage` is only in the main entry.
125
+
126
+ Both `@dogsbay/commands` and `@dogsbay/render` declare `"sideEffects": false`.
127
+
128
+ ### Variables
129
+
130
+ The index lists every template variable (`index.variables`, by lookup name: hyphens as
131
+ underscores, as the build reads them), each with its definitions and uses as ranges (1-based
132
+ line, 0-based columns, end exclusive, as `DocTarget`), from the files alone:
133
+
134
+ - **Definitions** (`via`): `config` (the config's `attributes:`, site-wide or a source's), `set`
135
+ (`{% set %}`, with the `{% if %}` / `{% elif %}` / `{% else %}` / `{% case %}` branches it sits
136
+ under), `with` (an include's `{% with %}` parameters), `param` (a partial's `params:`).
137
+ - **Uses** (`form`): `output` (`{{ }}`; `plain` when the tag is only `{{ name }}`, else its
138
+ `filters`), `condition` (an `if`/`elif`/`switch` test), `expression` (a set's or with's value, a
139
+ `for` list). Code blocks and inline code (but not `{minja}` fences), `{% raw %}` and loop
140
+ variables are not symbols. Each page is read as the build reads it: an ordinary page in content
141
+ mode (front matter included, hyphens in names, no comments, `for` or `with`); a template page or
142
+ a partial with `params:` in template mode (Jinja's grammar). A use's range is the root name.
143
+ - **Variants** (`index.variants`): one per `content.sources` entry, with the site's attributes
144
+ under the source's own. Each definition says whether it applies in each (`variants`): its
145
+ conditions evaluated against that variant's attributes; `null` when a condition reads a name only
146
+ a `{% set %}` gives.
147
+
148
+ The CLI's `--attribute` is not in the files, so it is not in the index. Several definitions per
149
+ name, a `kind` and a resolution `context` keep the shape open to DITA keys and conrefs. The fixture
150
+ `@dogsbay/samples/fixtures/variants` is the shared example.
151
+
100
152
  ## Defining a command
101
153
 
102
154
  ```ts
@@ -14,6 +14,7 @@
14
14
  * H1) is refused with an issue, never guessed.
15
15
  */
16
16
  import { z } from "zod";
17
+ import { contentHash } from "../sha256.js";
17
18
  export interface SectionInfo {
18
19
  level: number;
19
20
  text: string;
@@ -27,13 +28,7 @@ export interface SectionInfo {
27
28
  /** 0-based exclusive end of the section's OWN text (before its first sub-heading). */
28
29
  ownEnd: number;
29
30
  }
30
- /**
31
- * Divergence gate (plans/ide-change-review.md §3): a short content hash the
32
- * agent gets from `topic-read` and hands back as `expect` on a mutation. If
33
- * the target changed in between (a human typing, another agent), the verb
34
- * refuses with the current hash instead of writing over the newer text.
35
- */
36
- export declare const contentHash: (text: string) => string;
31
+ export { contentHash };
37
32
  export declare const topicReadCommand: import("../engine.js").CommandDef<z.ZodObject<{
38
33
  file: z.ZodString;
39
34
  includeBody: z.ZodDefault<z.ZodBoolean>;
@@ -14,7 +14,7 @@
14
14
  * H1) is refused with an issue, never guessed.
15
15
  */
16
16
  import { z } from "zod";
17
- import { sha256Hex } from "../sha256.js";
17
+ import { contentHash } from "../sha256.js";
18
18
  import { dump as dumpYaml, load as loadYaml } from "js-yaml";
19
19
  import { containerOpenBefore, fenceOpenBefore, slugifyHeadingText } from "@dogsbay/format-dogsbay-md/browser";
20
20
  import { normalizeStoragePath } from "../storage.js";
@@ -95,13 +95,7 @@ const loadDoc = async (ctx, rawFile) => {
95
95
  return { file, doc: { frontmatter, body, lines, openBefore, sections, eol } };
96
96
  };
97
97
  const isOutput = (x) => typeof x === "object" && x !== null && "data" in x;
98
- /**
99
- * Divergence gate (plans/ide-change-review.md §3): a short content hash the
100
- * agent gets from `topic-read` and hands back as `expect` on a mutation. If
101
- * the target changed in between (a human typing, another agent), the verb
102
- * refuses with the current hash instead of writing over the newer text.
103
- */
104
- export const contentHash = (text) => sha256Hex(text).slice(0, 16);
98
+ export { contentHash };
105
99
  const sectionHash = (doc, s) => contentHash(doc.lines.slice(s.line, s.end).join("\n"));
106
100
  const fileHash = (doc) => contentHash(doc.frontmatter + doc.lines.join("\n"));
107
101
  const STALE_PREVIEW_LINES = 40;
@@ -0,0 +1,12 @@
1
+ import type { SymbolDefinition, Variant } from "./variables.js";
2
+ export declare const CONFIG_FILES: string[];
3
+ export interface ConfigVariables {
4
+ file?: string;
5
+ variants: Variant[];
6
+ definitions: SymbolDefinition[];
7
+ /** Source folders whose pages are template pages (`templates: jinja`). */
8
+ templateSources: string[];
9
+ }
10
+ export declare function readConfigVariables(file: string | undefined, text: string | undefined): ConfigVariables;
11
+ /** Is `path` inside the source folder `dir` (workspace-relative; `""` is the root)? */
12
+ export declare const inFolder: (path: string, dir: string) => boolean;
@@ -0,0 +1,78 @@
1
+ /**
2
+ * The config's part in the variables index: one variant per `content.sources` entry (the site's
3
+ * `attributes:` under the source's own), and each attribute as a definition with its range in the
4
+ * YAML. Read with `yaml` (js-yaml gives no positions). Never throws: a config that does not parse
5
+ * gives no variants and no definitions.
6
+ */
7
+ import { isMap, isScalar, isSeq, LineCounter, parseDocument } from "yaml";
8
+ export const CONFIG_FILES = ["dogsbay.config.yml", "dogsbay.config.yaml", "dogsbay.config.json"];
9
+ const clean = (p) => p.replace(/\\/g, "/").replace(/^\.\/?/, "").replace(/\/+$/, "");
10
+ const get = (map, key) => (isMap(map) ? map.get(key, true) : undefined);
11
+ export function readConfigVariables(file, text) {
12
+ const out = { variants: [], definitions: [], templateSources: [], ...(file ? { file } : {}) };
13
+ if (!file || text === undefined)
14
+ return out;
15
+ const counter = new LineCounter();
16
+ let doc;
17
+ try {
18
+ doc = parseDocument(text, { lineCounter: counter, uniqueKeys: false });
19
+ }
20
+ catch {
21
+ return out;
22
+ }
23
+ if (doc.errors.length || !isMap(doc.contents))
24
+ return out;
25
+ const root = doc.contents;
26
+ const attrsOf = (node, context) => {
27
+ const values = {};
28
+ if (!isMap(node))
29
+ return values;
30
+ for (const pair of node.items) {
31
+ const key = pair.key;
32
+ if (!isScalar(key) || typeof key.value !== "string" && typeof key.value !== "number")
33
+ continue;
34
+ const name = String(key.value);
35
+ const value = pair.value;
36
+ // toJS with the document resolves an alias (`*no`), within yaml's alias-count limit
37
+ try {
38
+ values[name] = value && typeof value.toJS === "function" ? value.toJS(doc) : null;
39
+ }
40
+ catch {
41
+ values[name] = null;
42
+ }
43
+ const [start, end] = key.range ?? [0, 0];
44
+ const pos = counter.linePos(start);
45
+ // a quoted key: the name starts after the quote
46
+ const quoted = text[start] === '"' || text[start] === "'" ? 1 : 0;
47
+ out.definitions.push({
48
+ kind: "variable", name, via: "config",
49
+ ...(isScalar(value) && value.range ? { value: text.slice(value.range[0], value.range[1]) } : {}),
50
+ conditions: [], context,
51
+ file, line: pos.line, from: pos.col - 1 + quoted, to: pos.col - 1 + quoted + (end - start - 2 * quoted),
52
+ });
53
+ }
54
+ return values;
55
+ };
56
+ const site = attrsOf(get(root, "attributes"), { scope: "site" });
57
+ const sources = get(get(root, "content"), "sources");
58
+ if (isSeq(sources) && sources.items.length) {
59
+ sources.items.forEach((item, i) => {
60
+ const ns = get(item, "namespace");
61
+ const namespace = isScalar(ns) && ns.value != null ? String(ns.value) : undefined;
62
+ const p = get(item, "path");
63
+ const path = isScalar(p) && typeof p.value === "string" ? clean(p.value) : "";
64
+ const id = namespace ?? `source-${i}`;
65
+ const own = attrsOf(get(item, "attributes"), { scope: "source", source: id });
66
+ const t = get(item, "templates");
67
+ if (isScalar(t) && t.value === "jinja")
68
+ out.templateSources.push(path);
69
+ out.variants.push({ id, ...(namespace ? { namespace } : {}), path, attributes: { ...site, ...own } });
70
+ });
71
+ }
72
+ else if (out.definitions.length) {
73
+ out.variants.push({ id: "default", path: "", attributes: site });
74
+ }
75
+ return out;
76
+ }
77
+ /** Is `path` inside the source folder `dir` (workspace-relative; `""` is the root)? */
78
+ export const inFolder = (path, dir) => dir === "" || path === dir || path.startsWith(`${dir}/`);
package/dist/index.d.ts CHANGED
@@ -9,9 +9,11 @@
9
9
  * No I/O assumptions: commands see an injected Storage (real fs in Node,
10
10
  * memory in tests/browser, IPC-backed in Electron).
11
11
  */
12
- export { type Storage, MemoryStorage, NodeStorage, normalizeStoragePath, } from "./storage.js";
12
+ export { type Storage, MemoryStorage, normalizeStoragePath, } from "./storage.js";
13
+ export { NodeStorage, type NodeStorageOptions } from "./node-storage.js";
13
14
  export { Workspace } from "./workspace.js";
14
- export { buildWorkspaceIndex, anchorAliases, anchorAliasTargets, blankCodeRegions, type BuildIndexOptions, type WorkspaceIndex, type DocIndexEntry, type DocHeading, type DocLink, type DocInclude, type TopicMapIndexEntry, type TopicMapRef, type KeyDefinition, type KeyFileError, type InboundRef, type RefKind, } from "./indexes.js";
15
+ export { buildWorkspaceIndex, anchorAliases, anchorAliasTargets, blankCodeRegions, type BuildIndexOptions, type WorkspaceIndex, type DocIndexEntry, type DocHeading, type DocLink, type DocInclude, type DocTarget, type TopicMapIndexEntry, type TopicMapRef, type KeyDefinition, type KeyFileError, type InboundRef, type RefKind, } from "./indexes.js";
16
+ export { expressionNames, variableKey, type SymbolEntry, type SymbolDefinition, type SymbolUse, type SymbolRange, type SymbolCondition, type SymbolContext, type DefinitionVia, type UseForm, type FileVariables, type Variant, } from "./variables.js";
15
17
  export { flagForField, FlagArgumentError, type FlagSpec } from "./flags.js";
16
18
  export { commandInputJsonSchema, type CommandJsonSchema } from "./json-schema.js";
17
19
  export { defineCommand, CommandRegistry, createTaskQueue, shapeOf, unwrap, isRequired, type CommandDef, type CommandContext, type CommandWrites, type CommandOutput, type CommandResult, type EngineIssue, type IssueSeverity, } from "./engine.js";
@@ -29,7 +31,7 @@ import { splitTopicCommand, mergeTopicsCommand } from "./commands/refactor-struc
29
31
  export { WELL_KNOWN_FIELDS, type FieldSpec, type FrontmatterPolicy, } from "@dogsbay/types";
30
32
  export { linkRetargetCommand } from "./commands/link-retarget.js";
31
33
  export { validateCommand, whereUsedCommand, renderPageCommand, keysListCommand, keysResolveCommand, topicmapResolveCommand, reindexCommand, renameFileCommand, safeDeleteCommand, extractIncludeCommand, renameKeyCommand, keyifyCommand, splitTopicCommand, mergeTopicsCommand, };
32
- export { contentHash } from "./commands/content.js";
34
+ export { contentHash } from "./sha256.js";
33
35
  export { topicReadCommand, topicSetTitleCommand, sectionReplaceCommand, blockInsertCommand, blockDeleteCommand, propsGetCommand, propsSetCommand, } from "./commands/content.js";
34
36
  export { mapListCommand, mapAddRefCommand, mapMoveRefCommand, mapRemoveRefCommand, mapSetPropsCommand, } from "./commands/topicmap-edit.js";
35
37
  export declare const createDefaultRegistry: () => CommandRegistry;
package/dist/index.js CHANGED
@@ -9,9 +9,11 @@
9
9
  * No I/O assumptions: commands see an injected Storage (real fs in Node,
10
10
  * memory in tests/browser, IPC-backed in Electron).
11
11
  */
12
- export { MemoryStorage, NodeStorage, normalizeStoragePath, } from "./storage.js";
12
+ export { MemoryStorage, normalizeStoragePath, } from "./storage.js";
13
+ export { NodeStorage } from "./node-storage.js";
13
14
  export { Workspace } from "./workspace.js";
14
15
  export { buildWorkspaceIndex, anchorAliases, anchorAliasTargets, blankCodeRegions, } from "./indexes.js";
16
+ export { expressionNames, variableKey, } from "./variables.js";
15
17
  export { flagForField, FlagArgumentError } from "./flags.js";
16
18
  export { commandInputJsonSchema } from "./json-schema.js";
17
19
  export { defineCommand, CommandRegistry, createTaskQueue, shapeOf, unwrap, isRequired, } from "./engine.js";
@@ -31,7 +33,7 @@ export { WELL_KNOWN_FIELDS, } from "@dogsbay/types";
31
33
  export { linkRetargetCommand } from "./commands/link-retarget.js";
32
34
  import { mapListCommand, mapAddRefCommand, mapMoveRefCommand, mapRemoveRefCommand, mapSetPropsCommand, } from "./commands/topicmap-edit.js";
33
35
  export { validateCommand, whereUsedCommand, renderPageCommand, keysListCommand, keysResolveCommand, topicmapResolveCommand, reindexCommand, renameFileCommand, safeDeleteCommand, extractIncludeCommand, renameKeyCommand, keyifyCommand, splitTopicCommand, mergeTopicsCommand, };
34
- export { contentHash } from "./commands/content.js";
36
+ export { contentHash } from "./sha256.js";
35
37
  export { topicReadCommand, topicSetTitleCommand, sectionReplaceCommand, blockInsertCommand, blockDeleteCommand, propsGetCommand, propsSetCommand, } from "./commands/content.js";
36
38
  export { mapListCommand, mapAddRefCommand, mapMoveRefCommand, mapRemoveRefCommand, mapSetPropsCommand, } from "./commands/topicmap-edit.js";
37
39
  /** The standard registry with every built-in command registered. */
@@ -0,0 +1,15 @@
1
+ /**
2
+ * `@dogsbay/commands/indexes` — the workspace index on its own, for a browser or Worker bundle
3
+ * (the playground's link box, completion, Go to Definition; item 26).
4
+ *
5
+ * It reaches no zod, no command engine, no @dogsbay/render and no Node built-in, not even
6
+ * through a dynamic import: `tests/indexes-entry.test.ts` bundles this file and fails on any of
7
+ * them. The parser it does need (format-dogsbay-md's `/browser` entry) is the same module the
8
+ * host already ships, so a bundler keeps one copy. Everything here is also exported by the main
9
+ * entry, which adds the verbs and `NodeStorage`.
10
+ */
11
+ export { type Storage, MemoryStorage, normalizeStoragePath } from "./storage.js";
12
+ export { Workspace } from "./workspace.js";
13
+ export { contentHash } from "./sha256.js";
14
+ export { buildWorkspaceIndex, anchorAliases, anchorAliasTargets, blankCodeRegions, type BuildIndexOptions, type WorkspaceIndex, type DocIndexEntry, type DocHeading, type DocLink, type DocInclude, type DocTarget, type TopicMapIndexEntry, type TopicMapRef, type KeyDefinition, type KeyFileError, type InboundRef, type RefKind, } from "./indexes.js";
15
+ export { expressionNames, variableKey, type SymbolEntry, type SymbolDefinition, type SymbolUse, type SymbolRange, type SymbolCondition, type SymbolContext, type DefinitionVia, type UseForm, type FileVariables, type Variant, } from "./variables.js";
@@ -0,0 +1,15 @@
1
+ /**
2
+ * `@dogsbay/commands/indexes` — the workspace index on its own, for a browser or Worker bundle
3
+ * (the playground's link box, completion, Go to Definition; item 26).
4
+ *
5
+ * It reaches no zod, no command engine, no @dogsbay/render and no Node built-in, not even
6
+ * through a dynamic import: `tests/indexes-entry.test.ts` bundles this file and fails on any of
7
+ * them. The parser it does need (format-dogsbay-md's `/browser` entry) is the same module the
8
+ * host already ships, so a bundler keeps one copy. Everything here is also exported by the main
9
+ * entry, which adds the verbs and `NodeStorage`.
10
+ */
11
+ export { MemoryStorage, normalizeStoragePath } from "./storage.js";
12
+ export { Workspace } from "./workspace.js";
13
+ export { contentHash } from "./sha256.js";
14
+ export { buildWorkspaceIndex, anchorAliases, anchorAliasTargets, blankCodeRegions, } from "./indexes.js";
15
+ export { expressionNames, variableKey, } from "./variables.js";
package/dist/indexes.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { type TopicMapError } from "@dogsbay/format-topicmap";
2
2
  import type { Storage } from "./storage.js";
3
+ import { type FileVariables, type SymbolEntry, type Variant } from "./variables.js";
3
4
  export interface DocHeading {
4
5
  level: number;
5
6
  text: string;
@@ -34,6 +35,26 @@ export interface DocInclude {
34
35
  /** 1-based line of the directive. */
35
36
  line?: number;
36
37
  }
38
+ /**
39
+ * A place a `#fragment` link can land on, for a link box, completion after `page.md#`, Go to
40
+ * Definition and Rename. Authored targets are the `{#id}`s the author wrote (on a heading, a
41
+ * paragraph, a code block, a table, any container directive, an image, an inline directive) and
42
+ * raw `<a id>` / `id="…"` anchors; never an id the site or a component makes (tab panels,
43
+ * footnotes) and never a video's `::youtube{#…}` (its YouTube id). A heading with no `{#id}` is
44
+ * listed too, `authored: false`, with the slug the site gives it and no range.
45
+ */
46
+ export interface DocTarget {
47
+ id: string;
48
+ /** The node type: `heading`, `paragraph`, `code`, `table`, `callout`, `details`, `tabs`, `tab`, `image`, `badge`, …; `html` for a raw anchor. */
49
+ kind: string;
50
+ /** Its title, caption or label, an image's alt, a heading's text. */
51
+ label?: string;
52
+ authored: boolean;
53
+ /** 1-based line of the `#id` (the id's value for a raw anchor), and its 0-based columns, end exclusive. */
54
+ line?: number;
55
+ from?: number;
56
+ to?: number;
57
+ }
37
58
  export interface DocIndexEntry {
38
59
  path: string;
39
60
  frontmatter: Record<string, unknown>;
@@ -41,6 +62,8 @@ export interface DocIndexEntry {
41
62
  headings: DocHeading[];
42
63
  /** Every id a `#fragment` link can land on: explicit heading ids, `<a id>` anchors, heading slugs. */
43
64
  anchors: string[];
65
+ /** The same places with their kind, label and where the id is written (`DocTarget`), in document order. */
66
+ targets: DocTarget[];
44
67
  links: DocLink[];
45
68
  includes: DocInclude[];
46
69
  /** Key names referenced via `key:` hrefs. */
@@ -65,6 +88,8 @@ export interface DocIndexEntry {
65
88
  frontmatterEmpty: boolean;
66
89
  /** Set when the file could not be parsed; the entry is otherwise empty. */
67
90
  parseError?: string;
91
+ /** Template variables this file defines (`{% set %}`, `{% with %}`, `params:`) and reads, with ranges. */
92
+ variables: FileVariables;
68
93
  /**
69
94
  * Hash of the source bytes this entry was built from — the same hash
70
95
  * `topic-read` returns and the content verbs accept as `expect`, so a fix
@@ -124,6 +149,14 @@ export interface WorkspaceIndex {
124
149
  inbound: Map<string, InboundRef[]>;
125
150
  /** Key name → files that use it (via key: hrefs). */
126
151
  keyUses: Map<string, string[]>;
152
+ /**
153
+ * Template variables by lookup name (hyphens as underscores): every definition (the config's
154
+ * `attributes:`, `{% set %}`, `{% with %}`, `params:`) and every use, config first, then files in
155
+ * path order. See plans/variables-in-the-index.md.
156
+ */
157
+ variables: Map<string, SymbolEntry>;
158
+ /** One per `content.sources` entry of the config (none without a config). */
159
+ variants: Variant[];
127
160
  stats: {
128
161
  files: number;
129
162
  docs: number;