@capybara-hq/plugin-sdk 0.1.0-rc.7 → 0.1.0-rc.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/README.md +1 -1
  2. package/agent-docs/agent-templates.md +14 -2
  3. package/agent-docs/concepts.md +14 -5
  4. package/agent-docs/connector-templates.md +11 -3
  5. package/agent-docs/extension-points/channel.md +1 -1
  6. package/agent-docs/extension-points/context.md +15 -0
  7. package/agent-docs/extension-points/device-provider.md +15 -0
  8. package/agent-docs/extension-points/file-preview.md +3 -1
  9. package/agent-docs/extension-points/model-provider.md +3 -1
  10. package/agent-docs/extension-points/object-store.md +2 -0
  11. package/agent-docs/extension-points/push-provider.md +17 -0
  12. package/agent-docs/extensions.md +77 -4
  13. package/agent-docs/plugin-format.md +51 -12
  14. package/agent-docs/setup.md +54 -0
  15. package/dist/agent-template.d.ts +15 -6
  16. package/dist/agent-template.js +32 -13
  17. package/dist/avatar-presets.d.ts +8 -0
  18. package/dist/avatar-presets.js +17 -0
  19. package/dist/bootstrap.d.ts +109 -1
  20. package/dist/bootstrap.js +185 -2
  21. package/dist/cards.d.ts +60 -13
  22. package/dist/cards.js +88 -18
  23. package/dist/channel.d.ts +128 -47
  24. package/dist/channel.js +10 -5
  25. package/dist/client-css.d.ts +36 -0
  26. package/dist/client-css.js +326 -0
  27. package/dist/client-section.d.ts +35 -0
  28. package/dist/client-section.js +133 -0
  29. package/dist/config-ui.d.ts +28 -6
  30. package/dist/config-ui.js +88 -25
  31. package/dist/config-url-fetch.d.ts +19 -0
  32. package/dist/config-url-fetch.js +43 -0
  33. package/dist/connector-auth.d.ts +13 -2
  34. package/dist/connector-auth.js +82 -8
  35. package/dist/connector.d.ts +74 -32
  36. package/dist/context.d.ts +40 -0
  37. package/dist/context.js +2 -0
  38. package/dist/ctx.d.ts +210 -30
  39. package/dist/ctx.js +9 -1
  40. package/dist/define-extension.d.ts +23 -13
  41. package/dist/define-extension.js +19 -5
  42. package/dist/device-denied-paths.d.ts +20 -0
  43. package/dist/device-denied-paths.js +118 -0
  44. package/dist/device-operation.d.ts +339 -0
  45. package/dist/device-operation.js +312 -0
  46. package/dist/device-protocol.d.ts +285 -50
  47. package/dist/device-protocol.js +755 -90
  48. package/dist/device-provider.d.ts +708 -0
  49. package/dist/device-provider.js +325 -0
  50. package/dist/device-service.d.ts +52 -0
  51. package/dist/device-service.js +105 -0
  52. package/dist/dial-in.d.ts +239 -0
  53. package/dist/dial-in.js +155 -0
  54. package/dist/directory.d.ts +15 -12
  55. package/dist/extension-point.d.ts +2 -0
  56. package/dist/extension-point.js +7 -3
  57. package/dist/field-meta.d.ts +19 -0
  58. package/dist/field-meta.js +54 -0
  59. package/dist/file-preview.d.ts +43 -10
  60. package/dist/git-hosts.d.ts +53 -0
  61. package/dist/git-hosts.js +98 -0
  62. package/dist/hooks.d.ts +125 -20
  63. package/dist/hooks.js +5 -0
  64. package/dist/http-access.d.ts +71 -0
  65. package/dist/http-access.js +12 -0
  66. package/dist/identity.d.ts +38 -9
  67. package/dist/identity.js +21 -1
  68. package/dist/index.d.ts +31 -4
  69. package/dist/index.js +31 -4
  70. package/dist/model-params.d.ts +41 -22
  71. package/dist/model-params.js +28 -15
  72. package/dist/model.d.ts +210 -75
  73. package/dist/model.js +152 -19
  74. package/dist/net.d.ts +52 -0
  75. package/dist/net.js +34 -0
  76. package/dist/network-classes.d.ts +98 -0
  77. package/dist/network-classes.js +291 -0
  78. package/dist/permissions.d.ts +65 -22
  79. package/dist/permissions.js +139 -43
  80. package/dist/platform-only.d.ts +27 -0
  81. package/dist/platform-only.js +35 -0
  82. package/dist/plugin-manifest.d.ts +40 -9
  83. package/dist/plugin-manifest.js +171 -60
  84. package/dist/plugin-package.d.ts +82 -39
  85. package/dist/plugin-package.js +68 -41
  86. package/dist/push.d.ts +75 -0
  87. package/dist/push.js +87 -0
  88. package/dist/sandbox-linux-runtime-source.d.ts +1 -0
  89. package/dist/sandbox-linux-runtime-source.js +2343 -0
  90. package/dist/sandbox-native-runtime-source.d.ts +10 -0
  91. package/dist/sandbox-native-runtime-source.js +476 -0
  92. package/dist/sandbox-runtime-source.d.ts +47 -0
  93. package/dist/sandbox-runtime-source.js +73 -0
  94. package/dist/sandbox-write-denies.d.ts +139 -0
  95. package/dist/sandbox-write-denies.js +869 -0
  96. package/dist/secret.d.ts +8 -2
  97. package/dist/secret.js +11 -4
  98. package/dist/setup-check.d.ts +128 -0
  99. package/dist/setup-check.js +142 -0
  100. package/dist/setup-guide-parse.d.ts +121 -0
  101. package/dist/setup-guide-parse.js +356 -0
  102. package/dist/setup-guide-render.d.ts +45 -0
  103. package/dist/setup-guide-render.js +351 -0
  104. package/dist/setup-guide.d.ts +86 -72
  105. package/dist/setup-guide.js +340 -108
  106. package/dist/shell-capabilities.d.ts +211 -0
  107. package/dist/shell-capabilities.js +44 -0
  108. package/dist/shell-environment.d.ts +57 -0
  109. package/dist/shell-environment.js +21 -0
  110. package/dist/skill.d.ts +27 -17
  111. package/dist/skill.js +40 -26
  112. package/dist/storage.d.ts +52 -25
  113. package/dist/svg-viewbox.d.ts +10 -0
  114. package/dist/svg-viewbox.js +24 -0
  115. package/dist/theme-assets.d.ts +55 -0
  116. package/dist/theme-assets.js +489 -0
  117. package/dist/theme-readability.d.ts +37 -0
  118. package/dist/theme-readability.js +145 -0
  119. package/dist/theme-tokens.generated.d.ts +299 -0
  120. package/dist/theme-tokens.generated.js +184 -0
  121. package/dist/theme.d.ts +190 -0
  122. package/dist/theme.js +471 -0
  123. package/dist/tool.d.ts +104 -30
  124. package/dist/tool.js +29 -9
  125. package/dist/ui-parts.d.ts +23 -0
  126. package/dist/ui-parts.js +385 -0
  127. package/dist/ui-resolve.d.ts +35 -0
  128. package/dist/ui-resolve.js +42 -0
  129. package/dist/ui-slots.d.ts +65 -0
  130. package/dist/ui-slots.js +261 -0
  131. package/dist/ui.d.ts +232 -77
  132. package/dist/ui.js +104 -27
  133. package/dist/url.d.ts +4 -1
  134. package/dist/url.js +4 -1
  135. package/dist/web.d.ts +26 -20
  136. package/package.json +13 -1
  137. package/schemas/bootstrap-extra.v1.schema.json +186 -0
  138. package/schemas/bootstrap.v1.schema.json +20 -0
  139. package/schemas/connector-template.v1.schema.json +62 -4
  140. package/schemas/plugin.v1.schema.json +93 -143
  141. package/schemas/theme.v1.schema.json +302 -0
  142. package/agent-docs/extension-points/sandbox.md +0 -15
  143. package/dist/org-access.d.ts +0 -27
  144. package/dist/org-access.js +0 -35
  145. package/dist/sandbox.d.ts +0 -254
  146. package/dist/sandbox.js +0 -153
@@ -1,128 +1,116 @@
1
1
  /**
2
- * Plugin setup guides (spec `2026-11-08-plugin-setup-guides-design.md`): setup material a plugin
3
- * ships (steps and template files such as Slack's app manifest) that the kernel renders with a
4
- * fixed set of safe, deterministic variables and the web shows where the person needs it. The
5
- * format lives in `plugin.json` `setupGuides` ({@link PluginSetupGuide}); this module holds the
6
- * places, their modes and variables, the limits and the pure renderer.
2
+ * Plugin setup guides v2 (spec `2026-11-09-setup-guides-v2-design.md`): Markdown documents a plugin
3
+ * ships (`guides/<id>.md`, optional `guides/<id>.zh.md`) that the kernel renders for a place with a
4
+ * fixed set of safe, deterministic variables, mode and audience sections and live check rows. The
5
+ * declaration lives in `plugin.json` `setupGuides` ({@link PluginSetupGuide}); this module holds the
6
+ * place registry, the limits, the validator and the drift hash. The parser is
7
+ * `setup-guide-parse.ts`, the renderer `setup-guide-render.ts`.
7
8
  *
8
- * Placeholders are `{{name}}` (spaces inside the braces allowed) with `name` matching
9
- * `[A-Za-z][A-Za-z0-9]*`. There is no other syntax: no conditionals, loops, filters or escapes. A
10
- * placeholder the place does not define, or one without a value, stays as written.
9
+ * Variables are `{{name}}` (spaces inside the braces allowed) with `name` matching
10
+ * `[A-Za-z][A-Za-z0-9]*`. There is no other template syntax.
11
11
  */
12
- /** Where a guide is shown. `channel-connection`: 新建渠道 and the channel detail page. */
13
- export const SETUP_GUIDE_PLACES = ["channel-connection"];
12
+ import { createHash } from "node:crypto";
13
+ import { analyzeSetupGuide, checkMarkerIndex, ENCODED_SENTINEL_RE, lineSelected, normalizeGuideSource, parseGuideMarkdown, preparedGuideText, SENTINEL_RE, scanGuide, visitGuide, } from "./setup-guide-parse.js";
14
14
  /**
15
- * The modes of each place: a step or file with `mode` applies to that mode only.
16
- * `channel-connection`: the connection's `inboundMode`.
15
+ * Where a guide is shown. `channel-connection`: "New channel" and the channel detail page;
16
+ * `connector-template`: the pages of a connector template and the connectors made from it;
17
+ * `extension-deployment`: the super admin's page of the extension, whose checks verify the
18
+ * platform deployment config (a push provider's credentials); `device-connection`: the guide of a
19
+ * device provider's connection (how a member connects a machine through it).
17
20
  */
18
- export const SETUP_GUIDE_MODES = {
19
- "channel-connection": ["long_connection", "webhook"],
21
+ export const SETUP_GUIDE_PLACES = [
22
+ "channel-connection",
23
+ "connector-template",
24
+ "extension-deployment",
25
+ "device-connection",
26
+ ];
27
+ const COMMON_VARIABLES = {
28
+ publicUrl: "url",
29
+ orgName: "text",
30
+ pluginName: "token",
31
+ pluginVersion: "token",
32
+ mode: "token",
20
33
  };
21
- /**
22
- * The variables of each place. None is a secret: the kernel fills them from public URLs, names and
23
- * versions only (`publicUrl`, `webhookUrl`, `signInCallbackUrl`, `connectionName`, `orgName`,
24
- * `pluginName`, `pluginVersion`, `mode`).
25
- */
26
- export const SETUP_GUIDE_VARIABLES = {
27
- "channel-connection": [
28
- "publicUrl",
29
- "webhookUrl",
30
- "signInCallbackUrl",
31
- "connectionName",
32
- "orgName",
33
- "pluginName",
34
- "pluginVersion",
35
- "mode",
36
- ],
34
+ /** The place registry. None of the variables is a secret. */
35
+ export const SETUP_GUIDE_PLACE_INFO = {
36
+ "channel-connection": {
37
+ modes: ["long_connection", "webhook"],
38
+ audiences: ["admin"],
39
+ variables: {
40
+ ...COMMON_VARIABLES,
41
+ webhookUrl: "url",
42
+ signInCallbackUrl: "url",
43
+ connectionName: "text",
44
+ },
45
+ drift: true,
46
+ checks: true,
47
+ },
48
+ "connector-template": {
49
+ modes: [],
50
+ audiences: ["admin", "member"],
51
+ variables: {
52
+ ...COMMON_VARIABLES,
53
+ oauthCallbackUrl: "url",
54
+ signInCallbackUrl: "url",
55
+ templateId: "token",
56
+ templateName: "text",
57
+ connectorName: "text",
58
+ },
59
+ drift: true,
60
+ checks: true,
61
+ },
62
+ "extension-deployment": {
63
+ modes: [],
64
+ audiences: ["admin"],
65
+ variables: { ...COMMON_VARIABLES, pluginName: "text", signInCallbackUrl: "url" },
66
+ drift: false,
67
+ checks: true,
68
+ },
69
+ "device-connection": {
70
+ modes: [],
71
+ audiences: ["member"],
72
+ variables: { publicUrl: "url", orgId: "token", orgName: "text", pluginName: "token" },
73
+ drift: false,
74
+ checks: false,
75
+ },
37
76
  };
38
- /** Languages of a template file: the code block's label and how values are escaped. */
39
- export const SETUP_GUIDE_LANGUAGES = ["yaml", "json", "text"];
40
77
  /** Limits of setup guides. */
41
78
  export const SETUP_GUIDE_LIMITS = {
42
79
  /** Guides per plugin. */
43
80
  guides: 8,
44
- /** Steps per guide. */
45
- steps: 20,
46
- /** Files per guide. */
47
- files: 8,
48
- /** Characters of a step (each language). */
49
- stepChars: 2000,
50
- /** Characters of a title (each language). */
81
+ /** Connector templates one `connector-template` guide covers. */
82
+ templatesPerGuide: 64,
83
+ /** Bytes per document (each language). */
84
+ docBytes: 65536,
85
+ /** Fenced code blocks per document. */
86
+ codeBlocks: 24,
87
+ /** Check lines per document. */
88
+ checks: 16,
89
+ /** Sections per document. */
90
+ sections: 16,
91
+ /** Characters of the title and of a heading. */
51
92
  titleChars: 100,
52
- /** Bytes of a template file. */
53
- fileBytes: 64 * 1024,
93
+ /** Characters of a check label. */
94
+ checkLabelChars: 80,
95
+ /** Characters of a code fence title. */
96
+ fenceTitleChars: 100,
97
+ /** Markdown nesting depth. */
98
+ depth: 16,
54
99
  };
55
- /** File names a template file may have (checked on the path). */
56
- export const SETUP_GUIDE_FILE_RE = /\.(?:tmpl|ya?ml|json|txt)$/i;
57
- const PLACEHOLDER_RE = /\{\{\s*([A-Za-z][A-Za-z0-9]*)\s*\}\}/g;
58
- /** The placeholder names a text uses, each once, in order of first use. */
59
- export function setupGuidePlaceholders(text) {
60
- const out = [];
61
- for (const m of text.matchAll(PLACEHOLDER_RE)) {
62
- const name = m[1];
63
- if (!out.includes(name))
64
- out.push(name);
65
- }
66
- return out;
67
- }
68
- /** The placeholders of a text that the place does not define (the toolchain refuses them). */
69
- export function unknownSetupGuidePlaceholders(text, place) {
70
- const known = SETUP_GUIDE_VARIABLES[place];
71
- return setupGuidePlaceholders(text).filter((n) => !known.includes(n));
72
- }
73
- /** The modes a guide's steps and files use, in the place's order (empty: no mode switch). */
74
- export function setupGuideModes(guide) {
75
- const used = new Set();
76
- for (const s of guide.steps ?? [])
77
- if (s.mode !== undefined)
78
- used.add(s.mode);
79
- for (const f of guide.files ?? [])
80
- if (f.mode !== undefined)
81
- used.add(f.mode);
82
- return SETUP_GUIDE_MODES[guide.place].filter((m) => used.has(m));
83
- }
84
- // biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are what is replaced
85
- const CONTROL_RE = /[\u0000-\u001f\u007f]/g;
86
- /** A value as inserted into a text of the language (see {@link renderSetupGuideText}). */
87
- function escapeValue(value, language) {
88
- if (language === "text")
89
- return value.replace(CONTROL_RE, " ");
90
- // JSON string escaping without the quotes: valid inside a JSON string and a YAML double-quoted
91
- // scalar, whatever the value holds
92
- return JSON.stringify(value).slice(1, -1);
93
- }
94
- /**
95
- * Renders a guide text: each `{{name}}` with a value in `values` is replaced by it, escaped for
96
- * `language` (`yaml` / `json`: JSON-string-escaped without quotes, so a placeholder inside double
97
- * quotes stays one string; `text`: control characters become spaces). A placeholder whose value is
98
- * null or undefined stays as written and is listed in `unresolved` when `known` holds it; one not
99
- * in `known` stays as written and is not listed. Never runs code; deterministic.
100
- */
101
- export function renderSetupGuideText(text, values, language, known = Object.keys(values)) {
102
- const unresolved = [];
103
- const out = text.replace(PLACEHOLDER_RE, (whole, name) => {
104
- if (!known.includes(name))
105
- return whole;
106
- const v = Object.hasOwn(values, name) ? values[name] : undefined;
107
- if (v === null || v === undefined) {
108
- if (!unresolved.includes(name))
109
- unresolved.push(name);
110
- return whole;
111
- }
112
- return escapeValue(v, language);
113
- });
114
- return { text: out, unresolved };
100
+ /** The package path of a guide's document: `guides/<id>.md` (en) or `guides/<id>.zh.md` (zh). */
101
+ export function setupGuideDocPath(id, locale) {
102
+ return locale === "zh" ? `guides/${id}.zh.md` : `guides/${id}.md`;
115
103
  }
116
104
  /**
117
- * Whether a guide's template file is usable: present, at most {@link SETUP_GUIDE_LIMITS}`.fileBytes`,
118
- * valid UTF-8 text without NUL. The problem (English, naming the path), or undefined when it is.
119
- * Shared by the packer and the kernel's package reader.
105
+ * Whether a guide document is usable as a file: present, at most
106
+ * {@link SETUP_GUIDE_LIMITS}`.docBytes`, valid UTF-8 without NUL and without U+E000–U+E0FF. The
107
+ * problem (English, naming the path), or undefined. Shared by the packer and the kernel's reader.
120
108
  */
121
- export function setupGuideFileProblem(path, data) {
109
+ export function setupGuideDocProblem(path, data) {
122
110
  if (data === undefined)
123
111
  return `${path} not found in the package`;
124
- if (data.byteLength > SETUP_GUIDE_LIMITS.fileBytes) {
125
- return `${path} is larger than ${SETUP_GUIDE_LIMITS.fileBytes} bytes`;
112
+ if (data.byteLength > SETUP_GUIDE_LIMITS.docBytes) {
113
+ return `${path} is larger than ${SETUP_GUIDE_LIMITS.docBytes} bytes`;
126
114
  }
127
115
  let text;
128
116
  try {
@@ -131,5 +119,249 @@ export function setupGuideFileProblem(path, data) {
131
119
  catch {
132
120
  return `${path} is not valid UTF-8 text`;
133
121
  }
134
- return text.includes("\u0000") ? `${path} is not a text file (it contains NUL)` : undefined;
122
+ if (text.includes("\u0000"))
123
+ return `${path} is not a text file (it contains NUL)`;
124
+ if (/[-]/.test(text)) {
125
+ return `${path} contains a private-use character (U+E000–U+E0FF), which guides may not use`;
126
+ }
127
+ return undefined;
128
+ }
129
+ const QUOTING_LANGUAGES = new Set(["yaml", "yml", "json"]);
130
+ const firstUrlSentinel = /^(?:|%EE%80%80)(\d+)(?:|%EE%80%81)/i;
131
+ const hasSentinel = (s) => s !== null &&
132
+ s !== undefined &&
133
+ (new RegExp(SENTINEL_RE.source).test(s) || new RegExp(ENCODED_SENTINEL_RE.source, "i").test(s));
134
+ const sentinelIndexes = (s) => [
135
+ ...[...s.matchAll(SENTINEL_RE)].map((m) => Number(m[1])),
136
+ ...[...s.matchAll(ENCODED_SENTINEL_RE)].map((m) => Number(m[1])),
137
+ ];
138
+ /**
139
+ * Validates a guide's documents for a place (spec §4.5): title, sections well formed and known to
140
+ * the place, check lines, fence info strings, no indented code, limits, variables known to the place
141
+ * and allowed where they stand (§6.2), language parity of the zh document (§4.3), and, when
142
+ * `pluginChecks` is given, that every plugin check id is declared there (the extension's
143
+ * `permissions.setupChecks`). Messages name the file (`guides/<id>.md` when `id` is given) and line.
144
+ * `allowUnknownVariables` (the kernel's importer) accepts variables the place does not define: they
145
+ * render as written. Pure.
146
+ */
147
+ export function validateSetupGuide(input) {
148
+ const info = SETUP_GUIDE_PLACE_INFO[input.place];
149
+ const fileOf = (locale) => input.id !== undefined
150
+ ? setupGuideDocPath(input.id, locale)
151
+ : locale === "en"
152
+ ? "the English document"
153
+ : "the Chinese document";
154
+ const out = [];
155
+ const parsedBy = {};
156
+ const one = (locale, source) => {
157
+ const file = fileOf(locale);
158
+ const push = (i) => out.push({
159
+ level: i.level,
160
+ message: i.line !== undefined ? `${file}:${i.line}: ${i.message}` : `${file}: ${i.message}`,
161
+ });
162
+ const bytes = new TextEncoder().encode(source).byteLength;
163
+ if (bytes > SETUP_GUIDE_LIMITS.docBytes) {
164
+ push({ level: "error", message: `is larger than ${SETUP_GUIDE_LIMITS.docBytes} bytes` });
165
+ return;
166
+ }
167
+ const { parsed, scan, tree, uses } = analyzeSetupGuide(source);
168
+ parsedBy[locale] = parsed;
169
+ const issues = [...parsed.issues];
170
+ const err = (line, message, level = "error") => issues.push({ level, ...(line !== undefined && { line }), message });
171
+ for (const s of parsed.sections) {
172
+ if (s.type === "mode" && !info.modes.includes(s.value)) {
173
+ err(s.line, info.modes.length === 0
174
+ ? `place ${input.place} has no modes`
175
+ : `mode "${s.value}" is not one of the modes of place ${input.place}: ${info.modes.join(", ")}`);
176
+ }
177
+ if (s.type === "audience" && !info.audiences.includes(s.value)) {
178
+ err(s.line, `audience "${s.value}" is not one of the audiences of place ${input.place}: ${info.audiences.join(", ")}`);
179
+ }
180
+ }
181
+ if (!info.checks) {
182
+ for (const c of parsed.checks) {
183
+ err(c.line, `check ${c.id} is not allowed in place ${input.place}${input.id !== undefined ? ` (guide ${input.id})` : ""}: guides of this place have no target to check, so remove the line`);
184
+ }
185
+ }
186
+ if (input.pluginChecks !== undefined && info.checks) {
187
+ for (const c of parsed.checks) {
188
+ if (c.source === "plugin" && !input.pluginChecks.includes(c.id)) {
189
+ err(c.line, `check ${c.id} is not declared in the extension's permissions.setupChecks`);
190
+ }
191
+ }
192
+ }
193
+ // a check id twice in one rendering
194
+ const dupes = new Set();
195
+ for (const mode of [null, ...info.modes]) {
196
+ for (const audience of info.audiences) {
197
+ const seen = new Set();
198
+ parsed.checks.forEach((c) => {
199
+ if (!lineSelected(scan, c.line - 1, mode, audience))
200
+ return;
201
+ if (seen.has(c.id) && !dupes.has(c.id)) {
202
+ dupes.add(c.id);
203
+ err(c.line, `check ${c.id} appears twice in one rendering of the guide`);
204
+ }
205
+ seen.add(c.id);
206
+ });
207
+ }
208
+ }
209
+ // variables: known to the place, and allowed where they stand
210
+ const reported = new Set();
211
+ for (const u of uses) {
212
+ if (Object.hasOwn(info.variables, u.name) || input.allowUnknownVariables === true)
213
+ continue;
214
+ if (reported.has(u.name))
215
+ continue;
216
+ reported.add(u.name);
217
+ err(u.line, `unknown variable {{${u.name}}} for place ${input.place} (known: ${Object.keys(info.variables).join(", ")})`);
218
+ }
219
+ const typeOf = (n) => {
220
+ const name = uses[n]?.name;
221
+ return name === undefined ? undefined : info.variables[name];
222
+ };
223
+ const nameOf = (n) => `{{${uses[n]?.name ?? "?"}}}`;
224
+ const checkDestination = (url, line) => {
225
+ const all = sentinelIndexes(url);
226
+ if (all.length === 0)
227
+ return;
228
+ const m = firstUrlSentinel.exec(url);
229
+ const ok = m !== null && all.length === 1 && typeOf(Number(m[1])) === "url";
230
+ if (!ok) {
231
+ err(line, `${all.map(nameOf).join(", ")} in a link destination: only a url variable may stand there, at its start`);
232
+ }
233
+ };
234
+ visitGuide(tree, (node) => {
235
+ const line = node.position?.start.line;
236
+ switch (node.type) {
237
+ case "code": {
238
+ const lang = (node.lang ?? "").toLowerCase();
239
+ if (QUOTING_LANGUAGES.has(lang)) {
240
+ // values are JSON-escaped without the quotes: only safe inside a "…" string
241
+ for (const lineText of node.value.split("\n")) {
242
+ for (const m of lineText.matchAll(SENTINEL_RE)) {
243
+ const n = Number(m[1]);
244
+ if (typeOf(n) !== "text")
245
+ continue;
246
+ const before = lineText.slice(0, m.index).replace(/\\./g, "");
247
+ if ((before.match(/"/g)?.length ?? 0) % 2 === 1)
248
+ continue;
249
+ err(line, `the text variable ${nameOf(n)} in a ${lang} code block is not inside double quotes; its value is escaped as a string and may break the block or change its type ("${nameOf(n)}")`, "warning");
250
+ }
251
+ }
252
+ return;
253
+ }
254
+ for (const n of sentinelIndexes(node.value)) {
255
+ if (typeOf(n) === "text") {
256
+ err(line, `the text variable ${nameOf(n)} in a ${lang || "plain"} code block is not quoted; a value with spaces or quotes may break it (use a yaml or json block with "${nameOf(n)}")`, "warning");
257
+ }
258
+ }
259
+ return;
260
+ }
261
+ case "link":
262
+ case "definition":
263
+ checkDestination(node.url, line);
264
+ if (hasSentinel(node.title))
265
+ err(line, "variables are not allowed in a link title");
266
+ return;
267
+ case "image":
268
+ case "imageReference":
269
+ if (hasSentinel(node.alt) ||
270
+ (node.type === "image" && (hasSentinel(node.url) || hasSentinel(node.title)))) {
271
+ err(line, "variables are not allowed in an image");
272
+ }
273
+ return;
274
+ default:
275
+ return;
276
+ }
277
+ });
278
+ issues.sort((a, b) => (a.line ?? 0) - (b.line ?? 0));
279
+ issues.forEach(push);
280
+ };
281
+ one("en", input.en);
282
+ if (input.zh !== undefined)
283
+ one("zh", input.zh);
284
+ const en = parsedBy.en;
285
+ const zh = parsedBy.zh;
286
+ if (en !== undefined && zh !== undefined) {
287
+ const enFile = fileOf("en");
288
+ const zhFile = fileOf("zh");
289
+ const sec = (p) => JSON.stringify(p.sections.map((s) => [s.type, s.value, s.parent]));
290
+ if (sec(en) !== sec(zh)) {
291
+ out.push({
292
+ level: "error",
293
+ message: `${zhFile}: the sections differ from ${enFile}; both languages need the same sections in the same order`,
294
+ });
295
+ }
296
+ const chk = (p) => JSON.stringify(p.checks.map((c) => [c.section, c.id]));
297
+ if (chk(en) !== chk(zh)) {
298
+ out.push({
299
+ level: "error",
300
+ message: `${zhFile}: the checks differ from ${enFile}; both languages need the same check ids in the same sections`,
301
+ });
302
+ }
303
+ if (en.codeBlocks.length !== zh.codeBlocks.length) {
304
+ out.push({
305
+ level: "error",
306
+ message: `${zhFile}: has ${zh.codeBlocks.length} code blocks and ${enFile} has ${en.codeBlocks.length}; code blocks must be identical in every language`,
307
+ });
308
+ }
309
+ else {
310
+ en.codeBlocks.forEach((e, i) => {
311
+ const z = zh.codeBlocks[i];
312
+ if (z === undefined)
313
+ return;
314
+ const n = i + 1;
315
+ const name = `code block ${n}${z.title !== null ? ` ("${z.title}")` : ""}`;
316
+ if (z.section !== e.section) {
317
+ out.push({
318
+ level: "error",
319
+ message: `${zhFile}: ${name} is in another section than ${enFile} block ${n}; code blocks must be identical in every language`,
320
+ });
321
+ return;
322
+ }
323
+ if (z.language === e.language && z.text === e.text)
324
+ return;
325
+ if (z.language !== e.language) {
326
+ out.push({
327
+ level: "error",
328
+ message: `${zhFile}: ${name} is ${z.language || "without a language"} but ${enFile} block ${n} is ${e.language || "without a language"}; code blocks must be identical in every language`,
329
+ });
330
+ return;
331
+ }
332
+ const el = e.text.split("\n");
333
+ const zl = z.text.split("\n");
334
+ let line = 0;
335
+ while (line < el.length && line < zl.length && el[line] === zl[line])
336
+ line++;
337
+ out.push({
338
+ level: "error",
339
+ message: `${zhFile}: ${name} differs from ${enFile} block ${n} at line ${line + 1}; code blocks must be identical in every language`,
340
+ });
341
+ });
342
+ }
343
+ }
344
+ return out;
345
+ }
346
+ /**
347
+ * The drift hash of a guide for one mode and audience (spec §11): sha256 (hex) over the place, guide
348
+ * id, mode and audience, then, in document order after section selection, each fenced code block
349
+ * (language and text, title excluded) and each check id of the English document. Variables are not
350
+ * substituted; line endings are normalized. Prose, headings and check labels do not move it.
351
+ */
352
+ export function setupGuideHash(enSource, input) {
353
+ const scan = scanGuide(normalizeGuideSource(enSource));
354
+ const tree = parseGuideMarkdown(preparedGuideText(scan, (i) => lineSelected(scan, i, input.mode, input.audience)));
355
+ const h = createHash("sha256");
356
+ h.update(`capybara-guide-v2\0${input.place}\0${input.guideId}\0${input.mode ?? ""}\0${input.audience}\0`);
357
+ visitGuide(tree, (node) => {
358
+ if (node.type === "code") {
359
+ h.update(`code\0${node.lang ?? ""}\0${node.value}\0`);
360
+ return;
361
+ }
362
+ const c = checkMarkerIndex(node);
363
+ if (c !== undefined)
364
+ h.update(`check\0${scan.checks[c]?.id ?? ""}\0`);
365
+ });
366
+ return h.digest("hex");
135
367
  }