@duct-sdk/sdk 0.5.12 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/CHANGELOG.md +385 -336
  2. package/README.md +418 -264
  3. package/TOKEN_SPEC.md +243 -237
  4. package/dist/cli/add.d.ts +7 -0
  5. package/dist/cli/add.js +152 -0
  6. package/dist/cli/agent-prompt.d.ts +3 -0
  7. package/dist/cli/agent-prompt.js +39 -0
  8. package/dist/cli/api-sources.d.ts +26 -0
  9. package/dist/cli/api-sources.js +222 -0
  10. package/dist/cli/cloud.d.ts +133 -0
  11. package/dist/cli/cloud.js +298 -0
  12. package/dist/cli/config-loader.d.ts +14 -0
  13. package/dist/cli/config-loader.js +56 -7
  14. package/dist/cli/device-login.d.ts +17 -0
  15. package/dist/cli/device-login.js +75 -0
  16. package/dist/cli/drift.js +6 -6
  17. package/dist/cli/generators/any-stack.d.ts +3 -0
  18. package/dist/cli/generators/any-stack.js +97 -0
  19. package/dist/cli/generators/config.js +3 -2
  20. package/dist/cli/generators/receiver.js +7 -7
  21. package/dist/cli/generators/shell.js +12 -12
  22. package/dist/cli/generators/token-route.js +245 -245
  23. package/dist/cli/index.js +402 -611
  24. package/dist/cli/mcp-core.d.ts +42 -0
  25. package/dist/cli/mcp-core.js +161 -0
  26. package/dist/cli/mcp-setup.d.ts +4 -0
  27. package/dist/cli/mcp-setup.js +360 -0
  28. package/dist/cli/mcp.d.ts +2 -0
  29. package/dist/cli/mcp.js +457 -0
  30. package/dist/cli/migrate-intershell.js +5 -5
  31. package/dist/cli/policy-defaults.d.ts +37 -0
  32. package/dist/cli/policy-defaults.js +127 -0
  33. package/dist/cli/processors/integration-audit.js +2 -2
  34. package/dist/cli/processors/openapi-parser.d.ts +5 -0
  35. package/dist/cli/processors/openapi-parser.js +8 -3
  36. package/dist/cli/project-loader.d.ts +58 -0
  37. package/dist/cli/project-loader.js +198 -0
  38. package/dist/cli/project-writer.d.ts +23 -0
  39. package/dist/cli/project-writer.js +171 -0
  40. package/dist/cli/push.d.ts +43 -0
  41. package/dist/cli/push.js +276 -0
  42. package/dist/cli/safety-checks.d.ts +9 -0
  43. package/dist/cli/safety-checks.js +29 -0
  44. package/dist/cli/setup.d.ts +20 -0
  45. package/dist/cli/setup.js +349 -0
  46. package/dist/cli/shell-name.d.ts +8 -0
  47. package/dist/cli/shell-name.js +29 -0
  48. package/dist/cli/shells.d.ts +22 -0
  49. package/dist/cli/shells.js +122 -0
  50. package/dist/cli/split.d.ts +7 -0
  51. package/dist/cli/split.js +71 -0
  52. package/dist/cli/sync.d.ts +25 -0
  53. package/dist/cli/sync.js +120 -0
  54. package/dist/cli/test-runner.d.ts +21 -0
  55. package/dist/cli/test-runner.js +281 -0
  56. package/dist/core/compile.d.ts +43 -0
  57. package/dist/core/compile.js +510 -0
  58. package/dist/core/config.d.ts +533 -1
  59. package/dist/core/config.js +32 -12
  60. package/dist/core/hosted-upstream-check.d.ts +3 -0
  61. package/dist/core/hosted-upstream-check.js +35 -0
  62. package/dist/core/login-handoff.d.ts +1 -1
  63. package/dist/core/login-handoff.js +1 -1
  64. package/dist/core/project.d.ts +1798 -0
  65. package/dist/core/project.js +278 -0
  66. package/dist/core/readiness-checks.js +2 -2
  67. package/dist/core/types.d.ts +26 -1
  68. package/dist/index.d.ts +6 -0
  69. package/dist/index.js +16 -0
  70. package/dist/project.d.ts +4 -0
  71. package/dist/project.js +8 -0
  72. package/dist/server.d.ts +2 -0
  73. package/dist/server.js +1 -0
  74. package/fixtures/token-conformance-vectors.json +26 -0
  75. package/package.json +94 -94
  76. package/dist/adapters/react/page-context-guard.test.d.ts +0 -1
  77. package/dist/adapters/react/page-context-guard.test.js +0 -15
  78. package/dist/cli/agents/api-agent.d.ts +0 -22
  79. package/dist/cli/agents/api-agent.js +0 -761
  80. package/dist/cli/agents/auth-agent.d.ts +0 -7
  81. package/dist/cli/agents/auth-agent.js +0 -212
  82. package/dist/cli/agents/deeplink-agent.d.ts +0 -6
  83. package/dist/cli/agents/deeplink-agent.js +0 -285
  84. package/dist/cli/agents/llm.d.ts +0 -33
  85. package/dist/cli/agents/llm.js +0 -309
  86. package/dist/cli/agents/pipeline.d.ts +0 -72
  87. package/dist/cli/agents/pipeline.js +0 -421
  88. package/dist/cli/agents/reviewer-agent.d.ts +0 -13
  89. package/dist/cli/agents/reviewer-agent.js +0 -450
  90. package/dist/cli/agents/route-agent.d.ts +0 -17
  91. package/dist/cli/agents/route-agent.js +0 -383
  92. package/dist/cli/config-loader.test.d.ts +0 -1
  93. package/dist/cli/config-loader.test.js +0 -63
  94. package/dist/cli/detectors/topology.d.ts +0 -46
  95. package/dist/cli/detectors/topology.js +0 -417
  96. package/dist/cli/generators/config.test.d.ts +0 -1
  97. package/dist/cli/generators/config.test.js +0 -222
  98. package/dist/cli/generators/shell.test.d.ts +0 -1
  99. package/dist/cli/generators/shell.test.js +0 -73
  100. package/dist/cli/generators/token-route.test.d.ts +0 -1
  101. package/dist/cli/generators/token-route.test.js +0 -53
  102. package/dist/cli/generators/wiring-snippets.test.d.ts +0 -1
  103. package/dist/cli/generators/wiring-snippets.test.js +0 -80
  104. package/dist/cli/init.d.ts +0 -32
  105. package/dist/cli/init.js +0 -1336
  106. package/dist/cli/manifest-diff.test.d.ts +0 -1
  107. package/dist/cli/manifest-diff.test.js +0 -144
  108. package/dist/cli/processors/curl-parser.test.d.ts +0 -1
  109. package/dist/cli/processors/curl-parser.test.js +0 -24
  110. package/dist/cli/processors/integration-audit.test.d.ts +0 -1
  111. package/dist/cli/processors/integration-audit.test.js +0 -154
  112. package/dist/cli/processors/postprocess.d.ts +0 -22
  113. package/dist/cli/processors/postprocess.js +0 -107
  114. package/dist/cli/processors/prisma-parser.d.ts +0 -35
  115. package/dist/cli/processors/prisma-parser.js +0 -117
  116. package/dist/cli/processors/verify-discovery.d.ts +0 -33
  117. package/dist/cli/processors/verify-discovery.js +0 -193
  118. package/dist/cli/processors/verify-discovery.test.d.ts +0 -1
  119. package/dist/cli/processors/verify-discovery.test.js +0 -153
  120. package/dist/cli/processors/zod-extractor.d.ts +0 -27
  121. package/dist/cli/processors/zod-extractor.js +0 -153
  122. package/dist/cli/prompts/review.d.ts +0 -61
  123. package/dist/cli/prompts/review.js +0 -410
  124. package/dist/cli/selectors/express.d.ts +0 -12
  125. package/dist/cli/selectors/express.js +0 -117
  126. package/dist/cli/selectors/fastapi.d.ts +0 -12
  127. package/dist/cli/selectors/fastapi.js +0 -122
  128. package/dist/cli/selectors/generic.d.ts +0 -10
  129. package/dist/cli/selectors/generic.js +0 -74
  130. package/dist/cli/selectors/index.d.ts +0 -37
  131. package/dist/cli/selectors/index.js +0 -315
  132. package/dist/cli/selectors/next.d.ts +0 -12
  133. package/dist/cli/selectors/next.js +0 -130
  134. package/dist/core/config-policy.test.d.ts +0 -1
  135. package/dist/core/config-policy.test.js +0 -101
  136. package/dist/core/config-roundtrip.test.d.ts +0 -1
  137. package/dist/core/config-roundtrip.test.js +0 -180
  138. package/dist/core/endpoint-guard.test.d.ts +0 -1
  139. package/dist/core/endpoint-guard.test.js +0 -57
  140. package/dist/core/env-diagnostics.test.d.ts +0 -1
  141. package/dist/core/env-diagnostics.test.js +0 -31
  142. package/dist/core/evidence-bundle.conformance.test.d.ts +0 -1
  143. package/dist/core/evidence-bundle.conformance.test.js +0 -110
  144. package/dist/core/evidence-bundle.test.d.ts +0 -1
  145. package/dist/core/evidence-bundle.test.js +0 -58
  146. package/dist/core/invariants.test.d.ts +0 -1
  147. package/dist/core/invariants.test.js +0 -217
  148. package/dist/core/login-handoff.test.d.ts +0 -1
  149. package/dist/core/login-handoff.test.js +0 -31
  150. package/dist/core/profile.test.d.ts +0 -1
  151. package/dist/core/profile.test.js +0 -95
  152. package/dist/core/readiness-checks.test.d.ts +0 -1
  153. package/dist/core/readiness-checks.test.js +0 -106
  154. package/dist/core/receipt.test.d.ts +0 -1
  155. package/dist/core/receipt.test.js +0 -75
  156. package/dist/core/side-effects-review.test.d.ts +0 -1
  157. package/dist/core/side-effects-review.test.js +0 -28
  158. package/dist/core/token.test.d.ts +0 -1
  159. package/dist/core/token.test.js +0 -66
@@ -1,417 +0,0 @@
1
- // ============================================================
2
- // @duct/sdk — Topology Discovery
3
- // Reads package.json / pyproject.toml / go.mod, root config files,
4
- // and top-level directory names only. No LLM, no deep reads.
5
- // Must run before any agent or file selector.
6
- // ============================================================
7
- import * as path from "path";
8
- import * as fs from "fs/promises";
9
- // ----------------------------------------------------------------
10
- // Internal helpers
11
- // ----------------------------------------------------------------
12
- async function fileExists(filePath) {
13
- try {
14
- await fs.access(filePath);
15
- return true;
16
- }
17
- catch {
18
- return false;
19
- }
20
- }
21
- async function dirExists(dirPath) {
22
- try {
23
- const stat = await fs.stat(dirPath);
24
- return stat.isDirectory();
25
- }
26
- catch {
27
- return false;
28
- }
29
- }
30
- async function readJsonFile(filePath) {
31
- try {
32
- const raw = await fs.readFile(filePath, "utf-8");
33
- return JSON.parse(raw);
34
- }
35
- catch {
36
- return null;
37
- }
38
- }
39
- /** List only first-level entries under a directory. Safe — never recurses. */
40
- async function listTopLevel(dir) {
41
- try {
42
- const entries = await fs.readdir(dir, { withFileTypes: true });
43
- return entries.map((e) => ({ name: e.name, isDir: e.isDirectory() }));
44
- }
45
- catch {
46
- return [];
47
- }
48
- }
49
- const IGNORED_DIRS = new Set([
50
- "node_modules",
51
- ".git",
52
- ".next",
53
- "dist",
54
- "build",
55
- "out",
56
- ".turbo",
57
- ".vercel",
58
- ".cache",
59
- "coverage",
60
- "tmp",
61
- "temp",
62
- "__pycache__",
63
- ".venv",
64
- "venv",
65
- ".mypy_cache",
66
- ]);
67
- function hasDep(pkg, name) {
68
- return !!(pkg.dependencies?.[name] ?? pkg.devDependencies?.[name]);
69
- }
70
- function detectFrameworkFromPkg(pkg) {
71
- if (hasDep(pkg, "next")) {
72
- // App Router vs Pages Router determined later (needs dir check)
73
- return "next-app"; // default; refined in discoverTopology
74
- }
75
- if (hasDep(pkg, "@remix-run/react") || hasDep(pkg, "remix"))
76
- return "remix";
77
- if (hasDep(pkg, "@sveltejs/kit"))
78
- return "sveltekit";
79
- if (hasDep(pkg, "nuxt") || hasDep(pkg, "@nuxt/kit"))
80
- return "nuxt";
81
- if (hasDep(pkg, "vue") && !hasDep(pkg, "nuxt"))
82
- return "vue3";
83
- if (hasDep(pkg, "vite") && hasDep(pkg, "react"))
84
- return "vite-react";
85
- return "unknown";
86
- }
87
- // ----------------------------------------------------------------
88
- // Auth lib detection from package.json
89
- // ----------------------------------------------------------------
90
- function detectAuthFromPkg(pkg) {
91
- if (hasDep(pkg, "next-auth") || hasDep(pkg, "@auth/core"))
92
- return "nextauth";
93
- if (hasDep(pkg, "@clerk/nextjs") ||
94
- hasDep(pkg, "@clerk/clerk-sdk-node") ||
95
- hasDep(pkg, "@clerk/backend"))
96
- return "clerk";
97
- if (hasDep(pkg, "@auth0/nextjs-auth0") ||
98
- hasDep(pkg, "auth0") ||
99
- hasDep(pkg, "@auth0/auth0-react"))
100
- return "auth0";
101
- if (hasDep(pkg, "iron-session") ||
102
- hasDep(pkg, "cookie-session") ||
103
- hasDep(pkg, "express-session"))
104
- return "session-cookie";
105
- if (hasDep(pkg, "jsonwebtoken") || hasDep(pkg, "jose"))
106
- return "custom-jwt";
107
- return "unknown";
108
- }
109
- // ----------------------------------------------------------------
110
- // Route root and API root inference
111
- // ----------------------------------------------------------------
112
- async function inferRoots(projectRoot, framework, topLevel) {
113
- const dirs = new Set(topLevel.filter((e) => e.isDir).map((e) => e.name));
114
- // Next.js — refine app vs pages
115
- if (framework === "next-app" || framework === "next-pages") {
116
- const hasApp = dirs.has("app") ||
117
- (await dirExists(path.join(projectRoot, "src", "app")));
118
- const hasPages = dirs.has("pages") ||
119
- (await dirExists(path.join(projectRoot, "src", "pages")));
120
- if (hasApp && hasPages) {
121
- // Both exist — prefer App Router
122
- return {
123
- routeRoot: dirs.has("app") ? "app" : "src/app",
124
- apiRoot: dirs.has("app") ? "app/api" : "src/app/api",
125
- refinedFramework: "next-app",
126
- };
127
- }
128
- if (hasApp) {
129
- return {
130
- routeRoot: dirs.has("app") ? "app" : "src/app",
131
- apiRoot: dirs.has("app") ? "app/api" : "src/app/api",
132
- refinedFramework: "next-app",
133
- };
134
- }
135
- if (hasPages) {
136
- return {
137
- routeRoot: dirs.has("pages") ? "pages" : "src/pages",
138
- apiRoot: dirs.has("pages") ? "pages/api" : "src/pages/api",
139
- refinedFramework: "next-pages",
140
- };
141
- }
142
- // Default
143
- return { routeRoot: "app", apiRoot: "app/api", refinedFramework: "next-app" };
144
- }
145
- if (framework === "remix") {
146
- return { routeRoot: "app/routes", apiRoot: "app/routes", refinedFramework: "remix" };
147
- }
148
- if (framework === "sveltekit") {
149
- return {
150
- routeRoot: "src/routes",
151
- apiRoot: "src/routes/api",
152
- refinedFramework: "sveltekit",
153
- };
154
- }
155
- if (framework === "nuxt") {
156
- return {
157
- routeRoot: "pages",
158
- apiRoot: dirs.has("server") ? "server/api" : "api",
159
- refinedFramework: "nuxt",
160
- };
161
- }
162
- // Generic / unknown — best-guess from top-level dirs
163
- const routeRoot = dirs.has("routes")
164
- ? "routes"
165
- : dirs.has("pages")
166
- ? "pages"
167
- : dirs.has("views")
168
- ? "views"
169
- : "src";
170
- const apiRoot = dirs.has("api")
171
- ? "api"
172
- : dirs.has("routes")
173
- ? "routes"
174
- : dirs.has("controllers")
175
- ? "controllers"
176
- : dirs.has("handlers")
177
- ? "handlers"
178
- : "src";
179
- return { routeRoot, apiRoot, refinedFramework: framework };
180
- }
181
- // ----------------------------------------------------------------
182
- // Package manager detection
183
- // ----------------------------------------------------------------
184
- async function detectPackageManager(projectRoot, topLevel) {
185
- const files = topLevel.filter((e) => !e.isDir).map((e) => e.name);
186
- if (files.includes("pnpm-lock.yaml") || files.includes("pnpm-workspace.yaml"))
187
- return "pnpm";
188
- if (files.includes("yarn.lock"))
189
- return "yarn";
190
- if (files.includes("package-lock.json"))
191
- return "npm";
192
- if (files.includes("package.json")) {
193
- // Check packageManager field in package.json
194
- const pkg = await readJsonFile(path.join(projectRoot, "package.json"));
195
- const pm = pkg?.packageManager;
196
- if (pm?.startsWith("pnpm"))
197
- return "pnpm";
198
- if (pm?.startsWith("yarn"))
199
- return "yarn";
200
- if (pm?.startsWith("npm"))
201
- return "npm";
202
- return "npm"; // has package.json — default to npm
203
- }
204
- if (files.includes("requirements.txt") || files.includes("pyproject.toml") || files.includes("setup.py")) {
205
- return "pip";
206
- }
207
- return "unknown";
208
- }
209
- // ----------------------------------------------------------------
210
- // Confidence scoring
211
- // ----------------------------------------------------------------
212
- function computeConfidence(framework, apiRoots, routeRoots, packageManagerKnown) {
213
- if (framework === "unknown")
214
- return 0.3;
215
- let score = 0.5; // base — framework detected
216
- // Bonus for confirmed directory structure
217
- if (apiRoots.length > 0)
218
- score += 0.2;
219
- if (routeRoots.length > 0)
220
- score += 0.15;
221
- if (packageManagerKnown)
222
- score += 0.15;
223
- return Math.min(score, 1.0);
224
- }
225
- // ----------------------------------------------------------------
226
- // Language detection
227
- // ----------------------------------------------------------------
228
- async function detectLanguage(_projectRoot, topLevel) {
229
- const files = topLevel.filter((e) => !e.isDir).map((e) => e.name);
230
- if (files.includes("pyproject.toml") || files.includes("setup.py") || files.includes("requirements.txt")) {
231
- return "python";
232
- }
233
- if (files.includes("go.mod"))
234
- return "go";
235
- if (files.includes("Gemfile"))
236
- return "ruby";
237
- // TypeScript vs JavaScript — check for tsconfig or .ts files at root
238
- if (files.includes("tsconfig.json") || files.some((f) => f.endsWith(".ts"))) {
239
- return "typescript";
240
- }
241
- if (files.includes("package.json"))
242
- return "javascript";
243
- return "unknown";
244
- }
245
- // ----------------------------------------------------------------
246
- // Monorepo detection
247
- // ----------------------------------------------------------------
248
- async function detectMonorepo(projectRoot, pkg, topLevel) {
249
- // Check for npm/pnpm/yarn workspaces
250
- const workspaces = pkg?.workspaces;
251
- if (workspaces) {
252
- const patterns = Array.isArray(workspaces) ? workspaces : workspaces.packages;
253
- // For workspace patterns like "packages/*", "apps/*", collect matching dirs
254
- const packageDirs = [];
255
- for (const dirEntry of topLevel.filter((e) => e.isDir)) {
256
- if (IGNORED_DIRS.has(dirEntry.name))
257
- continue;
258
- const subPkg = await fileExists(path.join(projectRoot, dirEntry.name, "package.json"));
259
- if (subPkg && patterns.some((p) => p.startsWith(dirEntry.name) || p.includes("*"))) {
260
- // List sub-packages
261
- const subEntries = await listTopLevel(path.join(projectRoot, dirEntry.name));
262
- for (const sub of subEntries.filter((e) => e.isDir)) {
263
- const hasPkg = await fileExists(path.join(projectRoot, dirEntry.name, sub.name, "package.json"));
264
- if (hasPkg)
265
- packageDirs.push(`${dirEntry.name}/${sub.name}`);
266
- }
267
- if (packageDirs.length === 0)
268
- packageDirs.push(dirEntry.name);
269
- }
270
- }
271
- if (packageDirs.length > 0)
272
- return { isMonorepo: true, packageDirs };
273
- }
274
- // Heuristic: look for multiple package.json in top-level subdirs
275
- const subPkgDirs = [];
276
- for (const entry of topLevel.filter((e) => e.isDir)) {
277
- if (IGNORED_DIRS.has(entry.name))
278
- continue;
279
- const hasPkg = await fileExists(path.join(projectRoot, entry.name, "package.json"));
280
- if (hasPkg)
281
- subPkgDirs.push(entry.name);
282
- }
283
- if (subPkgDirs.length >= 2) {
284
- return { isMonorepo: true, packageDirs: subPkgDirs };
285
- }
286
- return { isMonorepo: false, packageDirs: [] };
287
- }
288
- // ----------------------------------------------------------------
289
- // discoverTopology — main export
290
- // ----------------------------------------------------------------
291
- /**
292
- * Topology Discovery.
293
- *
294
- * Reads only package.json / pyproject.toml / go.mod, root config files,
295
- * and top-level directory names. No LLM, no deep reads.
296
- * Must run before any agent or selector.
297
- */
298
- export async function discoverTopology(projectRoot) {
299
- const resolvedRoot = path.resolve(projectRoot);
300
- // 1. List top-level entries (names only, no recursion)
301
- const topLevel = await listTopLevel(resolvedRoot);
302
- // 2. Read package.json (or pyproject.toml / go.mod for other stacks)
303
- const pkg = await readJsonFile(path.join(resolvedRoot, "package.json"));
304
- // 3. Detect language
305
- const language = await detectLanguage(resolvedRoot, topLevel);
306
- // 4. Detect framework + auth lib from package.json
307
- let framework = "unknown";
308
- let authLib = "unknown";
309
- if (pkg) {
310
- framework = detectFrameworkFromPkg(pkg);
311
- authLib = detectAuthFromPkg(pkg);
312
- }
313
- else if (language === "python") {
314
- // FastAPI / Django detection via pyproject.toml or requirements
315
- const pyprojectContent = await readJsonFile(path.join(resolvedRoot, "pyproject.toml"));
316
- // pyproject.toml is TOML, not JSON — just check file presence
317
- const hasPyproject = await fileExists(path.join(resolvedRoot, "pyproject.toml"));
318
- const hasManagePy = await fileExists(path.join(resolvedRoot, "manage.py"));
319
- const hasMainPy = await fileExists(path.join(resolvedRoot, "main.py"));
320
- if (hasManagePy) {
321
- framework = "unknown"; // Django — no specific FrameworkName, falls to generic
322
- }
323
- else if (hasMainPy || hasPyproject) {
324
- framework = "unknown"; // FastAPI — generic
325
- }
326
- void pyprojectContent; // TOML not parsed
327
- authLib = "unknown"; // Python auth needs deeper scan
328
- }
329
- // 5. Check for auth config files at root to refine authLib
330
- if (authLib === "unknown") {
331
- const authConfigCandidates = ["auth.ts", "auth.js", "auth.config.ts"];
332
- for (const candidate of authConfigCandidates) {
333
- if (topLevel.some((e) => !e.isDir && e.name === candidate)) {
334
- // Presence of auth.ts is strong NextAuth signal
335
- authLib = "nextauth";
336
- break;
337
- }
338
- }
339
- }
340
- // 6. Infer route root and API root
341
- const { routeRoot, apiRoot, refinedFramework } = await inferRoots(resolvedRoot, framework, topLevel);
342
- framework = refinedFramework;
343
- // 7. Detect monorepo
344
- const { isMonorepo, packageDirs } = await detectMonorepo(resolvedRoot, pkg, topLevel);
345
- // 8. Detect package manager
346
- const packageManager = await detectPackageManager(resolvedRoot, topLevel);
347
- // 9. Build plural root arrays for selectors
348
- const routeRoots = buildRouteRoots(framework, routeRoot);
349
- const apiRoots = buildApiRoots(framework, apiRoot);
350
- // 10. Compute confidence
351
- const confidence = computeConfidence(framework, apiRoots, routeRoots, packageManager !== "unknown");
352
- return {
353
- framework,
354
- language,
355
- routeRoot,
356
- apiRoot,
357
- apiRoots,
358
- routeRoots,
359
- packageManager,
360
- projectRoot: resolvedRoot,
361
- confidence,
362
- authLib,
363
- isMonorepo,
364
- packageDirs,
365
- };
366
- }
367
- // ----------------------------------------------------------------
368
- // Plural roots helpers
369
- // ----------------------------------------------------------------
370
- function buildRouteRoots(framework, routeRoot) {
371
- switch (framework) {
372
- case "next-app":
373
- return ["app", "src/app"].filter((d) => d === routeRoot || routeRoot.includes(d.replace("src/", "")));
374
- case "next-pages":
375
- return ["pages", "src/pages"].filter((d) => d === routeRoot || routeRoot.includes(d.replace("src/", "")));
376
- case "remix":
377
- return ["app/routes", "app"];
378
- case "sveltekit":
379
- return ["src/routes"];
380
- case "nuxt":
381
- return ["pages"];
382
- default:
383
- return routeRoot ? [routeRoot] : [];
384
- }
385
- }
386
- function buildApiRoots(framework, apiRoot) {
387
- switch (framework) {
388
- case "next-app":
389
- return ["app/api", "src/app/api"].filter((d) => d === apiRoot || apiRoot.includes("api"));
390
- case "next-pages":
391
- return ["pages/api", "src/pages/api"].filter((d) => d === apiRoot || apiRoot.includes("api"));
392
- case "remix":
393
- return ["app/routes"];
394
- case "sveltekit":
395
- return ["src/routes/api", "src/routes"];
396
- default: {
397
- const candidates = ["routes", "src/routes", "api", "routers", "controllers", "handlers"];
398
- const found = candidates.filter((c) => apiRoot === c || apiRoot.startsWith(c));
399
- return found.length > 0 ? found : (apiRoot ? [apiRoot] : []);
400
- }
401
- }
402
- }
403
- // ----------------------------------------------------------------
404
- // detectTopology — spec-compliant alias
405
- // ----------------------------------------------------------------
406
- /**
407
- * Detect project topology for the selector pipeline.
408
- *
409
- * Returns an enriched TopoResult with plural `apiRoots`, `routeRoots`,
410
- * `packageManager`, `projectRoot`, and `confidence` in addition to the
411
- * existing fields from `discoverTopology()`.
412
- *
413
- * No LLM — pure filesystem reads only.
414
- */
415
- export async function detectTopology(projectRoot) {
416
- return discoverTopology(projectRoot);
417
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,222 +0,0 @@
1
- import { describe, it } from "node:test";
2
- import assert from "node:assert/strict";
3
- import { validateDuctConfigStrict } from "../../core/config.js";
4
- import { generateConfigFile } from "./config.js";
5
- import { generateReceiver, generateTokenRoute } from "./receiver.js";
6
- import { normalizeAuthSchema, normalizeDuctConfigForCodegen, resolveTokenEndpointUrl, } from "./normalize.js";
7
- const BASE_URL = "https://app.acme.com";
8
- function sampleConfig(overrides = {}) {
9
- return {
10
- shellId: "shell_acme_prod",
11
- product: {
12
- name: "Acme",
13
- description: "Acme test application",
14
- baseUrl: BASE_URL,
15
- apiBaseUrl: "https://api.acme.com",
16
- logoUrl: "https://app.acme.com/logo.png",
17
- },
18
- auth: {
19
- strategy: "nextauth",
20
- sessionFields: ["id", "email"],
21
- guestAllowed: false,
22
- tokenExpirySeconds: 300,
23
- tokenEndpoint: "/api/duct/token",
24
- },
25
- routes: [
26
- {
27
- path: "/orders/:orderId",
28
- name: "Order Detail",
29
- description: "Shows a single order",
30
- params: [
31
- { name: "orderId", type: "string", required: true },
32
- ],
33
- queryParams: [],
34
- uiStateHint: "detail",
35
- requiresAuth: true,
36
- deeplinkable: true,
37
- },
38
- ],
39
- actions: [
40
- {
41
- id: "get_order",
42
- name: "Get Order",
43
- description: "Fetch a single order by ID",
44
- method: "GET",
45
- path: "/api/orders/:orderId",
46
- agentAccessible: true,
47
- sideEffects: false,
48
- sensitivityLevel: "low",
49
- params: [],
50
- requiresAuth: true,
51
- },
52
- ],
53
- deeplinks: [],
54
- agentPermissions: {
55
- defaultLevel: "none",
56
- requireUserConsent: true,
57
- },
58
- widget: {
59
- position: "bottom-right",
60
- },
61
- intershell_enabled: true,
62
- registry_visibility: "public",
63
- webhooks: {
64
- identityUrl: "https://app.acme.com/duct/identity",
65
- },
66
- ...overrides,
67
- };
68
- }
69
- describe("resolveTokenEndpointUrl", () => {
70
- it("converts a relative path to a full URL", () => {
71
- assert.equal(resolveTokenEndpointUrl("/api/duct/token", BASE_URL), "https://app.acme.com/api/duct/token");
72
- });
73
- it("preserves an already-absolute URL", () => {
74
- const url = "https://app.acme.com/api/duct/token";
75
- assert.equal(resolveTokenEndpointUrl(url, BASE_URL), url);
76
- });
77
- it("returns undefined for invalid base URLs", () => {
78
- assert.equal(resolveTokenEndpointUrl("/api/duct/token", "not-a-url"), undefined);
79
- });
80
- });
81
- describe("normalizeDuctConfigForCodegen", () => {
82
- it("normalizes relative auth.tokenEndpoint before validation", () => {
83
- const normalized = normalizeDuctConfigForCodegen(sampleConfig());
84
- assert.equal(normalized.auth.tokenEndpoint, "https://app.acme.com/api/duct/token");
85
- const validation = validateDuctConfigStrict(normalized);
86
- assert.equal(validation.ok, true);
87
- });
88
- });
89
- describe("validateDuctConfigStrict", () => {
90
- it("rejects configs with relative tokenEndpoint before normalization", () => {
91
- const validation = validateDuctConfigStrict(sampleConfig());
92
- assert.equal(validation.ok, false);
93
- if (!validation.ok) {
94
- assert.ok(validation.issues.some((issue) => issue.area === "auth.tokenEndpoint"));
95
- }
96
- });
97
- it("accepts normalized configs", () => {
98
- const validation = validateDuctConfigStrict(normalizeDuctConfigForCodegen(sampleConfig()));
99
- assert.equal(validation.ok, true);
100
- });
101
- });
102
- describe("generateConfigFile", () => {
103
- it("emits apiBaseUrl, normalized tokenEndpoint, intershell flags, and product logoUrl", () => {
104
- const output = generateConfigFile(sampleConfig());
105
- assert.match(output, /apiBaseUrl: "https:\/\/api\.acme\.com"/);
106
- assert.match(output, /tokenEndpoint: "https:\/\/app\.acme\.com\/api\/duct\/token"/);
107
- assert.match(output, /intershell_enabled: true/);
108
- assert.match(output, /registry_visibility: "public"/);
109
- assert.match(output, /logoUrl: "https:\/\/app\.acme\.com\/logo\.png"/);
110
- });
111
- it("emits discovery evidence comments and schemas", () => {
112
- const output = generateConfigFile(sampleConfig({
113
- routes: [
114
- {
115
- path: "/orders/:orderId",
116
- name: "Order Detail",
117
- description: "Shows a single order",
118
- params: [{ name: "orderId", type: "string", required: true }],
119
- queryParams: [],
120
- uiStateHint: "detail",
121
- requiresAuth: true,
122
- deeplinkable: true,
123
- confidence: 0.91,
124
- evidence: ["app/orders/[orderId]/page.tsx:4"],
125
- },
126
- ],
127
- actions: [
128
- {
129
- id: "get_order",
130
- name: "Get Order",
131
- description: "Fetch a single order by ID",
132
- method: "GET",
133
- path: "/api/orders/:orderId",
134
- agentAccessible: true,
135
- sideEffects: false,
136
- sensitivityLevel: "low",
137
- params: [],
138
- requiresAuth: true,
139
- confidence: 0.88,
140
- evidence: ["app/api/orders/[orderId]/route.ts:12"],
141
- inputSchema: {
142
- type: "object",
143
- properties: { orderId: { type: "string" } },
144
- },
145
- },
146
- {
147
- id: "legacy_health",
148
- name: "Legacy Health",
149
- description: "Non /api backend route",
150
- method: "GET",
151
- path: "/v1/health",
152
- agentAccessible: true,
153
- sideEffects: false,
154
- sensitivityLevel: "none",
155
- params: [],
156
- requiresAuth: false,
157
- confidence: 0.65,
158
- evidence: ["warning: path does not start with /api/ — verify action proxy target"],
159
- },
160
- ],
161
- }));
162
- assert.match(output, /confidence 91%/);
163
- assert.match(output, /app\/orders\/\[orderId\]\/page\.tsx:4/);
164
- assert.match(output, /inputSchema:/);
165
- assert.match(output, /path: "\/v1\/health"/);
166
- assert.match(output, /verify action proxy target/);
167
- });
168
- it("uses the Duct docs URL instead of a fabricated company docs domain", () => {
169
- const output = generateConfigFile(sampleConfig());
170
- assert.match(output, /Docs: http:\/\/localhost:3005\/docs\/config/);
171
- assert.doesNotMatch(output, /docs\.acme\.com/);
172
- });
173
- });
174
- describe("generateReceiver", () => {
175
- it("uses the Duct docs URL instead of a fabricated company docs domain, for every framework", () => {
176
- const config = normalizeDuctConfigForCodegen(sampleConfig());
177
- const frameworks = [
178
- { name: "next-app", hasAppRouter: true, hasPagesRouter: false },
179
- { name: "next-pages", hasAppRouter: false, hasPagesRouter: false },
180
- { name: "remix", hasAppRouter: false, hasPagesRouter: false },
181
- { name: "vite-react", hasAppRouter: false, hasPagesRouter: false },
182
- { name: "sveltekit", hasAppRouter: false, hasPagesRouter: false },
183
- ];
184
- for (const fw of frameworks) {
185
- const output = generateReceiver(config, {
186
- name: fw.name,
187
- version: "1.0",
188
- hasAppRouter: fw.hasAppRouter,
189
- hasPagesRouter: fw.hasPagesRouter,
190
- packageManager: "npm",
191
- srcDir: ".",
192
- });
193
- assert.doesNotMatch(output, /docs\.your-domain\.com/, `${fw.name} receiver should not fabricate a docs domain`);
194
- }
195
- });
196
- });
197
- describe("generateTokenRoute", () => {
198
- it("imports generateDuctToken from @duct-sdk/sdk/server", () => {
199
- const output = generateTokenRoute(normalizeDuctConfigForCodegen(sampleConfig()), {
200
- name: "next-app",
201
- version: "14",
202
- hasAppRouter: true,
203
- hasPagesRouter: false,
204
- packageManager: "npm",
205
- srcDir: ".",
206
- });
207
- assert.match(output, /from "@duct-sdk\/sdk\/server"/);
208
- assert.doesNotMatch(output, /from "@duct-sdk\/sdk";/);
209
- });
210
- });
211
- describe("normalizeAuthSchema", () => {
212
- it("omits tokenEndpoint when it cannot be resolved", () => {
213
- const auth = normalizeAuthSchema({
214
- strategy: "none",
215
- sessionFields: [],
216
- guestAllowed: true,
217
- tokenExpirySeconds: 300,
218
- tokenEndpoint: "/api/duct/token",
219
- }, "not-a-url");
220
- assert.equal(auth.tokenEndpoint, undefined);
221
- });
222
- });
@@ -1 +0,0 @@
1
- export {};