@guren/core 1.12.0 → 1.13.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.
@@ -0,0 +1 @@
1
+ export * from "@guren/server/agent";
package/dist/agent.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from "@guren/server/agent";
2
+ export {};
package/dist/index.d.ts CHANGED
@@ -578,6 +578,24 @@ interface DeliveryOptions {
578
578
  */
579
579
  routeName?: string;
580
580
  }
581
+ /**
582
+ * The single storage key prefix every attachment object lives under:
583
+ * `attachments/<id>/<name>` for an original, `attachments/<id>/variants/…`
584
+ * for a derivative, and `attachments/` itself for the prune sweep's
585
+ * directory listing.
586
+ *
587
+ * Exported, and re-exported from `@guren/core`, because the layout is not
588
+ * private to this file. `guren check`'s attachments rules judge, from
589
+ * another package, whether uploaded bytes land somewhere the app serves
590
+ * statically — and the ones that reach the objects themselves have to name
591
+ * `<disk root>/attachments` to do it. A restated copy of the prefix over
592
+ * there does not fail loudly when this layout moves (a shard level, a
593
+ * rename): it stops matching, answers "not reachable", and reports an
594
+ * exposed app as safe. A build-failing security rule failing *open*, with
595
+ * nothing going red anywhere. Import this instead of restating it.
596
+ */
597
+ declare const ATTACHMENT_OBJECT_PREFIX = "attachments";
598
+ declare const DEFAULT_DELIVERY_ROUTE_NAME = "attachments.show";
581
599
  interface PruneOptions {
582
600
  /** Also delete `attachments/` storage prefixes that no row references. */
583
601
  objects?: boolean;
@@ -853,4 +871,4 @@ declare class GenerateVariantsJob extends Job<GenerateVariantsPayload> {
853
871
  failed(payload: GenerateVariantsPayload, _error: Error): Promise<void>;
854
872
  }
855
873
  //#endregion
856
- export { type AccessorDefinitions, type AccessorFn, type AttachOptions, Attachable, type AttachableRecordId, type AttachableStatic, type AttachedCollectionOptions, type AttachmentCollectionSpec, type AttachmentData, AttachmentDeliveryController, type AttachmentRecord, type AttachmentSource, type AttachmentUrlOptions, type AttachmentVariantRecord, type AttachmentsDeclaration, AttachmentsPruneCommand, type AwsDataApiDatabase, type AwsDataApiDatabaseOptions, type AwsDataApiSeederContext, type BelongsToManyRecord, type BelongsToManyRelationResult, type BelongsToRecord, type BelongsToRelationResult, type BelongsToRequiredRecord, type CastType, type ConfigureAttachmentsOptions, type ConfiguredAttachments, type D1DatabaseHandle, type D1DatabaseOptions, DatabaseApiTokenStore, type DatabaseApiTokenStoreOptions, DatabaseOAuthStateStore, DatabaseSessionStore, type DatabaseSessionStoreOptions, type DeliveryOptions, type DeliveryServeMode, type DiskDeliveryConfig, DrizzleAdapter, type EagerLoadConstraint, type FindManyOptions, GenerateVariantsJob, type GenerateVariantsPayload, type GroupCondition, type HasManyRecord, type HasManyRelationResult, type HasManyThroughRecord, type HasManyThroughRelationResult, type HasOneRecord, type HasOneRelationResult, type HeicPolicy, type HookCallback, type HookName, type ImagePolicy, type ImageProcessor, type InferModelInsert, type InferModelRecord, MassAssignmentException, type MigrationRunSummary, type MigrationStatusEntry, Model, type ModelHooks, ModelNotFoundException, type ModelObserver, type ModelObserverConstructor, type ModelPaginationMeta, type ModelQueryOptions, type MorphManyRecord, type MorphManyRelationResult, type MorphToRecord, type MorphToRelationResult, type MutatorDefinitions, type MutatorFn, type MySqlDatabase, type MySqlDatabaseOptions, type MySqlSeederContext, type ORMAdapter, type ORMAdapterAdvanced, type OrderByClause, type OrderByInput, type OrderDefinition, type OrderDirection, type PaginateOptions, type PaginatedResult, type PlainObject, type PostgresDatabase, type PostgresDatabaseOptions, type PostgresSeederContext, type PruneOptions, type PruneReport, QueryBuilder, type QueryBuilderOptions, type ScopeFunction, type SeederContext, type SeederHandler, type SeederRunSummary, type SimpleCondition, SoftDeletes, type SoftDeletesStatic, type SqliteDatabase, type SqliteDatabaseOptions, type SqliteSeederContext, type TransactionHandle, type TransactionModelScope, type VariantSpec, type WhereClause, type WhereCondition, type WhereGroupCallback, type WhereOperator, type WithRelations, configureAttachments, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, hasManyAttached, hasOneAttached, registerAttachmentRoutes, runSeeders };
874
+ export { ATTACHMENT_OBJECT_PREFIX, type AccessorDefinitions, type AccessorFn, type AttachOptions, Attachable, type AttachableRecordId, type AttachableStatic, type AttachedCollectionOptions, type AttachmentCollectionSpec, type AttachmentData, AttachmentDeliveryController, type AttachmentRecord, type AttachmentSource, type AttachmentUrlOptions, type AttachmentVariantRecord, type AttachmentsDeclaration, AttachmentsPruneCommand, type AwsDataApiDatabase, type AwsDataApiDatabaseOptions, type AwsDataApiSeederContext, type BelongsToManyRecord, type BelongsToManyRelationResult, type BelongsToRecord, type BelongsToRelationResult, type BelongsToRequiredRecord, type CastType, type ConfigureAttachmentsOptions, type ConfiguredAttachments, type D1DatabaseHandle, type D1DatabaseOptions, DEFAULT_DELIVERY_ROUTE_NAME, DatabaseApiTokenStore, type DatabaseApiTokenStoreOptions, DatabaseOAuthStateStore, DatabaseSessionStore, type DatabaseSessionStoreOptions, type DeliveryOptions, type DeliveryServeMode, type DiskDeliveryConfig, DrizzleAdapter, type EagerLoadConstraint, type FindManyOptions, GenerateVariantsJob, type GenerateVariantsPayload, type GroupCondition, type HasManyRecord, type HasManyRelationResult, type HasManyThroughRecord, type HasManyThroughRelationResult, type HasOneRecord, type HasOneRelationResult, type HeicPolicy, type HookCallback, type HookName, type ImagePolicy, type ImageProcessor, type InferModelInsert, type InferModelRecord, MassAssignmentException, type MigrationRunSummary, type MigrationStatusEntry, Model, type ModelHooks, ModelNotFoundException, type ModelObserver, type ModelObserverConstructor, type ModelPaginationMeta, type ModelQueryOptions, type MorphManyRecord, type MorphManyRelationResult, type MorphToRecord, type MorphToRelationResult, type MutatorDefinitions, type MutatorFn, type MySqlDatabase, type MySqlDatabaseOptions, type MySqlSeederContext, type ORMAdapter, type ORMAdapterAdvanced, type OrderByClause, type OrderByInput, type OrderDefinition, type OrderDirection, type PaginateOptions, type PaginatedResult, type PlainObject, type PostgresDatabase, type PostgresDatabaseOptions, type PostgresSeederContext, type PruneOptions, type PruneReport, QueryBuilder, type QueryBuilderOptions, type ScopeFunction, type SeederContext, type SeederHandler, type SeederRunSummary, type SimpleCondition, SoftDeletes, type SoftDeletesStatic, type SqliteDatabase, type SqliteDatabaseOptions, type SqliteSeederContext, type TransactionHandle, type TransactionModelScope, type VariantSpec, type WhereClause, type WhereCondition, type WhereGroupCallback, type WhereOperator, type WithRelations, configureAttachments, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, hasManyAttached, hasOneAttached, registerAttachmentRoutes, runSeeders };
package/dist/index.js CHANGED
@@ -665,6 +665,26 @@ function ulid(now = Date.now()) {
665
665
  for (let i = 0; i < 16; i++) chars += ENCODING[lastRandom[i]];
666
666
  return chars;
667
667
  }
668
+ //#endregion
669
+ //#region src/attachments/engine.ts
670
+ /**
671
+ * The single storage key prefix every attachment object lives under:
672
+ * `attachments/<id>/<name>` for an original, `attachments/<id>/variants/…`
673
+ * for a derivative, and `attachments/` itself for the prune sweep's
674
+ * directory listing.
675
+ *
676
+ * Exported, and re-exported from `@guren/core`, because the layout is not
677
+ * private to this file. `guren check`'s attachments rules judge, from
678
+ * another package, whether uploaded bytes land somewhere the app serves
679
+ * statically — and the ones that reach the objects themselves have to name
680
+ * `<disk root>/attachments` to do it. A restated copy of the prefix over
681
+ * there does not fail loudly when this layout moves (a shard level, a
682
+ * rename): it stops matching, answers "not reachable", and reports an
683
+ * exposed app as safe. A build-failing security rule failing *open*, with
684
+ * nothing going red anywhere. Import this instead of restating it.
685
+ */
686
+ const ATTACHMENT_OBJECT_PREFIX = "attachments";
687
+ const DEFAULT_DELIVERY_ROUTE_NAME = "attachments.show";
668
688
  /**
669
689
  * The inner (presigned) TTL behind a redirect. Fixed rather than derived
670
690
  * from `urlExpiresIn`: the inner credential is minted per request, so it
@@ -769,7 +789,7 @@ var AttachmentEngine = class {
769
789
  const inspection = await this.inspectImage(spec, collection, normalized, queued);
770
790
  const id = ulid();
771
791
  const name = inspection.name;
772
- const path = `attachments/${id}/${name}`;
792
+ const path = `${ATTACHMENT_OBJECT_PREFIX}/${id}/${name}`;
773
793
  const diskName = options.disk ?? this.defaultDisk;
774
794
  const disk = this.storage().disk(diskName);
775
795
  const contentType = inspection.contentType ?? normalized.declaredContentType ?? "application/octet-stream";
@@ -980,7 +1000,8 @@ var AttachmentEngine = class {
980
1000
  }
981
1001
  try {
982
1002
  const result = await this.processor.process(inspection.bytes, variantSpec);
983
- const path = `attachments/${id}/variants/${name}.${VARIANT_EXTENSION[result.format] ?? result.format}`;
1003
+ const extension = VARIANT_EXTENSION[result.format] ?? result.format;
1004
+ const path = `${ATTACHMENT_OBJECT_PREFIX}/${id}/variants/${name}.${extension}`;
984
1005
  await disk.put(path, Buffer.from(result.bytes), { contentType: IMAGE_MIME[result.format] ?? "application/octet-stream" });
985
1006
  variants[name] = {
986
1007
  status: "ready",
@@ -1043,7 +1064,7 @@ var AttachmentEngine = class {
1043
1064
  if (sniffed?.format === "heic" && payload.heic === "convert") {
1044
1065
  const converted = await this.processor.process(bytes, { format: "jpeg" });
1045
1066
  const name = replaceExtension(row.name, "jpg");
1046
- const path = `attachments/${row.id}/${name}`;
1067
+ const path = `${ATTACHMENT_OBJECT_PREFIX}/${row.id}/${name}`;
1047
1068
  await disk.put(path, Buffer.from(converted.bytes), { contentType: "image/jpeg" });
1048
1069
  if (path !== row.path) supersededPath = row.path;
1049
1070
  bytes = converted.bytes;
@@ -1061,7 +1082,7 @@ var AttachmentEngine = class {
1061
1082
  if (variants) updates.variants = variants;
1062
1083
  updates.updatedAt = /* @__PURE__ */ new Date();
1063
1084
  if (!await this.model.where({ id: row.id }).first()) {
1064
- await disk.deleteDirectory(`attachments/${row.id}`);
1085
+ await disk.deleteDirectory(`${ATTACHMENT_OBJECT_PREFIX}/${row.id}`);
1065
1086
  return;
1066
1087
  }
1067
1088
  await this.model.forceUpdate({ id: row.id }, updates);
@@ -1151,7 +1172,7 @@ var AttachmentEngine = class {
1151
1172
  * reverse would leave invisible orphaned objects only a bucket audit finds.
1152
1173
  */
1153
1174
  async purgeRows(rows) {
1154
- for (const row of rows) await this.storage().disk(String(row.disk)).deleteDirectory(`attachments/${String(row.id)}`);
1175
+ for (const row of rows) await this.storage().disk(String(row.disk)).deleteDirectory(`${ATTACHMENT_OBJECT_PREFIX}/${String(row.id)}`);
1155
1176
  const ids = rows.map((row) => String(row.id));
1156
1177
  for (let start = 0; start < ids.length; start += PRUNE_LOOKUP_CHUNK) await this.model.where({ id: ids.slice(start, start + PRUNE_LOOKUP_CHUNK) }).delete();
1157
1178
  }
@@ -1242,7 +1263,7 @@ var AttachmentEngine = class {
1242
1263
  let disk;
1243
1264
  try {
1244
1265
  disk = this.storage().disk(diskName);
1245
- prefixes = await disk.directories("attachments");
1266
+ prefixes = await disk.directories(ATTACHMENT_OBJECT_PREFIX);
1246
1267
  } catch (error) {
1247
1268
  report.skippedDisks.push({
1248
1269
  disk: diskName,
@@ -1873,4 +1894,4 @@ function hasManyAttached(options = {}) {
1873
1894
  return buildSpec("many", options);
1874
1895
  }
1875
1896
  //#endregion
1876
- export { Attachable, AttachmentDeliveryController, AttachmentsPruneCommand, DatabaseApiTokenStore, DatabaseOAuthStateStore, DatabaseSessionStore, DrizzleAdapter, GenerateVariantsJob, MassAssignmentException, Model, ModelNotFoundException, QueryBuilder, SoftDeletes, configureAttachments, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, hasManyAttached, hasOneAttached, registerAttachmentRoutes, runSeeders };
1897
+ export { ATTACHMENT_OBJECT_PREFIX, Attachable, AttachmentDeliveryController, AttachmentsPruneCommand, DEFAULT_DELIVERY_ROUTE_NAME, DatabaseApiTokenStore, DatabaseOAuthStateStore, DatabaseSessionStore, DrizzleAdapter, GenerateVariantsJob, MassAssignmentException, Model, ModelNotFoundException, QueryBuilder, SoftDeletes, configureAttachments, createAwsDataApiDatabase, createD1Database, createMySqlDatabase, createPostgresDatabase, createSqliteDatabase, defineModel, defineSeeder, hasManyAttached, hasOneAttached, registerAttachmentRoutes, runSeeders };
@@ -139,6 +139,38 @@ declare function ssrRuntimePaths(ssrDir: string, ssrFile: string, prefix: string
139
139
  * built-assets directory has to appear under both prefixes.
140
140
  */
141
141
  declare function stageStaticAssets(publicDir: string, assetsOut: string): void;
142
+ /**
143
+ * Extensions a browser renders as a *document* in the serving origin, for a
144
+ * platform that answers for `public/` before the app ever runs.
145
+ *
146
+ * Exactly the set `@guren/server`'s `rendersAsDocument` matches over Hono's
147
+ * mime table — the same two inputs the framework's own static guard reads, so
148
+ * a file that downloads locally downloads on a deploy target too. Written out
149
+ * rather than derived because this module imports nothing from the framework
150
+ * (see the header); `packages/server/tests/http/static-documents.test.ts`
151
+ * recomputes it from that table and fails when the two disagree, so a document
152
+ * type Hono adds cannot pass unnoticed.
153
+ *
154
+ * Two things the list does not reach, both of them the framework's own
155
+ * blind spots rather than new ones. `text/xsl` is a document type
156
+ * `rendersAsDocument` matches, but Hono's table names no extension for it, so
157
+ * `getMimeType` returns nothing for a `.xsl` file and the framework serves it
158
+ * unguarded too — adding it here would make a deploy target stricter than the
159
+ * app it deployed. And extension *case*: `getMimeType` lowercases before its
160
+ * lookup, so the framework guard does fire for `logo.SVG`, and a platform
161
+ * matching a literal pattern does not. Each plugin closes that where its own
162
+ * matcher allows, and the three answers differ — see each one's own comment
163
+ * rather than a list here that goes stale on the next target.
164
+ */
165
+ declare const DOCUMENT_ASSET_EXTENSIONS: readonly ['htm', 'html', 'svg', 'xhtml', 'xml'];
166
+ /**
167
+ * The pair `applyDocumentDisposition` sets, for a platform to set on the same
168
+ * files. Same reasoning as the framework's: `attachment` is honoured for
169
+ * navigations and ignored for subresource loads, so `<img src="/logo.svg">`
170
+ * and a CSS `url()` keep working while the URL opened directly downloads;
171
+ * `nosniff` stops the promotion a browser would otherwise do on its own.
172
+ */
173
+ declare const DOCUMENT_ASSET_HEADERS: Readonly<Record<string, string>>;
142
174
  /** What a dev-only module is needed for, so a plugin can word its own message. */
143
175
  type DevOnlyModuleKind = 'sqlite' | 'vite' | 'mcp' | 'sql-driver';
144
176
  interface DevOnlyModule {
@@ -196,6 +228,76 @@ declare const DEV_ONLY_MODULES: readonly [{
196
228
  readonly kind: 'mcp';
197
229
  readonly exportNames: readonly ["WebStandardStreamableHTTPServerTransport"];
198
230
  }];
231
+ /** One entry of `DEV_ONLY_MODULES`, with its `kind` still narrowed. */
232
+ type DevOnlyModuleEntry = (typeof DEV_ONLY_MODULES)[number];
233
+ /**
234
+ * The specifier `@guren/plugin-mcp` dynamically imports to serve the App MCP
235
+ * endpoint (RFC 0016 §7). Named here rather than inline in three plugins
236
+ * because it is the one entry of `DEV_ONLY_MODULES` whose stubbing is
237
+ * conditional, and each platform has to recognise it.
238
+ */
239
+ declare const MCP_TRANSPORT_SPECIFIER = "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
240
+ /** The package an app declares to opt into the App MCP endpoint. */
241
+ declare const MCP_PLUGIN_PACKAGE = "@guren/plugin-mcp";
242
+ /**
243
+ * Whether the app has opted into the App MCP endpoint (RFC 0016 §7).
244
+ *
245
+ * Resolves the RFC's Open Question 5 — how a build learns that an app wants
246
+ * the MCP transport — as **dependency sniffing**: declaring
247
+ * `@guren/plugin-mcp` in `dependencies` *is* the opt-in. Nothing else is
248
+ * asked of the developer, because there is nothing else to ask: an app that
249
+ * installed the plugin and mounted it wants the endpoint to work, and a build
250
+ * flag it must also remember to pass is a way for the endpoint to be silently
251
+ * compiled shut on a platform. The build does not *enable* anything here — it
252
+ * stops sabotaging what the app already configured.
253
+ *
254
+ * `dependencies` only, never `devDependencies`: a devDependency does not ship,
255
+ * so an app that has one has no MCP endpoint at runtime to protect. Reading
256
+ * both would keep the transport in the bundle of every app that merely
257
+ * develops against the plugin.
258
+ *
259
+ * Absent, unreadable, or malformed manifest answers `false` — no opt-in
260
+ * evidence is not the same as opt-in, and the false direction is the safe
261
+ * one: the transport stays stubbed, which is exactly today's behaviour.
262
+ */
263
+ declare function appUsesMcpPlugin(root: string): boolean;
264
+ /**
265
+ * The dev-only modules that must stay stubbed for this app.
266
+ *
267
+ * The policy layer over `DEV_ONLY_MODULES`, which stays exported and
268
+ * unchanged: it is the full inventory, and other consumers (the wrangler
269
+ * bundle probe, the stub-filename table) read it as such. What varies per app
270
+ * is only whether the *transport* entry is in force.
271
+ *
272
+ * `@guren/plugin-mcp` reaches the App MCP endpoint through exactly one lazy
273
+ * import — `MCP_TRANSPORT_SPECIFIER` — plus static imports of the SDK's
274
+ * `server/index.js` and `types.js`, which no entry here names. Stubbing the
275
+ * transport therefore compiles the endpoint shut on every platform, which is
276
+ * what the three deploy plugins did until RFC 0016 Phase 4a. Dropping the
277
+ * entry for an app that declared the plugin is the whole of the fix.
278
+ *
279
+ * `@modelcontextprotocol/sdk/server/mcp.js` stays stubbed regardless, and the
280
+ * distinction matters: that is the **Dev** MCP's `McpServer`, reached from
281
+ * `@guren/server`'s `McpServiceProvider`, which drives the CLI's code
282
+ * generators against the filesystem. It is compiled shut by the `NODE_ENV`
283
+ * define anyway; the stub is the second guard, and a deployed app has no use
284
+ * for it either way. Same for `@guren/cli` behind it, and for `bun:sqlite`
285
+ * and `vite`, none of which the App MCP endpoint touches.
286
+ *
287
+ * The return type keeps each entry's narrow `kind` so that a platform can
288
+ * index its `Record<kind, message>` table with `module.kind` at all. What
289
+ * makes those tables exhaustive is not this function — each is keyed off
290
+ * `DEV_ONLY_MODULES` directly (on Workers, that list plus
291
+ * `SQL_CLIENT_MODULES`), which is what turns a new kind there into a compile
292
+ * error there. Widening the return to `readonly DevOnlyModule[]` would leave
293
+ * that exhaustiveness untouched and instead break every one of the lookups,
294
+ * since `DevOnlyModuleKind` includes `'sql-driver'` — a kind Lambda's and
295
+ * Vercel's tables deliberately omit, because those two platforms decide the
296
+ * SQL clients per app rather than per platform.
297
+ */
298
+ declare function stubbableDevOnlyModules(options: {
299
+ mcpPlugin: boolean;
300
+ }): readonly DevOnlyModuleEntry[];
199
301
  /**
200
302
  * A database `@guren/orm` can connect through, named after the factory an
201
303
  * app's database config calls to declare it.
@@ -346,6 +448,17 @@ declare function unusedSqlClients(input: {
346
448
  dialects?: readonly DatabaseDialect[];
347
449
  }): readonly UnusedSqlClient[];
348
450
  type DevOnlySpecifier = (typeof DEV_ONLY_MODULES)[number]['specifier'];
451
+ /**
452
+ * Source for a stub replacing one dev-only module. Shared because what it
453
+ * encodes is a bundler constraint, not a platform choice: every name the
454
+ * importer destructures must be present or the bundle fails with "no matching
455
+ * export", and each is emitted as a throwing *function* because the stubbed
456
+ * names mix constructors (`new Database()`) with plain calls
457
+ * (`createServer()`) — a class invoked without `new` reports "Class
458
+ * constructor cannot be invoked without 'new'" instead of the real reason.
459
+ *
460
+ * @param message Platform-specific explanation, including the replacement API.
461
+ */
349
462
  declare function renderDevOnlyStub(module: DevOnlyModule, message: string): string;
350
463
  /**
351
464
  * The MCP SDK is only ever reached through subpaths, and a bundler alias on a
@@ -356,4 +469,4 @@ declare function renderDevOnlyStub(module: DevOnlyModule, message: string): stri
356
469
  */
357
470
  declare const MCP_SDK_SUBPATH_PREFIX = "@modelcontextprotocol/sdk/";
358
471
  //#endregion
359
- export { ClientAssetEnv, DATABASE_CONFIG_CANDIDATES, DATABASE_DIALECTS, DATABASE_FACTORIES, DEV_ONLY_MODULES, DatabaseDialect, DatabaseDialectDetection, DevOnlyModule, DevOnlyModuleKind, DevOnlySpecifier, MCP_SDK_SUBPATH_PREFIX, Manifest, ManifestEntry, PathLike, SQL_CLIENT_MODULES, SqlClientModule, SqlClientSpecifier, UnusedSqlClient, assertOutputDirOutsideRoot, clientManifestJson, detectDatabaseDialects, importSpecifier, parseDatabaseDialects, readManifest, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, ssrRuntimePaths, stageStaticAssets, unusedSqlClients };
472
+ export { ClientAssetEnv, DATABASE_CONFIG_CANDIDATES, DATABASE_DIALECTS, DATABASE_FACTORIES, DEV_ONLY_MODULES, DOCUMENT_ASSET_EXTENSIONS, DOCUMENT_ASSET_HEADERS, DatabaseDialect, DatabaseDialectDetection, DevOnlyModule, DevOnlyModuleEntry, DevOnlyModuleKind, DevOnlySpecifier, MCP_PLUGIN_PACKAGE, MCP_SDK_SUBPATH_PREFIX, MCP_TRANSPORT_SPECIFIER, Manifest, ManifestEntry, PathLike, SQL_CLIENT_MODULES, SqlClientModule, SqlClientSpecifier, UnusedSqlClient, appUsesMcpPlugin, assertOutputDirOutsideRoot, clientManifestJson, detectDatabaseDialects, importSpecifier, parseDatabaseDialects, readManifest, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, ssrRuntimePaths, stageStaticAssets, stubbableDevOnlyModules, unusedSqlClients };
@@ -282,6 +282,47 @@ function stageStaticAssets(publicDir, assetsOut) {
282
282
  if (existsSync(clientAssetsDir)) cpSync(clientAssetsDir, resolve(assetsOut, "public/assets"), { recursive: true });
283
283
  }
284
284
  /**
285
+ * Extensions a browser renders as a *document* in the serving origin, for a
286
+ * platform that answers for `public/` before the app ever runs.
287
+ *
288
+ * Exactly the set `@guren/server`'s `rendersAsDocument` matches over Hono's
289
+ * mime table — the same two inputs the framework's own static guard reads, so
290
+ * a file that downloads locally downloads on a deploy target too. Written out
291
+ * rather than derived because this module imports nothing from the framework
292
+ * (see the header); `packages/server/tests/http/static-documents.test.ts`
293
+ * recomputes it from that table and fails when the two disagree, so a document
294
+ * type Hono adds cannot pass unnoticed.
295
+ *
296
+ * Two things the list does not reach, both of them the framework's own
297
+ * blind spots rather than new ones. `text/xsl` is a document type
298
+ * `rendersAsDocument` matches, but Hono's table names no extension for it, so
299
+ * `getMimeType` returns nothing for a `.xsl` file and the framework serves it
300
+ * unguarded too — adding it here would make a deploy target stricter than the
301
+ * app it deployed. And extension *case*: `getMimeType` lowercases before its
302
+ * lookup, so the framework guard does fire for `logo.SVG`, and a platform
303
+ * matching a literal pattern does not. Each plugin closes that where its own
304
+ * matcher allows, and the three answers differ — see each one's own comment
305
+ * rather than a list here that goes stale on the next target.
306
+ */
307
+ const DOCUMENT_ASSET_EXTENSIONS = [
308
+ "htm",
309
+ "html",
310
+ "svg",
311
+ "xhtml",
312
+ "xml"
313
+ ];
314
+ /**
315
+ * The pair `applyDocumentDisposition` sets, for a platform to set on the same
316
+ * files. Same reasoning as the framework's: `attachment` is honoured for
317
+ * navigations and ignored for subresource loads, so `<img src="/logo.svg">`
318
+ * and a CSS `url()` keep working while the URL opened directly downloads;
319
+ * `nosniff` stops the promotion a browser would otherwise do on its own.
320
+ */
321
+ const DOCUMENT_ASSET_HEADERS = {
322
+ "Content-Disposition": "attachment",
323
+ "X-Content-Type-Options": "nosniff"
324
+ };
325
+ /**
285
326
  * Modules that cannot run off Bun but sit in the graph of any app importing
286
327
  * `@guren/core`, reached only through dev-time branches. Core aggregates
287
328
  * `@guren/server` and `@guren/orm`, where these imports actually live, so it
@@ -332,6 +373,82 @@ const DEV_ONLY_MODULES = [
332
373
  }
333
374
  ];
334
375
  /**
376
+ * The specifier `@guren/plugin-mcp` dynamically imports to serve the App MCP
377
+ * endpoint (RFC 0016 §7). Named here rather than inline in three plugins
378
+ * because it is the one entry of `DEV_ONLY_MODULES` whose stubbing is
379
+ * conditional, and each platform has to recognise it.
380
+ */
381
+ const MCP_TRANSPORT_SPECIFIER = "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
382
+ /** The package an app declares to opt into the App MCP endpoint. */
383
+ const MCP_PLUGIN_PACKAGE = "@guren/plugin-mcp";
384
+ /**
385
+ * Whether the app has opted into the App MCP endpoint (RFC 0016 §7).
386
+ *
387
+ * Resolves the RFC's Open Question 5 — how a build learns that an app wants
388
+ * the MCP transport — as **dependency sniffing**: declaring
389
+ * `@guren/plugin-mcp` in `dependencies` *is* the opt-in. Nothing else is
390
+ * asked of the developer, because there is nothing else to ask: an app that
391
+ * installed the plugin and mounted it wants the endpoint to work, and a build
392
+ * flag it must also remember to pass is a way for the endpoint to be silently
393
+ * compiled shut on a platform. The build does not *enable* anything here — it
394
+ * stops sabotaging what the app already configured.
395
+ *
396
+ * `dependencies` only, never `devDependencies`: a devDependency does not ship,
397
+ * so an app that has one has no MCP endpoint at runtime to protect. Reading
398
+ * both would keep the transport in the bundle of every app that merely
399
+ * develops against the plugin.
400
+ *
401
+ * Absent, unreadable, or malformed manifest answers `false` — no opt-in
402
+ * evidence is not the same as opt-in, and the false direction is the safe
403
+ * one: the transport stays stubbed, which is exactly today's behaviour.
404
+ */
405
+ function appUsesMcpPlugin(root) {
406
+ try {
407
+ const dependencies = JSON.parse(readFileSync(resolve(root, "package.json"), "utf8")).dependencies;
408
+ return typeof dependencies === "object" && dependencies !== null && "@guren/plugin-mcp" in dependencies;
409
+ } catch {
410
+ return false;
411
+ }
412
+ }
413
+ /**
414
+ * The dev-only modules that must stay stubbed for this app.
415
+ *
416
+ * The policy layer over `DEV_ONLY_MODULES`, which stays exported and
417
+ * unchanged: it is the full inventory, and other consumers (the wrangler
418
+ * bundle probe, the stub-filename table) read it as such. What varies per app
419
+ * is only whether the *transport* entry is in force.
420
+ *
421
+ * `@guren/plugin-mcp` reaches the App MCP endpoint through exactly one lazy
422
+ * import — `MCP_TRANSPORT_SPECIFIER` — plus static imports of the SDK's
423
+ * `server/index.js` and `types.js`, which no entry here names. Stubbing the
424
+ * transport therefore compiles the endpoint shut on every platform, which is
425
+ * what the three deploy plugins did until RFC 0016 Phase 4a. Dropping the
426
+ * entry for an app that declared the plugin is the whole of the fix.
427
+ *
428
+ * `@modelcontextprotocol/sdk/server/mcp.js` stays stubbed regardless, and the
429
+ * distinction matters: that is the **Dev** MCP's `McpServer`, reached from
430
+ * `@guren/server`'s `McpServiceProvider`, which drives the CLI's code
431
+ * generators against the filesystem. It is compiled shut by the `NODE_ENV`
432
+ * define anyway; the stub is the second guard, and a deployed app has no use
433
+ * for it either way. Same for `@guren/cli` behind it, and for `bun:sqlite`
434
+ * and `vite`, none of which the App MCP endpoint touches.
435
+ *
436
+ * The return type keeps each entry's narrow `kind` so that a platform can
437
+ * index its `Record<kind, message>` table with `module.kind` at all. What
438
+ * makes those tables exhaustive is not this function — each is keyed off
439
+ * `DEV_ONLY_MODULES` directly (on Workers, that list plus
440
+ * `SQL_CLIENT_MODULES`), which is what turns a new kind there into a compile
441
+ * error there. Widening the return to `readonly DevOnlyModule[]` would leave
442
+ * that exhaustiveness untouched and instead break every one of the lookups,
443
+ * since `DevOnlyModuleKind` includes `'sql-driver'` — a kind Lambda's and
444
+ * Vercel's tables deliberately omit, because those two platforms decide the
445
+ * SQL clients per app rather than per platform.
446
+ */
447
+ function stubbableDevOnlyModules(options) {
448
+ if (!options.mcpPlugin) return DEV_ONLY_MODULES;
449
+ return DEV_ONLY_MODULES.filter((module) => module.specifier !== MCP_TRANSPORT_SPECIFIER);
450
+ }
451
+ /**
335
452
  * The `@guren/orm` factory names an app's database config calls, and the
336
453
  * dialect each one declares.
337
454
  *
@@ -520,17 +637,6 @@ function unusedSqlClients(input) {
520
637
  }));
521
638
  }
522
639
  /**
523
- * Source for a stub replacing one dev-only module. Shared because what it
524
- * encodes is a bundler constraint, not a platform choice: every name the
525
- * importer destructures must be present or the bundle fails with "no matching
526
- * export", and each is emitted as a throwing *function* because the stubbed
527
- * names mix constructors (`new Database()`) with plain calls
528
- * (`createServer()`) — a class invoked without `new` reports "Class
529
- * constructor cannot be invoked without 'new'" instead of the real reason.
530
- *
531
- * @param message Platform-specific explanation, including the replacement API.
532
- */
533
- /**
534
640
  * A JavaScript string literal for `value`.
535
641
  *
536
642
  * `JSON.stringify` alone is not one: JSON and JavaScript disagree about
@@ -541,6 +647,17 @@ function unusedSqlClients(input) {
541
647
  function toJsStringLiteral(value) {
542
648
  return JSON.stringify(value).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
543
649
  }
650
+ /**
651
+ * Source for a stub replacing one dev-only module. Shared because what it
652
+ * encodes is a bundler constraint, not a platform choice: every name the
653
+ * importer destructures must be present or the bundle fails with "no matching
654
+ * export", and each is emitted as a throwing *function* because the stubbed
655
+ * names mix constructors (`new Database()`) with plain calls
656
+ * (`createServer()`) — a class invoked without `new` reports "Class
657
+ * constructor cannot be invoked without 'new'" instead of the real reason.
658
+ *
659
+ * @param message Platform-specific explanation, including the replacement API.
660
+ */
544
661
  function renderDevOnlyStub(module, message) {
545
662
  const comment = message.replace(/[\r\n\u2028\u2029]+/g, " ");
546
663
  const error = `throw new Error(${toJsStringLiteral(message)})`;
@@ -557,4 +674,4 @@ function renderDevOnlyStub(module, message) {
557
674
  */
558
675
  const MCP_SDK_SUBPATH_PREFIX = "@modelcontextprotocol/sdk/";
559
676
  //#endregion
560
- export { DATABASE_CONFIG_CANDIDATES, DATABASE_DIALECTS, DATABASE_FACTORIES, DEV_ONLY_MODULES, MCP_SDK_SUBPATH_PREFIX, SQL_CLIENT_MODULES, assertOutputDirOutsideRoot, clientManifestJson, detectDatabaseDialects, importSpecifier, parseDatabaseDialects, readManifest, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, ssrRuntimePaths, stageStaticAssets, unusedSqlClients };
677
+ export { DATABASE_CONFIG_CANDIDATES, DATABASE_DIALECTS, DATABASE_FACTORIES, DEV_ONLY_MODULES, DOCUMENT_ASSET_EXTENSIONS, DOCUMENT_ASSET_HEADERS, MCP_PLUGIN_PACKAGE, MCP_SDK_SUBPATH_PREFIX, MCP_TRANSPORT_SPECIFIER, SQL_CLIENT_MODULES, appUsesMcpPlugin, assertOutputDirOutsideRoot, clientManifestJson, detectDatabaseDialects, importSpecifier, parseDatabaseDialects, readManifest, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, ssrRuntimePaths, stageStaticAssets, stubbableDevOnlyModules, unusedSqlClients };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/core",
3
- "version": "1.12.0",
3
+ "version": "1.13.0",
4
4
  "type": "module",
5
5
  "sideEffects": [
6
6
  "./src/bin.ts",
@@ -45,6 +45,10 @@
45
45
  "types": "./dist/redis.d.ts",
46
46
  "default": "./dist/redis.js"
47
47
  },
48
+ "./agent": {
49
+ "types": "./dist/agent.d.ts",
50
+ "default": "./dist/agent.js"
51
+ },
48
52
  "./internal/deploy-build": {
49
53
  "types": "./dist/internal/deploy-build.d.ts",
50
54
  "default": "./dist/internal/deploy-build.js"
@@ -80,9 +84,9 @@
80
84
  "typecheck": "tsc --noEmit"
81
85
  },
82
86
  "dependencies": {
83
- "@guren/cli": "^2.13.0",
84
- "@guren/orm": "^2.6.1",
85
- "@guren/server": "^2.14.0"
87
+ "@guren/cli": "^2.14.0",
88
+ "@guren/orm": "^2.6.2",
89
+ "@guren/server": "^2.15.0"
86
90
  },
87
91
  "devDependencies": {
88
92
  "@types/node": "^20.14.10",