@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 159 lines 5.24 KB
Raw
1 import * as cloudfunctions from "@distilled.cloud/gcp/cloudfunctions_v2";
2 import * as Bundle from "alchemy/Bundle/Bundle";
3 import { findCwdForBundle, resolveMainPath } from "alchemy/Bundle/TempRoot";
4 import { sha256Object } from "alchemy/Util/sha256";
5 import { zipFiles } from "alchemy/Util/zip";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as HttpClient from "effect/http/HttpClient";
9 import * as HttpClientRequest from "effect/http/HttpClientRequest";
10 import { serviceAccountHostBundle } from "../GCPBindings.ts";
11
12 /**
13 * Bundles an Effect-native `GCP.CloudFunctions.Function` `main` into a
14 * Node.js source archive and uploads it through `generateUploadUrl`.
15 *
16 * The archive holds the bundled `index.mjs` (the generated entry around
17 * `main`) and a `package.json` declaring the Functions Framework, which
18 * the Node.js buildpack runs with `--target=handler`.
19 *
20 * NOT exported from `index.ts`.
21 */
22
23 export const FUNCTION_ENTRY_POINT = "handler";
24 export const DEFAULT_NODE_RUNTIME = "nodejs22";
25
26 export class FunctionSourceUploadFailed extends Data.TaggedError(
27 "GCP.CloudFunctions.FunctionSourceUploadFailed",
28 )<{ status: number; message: string }> {}
29
30 /**
31 * Generated entry for an Effect-native Cloud Function: imports only
32 * `@alchemy.run/gcp/Bootstrap/CloudFunction` plus the user's `main`, and
33 * exports the Functions Framework target. The runtime flag is raised
34 * before the user's module evaluates.
35 */
36 export const makeFunctionBootstrap =
37 (handler: string) =>
38 (importPath: string): string =>
39 `
40 import { makeHandler } from "@alchemy.run/gcp/Bootstrap/CloudFunction";
41
42 globalThis.__ALCHEMY_RUNTIME__ = true;
43 const { ${handler}: entrypoint } = await import(${JSON.stringify(importPath)});
44
45 export const ${FUNCTION_ENTRY_POINT} = makeHandler(entrypoint);
46 `;
47
48 const packageJson = `${JSON.stringify(
49 {
50 private: true,
51 type: "module",
52 main: "index.mjs",
53 dependencies: { "@google-cloud/functions-framework": "^3.4.0" },
54 },
55 null,
56 2,
57 )}\n`;
58
59 export const makeFunctionSource = Effect.gen(function* () {
60 const virtualEntryPlugin = yield* Bundle.virtualEntryPlugin;
61
62 /** Bundle `main` and hash the archive's content (no upload). */
63 const bundle = Effect.fn(function* (options: {
64 main: string;
65 handler?: string;
66 build?: Bundle.BundleConfig;
67 isExternal?: boolean;
68 }) {
69 const realMain = yield* resolveMainPath(options.main);
70 const cwd = yield* findCwdForBundle(realMain);
71 const bootstrap = makeFunctionBootstrap(options.handler ?? "default");
72 const output = yield* Bundle.build(
73 // Cloud Functions run as a service account.
74 serviceAccountHostBundle({
75 ...options.build?.input,
76 input: realMain,
77 cwd,
78 platform: "node",
79 resolve: {
80 conditionNames: ["node", "import", "module", "default"],
81 ...options.build?.input?.resolve,
82 },
83 plugins: [
84 options.build?.input?.plugins,
85 options.isExternal ? undefined : virtualEntryPlugin(bootstrap),
86 ],
87 }),
88 {
89 ...options.build?.output,
90 format: "esm",
91 sourcemap: options.build?.output?.sourcemap ?? false,
92 minify: options.build?.output?.minify ?? false,
93 entryFileNames: "index.mjs",
94 },
95 options.build,
96 );
97 const files = [
98 ...output.files.map((file) => ({
99 path: file.path,
100 content:
101 typeof file.content === "string" ? new TextEncoder().encode(file.content) : file.content,
102 })),
103 { path: "package.json", content: packageJson },
104 ];
105 const codeHash = (yield* sha256Object({
106 bundle: output.hash,
107 packageJson,
108 })).slice(0, 16);
109 return { files, codeHash };
110 });
111
112 /** Zip and upload the bundle; returns the `storageSource` to build from. */
113 const upload = Effect.fn(function* (options: {
114 parent: string;
115 files: ReadonlyArray<{ path: string; content: string | Uint8Array }>;
116 kmsKeyName?: string;
117 }) {
118 const archive = yield* zipFiles(options.files);
119 const target = yield* cloudfunctions.generateUploadUrlProjectsLocationsFunctions({
120 parent: options.parent,
121 body: {
122 environment: "GEN_2",
123 ...(options.kmsKeyName ? { kmsKeyName: options.kmsKeyName } : {}),
124 },
125 });
126 if (target.uploadUrl === undefined || target.storageSource === undefined) {
127 return yield* new FunctionSourceUploadFailed({
128 status: 0,
129 message: "generateUploadUrl returned no uploadUrl/storageSource",
130 });
131 }
132 const http = yield* HttpClient.HttpClient;
133 const response = yield* http
134 .execute(
135 HttpClientRequest.put(target.uploadUrl).pipe(
136 HttpClientRequest.bodyUint8Array(new Uint8Array(archive), "application/zip"),
137 ),
138 )
139 .pipe(
140 Effect.mapError(
141 (cause) =>
142 new FunctionSourceUploadFailed({
143 status: 0,
144 message: String(cause),
145 }),
146 ),
147 );
148 if (response.status < 200 || response.status >= 300) {
149 const text = yield* response.text.pipe(Effect.orElseSucceed(() => ""));
150 return yield* new FunctionSourceUploadFailed({
151 status: response.status,
152 message: text.slice(0, 500),
153 });
154 }
155 return target.storageSource;
156 });
157
158 return { bundle, upload };
159 });