@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 121 lines 4.3 KB
Raw
1 /**
2 * Runtime helpers consumed by generated bundle entrypoints (Cloudflare
3 * Workers, Cloudflare Containers, AWS Lambda, …).
4 *
5 * Anything exported here runs *inside* the deployed function — keep the
6 * surface tiny and dependency-light.
7 */
8
9 import * as ConfigProvider from "effect/ConfigProvider";
10 import * as Effect from "effect/Effect";
11 import * as Layer from "effect/Layer";
12 import { isRedactedMarker, sanitizeKey } from "./RuntimeContext.ts";
13 import { asEffect } from "./Util/types.ts";
14
15 /**
16 * Resolve the user's default-export entrypoint into a `Layer` for the
17 * bundled runtime.
18 *
19 * `entrypoint` may be any of:
20 * - a `Layer` factory (`{ build: (...) => ... }`) — used as-is
21 * - an Alchemy `Platform`/`Worker` construct (now a real `Effect`)
22 * - a plain `Effect`
23 *
24 * Centralized so the inline ternary doesn't have to be re-emitted into
25 * every bundle template (and accidentally rewritten to `x : x` by a bulk
26 * replace, which silently swaps the class in for the Effect and bricks
27 * every deployed worker/lambda).
28 */
29 export const makeEntrypointLayer = (tag: any, entrypoint: any): Layer.Layer<any> => {
30 if (typeof entrypoint?.build === "function") {
31 return entrypoint;
32 }
33 return Layer.effect(tag, asEffect(entrypoint));
34 };
35
36 /**
37 * Unwrap the `{"_tag":"Redacted","value":...}` marker that the deploy-time
38 * `Config` interceptor (see `Platform.ts`) and `RuntimeContext.set` use to
39 * preserve `Redacted`-ness across the env-var boundary. Returns the inner
40 * source value as a string, or `undefined` when `raw` is not a marker.
41 */
42 const parseRedactedMarker = (raw: string): string | undefined => {
43 if (!raw.startsWith("{")) {
44 return undefined;
45 }
46 try {
47 const parsed: unknown = JSON.parse(raw);
48 if (isRedactedMarker(parsed)) {
49 return typeof parsed.value === "string" ? parsed.value : JSON.stringify(parsed.value);
50 }
51 } catch {
52 // not JSON — plain env value, fall through
53 }
54 return undefined;
55 };
56
57 /**
58 * Reify an env-var string the way `RuntimeContext.get` does: unwrap the
59 * `Redacted` marker, unquote a JSON-stringified string, and pass anything
60 * else through verbatim.
61 */
62 const reifyEnvString = (raw: string): string => {
63 const marker = parseRedactedMarker(raw);
64 if (marker !== undefined) {
65 return marker;
66 }
67 if (raw.startsWith('"')) {
68 try {
69 const parsed: unknown = JSON.parse(raw);
70 if (typeof parsed === "string") {
71 return parsed;
72 }
73 } catch {
74 // not JSON — plain env value, fall through
75 }
76 }
77 return raw;
78 };
79
80 /**
81 * Wrap a runtime's env-backed `ConfigProvider` so values that were
82 * auto-bound by the deploy-time `Config` interceptor decode transparently.
83 *
84 * The engine can't know which config values are sensitive, so the
85 * interceptor binds every `Config` read during Init onto the deploy target
86 * as a secret, serialized as a `{"_tag":"Redacted","value":<source>}`
87 * marker. The interceptor's runtime branch reifies those markers for reads
88 * during Init, but effects that run later (request handlers, nested
89 * layers) resolve `Config` against the raw env-backed provider — without
90 * this wrapper, `Config.Number("PORT")` inside a handler sees the marker
91 * JSON instead of the source value and fails with a schema error.
92 *
93 * Two behaviors:
94 * - Leaf values that carry the marker are unwrapped to the raw source
95 * string before `Config` schemas decode them; everything else passes
96 * through untouched.
97 * - On a miss, falls back to the flat `sanitizeKey`-canonicalized key
98 * (`my.key` → `my_key`) that the interceptor bound the value under, so
99 * config names with non-alphanumeric characters resolve at runtime too.
100 */
101 export const reifyBoundConfigProvider = (
102 base: ConfigProvider.ConfigProvider,
103 env: Record<string, unknown>,
104 ): ConfigProvider.ConfigProvider =>
105 ConfigProvider.make((path) =>
106 base.load(path).pipe(
107 Effect.map((node) => {
108 if (node?._tag === "Value") {
109 const value = parseRedactedMarker(node.value);
110 return value === undefined ? node : ConfigProvider.makeValue(value);
111 }
112 if (node === undefined) {
113 const raw = env[sanitizeKey(path.map((p) => p.toString()).join("_"))];
114 if (typeof raw === "string") {
115 return ConfigProvider.makeValue(reifyEnvString(raw));
116 }
117 }
118 return node;
119 }),
120 ),
121 );