@specdest/devkit 0.1.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 (137) hide show
  1. package/catalog/README.md +11 -0
  2. package/catalog/modules/backend-convex/manifest.json +14 -0
  3. package/catalog/modules/backend-convex-expo/manifest.json +11 -0
  4. package/catalog/modules/backend-supabase/manifest.json +15 -0
  5. package/catalog/modules/backend-supabase-expo/manifest.json +11 -0
  6. package/catalog/modules/checker-runtime/config.ts +24 -0
  7. package/catalog/modules/checker-runtime/fs.ts +47 -0
  8. package/catalog/modules/checker-runtime/manifest.json +23 -0
  9. package/catalog/modules/devflow/.agents/skills/devflow/SKILL.md +33 -0
  10. package/catalog/modules/devflow/.devflow.json +10 -0
  11. package/catalog/modules/devflow/manifest.json +35 -0
  12. package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/SKILL.md +85 -0
  13. package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/activeScenario.mjs +130 -0
  14. package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/checkLocalEnvironment.mjs +7 -0
  15. package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/completeActiveScenario.mjs +36 -0
  16. package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/createActiveScenario.mjs +143 -0
  17. package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/localEnvironment.mjs +43 -0
  18. package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/prompt.mjs +25 -0
  19. package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/runActiveScenario.mjs +66 -0
  20. package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/runAuthoringScenario.mjs +146 -0
  21. package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/seed.mjs +56 -0
  22. package/catalog/modules/e2e-playwright/.agents/skills/e2e-playwright/scripts/seedActiveScenario.mjs +6 -0
  23. package/catalog/modules/e2e-playwright/docs/e2e-playwright/README.md +103 -0
  24. package/catalog/modules/e2e-playwright/manifest.json +206 -0
  25. package/catalog/modules/e2e-playwright/playwright.e2e.config.ts +39 -0
  26. package/catalog/modules/e2e-playwright/tests/e2e/support/e2ePlaywrightFlow.ts +107 -0
  27. package/catalog/modules/e2e-playwright/tests/e2e/support/fixtures.ts +27 -0
  28. package/catalog/modules/local-log/AGENTS.local-log.md +13 -0
  29. package/catalog/modules/local-log/docs/features/local-logging/README.md +70 -0
  30. package/catalog/modules/local-log/manifest.json +39 -0
  31. package/catalog/modules/local-log/tmp/logs/.gitignore +2 -0
  32. package/catalog/modules/local-log/tools/local-log/README.md +47 -0
  33. package/catalog/modules/local-log/tools/local-log/local-log.mjs +241 -0
  34. package/catalog/modules/stack-common-vite/manifest.json +16 -0
  35. package/catalog/modules/stack-expo-convex/manifest.json +31 -0
  36. package/catalog/modules/stack-expo-supabase/manifest.json +44 -0
  37. package/catalog/modules/stack-vite-convex/manifest.json +32 -0
  38. package/catalog/modules/stack-vite-supabase/manifest.json +45 -0
  39. package/catalog/rules/abac-permissions-convex/SKILL.md +17 -0
  40. package/catalog/rules/abac-permissions-convex/check.ts +86 -0
  41. package/catalog/rules/abac-permissions-convex/manifest.json +35 -0
  42. package/catalog/rules/abac-permissions-supabase/SKILL.md +17 -0
  43. package/catalog/rules/abac-permissions-supabase/check.ts +86 -0
  44. package/catalog/rules/abac-permissions-supabase/manifest.json +35 -0
  45. package/catalog/rules/convex-multi-presentation/SKILL.md +48 -0
  46. package/catalog/rules/convex-multi-presentation/boundary-test-baseline.json +3 -0
  47. package/catalog/rules/convex-multi-presentation/check.ts +271 -0
  48. package/catalog/rules/convex-multi-presentation/manifest.json +45 -0
  49. package/catalog/rules/convex-multi-presentation/policy.ts +261 -0
  50. package/catalog/rules/design-rules/SKILL.md +12 -0
  51. package/catalog/rules/design-rules/check.ts +83 -0
  52. package/catalog/rules/design-rules/config.json +5 -0
  53. package/catalog/rules/design-rules/manifest.json +40 -0
  54. package/catalog/rules/e2e-test-rules/SKILL.md +46 -0
  55. package/catalog/rules/e2e-test-rules/check.ts +144 -0
  56. package/catalog/rules/e2e-test-rules/config.json +32 -0
  57. package/catalog/rules/e2e-test-rules/manifest.json +40 -0
  58. package/catalog/rules/error-handling-rules/SKILL.md +21 -0
  59. package/catalog/rules/error-handling-rules/check.ts +72 -0
  60. package/catalog/rules/error-handling-rules/manifest.json +35 -0
  61. package/catalog/rules/layers-and-contracts/SKILL.md +36 -0
  62. package/catalog/rules/layers-and-contracts/check.ts +265 -0
  63. package/catalog/rules/layers-and-contracts/manifest.json +35 -0
  64. package/catalog/rules/layers-and-contracts-convex/SKILL.md +49 -0
  65. package/catalog/rules/layers-and-contracts-convex/check.ts +288 -0
  66. package/catalog/rules/layers-and-contracts-convex/manifest.json +40 -0
  67. package/catalog/rules/layers-and-contracts-convex/policy.ts +68 -0
  68. package/catalog/rules/layers-and-contracts-supabase/SKILL.md +52 -0
  69. package/catalog/rules/layers-and-contracts-supabase/check.ts +370 -0
  70. package/catalog/rules/layers-and-contracts-supabase/manifest.json +40 -0
  71. package/catalog/rules/layers-and-contracts-supabase/policy.ts +68 -0
  72. package/catalog/rules/module-size-rules/SKILL.md +5 -0
  73. package/catalog/rules/module-size-rules/check.ts +143 -0
  74. package/catalog/rules/module-size-rules/config.json +6 -0
  75. package/catalog/rules/module-size-rules/manifest.json +40 -0
  76. package/catalog/rules/module-size-rules-convex/SKILL.md +5 -0
  77. package/catalog/rules/module-size-rules-convex/check.ts +145 -0
  78. package/catalog/rules/module-size-rules-convex/config.json +6 -0
  79. package/catalog/rules/module-size-rules-convex/manifest.json +40 -0
  80. package/catalog/rules/module-size-rules-supabase/SKILL.md +5 -0
  81. package/catalog/rules/module-size-rules-supabase/check.ts +145 -0
  82. package/catalog/rules/module-size-rules-supabase/config.json +12 -0
  83. package/catalog/rules/module-size-rules-supabase/manifest.json +40 -0
  84. package/catalog/rules/mutation-command-rules/SKILL.md +15 -0
  85. package/catalog/rules/mutation-command-rules/check.ts +29 -0
  86. package/catalog/rules/mutation-command-rules/config.json +19 -0
  87. package/catalog/rules/mutation-command-rules/manifest.json +40 -0
  88. package/catalog/rules/nearby-contracts/SKILL.md +18 -0
  89. package/catalog/rules/nearby-contracts/check.ts +137 -0
  90. package/catalog/rules/nearby-contracts/config.json +10 -0
  91. package/catalog/rules/nearby-contracts/manifest.json +40 -0
  92. package/catalog/rules/no-raw-click-buttons/SKILL.md +5 -0
  93. package/catalog/rules/no-raw-click-buttons/check.ts +36 -0
  94. package/catalog/rules/no-raw-click-buttons/manifest.json +35 -0
  95. package/catalog/rules/public-api-export-barrels/SKILL.md +45 -0
  96. package/catalog/rules/public-api-export-barrels/check.ts +72 -0
  97. package/catalog/rules/public-api-export-barrels/config.json +4 -0
  98. package/catalog/rules/public-api-export-barrels/manifest.json +40 -0
  99. package/catalog/rules/route-tree-fresh/SKILL.md +16 -0
  100. package/catalog/rules/route-tree-fresh/check.ts +64 -0
  101. package/catalog/rules/route-tree-fresh/manifest.json +35 -0
  102. package/catalog/rules/strict-typescript/SKILL.md +3 -0
  103. package/catalog/rules/strict-typescript/check.ts +111 -0
  104. package/catalog/rules/strict-typescript/manifest.json +35 -0
  105. package/catalog/rules/supabase-contracts/SKILL.md +3 -0
  106. package/catalog/rules/supabase-contracts/check.ts +171 -0
  107. package/catalog/rules/supabase-contracts/manifest.json +35 -0
  108. package/catalog/rules/supabase-declarative-schema/SKILL.md +30 -0
  109. package/catalog/rules/supabase-declarative-schema/check.ts +261 -0
  110. package/catalog/rules/supabase-declarative-schema/config.json +8 -0
  111. package/catalog/rules/supabase-declarative-schema/manifest.json +40 -0
  112. package/catalog/rules/tanstack-form-rules/SKILL.md +11 -0
  113. package/catalog/rules/tanstack-form-rules/check.ts +57 -0
  114. package/catalog/rules/tanstack-form-rules/manifest.json +35 -0
  115. package/catalog/rules/unit-test-rules/SKILL.md +55 -0
  116. package/catalog/rules/unit-test-rules/check.ts +131 -0
  117. package/catalog/rules/unit-test-rules/config.json +22 -0
  118. package/catalog/rules/unit-test-rules/manifest.json +40 -0
  119. package/catalog/rules/unit-test-rules-convex/SKILL.md +41 -0
  120. package/catalog/rules/unit-test-rules-convex/check.ts +417 -0
  121. package/catalog/rules/unit-test-rules-convex/manifest.json +35 -0
  122. package/catalog/rules/unit-test-rules-supabase/SKILL.md +40 -0
  123. package/catalog/rules/unit-test-rules-supabase/check.ts +491 -0
  124. package/catalog/rules/unit-test-rules-supabase/manifest.json +35 -0
  125. package/catalog/rules/workstation-controller-rules/SKILL.md +22 -0
  126. package/catalog/rules/workstation-controller-rules/check.ts +107 -0
  127. package/catalog/rules/workstation-controller-rules/manifest.json +35 -0
  128. package/package.json +22 -0
  129. package/src/catalog-snapshot.js +39 -0
  130. package/src/catalog.js +117 -0
  131. package/src/cli.js +11 -0
  132. package/src/index.js +30 -0
  133. package/src/installer-primitives.js +198 -0
  134. package/src/project-operations.js +126 -0
  135. package/src/setup-requirements.js +82 -0
  136. package/src/shared-file.js +131 -0
  137. package/src/sync-core.js +276 -0
package/package.json ADDED
@@ -0,0 +1,22 @@
1
+ {
2
+ "name": "@specdest/devkit",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "bin": {
6
+ "specdest": "src/cli.js"
7
+ },
8
+ "exports": {
9
+ ".": "./src/index.js",
10
+ "./cli": "./src/cli.js"
11
+ },
12
+ "files": [
13
+ "src",
14
+ "catalog"
15
+ ],
16
+ "engines": {
17
+ "node": ">=24.0.0"
18
+ },
19
+ "publishConfig": {
20
+ "access": "public"
21
+ }
22
+ }
@@ -0,0 +1,39 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { listCatalogEntries, loadCatalogEntry } from './catalog.js';
3
+
4
+ function firstHeading(content) {
5
+ const line = content.split(/\r?\n/u).find((item) => /^#\s+\S/u.test(item.trim()));
6
+ return line ? line.trim().replace(/^#\s+/u, '').trim() : null;
7
+ }
8
+
9
+ function displayContent(entry) {
10
+ const skill = entry.artifacts.find((artifact) => artifact.path.endsWith('/SKILL.md'));
11
+ return skill?.content?.trim() || `${entry.kind} ${entry.id}`;
12
+ }
13
+
14
+ export async function buildCatalogSnapshot() {
15
+ const packageJson = JSON.parse(
16
+ await readFile(new URL('../package.json', import.meta.url), 'utf8'),
17
+ );
18
+ const listed = await listCatalogEntries();
19
+ const entries = [];
20
+ for (const item of listed) {
21
+ const entry = await loadCatalogEntry(item.id);
22
+ const content = displayContent(entry);
23
+ entries.push({
24
+ id: entry.id,
25
+ kind: entry.kind,
26
+ version: entry.version,
27
+ name: firstHeading(content) ?? entry.id,
28
+ content,
29
+ group: entry.kind === 'module' ? 'Modules' : 'Rules',
30
+ order: entries.length + 1,
31
+ source: '@specdest/devkit',
32
+ });
33
+ }
34
+ return {
35
+ schemaVersion: 1,
36
+ package: { name: packageJson.name, version: packageJson.version },
37
+ entries,
38
+ };
39
+ }
package/src/catalog.js ADDED
@@ -0,0 +1,117 @@
1
+ import { readdir, readFile } from 'node:fs/promises';
2
+ import { dirname, join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ import { validateSetupRequirements } from './setup-requirements.js';
6
+ import { validateManifest } from './sync-core.js';
7
+
8
+ export { validateSetupRequirements } from './setup-requirements.js';
9
+
10
+ const DEFAULT_CATALOG_ROOT = fileURLToPath(new URL('../catalog/', import.meta.url));
11
+
12
+ async function readManifest(path) {
13
+ const parsed = JSON.parse(await readFile(path, 'utf8'));
14
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
15
+ throw new Error(`Catalog manifest must be an object: ${path}`);
16
+ }
17
+ return parsed;
18
+ }
19
+
20
+ async function manifestLocations(catalogRoot = DEFAULT_CATALOG_ROOT) {
21
+ const locations = [];
22
+ for (const group of ['modules', 'rules']) {
23
+ const groupRoot = join(catalogRoot, group);
24
+ let entries;
25
+ try {
26
+ entries = await readdir(groupRoot, { withFileTypes: true });
27
+ } catch (error) {
28
+ if (error?.code === 'ENOENT') continue;
29
+ throw error;
30
+ }
31
+ for (const entry of entries) {
32
+ if (!entry.isDirectory()) continue;
33
+ locations.push(join(groupRoot, entry.name, 'manifest.json'));
34
+ }
35
+ }
36
+ return locations.sort();
37
+ }
38
+
39
+ async function hydrateManifest(manifestPath) {
40
+ const raw = await readManifest(manifestPath);
41
+ const base = dirname(manifestPath);
42
+ const artifacts = [];
43
+ for (const artifact of raw.artifacts ?? []) {
44
+ if (!artifact?.source) {
45
+ artifacts.push({ ...artifact });
46
+ continue;
47
+ }
48
+ const { source, ...rest } = artifact;
49
+ artifacts.push({
50
+ ...rest,
51
+ content: await readFile(join(base, source), 'utf8'),
52
+ });
53
+ }
54
+ const hydrated = { ...raw, artifacts };
55
+ validateManifest(hydrated);
56
+ const requires = hydrated.requires ?? [];
57
+ if (!Array.isArray(requires) || requires.some((id) => !String(id).trim())) {
58
+ throw new Error(`Invalid catalog dependencies: ${hydrated.id}`);
59
+ }
60
+ validateSetupRequirements(hydrated.setupRequirements ?? []);
61
+ if (hydrated.check) {
62
+ if (!Array.isArray(hydrated.check.command) || hydrated.check.command.length === 0) {
63
+ throw new Error(`Invalid checker command: ${hydrated.id}`);
64
+ }
65
+ }
66
+ return hydrated;
67
+ }
68
+
69
+ export async function listCatalogEntries(options = {}) {
70
+ const root = options.catalogRoot ?? DEFAULT_CATALOG_ROOT;
71
+ const entries = [];
72
+ for (const path of await manifestLocations(root)) {
73
+ const manifest = await readManifest(path);
74
+ entries.push({ id: manifest.id, kind: manifest.kind, version: manifest.version });
75
+ }
76
+ return entries.sort((a, b) => a.id.localeCompare(b.id));
77
+ }
78
+
79
+ async function catalogIndex(catalogRoot = DEFAULT_CATALOG_ROOT) {
80
+ const index = new Map();
81
+ for (const path of await manifestLocations(catalogRoot)) {
82
+ const manifest = await readManifest(path);
83
+ if (index.has(manifest.id)) throw new Error(`Duplicate catalog id: ${manifest.id}`);
84
+ index.set(manifest.id, path);
85
+ }
86
+ return index;
87
+ }
88
+
89
+ export async function loadCatalogEntry(id, options = {}) {
90
+ const root = options.catalogRoot ?? DEFAULT_CATALOG_ROOT;
91
+ const index = await catalogIndex(root);
92
+ const path = index.get(id);
93
+ if (!path) throw new Error(`Catalog entry not found: ${id}`);
94
+ return await hydrateManifest(path);
95
+ }
96
+
97
+ export async function resolveCatalogSelection(ids, options = {}) {
98
+ const root = options.catalogRoot ?? DEFAULT_CATALOG_ROOT;
99
+ const index = await catalogIndex(root);
100
+ const visiting = new Set();
101
+ const resolved = new Map();
102
+
103
+ const visit = async (id) => {
104
+ if (resolved.has(id)) return;
105
+ if (visiting.has(id)) throw new Error(`Catalog dependency cycle: ${id}`);
106
+ const path = index.get(id);
107
+ if (!path) throw new Error(`Catalog entry not found: ${id}`);
108
+ visiting.add(id);
109
+ const entry = await hydrateManifest(path);
110
+ for (const required of entry.requires ?? []) await visit(required);
111
+ visiting.delete(id);
112
+ resolved.set(id, entry);
113
+ };
114
+
115
+ for (const id of ids) await visit(id);
116
+ return [...resolved.values()];
117
+ }
package/src/cli.js ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ import { runCli } from './index.js';
3
+ import { createProjectCommandHandlers } from './project-operations.js';
4
+
5
+ try {
6
+ const exitCode = await runCli(process.argv.slice(2), process, createProjectCommandHandlers());
7
+ process.exitCode = exitCode;
8
+ } catch (error) {
9
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
10
+ process.exitCode = 1;
11
+ }
package/src/index.js ADDED
@@ -0,0 +1,30 @@
1
+ export * from './catalog.js';
2
+ export * from './installer-primitives.js';
3
+ export * from './project-operations.js';
4
+ export * from './setup-requirements.js';
5
+ export * from './shared-file.js';
6
+ export * from './sync-core.js';
7
+
8
+ export const COMMAND_NAMES = ['install', 'status', 'sync', 'check'];
9
+
10
+ const HELP = `Usage: specdest <command> [arguments]\n\nCommands:\n install <rule-or-module> Install a new rule or module\n status Show installed Specdest state\n sync Reconcile installed rules/modules\n check Run installed rule checks\n`;
11
+
12
+ export async function runCli(argv, io = process, handlers = {}) {
13
+ const [command, ...args] = argv;
14
+ if (!command || command === 'help' || command === '--help' || command === '-h') {
15
+ io.stdout.write(HELP);
16
+ return 0;
17
+ }
18
+ if (!COMMAND_NAMES.includes(command)) {
19
+ io.stderr.write(`Unknown command: ${command}\n\n${HELP}`);
20
+ return 2;
21
+ }
22
+ const handler = handlers[command];
23
+ if (!handler) {
24
+ io.stderr.write(`specdest ${command} is not implemented yet.\n`);
25
+ return 2;
26
+ }
27
+ return await handler(args, io);
28
+ }
29
+
30
+ export * from './catalog-snapshot.js';
@@ -0,0 +1,198 @@
1
+ import { mkdir, readFile, stat, writeFile } from 'node:fs/promises';
2
+ import { dirname, isAbsolute, resolve, sep } from 'node:path';
3
+
4
+ export function resolveProjectPath(projectRoot, relativePath) {
5
+ if (!relativePath || isAbsolute(relativePath)) {
6
+ throw new Error(`Path must be project-relative: ${relativePath}`);
7
+ }
8
+ const root = resolve(projectRoot);
9
+ const target = resolve(root, relativePath);
10
+ if (target !== root && !target.startsWith(`${root}${sep}`)) {
11
+ throw new Error(`Path escapes project: ${relativePath}`);
12
+ }
13
+ return target;
14
+ }
15
+
16
+ export function renderTemplate(value, parameters = {}) {
17
+ let result = String(value);
18
+ for (const [name, replacement] of Object.entries(parameters)) {
19
+ result = result.replaceAll(`{{${name}}}`, String(replacement ?? ''));
20
+ }
21
+ return result;
22
+ }
23
+
24
+ export function validateParameters(definitions = [], parameters = {}) {
25
+ const allowed = new Set(definitions.map((item) => String(item?.name ?? '')).filter(Boolean));
26
+ const unknown = Object.keys(parameters).filter((name) => !allowed.has(name)).sort();
27
+ if (unknown.length) throw new Error(`Unknown parameters: ${unknown.join(', ')}`);
28
+
29
+ const missing = definitions
30
+ .filter((item) => item?.required === true)
31
+ .map((item) => String(item.name))
32
+ .filter((name) => !String(parameters[name] ?? '').trim());
33
+ if (missing.length) throw new Error(`Missing parameters: ${missing.join(', ')}`);
34
+ return { ...parameters };
35
+ }
36
+
37
+ export async function readText(filePath) {
38
+ try {
39
+ return await readFile(filePath, 'utf8');
40
+ } catch (error) {
41
+ if (error?.code === 'ENOENT') return '';
42
+ throw error;
43
+ }
44
+ }
45
+
46
+ async function fileExists(filePath) {
47
+ try {
48
+ await stat(filePath);
49
+ return true;
50
+ } catch (error) {
51
+ if (error?.code === 'ENOENT') return false;
52
+ throw error;
53
+ }
54
+ }
55
+
56
+ export function changeAction(exists, existing, updated) {
57
+ if (exists && existing === updated) return 'unchanged';
58
+ return exists ? 'update' : 'create';
59
+ }
60
+
61
+ export async function planFileContent(projectRoot, relativePath, replacement, options = {}) {
62
+ const target = resolveProjectPath(projectRoot, relativePath);
63
+ const exists = await fileExists(target);
64
+ const existing = exists ? await readText(target) : '';
65
+ if (exists && options.createOnly) {
66
+ return {
67
+ relativePath,
68
+ target,
69
+ action: 'unchanged',
70
+ replacement: existing,
71
+ reason: 'preserve-project-owned',
72
+ };
73
+ }
74
+ return {
75
+ relativePath,
76
+ target,
77
+ action: changeAction(exists, existing, replacement),
78
+ replacement,
79
+ };
80
+ }
81
+
82
+ export async function applyFileOperation(operation) {
83
+ if (operation.action === 'unchanged') return;
84
+ if (!['create', 'update'].includes(operation.action)) {
85
+ throw new Error(`Unsupported file operation: ${operation.action}`);
86
+ }
87
+ await mkdir(dirname(operation.target), { recursive: true });
88
+ await writeFile(operation.target, operation.replacement, 'utf8');
89
+ }
90
+
91
+ function markdownSectionBounds(existing, heading) {
92
+ const trimmed = heading.trim();
93
+ const level = trimmed.match(/^(#{1,6})\s+/)?.[1].length ?? 2;
94
+ const lines = existing.split(/(?<=\n)/);
95
+ let offset = 0;
96
+ let start = -1;
97
+ let end = existing.length;
98
+ for (const line of lines) {
99
+ if (start < 0 && line.trim() === trimmed) start = offset;
100
+ else if (start >= 0 && new RegExp(`^#{1,${level}}\\s+`).test(line.trim())) {
101
+ end = offset;
102
+ break;
103
+ }
104
+ offset += line.length;
105
+ }
106
+ return start >= 0 ? [start, end] : null;
107
+ }
108
+
109
+ export function upsertMarkdownSection(existing, heading, body) {
110
+ const block = `${heading.trim()}\n\n${body.trim()}\n`;
111
+ const bounds = markdownSectionBounds(existing, heading);
112
+ if (!bounds) return `${existing.trimEnd()}${existing.trim() ? '\n\n' : ''}${block}`;
113
+ const [start, end] = bounds;
114
+ const before = existing.slice(0, start).trimEnd();
115
+ const after = existing.slice(end).trim();
116
+ return `${[before, block.trimEnd(), after].filter(Boolean).join('\n\n')}\n`;
117
+ }
118
+
119
+ function normalizeTextLines(text) {
120
+ return text.replace(/\r\n/g, '\n').split('\n');
121
+ }
122
+
123
+ function finishLineFile(lines) {
124
+ const trimmed = [...lines];
125
+ while (trimmed.length && !trimmed[trimmed.length - 1]?.trim()) trimmed.pop();
126
+ return trimmed.length ? `${trimmed.join('\n')}\n` : '';
127
+ }
128
+
129
+ export function upsertExactLines(existing, lines) {
130
+ const entries = lines.map((line) => String(line).trim()).filter(Boolean);
131
+ const existingLines = normalizeTextLines(existing);
132
+ if (
133
+ entries.every(
134
+ (entry) => existingLines.filter((line) => line.trim() === entry).length === 1,
135
+ )
136
+ ) {
137
+ return existing;
138
+ }
139
+ const remove = new Set(entries);
140
+ const kept = existingLines.filter((line) => !remove.has(line.trim()));
141
+ while (kept.length && !kept[kept.length - 1]?.trim()) kept.pop();
142
+ if (kept.length && entries.length) kept.push('');
143
+ kept.push(...entries);
144
+ return finishLineFile(kept);
145
+ }
146
+
147
+ export function removeExactLines(existing, lines) {
148
+ const remove = new Set(lines.map((line) => String(line).trim()).filter(Boolean));
149
+ return finishLineFile(normalizeTextLines(existing).filter((line) => !remove.has(line.trim())));
150
+ }
151
+
152
+ export function upsertKeyValueLines(existing, entries, separator = '=') {
153
+ const keys = new Set(Object.keys(entries));
154
+ const existingLines = normalizeTextLines(existing);
155
+ const exact = [...keys].every((key) => {
156
+ const matches = existingLines.filter((line) => {
157
+ const trimmed = line.trim();
158
+ if (!trimmed || trimmed.startsWith('#')) return false;
159
+ const index = trimmed.indexOf(separator);
160
+ return index >= 0 && trimmed.slice(0, index).trim() === key;
161
+ });
162
+ return matches.length === 1 && matches[0].trim() === `${key}${separator}${String(entries[key] ?? '')}`;
163
+ });
164
+ if (exact) return existing;
165
+ const kept = existingLines.filter((line) => {
166
+ const trimmed = line.trim();
167
+ if (!trimmed || trimmed.startsWith('#')) return true;
168
+ const index = trimmed.indexOf(separator);
169
+ return index < 0 || !keys.has(trimmed.slice(0, index).trim());
170
+ });
171
+
172
+ while (kept.length && !kept[kept.length - 1]?.trim()) kept.pop();
173
+ if (kept.length && keys.size) kept.push('');
174
+ for (const [key, value] of Object.entries(entries)) {
175
+ kept.push(`${key}${separator}${value}`);
176
+ }
177
+ return finishLineFile(kept);
178
+ }
179
+
180
+ export function removeMarkdownSection(existing, heading) {
181
+ const bounds = markdownSectionBounds(existing, heading);
182
+ if (!bounds) return existing;
183
+ const [start, end] = bounds;
184
+ const updated = `${existing.slice(0, start).trimEnd()}\n\n${existing.slice(end).trimStart()}`
185
+ .replace(/\n{3,}/g, '\n\n')
186
+ .trimEnd();
187
+ return updated ? `${updated}\n` : '';
188
+ }
189
+
190
+ export function removeKeyValueLines(existing, keys, separator = '=') {
191
+ const remove = new Set(keys.map((key) => String(key).trim()).filter(Boolean));
192
+ return finishLineFile(normalizeTextLines(existing).filter((line) => {
193
+ const trimmed = line.trim();
194
+ if (!trimmed || trimmed.startsWith('#')) return true;
195
+ const index = trimmed.indexOf(separator);
196
+ return index < 0 || !remove.has(trimmed.slice(0, index).trim());
197
+ }));
198
+ }
@@ -0,0 +1,126 @@
1
+ import { spawn } from 'node:child_process';
2
+
3
+ import { resolveCatalogSelection } from './catalog.js';
4
+ import { evaluateSetupRequirements } from './setup-requirements.js';
5
+ import {
6
+ applySyncPlan,
7
+ previewSync,
8
+ readInstalledState,
9
+ writeChecksState,
10
+ } from './sync-core.js';
11
+
12
+ function checkerArgs(command, args) {
13
+ if (command !== 'deno' || args.includes('--no-lock')) return args;
14
+ const [subcommand, ...rest] = args;
15
+ if (!subcommand) return args;
16
+ return [subcommand, '--no-lock', ...rest];
17
+ }
18
+
19
+ function defaultExecutor({ command, args, cwd }) {
20
+ return new Promise((resolve, reject) => {
21
+ const child = spawn(command, args, { cwd, stdio: ['ignore', 'pipe', 'pipe'] });
22
+ let stdout = '';
23
+ let stderr = '';
24
+ child.stdout.setEncoding('utf8');
25
+ child.stderr.setEncoding('utf8');
26
+ child.stdout.on('data', (chunk) => { stdout += chunk; });
27
+ child.stderr.on('data', (chunk) => { stderr += chunk; });
28
+ child.on('error', reject);
29
+ child.on('close', (code) => resolve({ exitCode: code ?? 1, stdout, stderr }));
30
+ });
31
+ }
32
+
33
+ export async function installCatalogEntry(projectRoot, id, options = {}) {
34
+ const current = await readInstalledState(projectRoot);
35
+ if (current.installed[id]) throw new Error(`${id} is already installed; use specdest sync`);
36
+ const requested = [...Object.keys(current.installed), id];
37
+ const entries = await resolveCatalogSelection(requested, options);
38
+ const desiredIds = entries.map((entry) => entry.id);
39
+ const plan = await previewSync(projectRoot, entries, { desiredIds });
40
+ await applySyncPlan(plan);
41
+ return plan;
42
+ }
43
+
44
+ export async function syncInstalledCatalog(projectRoot, options = {}) {
45
+ const current = await readInstalledState(projectRoot);
46
+ const entries = await resolveCatalogSelection(Object.keys(current.installed), options);
47
+ const plan = await previewSync(projectRoot, entries, { desiredIds: entries.map((entry) => entry.id) });
48
+ await applySyncPlan(plan);
49
+ return plan;
50
+ }
51
+
52
+ export async function getProjectStatus(projectRoot, options = {}) {
53
+ const current = await readInstalledState(projectRoot);
54
+ const entries = await resolveCatalogSelection(Object.keys(current.installed), options);
55
+ return {
56
+ ...current,
57
+ setup: await evaluateSetupRequirements(projectRoot, entries, options),
58
+ };
59
+ }
60
+
61
+ export async function runInstalledChecks(projectRoot, options = {}) {
62
+ const current = await readInstalledState(projectRoot);
63
+ const entries = await resolveCatalogSelection(Object.keys(current.installed), options);
64
+ const executor = options.executor ?? defaultExecutor;
65
+ const now = options.now ?? (() => new Date());
66
+ const results = {};
67
+ let exitCode = 0;
68
+
69
+ for (const entry of entries) {
70
+ if (entry.kind !== 'rule' || !entry.check) continue;
71
+ const [command, ...args] = entry.check.command;
72
+ const execution = await executor({ command, args: checkerArgs(command, args), cwd: projectRoot });
73
+ const status = execution.exitCode === 0 ? 'pass' : 'fail';
74
+ if (execution.exitCode !== 0) exitCode = 1;
75
+ results[entry.id] = {
76
+ status,
77
+ exitCode: execution.exitCode,
78
+ stdout: execution.stdout ?? '',
79
+ stderr: execution.stderr ?? '',
80
+ };
81
+ }
82
+
83
+ const checkedAt = now().toISOString();
84
+ await writeChecksState(projectRoot, { schemaVersion: 1, checkedAt, results });
85
+ return { exitCode, checkedAt, results };
86
+ }
87
+
88
+ export function createProjectCommandHandlers(projectRoot = process.cwd()) {
89
+ return {
90
+ install: async (args, io) => {
91
+ if (args.length !== 1) {
92
+ io.stderr.write('Usage: specdest install <rule-or-module>\n');
93
+ return 2;
94
+ }
95
+ const plan = await installCatalogEntry(projectRoot, args[0]);
96
+ io.stdout.write(`Installed ${args[0]} (${plan.operations.filter((op) => op.action !== 'unchanged').length} changes).\n`);
97
+ return 0;
98
+ },
99
+ status: async (args, io) => {
100
+ if (args.length) {
101
+ io.stderr.write('Usage: specdest status\n');
102
+ return 2;
103
+ }
104
+ io.stdout.write(`${JSON.stringify(await getProjectStatus(projectRoot), null, 2)}\n`);
105
+ return 0;
106
+ },
107
+ sync: async (args, io) => {
108
+ if (args.length) {
109
+ io.stderr.write('Usage: specdest sync\n');
110
+ return 2;
111
+ }
112
+ const plan = await syncInstalledCatalog(projectRoot);
113
+ io.stdout.write(`Synced ${Object.keys(plan.nextState.installed).length} installed items.\n`);
114
+ return 0;
115
+ },
116
+ check: async (args, io) => {
117
+ if (args.length) {
118
+ io.stderr.write('Usage: specdest check\n');
119
+ return 2;
120
+ }
121
+ const result = await runInstalledChecks(projectRoot);
122
+ for (const [id, check] of Object.entries(result.results)) io.stdout.write(`${check.status.toUpperCase()} ${id}\n`);
123
+ return result.exitCode;
124
+ },
125
+ };
126
+ }
@@ -0,0 +1,82 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+
4
+ const DEFAULT_ENV_FILES = [
5
+ '.env',
6
+ '.env.local',
7
+ '.env.development',
8
+ '.env.development.local',
9
+ '.env.production',
10
+ '.env.production.local',
11
+ '.env.test',
12
+ '.env.test.local',
13
+ ];
14
+
15
+ function parseEnvText(text) {
16
+ const values = {};
17
+ for (const rawLine of text.split(/\r?\n/)) {
18
+ const line = rawLine.trim();
19
+ if (!line || line.startsWith('#')) continue;
20
+ const normalized = line.startsWith('export ') ? line.slice(7).trim() : line;
21
+ const index = normalized.indexOf('=');
22
+ if (index <= 0) continue;
23
+ const name = normalized.slice(0, index).trim();
24
+ let value = normalized.slice(index + 1).trim();
25
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
26
+ value = value.slice(1, -1);
27
+ }
28
+ values[name] = value;
29
+ }
30
+ return values;
31
+ }
32
+ export function validateSetupRequirements(requirements = []) {
33
+ if (!Array.isArray(requirements)) throw new Error('setupRequirements must be an array');
34
+ const seen = new Set();
35
+ for (const item of requirements) {
36
+ if (!item || typeof item !== 'object' || Array.isArray(item)) throw new Error('Setup requirement must be an object');
37
+ if (item.kind !== 'env') throw new Error(`Unsupported setup requirement kind: ${item.kind}`);
38
+ if (!/^[A-Z][A-Z0-9_]*$/.test(String(item.name ?? ''))) throw new Error('Setup env requirement name must be uppercase snake case');
39
+ if (item.required !== true && item.required !== false) throw new Error(`Setup env requirement required must be boolean: ${item.name}`);
40
+ const key = `${item.kind}:${item.name}`;
41
+ if (seen.has(key)) throw new Error(`Duplicate setup requirement: ${item.name}`);
42
+ seen.add(key);
43
+ if (item.exampleFile !== undefined && !String(item.exampleFile).trim()) throw new Error(`Invalid exampleFile for setup requirement: ${item.name}`);
44
+ }
45
+ return requirements;
46
+ }
47
+
48
+ async function readProjectEnvValues(projectRoot, options = {}) {
49
+ const values = { ...(options.env ?? process.env) };
50
+ const files = options.envFiles ?? DEFAULT_ENV_FILES;
51
+ for (const relativePath of files) {
52
+ let text = '';
53
+ try {
54
+ text = await readFile(join(projectRoot, relativePath), 'utf8');
55
+ } catch (error) {
56
+ if (error?.code === 'ENOENT') continue;
57
+ throw error;
58
+ }
59
+ Object.assign(values, parseEnvText(text));
60
+ }
61
+ return values;
62
+ }
63
+ export async function evaluateSetupRequirements(projectRoot, entries, options = {}) {
64
+ const values = await readProjectEnvValues(projectRoot, options);
65
+ const requirements = [];
66
+ for (const entry of entries) {
67
+ validateSetupRequirements(entry.setupRequirements ?? []);
68
+ for (const item of entry.setupRequirements ?? []) {
69
+ const configured = Boolean(String(values[item.name] ?? '').trim());
70
+ requirements.push({
71
+ ownerId: entry.id,
72
+ ...item,
73
+ status: configured ? 'configured' : 'missing',
74
+ });
75
+ }
76
+ }
77
+ requirements.sort((a, b) => a.name.localeCompare(b.name) || a.ownerId.localeCompare(b.ownerId));
78
+ return {
79
+ requirements,
80
+ missing: requirements.filter((item) => item.required && item.status === 'missing'),
81
+ };
82
+ }