theokit 0.71.0 → 0.72.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-2SM6YMTM.js → actions-virtual-module-EAKYEMGF.js} +4 -4
- package/dist/{actions-virtual-module-5LRBP6YK.js → actions-virtual-module-OHENNMQG.js} +6 -6
- package/dist/adapters/agent-mount.js +3 -3
- package/dist/{agent-4FXJXZFD.js → agent-VJTZ4DQ7.js} +2 -2
- package/dist/{app-typed-client-LIIPHLO6.js → app-typed-client-ILLQYTXP.js} +6 -6
- package/dist/{app-typed-client-JFPV4YLS.js → app-typed-client-LHH77QDB.js} +4 -4
- package/dist/{aws-lambda-MUGK4WNZ.js → aws-lambda-7AZNJGWU.js} +6 -4
- package/dist/{aws-lambda-MUGK4WNZ.js.map → aws-lambda-7AZNJGWU.js.map} +1 -1
- package/dist/{build-KCIH3HI6.js → build-23QF5FNQ.js} +7 -7
- package/dist/build-23QF5FNQ.js.map +1 -0
- package/dist/{bun-JWZ2UOLJ.js → bun-NKVHOFSJ.js} +6 -4
- package/dist/{bun-JWZ2UOLJ.js.map → bun-NKVHOFSJ.js.map} +1 -1
- package/dist/{chunk-KOG5K26V.js → chunk-2Z7TANA4.js} +2 -2
- package/dist/{chunk-V6VARIR3.js → chunk-4EQEJ4PH.js} +9 -9
- package/dist/{chunk-3NAKOWTX.js → chunk-6U67SO5U.js} +3 -3
- package/dist/{chunk-IGCOTLQI.js → chunk-C5CAL3DX.js} +136 -5
- package/dist/{chunk-IGCOTLQI.js.map → chunk-C5CAL3DX.js.map} +1 -1
- package/dist/{chunk-YWWMYEAC.js → chunk-CLSYYO5F.js} +2 -2
- package/dist/{chunk-OSBGZYXZ.js → chunk-D2R5SJEL.js} +16 -2
- package/dist/chunk-D2R5SJEL.js.map +1 -0
- package/dist/{chunk-JMN4COMK.js → chunk-D7STTNQN.js} +3 -3
- package/dist/{chunk-DSPEN7ZJ.js → chunk-DKX7LF5Q.js} +4 -4
- package/dist/{chunk-5XXXJ6DT.js → chunk-E2RC367T.js} +47 -8
- package/dist/chunk-E2RC367T.js.map +1 -0
- package/dist/{chunk-3DGIANAN.js → chunk-FJEKQ4FT.js} +1 -1
- package/dist/{chunk-3DGIANAN.js.map → chunk-FJEKQ4FT.js.map} +1 -1
- package/dist/{chunk-KI4DOTN4.js → chunk-G7U7FQVC.js} +3 -1
- package/dist/chunk-G7U7FQVC.js.map +1 -0
- package/dist/{chunk-6AGXDYVE.js → chunk-IB5VIXLR.js} +2 -2
- package/dist/{chunk-Q4NSUGMS.js → chunk-JJXBRY2U.js} +74 -6
- package/dist/chunk-JJXBRY2U.js.map +1 -0
- package/dist/{chunk-PGDBSK2L.js → chunk-L6UHMWXU.js} +2 -2
- package/dist/{chunk-MS4A7N77.js → chunk-PEL3MJLM.js} +2 -2
- package/dist/{chunk-TNI4MARH.js → chunk-SFGGRC35.js} +23 -6
- package/dist/chunk-SFGGRC35.js.map +1 -0
- package/dist/{chunk-4D4YVXHR.js → chunk-SYIQV4UH.js} +29 -2
- package/dist/{chunk-4D4YVXHR.js.map → chunk-SYIQV4UH.js.map} +1 -1
- package/dist/{chunk-FFS7IRZF.js → chunk-SZWGXHY3.js} +2 -2
- package/dist/{chunk-SX7ZAHNE.js → chunk-WBB3MEEN.js} +16 -2
- package/dist/chunk-WBB3MEEN.js.map +1 -0
- package/dist/{chunk-TMQ52AZR.js → chunk-X2LFNDJQ.js} +2 -2
- package/dist/{chunk-FWEXQ2BR.js → chunk-XLSJWKSP.js} +11 -11
- package/dist/{chunk-NZDGV4YJ.js → chunk-YCF3N4JS.js} +2 -2
- package/dist/cli/index.js +9 -9
- package/dist/{cloudflare-XO43ZIQF.js → cloudflare-4M4XVNUH.js} +5 -3
- package/dist/{cloudflare-XO43ZIQF.js.map → cloudflare-4M4XVNUH.js.map} +1 -1
- package/dist/{config-support-O4REYSK5.js → config-support-SB5NDQZB.js} +11 -5
- package/dist/{config-support-O4REYSK5.js.map → config-support-SB5NDQZB.js.map} +1 -1
- package/dist/{deno-deploy-EUQDK2RC.js → deno-deploy-IVACZ62D.js} +11 -5
- package/dist/deno-deploy-IVACZ62D.js.map +1 -0
- package/dist/{dev-CD4YU5FN.js → dev-JDJWMRLH.js} +9 -9
- package/dist/{index-inRdhi59.d.ts → index-CmkWlIDO.d.ts} +3 -1
- package/dist/index.d.ts +12 -2
- package/dist/index.js +7 -7
- package/dist/{info-2H7I55YN.js → info-SUX7QVA3.js} +4 -4
- package/dist/{internal-api-TMLSNYMP.js → internal-api-6XNLCNI5.js} +6 -6
- package/dist/{internal-api-WAKX6AZW.js → internal-api-VDYOXOT7.js} +4 -4
- package/dist/{load-config-VMKOV44Y.js → load-config-52H3EKAA.js} +4 -4
- package/dist/{mcp-HS26ZCU4.js → mcp-WJNCTM7M.js} +3 -3
- package/dist/{netlify-LEYEQZK6.js → netlify-3HEWV375.js} +6 -4
- package/dist/{netlify-LEYEQZK6.js.map → netlify-3HEWV375.js.map} +1 -1
- package/dist/{node-OSVPYQ3D.js → node-QUGTW6XV.js} +2 -2
- package/dist/{observability-bootstrap-YQKMEYW7.js → observability-bootstrap-FP6LMMJE.js} +3 -3
- package/dist/{openapi-N4CXRUNT.js → openapi-Q53YOBIU.js} +4 -4
- package/dist/{preview-YDJSRJ2K.js → preview-BARW75PN.js} +3 -3
- package/dist/{rate-limit-BdNDZ3vt.d.ts → rate-limit-fULgvzCz.d.ts} +11 -1
- package/dist/{rate-limit-store-BEJnhWdw.d.ts → rate-limit-store-n1wD4Yk4.d.ts} +48 -1
- package/dist/registry-SDBODRU6.js +23 -0
- package/dist/{routes-ECCDRHXZ.js → routes-FDF4SLOB.js} +4 -4
- package/dist/{schema-ND7GHPQK.js → schema-LHNWUR4V.js} +3 -3
- package/dist/{schemas-QCMSKQDK.js → schemas-2R2J64ZH.js} +2 -2
- package/dist/server/auth/index.d.ts +1 -1
- package/dist/server/http/index.d.ts +1 -1
- package/dist/server/http/index.js +5 -3
- package/dist/server/index.d.ts +4 -4
- package/dist/server/index.js +15 -7
- package/dist/server/index.js.map +1 -1
- package/dist/server/rate-limit/index.d.ts +96 -14
- package/dist/server/rate-limit/index.js +10 -4
- package/dist/server/storage/index.js +1 -1
- package/dist/{server-boundary-RX2AFU5U.js → server-boundary-AO6EELRF.js} +4 -4
- package/dist/{server-boundary-NZPP33G6.js → server-boundary-E5GFVPLB.js} +6 -6
- package/dist/{start-TYXS5I4M.js → start-4JTYXQQJ.js} +14 -11
- package/dist/start-4JTYXQQJ.js.map +1 -0
- package/dist/{static-7OJNB7D2.js → static-NQPLPAB6.js} +6 -2
- package/dist/{static-7OJNB7D2.js.map → static-NQPLPAB6.js.map} +1 -1
- package/dist/{theo-cloud-3ET4G5T6.js → theo-cloud-HMFNZ3FS.js} +3 -1
- package/dist/{theo-cloud-3ET4G5T6.js.map → theo-cloud-HMFNZ3FS.js.map} +1 -1
- package/dist/{vercel-HTAWCNAG.js → vercel-5PMYEEKF.js} +6 -4
- package/dist/{vercel-HTAWCNAG.js.map → vercel-5PMYEEKF.js.map} +1 -1
- package/dist/vite-plugin/index.d.ts +2 -2
- package/dist/vite-plugin/index.js +7 -7
- package/dist/{vite-plugin-DDILUFYY.js → vite-plugin-3ON45MQE.js} +8 -8
- package/package.json +3 -3
- package/dist/build-KCIH3HI6.js.map +0 -1
- package/dist/chunk-5XXXJ6DT.js.map +0 -1
- package/dist/chunk-KI4DOTN4.js.map +0 -1
- package/dist/chunk-OSBGZYXZ.js.map +0 -1
- package/dist/chunk-Q4NSUGMS.js.map +0 -1
- package/dist/chunk-SX7ZAHNE.js.map +0 -1
- package/dist/chunk-TNI4MARH.js.map +0 -1
- package/dist/deno-deploy-EUQDK2RC.js.map +0 -1
- package/dist/registry-4JHCZ6EF.js +0 -23
- package/dist/start-TYXS5I4M.js.map +0 -1
- /package/dist/{actions-virtual-module-2SM6YMTM.js.map → actions-virtual-module-EAKYEMGF.js.map} +0 -0
- /package/dist/{actions-virtual-module-5LRBP6YK.js.map → actions-virtual-module-OHENNMQG.js.map} +0 -0
- /package/dist/{agent-4FXJXZFD.js.map → agent-VJTZ4DQ7.js.map} +0 -0
- /package/dist/{app-typed-client-LIIPHLO6.js.map → app-typed-client-ILLQYTXP.js.map} +0 -0
- /package/dist/{app-typed-client-JFPV4YLS.js.map → app-typed-client-LHH77QDB.js.map} +0 -0
- /package/dist/{chunk-KOG5K26V.js.map → chunk-2Z7TANA4.js.map} +0 -0
- /package/dist/{chunk-V6VARIR3.js.map → chunk-4EQEJ4PH.js.map} +0 -0
- /package/dist/{chunk-3NAKOWTX.js.map → chunk-6U67SO5U.js.map} +0 -0
- /package/dist/{chunk-YWWMYEAC.js.map → chunk-CLSYYO5F.js.map} +0 -0
- /package/dist/{chunk-JMN4COMK.js.map → chunk-D7STTNQN.js.map} +0 -0
- /package/dist/{chunk-DSPEN7ZJ.js.map → chunk-DKX7LF5Q.js.map} +0 -0
- /package/dist/{chunk-6AGXDYVE.js.map → chunk-IB5VIXLR.js.map} +0 -0
- /package/dist/{chunk-PGDBSK2L.js.map → chunk-L6UHMWXU.js.map} +0 -0
- /package/dist/{chunk-MS4A7N77.js.map → chunk-PEL3MJLM.js.map} +0 -0
- /package/dist/{chunk-FFS7IRZF.js.map → chunk-SZWGXHY3.js.map} +0 -0
- /package/dist/{chunk-TMQ52AZR.js.map → chunk-X2LFNDJQ.js.map} +0 -0
- /package/dist/{chunk-FWEXQ2BR.js.map → chunk-XLSJWKSP.js.map} +0 -0
- /package/dist/{chunk-NZDGV4YJ.js.map → chunk-YCF3N4JS.js.map} +0 -0
- /package/dist/{dev-CD4YU5FN.js.map → dev-JDJWMRLH.js.map} +0 -0
- /package/dist/{info-2H7I55YN.js.map → info-SUX7QVA3.js.map} +0 -0
- /package/dist/{internal-api-TMLSNYMP.js.map → internal-api-6XNLCNI5.js.map} +0 -0
- /package/dist/{internal-api-WAKX6AZW.js.map → internal-api-VDYOXOT7.js.map} +0 -0
- /package/dist/{load-config-VMKOV44Y.js.map → load-config-52H3EKAA.js.map} +0 -0
- /package/dist/{mcp-HS26ZCU4.js.map → mcp-WJNCTM7M.js.map} +0 -0
- /package/dist/{node-OSVPYQ3D.js.map → node-QUGTW6XV.js.map} +0 -0
- /package/dist/{observability-bootstrap-YQKMEYW7.js.map → observability-bootstrap-FP6LMMJE.js.map} +0 -0
- /package/dist/{openapi-N4CXRUNT.js.map → openapi-Q53YOBIU.js.map} +0 -0
- /package/dist/{preview-YDJSRJ2K.js.map → preview-BARW75PN.js.map} +0 -0
- /package/dist/{registry-4JHCZ6EF.js.map → registry-SDBODRU6.js.map} +0 -0
- /package/dist/{routes-ECCDRHXZ.js.map → routes-FDF4SLOB.js.map} +0 -0
- /package/dist/{schema-ND7GHPQK.js.map → schema-LHNWUR4V.js.map} +0 -0
- /package/dist/{schemas-QCMSKQDK.js.map → schemas-2R2J64ZH.js.map} +0 -0
- /package/dist/{server-boundary-RX2AFU5U.js.map → server-boundary-AO6EELRF.js.map} +0 -0
- /package/dist/{server-boundary-NZPP33G6.js.map → server-boundary-E5GFVPLB.js.map} +0 -0
- /package/dist/{vite-plugin-DDILUFYY.js.map → vite-plugin-3ON45MQE.js.map} +0 -0
|
@@ -7,13 +7,13 @@ import {
|
|
|
7
7
|
} from "./chunk-SSYDEKWF.js";
|
|
8
8
|
import {
|
|
9
9
|
dispatchControllerRequest
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-D7STTNQN.js";
|
|
11
11
|
import {
|
|
12
12
|
createAgentSubjectResolver,
|
|
13
13
|
isAgentCardPath,
|
|
14
14
|
matchAgentAuxRoute,
|
|
15
15
|
serveMatchedAuxRoute
|
|
16
|
-
} from "./chunk-
|
|
16
|
+
} from "./chunk-6U67SO5U.js";
|
|
17
17
|
import {
|
|
18
18
|
admitAgentRequest,
|
|
19
19
|
agentAccessDenied,
|
|
@@ -29,7 +29,7 @@ import {
|
|
|
29
29
|
securitySchema,
|
|
30
30
|
storageSchema,
|
|
31
31
|
uploadSchema
|
|
32
|
-
} from "./chunk-
|
|
32
|
+
} from "./chunk-WBB3MEEN.js";
|
|
33
33
|
import {
|
|
34
34
|
broadcastToDevtools
|
|
35
35
|
} from "./chunk-OIGJOYX6.js";
|
|
@@ -52,13 +52,13 @@ import {
|
|
|
52
52
|
executeAction,
|
|
53
53
|
executeRoute,
|
|
54
54
|
handleBatchRequest
|
|
55
|
-
} from "./chunk-
|
|
55
|
+
} from "./chunk-2Z7TANA4.js";
|
|
56
56
|
import {
|
|
57
57
|
createWebRequestSource,
|
|
58
58
|
incomingMessageToHandlerRequest,
|
|
59
59
|
sendError,
|
|
60
60
|
writeWebResponseToServerResponse
|
|
61
|
-
} from "./chunk-
|
|
61
|
+
} from "./chunk-SYIQV4UH.js";
|
|
62
62
|
import {
|
|
63
63
|
validateCsrfRequest
|
|
64
64
|
} from "./chunk-P6OS7652.js";
|
|
@@ -75,7 +75,7 @@ import {
|
|
|
75
75
|
} from "./chunk-VSLTKX5L.js";
|
|
76
76
|
import {
|
|
77
77
|
createRateLimiter
|
|
78
|
-
} from "./chunk-
|
|
78
|
+
} from "./chunk-SFGGRC35.js";
|
|
79
79
|
import {
|
|
80
80
|
createViteLoader
|
|
81
81
|
} from "./chunk-4ERYQBL6.js";
|
|
@@ -3024,19 +3024,19 @@ async function theoPluginAsync(rootOrOptions) {
|
|
|
3024
3024
|
}
|
|
3025
3025
|
const { assetsMapPlugin } = await import("./assets-map-CV2YZ3MY.js");
|
|
3026
3026
|
const assetsMap = assetsMapPlugin({ appDir: resolve9(projectRoot, options.appDir ?? "app") });
|
|
3027
|
-
const { appTypedClientPlugin } = await import("./app-typed-client-
|
|
3027
|
+
const { appTypedClientPlugin } = await import("./app-typed-client-ILLQYTXP.js");
|
|
3028
3028
|
const appClientPlugin = appTypedClientPlugin({
|
|
3029
3029
|
cwd: projectRoot,
|
|
3030
3030
|
serverDir: serverDirAbs,
|
|
3031
3031
|
distDir: resolve9(projectRoot, ".theokit")
|
|
3032
3032
|
});
|
|
3033
|
-
const { actionsVirtualModule } = await import("./actions-virtual-module-
|
|
3033
|
+
const { actionsVirtualModule } = await import("./actions-virtual-module-OHENNMQG.js");
|
|
3034
3034
|
const actionsPlugin = actionsVirtualModule({
|
|
3035
3035
|
serverDir: serverDirAbs,
|
|
3036
3036
|
distDir: resolve9(projectRoot, ".theokit")
|
|
3037
3037
|
});
|
|
3038
3038
|
const { agentsTypedClientPlugin } = await import("./agents-typed-client-PVUZU65B.js");
|
|
3039
|
-
const { generateManifest } = await import("./internal-api-
|
|
3039
|
+
const { generateManifest } = await import("./internal-api-6XNLCNI5.js");
|
|
3040
3040
|
const agentsClientPlugin = agentsTypedClientPlugin({
|
|
3041
3041
|
projectRoot,
|
|
3042
3042
|
agentsDir: agentsDirName,
|
|
@@ -3053,7 +3053,7 @@ async function theoPluginAsync(rootOrOptions) {
|
|
|
3053
3053
|
const controllerTransformPlugin = controllerSwcTransformPlugin({
|
|
3054
3054
|
serverDir: serverDirAbs
|
|
3055
3055
|
});
|
|
3056
|
-
const { serverOnlyImportBoundary } = await import("./server-boundary-
|
|
3056
|
+
const { serverOnlyImportBoundary } = await import("./server-boundary-E5GFVPLB.js");
|
|
3057
3057
|
const serverBoundaryPlugin = serverOnlyImportBoundary({
|
|
3058
3058
|
projectRoot,
|
|
3059
3059
|
serverDir: serverDirAbs
|
|
@@ -3237,4 +3237,4 @@ export {
|
|
|
3237
3237
|
theoPluginAsync,
|
|
3238
3238
|
theoPlugin
|
|
3239
3239
|
};
|
|
3240
|
-
//# sourceMappingURL=chunk-
|
|
3240
|
+
//# sourceMappingURL=chunk-XLSJWKSP.js.map
|
|
@@ -6,7 +6,7 @@ async function initCacheEngineFromConfig(cacheConfig) {
|
|
|
6
6
|
if (cacheConfig === void 0 || cacheConfig === null) return;
|
|
7
7
|
const { initCacheEngine, isCacheEngineInitialized } = await import("./engine-singleton-X4R7AZBJ.js");
|
|
8
8
|
if (isCacheEngineInitialized()) return;
|
|
9
|
-
const { cacheSchema } = await import("./schemas-
|
|
9
|
+
const { cacheSchema } = await import("./schemas-2R2J64ZH.js");
|
|
10
10
|
const parsed = cacheSchema.parse(cacheConfig);
|
|
11
11
|
if (!parsed.enabled) return;
|
|
12
12
|
initCacheEngine({
|
|
@@ -23,4 +23,4 @@ async function initCacheEngineFromConfig(cacheConfig) {
|
|
|
23
23
|
export {
|
|
24
24
|
initCacheEngineFromConfig
|
|
25
25
|
};
|
|
26
|
-
//# sourceMappingURL=chunk-
|
|
26
|
+
//# sourceMappingURL=chunk-YCF3N4JS.js.map
|
package/dist/cli/index.js
CHANGED
|
@@ -15,12 +15,12 @@ function cliVersion() {
|
|
|
15
15
|
// src/cli/index.ts
|
|
16
16
|
var cli = cac("theokit");
|
|
17
17
|
cli.command("dev", "Start development server").option("--port <port>", "Port number").action(async (options) => {
|
|
18
|
-
const { devCommand } = await import("../dev-
|
|
18
|
+
const { devCommand } = await import("../dev-JDJWMRLH.js");
|
|
19
19
|
await devCommand({ port: options.port ? Number(options.port) : void 0 });
|
|
20
20
|
});
|
|
21
21
|
cli.command("build", "Build for production").option("--target <target>", "Deploy target (node, vercel, cloudflare)").action(async (options) => {
|
|
22
22
|
try {
|
|
23
|
-
const { buildCommand } = await import("../build-
|
|
23
|
+
const { buildCommand } = await import("../build-23QF5FNQ.js");
|
|
24
24
|
await buildCommand({ target: options.target });
|
|
25
25
|
} catch (err) {
|
|
26
26
|
const msg = err instanceof Error ? err.message : String(err);
|
|
@@ -32,7 +32,7 @@ cli.command("build", "Build for production").option("--target <target>", "Deploy
|
|
|
32
32
|
});
|
|
33
33
|
cli.command("start", "Start production server").option("--port <port>", "Port number").action(async (options) => {
|
|
34
34
|
try {
|
|
35
|
-
const { startCommand } = await import("../start-
|
|
35
|
+
const { startCommand } = await import("../start-4JTYXQQJ.js");
|
|
36
36
|
await startCommand({ port: options.port ? Number(options.port) : void 0 });
|
|
37
37
|
} catch (err) {
|
|
38
38
|
const msg = err instanceof Error ? err.message : String(err);
|
|
@@ -44,7 +44,7 @@ cli.command("start", "Start production server").option("--port <port>", "Port nu
|
|
|
44
44
|
});
|
|
45
45
|
cli.command("preview", "Build for production, then serve it \u2014 one step (B-030)").option("--port <port>", "Port number").option("--target <target>", "Deploy target (node, vercel, cloudflare)").action(async (options) => {
|
|
46
46
|
try {
|
|
47
|
-
const { previewCommand } = await import("../preview-
|
|
47
|
+
const { previewCommand } = await import("../preview-BARW75PN.js");
|
|
48
48
|
await previewCommand({
|
|
49
49
|
port: options.port ? Number(options.port) : void 0,
|
|
50
50
|
target: options.target
|
|
@@ -77,7 +77,7 @@ cli.command(
|
|
|
77
77
|
"Run an agent in the terminal (stream + tool calls + approval)"
|
|
78
78
|
).action(async (name, message) => {
|
|
79
79
|
try {
|
|
80
|
-
const { agentCommand } = await import("../agent-
|
|
80
|
+
const { agentCommand } = await import("../agent-VJTZ4DQ7.js");
|
|
81
81
|
const { sawError } = await agentCommand(name, message);
|
|
82
82
|
if (sawError) process.exit(1);
|
|
83
83
|
} catch (err) {
|
|
@@ -108,7 +108,7 @@ cli.command("agent sessions gc", "Collect old transcripts for this project (dry
|
|
|
108
108
|
});
|
|
109
109
|
cli.command("mcp <agent>", "Serve an agent as an MCP server over stdio (for desktop MCP clients)").action(async (agent) => {
|
|
110
110
|
try {
|
|
111
|
-
const { mcpCommand } = await import("../mcp-
|
|
111
|
+
const { mcpCommand } = await import("../mcp-WJNCTM7M.js");
|
|
112
112
|
await mcpCommand(agent);
|
|
113
113
|
} catch (err) {
|
|
114
114
|
const msg = err instanceof Error ? err.message : String(err);
|
|
@@ -120,7 +120,7 @@ cli.command("mcp <agent>", "Serve an agent as an MCP server over stdio (for desk
|
|
|
120
120
|
});
|
|
121
121
|
cli.command("routes", "List all routes, actions, and WebSocket endpoints").action(async () => {
|
|
122
122
|
try {
|
|
123
|
-
const { routesCommand } = await import("../routes-
|
|
123
|
+
const { routesCommand } = await import("../routes-FDF4SLOB.js");
|
|
124
124
|
await routesCommand();
|
|
125
125
|
} catch (err) {
|
|
126
126
|
const msg = err instanceof Error ? err.message : String(err);
|
|
@@ -161,7 +161,7 @@ cli.command("add <package>", "Install a known TheoKit adapter or plugin (whiteli
|
|
|
161
161
|
await addCommand(pkg);
|
|
162
162
|
});
|
|
163
163
|
cli.command("info", "Print environment info (runtime, config, routes)").action(async () => {
|
|
164
|
-
const { infoCommand } = await import("../info-
|
|
164
|
+
const { infoCommand } = await import("../info-SUX7QVA3.js");
|
|
165
165
|
await infoCommand();
|
|
166
166
|
});
|
|
167
167
|
cli.command("doctor", "Report the RESOLVED state of this installation (never prints a secret)").action(async () => {
|
|
@@ -173,7 +173,7 @@ cli.command(
|
|
|
173
173
|
"Generate <distDir>/openapi.json from route schemas (opt-in via config.openapi)"
|
|
174
174
|
).option("--dry-run", "Print the document to stdout without writing to disk (EC-3)").action(async (options) => {
|
|
175
175
|
try {
|
|
176
|
-
const { openapiCommand } = await import("../openapi-
|
|
176
|
+
const { openapiCommand } = await import("../openapi-Q53YOBIU.js");
|
|
177
177
|
await openapiCommand({ dryRun: Boolean(options.dryRun) });
|
|
178
178
|
} catch (err) {
|
|
179
179
|
const msg = err instanceof Error ? err.message : String(err);
|
|
@@ -17,10 +17,10 @@ import {
|
|
|
17
17
|
rateLimitCheckFragment,
|
|
18
18
|
securityHeadersDeclarations,
|
|
19
19
|
serverDirLiteral
|
|
20
|
-
} from "./chunk-
|
|
20
|
+
} from "./chunk-C5CAL3DX.js";
|
|
21
21
|
import {
|
|
22
22
|
nodeAdapter
|
|
23
|
-
} from "./chunk-
|
|
23
|
+
} from "./chunk-G7U7FQVC.js";
|
|
24
24
|
import {
|
|
25
25
|
findRootDiv
|
|
26
26
|
} from "./chunk-3PWQQWT6.js";
|
|
@@ -343,6 +343,8 @@ var cloudflareAdapter = {
|
|
|
343
343
|
// that can mint one (`adapters/security-headers.ts`).
|
|
344
344
|
servesAgents: true,
|
|
345
345
|
appliesConfig: ["securityHeaders", "csrf", "disallowed", "cors", "serialization", "plugins"],
|
|
346
|
+
// B-257 — per-invocation: an in-process counter does not survive, so a declared limit needs a durable store.
|
|
347
|
+
enforcesRateLimit: "with-a-store",
|
|
346
348
|
async build(config, cwd, ctx) {
|
|
347
349
|
assertServicesUnsupported("cloudflare", readManifest(cwd));
|
|
348
350
|
await nodeAdapter.build(config, cwd, ctx);
|
|
@@ -412,4 +414,4 @@ export {
|
|
|
412
414
|
renderCloudflareWorkerEntry,
|
|
413
415
|
renderWranglerToml
|
|
414
416
|
};
|
|
415
|
-
//# sourceMappingURL=cloudflare-
|
|
417
|
+
//# sourceMappingURL=cloudflare-4M4XVNUH.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapters/cloudflare.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Cloudflare deploy adapter. All write paths are under `cwd/.theokit/cloudflare/`\n * and `cwd/wrangler.toml`. Build-time tool — no HTTP input.\n */\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport type { TheoConfig } from '../config/schema.js'\nimport { findRootDiv } from '../core/contracts/find-root-div.js'\nimport { parseAssetsMap } from '../core/contracts/module-preloads.js'\nimport type { SecurityHeadersConfig } from '../core/contracts/security-headers.js'\nimport { assertServicesUnsupported, readManifest } from '../services/index.js'\n\nimport { deployedAgentsFragment, type DeployedAgent } from './deployed-agents.js'\nimport { deployedCorsFragment, type DeployedCorsOptions } from './deployed-cors.js'\nimport { deployedCsrfFragment, type DeployedCsrfOptions } from './deployed-csrf.js'\nimport { planDeployedPlugins } from './deployed-plugins-module.js'\nimport {\n deployedRateLimitFragment,\n rateLimitCheckFragment,\n type DeployedRateLimitOptions,\n} from './deployed-rate-limit.js'\nimport {\n deployedRuntimeConfigFragment,\n serverDirLiteral,\n type DeployedRuntimeConfigOptions,\n type DeployedServerDirOptions,\n} from './deployed-runtime-config.js'\nimport { deployedTraceFragment } from './deployed-trace.js'\nimport { nodeAdapter } from './node.js'\nimport { describeDeployedSecurityHeaders, securityHeadersDeclarations } from './security-headers.js'\nimport type { AdapterBuildContext, DeployAdapter } from './types.js'\n\n/**\n * T2.1 — Cloudflare adapter rewritten to consume `theokit/adapters/web-shim`\n * instead of emitting an inline plain-object Request/Response shim. Reduces\n * template from ~50 lines to ~25 and centralizes maintenance.\n */\n\n/**\n * The built `index.html` split into the part before `<div id=\"root\">` and the\n * part after it.\n *\n * Refuses by name when streaming is on and the template is missing, rather than\n * emitting a worker that serves a headless document. A build that cannot produce\n * a correct artifact should say so at build time; the alternative is a deploy\n * that looks successful and serves pages with no stylesheet.\n */\n/**\n * @internal Exported for tests only. Nothing re-exports this module, so this does not reach the\n * published surface — `findRootDiv`, exported for the same reason, appears 0 times in `dist/`.\n */\nexport function readDocumentShell(\n cwd: string,\n streaming: boolean,\n): { htmlHead?: string; htmlTail?: string } {\n if (!streaming) return {}\n\n const indexPath = resolve(cwd, '.theokit/client/index.html')\n if (!existsSync(indexPath)) {\n throw new Error(\n `[adapter-cloudflare] ssrStreaming is on but ${indexPath} does not exist, so the worker ` +\n `would serve a document with no <head> and no client entry. Run the client build first, ` +\n `or set ssrStreaming: false in theo.config.ts.`,\n )\n }\n\n const indexHtml = readFileSync(indexPath, 'utf-8')\n const rootDiv = findRootDiv(indexHtml)\n if (rootDiv === undefined) {\n throw new Error(\n `[adapter-cloudflare] ${indexPath} has no <div id=\"root\">, so the streamed document has ` +\n `nowhere to put the app. Add one, or set ssrStreaming: false in theo.config.ts.`,\n )\n }\n\n return {\n htmlHead: indexHtml.slice(0, rootDiv.insertAt),\n htmlTail: indexHtml.slice(rootDiv.insertAt),\n }\n}\n\n/**\n * The routes, turned into source: static imports, a module map and a literal table (#369).\n *\n * Extracted so the worker renderer stays inside its length budget, and because this is the whole of\n * what changed about how a Worker finds a route — it reads as one idea rather than as three loops\n * inside a hundred lines of template.\n *\n * `../../` because the worker is written to `.theokit/cloudflare/worker.mjs` and `filePath` is\n * relative to the project root. The imports are static so Wrangler's bundler follows them:\n * `wrangler.toml` uploads `.theokit/client` and has never uploaded `server/`, so a module not\n * bundled INTO the worker is not on the platform at all.\n */\nfunction renderBakedRoutes(\n routes: readonly { filePath: string; routePath: string; methods?: readonly string[] }[],\n): { routeImports: string[]; routeModuleEntries: string[]; routeTableEntries: string[] } {\n const routeVar = (index: number): string => `__theoRoute${String(index)}`\n return {\n routeImports: routes.map(\n (route, index) => `import * as ${routeVar(index)} from '../../${route.filePath}'`,\n ),\n routeModuleEntries: routes.map(\n (route, index) => ` ${JSON.stringify(route.filePath)}: ${routeVar(index)},`,\n ),\n routeTableEntries: routes.map(\n (route) =>\n ` { filePath: ${JSON.stringify(route.filePath)}, routePath: ${JSON.stringify(route.routePath)}, ` +\n `methods: ${JSON.stringify([...(route.methods ?? [])])}, ` +\n `...compilePattern(${JSON.stringify(route.routePath)}) },`,\n ),\n }\n}\n\n/**\n * The route-resolution runtime the Worker gets instead of a directory scan (#369).\n *\n * A module map, the literal table, and a loader that refuses anything the build did not bake.\n * Emitted as its own block because it replaces one idea — \"find the routes\" — wholesale.\n */\nfunction routeRuntimeLines(moduleEntries: string[], tableEntries: string[]): string[] {\n return [\n `// #369 — the routes are baked at build time. The Worker used to reach for`,\n `// \\`scanServerRoutes\\` on the server directory — a readdirSync, in a runtime with no`,\n `// filesystem. The pattern is recompiled here from the same routePath the scanner`,\n `// used, so one function decides precedence on every target.`,\n `const ROUTE_MODULES = {`,\n ...moduleEntries,\n `}`,\n ``,\n `const routes = [`,\n ...tableEntries,\n `]`,\n ``,\n `// The executor asks for a module by the path the table names. Anything else was`,\n `// never bundled, and saying so beats returning undefined and failing later on a`,\n `// property access far from the cause.`,\n `async function loadModule(path) {`,\n ` const mod = ROUTE_MODULES[path]`,\n ` if (mod === undefined) {`,\n // No backticks in this message: it is emitted INTO a template literal, and a stray one closes\n // it. That is how #344 shipped a SyntaxError, and the emitted-entry parse gate caught this one\n // before it left the branch.\n \" throw new Error(`Route module '\" +\n '${path}' +\n \"' was not bundled into this Worker. \" +\n 'A Worker has no filesystem, so every route is imported at build time. ' +\n 'Re-run: theokit build --target cloudflare`)',\n ` }`,\n ` return mod`,\n `}`,\n ``,\n ]\n}\n\n/**\n * Read the map `theokit build` emitted, for baking into the worker (B-035).\n *\n * Returns `undefined` — never throws — for an absent or malformed file. A deploy that failed\n * because an optimisation was missing would turn a lost round trip into a broken build, and the\n * worker is correct without it.\n */\nexport function readAssetsMapForBake(path: string): Record<string, string[]> | undefined {\n try {\n return parseAssetsMap(readFileSync(path, 'utf8'))\n } catch {\n return undefined\n }\n}\n\n/**\n * The baked route-to-chunks map, as worker source (B-035).\n *\n * A literal and not a read, for the same reason the document shell is: a Worker has no filesystem\n * at request time. Emitted only when the build produced a map; otherwise the worker carries\n * nothing about preloads and behaves exactly as before.\n *\n * **It emits the DATA and no longer the code.** An earlier revision emitted a hand-written copy of\n * `injectModulePreloads`, justified by a claim that the worker could not import it. That claim was\n * false — `theokit/server` re-exports from `core/contracts/` and the generated worker already\n * imports that subpath — and the copy drifted within a day: a fix for proxy-form request targets\n * landed in the original and not in the duplicate. The worker now imports the real function, which\n * is the shape `adapters/security-headers.ts` established one directory over for exactly this\n * build-half/runtime-half pair.\n */\n/**\n * Whether this worker can preload at all (B-035).\n *\n * ONE predicate, read by the bake, the import and the call. Two conditions for one decision is\n * how the import came to be emitted for a worker that had no map to give it — found at review, in\n * the same change where a copy and its original had already drifted apart.\n *\n * Streaming is required because the other branch serves the document from `env.ASSETS` as a\n * static file and can inject nothing into it.\n */\nfunction preloadsApplyTo(opts: {\n ssrStreaming?: boolean\n assetsMap?: Record<string, string[]>\n}): boolean {\n return opts.ssrStreaming === true && opts.assetsMap !== undefined\n}\n\nfunction renderPreloadSupport(assetsMap: Record<string, string[]> | undefined): string {\n if (assetsMap === undefined) return ''\n return `const __THEO_ASSETS_MAP = ${JSON.stringify(assetsMap)}`\n}\n\n/**\n * The branch that answers a non-API request: streamed SSR, or the static asset the Worker\n * platform serves. Extracted at review — it is the one decision in this emitter with two whole\n * shapes behind it, and keeping it inline pushed the caller past its line budget.\n */\nfunction renderNonApiBranch(\n opts: NonNullable<Parameters<typeof renderCloudflareWorkerEntry>[0]>,\n preloadsApply: boolean,\n): string {\n return opts.ssrStreaming\n ? [\n ` // T2.3 — streaming SSR for non-API routes`,\n ` // The same primitive \\`theokit start\\` uses, not a second one:`,\n ` // 16 bytes of Web Crypto entropy, base64.`,\n ` const nonce = generateNonce()`,\n ` return withSecurityHeaders(`,\n ` await renderStreamingWeb(request, {`,\n !preloadsApply\n ? ` htmlHead: ${JSON.stringify(opts.htmlHead ?? '')},`\n : ` htmlHead: injectModulePreloads(${JSON.stringify(opts.htmlHead ?? '')}, __THEO_ASSETS_MAP, new URL(request.url).pathname),`,\n ` htmlTail: ${JSON.stringify(opts.htmlTail ?? '')},`,\n ` nonce,`,\n ` }),`,\n ` buildSecurityHeaders(SECURITY_HEADERS_CONFIG, { production: true }, { nonce }),`,\n ` )`,\n ].join('\\n')\n : [\n ` // #412 — the document, served by the worker so it carries the same baseline every`,\n ` // API response carries. It used to return 404 here while wrangler.toml declared a`,\n ` // \\`[site]\\` bucket nothing read, so the page was missing rather than unprotected.`,\n ` const assets = env?.ASSETS`,\n ` // A wrangler.toml that predates this binding has no ASSETS. Reading .fetch off`,\n ` // undefined would turn every page request into a 500; 404 is what this target`,\n ` // answered before, which is the honest fallback rather than a new failure.`,\n ` if (assets === undefined) return notFoundResponse()`,\n ` return withSecurityHeaders(await assets.fetch(request), SECURITY_HEADERS)`,\n ].join('\\n')\n}\n\nexport function renderCloudflareWorkerEntry(\n opts: {\n ssrStreaming?: boolean\n htmlHead?: string\n htmlTail?: string\n /**\n * B-035 — the route-to-chunks map, baked as a literal for the same reason the shell above\n * is: a Worker has no filesystem at request time. Absent when the build produced no map,\n * and then nothing about preloads is emitted at all.\n */\n assetsMap?: Record<string, string[]>\n securityHeaders?: SecurityHeadersConfig\n /**\n * The server routes, scanned on the BUILD machine (#369).\n *\n * A Worker has no filesystem, so the worker used to call `scanServerRoutes` — a `readdirSync` —\n * against a directory that does not exist there, and load each module through `import()` of a\n * file path. Both are baked here instead, which is the road this adapter already takes for the\n * document shell one function away.\n *\n * `filePath` is relative to the project root and is used for two things: the key the executor\n * looks a module up by, and the specifier the static import uses. Paths are emitted relative to\n * `.theokit/cloudflare/`, where the worker is written.\n */\n routes?: readonly { filePath: string; routePath: string; methods?: readonly string[] }[]\n /**\n * The two concerns #410 could not bake (#425), composed from one place so the six targets\n * cannot drift into six spellings. `serialization` is a literal like the security values above;\n * `plugins` is an import, because a closure has no literal.\n */\n runtimeConfigModule?: DeployedRuntimeConfigOptions['runtimeConfigModule']\n serialization?: DeployedRuntimeConfigOptions['serialization']\n /**\n * The app's agents, scanned on the build machine (#367).\n *\n * A different scan from `routes` and served by a different function — which is why a worker\n * that only consulted the route table answered every `/api/agents/<name>` with a 404.\n */\n agents?: readonly DeployedAgent[]\n /** B-185 — the app's `server/context.ts`, project-relative, or absent when it declares none. */\n contextModule?: string\n /** WebSocket route files, scanned on the build machine. Only their presence is used (#369). */\n wsRoutes?: readonly string[]\n } & DeployedServerDirOptions &\n DeployedCsrfOptions &\n DeployedCorsOptions &\n DeployedRateLimitOptions = {},\n): string {\n const streamingImport = opts.ssrStreaming\n ? `import { renderStreamingWeb } from '/@theo/entry-server'`\n : `// (ssrStreaming off: renderStreamingWeb not imported)`\n // #343 — the document shell is inlined as a build-time literal because a Worker\n // has no filesystem to read `index.html` from at request time. Without it,\n // `renderStreamingWeb` falls back to its empty-string defaults and the response\n // is React output with no `<html>`, no `<head>`, no stylesheet and no client\n // entry — hydration data for a page that cannot hydrate. The streaming\n // assembly was fixed in the generated entry and this, its only caller, was\n // left passing nothing.\n //\n // `JSON.stringify` and not a template literal: the shell contains quotes,\n // angle brackets and a `</script>`, and embedding it naively produces a worker\n // that fails to parse at deploy time rather than here.\n //\n // #410 — this is also the ONE deploy path that renders HTML at request time,\n // so the one that can mint a per-request CSP nonce: `renderStreamingWeb`\n // threads `options.nonce` into `renderToReadableStream` and into the hydration\n // script (`router/entry-server.ts`). Every other response below carries the\n // nonce-less baseline, which is what `buildSecurityHeaders` already does for a\n // prerendered route (EC-4).\n // Only the streaming branch renders HTML at request time; the other serves the document from\n // `env.ASSETS` as a static file and can inject nothing. Baking the map for it would ship the whole\n // route table as dead weight — found at review, where the emitter was measured declaring it with\n // zero call sites.\n const preloadsApply = preloadsApplyTo(opts)\n const preloadSupport = preloadsApply ? renderPreloadSupport(opts.assetsMap) : ''\n\n const nonApiBranch = renderNonApiBranch(opts, preloadsApply)\n\n // CR-006: Workers lack `process.cwd()` and the `node:*` import surface\n // is brittle even under `nodejs_compat`. We use the Web Crypto\n // `crypto.randomUUID()` instead of `node:crypto.randomUUID`, and embed\n // the server directory as a build-time literal instead of resolving via\n // `node:path` at runtime.\n const { routeImports, routeModuleEntries, routeTableEntries } = renderBakedRoutes(\n opts.routes ?? [],\n )\n const runtimeConfig = deployedRuntimeConfigFragment(opts)\n const agentsFragment = deployedAgentsFragment(\n opts.agents === undefined\n ? undefined\n : // B-185 — a Worker has no filesystem, so its identity module is baked exactly like its\n // agents and its routes (ADR 0014). `contextModule` is `undefined` for an app that\n // declares none, and the generator then emits no import for it.\n { kind: 'baked', agents: opts.agents, contextModule: opts.contextModule },\n {\n wrapSecurityHeaders: true,\n // B-185 — bound only when the runtime-config fragment declared the const, which is\n // exactly when a plugins module was emitted. Referencing it otherwise would emit an\n // identifier the entry never declares.\n pluginRunnerExpr:\n opts.runtimeConfigModule === undefined ? undefined : 'await THEO_PLUGIN_RUNNER',\n },\n )\n\n return [\n `// Generated by Theo — Cloudflare Workers Adapter`,\n `//`,\n `// REQUIREMENTS (EC-3):`,\n `// - wrangler.toml MUST include compatibility_flags = [\"nodejs_compat\"]`,\n `// (still required for transitive theokit/server deps, e.g. busboy)`,\n `// - package.json MUST list \"theokit\" in dependencies (not devDependencies)`,\n `// so Wrangler bundles theokit and its transitive deps`,\n `// - Deploy: wrangler deploy`,\n ``,\n !preloadsApply\n ? `import { matchRoute, executeRoute, compilePattern, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server'`\n : `import { matchRoute, executeRoute, compilePattern, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server'\\nimport { injectModulePreloads } from 'theokit/server/http'`,\n `import { createWebShim } from 'theokit/adapters/web-shim'`,\n opts.ssrStreaming\n ? `import { buildSecurityHeaders, generateNonce, withSecurityHeaders } from 'theokit/adapters/security-headers'`\n : `import { buildSecurityHeaders, withSecurityHeaders } from 'theokit/adapters/security-headers'`,\n `// T3.4 — WS bridge for Cloudflare Workers`,\n `import { createCloudflareWsBridge } from 'theokit/adapters/ws-shim'`,\n // B-027 — only when a limit is declared. `createRateLimiterWeb` is used at module scope by the\n // fragment below and was imported by no target but bun, so an entry that declared a limit threw\n // when it LOADED. `resolveClientIpFromRequest` is the forwarded-header fallback, behind\n // `trustProxy`; the primary source is `cf-connecting-ip`, which the Workers runtime writes.\n ...(opts.rateLimit === undefined\n ? []\n : [\n `import { createRateLimiterWeb } from 'theokit/server'`,\n `import { resolveClientIpFromRequest } from 'theokit/server/rate-limit'`,\n ]),\n streamingImport,\n ``,\n ...runtimeConfig.imports,\n ...agentsFragment.imports,\n ...routeImports,\n ``,\n `// CR-006: server directory is a build-time literal — Workers cannot`,\n `// call process.cwd() and resolving paths at runtime returned '/server'.`,\n `const serverDir = ${serverDirLiteral(opts)}`,\n ``,\n ...routeRuntimeLines(routeModuleEntries, routeTableEntries),\n `// #410 — the security baseline \\`theokit start\\` puts on every response, carried`,\n `// here as a literal because a Worker has no theo.config.ts to read. Same`,\n `// function, same input, so the deployed page and the local one cannot`,\n `// disagree about what the configuration means.`,\n preloadSupport,\n ...securityHeadersDeclarations(opts.securityHeaders),\n ``,\n ...deployedCsrfFragment(opts, 'a Worker'),\n ``,\n ...runtimeConfig.declarations,\n ...agentsFragment.declarations,\n ...deployedCorsFragment(opts.cors, 'cloudflare'),\n `// #369 — whether this project declares a WebSocket route, decided at build time. It used`,\n `// to answer it with \\`scanWebSocketRoutes\\`, which is the same readdirSync.`,\n `const HAS_WS_ROUTES = ${String((opts.wsRoutes ?? []).length > 0)}`,\n ``,\n `function notFoundResponse() {`,\n ` return withSecurityHeaders(`,\n ` new Response(`,\n ` JSON.stringify({ error: { code: 'NOT_FOUND', message: 'Route not found' } }),`,\n ` { status: 404, headers: { 'Content-Type': 'application/json' } },`,\n ` ),`,\n ` SECURITY_HEADERS,`,\n ` )`,\n `}`,\n ``,\n ...cloudflareHandleRequestFragment(\n nonApiBranch,\n runtimeConfig.executeRouteSpread,\n agentsFragment.branch,\n agentsFragment.hostBypass,\n opts.rateLimit,\n ),\n ].join('\\n')\n}\n\n/**\n * The Worker's request handler, as generated source.\n *\n * Extracted for the reason `vercel.ts` extracts its own fragments: the emitter is one array\n * literal, so every line the entry gains counts against `max-lines-per-function`, and #410 added\n * the CSRF literal to an emitter already sitting exactly at the ceiling.\n *\n * @param nonApiBranch - what a non-`/api/` request gets, which differs with `ssrStreaming`\n */\nfunction cloudflareHandleRequestFragment(\n nonApiBranch: string,\n runtimeSpread: string,\n agentBranch: readonly string[],\n /** SI-020 — the condition that keeps an agent card path out of the static-asset branch. */\n hostBypass: string,\n /** B-027 — the declared limit, or `undefined`. Passed rather than read: this fragment is a\n * separate function from `renderCloudflareWorkerEntry`, where `opts` is bound. */\n rateLimit: DeployedRateLimitOptions['rateLimit'],\n): string[] {\n return [\n `async function handleRequest(request, url, env) {`,\n ` if (!url.pathname.startsWith('/api/')${hostBypass}) {`,\n nonApiBranch,\n ` }`,\n ``,\n ...agentBranch,\n ``,\n ` const match = matchRoute(url.pathname, routes)`,\n ` if (!match) return notFoundResponse()`,\n ``,\n ` const { req, res, toResponse } = createWebShim(request, { trustedProxy: 'platform' })`,\n ...deployedTraceFragment('request', ' '),\n ` const method = request.method.toUpperCase()`,\n ` // #382 — the run is NOT awaited before the Response is taken. toResponse()`,\n ` // settles as soon as status + headers are known and carries a live body, so`,\n ` // the Worker starts flushing while the handler is still writing. Awaiting`,\n ` // executeRoute() first would re-buffer the whole response here even though`,\n ` // the shim streams; awaiting toResponse() does not — it settles at the head.`,\n ` return withSecurityHeaders(await toResponse(executeRoute({`,\n ` route: match.route, method, params: match.params,`,\n ` req, res, loadModule, serverDir, requestId, ...CSRF_CONFIG, ${runtimeSpread}`,\n ` })), SECURITY_HEADERS)`,\n `}`,\n ``,\n ...deployedRateLimitFragment(\n rateLimit,\n 'cloudflare',\n // `cf-connecting-ip` is the RUNTIME's answer and a caller cannot forge it through the edge.\n // A Worker reached directly has none, and then only a declared `trustProxy` produces an\n // address — otherwise `undefined`, which is the named 503 rather than everyone's bucket.\n `request.headers.get('cf-connecting-ip') ?? resolveClientIpFromRequest(request, TRUST_PROXY)`,\n // `request` alone: the handler binds `(request, env, ctx)` and the header is on the request.\n 'request',\n ),\n ``,\n `export default {`,\n ` async fetch(request, env, ctx) {`,\n ` const url = new URL(request.url)`,\n ``,\n ` // #409 — the preflight is answered BEFORE anything routes: an OPTIONS the router handles`,\n ` // is an OPTIONS the browser never gets a CORS answer to. The WebSocket upgrade above is`,\n ` // deliberately upstream of it — a 101 is not a CORS-governed response.`,\n ` const preflight = corsPreflight(request)`,\n ` if (preflight !== null) return withSecurityHeaders(preflight, SECURITY_HEADERS)`,\n ...rateLimitCheckFragment(rateLimit, ' ', 'request'),\n ``,\n ` // LCR0103 — the upgrade branch sits BELOW the limiter, and the order is the point.`,\n ` // It used to sit above, under the comment \"a 101 carries no document and no script,`,\n ` // so the security baseline does not apply to it\". That is true of the security`,\n ` // HEADERS — a document concern — and false of the limiter, which is a resource`,\n ` // concern: a long-lived socket is the most expensive thing this entry hands out, so`,\n ` // the upgrade is the path that most needs a budget, not the one that may skip it.`,\n ` // T3.4 — Detect WebSocket upgrade and delegate to the CF bridge.`,\n ` // A 101 carries no document and no script, so the security baseline does`,\n ` // not apply to it.`,\n ` if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {`,\n ` if (!HAS_WS_ROUTES) return notFoundResponse()`,\n ` const cfWs = createCloudflareWsBridge({`,\n ` onOpen: () => {},`,\n ` onMessage: (ws, data) => { ws.send(data) },`,\n ` onClose: () => {},`,\n ` })`,\n ` return cfWs.handle(request)`,\n ` }`,\n ``,\n ` return withCors(request, await handleRequest(request, url, env))`,\n ` },`,\n `}`,\n ]\n}\n\nexport function renderWranglerToml(): string {\n return [\n `# Generated by Theo — Cloudflare Workers`,\n `name = \"theo-app\"`,\n `main = \".theokit/cloudflare/worker.mjs\"`,\n `compatibility_date = \"2025-09-01\"`,\n `compatibility_flags = [\"nodejs_compat\"]`,\n ``,\n `# #412 — \\`[assets]\\` with a BINDING, not the legacy \\`[site]\\` bucket.`,\n `#`,\n `# \\`[site]\\` uploads to KV and is read through \\`kv-asset-handler\\` and a`,\n `# \\`__STATIC_CONTENT\\` binding — neither of which this worker has ever had. So the`,\n `# bucket was declared, uploaded, and consumed by nothing: with ssrStreaming off, a`,\n `# deploy answered 404 for its own page. This binding is what the worker calls.`,\n `[assets]`,\n `directory = \".theokit/client\"`,\n `binding = \"ASSETS\"`,\n `# A client-routed app asks for /dashboard, which is no file. Without this the asset`,\n `# handler 404s a deep link and the SPA never boots.`,\n `not_found_handling = \"single-page-application\"`,\n ``,\n `# Environment variables are set via wrangler secret or dashboard`,\n `# Example: wrangler secret put DATABASE_URL`,\n ].join('\\n')\n}\n\nexport const cloudflareAdapter: DeployAdapter = {\n name: 'cloudflare',\n streamsResponses: true,\n // #409 / #410 — the generated entry calls `executeRoute` with routes, loader\n // and serverDir only. CSRF, route policy, file middleware and Zod validation\n // still run because they live inside `executeRoute`; none of the remaining\n // configurable concerns reach it. Declared explicitly rather than omitted so\n // the gap is a statement in the source and not an absence.\n //\n // `securityHeaders` IS applied: the worker carries `security.headers` as a\n // literal and puts the built baseline on every response it returns, including\n // the streamed SSR document — with a per-request nonce, the only deploy path\n // that can mint one (`adapters/security-headers.ts`).\n servesAgents: true,\n appliesConfig: ['securityHeaders', 'csrf', 'disallowed', 'cors', 'serialization', 'plugins'],\n\n async build(config: TheoConfig, cwd: string, ctx?: AdapterBuildContext): Promise<void> {\n // Wave 2 (T2.2) — reject polyglot services on this adapter.\n assertServicesUnsupported('cloudflare', readManifest(cwd))\n\n // 1. Run the standard Node build first (ctx forwarded so nodeAdapter has makeVitePlugins)\n await nodeAdapter.build(config, cwd, ctx)\n\n const outputDir = resolve(cwd, '.theokit/cloudflare')\n mkdirSync(outputDir, { recursive: true })\n\n // 2. Emit Worker entry (now uses the shared web-shim)\n //\n // The document shell is read HERE, after the Node build produced\n // `.theokit/client/index.html`, and inlined into the worker: a Worker has no\n // filesystem at request time. Split on the root div with the same helper the\n // Node server uses (`ssr-setup.ts`), so the two paths cannot disagree about\n // where the shell ends (#343).\n const shell = readDocumentShell(cwd, config.ssrStreaming)\n // B-035 — the route-to-chunks map, read HERE on the build machine for the same reason the\n // shell above is: a Worker has no filesystem at request time. `nodeAdapter.build` ran\n // first, so the map the Node build emitted is on disk by now. Absent map -> nothing about\n // preloads is emitted, and the worker behaves exactly as it did before.\n const assetsMap = readAssetsMapForBake(resolve(cwd, '.theokit', 'client', 'assets-map.json'))\n\n // #369 — the routes are resolved HERE, on the build machine, for the same reason the document\n // shell above is read here: a Worker has no filesystem at request time, and the worker used to\n // run the scan itself against a directory that does not exist there.\n //\n // The scanner is INJECTED rather than imported: importing it would add an `adapters → server`\n // edge, which is the layering inversion ADR-0001 v3 removed for `vite-plugin` and which\n // `adapters-may-only-depend-on-core-router-services` refuses. An absent scanner emits a worker\n // with no routes rather than falling back to a runtime scan — the fallback IS the defect.\n const scanned = ctx?.scanRoutes?.(config.serverDir) ?? {\n routes: [],\n wsRoutes: [],\n agents: [],\n // B-185 — no provider means no scan, and an app whose context nobody looked for is\n // indistinguishable here from one that has none. Both resolve an anonymous caller, which is\n // the honest answer rather than an invented subject.\n contextModule: undefined,\n }\n\n const pluginsPlan = planDeployedPlugins(config.plugins, 'cloudflare')\n if (pluginsPlan !== undefined) {\n // Beside the worker, so the emitted import is a sibling. Wrangler bundles from here, which is\n // what lets the static import reach the app's own module at all (#425).\n writeFileSync(resolve(outputDir, 'theo.plugins.mjs'), pluginsPlan.source)\n }\n\n writeFileSync(\n resolve(outputDir, 'worker.mjs'),\n renderCloudflareWorkerEntry({\n ssrStreaming: config.ssrStreaming,\n ...shell,\n securityHeaders: config.security?.headers,\n csrf: config.security?.csrf,\n disallowed: config.security?.disallowed,\n cors: config.security?.cors,\n assetsMap,\n // #425 — a selector, not a transformer, so it rides as a literal like the values above.\n serialization: config.serialization,\n // #425 — the ONE concern that is not a literal. A closure cannot be baked, so a plugin\n // declared by module specifier is imported by the emitted module instead; a constructed one\n // is refused by name at build time rather than dropped in silence.\n runtimeConfigModule: pluginsPlan?.moduleSpecifier,\n routes: scanned.routes,\n // #367 — a Worker has no filesystem, so its agents are decided here like its routes.\n agents: scanned.agents,\n // B-185 — rides beside the agents because it is decided by the same provider, for the same\n // reason: `build.ts` holds `serverDir` and a Worker cannot look for the module itself.\n contextModule: scanned.contextModule,\n wsRoutes: scanned.wsRoutes,\n }),\n )\n\n // 3. Emit wrangler.toml (with nodejs_compat enforced)\n writeFileSync(resolve(cwd, 'wrangler.toml'), renderWranglerToml())\n\n // eslint-disable-next-line no-console -- CLI build progress\n console.log('\\n ✓ Cloudflare output → .theokit/cloudflare/ + wrangler.toml')\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(\n `${describeDeployedSecurityHeaders({\n target: 'cloudflare',\n securityHeaders: config.security?.headers,\n // Only the streaming worker renders HTML per request, so only it can put\n // the same nonce on the header and on the script tag it emits.\n mintsNonce: config.ssrStreaming,\n // #412 — either way the worker returns the document now: streamed by\n // `renderStreamingWeb`, or from the ASSETS binding it finally calls.\n documentHeaders: 'handler',\n })}\\n`,\n )\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,eAAe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U;AAAA,QACvB,YAAY,OAAO,UAAU;AAAA,QAC7B,MAAM,OAAO,UAAU;AAAA,QACvB;AAAA;AAAA,QAEA,eAAe,OAAO;AAAA;AAAA;AAAA;AAAA,QAItB,qBAAqB,aAAa;AAAA,QAClC,QAAQ,QAAQ;AAAA;AAAA,QAEhB,QAAQ,QAAQ;AAAA;AAAA;AAAA,QAGhB,eAAe,QAAQ;AAAA,QACvB,UAAU,QAAQ;AAAA,MACpB,CAAC;AAAA,IACH;AAGA,kBAAc,QAAQ,KAAK,eAAe,GAAG,mBAAmB,CAAC;AAGjE,YAAQ,IAAI,0EAAgE;AAE5E,YAAQ;AAAA,MACN,GAAG,gCAAgC;AAAA,QACjC,QAAQ;AAAA,QACR,iBAAiB,OAAO,UAAU;AAAA;AAAA;AAAA,QAGlC,YAAY,OAAO;AAAA;AAAA;AAAA,QAGnB,iBAAiB;AAAA,MACnB,CAAC,CAAC;AAAA;AAAA,IACJ;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/adapters/cloudflare.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Cloudflare deploy adapter. All write paths are under `cwd/.theokit/cloudflare/`\n * and `cwd/wrangler.toml`. Build-time tool — no HTTP input.\n */\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport type { TheoConfig } from '../config/schema.js'\nimport { findRootDiv } from '../core/contracts/find-root-div.js'\nimport { parseAssetsMap } from '../core/contracts/module-preloads.js'\nimport type { SecurityHeadersConfig } from '../core/contracts/security-headers.js'\nimport { assertServicesUnsupported, readManifest } from '../services/index.js'\n\nimport { deployedAgentsFragment, type DeployedAgent } from './deployed-agents.js'\nimport { deployedCorsFragment, type DeployedCorsOptions } from './deployed-cors.js'\nimport { deployedCsrfFragment, type DeployedCsrfOptions } from './deployed-csrf.js'\nimport { planDeployedPlugins } from './deployed-plugins-module.js'\nimport {\n deployedRateLimitFragment,\n rateLimitCheckFragment,\n type DeployedRateLimitOptions,\n} from './deployed-rate-limit.js'\nimport {\n deployedRuntimeConfigFragment,\n serverDirLiteral,\n type DeployedRuntimeConfigOptions,\n type DeployedServerDirOptions,\n} from './deployed-runtime-config.js'\nimport { deployedTraceFragment } from './deployed-trace.js'\nimport { nodeAdapter } from './node.js'\nimport { describeDeployedSecurityHeaders, securityHeadersDeclarations } from './security-headers.js'\nimport type { AdapterBuildContext, DeployAdapter } from './types.js'\n\n/**\n * T2.1 — Cloudflare adapter rewritten to consume `theokit/adapters/web-shim`\n * instead of emitting an inline plain-object Request/Response shim. Reduces\n * template from ~50 lines to ~25 and centralizes maintenance.\n */\n\n/**\n * The built `index.html` split into the part before `<div id=\"root\">` and the\n * part after it.\n *\n * Refuses by name when streaming is on and the template is missing, rather than\n * emitting a worker that serves a headless document. A build that cannot produce\n * a correct artifact should say so at build time; the alternative is a deploy\n * that looks successful and serves pages with no stylesheet.\n */\n/**\n * @internal Exported for tests only. Nothing re-exports this module, so this does not reach the\n * published surface — `findRootDiv`, exported for the same reason, appears 0 times in `dist/`.\n */\nexport function readDocumentShell(\n cwd: string,\n streaming: boolean,\n): { htmlHead?: string; htmlTail?: string } {\n if (!streaming) return {}\n\n const indexPath = resolve(cwd, '.theokit/client/index.html')\n if (!existsSync(indexPath)) {\n throw new Error(\n `[adapter-cloudflare] ssrStreaming is on but ${indexPath} does not exist, so the worker ` +\n `would serve a document with no <head> and no client entry. Run the client build first, ` +\n `or set ssrStreaming: false in theo.config.ts.`,\n )\n }\n\n const indexHtml = readFileSync(indexPath, 'utf-8')\n const rootDiv = findRootDiv(indexHtml)\n if (rootDiv === undefined) {\n throw new Error(\n `[adapter-cloudflare] ${indexPath} has no <div id=\"root\">, so the streamed document has ` +\n `nowhere to put the app. Add one, or set ssrStreaming: false in theo.config.ts.`,\n )\n }\n\n return {\n htmlHead: indexHtml.slice(0, rootDiv.insertAt),\n htmlTail: indexHtml.slice(rootDiv.insertAt),\n }\n}\n\n/**\n * The routes, turned into source: static imports, a module map and a literal table (#369).\n *\n * Extracted so the worker renderer stays inside its length budget, and because this is the whole of\n * what changed about how a Worker finds a route — it reads as one idea rather than as three loops\n * inside a hundred lines of template.\n *\n * `../../` because the worker is written to `.theokit/cloudflare/worker.mjs` and `filePath` is\n * relative to the project root. The imports are static so Wrangler's bundler follows them:\n * `wrangler.toml` uploads `.theokit/client` and has never uploaded `server/`, so a module not\n * bundled INTO the worker is not on the platform at all.\n */\nfunction renderBakedRoutes(\n routes: readonly { filePath: string; routePath: string; methods?: readonly string[] }[],\n): { routeImports: string[]; routeModuleEntries: string[]; routeTableEntries: string[] } {\n const routeVar = (index: number): string => `__theoRoute${String(index)}`\n return {\n routeImports: routes.map(\n (route, index) => `import * as ${routeVar(index)} from '../../${route.filePath}'`,\n ),\n routeModuleEntries: routes.map(\n (route, index) => ` ${JSON.stringify(route.filePath)}: ${routeVar(index)},`,\n ),\n routeTableEntries: routes.map(\n (route) =>\n ` { filePath: ${JSON.stringify(route.filePath)}, routePath: ${JSON.stringify(route.routePath)}, ` +\n `methods: ${JSON.stringify([...(route.methods ?? [])])}, ` +\n `...compilePattern(${JSON.stringify(route.routePath)}) },`,\n ),\n }\n}\n\n/**\n * The route-resolution runtime the Worker gets instead of a directory scan (#369).\n *\n * A module map, the literal table, and a loader that refuses anything the build did not bake.\n * Emitted as its own block because it replaces one idea — \"find the routes\" — wholesale.\n */\nfunction routeRuntimeLines(moduleEntries: string[], tableEntries: string[]): string[] {\n return [\n `// #369 — the routes are baked at build time. The Worker used to reach for`,\n `// \\`scanServerRoutes\\` on the server directory — a readdirSync, in a runtime with no`,\n `// filesystem. The pattern is recompiled here from the same routePath the scanner`,\n `// used, so one function decides precedence on every target.`,\n `const ROUTE_MODULES = {`,\n ...moduleEntries,\n `}`,\n ``,\n `const routes = [`,\n ...tableEntries,\n `]`,\n ``,\n `// The executor asks for a module by the path the table names. Anything else was`,\n `// never bundled, and saying so beats returning undefined and failing later on a`,\n `// property access far from the cause.`,\n `async function loadModule(path) {`,\n ` const mod = ROUTE_MODULES[path]`,\n ` if (mod === undefined) {`,\n // No backticks in this message: it is emitted INTO a template literal, and a stray one closes\n // it. That is how #344 shipped a SyntaxError, and the emitted-entry parse gate caught this one\n // before it left the branch.\n \" throw new Error(`Route module '\" +\n '${path}' +\n \"' was not bundled into this Worker. \" +\n 'A Worker has no filesystem, so every route is imported at build time. ' +\n 'Re-run: theokit build --target cloudflare`)',\n ` }`,\n ` return mod`,\n `}`,\n ``,\n ]\n}\n\n/**\n * Read the map `theokit build` emitted, for baking into the worker (B-035).\n *\n * Returns `undefined` — never throws — for an absent or malformed file. A deploy that failed\n * because an optimisation was missing would turn a lost round trip into a broken build, and the\n * worker is correct without it.\n */\nexport function readAssetsMapForBake(path: string): Record<string, string[]> | undefined {\n try {\n return parseAssetsMap(readFileSync(path, 'utf8'))\n } catch {\n return undefined\n }\n}\n\n/**\n * The baked route-to-chunks map, as worker source (B-035).\n *\n * A literal and not a read, for the same reason the document shell is: a Worker has no filesystem\n * at request time. Emitted only when the build produced a map; otherwise the worker carries\n * nothing about preloads and behaves exactly as before.\n *\n * **It emits the DATA and no longer the code.** An earlier revision emitted a hand-written copy of\n * `injectModulePreloads`, justified by a claim that the worker could not import it. That claim was\n * false — `theokit/server` re-exports from `core/contracts/` and the generated worker already\n * imports that subpath — and the copy drifted within a day: a fix for proxy-form request targets\n * landed in the original and not in the duplicate. The worker now imports the real function, which\n * is the shape `adapters/security-headers.ts` established one directory over for exactly this\n * build-half/runtime-half pair.\n */\n/**\n * Whether this worker can preload at all (B-035).\n *\n * ONE predicate, read by the bake, the import and the call. Two conditions for one decision is\n * how the import came to be emitted for a worker that had no map to give it — found at review, in\n * the same change where a copy and its original had already drifted apart.\n *\n * Streaming is required because the other branch serves the document from `env.ASSETS` as a\n * static file and can inject nothing into it.\n */\nfunction preloadsApplyTo(opts: {\n ssrStreaming?: boolean\n assetsMap?: Record<string, string[]>\n}): boolean {\n return opts.ssrStreaming === true && opts.assetsMap !== undefined\n}\n\nfunction renderPreloadSupport(assetsMap: Record<string, string[]> | undefined): string {\n if (assetsMap === undefined) return ''\n return `const __THEO_ASSETS_MAP = ${JSON.stringify(assetsMap)}`\n}\n\n/**\n * The branch that answers a non-API request: streamed SSR, or the static asset the Worker\n * platform serves. Extracted at review — it is the one decision in this emitter with two whole\n * shapes behind it, and keeping it inline pushed the caller past its line budget.\n */\nfunction renderNonApiBranch(\n opts: NonNullable<Parameters<typeof renderCloudflareWorkerEntry>[0]>,\n preloadsApply: boolean,\n): string {\n return opts.ssrStreaming\n ? [\n ` // T2.3 — streaming SSR for non-API routes`,\n ` // The same primitive \\`theokit start\\` uses, not a second one:`,\n ` // 16 bytes of Web Crypto entropy, base64.`,\n ` const nonce = generateNonce()`,\n ` return withSecurityHeaders(`,\n ` await renderStreamingWeb(request, {`,\n !preloadsApply\n ? ` htmlHead: ${JSON.stringify(opts.htmlHead ?? '')},`\n : ` htmlHead: injectModulePreloads(${JSON.stringify(opts.htmlHead ?? '')}, __THEO_ASSETS_MAP, new URL(request.url).pathname),`,\n ` htmlTail: ${JSON.stringify(opts.htmlTail ?? '')},`,\n ` nonce,`,\n ` }),`,\n ` buildSecurityHeaders(SECURITY_HEADERS_CONFIG, { production: true }, { nonce }),`,\n ` )`,\n ].join('\\n')\n : [\n ` // #412 — the document, served by the worker so it carries the same baseline every`,\n ` // API response carries. It used to return 404 here while wrangler.toml declared a`,\n ` // \\`[site]\\` bucket nothing read, so the page was missing rather than unprotected.`,\n ` const assets = env?.ASSETS`,\n ` // A wrangler.toml that predates this binding has no ASSETS. Reading .fetch off`,\n ` // undefined would turn every page request into a 500; 404 is what this target`,\n ` // answered before, which is the honest fallback rather than a new failure.`,\n ` if (assets === undefined) return notFoundResponse()`,\n ` return withSecurityHeaders(await assets.fetch(request), SECURITY_HEADERS)`,\n ].join('\\n')\n}\n\nexport function renderCloudflareWorkerEntry(\n opts: {\n ssrStreaming?: boolean\n htmlHead?: string\n htmlTail?: string\n /**\n * B-035 — the route-to-chunks map, baked as a literal for the same reason the shell above\n * is: a Worker has no filesystem at request time. Absent when the build produced no map,\n * and then nothing about preloads is emitted at all.\n */\n assetsMap?: Record<string, string[]>\n securityHeaders?: SecurityHeadersConfig\n /**\n * The server routes, scanned on the BUILD machine (#369).\n *\n * A Worker has no filesystem, so the worker used to call `scanServerRoutes` — a `readdirSync` —\n * against a directory that does not exist there, and load each module through `import()` of a\n * file path. Both are baked here instead, which is the road this adapter already takes for the\n * document shell one function away.\n *\n * `filePath` is relative to the project root and is used for two things: the key the executor\n * looks a module up by, and the specifier the static import uses. Paths are emitted relative to\n * `.theokit/cloudflare/`, where the worker is written.\n */\n routes?: readonly { filePath: string; routePath: string; methods?: readonly string[] }[]\n /**\n * The two concerns #410 could not bake (#425), composed from one place so the six targets\n * cannot drift into six spellings. `serialization` is a literal like the security values above;\n * `plugins` is an import, because a closure has no literal.\n */\n runtimeConfigModule?: DeployedRuntimeConfigOptions['runtimeConfigModule']\n serialization?: DeployedRuntimeConfigOptions['serialization']\n /**\n * The app's agents, scanned on the build machine (#367).\n *\n * A different scan from `routes` and served by a different function — which is why a worker\n * that only consulted the route table answered every `/api/agents/<name>` with a 404.\n */\n agents?: readonly DeployedAgent[]\n /** B-185 — the app's `server/context.ts`, project-relative, or absent when it declares none. */\n contextModule?: string\n /** WebSocket route files, scanned on the build machine. Only their presence is used (#369). */\n wsRoutes?: readonly string[]\n } & DeployedServerDirOptions &\n DeployedCsrfOptions &\n DeployedCorsOptions &\n DeployedRateLimitOptions = {},\n): string {\n const streamingImport = opts.ssrStreaming\n ? `import { renderStreamingWeb } from '/@theo/entry-server'`\n : `// (ssrStreaming off: renderStreamingWeb not imported)`\n // #343 — the document shell is inlined as a build-time literal because a Worker\n // has no filesystem to read `index.html` from at request time. Without it,\n // `renderStreamingWeb` falls back to its empty-string defaults and the response\n // is React output with no `<html>`, no `<head>`, no stylesheet and no client\n // entry — hydration data for a page that cannot hydrate. The streaming\n // assembly was fixed in the generated entry and this, its only caller, was\n // left passing nothing.\n //\n // `JSON.stringify` and not a template literal: the shell contains quotes,\n // angle brackets and a `</script>`, and embedding it naively produces a worker\n // that fails to parse at deploy time rather than here.\n //\n // #410 — this is also the ONE deploy path that renders HTML at request time,\n // so the one that can mint a per-request CSP nonce: `renderStreamingWeb`\n // threads `options.nonce` into `renderToReadableStream` and into the hydration\n // script (`router/entry-server.ts`). Every other response below carries the\n // nonce-less baseline, which is what `buildSecurityHeaders` already does for a\n // prerendered route (EC-4).\n // Only the streaming branch renders HTML at request time; the other serves the document from\n // `env.ASSETS` as a static file and can inject nothing. Baking the map for it would ship the whole\n // route table as dead weight — found at review, where the emitter was measured declaring it with\n // zero call sites.\n const preloadsApply = preloadsApplyTo(opts)\n const preloadSupport = preloadsApply ? renderPreloadSupport(opts.assetsMap) : ''\n\n const nonApiBranch = renderNonApiBranch(opts, preloadsApply)\n\n // CR-006: Workers lack `process.cwd()` and the `node:*` import surface\n // is brittle even under `nodejs_compat`. We use the Web Crypto\n // `crypto.randomUUID()` instead of `node:crypto.randomUUID`, and embed\n // the server directory as a build-time literal instead of resolving via\n // `node:path` at runtime.\n const { routeImports, routeModuleEntries, routeTableEntries } = renderBakedRoutes(\n opts.routes ?? [],\n )\n const runtimeConfig = deployedRuntimeConfigFragment(opts)\n const agentsFragment = deployedAgentsFragment(\n opts.agents === undefined\n ? undefined\n : // B-185 — a Worker has no filesystem, so its identity module is baked exactly like its\n // agents and its routes (ADR 0014). `contextModule` is `undefined` for an app that\n // declares none, and the generator then emits no import for it.\n { kind: 'baked', agents: opts.agents, contextModule: opts.contextModule },\n {\n wrapSecurityHeaders: true,\n // B-185 — bound only when the runtime-config fragment declared the const, which is\n // exactly when a plugins module was emitted. Referencing it otherwise would emit an\n // identifier the entry never declares.\n pluginRunnerExpr:\n opts.runtimeConfigModule === undefined ? undefined : 'await THEO_PLUGIN_RUNNER',\n },\n )\n\n return [\n `// Generated by Theo — Cloudflare Workers Adapter`,\n `//`,\n `// REQUIREMENTS (EC-3):`,\n `// - wrangler.toml MUST include compatibility_flags = [\"nodejs_compat\"]`,\n `// (still required for transitive theokit/server deps, e.g. busboy)`,\n `// - package.json MUST list \"theokit\" in dependencies (not devDependencies)`,\n `// so Wrangler bundles theokit and its transitive deps`,\n `// - Deploy: wrangler deploy`,\n ``,\n !preloadsApply\n ? `import { matchRoute, executeRoute, compilePattern, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server'`\n : `import { matchRoute, executeRoute, compilePattern, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server'\\nimport { injectModulePreloads } from 'theokit/server/http'`,\n `import { createWebShim } from 'theokit/adapters/web-shim'`,\n opts.ssrStreaming\n ? `import { buildSecurityHeaders, generateNonce, withSecurityHeaders } from 'theokit/adapters/security-headers'`\n : `import { buildSecurityHeaders, withSecurityHeaders } from 'theokit/adapters/security-headers'`,\n `// T3.4 — WS bridge for Cloudflare Workers`,\n `import { createCloudflareWsBridge } from 'theokit/adapters/ws-shim'`,\n // B-027 — only when a limit is declared. `createRateLimiterWeb` is used at module scope by the\n // fragment below and was imported by no target but bun, so an entry that declared a limit threw\n // when it LOADED. `resolveClientIpFromRequest` is the forwarded-header fallback, behind\n // `trustProxy`; the primary source is `cf-connecting-ip`, which the Workers runtime writes.\n ...(opts.rateLimit === undefined\n ? []\n : [\n `import { createRateLimiterWeb } from 'theokit/server'`,\n `import { resolveClientIpFromRequest } from 'theokit/server/rate-limit'`,\n ]),\n streamingImport,\n ``,\n ...runtimeConfig.imports,\n ...agentsFragment.imports,\n ...routeImports,\n ``,\n `// CR-006: server directory is a build-time literal — Workers cannot`,\n `// call process.cwd() and resolving paths at runtime returned '/server'.`,\n `const serverDir = ${serverDirLiteral(opts)}`,\n ``,\n ...routeRuntimeLines(routeModuleEntries, routeTableEntries),\n `// #410 — the security baseline \\`theokit start\\` puts on every response, carried`,\n `// here as a literal because a Worker has no theo.config.ts to read. Same`,\n `// function, same input, so the deployed page and the local one cannot`,\n `// disagree about what the configuration means.`,\n preloadSupport,\n ...securityHeadersDeclarations(opts.securityHeaders),\n ``,\n ...deployedCsrfFragment(opts, 'a Worker'),\n ``,\n ...runtimeConfig.declarations,\n ...agentsFragment.declarations,\n ...deployedCorsFragment(opts.cors, 'cloudflare'),\n `// #369 — whether this project declares a WebSocket route, decided at build time. It used`,\n `// to answer it with \\`scanWebSocketRoutes\\`, which is the same readdirSync.`,\n `const HAS_WS_ROUTES = ${String((opts.wsRoutes ?? []).length > 0)}`,\n ``,\n `function notFoundResponse() {`,\n ` return withSecurityHeaders(`,\n ` new Response(`,\n ` JSON.stringify({ error: { code: 'NOT_FOUND', message: 'Route not found' } }),`,\n ` { status: 404, headers: { 'Content-Type': 'application/json' } },`,\n ` ),`,\n ` SECURITY_HEADERS,`,\n ` )`,\n `}`,\n ``,\n ...cloudflareHandleRequestFragment(\n nonApiBranch,\n runtimeConfig.executeRouteSpread,\n agentsFragment.branch,\n agentsFragment.hostBypass,\n opts.rateLimit,\n ),\n ].join('\\n')\n}\n\n/**\n * The Worker's request handler, as generated source.\n *\n * Extracted for the reason `vercel.ts` extracts its own fragments: the emitter is one array\n * literal, so every line the entry gains counts against `max-lines-per-function`, and #410 added\n * the CSRF literal to an emitter already sitting exactly at the ceiling.\n *\n * @param nonApiBranch - what a non-`/api/` request gets, which differs with `ssrStreaming`\n */\nfunction cloudflareHandleRequestFragment(\n nonApiBranch: string,\n runtimeSpread: string,\n agentBranch: readonly string[],\n /** SI-020 — the condition that keeps an agent card path out of the static-asset branch. */\n hostBypass: string,\n /** B-027 — the declared limit, or `undefined`. Passed rather than read: this fragment is a\n * separate function from `renderCloudflareWorkerEntry`, where `opts` is bound. */\n rateLimit: DeployedRateLimitOptions['rateLimit'],\n): string[] {\n return [\n `async function handleRequest(request, url, env) {`,\n ` if (!url.pathname.startsWith('/api/')${hostBypass}) {`,\n nonApiBranch,\n ` }`,\n ``,\n ...agentBranch,\n ``,\n ` const match = matchRoute(url.pathname, routes)`,\n ` if (!match) return notFoundResponse()`,\n ``,\n ` const { req, res, toResponse } = createWebShim(request, { trustedProxy: 'platform' })`,\n ...deployedTraceFragment('request', ' '),\n ` const method = request.method.toUpperCase()`,\n ` // #382 — the run is NOT awaited before the Response is taken. toResponse()`,\n ` // settles as soon as status + headers are known and carries a live body, so`,\n ` // the Worker starts flushing while the handler is still writing. Awaiting`,\n ` // executeRoute() first would re-buffer the whole response here even though`,\n ` // the shim streams; awaiting toResponse() does not — it settles at the head.`,\n ` return withSecurityHeaders(await toResponse(executeRoute({`,\n ` route: match.route, method, params: match.params,`,\n ` req, res, loadModule, serverDir, requestId, ...CSRF_CONFIG, ${runtimeSpread}`,\n ` })), SECURITY_HEADERS)`,\n `}`,\n ``,\n ...deployedRateLimitFragment(\n rateLimit,\n 'cloudflare',\n // `cf-connecting-ip` is the RUNTIME's answer and a caller cannot forge it through the edge.\n // A Worker reached directly has none, and then only a declared `trustProxy` produces an\n // address — otherwise `undefined`, which is the named 503 rather than everyone's bucket.\n `request.headers.get('cf-connecting-ip') ?? resolveClientIpFromRequest(request, TRUST_PROXY)`,\n // `request` alone: the handler binds `(request, env, ctx)` and the header is on the request.\n 'request',\n ),\n ``,\n `export default {`,\n ` async fetch(request, env, ctx) {`,\n ` const url = new URL(request.url)`,\n ``,\n ` // #409 — the preflight is answered BEFORE anything routes: an OPTIONS the router handles`,\n ` // is an OPTIONS the browser never gets a CORS answer to. The WebSocket upgrade above is`,\n ` // deliberately upstream of it — a 101 is not a CORS-governed response.`,\n ` const preflight = corsPreflight(request)`,\n ` if (preflight !== null) return withSecurityHeaders(preflight, SECURITY_HEADERS)`,\n ...rateLimitCheckFragment(rateLimit, ' ', 'request'),\n ``,\n ` // LCR0103 — the upgrade branch sits BELOW the limiter, and the order is the point.`,\n ` // It used to sit above, under the comment \"a 101 carries no document and no script,`,\n ` // so the security baseline does not apply to it\". That is true of the security`,\n ` // HEADERS — a document concern — and false of the limiter, which is a resource`,\n ` // concern: a long-lived socket is the most expensive thing this entry hands out, so`,\n ` // the upgrade is the path that most needs a budget, not the one that may skip it.`,\n ` // T3.4 — Detect WebSocket upgrade and delegate to the CF bridge.`,\n ` // A 101 carries no document and no script, so the security baseline does`,\n ` // not apply to it.`,\n ` if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {`,\n ` if (!HAS_WS_ROUTES) return notFoundResponse()`,\n ` const cfWs = createCloudflareWsBridge({`,\n ` onOpen: () => {},`,\n ` onMessage: (ws, data) => { ws.send(data) },`,\n ` onClose: () => {},`,\n ` })`,\n ` return cfWs.handle(request)`,\n ` }`,\n ``,\n ` return withCors(request, await handleRequest(request, url, env))`,\n ` },`,\n `}`,\n ]\n}\n\nexport function renderWranglerToml(): string {\n return [\n `# Generated by Theo — Cloudflare Workers`,\n `name = \"theo-app\"`,\n `main = \".theokit/cloudflare/worker.mjs\"`,\n `compatibility_date = \"2025-09-01\"`,\n `compatibility_flags = [\"nodejs_compat\"]`,\n ``,\n `# #412 — \\`[assets]\\` with a BINDING, not the legacy \\`[site]\\` bucket.`,\n `#`,\n `# \\`[site]\\` uploads to KV and is read through \\`kv-asset-handler\\` and a`,\n `# \\`__STATIC_CONTENT\\` binding — neither of which this worker has ever had. So the`,\n `# bucket was declared, uploaded, and consumed by nothing: with ssrStreaming off, a`,\n `# deploy answered 404 for its own page. This binding is what the worker calls.`,\n `[assets]`,\n `directory = \".theokit/client\"`,\n `binding = \"ASSETS\"`,\n `# A client-routed app asks for /dashboard, which is no file. Without this the asset`,\n `# handler 404s a deep link and the SPA never boots.`,\n `not_found_handling = \"single-page-application\"`,\n ``,\n `# Environment variables are set via wrangler secret or dashboard`,\n `# Example: wrangler secret put DATABASE_URL`,\n ].join('\\n')\n}\n\nexport const cloudflareAdapter: DeployAdapter = {\n name: 'cloudflare',\n streamsResponses: true,\n // #409 / #410 — the generated entry calls `executeRoute` with routes, loader\n // and serverDir only. CSRF, route policy, file middleware and Zod validation\n // still run because they live inside `executeRoute`; none of the remaining\n // configurable concerns reach it. Declared explicitly rather than omitted so\n // the gap is a statement in the source and not an absence.\n //\n // `securityHeaders` IS applied: the worker carries `security.headers` as a\n // literal and puts the built baseline on every response it returns, including\n // the streamed SSR document — with a per-request nonce, the only deploy path\n // that can mint one (`adapters/security-headers.ts`).\n servesAgents: true,\n appliesConfig: ['securityHeaders', 'csrf', 'disallowed', 'cors', 'serialization', 'plugins'],\n // B-257 — per-invocation: an in-process counter does not survive, so a declared limit needs a durable store.\n enforcesRateLimit: 'with-a-store',\n\n async build(config: TheoConfig, cwd: string, ctx?: AdapterBuildContext): Promise<void> {\n // Wave 2 (T2.2) — reject polyglot services on this adapter.\n assertServicesUnsupported('cloudflare', readManifest(cwd))\n\n // 1. Run the standard Node build first (ctx forwarded so nodeAdapter has makeVitePlugins)\n await nodeAdapter.build(config, cwd, ctx)\n\n const outputDir = resolve(cwd, '.theokit/cloudflare')\n mkdirSync(outputDir, { recursive: true })\n\n // 2. Emit Worker entry (now uses the shared web-shim)\n //\n // The document shell is read HERE, after the Node build produced\n // `.theokit/client/index.html`, and inlined into the worker: a Worker has no\n // filesystem at request time. Split on the root div with the same helper the\n // Node server uses (`ssr-setup.ts`), so the two paths cannot disagree about\n // where the shell ends (#343).\n const shell = readDocumentShell(cwd, config.ssrStreaming)\n // B-035 — the route-to-chunks map, read HERE on the build machine for the same reason the\n // shell above is: a Worker has no filesystem at request time. `nodeAdapter.build` ran\n // first, so the map the Node build emitted is on disk by now. Absent map -> nothing about\n // preloads is emitted, and the worker behaves exactly as it did before.\n const assetsMap = readAssetsMapForBake(resolve(cwd, '.theokit', 'client', 'assets-map.json'))\n\n // #369 — the routes are resolved HERE, on the build machine, for the same reason the document\n // shell above is read here: a Worker has no filesystem at request time, and the worker used to\n // run the scan itself against a directory that does not exist there.\n //\n // The scanner is INJECTED rather than imported: importing it would add an `adapters → server`\n // edge, which is the layering inversion ADR-0001 v3 removed for `vite-plugin` and which\n // `adapters-may-only-depend-on-core-router-services` refuses. An absent scanner emits a worker\n // with no routes rather than falling back to a runtime scan — the fallback IS the defect.\n const scanned = ctx?.scanRoutes?.(config.serverDir) ?? {\n routes: [],\n wsRoutes: [],\n agents: [],\n // B-185 — no provider means no scan, and an app whose context nobody looked for is\n // indistinguishable here from one that has none. Both resolve an anonymous caller, which is\n // the honest answer rather than an invented subject.\n contextModule: undefined,\n }\n\n const pluginsPlan = planDeployedPlugins(config.plugins, 'cloudflare')\n if (pluginsPlan !== undefined) {\n // Beside the worker, so the emitted import is a sibling. Wrangler bundles from here, which is\n // what lets the static import reach the app's own module at all (#425).\n writeFileSync(resolve(outputDir, 'theo.plugins.mjs'), pluginsPlan.source)\n }\n\n writeFileSync(\n resolve(outputDir, 'worker.mjs'),\n renderCloudflareWorkerEntry({\n ssrStreaming: config.ssrStreaming,\n ...shell,\n securityHeaders: config.security?.headers,\n csrf: config.security?.csrf,\n disallowed: config.security?.disallowed,\n cors: config.security?.cors,\n assetsMap,\n // #425 — a selector, not a transformer, so it rides as a literal like the values above.\n serialization: config.serialization,\n // #425 — the ONE concern that is not a literal. A closure cannot be baked, so a plugin\n // declared by module specifier is imported by the emitted module instead; a constructed one\n // is refused by name at build time rather than dropped in silence.\n runtimeConfigModule: pluginsPlan?.moduleSpecifier,\n routes: scanned.routes,\n // #367 — a Worker has no filesystem, so its agents are decided here like its routes.\n agents: scanned.agents,\n // B-185 — rides beside the agents because it is decided by the same provider, for the same\n // reason: `build.ts` holds `serverDir` and a Worker cannot look for the module itself.\n contextModule: scanned.contextModule,\n wsRoutes: scanned.wsRoutes,\n }),\n )\n\n // 3. Emit wrangler.toml (with nodejs_compat enforced)\n writeFileSync(resolve(cwd, 'wrangler.toml'), renderWranglerToml())\n\n // eslint-disable-next-line no-console -- CLI build progress\n console.log('\\n ✓ Cloudflare output → .theokit/cloudflare/ + wrangler.toml')\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(\n `${describeDeployedSecurityHeaders({\n target: 'cloudflare',\n securityHeaders: config.security?.headers,\n // Only the streaming worker renders HTML per request, so only it can put\n // the same nonce on the header and on the script tag it emits.\n mintsNonce: config.ssrStreaming,\n // #412 — either way the worker returns the document now: streamed by\n // `renderStreamingWeb`, or from the ASSETS binding it finally calls.\n documentHeaders: 'handler',\n })}\\n`,\n )\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,eAAe;AA+CjB,SAAS,kBACd,KACA,WAC0C;AAC1C,MAAI,CAAC,UAAW,QAAO,CAAC;AAExB,QAAM,YAAY,QAAQ,KAAK,4BAA4B;AAC3D,MAAI,CAAC,WAAW,SAAS,GAAG;AAC1B,UAAM,IAAI;AAAA,MACR,+CAA+C,SAAS;AAAA,IAG1D;AAAA,EACF;AAEA,QAAM,YAAY,aAAa,WAAW,OAAO;AACjD,QAAM,UAAU,YAAY,SAAS;AACrC,MAAI,YAAY,QAAW;AACzB,UAAM,IAAI;AAAA,MACR,wBAAwB,SAAS;AAAA,IAEnC;AAAA,EACF;AAEA,SAAO;AAAA,IACL,UAAU,UAAU,MAAM,GAAG,QAAQ,QAAQ;AAAA,IAC7C,UAAU,UAAU,MAAM,QAAQ,QAAQ;AAAA,EAC5C;AACF;AAcA,SAAS,kBACP,QACuF;AACvF,QAAM,WAAW,CAAC,UAA0B,cAAc,OAAO,KAAK,CAAC;AACvE,SAAO;AAAA,IACL,cAAc,OAAO;AAAA,MACnB,CAAC,OAAO,UAAU,eAAe,SAAS,KAAK,CAAC,gBAAgB,MAAM,QAAQ;AAAA,IAChF;AAAA,IACA,oBAAoB,OAAO;AAAA,MACzB,CAAC,OAAO,UAAU,KAAK,KAAK,UAAU,MAAM,QAAQ,CAAC,KAAK,SAAS,KAAK,CAAC;AAAA,IAC3E;AAAA,IACA,mBAAmB,OAAO;AAAA,MACxB,CAAC,UACC,iBAAiB,KAAK,UAAU,MAAM,QAAQ,CAAC,gBAAgB,KAAK,UAAU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AIT,eAAe;AAAA,IACjB;AAEA,UAAM,cAAc,oBAAoB,OAAO,SAAS,YAAY;AACpE,QAAI,gBAAgB,QAAW;AAG7B,oBAAc,QAAQ,WAAW,kBAAkB,GAAG,YAAY,MAAM;AAAA,IAC1E;AAEA;AAAA,MACE,QAAQ,WAAW,YAAY;AAAA,MAC/B,4BAA4B;AAAA,QAC1B,cAAc,OAAO;AAAA,QACrB,GAAG;AAAA,QACH,iBAAiB,OAAO,UAAU;AAAA,QAClC,MAAM,OAAO,UAAU;AAAA,QACvB,YAAY,OAAO,UAAU;AAAA,QAC7B,MAAM,OAAO,UAAU;AAAA,QACvB;AAAA;AAAA,QAEA,eAAe,OAAO;AAAA;AAAA;AAAA;AAAA,QAItB,qBAAqB,aAAa;AAAA,QAClC,QAAQ,QAAQ;AAAA;AAAA,QAEhB,QAAQ,QAAQ;AAAA;AAAA;AAAA,QAGhB,eAAe,QAAQ;AAAA,QACvB,UAAU,QAAQ;AAAA,MACpB,CAAC;AAAA,IACH;AAGA,kBAAc,QAAQ,KAAK,eAAe,GAAG,mBAAmB,CAAC;AAGjE,YAAQ,IAAI,0EAAgE;AAE5E,YAAQ;AAAA,MACN,GAAG,gCAAgC;AAAA,QACjC,QAAQ;AAAA,QACR,iBAAiB,OAAO,UAAU;AAAA;AAAA;AAAA,QAGlC,YAAY,OAAO;AAAA;AAAA;AAAA,QAGnB,iBAAiB;AAAA,MACnB,CAAC,CAAC;AAAA;AAAA,IACJ;AAAA,EACF;AACF;","names":[]}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import "tsx/esm";
|
|
3
3
|
import {
|
|
4
4
|
nodeAdapter
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-G7U7FQVC.js";
|
|
6
6
|
import "./chunk-ZNZISJDZ.js";
|
|
7
7
|
|
|
8
8
|
// src/adapters/config-support.ts
|
|
@@ -118,12 +118,18 @@ var UnenforceableRateLimitError = class extends Error {
|
|
|
118
118
|
name = "UnenforceableRateLimitError";
|
|
119
119
|
};
|
|
120
120
|
function assertRateLimitEnforceable(config, adapter, target) {
|
|
121
|
-
const applied = adapter.appliesConfig ?? [];
|
|
122
|
-
if (applied === "runtime-not-emitted-here") return;
|
|
123
121
|
if (!isDeclared(config, "rateLimit")) return;
|
|
124
|
-
|
|
122
|
+
const enforces = adapter.enforcesRateLimit ?? "never";
|
|
123
|
+
if (enforces === "not-ours-to-judge") return;
|
|
124
|
+
if (enforces === "always") return;
|
|
125
|
+
if (enforces === "never") throw new UnenforceableRateLimitError(target);
|
|
126
|
+
if (declaresRateLimitStore(config)) return;
|
|
125
127
|
throw new UnenforceableRateLimitError(target);
|
|
126
128
|
}
|
|
129
|
+
function declaresRateLimitStore(config) {
|
|
130
|
+
const limit = config.rateLimit;
|
|
131
|
+
return typeof limit?.store === "object" && limit.store !== null;
|
|
132
|
+
}
|
|
127
133
|
export {
|
|
128
134
|
CONFIG_CONCERNS,
|
|
129
135
|
UnenforceableRateLimitError,
|
|
@@ -132,4 +138,4 @@ export {
|
|
|
132
138
|
findUnappliedConfig,
|
|
133
139
|
warnUnappliedConfig
|
|
134
140
|
};
|
|
135
|
-
//# sourceMappingURL=config-support-
|
|
141
|
+
//# sourceMappingURL=config-support-SB5NDQZB.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapters/config-support.ts"],"sourcesContent":["/**\n * Which configuration a deploy target's emitted handler actually applies.\n *\n * `theo.config.ts` validates `rateLimit`, `security.cors`, `security.csrf`,\n * `security.disallowed` and `serialization` for every target. Applying them is\n * the handler's job, and the six Web-standards adapters build `executeRoute`'s\n * context from a subset of its fields, so the rest fall back to hard-coded\n * defaults on a deployed app (usetheokit/theokit#410). `security.cors` was read\n * only by the dev server until #409 wired it into `theokit start`; the six Web\n * targets still drop it.\n *\n * This module does not fix that. It makes it **audible at build time**: a\n * config key that is parsed and then dropped is named, with the target that\n * drops it and the next action. Silence was the defect — an operator who\n * declares a rate limit and gets none has no reason to look.\n *\n * It warns rather than refuses, deliberately. Refusing would break every\n * deployment that declares `rateLimit` today, and the real fix — wiring a\n * limiter that needs a per-runtime client address — is not a build away\n * (`docs/program/journeys/j07-rate-limit.md` § Correction measured what it\n * costs). Forcing an operator to delete valid configuration in order to ship\n * would trade a silent gap for a loud one that also loses information.\n */\nimport type { TheoConfig } from '../config/schema.js'\n\nimport { nodeAdapter } from './node.js'\nimport type { ConfigConcern, DeployAdapter } from './types.js'\n\n/**\n * The closed set. A concern belongs here when it is (a) declarable in\n * `theo.config.ts` and (b) applied by a request handler rather than at build\n * time — a build-time key cannot be silently dropped by a runtime.\n */\nexport const CONFIG_CONCERNS = [\n 'rateLimit',\n 'cors',\n 'csrf',\n 'disallowed',\n 'serialization',\n 'plugins',\n 'securityHeaders',\n] as const satisfies readonly ConfigConcern[]\n\n/**\n * Does any production target apply this concern?\n *\n * DERIVED from what the `node` adapter declares, rather than listed. This was a hand-maintained\n * `APPLIED_BY_NO_TARGET` set holding `cors`, kept in step with `nodeAdapter.appliesConfig` by a\n * test — and #409, which taught `theokit start` to apply `cors`, emptied it. An empty hardcoded\n * set is not merely redundant: it makes the branch below provably unreachable, which the linter\n * says out loud (`sonarjs/no-empty-collection`).\n *\n * Deriving keeps the branch honest AND reachable: the moment a concern is added that `node` does\n * not apply, the advice stops claiming a target exists for it, with nothing to remember.\n */\nfunction appliedByNoTarget(concern: ConfigConcern): boolean {\n const applied = nodeAdapter.appliesConfig\n if (applied === undefined || applied === 'runtime-not-emitted-here') return true\n return !applied.includes(concern)\n}\n\n/** Where each concern lives in the config, for a message the operator can grep. */\nconst CONFIG_KEY: Record<ConfigConcern, string> = {\n rateLimit: 'rateLimit',\n cors: 'security.cors',\n csrf: 'security.csrf',\n disallowed: 'security.disallowed',\n serialization: 'serialization',\n plugins: 'plugins',\n securityHeaders: 'security.headers',\n}\n\nfunction isDeclared(config: TheoConfig, concern: ConfigConcern): boolean {\n const security = config.security\n switch (concern) {\n case 'rateLimit':\n return config.rateLimit !== undefined\n case 'cors':\n return security?.cors !== undefined\n case 'csrf':\n // `csrf` carries `.default('strict')` (config/schemas/security.ts:100) and\n // the deployed fallback is also `'strict'` (server/http/execute.ts:144).\n // A config that says `'strict'` therefore gets what it asked for, by\n // coincidence rather than by wiring -- reporting it dropped would be noise\n // over an identical outcome. Only a weaker setting is silently ignored.\n return security?.csrf !== undefined && security.csrf !== 'strict'\n case 'disallowed':\n return security?.disallowed !== undefined && security.disallowed.routes.length > 0\n case 'securityHeaders':\n return security?.headers !== undefined\n case 'serialization':\n // Same shape: `.default('json')` (config/schema.ts:147), and a target with\n // no transformer serializes as JSON. `'json'` is honoured by coincidence;\n // `'superjson'` is the case where the deployed app quietly disagrees with\n // the file.\n return config.serialization !== 'json'\n case 'plugins':\n return config.plugins !== undefined && config.plugins.length > 0\n }\n}\n\n/**\n * The concerns this config declares and this adapter does not apply.\n *\n * An adapter that emits no request handler of its own answers\n * `'runtime-not-emitted-here'` and is never reported against: it is not that\n * the configuration is dropped, it is that this build cannot know. Saying\n * nothing is the honest output, and it is a different fact from saying no.\n */\nexport function findUnappliedConfig(\n config: TheoConfig,\n adapter: Pick<DeployAdapter, 'appliesConfig'>,\n): ConfigConcern[] {\n const applied = adapter.appliesConfig ?? []\n if (applied === 'runtime-not-emitted-here') return []\n return CONFIG_CONCERNS.filter(\n (concern) => isDeclared(config, concern) && !applied.includes(concern),\n )\n}\n\n/**\n * The build-time message. Empty string when nothing was dropped, so the caller\n * neither branches nor prints a header over an empty list.\n */\nexport function describeUnappliedConfig(target: string, dropped: readonly ConfigConcern[]): string {\n if (dropped.length === 0) return ''\n const one = dropped.length === 1\n const list = dropped.map((concern) => ` - ${CONFIG_KEY[concern]}`).join('\\n')\n const elsewhere = dropped.filter((concern) => !appliedByNoTarget(concern))\n const nowhere = dropped.filter(appliedByNoTarget)\n\n // The advice has to change with the target, or it degenerates. Building for\n // `node` with only `security.cors` dropped once produced \"deploy to `node`,\n // which applies all of the above except security.cors\" -- an instruction to\n // do what you are already doing, about the one key it then excepts.\n const actions: string[] = []\n if (elsewhere.length > 0 && target !== 'node') {\n actions.push(\n ` - ${elsewhere.map((c) => CONFIG_KEY[c]).join(', ')}: build for \\`node\\` and run \\`theokit start\\`,`,\n ` which applies ${elsewhere.length === 1 ? 'it' : 'them'}; or remove ${elsewhere.length === 1 ? 'it' : 'them'} so the file states what runs.`,\n )\n } else if (elsewhere.length > 0) {\n actions.push(\n ` - ${elsewhere.map((c) => CONFIG_KEY[c]).join(', ')}: remove ${elsewhere.length === 1 ? 'it' : 'them'} so the file states what runs.`,\n )\n }\n if (nowhere.length > 0) {\n actions.push(\n ` - ${nowhere.map((c) => CONFIG_KEY[c]).join(', ')}: no production target applies ${nowhere.length === 1 ? 'this' : 'these'} today`,\n ` (usetheokit/theokit#409) -- terminate it in front of the app, or remove it.`,\n )\n }\n\n return [\n ` ! ${String(dropped.length)} configuration ${one ? 'key is' : 'keys are'} validated and NOT applied on \\`${target}\\`:`,\n list,\n ` The handler this target emits never reads ${one ? 'it' : 'them'}, so the deployed app`,\n ` behaves as if ${one ? 'the key were' : 'the keys were'} absent.`,\n ` What to do:`,\n ...actions,\n ` Tracked: usetheokit/theokit#410 (deploy targets), usetheokit/theokit#409 (cors).`,\n ].join('\\n')\n}\n\n/**\n * Emit the warning, if there is one. The sink is injected so the behaviour is\n * exercisable without driving a whole build: the alternative was a caller that\n * only a full `theokit build` could reach, which in practice means a caller\n * nothing tests.\n */\nexport function warnUnappliedConfig(\n config: TheoConfig,\n adapter: Pick<DeployAdapter, 'appliesConfig'>,\n target: string,\n log: (message: string) => void,\n): void {\n const dropped = findUnappliedConfig(config, adapter)\n if (dropped.length === 0) return\n log(`\\n${describeUnappliedConfig(target, dropped)}\\n`)\n}\n\n/**\n * A declared rate limit the chosen target cannot enforce.\n *\n * Its own class so a caller can distinguish it from a configuration typo — this is not the build\n * failing to understand the file, it is the build understanding it and refusing the combination.\n */\nexport class UnenforceableRateLimitError extends Error {\n override readonly name = 'UnenforceableRateLimitError'\n constructor(readonly target: string) {\n super(\n [\n `Refusing to build for \\`${target}\\`: theo.config.ts declares a rate limit and this target does not enforce one.`,\n ``,\n ` The config reads as protection the deploy will not have. Nothing at runtime reports the`,\n ` absence, so the first sign is abuse — which is why this refuses rather than warns.`,\n ``,\n ` Two honest ways forward:`,\n ` • build for \\`node\\` and run \\`theokit start\\`, which applies the limit; or`,\n ` • remove \\`rateLimit\\` from theo.config.ts, so the file states what actually runs.`,\n ``,\n ` There is deliberately no flag to keep the key and skip the check: a config that stays`,\n ` while doing nothing is the state this refusal exists to end (usetheokit/theokit#461).`,\n ].join('\\n'),\n )\n }\n}\n\n/**\n * Refuse a build whose target drops a DECLARED rate limit.\n *\n * Only `rateLimit`, and the narrowness is the design. A dropped `cors` or `serialization` degrades\n * where someone can see it, and `describeUnappliedConfig`'s warning is proportionate for those.\n * `rateLimit` is the one whose absence looks exactly like success, which is the same reasoning\n * `MissingRoutePolicyError` applies to an undeclared route policy: refuse where silence would be\n * read as safety.\n *\n * `'runtime-not-emitted-here'` is not judged. That adapter's runtime is someone else's and this\n * build cannot answer for it; refusing there would be asserting something unmeasured.\n */\nexport function assertRateLimitEnforceable(\n config: TheoConfig,\n adapter: Pick<DeployAdapter, 'appliesConfig'>,\n target: string,\n): void {\n const applied = adapter.appliesConfig ?? []\n if (applied === 'runtime-not-emitted-here') return\n if (!isDeclared(config, 'rateLimit')) return\n if (applied.includes('rateLimit')) return\n throw new UnenforceableRateLimitError(target)\n}\n"],"mappings":";;;;;;;;AAiCO,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAcA,SAAS,kBAAkB,SAAiC;AAC1D,QAAM,UAAU,YAAY;AAC5B,MAAI,YAAY,UAAa,YAAY,2BAA4B,QAAO;AAC5E,SAAO,CAAC,QAAQ,SAAS,OAAO;AAClC;AAGA,IAAM,aAA4C;AAAA,EAChD,WAAW;AA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B;AAAA,EAhBqB;AAAA,EADH,OAAO;AAkB3B;AAcO,SAAS,2BACd,QACA,SACA,QACM;AACN,QAAM,UAAU,QAAQ,iBAAiB,CAAC;AAC1C,MAAI,YAAY,2BAA4B;AAC5C,MAAI,CAAC,WAAW,QAAQ,WAAW,EAAG;AACtC,MAAI,QAAQ,SAAS,WAAW,EAAG;AACnC,QAAM,IAAI,4BAA4B,MAAM;AAC9C;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/adapters/config-support.ts"],"sourcesContent":["/**\n * Which configuration a deploy target's emitted handler actually applies.\n *\n * `theo.config.ts` validates `rateLimit`, `security.cors`, `security.csrf`,\n * `security.disallowed` and `serialization` for every target. Applying them is\n * the handler's job, and the six Web-standards adapters build `executeRoute`'s\n * context from a subset of its fields, so the rest fall back to hard-coded\n * defaults on a deployed app (usetheokit/theokit#410). `security.cors` was read\n * only by the dev server until #409 wired it into `theokit start`; the six Web\n * targets still drop it.\n *\n * This module does not fix that. It makes it **audible at build time**: a\n * config key that is parsed and then dropped is named, with the target that\n * drops it and the next action. Silence was the defect — an operator who\n * declares a rate limit and gets none has no reason to look.\n *\n * It warns rather than refuses, deliberately. Refusing would break every\n * deployment that declares `rateLimit` today, and the real fix — wiring a\n * limiter that needs a per-runtime client address — is not a build away\n * (`docs/program/journeys/j07-rate-limit.md` § Correction measured what it\n * costs). Forcing an operator to delete valid configuration in order to ship\n * would trade a silent gap for a loud one that also loses information.\n */\nimport type { TheoConfig } from '../config/schema.js'\n\nimport { nodeAdapter } from './node.js'\nimport type { ConfigConcern, DeployAdapter } from './types.js'\n\n/**\n * The closed set. A concern belongs here when it is (a) declarable in\n * `theo.config.ts` and (b) applied by a request handler rather than at build\n * time — a build-time key cannot be silently dropped by a runtime.\n */\nexport const CONFIG_CONCERNS = [\n 'rateLimit',\n 'cors',\n 'csrf',\n 'disallowed',\n 'serialization',\n 'plugins',\n 'securityHeaders',\n] as const satisfies readonly ConfigConcern[]\n\n/**\n * Does any production target apply this concern?\n *\n * DERIVED from what the `node` adapter declares, rather than listed. This was a hand-maintained\n * `APPLIED_BY_NO_TARGET` set holding `cors`, kept in step with `nodeAdapter.appliesConfig` by a\n * test — and #409, which taught `theokit start` to apply `cors`, emptied it. An empty hardcoded\n * set is not merely redundant: it makes the branch below provably unreachable, which the linter\n * says out loud (`sonarjs/no-empty-collection`).\n *\n * Deriving keeps the branch honest AND reachable: the moment a concern is added that `node` does\n * not apply, the advice stops claiming a target exists for it, with nothing to remember.\n */\nfunction appliedByNoTarget(concern: ConfigConcern): boolean {\n const applied = nodeAdapter.appliesConfig\n if (applied === undefined || applied === 'runtime-not-emitted-here') return true\n return !applied.includes(concern)\n}\n\n/** Where each concern lives in the config, for a message the operator can grep. */\nconst CONFIG_KEY: Record<ConfigConcern, string> = {\n rateLimit: 'rateLimit',\n cors: 'security.cors',\n csrf: 'security.csrf',\n disallowed: 'security.disallowed',\n serialization: 'serialization',\n plugins: 'plugins',\n securityHeaders: 'security.headers',\n}\n\nfunction isDeclared(config: TheoConfig, concern: ConfigConcern): boolean {\n const security = config.security\n switch (concern) {\n case 'rateLimit':\n return config.rateLimit !== undefined\n case 'cors':\n return security?.cors !== undefined\n case 'csrf':\n // `csrf` carries `.default('strict')` (config/schemas/security.ts:100) and\n // the deployed fallback is also `'strict'` (server/http/execute.ts:144).\n // A config that says `'strict'` therefore gets what it asked for, by\n // coincidence rather than by wiring -- reporting it dropped would be noise\n // over an identical outcome. Only a weaker setting is silently ignored.\n return security?.csrf !== undefined && security.csrf !== 'strict'\n case 'disallowed':\n return security?.disallowed !== undefined && security.disallowed.routes.length > 0\n case 'securityHeaders':\n return security?.headers !== undefined\n case 'serialization':\n // Same shape: `.default('json')` (config/schema.ts:147), and a target with\n // no transformer serializes as JSON. `'json'` is honoured by coincidence;\n // `'superjson'` is the case where the deployed app quietly disagrees with\n // the file.\n return config.serialization !== 'json'\n case 'plugins':\n return config.plugins !== undefined && config.plugins.length > 0\n }\n}\n\n/**\n * The concerns this config declares and this adapter does not apply.\n *\n * An adapter that emits no request handler of its own answers\n * `'runtime-not-emitted-here'` and is never reported against: it is not that\n * the configuration is dropped, it is that this build cannot know. Saying\n * nothing is the honest output, and it is a different fact from saying no.\n */\nexport function findUnappliedConfig(\n config: TheoConfig,\n adapter: Pick<DeployAdapter, 'appliesConfig'>,\n): ConfigConcern[] {\n const applied = adapter.appliesConfig ?? []\n if (applied === 'runtime-not-emitted-here') return []\n return CONFIG_CONCERNS.filter(\n (concern) => isDeclared(config, concern) && !applied.includes(concern),\n )\n}\n\n/**\n * The build-time message. Empty string when nothing was dropped, so the caller\n * neither branches nor prints a header over an empty list.\n */\nexport function describeUnappliedConfig(target: string, dropped: readonly ConfigConcern[]): string {\n if (dropped.length === 0) return ''\n const one = dropped.length === 1\n const list = dropped.map((concern) => ` - ${CONFIG_KEY[concern]}`).join('\\n')\n const elsewhere = dropped.filter((concern) => !appliedByNoTarget(concern))\n const nowhere = dropped.filter(appliedByNoTarget)\n\n // The advice has to change with the target, or it degenerates. Building for\n // `node` with only `security.cors` dropped once produced \"deploy to `node`,\n // which applies all of the above except security.cors\" -- an instruction to\n // do what you are already doing, about the one key it then excepts.\n const actions: string[] = []\n if (elsewhere.length > 0 && target !== 'node') {\n actions.push(\n ` - ${elsewhere.map((c) => CONFIG_KEY[c]).join(', ')}: build for \\`node\\` and run \\`theokit start\\`,`,\n ` which applies ${elsewhere.length === 1 ? 'it' : 'them'}; or remove ${elsewhere.length === 1 ? 'it' : 'them'} so the file states what runs.`,\n )\n } else if (elsewhere.length > 0) {\n actions.push(\n ` - ${elsewhere.map((c) => CONFIG_KEY[c]).join(', ')}: remove ${elsewhere.length === 1 ? 'it' : 'them'} so the file states what runs.`,\n )\n }\n if (nowhere.length > 0) {\n actions.push(\n ` - ${nowhere.map((c) => CONFIG_KEY[c]).join(', ')}: no production target applies ${nowhere.length === 1 ? 'this' : 'these'} today`,\n ` (usetheokit/theokit#409) -- terminate it in front of the app, or remove it.`,\n )\n }\n\n return [\n ` ! ${String(dropped.length)} configuration ${one ? 'key is' : 'keys are'} validated and NOT applied on \\`${target}\\`:`,\n list,\n ` The handler this target emits never reads ${one ? 'it' : 'them'}, so the deployed app`,\n ` behaves as if ${one ? 'the key were' : 'the keys were'} absent.`,\n ` What to do:`,\n ...actions,\n ` Tracked: usetheokit/theokit#410 (deploy targets), usetheokit/theokit#409 (cors).`,\n ].join('\\n')\n}\n\n/**\n * Emit the warning, if there is one. The sink is injected so the behaviour is\n * exercisable without driving a whole build: the alternative was a caller that\n * only a full `theokit build` could reach, which in practice means a caller\n * nothing tests.\n */\nexport function warnUnappliedConfig(\n config: TheoConfig,\n adapter: Pick<DeployAdapter, 'appliesConfig'>,\n target: string,\n log: (message: string) => void,\n): void {\n const dropped = findUnappliedConfig(config, adapter)\n if (dropped.length === 0) return\n log(`\\n${describeUnappliedConfig(target, dropped)}\\n`)\n}\n\n/**\n * A declared rate limit the chosen target cannot enforce.\n *\n * Its own class so a caller can distinguish it from a configuration typo — this is not the build\n * failing to understand the file, it is the build understanding it and refusing the combination.\n */\nexport class UnenforceableRateLimitError extends Error {\n override readonly name = 'UnenforceableRateLimitError'\n constructor(readonly target: string) {\n super(\n [\n `Refusing to build for \\`${target}\\`: theo.config.ts declares a rate limit and this target does not enforce one.`,\n ``,\n ` The config reads as protection the deploy will not have. Nothing at runtime reports the`,\n ` absence, so the first sign is abuse — which is why this refuses rather than warns.`,\n ``,\n ` Two honest ways forward:`,\n ` • build for \\`node\\` and run \\`theokit start\\`, which applies the limit; or`,\n ` • remove \\`rateLimit\\` from theo.config.ts, so the file states what actually runs.`,\n ``,\n ` There is deliberately no flag to keep the key and skip the check: a config that stays`,\n ` while doing nothing is the state this refusal exists to end (usetheokit/theokit#461).`,\n ].join('\\n'),\n )\n }\n}\n\n/**\n * Refuse a build whose target drops a DECLARED rate limit.\n *\n * Only `rateLimit`, and the narrowness is the design. A dropped `cors` or `serialization` degrades\n * where someone can see it, and `describeUnappliedConfig`'s warning is proportionate for those.\n * `rateLimit` is the one whose absence looks exactly like success, which is the same reasoning\n * `MissingRoutePolicyError` applies to an undeclared route policy: refuse where silence would be\n * read as safety.\n *\n * `'runtime-not-emitted-here'` is not judged. That adapter's runtime is someone else's and this\n * build cannot answer for it; refusing there would be asserting something unmeasured.\n */\nexport function assertRateLimitEnforceable(\n config: TheoConfig,\n adapter: Pick<DeployAdapter, 'enforcesRateLimit'>,\n target: string,\n): void {\n if (!isDeclared(config, 'rateLimit')) return\n\n // B-257 — this reads `enforcesRateLimit`, NOT `appliesConfig`. They were one list until now, and\n // `applied.includes('rateLimit')` returned before the throw, so adding that entry to silence the\n // WARNING also switched off this REFUSAL — on a runtime where the limit still cannot hold.\n //\n // **An omitted field REFUSES.** The first cut defaulted to `'not-ours-to-judge'`, which inverted\n // the rule it replaced: `appliesConfig ?? []` did not include `'rateLimit'`, so an adapter that\n // declared nothing was refused; `?? 'not-ours-to-judge'` let it through. Measured on\n // `static.ts`, which declares neither field and is registered at `registry.ts:28` — it went from\n // refusing a declared limit to proceeding with a console warning. `:213-215` refuses exactly that\n // outcome in its own words, and this member is on the EXPORTED `DeployAdapter`, so every\n // third-party adapter inherited the inversion too.\n //\n // Abstaining is a CLAIM about somebody else's runtime, and a claim has to be made rather than\n // inferred from silence.\n const enforces = adapter.enforcesRateLimit ?? 'never'\n\n // An adapter emitting no request handler is not judged. Its runtime is someone else's and this\n // build cannot answer for it; refusing would assert something unmeasured. An ABSTAIN, and the\n // reason it is not spelled `'never'`.\n if (enforces === 'not-ours-to-judge') return\n\n if (enforces === 'always') return\n\n // `'never'`, and the default for an adapter that declared nothing. Refusing here is what the\n // pre-B-257 rule did; reaching the store check below would let an undeclared adapter enforce by\n // accident whenever a config happened to name one.\n if (enforces === 'never') throw new UnenforceableRateLimitError(target)\n\n // `'with-a-store'`: a per-invocation runtime enforces only when the config names a durable\n // counter. Without one the in-process count dies with the invocation, and a limit that forgets is\n // a limit that does not limit — the same class of failure as a shared bucket, by another road.\n if (declaresRateLimitStore(config)) return\n\n throw new UnenforceableRateLimitError(target)\n}\n\n/** Does the declared `rateLimit` name a store the emitted entry could construct? */\nfunction declaresRateLimitStore(config: TheoConfig): boolean {\n const limit = (config as { rateLimit?: { store?: unknown } }).rateLimit\n return typeof limit?.store === 'object' && limit.store !== null\n}\n"],"mappings":";;;;;;;;AAiCO,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAcA,SAAS,kBAAkB,SAAiC;AAC1D,QAAM,UAAU,YAAY;AAC5B,MAAI,YAAY,UAAa,YAAY,2BAA4B,QAAO;AAC5E,SAAO,CAAC,QAAQ,SAAS,OAAO;AAClC;AAGA,IAAM,aAA4C;AAAA,EAChD,WAAW;AAAA,EACX,MAAM;AAAA,EACN,MAAM;AAAA,EACN,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,SAAS;AAAA,EACT,iBAAiB;AACnB;AAEA,SAAS,WAAW,QAAoB,SAAiC;AACvE,QAAM,WAAW,OAAO;AACxB,UAAQ,SAAS;AAAA,IACf,KAAK;AACH,aAAO,OAAO,cAAc;AAAA,IAC9B,KAAK;AACH,aAAO,UAAU,SAAS;AAAA,IAC5B,KAAK;AAMH,aAAO,UAAU,SAAS,UAAa,SAAS,SAAS;AAAA,IAC3D,KAAK;AACH,aAAO,UAAU,eAAe,UAAa,SAAS,WAAW,OAAO,SAAS;AAAA,IACnF,KAAK;AACH,aAAO,UAAU,YAAY;AAAA,IAC/B,KAAK;AAKH,aAAO,OAAO,kBAAkB;AAAA,IAClC,KAAK;AACH,aAAO,OAAO,YAAY,UAAa,OAAO,QAAQ,SAAS;AAAA,EACnE;AACF;AAUO,SAAS,oBACd,QACA,SACiB;AACjB,QAAM,UAAU,QAAQ,iBAAiB,CAAC;AAC1C,MAAI,YAAY,2BAA4B,QAAO,CAAC;AACpD,SAAO,gBAAgB;AAAA,IACrB,CAAC,YAAY,WAAW,QAAQ,OAA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;AAAA,IACH;AAAA,EACF,EAAE,KAAK,IAAI;AACb;AAQO,SAAS,oBACd,QACA,SACA,QACA,KACM;AACN,QAAM,UAAU,oBAAoB,QAAQ,OAAO;AACnD,MAAI,QAAQ,WAAW,EAAG;AAC1B,MAAI;AAAA,EAAK,wBAAwB,QAAQ,OAAO,CAAC;AAAA,CAAI;AACvD;AAQO,IAAM,8BAAN,cAA0C,MAAM;AAAA,EAErD,YAAqB,QAAgB;AACnC;AAAA,MACE;AAAA,QACE,2BAA2B,MAAM;AAAA,QACjC;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF,EAAE,KAAK,IAAI;AAAA,IACb;AAfmB;AAAA,EAgBrB;AAAA,EAhBqB;AAAA,EADH,OAAO;AAkB3B;AAcO,SAAS,2BACd,QACA,SACA,QACM;AACN,MAAI,CAAC,WAAW,QAAQ,WAAW,EAAG;AAgBtC,QAAM,WAAW,QAAQ,qBAAqB;AAK9C,MAAI,aAAa,oBAAqB;AAEtC,MAAI,aAAa,SAAU;AAK3B,MAAI,aAAa,QAAS,OAAM,IAAI,4BAA4B,MAAM;AAKtE,MAAI,uBAAuB,MAAM,EAAG;AAEpC,QAAM,IAAI,4BAA4B,MAAM;AAC9C;AAGA,SAAS,uBAAuB,QAA6B;AAC3D,QAAM,QAAS,OAA+C;AAC9D,SAAO,OAAO,OAAO,UAAU,YAAY,MAAM,UAAU;AAC7D;","names":[]}
|
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
} from "./chunk-V5SSTT3C.js";
|
|
6
6
|
import {
|
|
7
7
|
deployedEntryPreamble
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-IB5VIXLR.js";
|
|
9
9
|
import {
|
|
10
10
|
agentsDirLiteral,
|
|
11
11
|
deployedAgentsFragment,
|
|
@@ -16,10 +16,10 @@ import {
|
|
|
16
16
|
rateLimitCheckFragment,
|
|
17
17
|
scannedFromLoaderCache,
|
|
18
18
|
serverDirLiteral
|
|
19
|
-
} from "./chunk-
|
|
19
|
+
} from "./chunk-C5CAL3DX.js";
|
|
20
20
|
import {
|
|
21
21
|
nodeAdapter
|
|
22
|
-
} from "./chunk-
|
|
22
|
+
} from "./chunk-G7U7FQVC.js";
|
|
23
23
|
import "./chunk-WSMLSIS5.js";
|
|
24
24
|
import {
|
|
25
25
|
assertServicesUnsupported,
|
|
@@ -95,7 +95,11 @@ function renderDenoEntry(port, opts = {}) {
|
|
|
95
95
|
// `info.remoteAddr` is the runtime's own answer. A `UnixAddr` has no `hostname`, so the
|
|
96
96
|
// optional chain is what keeps the read from throwing there rather than a guess.
|
|
97
97
|
`info?.remoteAddr?.hostname ?? resolveClientIpFromRequest(request, TRUST_PROXY)`,
|
|
98
|
-
"request, info"
|
|
98
|
+
"request, info",
|
|
99
|
+
// B-257 — `npm:`, like every other specifier this target emits. A bare one does not resolve
|
|
100
|
+
// on Deno Deploy, and the durable limiter's import is emitted by the fragment rather than
|
|
101
|
+
// here, so the prefix has to travel with it.
|
|
102
|
+
"npm:"
|
|
99
103
|
),
|
|
100
104
|
``,
|
|
101
105
|
// The serve handler's SECOND parameter is bound here for the first time: `Deno.serve` has
|
|
@@ -213,6 +217,8 @@ var denoDeployAdapter = {
|
|
|
213
217
|
// through it (usetheokit/theokit#412).
|
|
214
218
|
servesAgents: true,
|
|
215
219
|
appliesConfig: ["securityHeaders", "csrf", "disallowed", "cors", "serialization", "plugins"],
|
|
220
|
+
// B-257 — per-invocation: an in-process counter does not survive, so a declared limit needs a durable store.
|
|
221
|
+
enforcesRateLimit: "with-a-store",
|
|
216
222
|
build(config, cwd, ctx) {
|
|
217
223
|
return buildDeno(config, cwd, {}, ctx);
|
|
218
224
|
}
|
|
@@ -222,4 +228,4 @@ export {
|
|
|
222
228
|
denoDeployAdapter,
|
|
223
229
|
renderDenoEntry
|
|
224
230
|
};
|
|
225
|
-
//# sourceMappingURL=deno-deploy-
|
|
231
|
+
//# sourceMappingURL=deno-deploy-IVACZ62D.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/adapters/deno-deploy.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Deno Deploy adapter. Writes to `cwd/.theokit/deno-deploy/`. Build-time.\n */\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport type { TheoConfig } from '../config/schema.js'\nimport { assertServicesUnsupported, readManifest } from '../services/index.js'\n\nimport { deployedAgentsFragment, scannedFromLoaderCache } from './deployed-agents.js'\nimport { planDeployedPlugins } from './deployed-plugins-module.js'\nimport { deployedEntryPreamble } from './deployed-preamble.js'\nimport { deployedRateLimitFragment, rateLimitCheckFragment } from './deployed-rate-limit.js'\nimport {\n agentsDirLiteral,\n deployedRuntimeConfigFragment,\n serverDirLiteral,\n} from './deployed-runtime-config.js'\nimport { deployedTraceFragment } from './deployed-trace.js'\nimport { nodeAdapter } from './node.js'\nimport { describeDeployedSecurityHeaders } from './security-headers.js'\nimport type { AdapterBuildContext, DeployAdapter, DeployedEntryOptions } from './types.js'\n\nexport interface DenoBuildDeps {\n runNodeBuild?: (config: TheoConfig, cwd: string, ctx?: AdapterBuildContext) => Promise<void>\n writeEntry?: (path: string, content: string) => void\n ensureDir?: (path: string) => void\n}\n\n/**\n * The framework imports this entry opens with, as `npm:` specifiers.\n *\n * Extracted from `renderDenoEntry` when adding the configured-directory literal pushed it past the\n * per-function line budget. A cohesive block — every line is one import of the same package family\n * — so lifting it keeps the budget a signal about the renderer rather than about its preamble.\n */\nconst FRAMEWORK_IMPORTS: readonly string[] = [\n `// Use npm: specifier so Deno resolves theokit from the user's package.json`,\n `// equivalent (works in both local 'deno run' and Deno Deploy).`,\n `import { scanServerRoutes, matchRoute, executeRoute, createProductionLoader, scanWebSocketRoutes, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'npm:theokit/server'`,\n `import { createWebShim } from 'npm:theokit/adapters/web-shim'`,\n `import { buildSecurityHeaders, withSecurityHeaders } from 'npm:theokit/adapters/security-headers'`,\n `// T3.3 — WS bridge for Deno runtime`,\n `import { createDenoWsBridge } from 'npm:theokit/adapters/ws-shim'`,\n]\n\n/** The target's name, in the five places that spell it. Adding a sixth tripped the duplicate-literal gate. */\n/* The name in the places a gate does NOT read. `assertServicesUnsupported` keeps the literal:\n * `services-other-adapters-reject.test.ts:30` requires each adapter to name ITSELF there, so a\n * copy-paste carrying another adapter's name cannot hide behind a constant. */\nconst TARGET = 'deno-deploy'\n\nexport function renderDenoEntry(port: number, opts: DeployedEntryOptions = {}): string {\n const runtimeConfig = deployedRuntimeConfigFragment(opts)\n const agentsFragment = deployedAgentsFragment(scannedFromLoaderCache(agentsDirLiteral(opts)), {\n notFound: 'notFound()',\n importPrefix: 'npm:',\n // B-185 — bound only when the runtime-config fragment declared the const, which is\n // exactly when a plugins module was emitted. Referencing it otherwise would emit an\n // identifier the entry never declares.\n pluginRunnerExpr:\n opts.runtimeConfigModule === undefined ? undefined : 'await THEO_PLUGIN_RUNNER',\n })\n return [\n `// Generated by Theo — Deno Deploy Adapter`,\n `// Deploy: deployctl deploy --project=<name> .theokit/deno/server.ts`,\n `// Requires Deno >= 1.40 (Deno.serve + npm: specifier support)`,\n ``,\n `// Runtime guard`,\n `if (typeof Deno === 'undefined') {`,\n ` throw new Error('TheoDenoDeployAdapter must run inside Deno.')`,\n `}`,\n ``,\n ...FRAMEWORK_IMPORTS,\n ``,\n `const port = Number(Deno.env.get('PORT') ?? '${port}')`,\n `const cwd = Deno.cwd()`,\n `const serverDir = cwd + '/' + ${serverDirLiteral(opts)}`,\n `let routesCache = null`,\n `let wsRoutesCache = null`,\n `let loaderCache = null`,\n ``,\n `// #410 — the security baseline \\`theokit start\\` puts on every response,`,\n `// carried here as a literal because the deployed isolate has no`,\n `// theo.config.ts to read. Non-API paths 404 here and are served by Deno`,\n `// Deploy's static asset handler, so this covers the API and not the`,\n `// document (usetheokit/theokit#412).`,\n ...deployedEntryPreamble(runtimeConfig, agentsFragment, opts, TARGET),\n ``,\n `function notFound() {`,\n ` return new Response(JSON.stringify({ error: { code: 'NOT_FOUND' } }), {`,\n ` status: 404,`,\n ` headers: { 'Content-Type': 'application/json' },`,\n ` })`,\n `}`,\n ``,\n // B-027 — `npm:`, like every other specifier this target emits (`:37-43`). A bare one does\n // not resolve on Deno Deploy, and the harness asserts the prefix is here before rewriting it.\n ...(opts.rateLimit === undefined\n ? []\n : [\n `import { createRateLimiterWeb } from 'npm:theokit/server'`,\n `import { resolveClientIpFromRequest } from 'npm:theokit/server/rate-limit'`,\n ``,\n ]),\n ...deployedRateLimitFragment(\n opts.rateLimit,\n TARGET,\n // `info.remoteAddr` is the runtime's own answer. A `UnixAddr` has no `hostname`, so the\n // optional chain is what keeps the read from throwing there rather than a guess.\n `info?.remoteAddr?.hostname ?? resolveClientIpFromRequest(request, TRUST_PROXY)`,\n 'request, info',\n // B-257 — `npm:`, like every other specifier this target emits. A bare one does not resolve\n // on Deno Deploy, and the durable limiter's import is emitted by the fragment rather than\n // here, so the prefix has to travel with it.\n 'npm:',\n ),\n ``,\n // The serve handler's SECOND parameter is bound here for the first time: `Deno.serve` has\n // always passed it and the emitted entry discarded it.\n `Deno.serve({ port }, async (request, info) => {`,\n ` // #409 — the preflight is answered BEFORE anything routes: an OPTIONS the router`,\n ` // handles is an OPTIONS the browser never gets a CORS answer to.`,\n ` const preflight = corsPreflight(request)`,\n ` if (preflight !== null) return withSecurityHeaders(preflight, SECURITY_HEADERS)`,\n ...rateLimitCheckFragment(opts.rateLimit, ' ', 'request, info'),\n ``,\n ` // LCR0103 — the upgrade branch sits BELOW the limiter, and the order is the point.`,\n ` // It used to sit above, under the comment \"a 101 carries no document and no script,`,\n ` // so the security baseline does not apply to it\". That is true of the security`,\n ` // HEADERS — a document concern — and false of the limiter, which is a resource`,\n ` // concern: a long-lived socket is the most expensive thing this entry hands out, so`,\n ` // the upgrade is the path that most needs a budget, not the one that may skip it.`,\n ` // T3.3 — Detect WebSocket upgrade and delegate to the Deno bridge.`,\n ` // A 101 carries no document and no script, so the security baseline does`,\n ` // not apply to it.`,\n ` if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {`,\n ` if (!wsRoutesCache) wsRoutesCache = scanWebSocketRoutes(serverDir)`,\n ` if (wsRoutesCache.length === 0) return notFound()`,\n ` const denoWs = createDenoWsBridge({`,\n ` onOpen: () => {},`,\n ` onMessage: (ws, data) => { ws.send(data) },`,\n ` onClose: () => {},`,\n ` }, Deno)`,\n ` return denoWs.handle(request)`,\n ` }`,\n ` return withCors(request, withSecurityHeaders(await handleRequest(request), SECURITY_HEADERS))`,\n `})`,\n ``,\n `async function handleRequest(request) {`,\n ` const url = new URL(request.url)`,\n ``,\n ` if (!url.pathname.startsWith('/api/')${agentsFragment.hostBypass}) {`,\n ` // Static + SPA fallback are served by Deno Deploy's static asset handler.`,\n ` return notFound()`,\n ` }`,\n ``,\n ` if (!routesCache) routesCache = scanServerRoutes(serverDir)`,\n ` if (!loaderCache) loaderCache = createProductionLoader()`,\n ``,\n ...agentsFragment.branch,\n ``,\n ` const match = matchRoute(url.pathname, routesCache)`,\n ` if (!match) return notFound()`,\n ``,\n ` const { req, res, toResponse } = createWebShim(request)`,\n ...deployedTraceFragment('request', ' '),\n ` const method = request.method.toUpperCase()`,\n ` // #382 — not awaited: toResponse() settles at the headers and carries a`,\n ` // live body, so Deno.serve streams while the handler writes.`,\n ` return toResponse(executeRoute({ route: match.route, method, params: match.params, req, res, loadModule: loaderCache, serverDir, requestId, ...CSRF_CONFIG, ${runtimeConfig.executeRouteSpread} }))`,\n `}`,\n ``,\n `console.log('Theo (Deno Deploy) listening on :' + port)`,\n ].join('\\n')\n}\n\nexport async function buildDeno(\n config: TheoConfig,\n cwd: string,\n deps: DenoBuildDeps = {},\n ctx?: AdapterBuildContext,\n): Promise<void> {\n // Wave 2 (T2.2) — reject polyglot services on this adapter.\n assertServicesUnsupported('deno-deploy', readManifest(cwd))\n\n const runNodeBuild = deps.runNodeBuild ?? nodeAdapter.build.bind(nodeAdapter)\n await runNodeBuild(config, cwd, ctx)\n\n const outputDir = resolve(cwd, '.theokit/deno')\n const ensureDir = deps.ensureDir ?? ((p: string) => mkdirSync(p, { recursive: true }))\n ensureDir(outputDir)\n\n const pluginsPlan = planDeployedPlugins(config.plugins, denoDeployAdapter.name)\n const entry = renderDenoEntry(config.port, {\n securityHeaders: config.security?.headers,\n csrf: config.security?.csrf,\n disallowed: config.security?.disallowed,\n cors: config.security?.cors,\n // #425 — a selector, not a transformer, so it rides as a literal like the values above.\n serialization: config.serialization,\n // #425 — the ONE concern that is not a literal. A closure cannot be baked, so a plugin\n // declared by module specifier is imported by the emitted module instead; a constructed one\n // is refused by name at build time rather than dropped in silence.\n runtimeConfigModule: pluginsPlan?.moduleSpecifier,\n // #95 — the configured directories, which `build.ts:210` already threads into the Vite\n // plugins. Without these two lines the literals above fall to their defaults and a project\n // with a custom dir deploys an entry that resolves a directory it does not have.\n serverDir: config.serverDir,\n agentsDir: config.agentsDir,\n })\n const write =\n deps.writeEntry ??\n ((p, c) => {\n writeFileSync(p, c)\n })\n if (pluginsPlan !== undefined) {\n // Beside the entry, so the emitted import is a sibling. Written through the same seam as\n // the entry so a test that captures one captures both (#425).\n write(resolve(outputDir, 'theo.plugins.mjs'), pluginsPlan.source)\n }\n write(resolve(outputDir, 'server.ts'), entry)\n\n // eslint-disable-next-line no-console -- CLI build progress\n console.log('\\n ✓ Deno Deploy output → .theokit/deno/server.ts')\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(\n `${describeDeployedSecurityHeaders({\n target: TARGET,\n securityHeaders: config.security?.headers,\n mintsNonce: false,\n documentHeaders: 'platform-unmanaged',\n })}\\n`,\n )\n}\n\nexport const denoDeployAdapter: DeployAdapter = {\n name: 'deno-deploy',\n streamsResponses: true,\n // #409 / #410 — the generated entry calls `executeRoute` with routes, loader\n // and serverDir only. CSRF, route policy, file middleware and Zod validation\n // still run because they live inside `executeRoute`; none of the remaining\n // configurable concerns reach it. Declared explicitly rather than omitted so\n // the gap is a statement in the source and not an absence.\n //\n // `securityHeaders` IS applied -- to every response this isolate returns. The\n // document comes from Deno Deploy's static asset handler and does not pass\n // through it (usetheokit/theokit#412).\n servesAgents: true,\n appliesConfig: ['securityHeaders', 'csrf', 'disallowed', 'cors', 'serialization', 'plugins'],\n // B-257 — per-invocation: an in-process counter does not survive, so a declared limit needs a durable store.\n enforcesRateLimit: 'with-a-store',\n build(config, cwd, ctx) {\n return buildDeno(config, cwd, {}, ctx)\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,SAAS,WAAW,qBAAqB;AACzC,SAAS,eAAe;AAgCxB,IAAM,oBAAuC;AAAA,EAC3C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAMA,IAAM,SAAS;AAER,SAAS,gBAAgB,MAAc,OAA6B,CAAC,GAAW;AACrF,QAAM,gBAAgB,8BAA8B,IAAI;AACxD,QAAM,iBAAiB,uBAAuB,uBAAuB,iBAAiB,IAAI,CAAC,GAAG;AAAA,IAC5F,UAAU;AAAA,IACV,cAAc;AAAA;AAAA;AAAA;AAAA,IAId,kBACE,KAAK,wBAAwB,SAAY,SAAY;AAAA,EACzD,CAAC;AACD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAG;AAAA,IACH;AAAA,IACA,gDAAgD,IAAI;AAAA,IACpD;AAAA,IACA,iCAAiC,iBAAiB,IAAI,CAAC;AAAA,IACvD;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAG,sBAAsB,eAAe,gBAAgB,MAAM,MAAM;AAAA,IACpE;A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