@guren/plugin-lambda 0.3.0 → 0.4.0

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.
@@ -1,7 +1,7 @@
1
1
  import { n as LAMBDA_HANDLER_MODULE, t as LAMBDA_HANDLER_EXPORTS } from "./handlers-CkWGWQQX.js";
2
2
  import { cpSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import { resolve } from "node:path";
4
- import { DEV_ONLY_MODULES, MCP_SDK_SUBPATH_PREFIX, assertOutputDirOutsideRoot, clientManifestJson, importSpecifier, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, ssrRuntimePaths, stageStaticAssets, unusedSqlClients } from "@guren/core/internal/deploy-build";
4
+ import { MCP_SDK_SUBPATH_PREFIX, appUsesMcpPlugin, assertOutputDirOutsideRoot, clientManifestJson, importSpecifier, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, ssrRuntimePaths, stageStaticAssets, stubbableDevOnlyModules, unusedSqlClients } from "@guren/core/internal/deploy-build";
5
5
  //#region src/build.ts
6
6
  const MCP_UNAVAILABLE = "The MCP endpoint is unavailable on AWS Lambda — it generates files on disk.";
7
7
  /**
@@ -26,14 +26,20 @@ const UNAVAILABLE_ON_LAMBDA = {
26
26
  * would fail at import time on Lambda even though no code path ever runs it.
27
27
  * Stubbing also keeps megabytes of dev tooling out of the bundle.
28
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.
29
+ * Which of them are in force is per app, and for one reason only: an app that
30
+ * declares `@guren/plugin-mcp` serves the App MCP endpoint here, so its
31
+ * transport must reach the bundle rather than a stub (RFC 0016 §7). The rest
32
+ * are unconditional — nothing an app can declare makes the Vite dev server or
33
+ * the *Dev* MCP's generators run on Lambda. `stubbableDevOnlyModules` owns
34
+ * that distinction; this function only renders what it is handed.
31
35
  */
32
- const DEV_ONLY_STUBS = Object.fromEntries(DEV_ONLY_MODULES.map((module) => [module.specifier, renderDevOnlyStub(module, UNAVAILABLE_ON_LAMBDA[module.kind])]));
36
+ function devOnlyStubs(mcpPlugin) {
37
+ return Object.fromEntries(stubbableDevOnlyModules({ mcpPlugin }).map((module) => [module.specifier, renderDevOnlyStub(module, UNAVAILABLE_ON_LAMBDA[module.kind])]));
38
+ }
33
39
  /**
34
40
  * 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.
41
+ * through. Both halves depend on the app, so it is built per build rather
42
+ * than at module scope.
37
43
  *
38
44
  * A stub here also *overrides* `external`, verified against Bun 1.3.14: the
39
45
  * bundler consults plugins before it consults the external list, so stubbing
@@ -41,14 +47,14 @@ const DEV_ONLY_STUBS = Object.fromEntries(DEV_ONLY_MODULES.map((module) => [modu
41
47
  * than leaving `external: ['@aws-sdk/*']` to keep drizzle's hoisted top-level
42
48
  * import of a package the runtime may not provide.
43
49
  */
44
- function stubsFor(root, dialects) {
50
+ function stubsFor(root, dialects, mcpPlugin) {
45
51
  const unused = unusedSqlClients({
46
52
  root,
47
53
  label: "Lambda build",
48
54
  dialects
49
55
  });
50
56
  return {
51
- ...DEV_ONLY_STUBS,
57
+ ...devOnlyStubs(mcpPlugin),
52
58
  ...Object.fromEntries(unused.map(({ module, message }) => [module.specifier, renderDevOnlyStub(module, message)]))
53
59
  };
54
60
  }
@@ -58,13 +64,21 @@ function stubsFor(root, dialects) {
58
64
  * rather than resolving to an empty module: a subpath reached from app code
59
65
  * (not Guren's disabled MCP endpoint) must fail loudly at build or cold start,
60
66
  * never silently hand back missing exports.
67
+ *
68
+ * Reachable only for an app that does *not* declare `@guren/plugin-mcp`. For
69
+ * one that does, the SDK is a dependency it deliberately ships, and this
70
+ * fallback would stub `server/index.js` and `types.js` — which
71
+ * `@guren/plugin-mcp` imports statically — leaving the endpoint just as
72
+ * compiled shut as the transport stub did. See `stubFilter`.
61
73
  */
62
74
  const unlistedMcpStub = `throw new Error(${JSON.stringify(MCP_UNAVAILABLE)})\n`;
63
75
  function escapeRegExp(value) {
64
76
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
65
77
  }
66
- function stubFilter(stubs) {
67
- return new RegExp(`^(?:${[...Object.keys(stubs).map(escapeRegExp), `${escapeRegExp(MCP_SDK_SUBPATH_PREFIX)}.+`].join("|")})$`);
78
+ function stubFilter(stubs, mcpPlugin) {
79
+ const terms = Object.keys(stubs).map(escapeRegExp);
80
+ if (!mcpPlugin) terms.push(`${escapeRegExp(MCP_SDK_SUBPATH_PREFIX)}.+`);
81
+ return new RegExp(`^(?:${terms.join("|")})$`);
68
82
  }
69
83
  /**
70
84
  * Assemble a deployable AWS Lambda directory (`.lambda/`) from a built Guren
@@ -102,7 +116,8 @@ async function buildLambdaOutput(options = {}) {
102
116
  entrypoint,
103
117
  env: bakedEnv
104
118
  }));
105
- await bundleHandler(wrapperPath, funcDir, stubsFor(root, options.databaseDialects));
119
+ const mcpPlugin = appUsesMcpPlugin(root);
120
+ await bundleHandler(wrapperPath, funcDir, stubsFor(root, options.databaseDialects, mcpPlugin), mcpPlugin);
106
121
  writeFileSync(resolve(funcDir, "package.json"), `${JSON.stringify({ type: "module" }, null, 2)}\n`);
107
122
  if (ssrFile) cpSync(ssrDir, resolve(funcDir, ".guren/ssr"), { recursive: true });
108
123
  if (existsSync(migrationsDir)) cpSync(migrationsDir, resolve(funcDir, "db/migrations"), { recursive: true });
@@ -133,8 +148,8 @@ function renderHandlerModule(input) {
133
148
  lines.push("");
134
149
  return lines.join("\n");
135
150
  }
136
- async function bundleHandler(handlerEntry, funcDir, stubs) {
137
- const filter = stubFilter(stubs);
151
+ async function bundleHandler(handlerEntry, funcDir, stubs, mcpPlugin) {
152
+ const filter = stubFilter(stubs, mcpPlugin);
138
153
  const result = await Bun.build({
139
154
  entrypoints: [handlerEntry],
140
155
  throw: false,
package/dist/cdk/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { r as lambdaHandlerId } from "../handlers-CkWGWQQX.js";
2
2
  import { existsSync, readFileSync, readdirSync } from "node:fs";
3
3
  import { resolve } from "node:path";
4
+ import { DOCUMENT_ASSET_EXTENSIONS, DOCUMENT_ASSET_HEADERS } from "@guren/core/internal/deploy-build";
4
5
  import { CfnOutput, Duration } from "aws-cdk-lib";
5
6
  import * as apigwv2 from "aws-cdk-lib/aws-apigatewayv2";
6
7
  import { HttpLambdaIntegration } from "aws-cdk-lib/aws-apigatewayv2-integrations";
@@ -129,10 +130,19 @@ var GurenLambdaApp = class extends Construct {
129
130
  enforceSSL: true
130
131
  });
131
132
  const apiDomain = `${this.httpApi.apiId}.execute-api.${this.httpApi.stack.region}.${this.httpApi.stack.urlSuffix}`;
133
+ const assetOrigin = origins.S3BucketOrigin.withOriginAccessControl(this.assetsBucket);
134
+ const documentGuard = new cloudfront.Function(this, "AssetDocumentGuard", {
135
+ code: cloudfront.FunctionCode.fromInline(renderAssetDocumentGuard()),
136
+ runtime: cloudfront.FunctionRuntime.JS_2_0
137
+ });
132
138
  const assetBehavior = {
133
- origin: origins.S3BucketOrigin.withOriginAccessControl(this.assetsBucket),
139
+ origin: assetOrigin,
134
140
  viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
135
- cachePolicy: cloudfront.CachePolicy.CACHING_OPTIMIZED
141
+ cachePolicy: cloudfront.CachePolicy.CACHING_OPTIMIZED,
142
+ functionAssociations: [{
143
+ function: documentGuard,
144
+ eventType: cloudfront.FunctionEventType.VIEWER_RESPONSE
145
+ }]
136
146
  };
137
147
  const additionalBehaviors = {
138
148
  "/assets/*": assetBehavior,
@@ -163,6 +173,84 @@ var GurenLambdaApp = class extends Construct {
163
173
  new CfnOutput(this, "ApiUrl", { value: this.httpApi.apiEndpoint });
164
174
  }
165
175
  };
176
+ /**
177
+ * The CloudFront function body that turns a staged document into a download.
178
+ *
179
+ * CloudFront answers every asset behaviour from S3 directly, so
180
+ * `guardStaticDocument` — which the framework applies on each mount that
181
+ * reaches `public/` — never sees these files. Without this the same app
182
+ * downloads an SVG locally and renders it inline, script and all, on its own
183
+ * origin in production.
184
+ *
185
+ * A viewer-response function rather than one cache behaviour per extension:
186
+ * a behaviour is chosen by path, so `*.svg` would also capture a `/feed.svg`
187
+ * the *app* renders and send it to S3, and the default limit of 25
188
+ * behaviours is already spent one per staged root entry. The association
189
+ * rides on `assetBehavior` alone, which is what keeps it off the default
190
+ * behaviour — the app, whose responses carry the framework's own headers.
191
+ *
192
+ * The extension is read from the request path because that path is the S3
193
+ * key here: this distribution sets no `defaultRootObject` and rewrites no
194
+ * index, so nothing stands between `/page.html` and the document. A platform
195
+ * that served `public/page.html` at `/page` would leave the `.html` half of
196
+ * this rule matching only the redirect.
197
+ *
198
+ * `toLowerCase()` covers the extension case `DOCUMENT_ASSET_EXTENSIONS`
199
+ * records as unreachable from a literal pattern: `getMimeType` lowercases
200
+ * before its lookup, so `logo.SVG` downloads under the framework's own guard,
201
+ * and reading the extension rather than matching a pattern is what lets this
202
+ * target agree with it.
203
+ */
204
+ function renderAssetDocumentGuard() {
205
+ const headers = Object.fromEntries(Object.entries(DOCUMENT_ASSET_HEADERS).map(([name, value]) => [name.toLowerCase(), value]));
206
+ return [
207
+ `var DOCUMENT_EXTENSIONS = ${JSON.stringify(DOCUMENT_ASSET_EXTENSIONS)}`,
208
+ `var DOCUMENT_HEADERS = ${JSON.stringify(headers)}`,
209
+ "",
210
+ ASSET_DOCUMENT_GUARD_BODY
211
+ ].join("\n");
212
+ }
213
+ /**
214
+ * The function CloudFront runs, verbatim, reading the two constants
215
+ * {@link renderAssetDocumentGuard} declares above it.
216
+ *
217
+ * Free of interpolation on purpose. A template that substitutes into its own
218
+ * body has to be read twice, once as TypeScript and once as the JavaScript it
219
+ * becomes, and a `$` or a backtick in the JavaScript changes the result of the
220
+ * first reading. Here the string is the program: it can be pasted into the
221
+ * CloudFront console, or run beside the two `var` lines anywhere else, and
222
+ * behave exactly as it does deployed.
223
+ */
224
+ const ASSET_DOCUMENT_GUARD_BODY = `function handler(event) {
225
+ var uri = event.request.uri
226
+ var response = event.response
227
+
228
+ // Decoded first: CloudFront picks the behavior from a normalized path but
229
+ // hands the function the raw one, and S3 resolves percent-encoding when it
230
+ // matches a key. So /evil%2Esvg reaches the object evil.svg while the raw
231
+ // string holds no dot at all — the extension test would find nothing and
232
+ // the document would come back inline. A malformed sequence throws rather
233
+ // than decoding; the raw path is the safe thing to judge in that case,
234
+ // since it is also what no key will match.
235
+ try {
236
+ uri = decodeURIComponent(uri)
237
+ } catch (error) {
238
+ uri = event.request.uri
239
+ }
240
+
241
+ var dot = uri.lastIndexOf('.')
242
+
243
+ // A dot only ends the last segment when it follows the last slash: without
244
+ // the comparison, /v1.2/app reads as an extension of "2/app".
245
+ if (dot > uri.lastIndexOf('/') && DOCUMENT_EXTENSIONS.indexOf(uri.substring(dot + 1).toLowerCase()) !== -1) {
246
+ for (var name in DOCUMENT_HEADERS) {
247
+ response.headers[name] = { value: DOCUMENT_HEADERS[name] }
248
+ }
249
+ }
250
+
251
+ return response
252
+ }
253
+ `;
166
254
  function dataApiEnvironment(dataApi) {
167
255
  if (!dataApi) return {};
168
256
  return {
package/dist/commands.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as buildLambdaOutput } from "./build-BYE_vKGQ.js";
1
+ import { t as buildLambdaOutput } from "./build-CHTrBLNm.js";
2
2
  import { DATABASE_DIALECTS, parseDatabaseDialects } from "@guren/core/internal/deploy-build";
3
3
  import { defineCommand } from "citty";
4
4
  var commands_default = { "lambda:build": defineCommand({
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { n as LAMBDA_HANDLER_MODULE, r as lambdaHandlerId, t as LAMBDA_HANDLER_EXPORTS } from "./handlers-CkWGWQQX.js";
2
- import { t as buildLambdaOutput } from "./build-BYE_vKGQ.js";
2
+ import { t as buildLambdaOutput } from "./build-CHTrBLNm.js";
3
3
  import { definePlugin } from "@guren/core";
4
4
  //#region src/index.ts
5
5
  const factory = definePlugin({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/plugin-lambda",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -45,7 +45,7 @@
45
45
  "typecheck": "tsc --noEmit"
46
46
  },
47
47
  "dependencies": {
48
- "@guren/core": "^1.10.0",
48
+ "@guren/core": "^1.13.0",
49
49
  "citty": "^0.1.6"
50
50
  },
51
51
  "peerDependencies": {