@specdest/devkit 0.4.6 → 0.4.9

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 (131) hide show
  1. package/README.md +52 -20
  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 +21 -0
  5. package/dist/npm/canonical-project.js +115 -0
  6. package/dist/npm/canonical-source.d.ts +26 -0
  7. package/dist/npm/canonical-source.js +248 -0
  8. package/dist/npm/catalog-snapshot.d.ts +53 -0
  9. package/dist/npm/catalog-snapshot.js +35 -0
  10. package/dist/npm/cli.d.ts +2 -0
  11. package/dist/npm/cli.js +18 -0
  12. package/dist/npm/commands.d.ts +15 -0
  13. package/dist/npm/commands.js +182 -0
  14. package/dist/npm/flow.d.ts +48 -0
  15. package/dist/npm/flow.js +430 -0
  16. package/dist/npm/git-catalog.d.ts +40 -0
  17. package/dist/npm/git-catalog.js +222 -0
  18. package/dist/npm/index.d.ts +4 -0
  19. package/dist/npm/index.js +32 -0
  20. package/dist/npm/installer-primitives.d.ts +3 -0
  21. package/dist/npm/installer-primitives.js +50 -0
  22. package/dist/npm/predefined-packages/abac.d.ts +2 -0
  23. package/dist/npm/predefined-packages/abac.js +22 -0
  24. package/dist/npm/predefined-packages/auth.d.ts +2 -0
  25. package/dist/npm/predefined-packages/auth.js +21 -0
  26. package/dist/npm/predefined-packages/convex.d.ts +2 -0
  27. package/dist/npm/predefined-packages/convex.js +53 -0
  28. package/dist/npm/predefined-packages/expo.d.ts +2 -0
  29. package/dist/npm/predefined-packages/expo.js +88 -0
  30. package/dist/npm/predefined-packages/firebase-hosting.d.ts +2 -0
  31. package/dist/npm/predefined-packages/firebase-hosting.js +24 -0
  32. package/dist/npm/predefined-packages/health.d.ts +10 -0
  33. package/dist/npm/predefined-packages/health.js +52 -0
  34. package/dist/npm/predefined-packages/husky.d.ts +2 -0
  35. package/dist/npm/predefined-packages/husky.js +57 -0
  36. package/dist/npm/predefined-packages/index.d.ts +12 -0
  37. package/dist/npm/predefined-packages/index.js +97 -0
  38. package/dist/npm/predefined-packages/install.d.ts +19 -0
  39. package/dist/npm/predefined-packages/install.js +86 -0
  40. package/dist/npm/predefined-packages/local-logging.d.ts +2 -0
  41. package/dist/npm/predefined-packages/local-logging.js +17 -0
  42. package/dist/npm/predefined-packages/logging.d.ts +2 -0
  43. package/dist/npm/predefined-packages/logging.js +21 -0
  44. package/dist/npm/predefined-packages/multi-tenancy.d.ts +2 -0
  45. package/dist/npm/predefined-packages/multi-tenancy.js +21 -0
  46. package/dist/npm/predefined-packages/nps.d.ts +2 -0
  47. package/dist/npm/predefined-packages/nps.js +32 -0
  48. package/dist/npm/predefined-packages/oxfmt.d.ts +2 -0
  49. package/dist/npm/predefined-packages/oxfmt.js +22 -0
  50. package/dist/npm/predefined-packages/oxlint.d.ts +2 -0
  51. package/dist/npm/predefined-packages/oxlint.js +35 -0
  52. package/dist/npm/predefined-packages/package-json.d.ts +3 -0
  53. package/dist/npm/predefined-packages/package-json.js +61 -0
  54. package/dist/npm/predefined-packages/payments.d.ts +2 -0
  55. package/dist/npm/predefined-packages/payments.js +31 -0
  56. package/dist/npm/predefined-packages/playwright.d.ts +2 -0
  57. package/dist/npm/predefined-packages/playwright.js +35 -0
  58. package/dist/npm/predefined-packages/project-signals.d.ts +4 -0
  59. package/dist/npm/predefined-packages/project-signals.js +39 -0
  60. package/dist/npm/predefined-packages/registry.d.ts +3 -0
  61. package/dist/npm/predefined-packages/registry.js +63 -0
  62. package/dist/npm/predefined-packages/resolver.d.ts +8 -0
  63. package/dist/npm/predefined-packages/resolver.js +35 -0
  64. package/dist/npm/predefined-packages/sentry.d.ts +2 -0
  65. package/dist/npm/predefined-packages/sentry.js +29 -0
  66. package/dist/npm/predefined-packages/shadcn.d.ts +2 -0
  67. package/dist/npm/predefined-packages/shadcn.js +23 -0
  68. package/dist/npm/predefined-packages/storybook.d.ts +2 -0
  69. package/dist/npm/predefined-packages/storybook.js +25 -0
  70. package/dist/npm/predefined-packages/stryker.d.ts +2 -0
  71. package/dist/npm/predefined-packages/stryker.js +48 -0
  72. package/dist/npm/predefined-packages/supabase.d.ts +2 -0
  73. package/dist/npm/predefined-packages/supabase.js +335 -0
  74. package/dist/npm/predefined-packages/tailwind.d.ts +2 -0
  75. package/dist/npm/predefined-packages/tailwind.js +18 -0
  76. package/dist/npm/predefined-packages/tanstack-form.d.ts +2 -0
  77. package/dist/npm/predefined-packages/tanstack-form.js +19 -0
  78. package/dist/npm/predefined-packages/tanstack-query.d.ts +2 -0
  79. package/dist/npm/predefined-packages/tanstack-query.js +15 -0
  80. package/dist/npm/predefined-packages/tanstack-router.d.ts +2 -0
  81. package/dist/npm/predefined-packages/tanstack-router.js +18 -0
  82. package/dist/npm/predefined-packages/types.d.ts +38 -0
  83. package/dist/npm/predefined-packages/types.js +1 -0
  84. package/dist/npm/predefined-packages/vite.d.ts +2 -0
  85. package/dist/npm/predefined-packages/vite.js +127 -0
  86. package/dist/npm/predefined-packages/vitest.d.ts +2 -0
  87. package/dist/npm/predefined-packages/vitest.js +20 -0
  88. package/dist/npm/predefined-packages/zod.d.ts +2 -0
  89. package/dist/npm/predefined-packages/zod.js +18 -0
  90. package/dist/npm/project-check.d.ts +14 -0
  91. package/dist/npm/project-check.js +118 -0
  92. package/dist/npm/project-context.d.ts +52 -0
  93. package/dist/npm/project-context.js +206 -0
  94. package/dist/npm/project-rules.d.ts +25 -0
  95. package/dist/npm/project-rules.js +75 -0
  96. package/dist/npm/project-runtime.d.ts +21 -0
  97. package/dist/npm/project-runtime.js +41 -0
  98. package/dist/npm/project-status.d.ts +32 -0
  99. package/dist/npm/project-status.js +70 -0
  100. package/dist/npm/project-sync.d.ts +7 -0
  101. package/dist/npm/project-sync.js +143 -0
  102. package/dist/npm/remote-installer.d.ts +35 -0
  103. package/dist/npm/remote-installer.js +351 -0
  104. package/dist/npm/rule-id-migrations.d.ts +6 -0
  105. package/dist/npm/rule-id-migrations.js +19 -0
  106. package/dist/npm/schemas.d.ts +64 -0
  107. package/dist/npm/schemas.js +194 -0
  108. package/dist/npm/slack.d.ts +16 -0
  109. package/dist/npm/slack.js +131 -0
  110. package/dist/npm/state.d.ts +14 -0
  111. package/dist/npm/state.js +231 -0
  112. package/dist/npm/supabase-local.d.ts +2 -0
  113. package/dist/npm/supabase-local.js +62 -0
  114. package/package.json +18 -12
  115. package/src/canonical-project-operations.js +0 -438
  116. package/src/canonical-project.js +0 -136
  117. package/src/canonical-source.js +0 -250
  118. package/src/catalog-snapshot.js +0 -39
  119. package/src/catalog.js +0 -117
  120. package/src/cli.js +0 -14
  121. package/src/fuzz.js +0 -291
  122. package/src/git-catalog.js +0 -177
  123. package/src/index.js +0 -36
  124. package/src/installer-primitives.js +0 -198
  125. package/src/project-operations.js +0 -189
  126. package/src/project-targeting.js +0 -48
  127. package/src/remote-installer.js +0 -479
  128. package/src/rule-profile.js +0 -61
  129. package/src/setup-requirements.js +0 -82
  130. package/src/shared-file.js +0 -131
  131. package/src/sync-core.js +0 -390
@@ -0,0 +1,40 @@
1
+ type ProjectProfiles = Record<string, {
2
+ ruleIds: string[];
3
+ }>;
4
+ type GitCatalogEntry = {
5
+ id: string;
6
+ kind: 'rule' | 'module';
7
+ version: string;
8
+ name: string;
9
+ content: string;
10
+ order: number;
11
+ source: string;
12
+ revision: string;
13
+ contentHash: string;
14
+ summary?: string;
15
+ category?: string;
16
+ scope?: string;
17
+ labels?: string[];
18
+ enforcement?: string;
19
+ legacyInstalledIds?: string[];
20
+ applicableStacks?: string[];
21
+ requiredPackages?: string[];
22
+ requiredCapabilities?: string[];
23
+ composedOf?: string[];
24
+ notApplicableRuleIds?: string[];
25
+ projectProfiles?: ProjectProfiles;
26
+ ai?: unknown;
27
+ verification?: unknown;
28
+ };
29
+ export declare function buildGitCatalog({ modulesRoot, repositoryRevision, }: {
30
+ modulesRoot: string;
31
+ repositoryRevision?: string;
32
+ }): Promise<{
33
+ schemaVersion: number;
34
+ package: {
35
+ name: string;
36
+ version: string;
37
+ };
38
+ entries: GitCatalogEntry[];
39
+ }>;
40
+ export {};
@@ -0,0 +1,222 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readdir, readFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { CanonicalManifestSchema, parseWithSchema } from "./schemas.js";
5
+ const sha256 = (value) => createHash('sha256').update(value).digest('hex');
6
+ const legacyImplementationFamilies = new Map([
7
+ ['abac-permissions-supabase', ['abac-permissions-convex', 'abac-permissions-supabase']],
8
+ [
9
+ 'layers-and-contracts',
10
+ ['layers-and-contracts', 'layers-and-contracts-convex', 'layers-and-contracts-supabase'],
11
+ ],
12
+ ['unit-test-rules', ['unit-test-rules', 'unit-test-rules-convex', 'unit-test-rules-supabase']],
13
+ [
14
+ 'unit-test-rules-supabase',
15
+ ['unit-test-rules', 'unit-test-rules-convex', 'unit-test-rules-supabase'],
16
+ ],
17
+ ]);
18
+ function legacyImplementationIds(manifest) {
19
+ const implementation = manifest.checker?.implementation;
20
+ if (!implementation || implementation === manifest.id)
21
+ return [];
22
+ return legacyImplementationFamilies.get(implementation) ?? [implementation];
23
+ }
24
+ async function moduleFiles(root) {
25
+ const files = [];
26
+ const walk = async (dir, prefix = '') => {
27
+ for (const entry of (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
28
+ const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
29
+ if (entry.isDirectory())
30
+ await walk(join(dir, entry.name), relative);
31
+ else if (entry.isFile())
32
+ files.push({ path: relative, content: await readFile(join(dir, entry.name), 'utf8') });
33
+ }
34
+ };
35
+ await walk(root);
36
+ return files.sort((a, b) => a.path.localeCompare(b.path));
37
+ }
38
+ function title(content, id) {
39
+ return content.match(/^#\s+(.+)$/mu)?.[1]?.trim() || id;
40
+ }
41
+ function summary(content, fallback) {
42
+ const normalized = String(content ?? '').replace(/\r\n?/gu, '\n');
43
+ const intent = normalized.match(/(?:^|\n)## Intent\s*\n+([^#][\s\S]*?)(?=\n## |$)/u)?.[1]?.trim();
44
+ const source = intent ||
45
+ normalized
46
+ .split('\n')
47
+ .map((line) => line.trim())
48
+ .find((line) => line && !line.startsWith('#')) ||
49
+ fallback;
50
+ return source
51
+ .replace(/^\*\*Rule:\*\*\s*/u, '')
52
+ .replace(/\s+/gu, ' ')
53
+ .slice(0, 240)
54
+ .trim();
55
+ }
56
+ function canonicalVersion(manifest) {
57
+ const version = String(manifest.version ?? '');
58
+ if (!/^\d+\.\d+\.\d+$/u.test(version)) {
59
+ throw new Error(`Canonical catalog entry requires SemVer version: ${manifest.id}`);
60
+ }
61
+ return version;
62
+ }
63
+ function catalogKind(manifest) {
64
+ const kind = manifest.kind ?? 'rule';
65
+ if (!['rule', 'module'].includes(kind))
66
+ throw new Error(`Invalid canonical kind: ${manifest.id}`);
67
+ return kind;
68
+ }
69
+ function notApplicableRuleIds(manifest) {
70
+ if (!Array.isArray(manifest.notApplicableRuleIds))
71
+ return undefined;
72
+ return [...new Set(manifest.notApplicableRuleIds.map(String))].sort();
73
+ }
74
+ function projectProfiles(manifest) {
75
+ if (!manifest.projectProfiles)
76
+ return undefined;
77
+ if (typeof manifest.projectProfiles !== 'object' || Array.isArray(manifest.projectProfiles)) {
78
+ throw new Error(`Invalid projectProfiles: ${manifest.id}`);
79
+ }
80
+ return Object.fromEntries(Object.entries(manifest.projectProfiles)
81
+ .sort(([a], [b]) => a.localeCompare(b))
82
+ .map(([name, definition]) => {
83
+ if (!definition || !Array.isArray(definition.ruleIds) || definition.ruleIds.length === 0) {
84
+ throw new Error(`Invalid project profile: ${manifest.id}:${name}`);
85
+ }
86
+ return [name, { ruleIds: [...new Set(definition.ruleIds.map(String))].sort() }];
87
+ }));
88
+ }
89
+ function stringList(value) {
90
+ if (!Array.isArray(value) || value.length === 0)
91
+ return undefined;
92
+ return [
93
+ ...new Set(value
94
+ .map(String)
95
+ .map((item) => item.trim())
96
+ .filter(Boolean)),
97
+ ].sort();
98
+ }
99
+ function applicableStacks(manifest) {
100
+ if (!Array.isArray(manifest.applicableStacks) || manifest.applicableStacks.length === 0)
101
+ return undefined;
102
+ return [...new Set(manifest.applicableStacks.map(String))].sort();
103
+ }
104
+ function requiredPackages(manifest) {
105
+ return stringList(manifest.requiredPackages);
106
+ }
107
+ function validateRuleApplicability(manifest) {
108
+ if (manifest.scope !== 'Stack-specific')
109
+ return;
110
+ if (!applicableStacks(manifest) && !requiredPackages(manifest)) {
111
+ throw new Error(`Stack-specific rule requires applicableStacks or requiredPackages: ${manifest.id}`);
112
+ }
113
+ }
114
+ export async function buildGitCatalog({ modulesRoot, repositoryRevision = 'working-tree', }) {
115
+ const directories = (await readdir(modulesRoot, { withFileTypes: true }))
116
+ .filter((entry) => entry.isDirectory())
117
+ .sort((a, b) => a.name.localeCompare(b.name));
118
+ const modules = [];
119
+ for (const directory of directories) {
120
+ const root = join(modulesRoot, directory.name);
121
+ const files = await moduleFiles(root);
122
+ const manifestFile = files.find((file) => file.path === 'manifest.json');
123
+ if (!manifestFile)
124
+ throw new Error(`Missing manifest.json: ${directory.name}`);
125
+ const manifest = parseWithSchema(CanonicalManifestSchema, JSON.parse(manifestFile.content), `canonical manifest ${directory.name}`);
126
+ if (manifest.id !== directory.name)
127
+ throw new Error(`Module id/path mismatch: ${directory.name}`);
128
+ modules.push({ files, manifest, ownContentHash: sha256(JSON.stringify(files)) });
129
+ }
130
+ const canonicalCheckHash = modules.find(({ manifest }) => manifest.id === 'canonical-check')?.ownContentHash ?? null;
131
+ const entries = [];
132
+ for (const { files, manifest, ownContentHash } of modules) {
133
+ const contentHash = manifest.checker?.path && canonicalCheckHash
134
+ ? sha256(JSON.stringify({ ownContentHash, canonicalCheckHash }))
135
+ : ownContentHash;
136
+ const guidance = files.find((file) => /(^|\/)rule\.md$/u.test(file.path) || /(^|\/)SKILL\.md$/u.test(file.path))?.content ?? '';
137
+ const kind = catalogKind(manifest);
138
+ if (kind === 'rule')
139
+ validateRuleApplicability(manifest);
140
+ entries.push({
141
+ id: manifest.id,
142
+ kind,
143
+ version: canonicalVersion(manifest),
144
+ name: title(guidance, manifest.id),
145
+ content: guidance,
146
+ ...(kind === 'rule' ? { summary: summary(guidance, manifest.name ?? manifest.id) } : {}),
147
+ ...(kind === 'rule' && manifest.category ? { category: String(manifest.category) } : {}),
148
+ ...(kind === 'rule' && manifest.scope ? { scope: String(manifest.scope) } : {}),
149
+ ...(kind === 'rule' && stringList(manifest.labels)
150
+ ? { labels: stringList(manifest.labels) }
151
+ : {}),
152
+ order: entries.length + 1,
153
+ source: 'private-devkit-git',
154
+ revision: repositoryRevision,
155
+ contentHash,
156
+ ...(kind === 'rule' ? { legacyInstalledIds: legacyImplementationIds(manifest) } : {}),
157
+ ...(kind === 'rule' ? { enforcement: String(manifest.enforcement ?? 'guidance') } : {}),
158
+ ...(kind === 'rule' && applicableStacks(manifest)
159
+ ? { applicableStacks: applicableStacks(manifest) }
160
+ : {}),
161
+ ...(kind === 'rule' && requiredPackages(manifest)
162
+ ? { requiredPackages: requiredPackages(manifest) }
163
+ : {}),
164
+ ...(kind === 'rule' && stringList(manifest.requiredCapabilities)
165
+ ? { requiredCapabilities: stringList(manifest.requiredCapabilities) }
166
+ : {}),
167
+ ...(kind === 'rule' && manifest.ai ? { ai: manifest.ai } : {}),
168
+ ...(kind === 'rule' && manifest.verification ? { verification: manifest.verification } : {}),
169
+ ...(kind === 'rule' && stringList(manifest.composedOf)
170
+ ? { composedOf: stringList(manifest.composedOf) }
171
+ : {}),
172
+ ...(kind === 'module' && notApplicableRuleIds(manifest)
173
+ ? { notApplicableRuleIds: notApplicableRuleIds(manifest) }
174
+ : {}),
175
+ ...(kind === 'module' && projectProfiles(manifest)
176
+ ? { projectProfiles: projectProfiles(manifest) }
177
+ : {}),
178
+ });
179
+ }
180
+ const ruleIds = new Set(entries.filter((entry) => entry.kind === 'rule').map((entry) => entry.id));
181
+ for (const entry of entries) {
182
+ for (const ruleId of entry.notApplicableRuleIds ?? []) {
183
+ if (!ruleIds.has(ruleId))
184
+ throw new Error(`Unknown not-applicable rule: ${entry.id}:${ruleId}`);
185
+ }
186
+ for (const [profileName, definition] of Object.entries(entry.projectProfiles ?? {})) {
187
+ for (const ruleId of definition.ruleIds) {
188
+ if (!ruleIds.has(ruleId))
189
+ throw new Error(`Unknown project-profile rule: ${entry.id}:${profileName}:${ruleId}`);
190
+ }
191
+ }
192
+ for (const childId of entry.composedOf ?? []) {
193
+ if (!ruleIds.has(childId))
194
+ throw new Error(`Unknown composed rule: ${entry.id}:${childId}`);
195
+ if (childId === entry.id)
196
+ throw new Error(`Rule cannot compose itself: ${entry.id}`);
197
+ }
198
+ }
199
+ const composition = new Map(entries
200
+ .filter((entry) => entry.kind === 'rule')
201
+ .map((entry) => [entry.id, entry.composedOf ?? []]));
202
+ const visiting = new Set();
203
+ const visited = new Set();
204
+ const visit = (id) => {
205
+ if (visiting.has(id))
206
+ throw new Error(`Rule composition cycle: ${id}`);
207
+ if (visited.has(id))
208
+ return;
209
+ visiting.add(id);
210
+ for (const childId of composition.get(id) ?? [])
211
+ visit(childId);
212
+ visiting.delete(id);
213
+ visited.add(id);
214
+ };
215
+ for (const id of composition.keys())
216
+ visit(id);
217
+ return {
218
+ schemaVersion: 1,
219
+ package: { name: '@specdest/devkit', version: repositoryRevision },
220
+ entries,
221
+ };
222
+ }
@@ -0,0 +1,4 @@
1
+ export { createCanonicalSource } from './canonical-source.ts';
2
+ export { createFlowCommandHandler } from './flow.ts';
3
+ export declare const COMMAND_NAMES: string[];
4
+ export declare function runCli(argv: any, io?: any, handlers?: any): Promise<any>;
@@ -0,0 +1,32 @@
1
+ export { createCanonicalSource } from "./canonical-source.js";
2
+ export { createFlowCommandHandler } from "./flow.js";
3
+ export const COMMAND_NAMES = [
4
+ 'status',
5
+ 'add',
6
+ 'sync',
7
+ 'check',
8
+ 'rules',
9
+ 'ai-instruction',
10
+ 'doctor',
11
+ 'flow',
12
+ 'supabase',
13
+ 'slack',
14
+ ];
15
+ const HELP = `Usage: specdest <command> [options]\n\nCommands:\n status [--refresh] [--json] Show canonical applicability/install status\n add <package> Adopt/install a predefined package\n sync Refresh catalog/cache and install/update applicable rules\n check [--refresh] [--json] [--details] [--staged | --files <path...>] Run canonical checks, optionally targeted\n rules [options] Load applicable rule guidance for AI/task context\n ai-instruction Print the minimal AI bootstrap instruction\n doctor Diagnose project/cache setup\n flow <command> Manage local resumable development flow state\n supabase <status|start|stop> Local Supabase through restricted Controller\n slack send <files...> Upload files to configured Slack channel\n`;
16
+ export async function runCli(argv, io = process, handlers = {}) {
17
+ const [command, ...args] = argv;
18
+ if (!command || command === 'help' || command === '--help' || command === '-h') {
19
+ io.stdout.write(HELP);
20
+ return 0;
21
+ }
22
+ if (!COMMAND_NAMES.includes(command)) {
23
+ io.stderr.write(`Unknown command: ${command}\n\n${HELP}`);
24
+ return 2;
25
+ }
26
+ const handler = handlers[command];
27
+ if (!handler) {
28
+ io.stderr.write(`specdest ${command} is not implemented yet.\n`);
29
+ return 2;
30
+ }
31
+ return await handler(args, io);
32
+ }
@@ -0,0 +1,3 @@
1
+ export declare function resolveProjectPath(projectRoot: string, relativePath: string): string;
2
+ export declare function upsertMarkdownSection(existing: string, heading: string, body: string): string;
3
+ export declare function removeMarkdownSection(existing: string, heading: string): string;
@@ -0,0 +1,50 @@
1
+ import { isAbsolute, resolve, sep } from 'node:path';
2
+ export function resolveProjectPath(projectRoot, relativePath) {
3
+ if (!relativePath || isAbsolute(relativePath)) {
4
+ throw new Error(`Path must be project-relative: ${relativePath}`);
5
+ }
6
+ const root = resolve(projectRoot);
7
+ const target = resolve(root, relativePath);
8
+ if (target !== root && !target.startsWith(`${root}${sep}`)) {
9
+ throw new Error(`Path escapes project: ${relativePath}`);
10
+ }
11
+ return target;
12
+ }
13
+ function markdownSectionBounds(existing, heading) {
14
+ const trimmed = heading.trim();
15
+ const level = trimmed.match(/^(#{1,6})\s+/)?.[1].length ?? 2;
16
+ const lines = existing.split(/(?<=\n)/);
17
+ let offset = 0;
18
+ let start = -1;
19
+ let end = existing.length;
20
+ for (const line of lines) {
21
+ if (start < 0 && line.trim() === trimmed)
22
+ start = offset;
23
+ else if (start >= 0 && new RegExp(`^#{1,${level}}\\s+`).test(line.trim())) {
24
+ end = offset;
25
+ break;
26
+ }
27
+ offset += line.length;
28
+ }
29
+ return start >= 0 ? [start, end] : null;
30
+ }
31
+ export function upsertMarkdownSection(existing, heading, body) {
32
+ const block = `${heading.trim()}\n\n${body.trim()}\n`;
33
+ const bounds = markdownSectionBounds(existing, heading);
34
+ if (!bounds)
35
+ return `${existing.trimEnd()}${existing.trim() ? '\n\n' : ''}${block}`;
36
+ const [start, end] = bounds;
37
+ const before = existing.slice(0, start).trimEnd();
38
+ const after = existing.slice(end).trim();
39
+ return `${[before, block.trimEnd(), after].filter(Boolean).join('\n\n')}\n`;
40
+ }
41
+ export function removeMarkdownSection(existing, heading) {
42
+ const bounds = markdownSectionBounds(existing, heading);
43
+ if (!bounds)
44
+ return existing;
45
+ const [start, end] = bounds;
46
+ const updated = `${existing.slice(0, start).trimEnd()}\n\n${existing.slice(end).trimStart()}`
47
+ .replace(/\n{3,}/g, '\n\n')
48
+ .trimEnd();
49
+ return updated ? `${updated}\n` : '';
50
+ }
@@ -0,0 +1,2 @@
1
+ import type { PackageRecipe } from './types.ts';
2
+ export declare const abacRecipe: PackageRecipe;
@@ -0,0 +1,22 @@
1
+ import { detectAnyPath } from "./project-signals.js";
2
+ export const abacRecipe = {
3
+ id: 'abac',
4
+ recipeVersion: '1.0.0',
5
+ role: 'feature',
6
+ requires: ['auth'],
7
+ variants: [
8
+ { id: 'supabase', when: ['supabase'] },
9
+ { id: 'convex', when: ['convex'] },
10
+ ],
11
+ async detect(projectRoot) {
12
+ return await detectAnyPath(projectRoot, ['src/lib/permissions.ts', 'src/permissions', 'src/policies', 'src/features/permissions'], 'ABAC policy integration was not detected');
13
+ },
14
+ async apply(_projectRoot, detection, _resolution) {
15
+ if (!detection.present) {
16
+ throw new Error('ABAC is not implemented in this project; creating ABAC policy code is not supported by `add abac` yet.');
17
+ }
18
+ if (!detection.compatible)
19
+ throw new Error(detection.reason ?? 'Existing ABAC integration is not compatible.');
20
+ return { source: 'adopted' };
21
+ },
22
+ };
@@ -0,0 +1,2 @@
1
+ import type { PackageRecipe } from './types.ts';
2
+ export declare const authRecipe: PackageRecipe;
@@ -0,0 +1,21 @@
1
+ import { detectAnyPath } from "./project-signals.js";
2
+ export const authRecipe = {
3
+ id: 'auth',
4
+ recipeVersion: '1.0.0',
5
+ role: 'feature',
6
+ variants: [
7
+ { id: 'supabase', when: ['supabase'] },
8
+ { id: 'convex', when: ['convex'] },
9
+ ],
10
+ async detect(projectRoot) {
11
+ return await detectAnyPath(projectRoot, ['src/application/auth', 'src/auth', 'app/auth', 'convex/auth.ts', 'convex/auth.config.ts'], 'authentication integration was not detected');
12
+ },
13
+ async apply(_projectRoot, detection, _resolution) {
14
+ if (!detection.present) {
15
+ throw new Error('Auth is not implemented in this project; creating auth is not supported by `add auth` yet.');
16
+ }
17
+ if (!detection.compatible)
18
+ throw new Error(detection.reason ?? 'Existing auth integration is not compatible.');
19
+ return { source: 'adopted' };
20
+ },
21
+ };
@@ -0,0 +1,2 @@
1
+ import type { PackageRecipe } from './types.ts';
2
+ export declare const convexRecipe: PackageRecipe;
@@ -0,0 +1,53 @@
1
+ import { ensurePnpmBuildPolicy, mergeMissing, projectPackageName, updatePackageJson, writeProjectFileIfMissing } from "./install.js";
2
+ import { detectDependency } from "./package-json.js";
3
+ async function installConvex(projectRoot, context) {
4
+ await updatePackageJson(projectRoot, (pkg) => ({
5
+ ...pkg,
6
+ name: pkg.name ?? projectPackageName(projectRoot),
7
+ private: pkg.private ?? true,
8
+ packageManager: pkg.packageManager ?? 'pnpm@11.6.0',
9
+ engines: {
10
+ ...pkg.engines,
11
+ node: pkg.engines?.node ?? '>=24.0.0',
12
+ pnpm: pkg.engines?.pnpm ?? '>=11.0.0',
13
+ },
14
+ scripts: mergeMissing(pkg.scripts, {
15
+ 'convex:dev': 'convex dev',
16
+ 'convex:codegen': 'convex codegen --typecheck=disable',
17
+ }),
18
+ dependencies: mergeMissing(pkg.dependencies, {
19
+ convex: '1.43.0',
20
+ }),
21
+ }));
22
+ await ensurePnpmBuildPolicy(projectRoot);
23
+ await writeProjectFileIfMissing(projectRoot, 'convex/schema.ts', `import { defineSchema } from 'convex/server';
24
+
25
+ export default defineSchema({});
26
+ `);
27
+ const expo = await detectDependency(projectRoot, 'expo', 'Expo');
28
+ if (expo.present) {
29
+ await writeProjectFileIfMissing(projectRoot, 'src/integrations/convex/config.ts', `export function convexConfig() {
30
+ return { url: process.env.EXPO_PUBLIC_CONVEX_URL ?? '' };
31
+ }
32
+ `);
33
+ }
34
+ await context.runCommand('pnpm', ['install', '--no-frozen-lockfile'], { cwd: projectRoot });
35
+ }
36
+ export const convexRecipe = {
37
+ id: 'convex',
38
+ recipeVersion: '1.1.1',
39
+ role: 'backend',
40
+ conflicts: ['supabase'],
41
+ async detect(projectRoot) {
42
+ return await detectDependency(projectRoot, 'convex', 'Convex');
43
+ },
44
+ async apply(projectRoot, detection, _resolution, context) {
45
+ if (detection.present) {
46
+ if (!detection.compatible)
47
+ throw new Error(detection.reason ?? 'Existing Convex setup is not compatible.');
48
+ return { source: 'adopted' };
49
+ }
50
+ await installConvex(projectRoot, context);
51
+ return { source: 'installed' };
52
+ },
53
+ };
@@ -0,0 +1,2 @@
1
+ import type { PackageRecipe } from './types.ts';
2
+ export declare const expoRecipe: PackageRecipe;
@@ -0,0 +1,88 @@
1
+ import { ensurePnpmBuildPolicy, mergeMissing, projectPackageName, updatePackageJson, writeProjectFileIfMissing } from "./install.js";
2
+ import { detectDependency } from "./package-json.js";
3
+ const dependencies = {
4
+ expo: '57.0.19',
5
+ react: '19.2.3',
6
+ 'react-dom': '19.2.3',
7
+ 'react-native': '0.86.3',
8
+ 'react-native-web': '0.21.2',
9
+ };
10
+ const devDependencies = {
11
+ '@types/react': '19.2.14',
12
+ typescript: '6.0.3',
13
+ };
14
+ async function installExpo(projectRoot, context) {
15
+ const pkg = await updatePackageJson(projectRoot, (current) => ({
16
+ ...current,
17
+ name: current.name ?? projectPackageName(projectRoot),
18
+ private: current.private ?? true,
19
+ main: current.main ?? 'index.ts',
20
+ packageManager: current.packageManager ?? 'pnpm@11.6.0',
21
+ engines: {
22
+ ...current.engines,
23
+ node: current.engines?.node ?? '>=24.0.0',
24
+ pnpm: current.engines?.pnpm ?? '>=11.0.0',
25
+ },
26
+ scripts: mergeMissing(current.scripts, {
27
+ start: 'expo start',
28
+ android: 'expo start --android',
29
+ ios: 'expo start --ios',
30
+ web: 'expo start --web',
31
+ typecheck: 'tsc --noEmit',
32
+ }),
33
+ dependencies: mergeMissing(current.dependencies, dependencies),
34
+ devDependencies: mergeMissing(current.devDependencies, devDependencies),
35
+ }));
36
+ const name = pkg.name;
37
+ await ensurePnpmBuildPolicy(projectRoot);
38
+ await writeProjectFileIfMissing(projectRoot, 'index.ts', `import { registerRootComponent } from 'expo';
39
+ import App from './App';
40
+
41
+ registerRootComponent(App);
42
+ `);
43
+ await writeProjectFileIfMissing(projectRoot, 'App.tsx', `import { SafeAreaView, Text } from 'react-native';
44
+
45
+ export default function App() {
46
+ return <SafeAreaView><Text>Specdest app</Text></SafeAreaView>;
47
+ }
48
+ `);
49
+ await writeProjectFileIfMissing(projectRoot, 'app.json', `${JSON.stringify({
50
+ expo: {
51
+ name,
52
+ slug: name,
53
+ version: '1.0.0',
54
+ orientation: 'portrait',
55
+ userInterfaceStyle: 'automatic',
56
+ },
57
+ }, null, 2)}\n`);
58
+ await writeProjectFileIfMissing(projectRoot, 'tsconfig.json', `{
59
+ "extends": "expo/tsconfig.base",
60
+ "compilerOptions": {
61
+ "strict": true
62
+ }
63
+ }
64
+ `);
65
+ await context.runCommand('pnpm', ['install', '--no-frozen-lockfile'], { cwd: projectRoot });
66
+ }
67
+ export const expoRecipe = {
68
+ id: 'expo',
69
+ recipeVersion: '1.2.0',
70
+ role: 'frontend',
71
+ setupRequirements: [
72
+ { kind: 'package', packageId: 'oxlint', required: true },
73
+ { kind: 'package', packageId: 'husky', required: true, when: 'git' },
74
+ ],
75
+ conflicts: ['vite'],
76
+ async detect(projectRoot) {
77
+ return await detectDependency(projectRoot, 'expo', 'Expo');
78
+ },
79
+ async apply(projectRoot, detection, _resolution, context) {
80
+ if (detection.present) {
81
+ if (!detection.compatible)
82
+ throw new Error(detection.reason ?? 'Existing Expo setup is not compatible.');
83
+ return { source: 'adopted' };
84
+ }
85
+ await installExpo(projectRoot, context);
86
+ return { source: 'installed' };
87
+ },
88
+ };
@@ -0,0 +1,2 @@
1
+ import type { PackageRecipe } from './types.ts';
2
+ export declare const firebaseHostingRecipe: PackageRecipe;
@@ -0,0 +1,24 @@
1
+ import { detectDependency } from "./package-json.js";
2
+ import { pathExists } from "./project-signals.js";
3
+ export const firebaseHostingRecipe = {
4
+ id: 'firebase-hosting',
5
+ recipeVersion: '1.0.0',
6
+ role: 'integration',
7
+ requires: ['vite'],
8
+ async detect(projectRoot) {
9
+ const [firebaseJson, firebaseRc, tools] = await Promise.all([
10
+ pathExists(projectRoot, 'firebase.json'),
11
+ pathExists(projectRoot, '.firebaserc'),
12
+ detectDependency(projectRoot, 'firebase-tools', 'firebase-tools'),
13
+ ]);
14
+ if (firebaseJson && firebaseRc) {
15
+ return { present: true, compatible: true, detectedVersion: tools.present ? tools.detectedVersion : null };
16
+ }
17
+ return { present: false, compatible: false, detectedVersion: null, reason: 'firebase.json and .firebaserc were not both found' };
18
+ },
19
+ async apply(_projectRoot, detection, _resolution) {
20
+ if (!detection.present)
21
+ throw new Error('Firebase Hosting configuration was not detected; creating Firebase Hosting configuration is not supported by `add firebase-hosting` yet.');
22
+ return { source: 'adopted' };
23
+ },
24
+ };
@@ -0,0 +1,10 @@
1
+ export declare function inspectPredefinedPackageState(projectRoot: string, state?: any): Promise<{
2
+ registered: string[];
3
+ present: string[];
4
+ issues: string[];
5
+ }>;
6
+ export declare function assertPredefinedPackageState(projectRoot: string): Promise<{
7
+ registered: string[];
8
+ present: string[];
9
+ issues: string[];
10
+ }>;
@@ -0,0 +1,52 @@
1
+ import { listPackageRecipes } from "./registry.js";
2
+ import { installedPackageIds, resolvePackageAddition } from "./resolver.js";
3
+ import { readInstalledState } from "../state.js";
4
+ export async function inspectPredefinedPackageState(projectRoot, state) {
5
+ const installedState = state ?? await readInstalledState(projectRoot);
6
+ const recipes = listPackageRecipes();
7
+ const byId = new Map(recipes.map((recipe) => [recipe.id, recipe]));
8
+ const detections = new Map(await Promise.all(recipes.map(async (recipe) => [recipe.id, await recipe.detect(projectRoot)])));
9
+ const registered = installedPackageIds(installedState);
10
+ const present = recipes.filter((recipe) => detections.get(recipe.id)?.present).map((recipe) => recipe.id);
11
+ const issues = [];
12
+ for (const id of registered) {
13
+ const recipe = byId.get(id);
14
+ if (!recipe) {
15
+ issues.push(`Unknown registered predefined package: ${id}`);
16
+ continue;
17
+ }
18
+ const detection = detections.get(id);
19
+ if (!detection?.present) {
20
+ issues.push(`${id} is registered but no longer detected in the project`);
21
+ continue;
22
+ }
23
+ if (!detection.compatible) {
24
+ issues.push(`${id}: ${detection.reason ?? 'detected package is not compatible'}`);
25
+ continue;
26
+ }
27
+ const registeredDependencies = registered.filter((candidate) => candidate !== id);
28
+ const presentEnvironment = present.filter((candidate) => candidate !== id);
29
+ try {
30
+ const resolution = resolvePackageAddition(recipe, {
31
+ registeredPackageIds: registeredDependencies,
32
+ presentPackageIds: presentEnvironment,
33
+ knownRecipes: recipes,
34
+ });
35
+ const recordedVariant = installedState.installed[id]?.resolvedVariant ?? null;
36
+ if (recordedVariant !== resolution.variant) {
37
+ issues.push(`${id} resolved variant changed from ${recordedVariant ?? 'none'} to ${resolution.variant ?? 'none'}`);
38
+ }
39
+ }
40
+ catch (error) {
41
+ issues.push(error.message);
42
+ }
43
+ }
44
+ return { registered, present, issues: [...new Set(issues)].sort() };
45
+ }
46
+ export async function assertPredefinedPackageState(projectRoot) {
47
+ const health = await inspectPredefinedPackageState(projectRoot);
48
+ if (health.issues.length) {
49
+ throw new Error(`Predefined package state is invalid:\n- ${health.issues.join('\n- ')}`);
50
+ }
51
+ return health;
52
+ }
@@ -0,0 +1,2 @@
1
+ import type { PackageRecipe } from './types.ts';
2
+ export declare const huskyRecipe: PackageRecipe;