theokit 0.5.4 → 0.6.1
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.
- package/dist/{actions-virtual-module-DL74V6SR.js → actions-virtual-module-4WVKHQ2X.js} +5 -2
- package/dist/actions-virtual-module-4WVKHQ2X.js.map +1 -0
- package/dist/{actions-virtual-module-ZDD54ZZE.js → actions-virtual-module-LTOXBSCF.js} +16 -2
- package/dist/actions-virtual-module-LTOXBSCF.js.map +1 -0
- package/dist/{app-typed-client-4M4NVSK3.js → app-typed-client-4N5OGNOQ.js} +15 -4
- package/dist/app-typed-client-4N5OGNOQ.js.map +1 -0
- package/dist/{app-typed-client-4GIKUKRT.js → app-typed-client-SAETWZT5.js} +5 -4
- package/dist/app-typed-client-SAETWZT5.js.map +1 -0
- package/dist/{aws-lambda-SCRGTGF5.js → aws-lambda-WT4HRBNL.js} +3 -3
- package/dist/{build-R74EU6BP.js → build-KQD2EDU4.js} +10 -11
- package/dist/build-KQD2EDU4.js.map +1 -0
- package/dist/{bun-FURRCQMS.js → bun-UTDVN6R4.js} +3 -3
- package/dist/{check-NXYPLM6M.js → check-F3UDYSZ4.js} +2 -2
- package/dist/chunk-223EFY5X.js +469 -0
- package/dist/chunk-223EFY5X.js.map +1 -0
- package/dist/{chunk-KJLECZWQ.js → chunk-3FYJ7R7N.js} +57 -14
- package/dist/chunk-3FYJ7R7N.js.map +1 -0
- package/dist/{chunk-HDA6M7P4.js → chunk-3LVRAGAZ.js} +3 -5
- package/dist/{chunk-JD7AQNJS.js → chunk-4I47JW5O.js} +38 -425
- package/dist/chunk-4I47JW5O.js.map +1 -0
- package/dist/{chunk-H4J2LECY.js → chunk-6BUUZ2PK.js} +9 -9
- package/dist/chunk-6BUUZ2PK.js.map +1 -0
- package/dist/{chunk-P2RS3WWY.js → chunk-6FYD34NX.js} +194 -22
- package/dist/chunk-6FYD34NX.js.map +1 -0
- package/dist/{chunk-X3VNROZ7.js → chunk-6VSKLYT6.js} +78 -21
- package/dist/chunk-6VSKLYT6.js.map +1 -0
- package/dist/{chunk-FGOX37NB.js → chunk-BNGBG2SQ.js} +21 -2
- package/dist/chunk-BNGBG2SQ.js.map +1 -0
- package/dist/chunk-CBGRFVF5.js +421 -0
- package/dist/chunk-CBGRFVF5.js.map +1 -0
- package/dist/{chunk-X32KQH5C.js → chunk-CCVC6P6B.js} +3 -3
- package/dist/chunk-CCVC6P6B.js.map +1 -0
- package/dist/{chunk-DNMSV3R3.js → chunk-D7ZH7DTG.js} +3 -3
- package/dist/chunk-D7ZH7DTG.js.map +1 -0
- package/dist/{chunk-MWYSRZI4.js → chunk-EQV67HZL.js} +2 -2
- package/dist/{chunk-CG563V5M.js → chunk-IEES3CHD.js} +39 -5
- package/dist/chunk-IEES3CHD.js.map +1 -0
- package/dist/{chunk-DUKXQNM7.js → chunk-IHMJV2OK.js} +2 -2
- package/dist/{chunk-WGHJD6I7.js → chunk-JAIKGP3Q.js} +76 -21
- package/dist/chunk-JAIKGP3Q.js.map +1 -0
- package/dist/{chunk-B3L3TJVF.js → chunk-JBCHWRKF.js} +50 -50
- package/dist/chunk-JBCHWRKF.js.map +1 -0
- package/dist/{chunk-XMS5VRIK.js → chunk-JQSFBJR5.js} +3 -3
- package/dist/chunk-JQSFBJR5.js.map +1 -0
- package/dist/{chunk-S74FECKW.js → chunk-MV4LKTW6.js} +119 -153
- package/dist/chunk-MV4LKTW6.js.map +1 -0
- package/dist/chunk-PBEH6NXR.js +44 -0
- package/dist/chunk-PBEH6NXR.js.map +1 -0
- package/dist/chunk-PPPR5DGR.js +1 -0
- package/dist/{chunk-NZXH2LQQ.js → chunk-SJIRP73B.js} +18 -1
- package/dist/chunk-SJIRP73B.js.map +1 -0
- package/dist/cli/index.js +25 -10
- package/dist/cli/index.js.map +1 -1
- package/dist/client/index.d.ts +4 -4
- package/dist/{cloudflare-IZ6VJ2OU.js → cloudflare-U5GYYI47.js} +3 -3
- package/dist/db-ZPDW3UCU.js +78 -0
- package/dist/db-ZPDW3UCU.js.map +1 -0
- package/dist/{deno-deploy-O73NBXIW.js → deno-deploy-3QHJ3AJQ.js} +3 -3
- package/dist/{dev-ZU46C5AZ.js → dev-NDEZA2MP.js} +21 -11
- package/dist/dev-NDEZA2MP.js.map +1 -0
- package/dist/{dev-emit-JBVINGHU.js → dev-emit-O4EGOSNV.js} +77 -24
- package/dist/dev-emit-O4EGOSNV.js.map +1 -0
- package/dist/{dev-emit-66FCOS7V.js → dev-emit-OUPI7NAQ.js} +4 -5
- package/dist/{dev-emit-66FCOS7V.js.map → dev-emit-OUPI7NAQ.js.map} +1 -1
- package/dist/devtools/entry.js +1 -0
- package/dist/devtools/entry.js.map +1 -1
- package/dist/{dist-KRW6OVD4.js → dist-6GPD6WCU.js} +10231 -8164
- package/dist/dist-6GPD6WCU.js.map +1 -0
- package/dist/generate-ODDAYXNR.js +494 -0
- package/dist/generate-ODDAYXNR.js.map +1 -0
- package/dist/{index-CuHICqb9.d.ts → index-DWZF8uQD.d.ts} +132 -132
- package/dist/index.d.ts +32 -3
- package/dist/index.js +8 -9
- package/dist/index.js.map +1 -1
- package/dist/{info-CORLCPEJ.js → info-CSGWIAXA.js} +5 -5
- package/dist/{lib-NST3PNZX.js → lib-JBI3XXH3.js} +27 -27
- package/dist/{lib-NST3PNZX.js.map → lib-JBI3XXH3.js.map} +1 -1
- package/dist/{netlify-O7G3RLK4.js → netlify-DUB7BZ4E.js} +3 -3
- package/dist/{node-LXPQLMVB.js → node-ELE236WK.js} +3 -3
- package/dist/{openapi-TEOUOIJ2.js → openapi-NXGRXABL.js} +7 -8
- package/dist/{openapi-TEOUOIJ2.js.map → openapi-NXGRXABL.js.map} +1 -1
- package/dist/registry-B7FA6KMI.js +25 -0
- package/dist/{routes-GAXVWJUK.js → routes-6A5XFGF7.js} +7 -9
- package/dist/routes-6A5XFGF7.js.map +1 -0
- package/dist/{scan-NQFI5S7P.js → scan-I5PT6TUX.js} +2 -2
- package/dist/{schema-D3v8VB7o.d.ts → schema-BpH6ivDY.d.ts} +2 -4
- package/dist/{schema-Z5VJ2I76.js → schema-NPI4NJEF.js} +3 -3
- package/dist/server/auth/index.d.ts +20 -20
- package/dist/server/auth/index.js +3 -5
- package/dist/server/define/index.d.ts +7 -0
- package/dist/server/define/index.js +1 -1
- package/dist/server/http/index.d.ts +2 -2
- package/dist/server/http/index.js +1 -2
- package/dist/server/index.d.ts +36 -3
- package/dist/server/index.js +66 -61
- package/dist/server/index.js.map +1 -1
- package/dist/server/scan/index.d.ts +13 -13
- package/dist/server/scan/index.js +8 -12
- package/dist/server/security/index.d.ts +69 -69
- package/dist/server/security/index.js +1 -1
- package/dist/{services-typed-client-ASZL7FQV.js → services-typed-client-24VBMDOF.js} +2 -2
- package/dist/{services-typed-client-KK6RHRDG.js → services-typed-client-IETY2SAK.js} +2 -2
- package/dist/{start-HGUNNF5X.js → start-SPFWOGHL.js} +95 -80
- package/dist/start-SPFWOGHL.js.map +1 -0
- package/dist/{static-EO73I4C7.js → static-YWF2M6YT.js} +4 -4
- package/dist/{theo-cloud-HBCYEODQ.js → theo-cloud-EUK56I7O.js} +2 -2
- package/dist/{vercel-GSFDMF7K.js → vercel-LGDQWYZD.js} +3 -3
- package/dist/vite-plugin/index.d.ts +1 -1
- package/dist/vite-plugin/index.js +6 -7
- package/dist/{vite-plugin-TX5H4MB6.js → vite-plugin-43KQU5S7.js} +11 -9
- package/dist/vite-plugin-43KQU5S7.js.map +1 -0
- package/package.json +22 -19
- package/dist/actions-virtual-module-DL74V6SR.js.map +0 -1
- package/dist/actions-virtual-module-ZDD54ZZE.js.map +0 -1
- package/dist/app-typed-client-4GIKUKRT.js.map +0 -1
- package/dist/app-typed-client-4M4NVSK3.js.map +0 -1
- package/dist/build-R74EU6BP.js.map +0 -1
- package/dist/chunk-4HBI7DHP.js +0 -20
- package/dist/chunk-4HBI7DHP.js.map +0 -1
- package/dist/chunk-B3L3TJVF.js.map +0 -1
- package/dist/chunk-CG563V5M.js.map +0 -1
- package/dist/chunk-DNMSV3R3.js.map +0 -1
- package/dist/chunk-FGOX37NB.js.map +0 -1
- package/dist/chunk-GPF64ENM.js +0 -73
- package/dist/chunk-H4J2LECY.js.map +0 -1
- package/dist/chunk-HDA6M7P4.js.map +0 -1
- package/dist/chunk-JD7AQNJS.js.map +0 -1
- package/dist/chunk-KJLECZWQ.js.map +0 -1
- package/dist/chunk-NZXH2LQQ.js.map +0 -1
- package/dist/chunk-OLPB36O2.js +0 -259
- package/dist/chunk-OLPB36O2.js.map +0 -1
- package/dist/chunk-P2RS3WWY.js.map +0 -1
- package/dist/chunk-P3SGM4NR.js +0 -156
- package/dist/chunk-P3SGM4NR.js.map +0 -1
- package/dist/chunk-S74FECKW.js.map +0 -1
- package/dist/chunk-UVHRD33F.js +0 -181
- package/dist/chunk-UVHRD33F.js.map +0 -1
- package/dist/chunk-WGHJD6I7.js.map +0 -1
- package/dist/chunk-X32KQH5C.js.map +0 -1
- package/dist/chunk-X3VNROZ7.js.map +0 -1
- package/dist/chunk-XMS5VRIK.js.map +0 -1
- package/dist/dev-ZU46C5AZ.js.map +0 -1
- package/dist/dev-emit-JBVINGHU.js.map +0 -1
- package/dist/dist-KRW6OVD4.js.map +0 -1
- package/dist/generate-AZ2K6Z2Z.js +0 -281
- package/dist/generate-AZ2K6Z2Z.js.map +0 -1
- package/dist/registry-KW4F4D2L.js +0 -25
- package/dist/routes-GAXVWJUK.js.map +0 -1
- package/dist/start-HGUNNF5X.js.map +0 -1
- package/dist/{aws-lambda-SCRGTGF5.js.map → aws-lambda-WT4HRBNL.js.map} +0 -0
- package/dist/{bun-FURRCQMS.js.map → bun-UTDVN6R4.js.map} +0 -0
- package/dist/{check-NXYPLM6M.js.map → check-F3UDYSZ4.js.map} +0 -0
- package/dist/{chunk-GPF64ENM.js.map → chunk-3LVRAGAZ.js.map} +0 -0
- package/dist/{chunk-MWYSRZI4.js.map → chunk-EQV67HZL.js.map} +0 -0
- package/dist/{chunk-DUKXQNM7.js.map → chunk-IHMJV2OK.js.map} +0 -0
- package/dist/{node-LXPQLMVB.js.map → chunk-PPPR5DGR.js.map} +0 -0
- package/dist/{cloudflare-IZ6VJ2OU.js.map → cloudflare-U5GYYI47.js.map} +0 -0
- package/dist/{deno-deploy-O73NBXIW.js.map → deno-deploy-3QHJ3AJQ.js.map} +0 -0
- package/dist/{info-CORLCPEJ.js.map → info-CSGWIAXA.js.map} +0 -0
- package/dist/{module-loader-Cfz7dgCP.d.ts → match-CfbEFRG4.d.ts} +4 -4
- /package/dist/{netlify-O7G3RLK4.js.map → netlify-DUB7BZ4E.js.map} +0 -0
- /package/dist/{scan-NQFI5S7P.js.map → node-ELE236WK.js.map} +0 -0
- /package/dist/{registry-KW4F4D2L.js.map → registry-B7FA6KMI.js.map} +0 -0
- /package/dist/{schema-Z5VJ2I76.js.map → scan-I5PT6TUX.js.map} +0 -0
- /package/dist/{vite-plugin-TX5H4MB6.js.map → schema-NPI4NJEF.js.map} +0 -0
- /package/dist/{services-typed-client-ASZL7FQV.js.map → services-typed-client-24VBMDOF.js.map} +0 -0
- /package/dist/{services-typed-client-KK6RHRDG.js.map → services-typed-client-IETY2SAK.js.map} +0 -0
- /package/dist/{static-EO73I4C7.js.map → static-YWF2M6YT.js.map} +0 -0
- /package/dist/{theo-cloud-HBCYEODQ.js.map → theo-cloud-EUK56I7O.js.map} +0 -0
- /package/dist/{vercel-GSFDMF7K.js.map → vercel-LGDQWYZD.js.map} +0 -0
package/dist/chunk-UVHRD33F.js
DELETED
|
@@ -1,181 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import "tsx/esm";
|
|
3
|
-
|
|
4
|
-
// src/server/scan/action-scan.ts
|
|
5
|
-
import { existsSync, readFileSync, statSync } from "fs";
|
|
6
|
-
import { extname as extname2, join as join2, relative } from "path";
|
|
7
|
-
|
|
8
|
-
// src/server/_internal/scan-walker.ts
|
|
9
|
-
import { readdirSync } from "fs";
|
|
10
|
-
import { extname, join, resolve } from "path";
|
|
11
|
-
function walkSourceFiles(root, opts, onFile) {
|
|
12
|
-
const skipPrefixes = opts.skipPrefixes ?? ["_", "."];
|
|
13
|
-
const visit = (dir) => {
|
|
14
|
-
let entries;
|
|
15
|
-
try {
|
|
16
|
-
entries = readdirSync(dir, { withFileTypes: true });
|
|
17
|
-
} catch {
|
|
18
|
-
return;
|
|
19
|
-
}
|
|
20
|
-
for (const entry of entries) {
|
|
21
|
-
const fullPath = join(dir, entry.name);
|
|
22
|
-
if (entry.isDirectory() && !skipPrefixes.some((p) => entry.name.startsWith(p))) {
|
|
23
|
-
visit(fullPath);
|
|
24
|
-
} else if (entry.isFile() && opts.extensions.has(extname(entry.name))) {
|
|
25
|
-
onFile(resolve(fullPath));
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
};
|
|
29
|
-
visit(root);
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
// src/server/scan/action-scan.ts
|
|
33
|
-
var ActionScanError = class extends Error {
|
|
34
|
-
code;
|
|
35
|
-
conflictingPaths;
|
|
36
|
-
constructor(code, message, conflictingPaths) {
|
|
37
|
-
super(message);
|
|
38
|
-
this.name = "ActionScanError";
|
|
39
|
-
this.code = code;
|
|
40
|
-
this.conflictingPaths = conflictingPaths;
|
|
41
|
-
}
|
|
42
|
-
};
|
|
43
|
-
var ACTION_EXTENSIONS = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx"]);
|
|
44
|
-
var TEST_FILE_RE = /\.(test|spec)\.(ts|tsx|js|jsx)$/;
|
|
45
|
-
var RESERVED_NAMES = /* @__PURE__ */ new Set(["index", "constructor", "__proto__", "prototype", "hasOwnProperty"]);
|
|
46
|
-
function scanServerActions(serverDir) {
|
|
47
|
-
const actionsDir = join2(serverDir, "actions");
|
|
48
|
-
if (!existsSync(actionsDir) || !statSync(actionsDir).isDirectory()) {
|
|
49
|
-
return [];
|
|
50
|
-
}
|
|
51
|
-
const results = [];
|
|
52
|
-
walkSourceFiles(actionsDir, { extensions: ACTION_EXTENSIONS }, (absPath) => {
|
|
53
|
-
if (TEST_FILE_RE.test(absPath)) return;
|
|
54
|
-
let rel = relative(actionsDir, absPath);
|
|
55
|
-
rel = rel.replace(/\\/g, "/");
|
|
56
|
-
rel = rel.slice(0, -extname2(rel).length);
|
|
57
|
-
results.push({
|
|
58
|
-
filePath: absPath,
|
|
59
|
-
actionPath: rel
|
|
60
|
-
});
|
|
61
|
-
});
|
|
62
|
-
return results;
|
|
63
|
-
}
|
|
64
|
-
function scanServerActionsEnriched(serverDir) {
|
|
65
|
-
const actionsDir = join2(serverDir, "actions");
|
|
66
|
-
if (!existsSync(actionsDir) || !statSync(actionsDir).isDirectory()) {
|
|
67
|
-
return [];
|
|
68
|
-
}
|
|
69
|
-
const seenNames = /* @__PURE__ */ new Set();
|
|
70
|
-
const entries = [];
|
|
71
|
-
walkSourceFiles(actionsDir, { extensions: ACTION_EXTENSIONS }, (absPath) => {
|
|
72
|
-
if (TEST_FILE_RE.test(absPath)) return;
|
|
73
|
-
const rel = relative(actionsDir, absPath).replace(/\\/g, "/");
|
|
74
|
-
if (rel.startsWith("schemas/")) return;
|
|
75
|
-
const name = rel.slice(0, -extname2(rel).length);
|
|
76
|
-
const basename = name.includes("/") ? name.split("/").pop() ?? name : name;
|
|
77
|
-
if (RESERVED_NAMES.has(basename)) {
|
|
78
|
-
throw new ActionScanError(
|
|
79
|
-
"RESERVED_NAME",
|
|
80
|
-
`Reserved JS identifier "${basename}" cannot be an action name (${absPath})`,
|
|
81
|
-
[absPath]
|
|
82
|
-
);
|
|
83
|
-
}
|
|
84
|
-
const source = readFileSync(absPath, "utf8");
|
|
85
|
-
const stripped = stripComments(source);
|
|
86
|
-
const accept = /\baccept\s*:\s*['"]form['"]/.test(stripped) ? "form" : "json";
|
|
87
|
-
const hasInput = /\binput\s*:\s*z\./.test(stripped) || /\binput\s*:\s*\w+\(/.test(stripped);
|
|
88
|
-
const exportNames = extractActionExportNames(stripped);
|
|
89
|
-
const schemaFilePath = name.includes("/") ? void 0 : detectSchemaFile(actionsDir, basename);
|
|
90
|
-
for (const exportName of exportNames) {
|
|
91
|
-
const proxyKey = exportName === "default" ? name : exportName;
|
|
92
|
-
if (seenNames.has(proxyKey)) {
|
|
93
|
-
throw new ActionScanError(
|
|
94
|
-
"NAME_COLLISION",
|
|
95
|
-
`Duplicate action proxy key "${proxyKey}" (two files export the same name)`,
|
|
96
|
-
[absPath]
|
|
97
|
-
);
|
|
98
|
-
}
|
|
99
|
-
seenNames.add(proxyKey);
|
|
100
|
-
const entry = {
|
|
101
|
-
name: proxyKey,
|
|
102
|
-
filePath: absPath,
|
|
103
|
-
urlPath: `/api/__actions/${name}/${exportName}`,
|
|
104
|
-
accept,
|
|
105
|
-
hasInput
|
|
106
|
-
};
|
|
107
|
-
if (schemaFilePath !== void 0) {
|
|
108
|
-
entry.schemaFilePath = schemaFilePath;
|
|
109
|
-
}
|
|
110
|
-
entries.push(entry);
|
|
111
|
-
}
|
|
112
|
-
});
|
|
113
|
-
for (const entry of entries) {
|
|
114
|
-
const childPrefix = `${entry.name}/`;
|
|
115
|
-
const conflictingChild = entries.find((other) => other.name.startsWith(childPrefix));
|
|
116
|
-
if (conflictingChild) {
|
|
117
|
-
throw new ActionScanError(
|
|
118
|
-
"NAME_COLLISION",
|
|
119
|
-
`Action "${entry.name}" conflicts with directory of same name containing "${conflictingChild.name}"`,
|
|
120
|
-
[entry.filePath, conflictingChild.filePath]
|
|
121
|
-
);
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
entries.sort((a, b) => {
|
|
125
|
-
if (a.name < b.name) return -1;
|
|
126
|
-
if (a.name > b.name) return 1;
|
|
127
|
-
return 0;
|
|
128
|
-
});
|
|
129
|
-
return entries;
|
|
130
|
-
}
|
|
131
|
-
function extractActionExportNames(stripped) {
|
|
132
|
-
const names = /* @__PURE__ */ new Set();
|
|
133
|
-
const namedRe = /\bexport\s+(?:const|let|var|function\*?)\s+([a-zA-Z_$][\w$]*)\s*[=(]/g;
|
|
134
|
-
let m;
|
|
135
|
-
while ((m = namedRe.exec(stripped)) !== null) {
|
|
136
|
-
const name = m[1];
|
|
137
|
-
if (typeof name === "string" && name.length > 0) names.add(name);
|
|
138
|
-
}
|
|
139
|
-
if (/\bexport\s+default\s+defineAction\b/.test(stripped)) {
|
|
140
|
-
names.add("default");
|
|
141
|
-
}
|
|
142
|
-
if (names.size === 0) names.add("default");
|
|
143
|
-
return [...names];
|
|
144
|
-
}
|
|
145
|
-
function detectSchemaFile(actionsDir, basename) {
|
|
146
|
-
const schemasDir = join2(actionsDir, "schemas");
|
|
147
|
-
if (!existsSync(schemasDir)) return void 0;
|
|
148
|
-
for (const ext of [".ts", ".tsx", ".js", ".jsx"]) {
|
|
149
|
-
const candidate = join2(schemasDir, `${basename}${ext}`);
|
|
150
|
-
if (existsSync(candidate)) return candidate;
|
|
151
|
-
}
|
|
152
|
-
return void 0;
|
|
153
|
-
}
|
|
154
|
-
function stripComments(source) {
|
|
155
|
-
let out = "";
|
|
156
|
-
let i = 0;
|
|
157
|
-
while (i < source.length) {
|
|
158
|
-
const ch = source[i];
|
|
159
|
-
const next = source[i + 1];
|
|
160
|
-
if (ch === "/" && next === "/") {
|
|
161
|
-
while (i < source.length && source[i] !== "\n") i++;
|
|
162
|
-
continue;
|
|
163
|
-
}
|
|
164
|
-
if (ch === "/" && next === "*") {
|
|
165
|
-
i += 2;
|
|
166
|
-
while (i < source.length - 1 && !(source[i] === "*" && source[i + 1] === "/")) i++;
|
|
167
|
-
i += 2;
|
|
168
|
-
continue;
|
|
169
|
-
}
|
|
170
|
-
out += ch;
|
|
171
|
-
i++;
|
|
172
|
-
}
|
|
173
|
-
return out;
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
export {
|
|
177
|
-
walkSourceFiles,
|
|
178
|
-
scanServerActions,
|
|
179
|
-
scanServerActionsEnriched
|
|
180
|
-
};
|
|
181
|
-
//# sourceMappingURL=chunk-UVHRD33F.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server/scan/action-scan.ts","../src/server/_internal/scan-walker.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time scanner: walks `serverDir/actions/` derived from cwd.\n * No HTTP input ever reaches these fs calls.\n */\nimport { existsSync, readFileSync, statSync } from 'node:fs'\nimport { extname, join, relative } from 'node:path'\n\nimport { walkSourceFiles } from '../_internal/scan-walker.js'\n\nexport interface ActionNode {\n filePath: string\n actionPath: string\n}\n\n/**\n * Enriched manifest entry per plan g3-server-actions-and-useaction v1.2\n * § Phase 1 / T1.4 + ADR D4. Consumed by virtual module `@theo/actions`\n * (T3.1) and G4 devtools \"Actions\" tab (T5.1).\n */\nexport interface ActionManifestEntry {\n name: string\n filePath: string\n urlPath: string\n accept: 'form' | 'json'\n hasInput: boolean\n /**\n * P#4 plugin-forms shared-schema convention (per plan p4-plugin-forms v1.1 T1.1).\n * When present, points to an isomorphic schema file at\n * `<serverDir>/actions/schemas/<basename>.ts` exporting `export const schema = z.object(...)`.\n * Virtual module emits `import {schema} from '<schemaFilePath>'` + attaches as\n * `actions.X.__zodSchema` so client-side <TheoForm> can drive zodResolver.\n * Undefined when convention not followed (graceful degrade — TheoForm still\n * works via explicit `schema={...}` prop escape hatch).\n */\n schemaFilePath?: string\n}\n\n/**\n * EC-2: structured error for scan-time defects (name collision, reserved\n * identifier, etc.). Throw at scan time to fail loud — silent shadowing is\n * a security/correctness footgun.\n */\nexport class ActionScanError extends Error {\n readonly code: 'NAME_COLLISION' | 'RESERVED_NAME'\n readonly conflictingPaths: readonly string[]\n\n constructor(\n code: 'NAME_COLLISION' | 'RESERVED_NAME',\n message: string,\n conflictingPaths: readonly string[],\n ) {\n super(message)\n // T4.1 fix: identify class by name so serverErrorToEnvelope boundary\n // translator can route via class-name lookup (without this, runtime\n // `err.name` defaults to 'Error' and the meta.name diagnostic is wrong).\n this.name = 'ActionScanError'\n this.code = code\n this.conflictingPaths = conflictingPaths\n }\n}\n\nconst ACTION_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx'])\nconst TEST_FILE_RE = /\\.(test|spec)\\.(ts|tsx|js|jsx)$/\nconst RESERVED_NAMES = new Set(['index', 'constructor', '__proto__', 'prototype', 'hasOwnProperty'])\n\n/**\n * Backward-compatible: original simple-shape scanner used by existing\n * consumers. Preserved verbatim; new consumers should call\n * `scanServerActionsEnriched`.\n */\nexport function scanServerActions(serverDir: string): ActionNode[] {\n const actionsDir = join(serverDir, 'actions')\n if (!existsSync(actionsDir) || !statSync(actionsDir).isDirectory()) {\n return []\n }\n\n const results: ActionNode[] = []\n walkSourceFiles(actionsDir, { extensions: ACTION_EXTENSIONS }, (absPath) => {\n if (TEST_FILE_RE.test(absPath)) return\n let rel = relative(actionsDir, absPath)\n rel = rel.replace(/\\\\/g, '/')\n rel = rel.slice(0, -extname(rel).length)\n results.push({\n filePath: absPath,\n actionPath: rel,\n })\n })\n return results\n}\n\n/**\n * Enriched scan: light AST detection of `accept: 'form'|'json'` + `input:`\n * presence via regex-after-comment-stripping (EC-9). Throws ActionScanError\n * on file/dir name collision (EC-2) or reserved JS identifier names.\n *\n * Output `ActionManifestEntry[]` is sorted by `name` for deterministic\n * `.theokit/actions-manifest.json` emission.\n */\nexport function scanServerActionsEnriched(serverDir: string): ActionManifestEntry[] {\n const actionsDir = join(serverDir, 'actions')\n if (!existsSync(actionsDir) || !statSync(actionsDir).isDirectory()) {\n return []\n }\n\n const seenNames = new Set<string>()\n const entries: ActionManifestEntry[] = []\n\n // Collect first; collision-check after the full walk.\n walkSourceFiles(actionsDir, { extensions: ACTION_EXTENSIONS }, (absPath) => {\n if (TEST_FILE_RE.test(absPath)) return\n const rel = relative(actionsDir, absPath).replace(/\\\\/g, '/')\n // P#4 plugin-forms — `schemas/` subdir holds isomorphic zod schemas\n // for the shared-schema convention (T1.1). NOT executable actions; skip.\n if (rel.startsWith('schemas/')) return\n const name = rel.slice(0, -extname(rel).length)\n\n const basename = name.includes('/') ? (name.split('/').pop() ?? name) : name\n if (RESERVED_NAMES.has(basename)) {\n throw new ActionScanError(\n 'RESERVED_NAME',\n `Reserved JS identifier \"${basename}\" cannot be an action name (${absPath})`,\n [absPath],\n )\n }\n // File-level collision (one file appearing twice) is impossible via the\n // walker; per-export collision check happens inside the export loop below.\n const source = readFileSync(absPath, 'utf8')\n const stripped = stripComments(source)\n const accept = /\\baccept\\s*:\\s*['\"]form['\"]/.test(stripped) ? 'form' : 'json'\n const hasInput = /\\binput\\s*:\\s*z\\./.test(stripped) || /\\binput\\s*:\\s*\\w+\\(/.test(stripped)\n\n // T7.1 wire fix — extract exports so the urlPath includes the second\n // segment required by action-middleware (`/api/__actions/<file>/<export>`).\n // Each named action export becomes its own manifest entry.\n // Proxy key on the EXPORT name (so consumers write `actions.saveMemory(input)`).\n // URL keeps the runtime 2-segment shape `/api/__actions/<file>/<export>`\n // expected by action-middleware. Cross-file export collisions become a\n // scan error to surface the ambiguity early.\n const exportNames = extractActionExportNames(stripped)\n // P#4 plugin-forms shared-schema convention: check for\n // `<actionsDir>/schemas/<basename>.ts` (or .tsx/.js/.jsx).\n // Skip when actions live in subdirs (`schemas/` is flat by convention).\n const schemaFilePath = name.includes('/') ? undefined : detectSchemaFile(actionsDir, basename)\n for (const exportName of exportNames) {\n const proxyKey = exportName === 'default' ? name : exportName\n if (seenNames.has(proxyKey)) {\n throw new ActionScanError(\n 'NAME_COLLISION',\n `Duplicate action proxy key \"${proxyKey}\" (two files export the same name)`,\n [absPath],\n )\n }\n seenNames.add(proxyKey)\n const entry: ActionManifestEntry = {\n name: proxyKey,\n filePath: absPath,\n urlPath: `/api/__actions/${name}/${exportName}`,\n accept,\n hasInput,\n }\n if (schemaFilePath !== undefined) {\n entry.schemaFilePath = schemaFilePath\n }\n entries.push(entry)\n }\n })\n\n // EC-2: detect file vs dir collisions (e.g., foo.ts AND foo/bar.ts).\n // After walk completes, any name that has children prefixed `name/` triggers collision.\n for (const entry of entries) {\n const childPrefix = `${entry.name}/`\n const conflictingChild = entries.find((other) => other.name.startsWith(childPrefix))\n if (conflictingChild) {\n throw new ActionScanError(\n 'NAME_COLLISION',\n `Action \"${entry.name}\" conflicts with directory of same name containing \"${conflictingChild.name}\"`,\n [entry.filePath, conflictingChild.filePath],\n )\n }\n }\n\n entries.sort((a, b) => {\n if (a.name < b.name) return -1\n if (a.name > b.name) return 1\n return 0\n })\n return entries\n}\n\n/**\n * Strip JavaScript line + block comments from source. Simple state machine\n * (does not parse strings — false positives if a comment marker appears\n * inside a string literal, but that's an acceptable trade-off for v1 vs\n * full AST parse).\n */\n/**\n * Extract action export names via regex over comment-stripped source.\n * Matches `export const <name> = defineAction(...)`, `export default\n * defineAction(...)`, and `export function <name>(...)` forms. Returns\n * `['default']` when no named action exports are found (best-effort fallback\n * for default-export shapes the regex misses).\n */\nfunction extractActionExportNames(stripped: string): string[] {\n const names = new Set<string>()\n const namedRe = /\\bexport\\s+(?:const|let|var|function\\*?)\\s+([a-zA-Z_$][\\w$]*)\\s*[=(]/g\n let m: RegExpExecArray | null\n while ((m = namedRe.exec(stripped)) !== null) {\n const name = m[1]\n if (typeof name === 'string' && name.length > 0) names.add(name)\n }\n if (/\\bexport\\s+default\\s+defineAction\\b/.test(stripped)) {\n names.add('default')\n }\n if (names.size === 0) names.add('default')\n return [...names]\n}\n\n/**\n * P#4 plugin-forms shared-schema convention helper (per plan p4-plugin-forms v1.1 T1.1).\n * Returns the resolved path to `<actionsDir>/schemas/<basename>.<ext>` if it exists.\n * Tries `.ts`, `.tsx`, `.js`, `.jsx` in that order. Returns undefined when no match.\n */\nfunction detectSchemaFile(actionsDir: string, basename: string): string | undefined {\n const schemasDir = join(actionsDir, 'schemas')\n if (!existsSync(schemasDir)) return undefined\n for (const ext of ['.ts', '.tsx', '.js', '.jsx']) {\n const candidate = join(schemasDir, `${basename}${ext}`)\n if (existsSync(candidate)) return candidate\n }\n return undefined\n}\n\nfunction stripComments(source: string): string {\n let out = ''\n let i = 0\n while (i < source.length) {\n const ch = source[i]\n const next = source[i + 1]\n if (ch === '/' && next === '/') {\n // Line comment: skip until newline\n while (i < source.length && source[i] !== '\\n') i++\n continue\n }\n if (ch === '/' && next === '*') {\n // Block comment: skip until */\n i += 2\n while (i < source.length - 1 && !(source[i] === '*' && source[i + 1] === '/')) i++\n i += 2\n continue\n }\n out += ch\n i++\n }\n return out\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time scanner: walks directories derived from cwd.\n * No HTTP input ever reaches these fs calls.\n */\nimport { readdirSync } from 'node:fs'\nimport { extname, join, resolve } from 'node:path'\n\n/**\n * Options for walkSourceFiles.\n *\n * Sequential by design — callers (route precedence) depend on insertion\n * order (EC-19 documented decision). Async-callback support is implicit\n * via JavaScript's serial await loop.\n *\n * Tested on macOS + Linux. Windows long-path support not validated (EC-20).\n */\nexport interface WalkOptions {\n /** File extensions to include (e.g., new Set(['.ts', '.tsx'])). */\n extensions: ReadonlySet<string>\n /** Skip directories whose name starts with any of these (default: ['_', '.']). */\n skipPrefixes?: readonly string[]\n}\n\n/**\n * Recursively walk `root`, invoking `onFile(absPath)` for every file matching\n * `opts.extensions`. Directories whose name starts with any `skipPrefixes`\n * char are skipped (defaults to `_` and `.`).\n *\n * Replaces 3 near-identical recursive walkers in scan.ts, action-scan.ts,\n * ws-scan.ts (PV-3 — DRY consolidation). Resolves T3.1 of\n * architecture-review-remediation-plan.\n *\n * Symlink loops are NOT tracked — callers must avoid them or pre-resolve\n * via `fs.realpath`. EC-11 documented but not implemented (rare in dev).\n */\nexport function walkSourceFiles(\n root: string,\n opts: WalkOptions,\n onFile: (absPath: string) => void,\n): void {\n const skipPrefixes = opts.skipPrefixes ?? ['_', '.']\n const visit = (dir: string): void => {\n let entries\n try {\n entries = readdirSync(dir, { withFileTypes: true })\n } catch {\n // Silently skip unreadable directories — caller controls discoverability\n return\n }\n for (const entry of entries) {\n const fullPath = join(dir, entry.name)\n if (entry.isDirectory() && !skipPrefixes.some((p) => entry.name.startsWith(p))) {\n visit(fullPath)\n } else if (entry.isFile() && opts.extensions.has(extname(entry.name))) {\n onFile(resolve(fullPath))\n }\n }\n }\n visit(root)\n}\n"],"mappings":";;;;AAIA,SAAS,YAAY,cAAc,gBAAgB;AACnD,SAAS,WAAAA,UAAS,QAAAC,OAAM,gBAAgB;;;ACDxC,SAAS,mBAAmB;AAC5B,SAAS,SAAS,MAAM,eAAe;AA8BhC,SAAS,gBACd,MACA,MACA,QACM;AACN,QAAM,eAAe,KAAK,gBAAgB,CAAC,KAAK,GAAG;AACnD,QAAM,QAAQ,CAAC,QAAsB;AACnC,QAAI;AACJ,QAAI;AACF,gBAAU,YAAY,KAAK,EAAE,eAAe,KAAK,CAAC;AAAA,IACpD,QAAQ;AAEN;AAAA,IACF;AACA,eAAW,SAAS,SAAS;AAC3B,YAAM,WAAW,KAAK,KAAK,MAAM,IAAI;AACrC,UAAI,MAAM,YAAY,KAAK,CAAC,aAAa,KAAK,CAAC,MAAM,MAAM,KAAK,WAAW,CAAC,CAAC,GAAG;AAC9E,cAAM,QAAQ;AAAA,MAChB,WAAW,MAAM,OAAO,KAAK,KAAK,WAAW,IAAI,QAAQ,MAAM,IAAI,CAAC,GAAG;AACrE,eAAO,QAAQ,QAAQ,CAAC;AAAA,MAC1B;AAAA,IACF;AAAA,EACF;AACA,QAAM,IAAI;AACZ;;;ADjBO,IAAM,kBAAN,cAA8B,MAAM;AAAA,EAChC;AAAA,EACA;AAAA,EAET,YACE,MACA,SACA,kBACA;AACA,UAAM,OAAO;AAIb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,mBAAmB;AAAA,EAC1B;AACF;AAEA,IAAM,oBAAoB,oBAAI,IAAI,CAAC,OAAO,QAAQ,OAAO,MAAM,CAAC;AAChE,IAAM,eAAe;AACrB,IAAM,iBAAiB,oBAAI,IAAI,CAAC,SAAS,eAAe,aAAa,aAAa,gBAAgB,CAAC;AAO5F,SAAS,kBAAkB,WAAiC;AACjE,QAAM,aAAaC,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1
|
-
{"version":3,"sources":["../src/vite-plugin/openapi-emit/emit.ts","../src/vite-plugin/openapi-emit/zod-to-openapi.ts","../src/vite-plugin/openapi-emit/load-routes.ts"],"sourcesContent":["/**\n * In-house `emitOpenApi()` orchestrator (build-time only).\n *\n * Pure transformation: takes a route manifest (already hydrated with Zod\n * schemas extracted from `defineRoute()` config) + the openapi config\n * block, builds an OpenAPI 3.x document, writes `<outDir>/openapi.json`,\n * returns the document for downstream callers (CLI logs, tests).\n *\n * Per G2 plan v1.1 T2.1. Modelled on trpc-openapi's\n * `generateOpenApiDocument` + encore's `Generator.Generate()`.\n *\n * NEVER ship to runtime — devDep-shaped artifact.\n *\n * Path templating: TheoKit's `:param` syntax is converted to OpenAPI's\n * `{param}` per the spec. Env-var override: `THEOKIT_OPENAPI_SERVER_URL`\n * overrides `servers[0].url` without rebuilding the config.\n */\n/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time emit. outDir is a config-controlled relative path. The\n * caller already refused absolute paths via theoConfigSchema.distDir\n * pattern; the openapi.outDir field follows the same convention.\n */\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport type { z } from 'zod'\n\nimport { zodToOpenApiSchema, type ConvertCtx, type OpenApiSchema } from './zod-to-openapi.js'\n\nexport interface OpenApiManifestRoute {\n /** TheoKit-style path with `:param` placeholders (`/users/:id`). */\n routePath: string\n /** Uppercase HTTP methods the route exports (`['GET','POST']`). */\n methods: string[]\n /** Optional `defineRoute({body})` schema. */\n body?: z.ZodType\n /** Optional `defineRoute({query})` schema. */\n query?: z.ZodType\n /** Optional `defineRoute({params})` schema. */\n params?: z.ZodType\n /** Optional `defineRoute({response})` schema. */\n response?: z.ZodType\n}\n\nexport interface OpenApiEmitConfig {\n servers: { url: string; description?: string }[]\n specVersion: '3.1.0' | '3.0.3'\n title: string\n version: string\n outDir: string\n}\n\nexport interface OpenApiOperation {\n operationId?: string\n parameters?: OpenApiParameter[]\n requestBody?: {\n required?: boolean\n content: Record<string, { schema: OpenApiSchema }>\n }\n responses: Record<\n string,\n { description: string; content?: Record<string, { schema: OpenApiSchema }> }\n >\n}\n\nexport interface OpenApiParameter {\n name: string\n in: 'path' | 'query' | 'header' | 'cookie'\n required: boolean\n schema: OpenApiSchema\n description?: string\n}\n\nexport type OpenApiPathItem = Partial<\n Record<'get' | 'post' | 'put' | 'patch' | 'delete' | 'head' | 'options', OpenApiOperation>\n>\n\nexport interface OpenApiDocument {\n openapi: '3.1.0' | '3.0.3'\n info: { title: string; version: string }\n servers: { url: string; description?: string }[]\n paths: Record<string, OpenApiPathItem>\n components?: { schemas?: Record<string, OpenApiSchema> }\n}\n\nexport interface EmitOpenApiInput {\n manifest: OpenApiManifestRoute[]\n config: OpenApiEmitConfig\n}\n\nexport interface EmitOpenApiResult {\n document: OpenApiDocument\n path: string\n}\n\nconst METHOD_TO_KEY: Record<string, keyof OpenApiPathItem> = {\n GET: 'get',\n POST: 'post',\n PUT: 'put',\n PATCH: 'patch',\n DELETE: 'delete',\n HEAD: 'head',\n OPTIONS: 'options',\n}\n\n/** Convert `/users/:id/posts/:postId?` → `/users/{id}/posts/{postId}`. */\nexport function templatePath(routePath: string): string {\n // Bounded quantifier (\\w{0,64}) is OSS-safe — TheoKit route param names\n // never exceed 64 chars in practice; cap prevents super-linear backtracking.\n return routePath.replace(/:([A-Za-z_]\\w{0,64})\\??/g, '{$1}')\n}\n\nfunction buildParameters(\n paramsSchema: z.ZodType | undefined,\n querySchema: z.ZodType | undefined,\n ctx: ConvertCtx,\n): OpenApiParameter[] {\n const out: OpenApiParameter[] = []\n if (paramsSchema !== undefined) {\n appendObjectAsParameters(paramsSchema, 'path', out, ctx)\n }\n if (querySchema !== undefined) {\n appendObjectAsParameters(querySchema, 'query', out, ctx)\n }\n return out\n}\n\nfunction appendObjectAsParameters(\n schema: z.ZodType,\n location: 'path' | 'query',\n out: OpenApiParameter[],\n ctx: ConvertCtx,\n): void {\n // We expect an object schema; if it's not, skip silently (caller already\n // validated upstream when scanning defineRoute()).\n const shape = (schema as unknown as { shape?: Record<string, z.ZodType> }).shape\n if (shape === undefined) return\n for (const [name, child] of Object.entries(shape)) {\n const childDef = (child as unknown as { _def: { typeName?: string } })._def\n const optional = childDef.typeName === 'ZodOptional' || childDef.typeName === 'ZodDefault'\n out.push({\n name,\n in: location,\n required: location === 'path' ? true : !optional,\n schema: zodToOpenApiSchema(child, { ctx }),\n })\n }\n}\n\nfunction buildOperation(\n route: OpenApiManifestRoute,\n ctx: ConvertCtx,\n method: string,\n): OpenApiOperation {\n // Bounded sanitizer: two single-pass replacements (no nested quantifiers).\n const sanitized = route.routePath.replace(/[/:\\-{}]/g, '_').replace(/_+/g, '_')\n const operationId = `${method.toLowerCase()}_${sanitized.replace(/^_|_$/g, '')}`\n const op: OpenApiOperation = {\n operationId,\n responses: {\n '200': { description: 'OK' },\n },\n }\n\n const parameters = buildParameters(route.params, route.query, ctx)\n if (parameters.length > 0) op.parameters = parameters\n\n // Body only meaningful for write methods; we still attach if defined so\n // the document is honest about the contract.\n if (route.body !== undefined) {\n op.requestBody = {\n required: true,\n content: {\n 'application/json': { schema: zodToOpenApiSchema(route.body, { ctx }) },\n },\n }\n }\n\n if (route.response !== undefined) {\n op.responses['200'] = {\n description: 'OK',\n content: {\n 'application/json': { schema: zodToOpenApiSchema(route.response, { ctx }) },\n },\n }\n }\n\n return op\n}\n\nexport function emitOpenApi(input: EmitOpenApiInput): EmitOpenApiResult {\n const { manifest, config } = input\n\n const ctx: ConvertCtx = { seen: new Map(), components: {} }\n\n const paths: Record<string, OpenApiPathItem> = {}\n for (const route of manifest) {\n const templatedPath = templatePath(route.routePath)\n const item: OpenApiPathItem = paths[templatedPath] ?? {}\n for (const method of route.methods) {\n // Defensive: manifest emitter normalizes to uppercase, but if a\n // future scanner produces a non-HTTP verb the key lookup yields\n // undefined and we skip silently. TS narrows the indexed type to\n // keyof OpenApiPathItem; the runtime undefined check is honest.\n const key = METHOD_TO_KEY[method.toUpperCase()] as keyof OpenApiPathItem | undefined\n if (key === undefined) continue\n item[key] = buildOperation(route, ctx, method)\n }\n paths[templatedPath] = item\n }\n\n const servers = applyServerOverride(config.servers)\n\n const document: OpenApiDocument = {\n openapi: config.specVersion,\n info: { title: config.title, version: config.version },\n servers,\n paths,\n }\n\n if (Object.keys(ctx.components).length > 0) {\n document.components = { schemas: ctx.components }\n }\n\n mkdirSync(config.outDir, { recursive: true })\n const outPath = join(config.outDir, 'openapi.json')\n writeFileSync(outPath, `${JSON.stringify(document, null, 2)}\\n`, 'utf8')\n\n return { document, path: outPath }\n}\n\nfunction applyServerOverride(\n servers: { url: string; description?: string }[],\n): { url: string; description?: string }[] {\n const override = process.env.THEOKIT_OPENAPI_SERVER_URL\n if (override === undefined || override === '') return servers\n if (servers.length === 0) return [{ url: override }]\n const [first, ...rest] = servers\n return [\n {\n url: override,\n ...(first.description !== undefined ? { description: first.description } : {}),\n },\n ...rest,\n ]\n}\n","/**\n * Zod → OpenAPI 3.0 Schema converter (build-time only).\n *\n * Uses Zod v4's native `z.toJSONSchema()` and post-processes\n * the JSON Schema output into OpenAPI 3.0 format:\n * - Removes `$schema` (invalid in OpenAPI 3.0)\n * - Converts `type: [\"string\", \"null\"]` → `{ type: \"string\", nullable: true }`\n * - Recursively normalizes nested schemas\n *\n * NEVER ship to runtime — devDep-shaped artifact.\n */\nimport { z } from 'zod'\n\nexport interface OpenApiSchema {\n type?: 'string' | 'number' | 'integer' | 'boolean' | 'array' | 'object' | 'null'\n format?: string\n items?: OpenApiSchema\n properties?: Record<string, OpenApiSchema>\n required?: string[]\n additionalProperties?: boolean | OpenApiSchema\n oneOf?: OpenApiSchema[]\n anyOf?: OpenApiSchema[]\n allOf?: OpenApiSchema[]\n discriminator?: { propertyName: string; mapping?: Record<string, string> }\n enum?: unknown[]\n nullable?: boolean\n description?: string\n default?: unknown\n $ref?: string\n}\n\nexport interface ConvertCtx {\n seen: Map<z.ZodType, string>\n components: Record<string, OpenApiSchema>\n}\n\nexport interface ConvertOptions {\n ctx?: ConvertCtx\n name?: string\n}\n\nexport class ZodToOpenApiError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ZodToOpenApiError'\n }\n}\n\nexport function zodToOpenApiSchema(schema: z.ZodType, options: ConvertOptions = {}): OpenApiSchema {\n const ctx: ConvertCtx = options.ctx ?? { seen: new Map(), components: {} }\n\n const name = options.name\n if (name !== undefined) {\n if (Object.prototype.hasOwnProperty.call(ctx.components, name)) {\n return { $ref: `#/components/schemas/${name}` }\n }\n ctx.seen.set(schema, name)\n ctx.components[name] = {}\n const body = convertSchema(schema, ctx)\n ctx.components[name] = body\n return { $ref: `#/components/schemas/${name}` }\n }\n\n return convertSchema(schema, ctx)\n}\n\nfunction convertSchema(schema: z.ZodType, ctx: ConvertCtx): OpenApiSchema {\n const existing = ctx.seen.get(schema)\n if (existing !== undefined) {\n return { $ref: `#/components/schemas/${existing}` }\n }\n\n try {\n const jsonSchema = z.toJSONSchema(schema) as Record<string, unknown>\n return toOpenApi3(jsonSchema)\n } catch {\n return {}\n }\n}\n\n/**\n * Post-process JSON Schema (draft-2020-12) → OpenAPI 3.0.\n * Handles:\n * - $schema removal\n * - nullable conversion\n * - Recursive normalization of properties/items/anyOf/oneOf/allOf\n */\nfunction toOpenApi3(js: Record<string, unknown>): OpenApiSchema {\n const { $schema: _, $defs: _defs, ...rest } = js\n const out: Record<string, unknown> = {}\n\n for (const [key, value] of Object.entries(rest)) {\n if (key === 'type' && Array.isArray(value)) {\n const types = value as string[]\n const hasNull = types.includes('null')\n const nonNull = types.filter((t: string) => t !== 'null')\n out.type = nonNull.length === 1 ? nonNull[0] : nonNull\n if (hasNull) out.nullable = true\n } else if (key === 'properties' && value && typeof value === 'object') {\n const props: Record<string, OpenApiSchema> = {}\n for (const [pk, pv] of Object.entries(value as Record<string, unknown>)) {\n props[pk] = pv && typeof pv === 'object' ? toOpenApi3(pv as Record<string, unknown>) : (pv as OpenApiSchema)\n }\n out.properties = props\n } else if (key === 'items' && value && typeof value === 'object') {\n out.items = toOpenApi3(value as Record<string, unknown>)\n } else if ((key === 'anyOf' || key === 'oneOf' || key === 'allOf') && Array.isArray(value)) {\n out[key] = (value as Record<string, unknown>[]).map((v) => toOpenApi3(v))\n } else if (key === 'additionalProperties' && value && typeof value === 'object') {\n out.additionalProperties = toOpenApi3(value as Record<string, unknown>)\n } else {\n out[key] = value\n }\n }\n\n return out as OpenApiSchema\n}\n","/**\n * Build-time route loader for OpenAPI emit.\n *\n * Takes the G1 manifest (filePath + routePath + methods) and hydrates each\n * route's Zod schemas by dynamically importing the module. `defineRoute`\n * is an identity function, so the imported config exposes `body/query/\n * params/response` directly without any AST gymnastics.\n *\n * Supports both export shapes:\n * 1. `export const POST = defineRoute({...})` (per-method named exports)\n * 2. `export default defineRoute({...})` (single-export legacy shape)\n *\n * Per G2 plan v1.1 T2.2. Uses Vite's `ssrLoadModule` because route files\n * are TS at build time — Node's native loader doesn't transpile.\n */\nimport { resolve } from 'node:path'\n\nimport type { z } from 'zod'\n\nimport type { ManifestRoute } from '../../server/scan/manifest.js'\n\nimport type { OpenApiManifestRoute } from './emit.js'\n\ninterface RouteConfigShape {\n body?: z.ZodType\n query?: z.ZodType\n params?: z.ZodType\n response?: z.ZodType\n}\n\ninterface ViteLikeServer {\n ssrLoadModule: (id: string) => Promise<Record<string, unknown>>\n close: () => Promise<void>\n}\n\ninterface DefaultLoader {\n load: (absPath: string) => Promise<Record<string, unknown>>\n dispose: () => Promise<void>\n}\n\n/** Method names recognized as per-route named exports (UPPERCASE). */\nconst HTTP_METHOD_KEYS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'] as const\n\nexport interface LoadRoutesOptions {\n serverDir: string\n routes: ManifestRoute[]\n /** Injectable for tests; defaults to a fresh Vite SSR dev server. */\n loadModule?: (absPath: string) => Promise<Record<string, unknown>>\n}\n\n/**\n * Hydrate manifest routes with Zod schemas extracted from their modules.\n *\n * Returns one `OpenApiManifestRoute` per (file × method) tuple. If a route\n * file declares multiple methods (`GET` + `POST`), each method gets its\n * own entry with the schemas from that method's `defineRoute()` call.\n *\n * Routes that fail to load are skipped with a console warning — the emit\n * should be best-effort, not a hard build failure.\n *\n * The default Vite loader is created once per call and disposed in the\n * `finally` block so the underlying server is released even when route\n * loading throws.\n */\nexport async function loadRoutesForOpenApi(\n options: LoadRoutesOptions,\n): Promise<OpenApiManifestRoute[]> {\n const { serverDir, routes } = options\n let loadModule = options.loadModule\n let dispose: (() => Promise<void>) | undefined\n if (loadModule === undefined) {\n const created = await createDefaultLoader(serverDir)\n loadModule = created.load\n dispose = created.dispose\n }\n\n const out: OpenApiManifestRoute[] = []\n try {\n for (const r of routes) {\n const abs = resolve(serverDir, r.filePath)\n let mod: Record<string, unknown>\n try {\n mod = await loadModule(abs)\n } catch (err) {\n console.warn(\n `[openapi-emit] Skipping ${r.filePath}: load failed (${(err as Error).message})`,\n )\n continue\n }\n\n const methods = r.methods ?? HTTP_METHOD_KEYS.filter((m) => mod[m] !== undefined)\n if (methods.length === 0) {\n // Fall back to default export when no method-named exports detected.\n const def = mod.default\n if (def !== undefined && def !== null) {\n out.push({ routePath: r.routePath, methods: ['GET'], ...extractSchemas(def) })\n }\n continue\n }\n\n for (const method of methods) {\n const handler = mod[method] ?? mod.default\n if (handler === undefined || handler === null) continue\n out.push({ routePath: r.routePath, methods: [method], ...extractSchemas(handler) })\n }\n }\n } finally {\n if (dispose !== undefined) {\n await dispose()\n }\n }\n return out\n}\n\nfunction extractSchemas(handlerExport: unknown): RouteConfigShape {\n if (typeof handlerExport !== 'object' || handlerExport === null) return {}\n const cfg = handlerExport as RouteConfigShape\n const out: RouteConfigShape = {}\n if (cfg.body !== undefined) out.body = cfg.body\n if (cfg.query !== undefined) out.query = cfg.query\n if (cfg.params !== undefined) out.params = cfg.params\n if (cfg.response !== undefined) out.response = cfg.response\n return out\n}\n\n/**\n * Default loader: spin up a minimal Vite SSR dev server (no HMR, no\n * middlewares) just to use its `ssrLoadModule`. Vite handles TS, ESM, and\n * import resolution for free.\n *\n * Returns `{load, dispose}` — the caller owns the lifecycle and MUST\n * call `dispose()` (typically in a `finally`) so the server is closed.\n */\nasync function createDefaultLoader(serverDir: string): Promise<DefaultLoader> {\n // Vite is a peerDep in build flows; import dynamically.\n const { createServer } = await import('vite')\n const server = (await createServer({\n root: serverDir,\n configFile: false,\n server: { middlewareMode: true },\n appType: 'custom',\n logLevel: 'silent',\n })) as unknown as ViteLikeServer\n\n const swallow = (): void => {\n /* eat close errors — best-effort cleanup */\n }\n return {\n load: async (absPath) => server.ssrLoadModule(absPath),\n dispose: async () => {\n await server.close().catch(swallow)\n },\n }\n}\n"],"mappings":";;;;AAsBA,SAAS,WAAW,qBAAqB;AACzC,SAAS,YAAY;;;ACZrB,SAAS,SAAS;AAqCX,SAAS,mBAAmB,QAAmB,UAA0B,CAAC,GAAkB;AACjG,QAAM,MAAkB,QAAQ,OAAO,EAAE,MAAM,oBAAI,IAAI,GAAG,YAAY,CAAC,EAAE;AAEzE,QAAM,OAAO,QAAQ;AACrB,MAAI,SAAS,QAAW;AACtB,QAAI,OAAO,UAAU,eAAe,KAAK,IAAI,YAAY,IAAI,GAAG;AAC9D,aAAO,EAAE,MAAM,wBAAwB,IAAI,GAAG;AAAA,IAChD;AACA,QAAI,KAAK,IAAI,QAAQ,IAAI;AACzB,QAAI,WAAW,IAAI,IAAI,CAAC;AACxB,UAAM,OAAO,cAAc,QAAQ,GAAG;AACtC,QAAI,WAAW,IAAI,IAAI;AACvB,WAAO,EAAE,MAAM,wBAAwB,IAAI,GAAG;AAAA,EAChD;AAEA,SAAO,cAAc,QAAQ,GAAG;AAClC;AAEA,SAAS,cAAc,QAAmB,KAAgC;AACxE,QAAM,WAAW,IAAI,KAAK,IAAI,MAAM;AACpC,MAAI,aAAa,QAAW;AAC1B,WAAO,EAAE,MAAM,wBAAwB,QAAQ,GAAG;AAAA,EACpD;AAEA,MAAI;AACF,UAAM,aAAa,EAAE,aAAa,MAAM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
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/services/adapters-bridge/adapter-support.ts","../src/services/generators/caddy-generator.ts","../src/services/generators/compose-generator.ts","../src/services/generators/openapi-client-gen.ts","../src/services/adapters-bridge/manifest.ts","../src/services/schema.ts","../src/services/runtime/orchestrator.ts","../src/services/runtime/healthcheck-poller.ts","../src/services/runtime/log-merge.ts","../src/services/runtime/process-spawn-helpers.ts","../src/services/adapters-bridge/theo-cloud-adapter-stub.ts","../src/services/adapters-bridge/vite-proxy-builder.ts"],"sourcesContent":["/**\n * Adapter support gates (Wave 2 — TheoCloud-first focus).\n *\n * Wave 2 SUPPORTS polyglot `services: {}` on TWO targets ONLY:\n * - `node` (local docker-compose harness — TheoCloud-shaped)\n * - `theo-cloud` (the principal deploy target — Wave 3 adapter)\n *\n * All other in-tree deploy adapters (vercel, cloudflare, bun, deno-deploy,\n * aws-lambda, netlify, static) ARE STILL FIRST-CLASS DEPLOY TARGETS for\n * the TS app, but `services: {}` Wave 2 is NOT yet wired through them.\n * They reject loudly with an actionable message when the manifest has\n * non-empty services — pointing the user at `node` (local) or TheoCloud.\n *\n * Per owner decision 2026-05-27: TheoKit's polyglot services energy is\n * 100% TheoCloud; Vercel/Cloudflare/etc. polyglot-services wire-ups are\n * out of Wave 2 scope and deferred to fresh ADRs if demand emerges.\n */\nimport type { ServicesManifest } from './manifest.js'\n\nconst SUPPORTED_IN_WAVE_2 = ['node (local)', 'theo-cloud (Wave 3)'] as const\n\n/**\n * Reject if the adapter does not support polyglot services. Adapters\n * outside `node` + `theo-cloud` call this; the message points to the\n * supported alternatives.\n *\n * Throws when manifest has non-empty services. No-op when manifest is null\n * or empty (Wave 1 BC — the app still deploys, just without sidecars).\n */\nexport function assertServicesUnsupported(\n adapterName: string,\n manifest: ServicesManifest | null,\n): void {\n if (!manifest || manifest.services.length === 0) return\n const names = manifest.services.map((s) => s.name).join(', ')\n throw new Error(\n `Adapter '${adapterName}' does not support polyglot services in Wave 2.\\n` +\n `Detected services in theo.config.ts: ${names}.\\n\\n` +\n `Wave 2 supports: ${SUPPORTED_IN_WAVE_2.join(', ')}.\\n` +\n `TheoCloud is the strategic deploy target — the adapter ships in Wave 3.\\n` +\n `For local dev/prod-like validation today, use \\`theokit build --target node\\`\\n` +\n `(emits docker-compose + Caddyfile — TheoCloud-shaped harness).\\n\\n` +\n `See docs/concepts/services.md.`,\n )\n}\n","/**\n * Caddyfile generator (T3.3).\n *\n * Emits a Caddyfile that fronts the TheoKit web app + declared services\n * with W3C trace context propagation enabled (Caddy 2.11+ `tracing` directive).\n *\n * Generated output sits at `<dist>/.theokit/node/Caddyfile`, consumed by the\n * docker-compose stack (T3.3 compose-generator).\n *\n * EC-23: `reverse_proxy` directives are ordered by prefix length DESC.\n * Caddy matches longest-prefix-first when written in order.\n */\nimport type { ServicesManifest } from '../adapters-bridge/manifest.js'\n\nexport interface CaddyfileOptions {\n /** Port Caddy listens on (TheoKit web port; default 3000). */\n port: number\n /** TheoKit web container hostname (compose service name). Default 'web'. */\n webHost: string\n}\n\nfunction reverseProxyLines(servicePath: string, target: string, cors: boolean): string[] {\n const out = [`\\treverse_proxy ${servicePath}* ${target}`]\n if (cors) {\n out.push(\n `\\theader ${servicePath}* Access-Control-Allow-Origin \"*\"`,\n `\\theader ${servicePath}* Access-Control-Allow-Methods \"GET, POST, PUT, DELETE, OPTIONS\"`,\n `\\theader ${servicePath}* Access-Control-Allow-Headers \"Content-Type, Authorization, traceparent, tracestate, baggage\"`,\n )\n }\n return out\n}\n\nexport function generateCaddyfile(\n manifest: ServicesManifest | null,\n options: CaddyfileOptions,\n): string {\n // EC-23: sort services by proxy prefix length DESC so longest matches first\n const services = (manifest?.services ?? [])\n .slice()\n .sort((a, b) => b.proxy.length - a.proxy.length)\n\n const serviceLines = services.flatMap((svc) =>\n reverseProxyLines(svc.proxy, `${svc.name}:${String(svc.port)}`, svc.cors),\n )\n\n const lines: string[] = [\n `:${String(options.port)} {`,\n `\\t# W3C Trace Context propagation (Caddy 2.11+)`,\n `\\ttracing`,\n `\\theader -Server`,\n ...serviceLines,\n `\\treverse_proxy ${options.webHost}:${String(options.port)}`,\n `}`,\n '',\n ]\n return lines.join('\\n')\n}\n","/**\n * docker-compose.yml generator (T3.3).\n *\n * Emits the \"TheoCloud-shaped\" local harness — Caddy ingress in front of\n * web + declared services. Each service has a healthcheck and Caddy\n * `depends_on: service_healthy`.\n *\n * Used by the Node adapter: `theokit build --target node` writes the\n * compose stack to `.theokit/node/docker-compose.yml`.\n */\nimport type { ManifestServiceEntry, ServicesManifest } from '../adapters-bridge/manifest.js'\n\nexport interface ComposeOptions {\n /** Port for the web container (TheoKit). Default 3000. */\n webPort: number\n /** Caddy listening port (default same as webPort — Caddy fronts everything). */\n caddyPort?: number\n /** Project name (compose file `name:` field). */\n projectName?: string\n}\n\nfunction indent(level: number): string {\n return ' '.repeat(level)\n}\n\nfunction healthcheckLines(svc: ManifestServiceEntry): string[] {\n const checker =\n svc.runtime === 'python'\n ? `curl -f http://localhost:${String(svc.port)}${svc.healthcheck} || exit 1`\n : `wget --spider -q http://localhost:${String(svc.port)}${svc.healthcheck} || exit 1`\n return [\n `${indent(2)}healthcheck:`,\n `${indent(3)}test: [\"CMD-SHELL\", \"${checker}\"]`,\n `${indent(3)}interval: 10s`,\n `${indent(3)}timeout: 5s`,\n `${indent(3)}retries: 3`,\n ]\n}\n\nfunction envLines(env: Record<string, string>): string[] {\n const lines: string[] = [`${indent(2)}environment:`]\n for (const [k, v] of Object.entries(env)) {\n lines.push(`${indent(3)}${k}: ${JSON.stringify(v)}`)\n }\n return lines\n}\n\nfunction serviceBlockLines(svc: ManifestServiceEntry): string[] {\n // EC-8: auto-inject convention env vars in the container too\n const env: Record<string, string> = {\n THEOKIT_SERVICE_NAME: svc.name,\n THEOKIT_SERVICE_PORT: String(svc.port),\n ...(svc.env ?? {}),\n }\n return [\n `${indent(1)}${svc.name}:`,\n `${indent(2)}build:`,\n `${indent(3)}context: ./services/${svc.name}`,\n `${indent(2)}expose:`,\n `${indent(3)}- \"${String(svc.port)}\"`,\n ...envLines(env),\n ...healthcheckLines(svc),\n ]\n}\n\nfunction caddyBlockLines(caddyPort: number, services: ManifestServiceEntry[]): string[] {\n const depends: string[] = [\n `${indent(2)}depends_on:`,\n `${indent(3)}web:`,\n `${indent(4)}condition: service_healthy`,\n ]\n for (const svc of services) {\n depends.push(`${indent(3)}${svc.name}:`, `${indent(4)}condition: service_healthy`)\n }\n return [\n `${indent(1)}caddy:`,\n `${indent(2)}image: caddy:2.11`,\n `${indent(2)}ports:`,\n `${indent(3)}- \"${String(caddyPort)}:${String(caddyPort)}\"`,\n `${indent(2)}volumes:`,\n `${indent(3)}- ./Caddyfile:/etc/caddy/Caddyfile:ro`,\n ...depends,\n ]\n}\n\nfunction webBlockLines(webPort: number): string[] {\n return [\n `${indent(1)}web:`,\n `${indent(2)}build:`,\n `${indent(3)}context: .`,\n `${indent(3)}dockerfile: Dockerfile`,\n `${indent(2)}expose:`,\n `${indent(3)}- \"${String(webPort)}\"`,\n `${indent(2)}healthcheck:`,\n `${indent(3)}test: [\"CMD-SHELL\", \"wget --spider -q http://localhost:${String(webPort)}/api/health || exit 1\"]`,\n `${indent(3)}interval: 10s`,\n `${indent(3)}timeout: 5s`,\n `${indent(3)}retries: 3`,\n ]\n}\n\nexport function generateComposeYaml(\n manifest: ServicesManifest | null,\n options: ComposeOptions,\n): string {\n const services = manifest?.services ?? []\n const webPort = options.webPort\n const caddyPort = options.caddyPort ?? webPort\n\n const projectLines = options.projectName ? [`name: ${options.projectName}`] : []\n\n const lines: string[] = [\n ...projectLines,\n `services:`,\n ...caddyBlockLines(caddyPort, services),\n ...webBlockLines(webPort),\n ...services.flatMap(serviceBlockLines),\n '',\n ]\n return lines.join('\\n')\n}\n","/**\n * OpenAPI → TypeScript client generation (T5.1).\n *\n * Thin wrapper around `@hey-api/openapi-ts` (the de facto 2026 generator\n * used by Vercel/OpenCode/PayPal). Called by the Vite plugin\n * `services-typed-client.ts` at dev startup and when an OpenAPI URL\n * changes.\n *\n * Production behavior:\n * - For each service with a `openapi` URL, fetch the spec\n * - Run Hey API generator to write `<cwd>/clients/<service-name>.ts`\n * - On any failure: log warning, do NOT crash dev (best-effort)\n *\n * The actual `@hey-api/openapi-ts` invocation is dynamic-imported so\n * that consumers without the dep (TS-only Wave 1 apps) don't pay\n * the bundle cost.\n */\nimport type { ManifestServiceEntry } from '../adapters-bridge/manifest.js'\n\nexport interface GenerateClientOptions {\n service: ManifestServiceEntry\n /** Directory to write `<service-name>.ts` into. */\n outputDir: string\n /** Logger for warnings/info. */\n log?: (level: 'info' | 'warn' | 'error', msg: string) => void\n /** Test injection — replace fetch (so tests don't hit the network). */\n customFetch?: typeof fetch\n}\n\nexport interface GenerateClientResult {\n generated: boolean\n outputFile?: string\n skippedReason?: string\n}\n\n/**\n * Generate a typed client for one service. No-op (returns skipped=true)\n * if the service has no `openapi` URL.\n *\n * The generator runs the Hey API tool. If the tool import fails (not\n * installed), the function logs a warning and returns `{ generated: false }`.\n */\nexport async function generateTypedClient(\n options: GenerateClientOptions,\n): Promise<GenerateClientResult> {\n const log =\n options.log ??\n ((_level: 'info' | 'warn' | 'error', _msg: string) => {\n // default: silent in production; tests inject their own\n })\n const { service, outputDir } = options\n\n if (!service.openapi) {\n return { generated: false, skippedReason: 'no openapi URL declared' }\n }\n\n const f = options.customFetch ?? fetch\n let spec: unknown\n try {\n const res = await f(service.openapi)\n if (!res.ok) {\n log('warn', `[${service.name}] openapi fetch returned ${String(res.status)}; skipping`)\n return { generated: false, skippedReason: `fetch returned ${String(res.status)}` }\n }\n spec = await res.json()\n } catch (err) {\n log(\n 'warn',\n `[${service.name}] openapi fetch failed: ${err instanceof Error ? err.message : String(err)}`,\n )\n return { generated: false, skippedReason: 'fetch failed' }\n }\n\n // Dynamic import — soft dep. We pass through a variable so the typechecker\n // doesn't resolve the literal at build time (the dep is optional;\n // consumers without it get a graceful skip).\n let createClient: unknown\n try {\n // Soft-dep resolution. We pass the module name through a String wrapper\n // call site that the typechecker cannot statically resolve — so missing\n // dep at typecheck time does not break the build. Runtime behavior is\n // identical to `import('@hey-api/openapi-ts')`.\n const segment1 = '@hey-api/'\n const segment2 = 'openapi-ts'\n const moduleName = `${segment1}${segment2}`\n const dyn: Promise<unknown> = import(moduleName).catch(() => null)\n const mod = (await dyn) as { createClient?: unknown } | null\n createClient = mod?.createClient\n } catch {\n createClient = undefined\n }\n\n if (typeof createClient !== 'function') {\n log(\n 'warn',\n `[${service.name}] @hey-api/openapi-ts not installed; typed client not generated. ` +\n `Run \\`pnpm add -D @hey-api/openapi-ts @hey-api/client-fetch\\` to enable.`,\n )\n return { generated: false, skippedReason: 'hey-api not installed' }\n }\n\n const outputFile = `${outputDir}/${service.name}.ts`\n try {\n await (createClient as (cfg: unknown) => Promise<unknown>)({\n input: spec,\n output: { path: outputDir, format: 'prettier' },\n plugins: [{ name: '@hey-api/client-fetch' }],\n })\n log('info', `[${service.name}] typed client generated at ${outputFile}`)\n return { generated: true, outputFile }\n } catch (err) {\n log(\n 'warn',\n `[${service.name}] Hey API generation failed: ${err instanceof Error ? err.message : String(err)}`,\n )\n return { generated: false, skippedReason: 'generator threw' }\n }\n}\n","/**\n * Neutral cross-product manifest (T1.4).\n *\n * Emitted by `theokit build` at `<cwd>/.theokit/services.json` (schemaVersion 1).\n * Consumed by EVERY deploy adapter (Vercel, Node, Cloudflare, future TheoCloud).\n *\n * Shape is INTENTIONALLY platform-neutral (ADR-0015 invariant + D5). No\n * `vercel`/`cloudflare`/`theoCloud` keys — platform-specific tuning lives in\n * `theo.config.ts` and is read by each adapter's own code, NOT serialized\n * into this manifest.\n *\n * Topological ordering enforced (dependsOn-resolved deps first) so adapters\n * that need boot order (docker-compose, K8s) can consume the array verbatim.\n */\n/* eslint-disable security/detect-non-literal-fs-filename --\n * Manifest read/write paths are derived from the trusted `cwd` plus a fixed\n * subpath (`.theokit/services.json`). No user input flows into the path.\n */\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\nimport type { ServiceDefinition, ServicesConfig } from '../schema.js'\n\n/**\n * Plan v1.2 T2.2 — service shape enum, mirrored from\n * `theo-cloud/api/internal/source/services.schema.json`. Optional in\n * services.json v2; TheoCloud Go-side defaults to `server` when absent.\n */\nexport type ManifestServiceType = 'server' | 'worker' | 'frontend'\n\nexport interface ManifestServiceEntry {\n name: string\n runtime: 'python' | 'node'\n /** Plan v1.2 T2.2 — service shape. Omit to keep default `server`. */\n type?: ManifestServiceType\n port: number\n proxy: string\n dev: string\n build?: string\n start: string\n openapi?: string\n healthcheck: string\n cors: boolean\n env?: Record<string, string>\n dependsOn?: string[]\n passSetCookie: boolean\n}\n\n/**\n * Plan v1.2 T2.1 — services.json now ships in 2 shapes:\n *\n * v1 (deprecated, sunset theokit 0.6.0): { version: 1, services: [...] }\n * v2 (current): { version: 2, project: <name>, services: [...] }\n *\n * `buildManifest()` selects which version to emit based on whether a\n * project name is supplied. Consumers (TheoCloud Go-side validator)\n * accept both via the JSON Schema 7 `oneOf` block.\n */\nexport interface ServicesManifestV1 {\n version: 1\n services: ManifestServiceEntry[]\n}\n\nexport interface ServicesManifestV2 {\n version: 2\n project: string\n services: ManifestServiceEntry[]\n}\n\nexport type ServicesManifest = ServicesManifestV1 | ServicesManifestV2\n\nconst MANIFEST_RELATIVE_PATH = ['.theokit', 'services.json'] as const\n\n/**\n * Topological sort using Kahn's algorithm.\n * Returns service names in dependency order (deps before dependants).\n * Schema validation guarantees no cycles, no self-deps, no missing references —\n * but we still defensively handle missing deps as no-op.\n */\nfunction topoSort(services: ServicesConfig): string[] {\n const names = Object.keys(services)\n const indeg: Record<string, number> = Object.fromEntries(names.map((n) => [n, 0]))\n const adj: Record<string, string[]> = Object.fromEntries(names.map((n) => [n, []]))\n\n const cmp = (a: string, b: string) => a.localeCompare(b)\n\n for (const name of names) {\n const deps = services[name].dependsOn ?? []\n for (const dep of deps) {\n if (!(dep in indeg)) continue\n adj[dep].push(name)\n indeg[name] = (indeg[name] ?? 0) + 1\n }\n }\n\n // Sort initial roots for determinism\n const queue: string[] = names.filter((n) => indeg[n] === 0).sort(cmp)\n const result: string[] = []\n while (queue.length > 0) {\n const cur = queue.shift()\n if (cur === undefined) break\n result.push(cur)\n const adjacent = (adj[cur] ?? []).slice().sort(cmp)\n for (const next of adjacent) {\n indeg[next] = (indeg[next] ?? 0) - 1\n if (indeg[next] === 0) {\n queue.push(next)\n }\n }\n }\n return result.length === names.length ? result : names // fallback (should not hit; schema rejects cycles)\n}\n\nfunction definitionToEntry(name: string, def: ServiceDefinition): ManifestServiceEntry {\n const entry: ManifestServiceEntry = {\n name,\n runtime: def.runtime,\n port: def.port,\n proxy: def.proxy,\n dev: def.dev,\n start: def.start,\n healthcheck: def.healthcheck,\n cors: def.cors,\n passSetCookie: def.passSetCookie,\n }\n // Plan v1.2 T2.2 — only emit `type` when explicitly set so v1 fixtures\n // (no type field at all) stay byte-identical.\n if (def.type !== undefined) entry.type = def.type\n if (def.build !== undefined) entry.build = def.build\n if (def.openapi !== undefined) entry.openapi = def.openapi\n if (def.env !== undefined) entry.env = def.env\n if (def.dependsOn !== undefined) entry.dependsOn = [...def.dependsOn]\n return entry\n}\n\n/**\n * Build a services manifest. Plan v1.2 T2.1: pass a `project` name to emit\n * v2; omit it to emit v1 (deprecated, accepted by TheoCloud until 0.6.0\n * sunset).\n */\nexport function buildManifest(services: ServicesConfig, project?: string): ServicesManifest {\n const ordered = topoSort(services)\n const entries = ordered.map((name) => definitionToEntry(name, services[name]))\n if (project !== undefined && project.length > 0) {\n return { version: 2, project, services: entries }\n }\n return { version: 1, services: entries }\n}\n\nfunction manifestPath(cwd: string): string {\n return join(cwd, ...MANIFEST_RELATIVE_PATH)\n}\n\n/**\n * Write the manifest to `<cwd>/.theokit/services.json`.\n *\n * EC-6 fix: creates `.theokit/` recursively if absent (fresh project on first\n * `pnpm build` would otherwise hit ENOENT).\n */\nexport function writeManifest(cwd: string, manifest: ServicesManifest): void {\n const file = manifestPath(cwd)\n mkdirSync(dirname(file), { recursive: true })\n writeFileSync(file, JSON.stringify(manifest, null, 2), 'utf-8')\n}\n\n/**\n * Read the manifest from `<cwd>/.theokit/services.json`.\n *\n * Returns null if the file does not exist (adapter's job to handle).\n * Throws with an actionable message if the file is malformed JSON.\n */\nexport function readManifest(cwd: string): ServicesManifest | null {\n const file = manifestPath(cwd)\n if (!existsSync(file)) return null\n const raw = readFileSync(file, 'utf-8')\n try {\n return JSON.parse(raw) as ServicesManifest\n } catch (err) {\n throw new Error(\n `failed to parse services.json at ${file}: ${\n err instanceof Error ? err.message : String(err)\n }`,\n )\n }\n}\n","/**\n * Wave 2 — Polyglot Services Orchestration (T1.1).\n *\n * Declarative `services: {}` primitive for `theo.config.ts`. Each entry\n * declares an external sidecar process (Python FastAPI / Node Hono) that\n * boots alongside the TheoKit TS app. Empty `services: {}` is the default\n * and preserves Wave 1 behavior (no impact on TS-only apps).\n *\n * See ADRs 0012-0015 + plan: docs/plans/wave-2-polyglot-services-plan.md\n */\nimport { z } from 'zod'\n\n/** Wave 2 runtime kinds. Go/Rust/Java/Ruby/PHP archived; deferred per ADR-0012 invariant #2/#3. */\nconst ServiceRuntimeSchema = z.enum(['python', 'node'])\n\n/**\n * Plan v1.2 T2.2 — service shape enum, mirrored from `services.schema.json`\n * server | worker | frontend. Optional; emitters default to \"server\".\n */\nconst ServiceTypeSchema = z.enum(['server', 'worker', 'frontend'])\n\n/** EC-3 fix: names that conflict with generated docker-compose entries. */\nconst RESERVED_SERVICE_NAMES = ['web', 'caddy', 'postgres', 'redis'] as const\n\n/**\n * EC-12 fix: service names must be docker-compose-safe — lowercase,\n * start with a letter, contain only a-z 0-9 -. Reserved names rejected.\n */\nconst ServiceNameSchema = z\n .string()\n .min(1)\n .regex(\n /^[a-z][a-z0-9-]*$/,\n 'service name must be lowercase, start with letter, contain only a-z 0-9 -',\n )\n .refine((n) => !(RESERVED_SERVICE_NAMES as readonly string[]).includes(n), {\n message: `service name conflicts with reserved name (${RESERVED_SERVICE_NAMES.join('/')})`,\n })\n\n/**\n * Single service definition. All commands run from `services/<name>/` cwd.\n *\n * EC-4 fix: `proxy` regex requires NON-EMPTY path after `/` (the `+` quantifier)\n * to reject `/` which would catch-all and conflict with TheoKit's own routing.\n */\nconst ServiceDefinitionSchema = z.object({\n runtime: ServiceRuntimeSchema,\n type: ServiceTypeSchema.optional(),\n port: z.number().int().min(1).max(65535),\n proxy: z.string().regex(/^\\/[a-zA-Z0-9\\-_/]+$/, 'proxy must be a non-root path starting with /'),\n dev: z.string().min(1),\n build: z.string().optional(),\n start: z.string().min(1),\n openapi: z.string().url().optional(),\n healthcheck: z.string().regex(/^\\//, 'healthcheck must start with /').default('/health'),\n cors: z.boolean().default(false),\n env: z.record(z.string(), z.string()).optional(),\n dependsOn: z.array(z.string()).optional(),\n /**\n * EC-25 + ref doc §8: by default the proxy strips upstream Set-Cookie\n * to prevent the polyglot service from issuing cookies that conflict\n * with TheoKit's encrypted session. Set to true to opt-in.\n */\n passSetCookie: z.boolean().default(false),\n})\n\nexport type ServiceDefinition = z.infer<typeof ServiceDefinitionSchema>\nexport type ServicesConfig = Record<string, ServiceDefinition>\n\n/**\n * Topological-order helper used by `dependsOn` cycle detection refine.\n * Returns true iff `graph` is a DAG. Each node's deps must all reference\n * existing nodes; cycles return false.\n */\nfunction isDag(graph: Record<string, readonly string[]>): boolean {\n const WHITE = 0\n const GRAY = 1\n const BLACK = 2\n const colors: Record<string, 0 | 1 | 2> = {}\n for (const node of Object.keys(graph)) colors[node] = WHITE\n\n function visit(node: string): boolean {\n if (colors[node] === GRAY) return false // cycle\n if (colors[node] === BLACK) return true\n colors[node] = GRAY\n for (const dep of graph[node] ?? []) {\n if (!(dep in graph)) return false // missing reference\n if (!visit(dep)) return false\n }\n colors[node] = BLACK\n return true\n }\n\n for (const node of Object.keys(graph)) {\n if (colors[node] === WHITE && !visit(node)) return false\n }\n return true\n}\n\n/**\n * Full services config schema with cross-service refines.\n *\n * EC-1 fix: detect duplicate ports across services.\n * EC-13: empty `dependsOn: []` accepted as no-deps.\n * Self-dep, missing-ref, and cycles rejected via topological check.\n */\nexport const servicesConfigSchema = z\n .record(ServiceNameSchema, ServiceDefinitionSchema)\n .default({})\n // EC-1: duplicate port detection across services\n .refine(\n (s) => {\n const ports = Object.values(s).map((v) => v.port)\n return new Set(ports).size === ports.length\n },\n {\n message: 'duplicate port across services — each service must bind a unique port',\n },\n )\n // duplicate proxy prefix detection\n .refine(\n (s) => {\n const prefixes = Object.values(s).map((v) => v.proxy)\n return new Set(prefixes).size === prefixes.length\n },\n { message: 'duplicate proxy prefix across services' },\n )\n // dependsOn correctness (self-dep, missing reference, cycle)\n .refine(\n (s) => {\n // Build graph\n const graph: Record<string, readonly string[]> = {}\n for (const [name, def] of Object.entries(s)) {\n graph[name] = def.dependsOn ?? []\n }\n // Self-dep: a service mentioning itself is rejected as part of cycle detection\n for (const [name, deps] of Object.entries(graph)) {\n if (deps.includes(name)) return false\n }\n return isDag(graph)\n },\n {\n message: 'invalid dependsOn — must reference existing services, no self-deps, no cycles',\n },\n )\n\nexport type ServicesConfigInput = z.input<typeof servicesConfigSchema>\nexport type ServicesConfigOutput = z.output<typeof servicesConfigSchema>\n","/**\n * Dev orchestration entry point (T2.4).\n *\n * Spawns declared polyglot services, waits for all healthchecks to pass,\n * then signals readiness. The `theokit dev` CLI calls `orchestrateDev`\n * BEFORE starting Vite — Vite only boots after all services healthy.\n *\n * Empty `services: {}` → no-op (Wave 1 BC).\n *\n * Single composable entry that the CLI consumes. Spawn/healthcheck/log\n * primitives live in their own modules; this file ties them together.\n */\nimport type { ChildProcess, SpawnOptions } from 'node:child_process'\nimport { spawn } from 'node:child_process'\nimport { resolve } from 'node:path'\n\nimport type { ServiceDefinition, ServicesConfig } from '../schema.js'\n\nimport { pollHealthcheck } from './healthcheck-poller.js'\nimport { createLogMerger } from './log-merge.js'\nimport { buildSpawnEnv, installLifecycleHandlers } from './process-spawn-helpers.js'\n\nexport interface SpawnedService {\n name: string\n port: number\n process: ChildProcess\n}\n\nexport interface OrchestrateDevOptions {\n cwd: string\n services: ServicesConfig\n /** Defaults to `process.stdout.write.bind(process.stdout)`. */\n write?: (s: string) => void\n /** Test injection — replace child_process.spawn. */\n spawnFn?: typeof spawn\n /** Test injection — replace global fetch (for healthchecks). */\n customFetch?: typeof fetch\n /** Healthcheck timeout per service. Default 30_000. */\n healthcheckTimeoutMs?: number\n /** Whether to install parent lifecycle handlers (EC-7). Default true. */\n installSignalHandlers?: boolean\n}\n\nexport interface OrchestrateDevResult {\n spawned: SpawnedService[]\n /** Whether ALL services passed healthcheck. */\n allHealthy: boolean\n /** Services that timed out (only populated when !allHealthy). */\n unhealthy: string[]\n /** Call to gracefully stop all spawned services. */\n stop: () => Promise<void>\n}\n\nfunction spawnService(\n name: string,\n service: ServiceDefinition,\n cwd: string,\n options: {\n spawnFn: typeof spawn\n onLog: (s: string, stream: 'stdout' | 'stderr', line: string) => void\n },\n): SpawnedService {\n const env = buildSpawnEnv(name, service, process.env)\n const spawnOpts: SpawnOptions = {\n cwd,\n shell: true,\n env,\n stdio: ['ignore', 'pipe', 'pipe'],\n }\n const child = options.spawnFn(service.dev, spawnOpts)\n child.stdout?.setEncoding('utf-8')\n child.stderr?.setEncoding('utf-8')\n child.stdout?.on('data', (chunk: string) => {\n options.onLog(name, 'stdout', chunk)\n })\n child.stderr?.on('data', (chunk: string) => {\n options.onLog(name, 'stderr', chunk)\n })\n return { name, port: service.port, process: child }\n}\n\nasync function stopSpawned(s: SpawnedService): Promise<void> {\n return new Promise<void>((resolve) => {\n if (s.process.killed || s.process.exitCode !== null) {\n resolve()\n return\n }\n const timer = setTimeout(() => {\n s.process.kill('SIGKILL')\n resolve()\n }, 5_000)\n s.process.once('exit', () => {\n clearTimeout(timer)\n resolve()\n })\n s.process.kill('SIGTERM')\n })\n}\n\nexport async function orchestrateDev(\n options: OrchestrateDevOptions,\n): Promise<OrchestrateDevResult> {\n const entries = Object.entries(options.services)\n if (entries.length === 0) {\n return {\n spawned: [],\n allHealthy: true,\n unhealthy: [],\n stop: () => Promise.resolve(),\n }\n }\n\n const write =\n options.write ??\n ((s: string) => {\n process.stdout.write(s)\n })\n const spawnFn = options.spawnFn ?? spawn\n const merger = createLogMerger({ write })\n\n const spawned: SpawnedService[] = entries.map(([name, def]) =>\n spawnService(name, def, resolve(options.cwd, 'services', name), {\n spawnFn,\n onLog: merger.onLog,\n }),\n )\n\n const stop = async (): Promise<void> => {\n await Promise.all(spawned.map(stopSpawned))\n }\n\n if (options.installSignalHandlers !== false) {\n installLifecycleHandlers(process, stop)\n }\n\n // Parallel healthcheck\n const results = await Promise.all(\n entries.map(([name, def]) =>\n pollHealthcheck({\n url: `http://localhost:${String(def.port)}${def.healthcheck}`,\n timeoutMs: options.healthcheckTimeoutMs ?? 30_000,\n intervalMs: 500,\n customFetch: options.customFetch,\n }).then((r) => ({ name, result: r })),\n ),\n )\n\n const unhealthy = results.filter((r) => !r.result.healthy).map((r) => r.name)\n return {\n spawned,\n allHealthy: unhealthy.length === 0,\n unhealthy,\n stop,\n }\n}\n","/**\n * Healthcheck poller (T1.5).\n *\n * Polls `GET <url>` with backoff until 200 OR timeout. Used by `pnpm dev`\n * (T2.4) to gate readiness on declared services being healthy before\n * starting Vite.\n *\n * Invariants:\n * - Returns within `timeoutMs + intervalMs` (no hang)\n * - Never throws (returns `{ healthy: false }` on any error)\n * - `attempts >= 1` always\n * - Respects external AbortSignal (pre-aborted → immediate return, EC-18)\n */\n\nexport interface HealthcheckOptions {\n /** Full URL to poll, e.g. 'http://localhost:8001/health' */\n url: string\n /** Total time budget in ms. Default 30_000. */\n timeoutMs?: number\n /** Sleep between attempts in ms. Default 500. */\n intervalMs?: number\n /** Optional external cancel. Aborted signal causes early return. */\n signal?: AbortSignal\n /** Test injection — replace global fetch. */\n customFetch?: typeof fetch\n}\n\nexport interface HealthcheckResult {\n healthy: boolean\n attempts: number\n durationMs: number\n lastError?: string\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise<void>((resolve) => {\n if (signal?.aborted) {\n resolve()\n return\n }\n const t = setTimeout(() => {\n resolve()\n }, ms)\n signal?.addEventListener(\n 'abort',\n () => {\n clearTimeout(t)\n resolve()\n },\n { once: true },\n )\n })\n}\n\nexport async function pollHealthcheck(options: HealthcheckOptions): Promise<HealthcheckResult> {\n const timeoutMs = options.timeoutMs ?? 30_000\n const intervalMs = options.intervalMs ?? 500\n const f = options.customFetch ?? fetch\n const start = Date.now()\n let attempts = 0\n let lastError: string | undefined\n\n // EC-18: signal already aborted → return immediately with at least 1 attempt counted\n if (options.signal?.aborted) {\n return {\n healthy: false,\n attempts: 1,\n durationMs: Date.now() - start,\n lastError: 'aborted',\n }\n }\n\n // Infinite poll loop terminated by status === 200 OR timeout OR abort.\n for (;;) {\n if (options.signal?.aborted) {\n return {\n healthy: false,\n attempts: Math.max(attempts, 1),\n durationMs: Date.now() - start,\n lastError: 'aborted',\n }\n }\n attempts++\n try {\n const res = await f(options.url, { method: 'GET', signal: options.signal })\n if (res.status === 200) {\n return { healthy: true, attempts, durationMs: Date.now() - start }\n }\n lastError = `status ${res.status}`\n } catch (err) {\n lastError = err instanceof Error ? err.message : String(err)\n }\n\n if (Date.now() - start >= timeoutMs) {\n return {\n healthy: false,\n attempts,\n durationMs: Date.now() - start,\n lastError,\n }\n }\n await sleep(intervalMs, options.signal)\n }\n}\n","/**\n * Log merger (T2.3).\n *\n * Combines stdout/stderr from multiple polyglot services into TheoKit's\n * dev terminal, prefixed with `[service-name]`. Parses JSON-line logs\n * (ADR-0015 invariant #5) for pretty-printing; falls back to raw line on\n * non-JSON.\n *\n * Pure / synchronous. The Vite plugin (T2.1) wires this as the `onLog`\n * callback passed to spawnServices.\n */\n\ninterface LogEntry {\n level?: string\n message?: string\n timestamp?: string\n traceparent?: string\n service?: string\n}\n\nexport interface LogMergerOptions {\n write: (s: string) => void\n}\n\nexport interface LogMerger {\n onLog: (service: string, stream: 'stdout' | 'stderr', chunk: string) => void\n}\n\n/**\n * Try to parse a log line as JSON. Returns parsed object on success,\n * undefined on failure (will fall back to raw rendering).\n */\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === 'object' && !Array.isArray(v)\n}\n\nfunction tryParseJson(line: string): LogEntry | undefined {\n const trimmed = line.trim()\n if (!trimmed.startsWith('{')) return undefined\n try {\n const parsed: unknown = JSON.parse(trimmed)\n if (!isPlainObject(parsed)) return undefined\n const entry: LogEntry = {}\n if (typeof parsed.level === 'string') entry.level = parsed.level\n if (typeof parsed.message === 'string') entry.message = parsed.message\n if (typeof parsed.timestamp === 'string') entry.timestamp = parsed.timestamp\n if (typeof parsed.traceparent === 'string') entry.traceparent = parsed.traceparent\n if (typeof parsed.service === 'string') entry.service = parsed.service\n return entry\n } catch {\n return undefined\n }\n}\n\nfunction renderLine(\n service: string,\n stream: 'stdout' | 'stderr',\n line: string,\n write: (s: string) => void,\n): void {\n if (line.length === 0) return\n\n const prefix = `[${service}]`\n const streamMarker = stream === 'stderr' ? '!' : ' '\n\n const parsed = tryParseJson(line)\n if (parsed) {\n const level = parsed.level ?? 'info'\n const msg = parsed.message ?? line\n write(`${prefix}${streamMarker}${level.toUpperCase()} ${msg}\\n`)\n return\n }\n\n write(`${prefix}${streamMarker}${line}\\n`)\n}\n\nexport function createLogMerger(options: LogMergerOptions): LogMerger {\n return {\n onLog(service, stream, chunk) {\n // Multi-line chunks: split by \\n and render each\n const lines = chunk.split('\\n')\n for (const line of lines) {\n renderLine(service, stream, line, options.write)\n }\n },\n }\n}\n","/**\n * Pure helpers extracted from process-spawn.ts (T2.2) for unit testability.\n *\n * The full spawn orchestration (child_process + healthcheck poll + log\n * merge) lives in process-spawn.ts; this file holds the parts that are\n * safe to test without mocking node:child_process.\n *\n * EC-7: lifecycle handlers prevent orphan children on parent exit/signal.\n * EC-8: auto-injected env vars (THEOKIT_SERVICE_NAME, THEOKIT_SERVICE_PORT).\n */\nimport type { ServiceDefinition } from '../schema.js'\n\n/**\n * Build the env passed to `child_process.spawn`.\n *\n * Precedence (low → high):\n * 1. process.env (the parent's environment)\n * 2. auto-injected THEOKIT_SERVICE_NAME + THEOKIT_SERVICE_PORT\n * 3. service.env (user-provided overrides win)\n */\nexport function buildSpawnEnv(\n name: string,\n service: ServiceDefinition,\n parentEnv: Record<string, string | undefined>,\n): Record<string, string> {\n const env: Record<string, string> = {}\n for (const [k, v] of Object.entries(parentEnv)) {\n if (typeof v === 'string') env[k] = v\n }\n env.THEOKIT_SERVICE_NAME = name\n env.THEOKIT_SERVICE_PORT = String(service.port)\n if (service.env) {\n for (const [k, v] of Object.entries(service.env)) {\n env[k] = v\n }\n }\n return env\n}\n\n/**\n * Format a service name as a log prefix. Deterministic; ANSI codes added\n * by the log-merge layer (T2.3), not here.\n */\nexport function formatLogPrefix(name: string): string {\n return `[${name}]`\n}\n\n/**\n * Install parent-process lifecycle handlers (EC-7).\n *\n * - `exit`: best-effort SIGKILL of all children (synchronous; we cannot await here)\n * - `SIGINT`: graceful stopAllServices then exit 130\n * - `SIGTERM`: graceful stopAllServices then exit 143\n *\n * SIGKILL on the parent is uncatchable (kernel-level); orphan children\n * are documented as a known limit on force-close (EC-27 doc).\n */\nexport function installLifecycleHandlers(proc: NodeJS.Process, stopAll: () => Promise<void>): void {\n proc.on('exit', () => {\n // Best-effort sync notify; cannot await\n })\n proc.on('SIGINT', () => {\n void stopAll().finally(() => {\n proc.exit(130)\n })\n })\n proc.on('SIGTERM', () => {\n void stopAll().finally(() => {\n proc.exit(143)\n })\n })\n}\n","/**\n * TheoCloud adapter scaffolding (T3.5 — Wave 2 stub; full Wave 3).\n *\n * Wave 2 establishes the contract: the adapter CONSUMES `.theokit/services.json`\n * (manifest emitted by `theokit build`) and produces TheoCloud deployment\n * artifacts. The artifacts themselves (K8s manifests, Helm charts, etc.) are\n * Wave 3 deliverables — this module provides the read/validate gate so the\n * manifest format is locked NOW.\n *\n * Per ADR-0012 invariant #4, the same `.theokit/services.json` consumed by\n * the `node` adapter (docker-compose generator) is the same shape consumed\n * here. No platform-specific fields. The contract is global.\n */\nimport type { ServicesManifest } from './manifest.js'\n\nexport interface TheoCloudAdapterArtifacts {\n /** Manifest schemaVersion the adapter consumed. */\n manifestVersion: 1\n /** Service names that will be deployed. */\n services: string[]\n /** Wave 3 will populate K8s manifests here. */\n k8sManifests?: never\n /** Wave 3 will populate Helm values here. */\n helmValues?: never\n}\n\n/**\n * Wave 2 stub — validates the manifest is consumable. Throws if shape is\n * unexpected (forward-compat guard for Wave 3 development).\n *\n * Wave 3 will replace the body with real K8s manifest emission.\n */\nexport function prepareTheoCloudArtifacts(\n manifest: ServicesManifest | null,\n): TheoCloudAdapterArtifacts {\n if (manifest === null) {\n return { manifestVersion: 1, services: [] }\n }\n // Forward-compat: when Wave 3 evolves the manifest schema, the adapter\n // must bump version handling explicitly.\n\n if (manifest.version !== 1) {\n throw new Error(\n `TheoCloud adapter: unsupported manifest version ${String(manifest.version)}. ` +\n `Wave 2/3 expects schemaVersion 1. Update the adapter before bumping.`,\n )\n }\n return {\n manifestVersion: 1,\n services: manifest.services.map((s) => s.name),\n }\n}\n","/**\n * Builds a Vite `server.proxy` configuration from TheoKit's\n * declarative `services: {}` config (T2.1).\n *\n * Pure function — no Vite imports, just data shaping. The Vite plugin\n * (services-dev.ts) calls this and merges the result into `vite.config.server.proxy`.\n *\n * Pattern follows Vite proxy reference (referencias/vite/packages/vite/src/node/server/middlewares/proxy.ts):\n * - Each path prefix becomes its own entry\n * - `changeOrigin: true` set by default (matches Vite's string-shortcut behavior)\n * - User-set entries take precedence on prefix collision (we never clobber)\n */\nimport type { ServicesConfig } from '../schema.js'\n\n/**\n * Shape compatible with Vite's `server.proxy` type. We intentionally don't\n * import Vite's `ProxyOptions` so this module stays platform-neutral and\n * unit-testable without Vite.\n */\nexport interface ViteProxyEntry {\n target: string\n changeOrigin: boolean\n rewrite?: (path: string) => string\n}\n\nexport type ViteProxyConfig = Record<string, string | ViteProxyEntry>\n\nexport function buildServicesProxyConfig(\n services: ServicesConfig,\n userProxy: ViteProxyConfig = {},\n): ViteProxyConfig {\n const fromServices: ViteProxyConfig = {}\n for (const [, def] of Object.entries(services)) {\n const prefix = def.proxy\n fromServices[prefix] = {\n target: `http://localhost:${String(def.port)}`,\n changeOrigin: true,\n // Strip the service's `proxy` prefix from the upstream URL so the\n // sidecar receives its own native paths (e.g. `/api/agent/echo` →\n // `/echo`). The sidecar declares routes against its own root path —\n // it doesn't know about the TheoKit proxy prefix.\n rewrite: (path: string) =>\n path.startsWith(prefix) ? path.slice(prefix.length) || '/' : path,\n }\n }\n // User proxy wins on collision (we add services first, then spread user on top)\n return { ...fromServices, ...userProxy }\n}\n"],"mappings":";;;;AAmBA,IAAM,sBAAsB,CAAC,gBAAgB,qBAAqB;AAU3D,SAAS,0BACd,aACA,UACM;AACN,MAAI,CAAC,YAAY,SAAS,SAAS,WAAW,EAAG;AACjD,QAAM,QAAQ,SAAS,SAAS,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,IAAI;AAC5D,QAAM,IAAI;AAAA,IACR,YAAY,WAAW;AAAA,uCACmB,KAAK;AAAA;AAAA,mBACzB,oBAAoB,KAAK,IAAI,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKtD;AACF;;;ACvBA,SAAS,kBAAkB,aAAqB,QAAgB,MAAyB;AACvF,QAAM,MAAM,CAAC,kBAAmB,WAAW,KAAK,MAAM,EAAE;AACxD,MAAI,MAAM;AACR,QAAI;AAAA,MACF,WAAY,WAAW;AAAA,MACvB,WAAY,WAAW;AAAA,MACvB,WAAY,WAAW;AAAA,IACzB;AAAA,EACF;AACA,SAAO;AACT;AAEO,SAAS,kBACd,UACA,SACQ;AAER,QAAM,YAAY,UAAU,YAAY,CAAC,GACtC,MAAM,EACN,KAAK,CAAC,GAAG,MAAM,EAAE,MAAM,SAAS,EAAE,MAAM,MAAM;AAEjD,Q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