@specdest/devkit 0.4.6 → 0.4.8

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 (125) hide show
  1. package/README.md +34 -4
  2. package/dist/npm/canonical-project-operations.d.ts +5 -0
  3. package/dist/npm/canonical-project-operations.js +5 -0
  4. package/dist/npm/canonical-project.d.ts +10 -0
  5. package/dist/npm/canonical-project.js +109 -0
  6. package/dist/npm/canonical-source.d.ts +14 -0
  7. package/dist/npm/canonical-source.js +216 -0
  8. package/dist/npm/catalog-snapshot.d.ts +47 -0
  9. package/dist/npm/catalog-snapshot.js +28 -0
  10. package/dist/npm/cli.d.ts +2 -0
  11. package/dist/npm/cli.js +15 -0
  12. package/dist/npm/commands.d.ts +9 -0
  13. package/dist/npm/commands.js +157 -0
  14. package/dist/npm/flow.d.ts +48 -0
  15. package/dist/npm/flow.js +396 -0
  16. package/dist/npm/fuzz.d.ts +138 -0
  17. package/dist/npm/fuzz.js +327 -0
  18. package/dist/npm/git-catalog.d.ts +39 -0
  19. package/dist/npm/git-catalog.js +190 -0
  20. package/dist/npm/index.d.ts +5 -0
  21. package/dist/npm/index.js +22 -0
  22. package/dist/npm/installer-primitives.d.ts +3 -0
  23. package/dist/npm/installer-primitives.js +50 -0
  24. package/dist/npm/predefined-packages/abac.d.ts +2 -0
  25. package/dist/npm/predefined-packages/abac.js +22 -0
  26. package/dist/npm/predefined-packages/auth.d.ts +2 -0
  27. package/dist/npm/predefined-packages/auth.js +21 -0
  28. package/dist/npm/predefined-packages/convex.d.ts +2 -0
  29. package/dist/npm/predefined-packages/convex.js +53 -0
  30. package/dist/npm/predefined-packages/expo.d.ts +2 -0
  31. package/dist/npm/predefined-packages/expo.js +84 -0
  32. package/dist/npm/predefined-packages/firebase-hosting.d.ts +2 -0
  33. package/dist/npm/predefined-packages/firebase-hosting.js +24 -0
  34. package/dist/npm/predefined-packages/health.d.ts +10 -0
  35. package/dist/npm/predefined-packages/health.js +52 -0
  36. package/dist/npm/predefined-packages/husky.d.ts +2 -0
  37. package/dist/npm/predefined-packages/husky.js +57 -0
  38. package/dist/npm/predefined-packages/index.d.ts +11 -0
  39. package/dist/npm/predefined-packages/index.js +56 -0
  40. package/dist/npm/predefined-packages/install.d.ts +19 -0
  41. package/dist/npm/predefined-packages/install.js +85 -0
  42. package/dist/npm/predefined-packages/local-logging.d.ts +2 -0
  43. package/dist/npm/predefined-packages/local-logging.js +17 -0
  44. package/dist/npm/predefined-packages/logging.d.ts +2 -0
  45. package/dist/npm/predefined-packages/logging.js +21 -0
  46. package/dist/npm/predefined-packages/multi-tenancy.d.ts +2 -0
  47. package/dist/npm/predefined-packages/multi-tenancy.js +21 -0
  48. package/dist/npm/predefined-packages/nps.d.ts +2 -0
  49. package/dist/npm/predefined-packages/nps.js +32 -0
  50. package/dist/npm/predefined-packages/oxfmt.d.ts +2 -0
  51. package/dist/npm/predefined-packages/oxfmt.js +22 -0
  52. package/dist/npm/predefined-packages/oxlint.d.ts +2 -0
  53. package/dist/npm/predefined-packages/oxlint.js +35 -0
  54. package/dist/npm/predefined-packages/package-json.d.ts +3 -0
  55. package/dist/npm/predefined-packages/package-json.js +61 -0
  56. package/dist/npm/predefined-packages/payments.d.ts +2 -0
  57. package/dist/npm/predefined-packages/payments.js +31 -0
  58. package/dist/npm/predefined-packages/playwright.d.ts +2 -0
  59. package/dist/npm/predefined-packages/playwright.js +35 -0
  60. package/dist/npm/predefined-packages/project-signals.d.ts +4 -0
  61. package/dist/npm/predefined-packages/project-signals.js +39 -0
  62. package/dist/npm/predefined-packages/registry.d.ts +3 -0
  63. package/dist/npm/predefined-packages/registry.js +63 -0
  64. package/dist/npm/predefined-packages/resolver.d.ts +8 -0
  65. package/dist/npm/predefined-packages/resolver.js +35 -0
  66. package/dist/npm/predefined-packages/sentry.d.ts +2 -0
  67. package/dist/npm/predefined-packages/sentry.js +29 -0
  68. package/dist/npm/predefined-packages/shadcn.d.ts +2 -0
  69. package/dist/npm/predefined-packages/shadcn.js +23 -0
  70. package/dist/npm/predefined-packages/storybook.d.ts +2 -0
  71. package/dist/npm/predefined-packages/storybook.js +25 -0
  72. package/dist/npm/predefined-packages/stryker.d.ts +2 -0
  73. package/dist/npm/predefined-packages/stryker.js +48 -0
  74. package/dist/npm/predefined-packages/supabase.d.ts +2 -0
  75. package/dist/npm/predefined-packages/supabase.js +84 -0
  76. package/dist/npm/predefined-packages/tailwind.d.ts +2 -0
  77. package/dist/npm/predefined-packages/tailwind.js +18 -0
  78. package/dist/npm/predefined-packages/tanstack-form.d.ts +2 -0
  79. package/dist/npm/predefined-packages/tanstack-form.js +19 -0
  80. package/dist/npm/predefined-packages/tanstack-query.d.ts +2 -0
  81. package/dist/npm/predefined-packages/tanstack-query.js +15 -0
  82. package/dist/npm/predefined-packages/tanstack-router.d.ts +2 -0
  83. package/dist/npm/predefined-packages/tanstack-router.js +18 -0
  84. package/dist/npm/predefined-packages/types.d.ts +31 -0
  85. package/dist/npm/predefined-packages/types.js +1 -0
  86. package/dist/npm/predefined-packages/vite.d.ts +2 -0
  87. package/dist/npm/predefined-packages/vite.js +123 -0
  88. package/dist/npm/predefined-packages/vitest.d.ts +2 -0
  89. package/dist/npm/predefined-packages/vitest.js +20 -0
  90. package/dist/npm/predefined-packages/zod.d.ts +2 -0
  91. package/dist/npm/predefined-packages/zod.js +18 -0
  92. package/dist/npm/project-check.d.ts +6 -0
  93. package/dist/npm/project-check.js +87 -0
  94. package/dist/npm/project-context.d.ts +42 -0
  95. package/dist/npm/project-context.js +192 -0
  96. package/dist/npm/project-rules.d.ts +22 -0
  97. package/dist/npm/project-rules.js +66 -0
  98. package/dist/npm/project-runtime.d.ts +18 -0
  99. package/dist/npm/project-runtime.js +27 -0
  100. package/dist/npm/project-status.d.ts +32 -0
  101. package/dist/npm/project-status.js +56 -0
  102. package/dist/npm/project-sync.d.ts +7 -0
  103. package/dist/npm/project-sync.js +135 -0
  104. package/dist/npm/remote-installer.d.ts +4 -0
  105. package/dist/npm/remote-installer.js +312 -0
  106. package/dist/npm/state.d.ts +14 -0
  107. package/dist/npm/state.js +182 -0
  108. package/package.json +10 -7
  109. package/src/canonical-project-operations.js +0 -438
  110. package/src/canonical-project.js +0 -136
  111. package/src/canonical-source.js +0 -250
  112. package/src/catalog-snapshot.js +0 -39
  113. package/src/catalog.js +0 -117
  114. package/src/cli.js +0 -14
  115. package/src/fuzz.js +0 -291
  116. package/src/git-catalog.js +0 -177
  117. package/src/index.js +0 -36
  118. package/src/installer-primitives.js +0 -198
  119. package/src/project-operations.js +0 -189
  120. package/src/project-targeting.js +0 -48
  121. package/src/remote-installer.js +0 -479
  122. package/src/rule-profile.js +0 -61
  123. package/src/setup-requirements.js +0 -82
  124. package/src/shared-file.js +0 -131
  125. package/src/sync-core.js +0 -390
@@ -0,0 +1,312 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdir, readFile, stat, unlink, writeFile } from 'node:fs/promises';
3
+ import { dirname, isAbsolute, resolve, sep } from 'node:path';
4
+ import { removeMarkdownSection, resolveProjectPath, upsertMarkdownSection } from './installer-primitives.js';
5
+ import { readChecksState, readInstalledState, writeChecksState, writeInstalledState } from "./state.js";
6
+ const SUPPORTED_OPERATIONS = new Set(['copy_file', 'scaffold_file', 'managed_section']);
7
+ const clone = (value) => value === undefined ? undefined : JSON.parse(JSON.stringify(value));
8
+ const hash = (value) => createHash('sha256').update(typeof value === 'string' ? value : JSON.stringify(value)).digest('hex');
9
+ function payloadPath(payloadRoot, relativePath) {
10
+ if (!relativePath || isAbsolute(relativePath))
11
+ throw new Error(`Source must be payload-relative: ${relativePath}`);
12
+ const root = resolve(payloadRoot);
13
+ const target = resolve(root, relativePath);
14
+ if (target !== root && !target.startsWith(`${root}${sep}`))
15
+ throw new Error(`Source escapes payload: ${relativePath}`);
16
+ return target;
17
+ }
18
+ async function exists(path) {
19
+ try {
20
+ await stat(path);
21
+ return true;
22
+ }
23
+ catch (error) {
24
+ if (error?.code === 'ENOENT')
25
+ return false;
26
+ throw error;
27
+ }
28
+ }
29
+ const checkerSkillIds = new Map([
30
+ ['abac-permissions-convex', 'abac-permissions'],
31
+ ['abac-permissions-supabase', 'abac-permissions'],
32
+ ['unit-test-rules-convex', 'unit-test-rules'],
33
+ ['unit-test-rules-supabase', 'unit-test-rules'],
34
+ ]);
35
+ function checkerSkillId(implementation) {
36
+ return checkerSkillIds.get(implementation) ?? implementation;
37
+ }
38
+ function normalizeManifest(manifest) {
39
+ const operations = Array.isArray(manifest?.operations) ? [...manifest.operations] : [];
40
+ const checkerImplementation = String(manifest?.checker?.implementation ?? '').trim();
41
+ const check = manifest?.check ?? (checkerImplementation
42
+ ? { command: ['node', `.agents/skills/${checkerSkillId(checkerImplementation)}/check.ts`] }
43
+ : undefined);
44
+ for (const copy of manifest?.copies ?? []) {
45
+ if (copy.type === 'directory' || copy.directory === true) {
46
+ throw new Error(`Directory copies are not supported: ${copy.source}`);
47
+ }
48
+ operations.push({
49
+ type: copy.mode === 'scaffold' || copy.mode === 'create-only' ? 'scaffold_file' : 'copy_file',
50
+ source: copy.source,
51
+ path: copy.target ?? copy.path,
52
+ });
53
+ }
54
+ for (const section of manifest?.markdownSections ?? []) {
55
+ operations.push({
56
+ type: 'managed_section',
57
+ path: section.path,
58
+ heading: section.heading,
59
+ content: section.body ?? section.content ?? '',
60
+ });
61
+ }
62
+ return { ...manifest, operations, ...(check ? { check } : {}) };
63
+ }
64
+ export function validateRemoteManifest(input) {
65
+ if (!input || typeof input !== 'object' || !String(input.id ?? '').trim())
66
+ throw new Error('Manifest id is required');
67
+ const manifest = normalizeManifest(input);
68
+ for (const operation of manifest.operations) {
69
+ if (!SUPPORTED_OPERATIONS.has(operation?.type))
70
+ throw new Error(`Unsupported manifest operation: ${operation?.type}`);
71
+ resolveProjectPath('/__specdest_project__', operation.path);
72
+ if (operation.type !== 'managed_section' && !String(operation.source ?? '').trim()) {
73
+ throw new Error(`Manifest operation source is required: ${operation.type}`);
74
+ }
75
+ if (operation.type === 'managed_section' && !String(operation.heading ?? '').trim()) {
76
+ throw new Error('Managed section heading is required');
77
+ }
78
+ }
79
+ return manifest;
80
+ }
81
+ function ownershipKey(operation) {
82
+ return operation.type === 'managed_section'
83
+ ? `section:${operation.path}:${operation.heading}`
84
+ : `file:${operation.path}`;
85
+ }
86
+ async function readProjectFile(projectRoot, relativePath) {
87
+ const target = resolveProjectPath(projectRoot, relativePath);
88
+ if (!(await exists(target)))
89
+ return { exists: false, value: '' };
90
+ return { exists: true, value: await readFile(target, 'utf8') };
91
+ }
92
+ async function writeProjectFile(projectRoot, relativePath, content) {
93
+ const target = resolveProjectPath(projectRoot, relativePath);
94
+ await mkdir(dirname(target), { recursive: true });
95
+ await writeFile(target, content, 'utf8');
96
+ }
97
+ function sectionBody(text, heading) {
98
+ const trimmed = heading.trim();
99
+ const level = trimmed.match(/^(#{1,6})\s+/)?.[1].length ?? 2;
100
+ const lines = text.split(/(?<=\n)/u);
101
+ let found = false;
102
+ const body = [];
103
+ for (const line of lines) {
104
+ if (!found) {
105
+ if (line.trim() === trimmed)
106
+ found = true;
107
+ continue;
108
+ }
109
+ if (new RegExp(`^#{1,${level}}\\s+`, 'u').test(line.trim()))
110
+ break;
111
+ body.push(line);
112
+ }
113
+ return found ? body.join('').trim() : null;
114
+ }
115
+ function legacyMarkdownSection(text, heading) {
116
+ const lines = text.split(/(?<=\n)/u);
117
+ const level = heading.trim().match(/^(#{1,6})\s/u)?.[1].length ?? 2;
118
+ let start = -1;
119
+ let end = text.length;
120
+ let offset = 0;
121
+ for (const line of lines) {
122
+ if (start < 0 && line.trim() === heading.trim())
123
+ start = offset;
124
+ else if (start >= 0 && new RegExp(`^#{1,${level}}\\s+`, 'u').test(line.trim())) {
125
+ end = offset;
126
+ break;
127
+ }
128
+ offset += line.length;
129
+ }
130
+ return start < 0 ? { exists: false, value: '' } : { exists: true, value: text.slice(start, end).trimEnd() };
131
+ }
132
+ async function migrateLegacyMarkdownOwnership(projectRoot, prior) {
133
+ for (const [key, record] of Object.entries(prior)) {
134
+ if (record?.type !== 'markdown')
135
+ continue;
136
+ const file = await readProjectFile(projectRoot, record.path);
137
+ const legacyCurrent = file.exists
138
+ ? legacyMarkdownSection(file.value, record.heading)
139
+ : { exists: false, value: '' };
140
+ if (record.appliedHash !== fingerprint(legacyCurrent)) {
141
+ throw new Error(`Conflict: managed content changed: ${record.path}`);
142
+ }
143
+ const currentBody = file.exists ? sectionBody(file.value, record.heading) : null;
144
+ const nextKey = `section:${record.path}:${record.heading}`;
145
+ if (prior[nextKey])
146
+ throw new Error(`Conflicting ownership records: ${record.path}`);
147
+ const previousBody = record.previousExists
148
+ ? sectionBody(String(record.previousValue ?? ''), record.heading)
149
+ : null;
150
+ prior[nextKey] = {
151
+ type: 'section',
152
+ path: record.path,
153
+ heading: record.heading,
154
+ previousExists: Boolean(record.previousExists),
155
+ previousValue: previousBody ?? '',
156
+ appliedHash: fingerprint({ exists: currentBody !== null, value: currentBody ?? '' }),
157
+ };
158
+ delete prior[key];
159
+ }
160
+ }
161
+ async function currentOwnership(projectRoot, record) {
162
+ const file = await readProjectFile(projectRoot, record.path);
163
+ if (record.type === 'file')
164
+ return file;
165
+ const body = file.exists ? sectionBody(file.value, record.heading) : null;
166
+ return { exists: body !== null, value: body ?? '' };
167
+ }
168
+ function fingerprint(value) {
169
+ return hash({ exists: value.exists, value: value.value });
170
+ }
171
+ function assertOwned(record, current) {
172
+ if (record.appliedHash !== fingerprint(current))
173
+ throw new Error(`Conflict: managed content changed: ${record.path}`);
174
+ }
175
+ async function restoreOwnership(projectRoot, record) {
176
+ const current = await currentOwnership(projectRoot, record);
177
+ assertOwned(record, current);
178
+ if (record.type === 'file') {
179
+ const target = resolveProjectPath(projectRoot, record.path);
180
+ if (record.previousExists)
181
+ await writeProjectFile(projectRoot, record.path, record.previousValue);
182
+ else if (await exists(target))
183
+ await unlink(target);
184
+ return;
185
+ }
186
+ const file = await readProjectFile(projectRoot, record.path);
187
+ const updated = record.previousExists
188
+ ? upsertMarkdownSection(file.value, record.heading, record.previousValue)
189
+ : removeMarkdownSection(file.value, record.heading);
190
+ await writeProjectFile(projectRoot, record.path, updated);
191
+ }
192
+ async function applyManagedFile(operation, context) {
193
+ const key = ownershipKey(operation);
194
+ const current = await readProjectFile(context.projectRoot, operation.path);
195
+ const prior = context.prior[key];
196
+ if (prior)
197
+ assertOwned(prior, current);
198
+ const source = await readFile(payloadPath(context.payloadRoot, operation.source), 'utf8');
199
+ await writeProjectFile(context.projectRoot, operation.path, source);
200
+ const original = prior ?? { previousExists: current.exists, previousValue: current.value };
201
+ context.next[key] = {
202
+ type: 'file',
203
+ path: operation.path,
204
+ previousExists: original.previousExists,
205
+ previousValue: original.previousValue,
206
+ appliedHash: fingerprint({ exists: true, value: source }),
207
+ };
208
+ context.touched.add(key);
209
+ }
210
+ async function applyScaffold(operation, context) {
211
+ const key = ownershipKey(operation);
212
+ const prior = context.prior[key];
213
+ if (prior) {
214
+ delete context.next[key];
215
+ context.touched.add(key);
216
+ return;
217
+ }
218
+ const target = resolveProjectPath(context.projectRoot, operation.path);
219
+ if (await exists(target))
220
+ return;
221
+ const source = await readFile(payloadPath(context.payloadRoot, operation.source), 'utf8');
222
+ await writeProjectFile(context.projectRoot, operation.path, source);
223
+ }
224
+ async function applyManagedSection(operation, context) {
225
+ const key = ownershipKey(operation);
226
+ const file = await readProjectFile(context.projectRoot, operation.path);
227
+ const body = file.exists ? sectionBody(file.value, operation.heading) : null;
228
+ const current = { exists: body !== null, value: body ?? '' };
229
+ const prior = context.prior[key];
230
+ if (prior)
231
+ assertOwned(prior, current);
232
+ const original = prior ?? { previousExists: current.exists, previousValue: current.value };
233
+ const updated = upsertMarkdownSection(file.value, operation.heading, String(operation.content ?? ''));
234
+ await writeProjectFile(context.projectRoot, operation.path, updated);
235
+ const appliedBody = sectionBody(updated, operation.heading) ?? '';
236
+ context.next[key] = {
237
+ type: 'section',
238
+ path: operation.path,
239
+ heading: operation.heading,
240
+ previousExists: original.previousExists,
241
+ previousValue: original.previousValue,
242
+ appliedHash: fingerprint({ exists: true, value: appliedBody }),
243
+ };
244
+ context.touched.add(key);
245
+ }
246
+ async function applyOperation(operation, context) {
247
+ if (operation.type === 'copy_file')
248
+ return applyManagedFile(operation, context);
249
+ if (operation.type === 'scaffold_file')
250
+ return applyScaffold(operation, context);
251
+ return applyManagedSection(operation, context);
252
+ }
253
+ async function reconcile(kind, { projectRoot, payloadRoot, manifest: inputManifest }) {
254
+ const manifest = validateRemoteManifest(inputManifest);
255
+ const installedState = await readInstalledState(projectRoot);
256
+ const runtimeState = await readChecksState(projectRoot);
257
+ runtimeState.results ??= {};
258
+ runtimeState.ownership ??= {};
259
+ const installed = installedState.installed[manifest.id];
260
+ if (kind === 'install' && installed)
261
+ throw new Error(`${manifest.id} is already installed`);
262
+ if (kind !== 'install' && !installed)
263
+ throw new Error(`${manifest.id} is not installed`);
264
+ const prior = clone(runtimeState.ownership[manifest.id] ?? {});
265
+ await migrateLegacyMarkdownOwnership(projectRoot, prior);
266
+ const context = { projectRoot, payloadRoot, prior, next: clone(prior), touched: new Set() };
267
+ if (kind === 'remove') {
268
+ for (const record of Object.values(prior))
269
+ await restoreOwnership(projectRoot, record);
270
+ context.next = {};
271
+ }
272
+ else {
273
+ for (const operation of manifest.operations)
274
+ await applyOperation(operation, context);
275
+ for (const [key, record] of Object.entries(prior)) {
276
+ if (!context.touched.has(key) && context.next[key]) {
277
+ await restoreOwnership(projectRoot, record);
278
+ delete context.next[key];
279
+ }
280
+ }
281
+ }
282
+ if (kind === 'remove') {
283
+ delete installedState.installed[manifest.id];
284
+ installedState.requested = installedState.requested.filter((id) => id !== manifest.id);
285
+ delete runtimeState.ownership[manifest.id];
286
+ delete runtimeState.results[manifest.id];
287
+ }
288
+ else {
289
+ const contentHash = String(manifest.contentHash ?? hash({
290
+ id: manifest.id,
291
+ revision: manifest.revision ?? null,
292
+ operations: manifest.operations,
293
+ check: manifest.check ?? null,
294
+ }));
295
+ const revision = String(manifest.revision ?? contentHash);
296
+ installedState.installed[manifest.id] = {
297
+ kind: manifest.kind ?? 'rule',
298
+ version: String(manifest.version ?? contentHash),
299
+ revision,
300
+ contentHash,
301
+ ...(manifest.check ? { check: clone(manifest.check) } : {}),
302
+ };
303
+ installedState.requested = [...new Set([...installedState.requested, manifest.id])].sort();
304
+ runtimeState.ownership[manifest.id] = context.next;
305
+ }
306
+ await writeInstalledState(projectRoot, { ...installedState, schemaVersion: 2 });
307
+ await writeChecksState(projectRoot, { ...runtimeState, schemaVersion: 2 });
308
+ return installedState.installed[manifest.id] ?? null;
309
+ }
310
+ export async function installRule(options) { return reconcile('install', options); }
311
+ export async function syncRule(options) { return reconcile('sync', options); }
312
+ export async function removeRule(options) { return reconcile('remove', options); }
@@ -0,0 +1,14 @@
1
+ export declare const STATE_SCHEMA_VERSION = 2;
2
+ export declare const CHECKS_SCHEMA_VERSION = 2;
3
+ export declare const METADATA_DIRECTORY = ".spd";
4
+ export declare const LEGACY_METADATA_DIRECTORY = ".specdest";
5
+ export declare const INSTALLED_RELATIVE_PATH = ".spd/installed.json";
6
+ export declare const STATE_RELATIVE_PATH = ".spd/state.json";
7
+ export declare const CHECKS_RELATIVE_PATH = ".spd/state.json";
8
+ export declare const LEGACY_CHECKS_RELATIVE_PATH = ".spd/checks.json";
9
+ export declare function formatJsonState(value: unknown): string;
10
+ export declare function ensureMetadataNamespace(projectRoot: string): Promise<void>;
11
+ export declare function readInstalledState(projectRoot: string): Promise<any>;
12
+ export declare function writeInstalledState(projectRoot: string, state: any): Promise<void>;
13
+ export declare function readChecksState(projectRoot: string): Promise<any>;
14
+ export declare function writeChecksState(projectRoot: string, state: any): Promise<void>;
@@ -0,0 +1,182 @@
1
+ import { access, mkdir, readFile, readdir, rename, writeFile } from 'node:fs/promises';
2
+ import { dirname, join } from 'node:path';
3
+ export const STATE_SCHEMA_VERSION = 2;
4
+ export const CHECKS_SCHEMA_VERSION = 2;
5
+ export const METADATA_DIRECTORY = '.spd';
6
+ export const LEGACY_METADATA_DIRECTORY = '.specdest';
7
+ export const INSTALLED_RELATIVE_PATH = '.spd/installed.json';
8
+ export const STATE_RELATIVE_PATH = '.spd/state.json';
9
+ export const CHECKS_RELATIVE_PATH = STATE_RELATIVE_PATH;
10
+ export const LEGACY_CHECKS_RELATIVE_PATH = '.spd/checks.json';
11
+ const EMPTY_INSTALLED = Object.freeze({ schemaVersion: 2, requested: [], installed: {} });
12
+ const EMPTY_CHECKS = Object.freeze({ schemaVersion: CHECKS_SCHEMA_VERSION, results: {} });
13
+ const JSON_INDENT = 2;
14
+ const JSON_LINE_WIDTH = 100;
15
+ function clone(value) {
16
+ return JSON.parse(JSON.stringify(value));
17
+ }
18
+ function isOmittedJsonValue(value) {
19
+ return value === undefined || ['function', 'symbol'].includes(typeof value);
20
+ }
21
+ function formatJsonValue(value, depth = 0, { arrayItem = false } = {}) {
22
+ if (isOmittedJsonValue(value))
23
+ return arrayItem ? 'null' : undefined;
24
+ if (value === null || typeof value !== 'object')
25
+ return JSON.stringify(value);
26
+ const indent = ' '.repeat(depth * JSON_INDENT);
27
+ const childIndent = ' '.repeat((depth + 1) * JSON_INDENT);
28
+ if (Array.isArray(value)) {
29
+ if (!value.length)
30
+ return '[]';
31
+ const primitive = value.every((item) => isOmittedJsonValue(item) || item === null || ['string', 'number', 'boolean'].includes(typeof item));
32
+ if (primitive) {
33
+ const inline = `[${value.map((item) => formatJsonValue(item, depth + 1, { arrayItem: true })).join(', ')}]`;
34
+ if (indent.length + inline.length <= JSON_LINE_WIDTH)
35
+ return inline;
36
+ }
37
+ return `[\n${value.map((item) => `${childIndent}${formatJsonValue(item, depth + 1, { arrayItem: true })}`).join(',\n')}\n${indent}]`;
38
+ }
39
+ const entries = Object.entries(value).filter(([, item]) => !isOmittedJsonValue(item));
40
+ if (!entries.length)
41
+ return '{}';
42
+ return `{\n${entries.map(([key, item]) => `${childIndent}${JSON.stringify(key)}: ${formatJsonValue(item, depth + 1)}`).join(',\n')}\n${indent}}`;
43
+ }
44
+ export function formatJsonState(value) {
45
+ return `${formatJsonValue(value)}\n`;
46
+ }
47
+ async function pathExists(path) {
48
+ try {
49
+ await access(path);
50
+ return true;
51
+ }
52
+ catch (error) {
53
+ if (error.code === 'ENOENT')
54
+ return false;
55
+ throw error;
56
+ }
57
+ }
58
+ async function listRelativeFiles(root, directory = '') {
59
+ const absolute = join(root, directory);
60
+ const entries = await readdir(absolute, { withFileTypes: true });
61
+ const files = [];
62
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
63
+ const relativePath = directory ? join(directory, entry.name) : entry.name;
64
+ if (entry.isDirectory())
65
+ files.push(...await listRelativeFiles(root, relativePath));
66
+ else
67
+ files.push(relativePath);
68
+ }
69
+ return files;
70
+ }
71
+ async function assertCompatibleNamespaces(projectRoot) {
72
+ const canonicalRoot = join(projectRoot, METADATA_DIRECTORY);
73
+ const legacyRoot = join(projectRoot, LEGACY_METADATA_DIRECTORY);
74
+ const legacyFiles = await listRelativeFiles(legacyRoot);
75
+ for (const relativePath of legacyFiles) {
76
+ const canonicalPath = join(canonicalRoot, relativePath);
77
+ if (!(await pathExists(canonicalPath))) {
78
+ throw new Error(`Specdest metadata namespace conflict: legacy ${LEGACY_METADATA_DIRECTORY}/${relativePath} has no canonical counterpart.`);
79
+ }
80
+ const [canonical, legacy] = await Promise.all([
81
+ readFile(canonicalPath),
82
+ readFile(join(legacyRoot, relativePath)),
83
+ ]);
84
+ if (!canonical.equals(legacy)) {
85
+ throw new Error(`Specdest metadata namespace conflict: ${METADATA_DIRECTORY}/${relativePath} differs from legacy ${LEGACY_METADATA_DIRECTORY}/${relativePath}.`);
86
+ }
87
+ }
88
+ }
89
+ export async function ensureMetadataNamespace(projectRoot) {
90
+ const canonicalRoot = join(projectRoot, METADATA_DIRECTORY);
91
+ const legacyRoot = join(projectRoot, LEGACY_METADATA_DIRECTORY);
92
+ const [canonicalExists, legacyExists] = await Promise.all([
93
+ pathExists(canonicalRoot),
94
+ pathExists(legacyRoot),
95
+ ]);
96
+ if (canonicalExists && legacyExists) {
97
+ await assertCompatibleNamespaces(projectRoot);
98
+ return;
99
+ }
100
+ if (!canonicalExists && legacyExists)
101
+ await rename(legacyRoot, canonicalRoot);
102
+ }
103
+ async function readJsonOrDefault(filePath, fallback) {
104
+ try {
105
+ return JSON.parse(await readFile(filePath, 'utf8'));
106
+ }
107
+ catch (error) {
108
+ if (error.code === 'ENOENT')
109
+ return clone(fallback);
110
+ throw error;
111
+ }
112
+ }
113
+ async function writeJsonAtomic(filePath, value) {
114
+ await mkdir(dirname(filePath), { recursive: true });
115
+ const temp = `${filePath}.${process.pid}.tmp`;
116
+ await writeFile(temp, formatJsonState(value), 'utf8');
117
+ await rename(temp, filePath);
118
+ }
119
+ function validId(value) {
120
+ return Boolean(typeof value === 'string' && value &&
121
+ value.split('-').every((part) => part && /^[A-Za-z0-9_]+$/u.test(part)));
122
+ }
123
+ function validateInstalledState(state) {
124
+ const legacy = state?.schemaVersion === 1;
125
+ const current = state?.schemaVersion === STATE_SCHEMA_VERSION;
126
+ if ((!legacy && !current) || !state.installed || Array.isArray(state.installed) || typeof state.installed !== 'object') {
127
+ throw new Error('Invalid .spd/installed.json state');
128
+ }
129
+ if (current && (!Array.isArray(state.requested) || state.requested.some((id) => !validId(id) || !state.installed[id]))) {
130
+ throw new Error('Invalid .spd/installed.json requested roots');
131
+ }
132
+ return state;
133
+ }
134
+ function validateChecksState(state) {
135
+ const legacy = state?.schemaVersion === 1;
136
+ const current = state?.schemaVersion === CHECKS_SCHEMA_VERSION;
137
+ if ((!legacy && !current) || !state.results || Array.isArray(state.results) || typeof state.results !== 'object') {
138
+ throw new Error('Invalid .spd/state.json state');
139
+ }
140
+ if (legacy && state.checkedAt !== null && typeof state.checkedAt !== 'string') {
141
+ throw new Error('Invalid .spd/state.json checkedAt');
142
+ }
143
+ return state;
144
+ }
145
+ export async function readInstalledState(projectRoot) {
146
+ await ensureMetadataNamespace(projectRoot);
147
+ const state = await readJsonOrDefault(join(projectRoot, INSTALLED_RELATIVE_PATH), EMPTY_INSTALLED);
148
+ return validateInstalledState(state);
149
+ }
150
+ export async function writeInstalledState(projectRoot, state) {
151
+ await ensureMetadataNamespace(projectRoot);
152
+ validateInstalledState(state);
153
+ if (state.schemaVersion !== STATE_SCHEMA_VERSION)
154
+ throw new Error('Cannot write legacy .spd/installed.json state');
155
+ await writeJsonAtomic(join(projectRoot, INSTALLED_RELATIVE_PATH), state);
156
+ }
157
+ export async function readChecksState(projectRoot) {
158
+ await ensureMetadataNamespace(projectRoot);
159
+ const statePath = join(projectRoot, STATE_RELATIVE_PATH);
160
+ let state;
161
+ try {
162
+ state = JSON.parse(await readFile(statePath, 'utf8'));
163
+ }
164
+ catch (error) {
165
+ if (error.code !== 'ENOENT')
166
+ throw error;
167
+ state = await readJsonOrDefault(join(projectRoot, LEGACY_CHECKS_RELATIVE_PATH), EMPTY_CHECKS);
168
+ }
169
+ return validateChecksState(state);
170
+ }
171
+ export async function writeChecksState(projectRoot, state) {
172
+ await ensureMetadataNamespace(projectRoot);
173
+ validateChecksState(state);
174
+ if (state.schemaVersion !== CHECKS_SCHEMA_VERSION)
175
+ throw new Error('Cannot write legacy .spd/state.json state');
176
+ const current = await readJsonOrDefault(join(projectRoot, STATE_RELATIVE_PATH), { schemaVersion: CHECKS_SCHEMA_VERSION });
177
+ await writeJsonAtomic(join(projectRoot, STATE_RELATIVE_PATH), {
178
+ ...current,
179
+ ...state,
180
+ schemaVersion: CHECKS_SCHEMA_VERSION,
181
+ });
182
+ }
package/package.json CHANGED
@@ -1,16 +1,15 @@
1
1
  {
2
2
  "name": "@specdest/devkit",
3
- "version": "0.4.6",
3
+ "version": "0.4.8",
4
4
  "type": "module",
5
5
  "bin": {
6
- "specdest": "src/cli.js"
6
+ "specdest": "dist/npm/cli.js"
7
7
  },
8
8
  "exports": {
9
- ".": "./src/index.js",
10
- "./cli": "./src/cli.js"
9
+ ".": "./dist/npm/index.js"
11
10
  },
12
11
  "files": [
13
- "src"
12
+ "dist/npm"
14
13
  ],
15
14
  "engines": {
16
15
  "node": ">=24.0.0",
@@ -22,19 +21,23 @@
22
21
  },
23
22
  "scripts": {
24
23
  "test": "node --test test/*.test.js",
24
+ "test:acceptance": "node scripts/fresh-project-acceptance.mjs",
25
25
  "lint": "node scripts/validate-js.mjs",
26
26
  "check": "pnpm run lint && pnpm run rules:validate && pnpm run rules:audit && pnpm run typecheck && pnpm run test",
27
27
  "rules:validate": "node scripts/validate-rule-authoring.mjs",
28
28
  "catalog:snapshot": "node scripts/export-catalog-snapshot.mjs",
29
29
  "release:preflight": "node scripts/release-preflight.mjs",
30
30
  "smoke:published": "node scripts/smoke-published-package.mjs",
31
- "typecheck": "node scripts/typecheck-checkers.mjs",
31
+ "typecheck": "tsc --noEmit -p tsconfig.json && pnpm run typecheck:checkers",
32
32
  "release:build": "node scripts/build-release-artifacts.mjs",
33
33
  "smoke:artifact": "node scripts/smoke-package-artifact.mjs",
34
34
  "runtime:build": "node scripts/build-remote-runtime.mjs",
35
35
  "catalog:git": "node scripts/export-git-catalog.mjs",
36
36
  "rules:audit": "node scripts/generate-rule-audit.mjs --check",
37
- "rules:audit:write": "node scripts/generate-rule-audit.mjs"
37
+ "rules:audit:write": "node scripts/generate-rule-audit.mjs",
38
+ "typecheck:checkers": "node scripts/typecheck-checkers.mjs",
39
+ "build": "node -e \"require('node:fs').rmSync('dist/npm',{recursive:true,force:true})\" && tsc -p tsconfig.build.json",
40
+ "prepack": "pnpm run build"
38
41
  },
39
42
  "devDependencies": {
40
43
  "@types/node": "^24.0.0",