@guren/plugin-lambda 0.2.0 → 0.2.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/build-56qBHosh.js +221 -0
- package/dist/cdk/index.d.ts +56 -56
- package/dist/cdk/index.js +164 -178
- package/dist/commands.d.ts +21 -22
- package/dist/commands.js +36 -45
- package/dist/handlers-CkWGWQQX.js +19 -0
- package/dist/index.d.ts +38 -37
- package/dist/index.js +17 -22
- package/package.json +5 -5
- package/dist/chunk-K64F77DP.js +0 -12
- package/dist/chunk-OTE5NGTW.js +0 -262
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import { n as LAMBDA_HANDLER_MODULE, t as LAMBDA_HANDLER_EXPORTS } from "./handlers-CkWGWQQX.js";
|
|
2
|
+
import { cpSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { resolve } from "node:path";
|
|
4
|
+
import { DEV_ONLY_MODULES, MCP_SDK_SUBPATH_PREFIX, assertOutputDirOutsideRoot, importSpecifier, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, ssrRuntimePaths, stageStaticAssets, unusedSqlClients } from "@guren/core/internal/deploy-build";
|
|
5
|
+
//#region src/build.ts
|
|
6
|
+
const MCP_UNAVAILABLE = "The MCP endpoint is unavailable on AWS Lambda — it generates files on disk.";
|
|
7
|
+
/**
|
|
8
|
+
* Why the dev-only modules in `DEV_ONLY_MODULES` cannot run here, worded for
|
|
9
|
+
* this platform: each names the Lambda-appropriate replacement.
|
|
10
|
+
*
|
|
11
|
+
* Keyed on the kinds this platform stubs unconditionally, not on every kind
|
|
12
|
+
* that exists. The SQL clients are load-bearing on Lambda — the app connects
|
|
13
|
+
* to Postgres or the Data API through them — so which of those are dead
|
|
14
|
+
* weight is decided per app, not here, and their messages come from
|
|
15
|
+
* `unusedSqlClients`.
|
|
16
|
+
*/
|
|
17
|
+
const UNAVAILABLE_ON_LAMBDA = {
|
|
18
|
+
sqlite: "bun:sqlite is unavailable on AWS Lambda — use createAwsDataApiDatabase() or createPostgresDatabase().",
|
|
19
|
+
vite: "The Vite dev server is unavailable on AWS Lambda — serve assets from S3/CloudFront.",
|
|
20
|
+
mcp: MCP_UNAVAILABLE
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Dev-only modules replaced with throwing stubs rather than left external.
|
|
24
|
+
* Inlining a lazily-imported module hoists that module's own static imports to
|
|
25
|
+
* the bundle top level, so an external module reached this way (the MCP SDK)
|
|
26
|
+
* would fail at import time on Lambda even though no code path ever runs it.
|
|
27
|
+
* Stubbing also keeps megabytes of dev tooling out of the bundle.
|
|
28
|
+
*
|
|
29
|
+
* Unconditional, unlike the database clients: nothing an app can declare makes
|
|
30
|
+
* the Vite dev server or the MCP endpoint's generators run on Lambda.
|
|
31
|
+
*/
|
|
32
|
+
const DEV_ONLY_STUBS = Object.fromEntries(DEV_ONLY_MODULES.map((module) => [module.specifier, renderDevOnlyStub(module, UNAVAILABLE_ON_LAMBDA[module.kind])]));
|
|
33
|
+
/**
|
|
34
|
+
* The dev-only stubs plus one per database client this app does not connect
|
|
35
|
+
* through. Unlike the dev-only set this depends on the app, so it is built
|
|
36
|
+
* per build rather than at module scope.
|
|
37
|
+
*
|
|
38
|
+
* A stub here also *overrides* `external`, verified against Bun 1.3.14: the
|
|
39
|
+
* bundler consults plugins before it consults the external list, so stubbing
|
|
40
|
+
* `@aws-sdk/client-rds-data` for a Postgres app really does replace it rather
|
|
41
|
+
* than leaving `external: ['@aws-sdk/*']` to keep drizzle's hoisted top-level
|
|
42
|
+
* import of a package the runtime may not provide.
|
|
43
|
+
*/
|
|
44
|
+
function stubsFor(root, dialects) {
|
|
45
|
+
const unused = unusedSqlClients({
|
|
46
|
+
root,
|
|
47
|
+
label: "Lambda build",
|
|
48
|
+
dialects
|
|
49
|
+
});
|
|
50
|
+
return {
|
|
51
|
+
...DEV_ONLY_STUBS,
|
|
52
|
+
...Object.fromEntries(unused.map(({ module, message }) => [module.specifier, renderDevOnlyStub(module, message)]))
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Fallback for an MCP SDK subpath `DEV_ONLY_MODULES` does not name. It cannot
|
|
57
|
+
* know which names the importer destructures, so it throws on evaluation
|
|
58
|
+
* rather than resolving to an empty module: a subpath reached from app code
|
|
59
|
+
* (not Guren's disabled MCP endpoint) must fail loudly at build or cold start,
|
|
60
|
+
* never silently hand back missing exports.
|
|
61
|
+
*/
|
|
62
|
+
const unlistedMcpStub = `throw new Error(${JSON.stringify(MCP_UNAVAILABLE)})\n`;
|
|
63
|
+
function escapeRegExp(value) {
|
|
64
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
65
|
+
}
|
|
66
|
+
function stubFilter(stubs) {
|
|
67
|
+
return new RegExp(`^(?:${[...Object.keys(stubs).map(escapeRegExp), `${escapeRegExp(MCP_SDK_SUBPATH_PREFIX)}.+`].join("|")})$`);
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Assemble a deployable AWS Lambda directory (`.lambda/`) from a built Guren
|
|
71
|
+
* app: a self-contained function bundle for the Node.js runtime, the SSR
|
|
72
|
+
* bundle and migrations alongside it, static assets staged for S3, and an
|
|
73
|
+
* `env.json` with the environment the function expects.
|
|
74
|
+
*/
|
|
75
|
+
async function buildLambdaOutput(options = {}) {
|
|
76
|
+
const root = resolvePathLike(options.rootDir ?? process.cwd());
|
|
77
|
+
const out = resolvePathLike(options.outputDir ?? resolve(root, ".lambda"));
|
|
78
|
+
const entrypoint = resolvePathLike(options.entrypoint ?? resolve(root, "src/lambda.ts"));
|
|
79
|
+
const publicDir = resolvePathLike(options.publicDir ?? resolve(root, "public"));
|
|
80
|
+
const ssrDir = resolvePathLike(options.ssrDir ?? resolve(root, ".guren/ssr"));
|
|
81
|
+
const migrationsDir = resolvePathLike(options.migrationsDir ?? resolve(root, "db/migrations"));
|
|
82
|
+
const clientEntryKey = options.clientEntryKey ?? "resources/js/app.tsx";
|
|
83
|
+
const ssrEntryKey = options.ssrEntryKey ?? "resources/js/ssr.tsx";
|
|
84
|
+
assertOutputDirOutsideRoot(out, root, "Lambda build");
|
|
85
|
+
if (!options.skipAppBuild) runAppBuild(root);
|
|
86
|
+
if (!existsSync(entrypoint)) throw new Error(`Lambda build: entrypoint not found at ${entrypoint}. Run \`bunx guren plugin @guren/plugin-lambda\` to scaffold src/lambda.ts, or pass "entrypoint".`);
|
|
87
|
+
const ssrFile = resolveSsrEntry(ssrDir, ssrEntryKey);
|
|
88
|
+
const assetEnv = resolveClientAssetEnv(publicDir, clientEntryKey, "Lambda build");
|
|
89
|
+
resetOutputDir(out, root, "Lambda build");
|
|
90
|
+
const funcDir = resolve(out, "function");
|
|
91
|
+
mkdirSync(funcDir, { recursive: true });
|
|
92
|
+
stageStaticAssets(publicDir, resolve(out, "assets"));
|
|
93
|
+
const env = buildLambdaEnvironment(assetEnv, ssrFile, ssrDir);
|
|
94
|
+
const wrapperPath = resolve(out, `${LAMBDA_HANDLER_MODULE}.ts`);
|
|
95
|
+
writeFileSync(wrapperPath, renderHandlerModule({
|
|
96
|
+
out,
|
|
97
|
+
entrypoint,
|
|
98
|
+
env
|
|
99
|
+
}));
|
|
100
|
+
await bundleHandler(wrapperPath, funcDir, stubsFor(root, options.databaseDialects));
|
|
101
|
+
writeFileSync(resolve(funcDir, "package.json"), `${JSON.stringify({ type: "module" }, null, 2)}\n`);
|
|
102
|
+
if (ssrFile) cpSync(ssrDir, resolve(funcDir, ".guren/ssr"), { recursive: true });
|
|
103
|
+
if (existsSync(migrationsDir)) cpSync(migrationsDir, resolve(funcDir, "db/migrations"), { recursive: true });
|
|
104
|
+
writeFileSync(resolve(out, "env.json"), `${JSON.stringify({
|
|
105
|
+
NODE_ENV: "production",
|
|
106
|
+
...env
|
|
107
|
+
}, null, 2)}\n`);
|
|
108
|
+
if (options.zip) zipFunction(out, funcDir);
|
|
109
|
+
}
|
|
110
|
+
function buildLambdaEnvironment(assetEnv, ssrFile, ssrDir) {
|
|
111
|
+
const env = {};
|
|
112
|
+
if (assetEnv.entry) env.GUREN_INERTIA_ENTRY = assetEnv.entry;
|
|
113
|
+
if (assetEnv.styles) env.GUREN_INERTIA_STYLES = assetEnv.styles;
|
|
114
|
+
if (ssrFile) {
|
|
115
|
+
const ssrPaths = ssrRuntimePaths(ssrDir, ssrFile, "./.guren/ssr");
|
|
116
|
+
env.GUREN_INERTIA_SSR_ENTRY = ssrPaths.entry;
|
|
117
|
+
if (ssrPaths.manifest) env.GUREN_INERTIA_SSR_MANIFEST = ssrPaths.manifest;
|
|
118
|
+
}
|
|
119
|
+
return env;
|
|
120
|
+
}
|
|
121
|
+
function renderHandlerModule(input) {
|
|
122
|
+
const lines = ["// Generated by `guren lambda:build`. Do not edit — regenerate instead.", ""];
|
|
123
|
+
const envEntries = Object.entries(input.env);
|
|
124
|
+
if (envEntries.length > 0) lines.push("// Baked as defaults so a deploy needs no function configuration; real", "// environment variables (e.g. absolute CloudFront URLs) still win.", ...envEntries.map(([key, value]) => `process.env.${key} ??= ${JSON.stringify(value)}`), "");
|
|
125
|
+
lines.push("// Imported dynamically so the assignments above run before the app module", "// graph evaluates — static imports are hoisted past them.", `const module = await import(${JSON.stringify(importSpecifier(input.out, input.entrypoint, "Lambda build"))})`, "");
|
|
126
|
+
for (const name of LAMBDA_HANDLER_EXPORTS) if (name === "console") lines.push("const consoleHandler = module.console", "export { consoleHandler as console }");
|
|
127
|
+
else lines.push(`export const ${name} = module.${name}`);
|
|
128
|
+
lines.push("");
|
|
129
|
+
return lines.join("\n");
|
|
130
|
+
}
|
|
131
|
+
async function bundleHandler(handlerEntry, funcDir, stubs) {
|
|
132
|
+
const filter = stubFilter(stubs);
|
|
133
|
+
const result = await Bun.build({
|
|
134
|
+
entrypoints: [handlerEntry],
|
|
135
|
+
throw: false,
|
|
136
|
+
outdir: funcDir,
|
|
137
|
+
target: "node",
|
|
138
|
+
minify: {
|
|
139
|
+
whitespace: true,
|
|
140
|
+
syntax: true,
|
|
141
|
+
identifiers: false
|
|
142
|
+
},
|
|
143
|
+
define: {
|
|
144
|
+
"process.env.NODE_ENV": "\"production\"",
|
|
145
|
+
"import.meta.url": "\"file:///var/task/config/lambda.js\""
|
|
146
|
+
},
|
|
147
|
+
external: ["@aws-sdk/*"],
|
|
148
|
+
plugins: [{
|
|
149
|
+
name: "guren-lambda-stubs",
|
|
150
|
+
setup(build) {
|
|
151
|
+
build.onResolve({ filter }, (args) => ({
|
|
152
|
+
path: args.path,
|
|
153
|
+
namespace: "guren-lambda-stub"
|
|
154
|
+
}));
|
|
155
|
+
build.onLoad({
|
|
156
|
+
filter: /.*/,
|
|
157
|
+
namespace: "guren-lambda-stub"
|
|
158
|
+
}, (args) => ({
|
|
159
|
+
contents: stubs[args.path] ?? unlistedMcpStub,
|
|
160
|
+
loader: "js"
|
|
161
|
+
}));
|
|
162
|
+
}
|
|
163
|
+
}]
|
|
164
|
+
});
|
|
165
|
+
if (!result.success) {
|
|
166
|
+
const details = result.logs.map((log) => String(log)).join("\n");
|
|
167
|
+
throw new Error(`Lambda build: bun build failed.\n${details}`);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
function zipFunction(out, funcDir) {
|
|
171
|
+
if (Bun.spawnSync({
|
|
172
|
+
cmd: [
|
|
173
|
+
"zip",
|
|
174
|
+
"-qr",
|
|
175
|
+
resolve(out, "function.zip"),
|
|
176
|
+
"."
|
|
177
|
+
],
|
|
178
|
+
cwd: funcDir,
|
|
179
|
+
stdout: "inherit",
|
|
180
|
+
stderr: "inherit"
|
|
181
|
+
}).exitCode !== 0) throw new Error("Lambda build: zip failed. Install the `zip` binary or deploy the function directory directly (CDK archives it for you).");
|
|
182
|
+
}
|
|
183
|
+
function hasBuildScript(root) {
|
|
184
|
+
const packageJsonPath = resolve(root, "package.json");
|
|
185
|
+
if (!existsSync(packageJsonPath)) return false;
|
|
186
|
+
try {
|
|
187
|
+
const { scripts } = JSON.parse(readFileSync(packageJsonPath, "utf8"));
|
|
188
|
+
return Boolean(scripts?.build);
|
|
189
|
+
} catch {
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
function runAppBuild(root) {
|
|
194
|
+
if (!hasBuildScript(root)) {
|
|
195
|
+
console.warn("Lambda build: no \"build\" script in package.json — skipping the app build step.");
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
if (Bun.spawnSync({
|
|
199
|
+
cmd: [
|
|
200
|
+
"bun",
|
|
201
|
+
"run",
|
|
202
|
+
"build"
|
|
203
|
+
],
|
|
204
|
+
cwd: root,
|
|
205
|
+
stdout: "inherit",
|
|
206
|
+
stderr: "inherit"
|
|
207
|
+
}).exitCode !== 0) throw new Error("Lambda build: the app \"build\" script failed.");
|
|
208
|
+
}
|
|
209
|
+
/** Absolute path of the built SSR entry chunk, or undefined for CSR-only apps. */
|
|
210
|
+
function resolveSsrEntry(ssrDir, ssrEntryKey) {
|
|
211
|
+
const file = resolveSsrEntryFile(ssrDir, ssrEntryKey, "Lambda build");
|
|
212
|
+
if (!file) return;
|
|
213
|
+
if (!hasRendererExport(readFileSync(file, "utf8"))) throw new Error(`Lambda build: SSR entry ${file} does not export a renderer (expected a named "render" or default export).`);
|
|
214
|
+
return file;
|
|
215
|
+
}
|
|
216
|
+
function hasRendererExport(source) {
|
|
217
|
+
if (/export\s*\*\s*from/.test(source)) return true;
|
|
218
|
+
return /export\s+default\b/.test(source) || /export\s*\{[^}]*\b(?:render|default)\b[^}]*\}/.test(source) || /export\s+(?:const|let|var|function|async\s+function)\s+render\b/.test(source);
|
|
219
|
+
}
|
|
220
|
+
//#endregion
|
|
221
|
+
export { buildLambdaOutput as t };
|
package/dist/cdk/index.d.ts
CHANGED
|
@@ -1,56 +1,56 @@
|
|
|
1
|
-
import { Duration } from
|
|
2
|
-
import * as apigwv2 from
|
|
3
|
-
import * as cloudfront from
|
|
4
|
-
import * as lambda from
|
|
5
|
-
import * as s3 from
|
|
6
|
-
import * as sqs from
|
|
7
|
-
import { Construct } from
|
|
8
|
-
|
|
1
|
+
import { Duration } from "aws-cdk-lib";
|
|
2
|
+
import * as apigwv2 from "aws-cdk-lib/aws-apigatewayv2";
|
|
3
|
+
import * as cloudfront from "aws-cdk-lib/aws-cloudfront";
|
|
4
|
+
import * as lambda from "aws-cdk-lib/aws-lambda";
|
|
5
|
+
import * as s3 from "aws-cdk-lib/aws-s3";
|
|
6
|
+
import * as sqs from "aws-cdk-lib/aws-sqs";
|
|
7
|
+
import { Construct } from "constructs";
|
|
8
|
+
//#region src/cdk/index.d.ts
|
|
9
9
|
interface GurenLambdaQueueProps {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
10
|
+
/** SQS messages delivered per invocation. Defaults to 10. */
|
|
11
|
+
batchSize?: number;
|
|
12
|
+
/** Retries before a message lands in the dead-letter queue. Defaults to 3. */
|
|
13
|
+
maxReceiveCount?: number;
|
|
14
|
+
/** Worker timeout. Also drives the queue's visibility timeout. Defaults to 60 seconds. */
|
|
15
|
+
timeout?: Duration;
|
|
16
16
|
}
|
|
17
17
|
interface GurenLambdaScheduleProps {
|
|
18
|
-
|
|
19
|
-
|
|
18
|
+
/** How often the scheduler handler runs. Defaults to every minute. */
|
|
19
|
+
rate?: Duration;
|
|
20
20
|
}
|
|
21
21
|
interface GurenLambdaAssetsProps {
|
|
22
|
-
|
|
23
|
-
|
|
22
|
+
/** The staged assets directory produced by `guren lambda:build` (`.lambda/assets`). */
|
|
23
|
+
dir: string;
|
|
24
24
|
}
|
|
25
25
|
interface GurenLambdaDataApiProps {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
26
|
+
/** Aurora cluster ARN — exposed as DATABASE_RESOURCE_ARN. */
|
|
27
|
+
resourceArn: string;
|
|
28
|
+
/** Secrets Manager secret ARN — exposed as DATABASE_SECRET_ARN. */
|
|
29
|
+
secretArn: string;
|
|
30
|
+
/** Database name — exposed as DATABASE_NAME. */
|
|
31
|
+
database?: string;
|
|
32
32
|
}
|
|
33
33
|
interface GurenLambdaAppProps {
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
34
|
+
/** The function directory produced by `guren lambda:build` (`.lambda/function`). */
|
|
35
|
+
functionDir: string;
|
|
36
|
+
/** Environment variables shared by every function (DATABASE_*, APP_KEY, ...). */
|
|
37
|
+
environment?: Record<string, string>;
|
|
38
|
+
/** Defaults to Node.js 22 — the runtime `lambda:build` bundles for. */
|
|
39
|
+
runtime?: lambda.Runtime;
|
|
40
|
+
/** Memory for every function. Defaults to 512 MB. */
|
|
41
|
+
memorySize?: number;
|
|
42
|
+
/** HTTP function timeout. Defaults to 30 seconds. */
|
|
43
|
+
timeout?: Duration;
|
|
44
|
+
/** Provision SQS + a queue worker wired to the `queue` export. */
|
|
45
|
+
queue?: GurenLambdaQueueProps;
|
|
46
|
+
/** Provision an EventBridge rule wired to the `schedule` export. */
|
|
47
|
+
schedule?: GurenLambdaScheduleProps;
|
|
48
|
+
/** Provision a console function wired to the `console` export (invoke with `{"command": "db:migrate"}`). */
|
|
49
|
+
console?: boolean;
|
|
50
|
+
/** Serve `.lambda/assets` from S3 behind CloudFront, with the app as the default origin. */
|
|
51
|
+
assets?: GurenLambdaAssetsProps;
|
|
52
|
+
/** Wire every function to Aurora via the RDS Data API: environment plus the rds-data and secret-read grants. */
|
|
53
|
+
dataApi?: GurenLambdaDataApiProps;
|
|
54
54
|
}
|
|
55
55
|
/**
|
|
56
56
|
* The full serverless topology for a Guren app in one construct: an HTTP API
|
|
@@ -69,16 +69,16 @@ interface GurenLambdaAppProps {
|
|
|
69
69
|
* ```
|
|
70
70
|
*/
|
|
71
71
|
declare class GurenLambdaApp extends Construct {
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
72
|
+
readonly httpFunction: lambda.Function;
|
|
73
|
+
readonly httpApi: apigwv2.HttpApi;
|
|
74
|
+
readonly queue?: sqs.Queue;
|
|
75
|
+
readonly deadLetterQueue?: sqs.Queue;
|
|
76
|
+
readonly queueFunction?: lambda.Function;
|
|
77
|
+
readonly scheduleFunction?: lambda.Function;
|
|
78
|
+
readonly consoleFunction?: lambda.Function;
|
|
79
|
+
readonly assetsBucket?: s3.Bucket;
|
|
80
|
+
readonly distribution?: cloudfront.Distribution;
|
|
81
|
+
constructor(scope: Construct, id: string, props: GurenLambdaAppProps);
|
|
82
82
|
}
|
|
83
|
-
|
|
84
|
-
export { GurenLambdaApp,
|
|
83
|
+
//#endregion
|
|
84
|
+
export { GurenLambdaApp, GurenLambdaAppProps, GurenLambdaAssetsProps, GurenLambdaDataApiProps, GurenLambdaQueueProps, GurenLambdaScheduleProps };
|