slicejs-cli 4.5.0 → 4.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/client.js +162 -83
  2. package/commands/Print.js +158 -164
  3. package/commands/build/build.js +27 -1
  4. package/commands/buildProduction/buildProduction.js +42 -71
  5. package/commands/bundle/bundle.js +65 -60
  6. package/commands/docs/agents.js +260 -0
  7. package/commands/docs/events.js +365 -0
  8. package/commands/docs/index.js +123 -0
  9. package/commands/doctor/doctor.js +43 -9
  10. package/commands/export/checkExport.js +163 -0
  11. package/commands/export/clientRedirects.js +72 -0
  12. package/commands/export/copyDist.js +180 -0
  13. package/commands/export/export.js +236 -0
  14. package/commands/export/files.js +33 -0
  15. package/commands/export/hosts/cloudflare.js +48 -0
  16. package/commands/export/hosts/github.js +31 -0
  17. package/commands/export/hosts/index.js +69 -0
  18. package/commands/export/hosts/netlify.js +42 -0
  19. package/commands/export/hosts/nginx.js +73 -0
  20. package/commands/export/hosts/none.js +23 -0
  21. package/commands/export/hosts/s3.js +24 -0
  22. package/commands/export/hosts/shared.js +62 -0
  23. package/commands/export/hosts/vercel.js +69 -0
  24. package/commands/export/outDir.js +91 -0
  25. package/commands/export/prerender.js +121 -0
  26. package/commands/getComponent/getComponent.js +39 -34
  27. package/commands/init/init.js +32 -22
  28. package/commands/lint/lint.js +2 -2
  29. package/commands/lint/types.js +1 -1
  30. package/commands/listComponents/listComponents.js +205 -172
  31. package/commands/seo/check.js +1 -1
  32. package/commands/seo/images.js +1 -1
  33. package/commands/seo/sitemap.js +1 -1
  34. package/commands/setup/lint.js +1 -1
  35. package/commands/skill/skill.js +2 -2
  36. package/commands/startServer/startServer.js +60 -21
  37. package/commands/startServer/watchServer.js +3 -3
  38. package/commands/translator/check.js +1 -1
  39. package/commands/translator/init.js +1 -1
  40. package/commands/typecheck/typecheck.js +2 -2
  41. package/commands/types/types.js +22 -3
  42. package/commands/utils/VersionChecker.js +14 -14
  43. package/commands/utils/bundling/BundleGenerator.js +45 -27
  44. package/commands/utils/bundling/DependencyAnalyzer.js +38 -17
  45. package/commands/utils/componentCatalog.js +120 -0
  46. package/commands/utils/publicEnv.js +74 -0
  47. package/commands/utils/updateManager.js +12 -12
  48. package/package.json +22 -23
@@ -0,0 +1,260 @@
1
+ import fs from 'fs-extra';
2
+ import path from 'path';
3
+
4
+ import {
5
+ componentDocCell,
6
+ serializeComponentsRegistry,
7
+ writeComponentsRegistry,
8
+ } from '../utils/componentCatalog.js';
9
+
10
+ const MARKER_START = (name) => `<!-- slice:generated:${name}:start -->`;
11
+ const MARKER_END = (name) => `<!-- slice:generated:${name}:end -->`;
12
+
13
+ const DEFAULT_PURPOSES = {
14
+ AppComponents: 'Application-specific UI: the shell and the screens that compose Visual components for this product.',
15
+ DocumentationPages: 'Generated documentation pages and their supporting views.',
16
+ DemoComponents: 'Interactive demos and fixtures used by documentation or examples.',
17
+ };
18
+
19
+ export function readGeneratedBlock(content, name) {
20
+ const start = content.indexOf(MARKER_START(name));
21
+ const end = content.indexOf(MARKER_END(name));
22
+ if (start === -1 || end === -1 || end < start) return null;
23
+ return content.slice(start, end + MARKER_END(name).length);
24
+ }
25
+
26
+ function replaceGeneratedBlock(content, name, block) {
27
+ const start = content.indexOf(MARKER_START(name));
28
+ const end = content.indexOf(MARKER_END(name));
29
+ const wrapped = `${MARKER_START(name)}\n${block.trim()}\n${MARKER_END(name)}`;
30
+ if (start !== -1 && end !== -1 && end > start) {
31
+ return `${content.slice(0, start)}${wrapped}${content.slice(end + MARKER_END(name).length)}`;
32
+ }
33
+ const separator = content.endsWith('\n') ? '\n' : '\n\n';
34
+ return `${content}${separator}## Components (generated)\n\n${wrapped}\n`;
35
+ }
36
+
37
+ function categoryRows(catalog) {
38
+ const rows = catalog.categories.map((category) => {
39
+ const count = category.components.length;
40
+ return `| ${category.name} | ${category.type} | \`${category.relativePath}\` | ${count} | [AGENTS.md](${category.relativePath}/AGENTS.md) |`;
41
+ });
42
+ return [
43
+ '| Category | Type | Path | Components | Guide |',
44
+ '| --- | --- | --- | --- | --- |',
45
+ ...rows,
46
+ ].join('\n');
47
+ }
48
+
49
+ function componentRows(category) {
50
+ const rows = category.components.map((component) =>
51
+ `| ${component.name} | ${component.type} | ${component.fileCount} | ${componentDocCell(component)} |`,
52
+ );
53
+ return [
54
+ '| Component | Type | Files | Docs |',
55
+ '| --- | --- | --- | --- |',
56
+ ...(rows.length ? rows : ['| — | — | — | — |']),
57
+ ].join('\n');
58
+ }
59
+
60
+ function packageName(projectRoot, packageJson) {
61
+ return packageJson?.name || path.basename(projectRoot);
62
+ }
63
+
64
+ function packageManager(projectRoot, packageJson) {
65
+ if (packageJson?.packageManager) return String(packageJson.packageManager).split('@')[0];
66
+ if (fs.existsSync(path.join(projectRoot, 'pnpm-lock.yaml'))) return 'pnpm';
67
+ if (fs.existsSync(path.join(projectRoot, 'yarn.lock'))) return 'yarn';
68
+ return 'npm';
69
+ }
70
+
71
+ function rootAgentsTemplate({ projectRoot, packageJson, catalog }) {
72
+ const name = packageName(projectRoot, packageJson);
73
+ const pm = packageManager(projectRoot, packageJson);
74
+ return `# ${name} — agent guide
75
+
76
+ ## Read first
77
+
78
+ 1. This file.
79
+ 2. The nearest \`src/Components/<Category>/AGENTS.md\` before editing a component.
80
+ 3. The component \`README.md\` before changing its API or behavior.
81
+ 4. \`docs/events/\` before changing an event contract.
82
+
83
+ ## Commands
84
+
85
+ - Dev: \`${pm} dev\`
86
+ - Build: \`${pm} build\`
87
+ - Regenerate docs: \`${pm} exec slice docs generate\`
88
+ - Check generated docs: \`${pm} exec slice docs check\`
89
+
90
+ ## Component categories
91
+
92
+ ${MARKER_START('categories')}
93
+ ${categoryRows(catalog)}
94
+ ${MARKER_END('categories')}
95
+
96
+ ## Documentation map
97
+
98
+ - Category guides: \`src/Components/<Category>/AGENTS.md\`
99
+ - Component docs: \`<Component>/README.md\`
100
+ - Event catalog: \`docs/events/index.md\`, \`diagram.mmd\`, \`diagram.html\`
101
+ - Changelog (optional): \`CHANGELOG.md\` or \`src/Components/<Category>/CHANGELOG.md\`
102
+
103
+ ## Rules
104
+
105
+ - Visual and Service are registry categories. Do not hand-edit components installed by \`slice get\`;
106
+ their authoritative docs are \`slice docs\` / MCP.
107
+ - App-owned components document themselves in \`README.md\` next to the code.
108
+ - Generated files are never edited by hand: \`components.js\`, \`docs/events/*\`,
109
+ \`src/slice-events.generated.js\`, \`src/*.generated.d.ts\`.
110
+ - A behavior change updates the component README and the category guide in the same change.
111
+ - Event names use \`namespace:action\`.
112
+
113
+ ## Done
114
+
115
+ - [ ] Component README updated (or \`No docs impact\` explained)
116
+ - [ ] Nearest category \`AGENTS.md\` updated
117
+ - [ ] \`slice docs generate\` run when events/components changed
118
+ - [ ] Changelog updated if the project uses one
119
+ `;
120
+ }
121
+
122
+ function registryRules(category) {
123
+ if (category.name === 'Visual') {
124
+ return `## Registry rule
125
+
126
+ \`Visual\` is where \`slice get\` installs registry Visual components. A downloaded component is not
127
+ edited by hand: its authoritative docs are \`slice docs\` / MCP. A local component added to this
128
+ category is app-owned and documents itself in its own \`README.md\`.
129
+ `;
130
+ }
131
+ if (category.name === 'Service') {
132
+ return `## Registry rule
133
+
134
+ \`Service\` is where \`slice get\` installs registry Service components. A downloaded component is not
135
+ edited by hand: its authoritative docs are \`slice docs\` / MCP. A local service added to this
136
+ category is app-owned and documents itself in its own \`README.md\`.
137
+ `;
138
+ }
139
+ return `## What this category is
140
+
141
+ ${category.description || DEFAULT_PURPOSES[category.name] || 'TODO: describe this category. What belongs here, what does not, and how it relates to the other categories.'}
142
+ `;
143
+ }
144
+
145
+ function categoryAgentsTemplate(category) {
146
+ return `# ${category.name}
147
+
148
+ ${registryRules(category)}
149
+
150
+ ## Components
151
+
152
+ ${MARKER_START('components')}
153
+ ${componentRows(category)}
154
+ ${MARKER_END('components')}
155
+
156
+ ## Local rules
157
+
158
+ - Keep this guide current when adding, removing or changing a component in this category.
159
+ - Prefer the component \`README.md\` for API details; link it from the table above.
160
+ - Document non-obvious decisions and gotchas here.
161
+
162
+ ## Events
163
+
164
+ - Emitted and listened events are documented in \`docs/events/\`.
165
+ - Event names use \`namespace:action\`.
166
+
167
+ ## Changelog
168
+
169
+ - Optional: \`CHANGELOG.md\` next to this file.
170
+ `;
171
+ }
172
+
173
+ function updateRootAgents(content, catalog) {
174
+ const block = categoryRows(catalog);
175
+ if (readGeneratedBlock(content, 'categories')) {
176
+ return replaceGeneratedBlock(content, 'categories', block);
177
+ }
178
+ const separator = content.endsWith('\n') ? '\n' : '\n\n';
179
+ return `${content}${separator}## Component categories\n\n${MARKER_START('categories')}\n${block}\n${MARKER_END('categories')}\n`;
180
+ }
181
+
182
+ function updateCategoryAgents(content, category) {
183
+ const block = componentRows(category);
184
+ if (readGeneratedBlock(content, 'components')) {
185
+ return replaceGeneratedBlock(content, 'components', block);
186
+ }
187
+ const separator = content.endsWith('\n') ? '\n' : '\n\n';
188
+ return `${content}${separator}## Components (generated)\n\n${MARKER_START('components')}\n${block}\n${MARKER_END('components')}\n`;
189
+ }
190
+
191
+ export async function expectedAgentsFiles({ projectRoot, catalog }) {
192
+ const packageJsonPath = path.join(projectRoot, 'package.json');
193
+ const packageJson = (await fs.pathExists(packageJsonPath)) ? await fs.readJson(packageJsonPath) : null;
194
+ const files = new Map();
195
+
196
+ const rootPath = path.join(projectRoot, 'AGENTS.md');
197
+ if (await fs.pathExists(rootPath)) {
198
+ const current = await fs.readFile(rootPath, 'utf8');
199
+ files.set(rootPath, updateRootAgents(current, catalog));
200
+ } else {
201
+ files.set(rootPath, rootAgentsTemplate({ projectRoot, packageJson, catalog }));
202
+ }
203
+
204
+ for (const category of catalog.categories) {
205
+ const categoryPath = path.join(category.directory, 'AGENTS.md');
206
+ if (await fs.pathExists(categoryPath)) {
207
+ const current = await fs.readFile(categoryPath, 'utf8');
208
+ files.set(categoryPath, updateCategoryAgents(current, category));
209
+ } else {
210
+ files.set(categoryPath, categoryAgentsTemplate(category));
211
+ }
212
+ }
213
+
214
+ const claudePath = path.join(projectRoot, 'CLAUDE.md');
215
+ if (!(await fs.pathExists(claudePath))) files.set(claudePath, '@AGENTS.md\n');
216
+
217
+ files.set(
218
+ path.join(projectRoot, 'src', 'Components', 'components.js'),
219
+ serializeComponentsRegistry(catalog),
220
+ );
221
+
222
+ return files;
223
+ }
224
+
225
+ export async function generateAgents({ projectRoot, catalog }) {
226
+ const files = await expectedAgentsFiles({ projectRoot, catalog });
227
+ for (const [filePath, content] of files) {
228
+ await fs.ensureDir(path.dirname(filePath));
229
+ await fs.writeFile(filePath, content, 'utf8');
230
+ }
231
+ await writeComponentsRegistry(projectRoot, catalog);
232
+ return { files: [...files.keys()] };
233
+ }
234
+
235
+ export async function checkAgents({ projectRoot, catalog }) {
236
+ const issues = [];
237
+ const expected = await expectedAgentsFiles({ projectRoot, catalog });
238
+
239
+ for (const [filePath, content] of expected) {
240
+ if (!(await fs.pathExists(filePath))) {
241
+ issues.push(`missing ${path.relative(projectRoot, filePath).replace(/\\/g, '/')}`);
242
+ continue;
243
+ }
244
+ const actual = await fs.readFile(filePath, 'utf8');
245
+ if (actual !== content) {
246
+ issues.push(`outdated ${path.relative(projectRoot, filePath).replace(/\\/g, '/')}`);
247
+ }
248
+ }
249
+
250
+ for (const category of catalog.categories) {
251
+ const categoryPath = path.join(category.directory, 'AGENTS.md');
252
+ if (!(await fs.pathExists(categoryPath))) continue;
253
+ const content = await fs.readFile(categoryPath, 'utf8');
254
+ if (content.includes('TODO: describe this category')) {
255
+ issues.push(`placeholder purpose in ${path.relative(projectRoot, categoryPath).replace(/\\/g, '/')}`);
256
+ }
257
+ }
258
+
259
+ return { ok: issues.length === 0, issues };
260
+ }
@@ -0,0 +1,365 @@
1
+ import fs from 'fs-extra';
2
+ import path from 'path';
3
+
4
+ import {
5
+ buildEventManifest,
6
+ collectEventGraph,
7
+ collectEventRegistry,
8
+ } from '../types/types.js';
9
+
10
+ const GENERATED_MARKER = '<!-- Generated by `slice docs generate events`. Do not edit by hand. -->';
11
+
12
+ const escapeText = (value) => String(value ?? '').replace(/\r?\n/g, ' ').trim();
13
+ const escapeHtml = (value) =>
14
+ escapeText(value)
15
+ .replace(/&/g, '&amp;')
16
+ .replace(/</g, '&lt;')
17
+ .replace(/>/g, '&gt;')
18
+ .replace(/"/g, '&quot;');
19
+ const escapeMermaid = (value) => escapeText(value).replace(/"/g, '&quot;');
20
+
21
+ function namespaceOf(eventName) {
22
+ const index = String(eventName).indexOf(':');
23
+ return index > 0 ? String(eventName).slice(0, index) : null;
24
+ }
25
+
26
+ function slugify(value) {
27
+ return String(value).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'events';
28
+ }
29
+
30
+ function fileForNamespace(namespace, used) {
31
+ const base = namespace ? slugify(namespace) : 'invalid';
32
+ let name = base;
33
+ let counter = 2;
34
+ while (used.has(name)) name = `${base}-${counter++}`;
35
+ used.add(name);
36
+ return `${name}.md`;
37
+ }
38
+
39
+ function rolesFor(event) {
40
+ return [
41
+ ...event.emitters.map((site) => ({ ...site, role: 'emitter' })),
42
+ ...event.listeners.map((site) => ({ ...site, role: 'listener' })),
43
+ ];
44
+ }
45
+
46
+ function uniqueComponents(event) {
47
+ const set = new Set();
48
+ for (const site of [...event.emitters, ...event.listeners]) {
49
+ if (site.component) set.add(site.component);
50
+ }
51
+ return [...set].sort();
52
+ }
53
+
54
+ function renderPayload(payload) {
55
+ if (payload == null) return '—';
56
+ return `\`${JSON.stringify(payload)}\``;
57
+ }
58
+
59
+ function renderIndex(manifest, registry, namespaces, namespaceFiles) {
60
+ const namespaceRows = Object.entries(namespaces).map(([namespace, events]) => {
61
+ const emitters = new Set();
62
+ const listeners = new Set();
63
+ for (const event of events) {
64
+ for (const site of event.emitters) if (site.component) emitters.add(site.component);
65
+ for (const site of event.listeners) if (site.component) listeners.add(site.component);
66
+ }
67
+ return `| ${namespace} | ${events.length} | ${emitters.size} | ${listeners.size} | [${namespace}](./${namespaceFiles.get(namespace)}) |`;
68
+ });
69
+
70
+ const declaredNoEmitter = Object.entries(registry)
71
+ .filter(([name]) => !manifest.events[name]?.emitters.length)
72
+ .map(([name]) => `\`${name}\``);
73
+ const usedUndeclared = Object.keys(manifest.events)
74
+ .filter((name) => !(name in registry))
75
+ .map((name) => `\`${name}\``);
76
+ const invalidNames = Object.keys(manifest.events)
77
+ .filter((name) => !namespaceOf(name))
78
+ .map((name) => `\`${name}\``);
79
+ const dynamicSites = [
80
+ ...manifest.dynamic.emitters.map((site) => `emit ${site.file}:${site.line}`),
81
+ ...manifest.dynamic.listeners.map((site) => `subscribe ${site.file}:${site.line}`),
82
+ ];
83
+
84
+ return `# Events
85
+
86
+ ${GENERATED_MARKER}
87
+
88
+ This catalog is generated from \`slice.events.register(...)\` and the static
89
+ \`emit\`/\`subscribe\` call sites. The machine manifest is
90
+ [\`src/slice-events.generated.js\`](../../src/slice-events.generated.js).
91
+
92
+ ## Summary
93
+
94
+ | Namespace | Events | Emitters | Listeners | Page |
95
+ | --- | --- | --- | --- | --- |
96
+ ${namespaceRows.length ? namespaceRows.join('\n') : '| — | 0 | 0 | 0 | — |'}
97
+
98
+ ## Diagram
99
+
100
+ - [Mermaid source](./diagram.mmd)
101
+ - [Standalone HTML](./diagram.html)
102
+
103
+ ## Drift
104
+
105
+ ### Declared but never emitted
106
+
107
+ ${declaredNoEmitter.length ? declaredNoEmitter.map((name) => `- ${name}`).join('\n') : '- None.'}
108
+
109
+ ### Used but not declared
110
+
111
+ ${usedUndeclared.length ? usedUndeclared.map((name) => `- ${name}`).join('\n') : '- None.'}
112
+
113
+ ### Events without a namespace
114
+
115
+ ${invalidNames.length ? invalidNames.map((name) => `- ${name}`).join('\n') : '- None.'}
116
+
117
+ ### Dynamic sites (not statically resolvable)
118
+
119
+ ${dynamicSites.length ? dynamicSites.map((site) => `- \`${site}\``).join('\n') : '- None.'}
120
+ `;
121
+ }
122
+
123
+ function renderNamespace(namespace, events) {
124
+ const sections = events.map((event) => {
125
+ const roles = rolesFor(event);
126
+ const rows = roles.map((site) => {
127
+ const component = site.component || path.basename(site.file, '.js');
128
+ return `| ${site.role} | ${component} | ${site.category || '—'} | \`${site.file}:${site.line}\` |`;
129
+ });
130
+ return `## \`${event.name}\`
131
+
132
+ Payload: ${renderPayload(event.payload)}
133
+
134
+ | Role | Component | Category | Source |
135
+ | --- | --- | --- | --- |
136
+ ${rows.length ? rows.join('\n') : '| — | — | — | — |'}
137
+ `;
138
+ });
139
+
140
+ return `# ${namespace} events
141
+
142
+ ${GENERATED_MARKER}
143
+
144
+ ${sections.length ? sections.join('\n') : 'No events in this namespace.'}
145
+ `;
146
+ }
147
+
148
+ function renderMermaid(manifest, namespaces) {
149
+ const componentIds = new Map();
150
+ const lines = ['flowchart LR'];
151
+ let counter = 0;
152
+ const idForComponent = (name) => {
153
+ if (!componentIds.has(name)) {
154
+ componentIds.set(name, `c${counter++}`);
155
+ }
156
+ return componentIds.get(name);
157
+ };
158
+
159
+ for (const [namespace, events] of Object.entries(namespaces)) {
160
+ const safeNs = `ns${counter++}`;
161
+ lines.push(` subgraph ${safeNs}["${escapeMermaid(namespace)}"]`);
162
+ for (const [index, event] of events.entries()) {
163
+ const eventId = `e${counter++}`;
164
+ event._diagramId = eventId;
165
+ lines.push(` ${eventId}(("${escapeMermaid(event.name)}"))`);
166
+ }
167
+ lines.push(' end');
168
+ }
169
+
170
+ const dynamic = manifest.dynamic;
171
+ const componentNames = new Set();
172
+ for (const event of Object.values(manifest.events)) {
173
+ for (const site of [...event.emitters, ...event.listeners]) {
174
+ if (site.component) componentNames.add(site.component);
175
+ }
176
+ }
177
+ for (const name of [...componentNames].sort()) {
178
+ lines.push(` ${idForComponent(name)}["${escapeMermaid(name)}"]`);
179
+ }
180
+
181
+ for (const event of Object.values(manifest.events)) {
182
+ const eventId = event._diagramId;
183
+ if (!eventId) continue;
184
+ const emitters = [...new Set(event.emitters.map((site) => site.component || path.basename(site.file, '.js')))];
185
+ const listeners = [...new Set(event.listeners.map((site) => site.component || path.basename(site.file, '.js')))];
186
+ for (const emitter of emitters) {
187
+ const emitterId = componentIds.has(emitter) ? componentIds.get(emitter) : idForComponent(emitter);
188
+ if (!componentIds.has(emitter)) lines.push(` ${emitterId}["${escapeMermaid(emitter)}"]`);
189
+ lines.push(` ${emitterId} -->|emit| ${eventId}`);
190
+ }
191
+ for (const listener of listeners) {
192
+ const listenerId = componentIds.has(listener) ? componentIds.get(listener) : idForComponent(listener);
193
+ if (!componentIds.has(listener)) lines.push(` ${listenerId}["${escapeMermaid(listener)}"]`);
194
+ lines.push(` ${eventId} -->|listen| ${listenerId}`);
195
+ }
196
+ }
197
+
198
+ if (dynamic.emitters.length || dynamic.listeners.length) {
199
+ lines.push(` dynamic(["dynamic sites"])`);
200
+ for (const site of dynamic.emitters) {
201
+ const id = idForComponent(site.component || path.basename(site.file, '.js'));
202
+ lines.push(` ${id} -.->|dynamic emit| dynamic`);
203
+ }
204
+ for (const site of dynamic.listeners) {
205
+ const id = idForComponent(site.component || path.basename(site.file, '.js'));
206
+ lines.push(` dynamic -.->|dynamic listen| ${id}`);
207
+ }
208
+ }
209
+
210
+ return `${lines.join('\n')}\n`;
211
+ }
212
+
213
+ function renderHtml(manifest, namespaces, registry) {
214
+ const sections = Object.entries(namespaces).map(([namespace, events]) => {
215
+ const height = Math.max(120, events.length * 80 + 40);
216
+ const eventNodes = events.map((event, index) => {
217
+ const rowY = 40 + index * 80;
218
+ const emitters = [...new Set(event.emitters.map((site) => site.component || path.basename(site.file, '.js')))];
219
+ const listeners = [...new Set(event.listeners.map((site) => site.component || path.basename(site.file, '.js')))];
220
+ const emitterNodes = emitters.map((name, i) => {
221
+ const y = rowY - ((emitters.length - 1) * 14) + i * 28;
222
+ return { name, y, x: 20, w: 180 };
223
+ });
224
+ const listenerNodes = listeners.map((name, i) => {
225
+ const y = rowY - ((listeners.length - 1) * 14) + i * 28;
226
+ return { name, y, x: 900, w: 180 };
227
+ });
228
+ const eventX = 440;
229
+ const eventW = 220;
230
+ const lines = [
231
+ ...emitterNodes.map((node) => `<line x1="${node.x + node.w}" y1="${node.y + 12}" x2="${eventX}" y2="${rowY + 16}" />`),
232
+ ...listenerNodes.map((node) => `<line x1="${eventX + eventW}" y1="${rowY + 16}" x2="${node.x}" y2="${node.y + 12}" />`),
233
+ ];
234
+ const boxes = [
235
+ ...emitterNodes.map((node) => `<g><rect x="${node.x}" y="${node.y}" width="${node.w}" height="24" rx="6" /><text x="${node.x + 8}" y="${node.y + 16}">${escapeHtml(node.name)}</text></g>`),
236
+ ...listenerNodes.map((node) => `<g><rect x="${node.x}" y="${node.y}" width="${node.w}" height="24" rx="6" /><text x="${node.x + 8}" y="${node.y + 16}">${escapeHtml(node.name)}</text></g>`),
237
+ `<g class="event"><rect x="${eventX}" y="${rowY}" width="${eventW}" height="32" rx="16" /><text x="${eventX + 12}" y="${rowY + 21}">${escapeHtml(event.name)}</text></g>`,
238
+ ];
239
+ return { lines: lines.join(''), boxes: boxes.join('') };
240
+ });
241
+ return `<section id="ns-${slugify(namespace)}">
242
+ <h2>${escapeHtml(namespace)}</h2>
243
+ <svg viewBox="0 0 1100 ${height}" role="img" aria-label="${escapeHtml(namespace)} event graph">
244
+ ${eventNodes.map((node) => node.lines).join('')}
245
+ ${eventNodes.map((node) => node.boxes).join('')}
246
+ </svg>
247
+ </section>`;
248
+ });
249
+
250
+ const rows = Object.entries(namespaces).map(([namespace, events]) =>
251
+ `<tr><td>${escapeHtml(namespace)}</td><td>${events.length}</td><td><a href="#ns-${slugify(namespace)}">graph</a></td></tr>`,
252
+ );
253
+
254
+ return `<!doctype html>
255
+ <html lang="en">
256
+ <head>
257
+ <meta charset="utf-8">
258
+ <meta name="viewport" content="width=device-width, initial-scale=1">
259
+ <title>Slice events</title>
260
+ <style>
261
+ :root { color-scheme: light dark; font-family: ui-sans-serif, system-ui, sans-serif; }
262
+ body { margin: 0 auto; max-width: 1180px; padding: 32px; line-height: 1.5; }
263
+ table { border-collapse: collapse; width: 100%; margin: 16px 0 32px; }
264
+ th, td { border-bottom: 1px solid color-mix(in srgb, currentColor 20%, transparent); padding: 8px; text-align: left; }
265
+ section { margin-top: 36px; }
266
+ svg { width: 100%; height: auto; border: 1px solid color-mix(in srgb, currentColor 16%, transparent); border-radius: 12px; }
267
+ rect { fill: color-mix(in srgb, currentColor 8%, transparent); stroke: color-mix(in srgb, currentColor 24%, transparent); }
268
+ text { fill: currentColor; font-size: 12px; }
269
+ line { stroke: color-mix(in srgb, currentColor 35%, transparent); stroke-width: 1.5; }
270
+ .event rect { fill: color-mix(in srgb, #7c3aed 18%, transparent); }
271
+ code { font-family: ui-monospace, SFMono-Regular, monospace; }
272
+ </style>
273
+ </head>
274
+ <body>
275
+ ${GENERATED_MARKER}
276
+ <h1>Slice events</h1>
277
+ <p>Generated from <code>slice.events.register(...)</code> and static emit/subscribe sites. The machine manifest is <a href="../../src/slice-events.generated.js"><code>src/slice-events.generated.js</code></a>.</p>
278
+ <table><thead><tr><th>Namespace</th><th>Events</th><th>Graph</th></tr></thead><tbody>
279
+ ${rows.join('\n') || '<tr><td>—</td><td>0</td><td>—</td></tr>'}
280
+ </tbody></table>
281
+ <p>Declared events: ${Object.keys(registry).length}. Total events: ${Object.keys(manifest.events).length}.</p>
282
+ ${sections.join('\n') || '<p>No events registered.</p>'}
283
+ </body>
284
+ </html>
285
+ `;
286
+ }
287
+
288
+ export async function buildEventDocs({ projectRoot }) {
289
+ const registry = await collectEventRegistry({ projectRoot });
290
+ const graph = await collectEventGraph({ projectRoot });
291
+ const manifest = buildEventManifest(registry, graph);
292
+ const namespaces = {};
293
+ for (const name of Object.keys(manifest.events).sort((a, b) => a.localeCompare(b))) {
294
+ const namespace = namespaceOf(name) || 'invalid';
295
+ if (!namespaces[namespace]) namespaces[namespace] = [];
296
+ namespaces[namespace].push({ name, ...manifest.events[name] });
297
+ }
298
+ for (const events of Object.values(namespaces)) {
299
+ events.sort((a, b) => a.name.localeCompare(b.name));
300
+ }
301
+
302
+ const outDir = path.join(projectRoot, 'docs', 'events');
303
+ const files = new Map();
304
+ const usedNames = new Set();
305
+ const namespaceFiles = new Map();
306
+ for (const [namespace, events] of Object.entries(namespaces)) {
307
+ const file = fileForNamespace(namespace, usedNames);
308
+ namespaceFiles.set(namespace, file);
309
+ files.set(path.join(outDir, file), renderNamespace(namespace, events));
310
+ }
311
+ files.set(path.join(outDir, 'index.md'), renderIndex(manifest, registry, namespaces, namespaceFiles));
312
+ files.set(path.join(outDir, 'diagram.mmd'), `${GENERATED_MARKER}\n\n${renderMermaid(manifest, namespaces)}`);
313
+ files.set(path.join(outDir, 'diagram.html'), renderHtml(manifest, namespaces, registry));
314
+ return { files, manifest, registry, namespaces };
315
+ }
316
+
317
+ export async function generateEventDocs({ projectRoot }) {
318
+ const { files } = await buildEventDocs({ projectRoot });
319
+ const outDir = path.join(projectRoot, 'docs', 'events');
320
+ await fs.ensureDir(outDir);
321
+
322
+ // Remove only generated pages that are no longer in the current graph.
323
+ if (await fs.pathExists(outDir)) {
324
+ for (const entry of await fs.readdir(outDir)) {
325
+ const fullPath = path.join(outDir, entry);
326
+ if (!(await fs.stat(fullPath)).isFile() || files.has(fullPath)) continue;
327
+ const head = (await fs.readFile(fullPath, 'utf8')).slice(0, 300);
328
+ if (head.includes('Generated by `slice docs generate events`')) await fs.remove(fullPath);
329
+ }
330
+ }
331
+
332
+ for (const [filePath, content] of files) {
333
+ await fs.ensureDir(path.dirname(filePath));
334
+ await fs.writeFile(filePath, content, 'utf8');
335
+ }
336
+ return { files: [...files.keys()] };
337
+ }
338
+
339
+ export async function checkEventDocs({ projectRoot }) {
340
+ const { files } = await buildEventDocs({ projectRoot });
341
+ const issues = [];
342
+ const expected = new Set(files.keys());
343
+ for (const [filePath, content] of files) {
344
+ if (!(await fs.pathExists(filePath))) {
345
+ issues.push(`missing ${path.relative(projectRoot, filePath).replace(/\\/g, '/')}`);
346
+ continue;
347
+ }
348
+ const actual = await fs.readFile(filePath, 'utf8');
349
+ if (actual !== content) issues.push(`outdated ${path.relative(projectRoot, filePath).replace(/\\/g, '/')}`);
350
+ }
351
+
352
+ const outDir = path.join(projectRoot, 'docs', 'events');
353
+ if (await fs.pathExists(outDir)) {
354
+ for (const entry of await fs.readdir(outDir)) {
355
+ const fullPath = path.join(outDir, entry);
356
+ if (expected.has(fullPath) || !(await fs.stat(fullPath)).isFile()) continue;
357
+ const head = (await fs.readFile(fullPath, 'utf8')).slice(0, 300);
358
+ if (head.includes('Generated by `slice docs generate events`')) {
359
+ issues.push(`orphan ${path.relative(projectRoot, fullPath).replace(/\\/g, '/')}`);
360
+ }
361
+ }
362
+ }
363
+
364
+ return { ok: issues.length === 0, issues };
365
+ }