@happyvertical/smrt-core 0.40.56 → 0.40.58
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/generators/rest.d.ts +39 -0
- package/dist/generators/rest.d.ts.map +1 -1
- package/dist/generators/rest.js +115 -0
- package/dist/generators/rest.js.map +1 -1
- package/dist/manifest/static-manifest.js +1 -1
- package/dist/manifest/static-manifest.js.map +1 -1
- package/dist/manifest/store.js +1 -1
- package/dist/manifest/test-manifest-stub.d.ts.map +1 -1
- package/dist/manifest/test-manifest-stub.js +172 -1
- package/dist/manifest/test-manifest-stub.js.map +1 -1
- package/dist/manifest.json +1 -1
- package/dist/smrt-knowledge.json +3 -3
- package/package.json +10 -10
|
@@ -137,6 +137,45 @@ export declare class APIGenerator {
|
|
|
137
137
|
private isRoutePublic;
|
|
138
138
|
private isApiActionEnabled;
|
|
139
139
|
private getCollectionObjectName;
|
|
140
|
+
/**
|
|
141
|
+
* Dispatch a decorator-declared custom COLLECTION-scoped action —
|
|
142
|
+
* `@smrt({ api: { include: [...], routes: { action: { scope: 'collection',
|
|
143
|
+
* method, path } } } })` — on the runtime transport (#2047). The generated
|
|
144
|
+
* SvelteKit transport already dispatches these routes; this keeps the two
|
|
145
|
+
* transports coherent for the same decorator metadata.
|
|
146
|
+
*
|
|
147
|
+
* Deliberately narrow, matching this router's URL shape: single-segment
|
|
148
|
+
* collection-scoped paths only (multi-segment custom paths remain a
|
|
149
|
+
* SvelteKit-transport feature), the action must be exposed by `api.include`
|
|
150
|
+
* (and not excluded), and the HTTP method must match the route metadata.
|
|
151
|
+
* Non-matching requests fall through to CRUD handling unchanged.
|
|
152
|
+
*
|
|
153
|
+
* Scope is resolved through the shared `resolveCustomActionMetadata`
|
|
154
|
+
* contract, not read off the route alone: `scope` is OPTIONAL and defaults
|
|
155
|
+
* to `collection` for statics and `item` for instance methods, so requiring
|
|
156
|
+
* a literal `scope: 'collection'` would skip a valid static action and let
|
|
157
|
+
* `POST /<collection>/<action>` fall through into `create`. The receiver
|
|
158
|
+
* decides — a route-only scope cannot manufacture one — so an action with no
|
|
159
|
+
* collection-hosted receiver falls through unless the route explicitly
|
|
160
|
+
* declared `scope: 'collection'`, in which case it is declared-but-missing
|
|
161
|
+
* and returns 501 rather than degrading into a malformed CRUD write.
|
|
162
|
+
*
|
|
163
|
+
* Arguments, failures, and result shaping all reuse the shared custom-action
|
|
164
|
+
* helpers so this transport matches generated REST/CLI/MCP exactly: declared
|
|
165
|
+
* parameters are projected (a zero-parameter action takes no body at all, an
|
|
166
|
+
* `options` bag is passed through, named parameters are read off the body),
|
|
167
|
+
* a returned `{ ok: false, ... }` failure becomes its requested non-2xx
|
|
168
|
+
* status with a redacted payload, and success wraps as `{ action, result }`.
|
|
169
|
+
*/
|
|
170
|
+
private dispatchCustomCollectionAction;
|
|
171
|
+
/**
|
|
172
|
+
* Public-safe projection for custom-action results, mirroring the generated
|
|
173
|
+
* SvelteKit routes' `toPublicResult`: a `SmrtObject` (anything exposing
|
|
174
|
+
* `toPublicJSON`) becomes its public projection with the caller's
|
|
175
|
+
* permissions, arrays and plain objects are walked, non-plain instances and
|
|
176
|
+
* primitives pass through, and a cycle guard breaks reference loops.
|
|
177
|
+
*/
|
|
178
|
+
private sanitizeActionResult;
|
|
140
179
|
/**
|
|
141
180
|
* Fail-closed tenant read scope (#1782).
|
|
142
181
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rest.d.ts","sourceRoot":"","sources":["../../src/generators/rest.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,IAAI,MAAM,WAAW,CAAC;AAE7B,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAKpD,OAAO,KAAK,EAAqB,UAAU,EAAE,MAAM,WAAW,CAAC;AAE/D,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"rest.d.ts","sourceRoot":"","sources":["../../src/generators/rest.ts"],"names":[],"mappings":"AA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gBAAqB,GAC5B;IAAE,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CActC;AAED;;GAEG;AACH,wBAAgB,eAAe,CAC7B,OAAO,EAAE,CAAC,OAAO,UAAU,CAAC,EAAE,EAC9B,OAAO,GAAE,UAAe,EACxB,MAAM,GAAE,gBAAqB,GAC5B,OAAO,CAAC,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,CAwB9B"}
|
package/dist/generators/rest.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { isTenantScopedClassResolved, resolveDispatchTenantScope } from "../dispatch/tenant-resolver.js";
|
|
2
2
|
import { getTableVersion } from "../change-feed.js";
|
|
3
|
+
import { buildCustomActionInvocationArgs, normalizeCustomActionFailure, resolveCustomActionMetadata } from "./custom-action.js";
|
|
3
4
|
import { ObjectRegistry } from "../registry.js";
|
|
4
5
|
import "../dispatch/index.js";
|
|
5
6
|
import { canonicalReadRepresentation, computeTableVersionEtag, conditionalJsonResponse, ifNoneMatchHasConcreteMatch, ifNoneMatchSatisfied, resolveReadCacheControl, resolveTenantEtagDiscriminator, versionConditionalResponse, warnIfSharedCacheNeutralized, warnIfTenantScopedPublicRead } from "./conditional-get.js";
|
|
@@ -286,6 +287,10 @@ var APIGenerator = class {
|
|
|
286
287
|
*/
|
|
287
288
|
async executeCrudOperation(req, collection, objectId, url, objectName) {
|
|
288
289
|
try {
|
|
290
|
+
if (objectId && objectName) {
|
|
291
|
+
const customResponse = await this.dispatchCustomCollectionAction(req, collection, objectId, url, objectName);
|
|
292
|
+
if (customResponse) return customResponse;
|
|
293
|
+
}
|
|
289
294
|
const action = this.getCrudAction(req.method, objectId);
|
|
290
295
|
if (action && !this.isApiActionEnabled(objectName, action)) return this.createErrorResponse(405, "Method not allowed");
|
|
291
296
|
if (objectId === "count" && req.method === "GET") return await this.handleCount(collection, url.searchParams, objectName);
|
|
@@ -349,6 +354,116 @@ var APIGenerator = class {
|
|
|
349
354
|
return registered?.qualifiedName || registered?.name || itemClass.name;
|
|
350
355
|
}
|
|
351
356
|
/**
|
|
357
|
+
* Dispatch a decorator-declared custom COLLECTION-scoped action —
|
|
358
|
+
* `@smrt({ api: { include: [...], routes: { action: { scope: 'collection',
|
|
359
|
+
* method, path } } } })` — on the runtime transport (#2047). The generated
|
|
360
|
+
* SvelteKit transport already dispatches these routes; this keeps the two
|
|
361
|
+
* transports coherent for the same decorator metadata.
|
|
362
|
+
*
|
|
363
|
+
* Deliberately narrow, matching this router's URL shape: single-segment
|
|
364
|
+
* collection-scoped paths only (multi-segment custom paths remain a
|
|
365
|
+
* SvelteKit-transport feature), the action must be exposed by `api.include`
|
|
366
|
+
* (and not excluded), and the HTTP method must match the route metadata.
|
|
367
|
+
* Non-matching requests fall through to CRUD handling unchanged.
|
|
368
|
+
*
|
|
369
|
+
* Scope is resolved through the shared `resolveCustomActionMetadata`
|
|
370
|
+
* contract, not read off the route alone: `scope` is OPTIONAL and defaults
|
|
371
|
+
* to `collection` for statics and `item` for instance methods, so requiring
|
|
372
|
+
* a literal `scope: 'collection'` would skip a valid static action and let
|
|
373
|
+
* `POST /<collection>/<action>` fall through into `create`. The receiver
|
|
374
|
+
* decides — a route-only scope cannot manufacture one — so an action with no
|
|
375
|
+
* collection-hosted receiver falls through unless the route explicitly
|
|
376
|
+
* declared `scope: 'collection'`, in which case it is declared-but-missing
|
|
377
|
+
* and returns 501 rather than degrading into a malformed CRUD write.
|
|
378
|
+
*
|
|
379
|
+
* Arguments, failures, and result shaping all reuse the shared custom-action
|
|
380
|
+
* helpers so this transport matches generated REST/CLI/MCP exactly: declared
|
|
381
|
+
* parameters are projected (a zero-parameter action takes no body at all, an
|
|
382
|
+
* `options` bag is passed through, named parameters are read off the body),
|
|
383
|
+
* a returned `{ ok: false, ... }` failure becomes its requested non-2xx
|
|
384
|
+
* status with a redacted payload, and success wraps as `{ action, result }`.
|
|
385
|
+
*/
|
|
386
|
+
async dispatchCustomCollectionAction(req, collection, pathSegment, url, objectName) {
|
|
387
|
+
const apiConfig = ObjectRegistry.getConfig(objectName)?.api;
|
|
388
|
+
if (!apiConfig || typeof apiConfig !== "object" || !apiConfig.routes) return null;
|
|
389
|
+
for (const [actionName, routeConfig] of Object.entries(apiConfig.routes)) {
|
|
390
|
+
const routePath = routeConfig?.path || actionName;
|
|
391
|
+
if (routePath.includes("/") || routePath !== pathSegment) continue;
|
|
392
|
+
const routeMethod = (routeConfig?.method || "POST").toUpperCase();
|
|
393
|
+
if (routeMethod !== req.method.toUpperCase()) continue;
|
|
394
|
+
if (apiConfig.include && !apiConfig.include.includes(actionName)) continue;
|
|
395
|
+
if (apiConfig.exclude?.includes(actionName)) continue;
|
|
396
|
+
const collectionMethod = collection[actionName];
|
|
397
|
+
const itemConstructor = ObjectRegistry.getClass(objectName)?.constructor;
|
|
398
|
+
const staticMethod = itemConstructor?.[actionName];
|
|
399
|
+
const isCollectionHosted = typeof collectionMethod === "function";
|
|
400
|
+
if (!isCollectionHosted && !(!isCollectionHosted && typeof staticMethod === "function")) {
|
|
401
|
+
if (routeConfig?.scope === "collection") return this.createErrorResponse(501, `Custom action '${actionName}' is declared but not implemented`);
|
|
402
|
+
continue;
|
|
403
|
+
}
|
|
404
|
+
const metadata = resolveCustomActionMetadata({
|
|
405
|
+
actionName,
|
|
406
|
+
apiConfig,
|
|
407
|
+
method: ObjectRegistry.getMethods(objectName)?.get(actionName),
|
|
408
|
+
defaultScope: "collection"
|
|
409
|
+
});
|
|
410
|
+
if (metadata.scope !== "collection") continue;
|
|
411
|
+
const invoke = isCollectionHosted ? (args) => collectionMethod.apply(collection, args) : (args) => staticMethod.apply(itemConstructor, args);
|
|
412
|
+
let options;
|
|
413
|
+
if (routeMethod === "GET") options = Object.fromEntries(url.searchParams.entries());
|
|
414
|
+
else {
|
|
415
|
+
let rawBody = "";
|
|
416
|
+
try {
|
|
417
|
+
rawBody = await req.text();
|
|
418
|
+
} catch {
|
|
419
|
+
rawBody = "";
|
|
420
|
+
}
|
|
421
|
+
if (rawBody.trim() !== "") try {
|
|
422
|
+
options = JSON.parse(rawBody);
|
|
423
|
+
} catch {
|
|
424
|
+
return this.createErrorResponse(400, "Invalid JSON body");
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
const result = await invoke(metadata.parameters ? buildCustomActionInvocationArgs(metadata, {
|
|
428
|
+
...options && typeof options === "object" && !Array.isArray(options) ? options : {},
|
|
429
|
+
options
|
|
430
|
+
}) : [options]);
|
|
431
|
+
const failure = normalizeCustomActionFailure(result);
|
|
432
|
+
if (failure) return this.createJsonResponse({ error: failure }, failure.status);
|
|
433
|
+
return this.createJsonResponse({
|
|
434
|
+
action: actionName,
|
|
435
|
+
result: this.sanitizeActionResult(result)
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
return null;
|
|
439
|
+
}
|
|
440
|
+
/**
|
|
441
|
+
* Public-safe projection for custom-action results, mirroring the generated
|
|
442
|
+
* SvelteKit routes' `toPublicResult`: a `SmrtObject` (anything exposing
|
|
443
|
+
* `toPublicJSON`) becomes its public projection with the caller's
|
|
444
|
+
* permissions, arrays and plain objects are walked, non-plain instances and
|
|
445
|
+
* primitives pass through, and a cycle guard breaks reference loops.
|
|
446
|
+
*/
|
|
447
|
+
sanitizeActionResult(value, seen = /* @__PURE__ */ new WeakSet()) {
|
|
448
|
+
if (value === null || typeof value !== "object") return value;
|
|
449
|
+
if (seen.has(value)) return null;
|
|
450
|
+
const serializable = value;
|
|
451
|
+
if (typeof serializable.toPublicJSON === "function") {
|
|
452
|
+
seen.add(value);
|
|
453
|
+
return this.sanitizeActionResult(serializable.toPublicJSON(this.getPublicJsonOptions()), seen);
|
|
454
|
+
}
|
|
455
|
+
if (Array.isArray(value)) {
|
|
456
|
+
seen.add(value);
|
|
457
|
+
return value.map((entry) => this.sanitizeActionResult(entry, seen));
|
|
458
|
+
}
|
|
459
|
+
const proto = Object.getPrototypeOf(value);
|
|
460
|
+
if (proto !== Object.prototype && proto !== null) return value;
|
|
461
|
+
seen.add(value);
|
|
462
|
+
const out = {};
|
|
463
|
+
for (const [key, entry] of Object.entries(value)) out[key] = this.sanitizeActionResult(entry, seen);
|
|
464
|
+
return out;
|
|
465
|
+
}
|
|
466
|
+
/**
|
|
352
467
|
* Fail-closed tenant read scope (#1782).
|
|
353
468
|
*
|
|
354
469
|
* A `@TenantScoped` model served over a public/anonymous read has no ambient
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rest.js","names":[],"sources":["../../src/generators/rest.ts"],"sourcesContent":["/**\n * High-performance REST API generator for smrt objects using Node.js HTTP server\n *\n * Designed for minimal bundle size and maximum performance\n */\n\nimport http from 'node:http';\nimport { getTableVersion } from '../change-feed';\nimport type { SmrtCollection } from '../collection';\nimport {\n isTenantScopedClassResolved,\n resolveDispatchTenantScope,\n} from '../dispatch';\nimport type { PublicJsonOptions, SmrtObject } from '../object';\nimport { ObjectRegistry } from '../registry';\nimport type {\n RegisteredClass,\n RegisteredField,\n SmrtObjectConstructor,\n} from '../registry/types';\nimport type {\n FieldDefinition,\n MethodDefinition,\n SmartObjectDefinition,\n SmartObjectManifest,\n} from '../scanner/types';\nimport {\n processSyncApplyBatch,\n SYNC_APPLY_ROUTE_SEGMENTS,\n type SyncApplyOp,\n type SyncApplyTarget,\n} from '../sync/apply';\nimport { computeWebManifestHash } from '../vite-plugin/web-collections';\nimport { handleChangesRoute } from './changes-route';\nimport {\n canonicalReadRepresentation,\n computeTableVersionEtag,\n conditionalJsonResponse,\n ifNoneMatchHasConcreteMatch,\n ifNoneMatchSatisfied,\n resolveReadCacheControl,\n resolveTenantEtagDiscriminator,\n versionConditionalResponse,\n warnIfSharedCacheNeutralized,\n warnIfTenantScopedPublicRead,\n} from './conditional-get';\nimport { handleEventsRoute } from './events-route';\n\nexport interface APIConfig {\n basePath?: string;\n enableCors?: boolean;\n /**\n * Explicit CORS origin allowlist (#1540). Required when `enableCors` is true —\n * the generator never emits `Access-Control-Allow-Origin: *`. A request's\n * `Origin` is echoed only when it appears here.\n */\n allowedOrigins?: string[];\n /**\n * Opt into credentialed CORS (#1861). When true, CORS responses to an\n * allow-listed origin also carry `Access-Control-Allow-Credentials: true`, so\n * a cross-origin browser client may send cookies (the only auth an\n * `EventSource` can carry — it cannot set an `Authorization` header). Requires\n * `enableCors` + a non-empty `allowedOrigins`: credentials are NEVER paired\n * with a wildcard origin, and the origin is still echoed only when it is\n * explicitly allow-listed. Fail-closed default (`false`): same-origin only,\n * even when CORS is otherwise enabled, so a plain `enableCors` never silently\n * starts flowing cookies cross-origin.\n */\n allowCredentials?: boolean;\n customRoutes?: Record<string, (req: Request) => Promise<Response>>;\n authMiddleware?: (\n objectName: string,\n action: string,\n ) => (req: Request) => Promise<Request | Response>;\n port?: number;\n hostname?: string;\n /**\n * Live `_events` route options. `maxSubscribers` caps active SSE streams per\n * process (#1860); over-cap connections receive a retryable 503. Set to 0\n * for no cap.\n */\n eventsRoute?: {\n maxSubscribers?: number;\n };\n /**\n * The build's web-collection SHAPE digest (#1764) — the same value the\n * generated `@happyvertical/smrt-virt-web` module exports. When supplied it is\n * folded into every read ETag via {@link computeTableVersionEtag}, so a\n * shape-only deploy (no table write) busts every read validator, closing\n * the documented v2 staleness gap. When omitted, APIGenerator computes the\n * same digest from the runtime registry on first read (#1862). The generated\n * SvelteKit routes bake the same constant in directly rather than going\n * through this runtime server.\n */\n manifestHash?: string;\n}\n\nexport interface APIContext {\n db?: unknown;\n ai?: unknown;\n user?: {\n id: string;\n username?: string;\n roles?: string[];\n };\n /** Resolved permission slugs held by the caller. */\n permissions?: Iterable<string>;\n}\n\nfunction registeredFieldsToManifest(\n fields: Map<string, RegisteredField>,\n): Record<string, FieldDefinition> {\n const result: Record<string, FieldDefinition> = {};\n for (const [name, field] of fields) {\n if (!field || typeof field.type !== 'string') continue;\n const defaultValue =\n field.default !== undefined ? field.default : field._meta?.default;\n result[name] = {\n type: field.type as FieldDefinition['type'],\n ...(field.required !== undefined ? { required: field.required } : {}),\n ...(defaultValue !== undefined ? { default: defaultValue } : {}),\n ...(field.related !== undefined ? { related: field.related } : {}),\n ...(field.transient !== undefined ? { transient: field.transient } : {}),\n ...(field.sensitive !== undefined ? { sensitive: field.sensitive } : {}),\n ...(field.readonly !== undefined ? { readonly: field.readonly } : {}),\n ...(field.readPermission !== undefined\n ? { readPermission: field.readPermission }\n : {}),\n ...(field._meta !== undefined ? { _meta: field._meta } : {}),\n };\n }\n return result;\n}\n\nfunction registeredMethodsToManifest(\n methods: Map<string, MethodDefinition> | undefined,\n): Record<string, MethodDefinition> {\n return Object.fromEntries(methods ?? []);\n}\n\nfunction pluralizeRuntimeCollectionName(className: string): string {\n const lower = className.toLowerCase();\n if (lower.endsWith('y')) return `${lower.slice(0, -1)}ies`;\n if (lower.endsWith('s') || lower.endsWith('x') || lower.endsWith('z')) {\n return `${lower}es`;\n }\n if (lower.endsWith('ch') || lower.endsWith('sh')) return `${lower}es`;\n return `${lower}s`;\n}\n\nfunction runtimeObjectDefinition(\n key: string,\n info: RegisteredClass,\n): SmartObjectDefinition {\n const className = info.name || key;\n return {\n className,\n name: className.toLowerCase(),\n collection: info.collection || pluralizeRuntimeCollectionName(className),\n filePath: info.sourceFilePath || '',\n fields: registeredFieldsToManifest(info.inheritedFields || info.fields),\n methods: registeredMethodsToManifest(info.inheritedMethods || info.methods),\n decoratorConfig: info.config || {},\n ...(info.qualifiedName ? { qualifiedName: info.qualifiedName } : {}),\n ...(info.packageName ? { packageName: info.packageName } : {}),\n ...(info.visibility ? { visibility: info.visibility } : {}),\n ...(info.extends ? { extends: info.extends } : {}),\n ...(info.extendsTypeArg ? { extendsTypeArg: info.extendsTypeArg } : {}),\n ...(info.tools ? { tools: info.tools } : {}),\n };\n}\n\n/**\n * Compute the runtime REST web-manifest hash from the registered object graph\n * (#1862). This mirrors the Vite/SvelteKit source (`computeWebManifestHash`)\n * but builds the manifest from `ObjectRegistry` for APIGenerator deployments.\n */\nexport function computeRuntimeWebManifestHash(\n classes: Iterable<[string, RegisteredClass]> = ObjectRegistry.getAllClasses(),\n): string {\n const objects: SmartObjectManifest['objects'] = {};\n const seen = new Set<RegisteredClass>();\n for (const [key, info] of classes) {\n if (seen.has(info)) continue;\n seen.add(info);\n const manifestKey = info.qualifiedName || key;\n objects[manifestKey] = runtimeObjectDefinition(key, info);\n }\n return computeWebManifestHash({\n version: 'runtime',\n timestamp: 0,\n objects,\n });\n}\n\n/**\n * High-performance API generator using native Bun\n */\nexport class APIGenerator {\n private config: APIConfig;\n private collections = new Map<string, SmrtCollection<SmrtObject>>();\n private context: APIContext;\n private runtimeManifestHash: string | undefined;\n\n constructor(config: APIConfig = {}, context: APIContext = {}) {\n this.config = {\n basePath: '/api/v1',\n // Security defaults (#1540): bind to loopback and keep CORS off unless an\n // explicit origin allowlist is supplied. No `Access-Control-Allow-Origin: *`.\n enableCors: false,\n port: 3000,\n hostname: '127.0.0.1',\n ...config,\n };\n this.context = context;\n }\n\n /**\n * Register a pre-configured collection instance for API exposure\n *\n * @param name - URL path segment for the collection (e.g., 'products' for /api/products)\n * @param collection - Pre-initialized SmrtCollection instance\n */\n registerCollection(\n name: string,\n collection: SmrtCollection<SmrtObject>,\n ): void {\n this.collections.set(name, collection);\n this.runtimeManifestHash = undefined;\n }\n\n /**\n * Resolve the database for generator-level routes that are not object-scoped\n * (currently the `_changes` feed, #1758).\n *\n * Prefers the explicit `APIContext.db`, but falls back to the first\n * registered collection's live handle so the feed works under the documented\n * `registerCollection()` wiring, where callers configure collections with a\n * database but never populate `APIContext.db`. Without the fallback the feed\n * would 503 even though the database is reachable.\n */\n private resolveContextDb(): unknown {\n return (\n this.context.db ?? this.collections.values().next().value?.db ?? undefined\n );\n }\n\n /**\n * Create Node.js HTTP server with all routes\n */\n createServer(): { server: http.Server; url: string } {\n const server = http.createServer(async (req, res) => {\n try {\n const request = await this.nodeRequestToWebRequest(req);\n const response = await this.handleRequest(request);\n await this.webResponseToNodeResponse(response, res);\n } catch (_error) {\n res.statusCode = 500;\n res.end('Internal Server Error');\n }\n });\n\n server.listen(this.config.port, this.config.hostname);\n\n return {\n server,\n url: `http://${this.config.hostname}:${this.config.port}`,\n };\n }\n\n /**\n * Convert stream to string\n */\n private async streamToString(stream: http.IncomingMessage): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of stream) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n return Buffer.concat(chunks).toString('utf-8');\n }\n\n /**\n * Convert Node.js IncomingMessage to Web Request\n */\n private async nodeRequestToWebRequest(\n req: http.IncomingMessage,\n ): Promise<Request> {\n const url = `http://${this.config.hostname}:${this.config.port}${req.url}`;\n const method = req.method || 'GET';\n const headers = new Headers();\n\n for (const [key, value] of Object.entries(req.headers)) {\n if (value) {\n headers.set(key, Array.isArray(value) ? value[0] : value);\n }\n }\n\n let body: string | undefined;\n if (method !== 'GET' && method !== 'HEAD') {\n body = await this.streamToString(req);\n }\n\n return new Request(url, {\n method,\n headers,\n body,\n });\n }\n\n /**\n * Convert Web Response to Node.js ServerResponse\n */\n private async webResponseToNodeResponse(\n webResponse: Response,\n res: http.ServerResponse,\n ): Promise<void> {\n res.statusCode = webResponse.status;\n\n // Set headers\n webResponse.headers.forEach((value, key) => {\n res.setHeader(key, value);\n });\n\n // Send body\n if (webResponse.body) {\n const reader = webResponse.body.getReader();\n\n // Client disconnect handling — essential for the long-lived `_events` SSE\n // stream (#1763): a never-ending stream is only torn down when its reader\n // is cancelled, and nothing cancels it unless we detect the socket close.\n // On `res`/socket 'close' before the response finished, cancel the reader\n // so the source stream's `cancel()` fires (unsubscribe + clear heartbeat).\n let clientGone = false;\n const onClose = () => {\n if (res.writableFinished) return; // normal completion, not a disconnect\n clientGone = true;\n void reader.cancel().catch(() => {});\n };\n res.on('close', onClose);\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done || clientGone) break;\n if (!res.write(value)) {\n // Respect back-pressure so a slow/absent consumer can't unbounded-\n // buffer in the Node socket. Resolve on 'drain' OR on 'close'/\n // 'error' — a disconnect while back-pressured never fires 'drain',\n // so waiting only for it would hang this frame forever (leaking it\n // and pinning the reader for the long-lived `_events` stream). Race\n // the three and remove the losers so one-shot listeners don't pile\n // up across many drains.\n await new Promise<void>((resolve) => {\n const settle = () => {\n res.off('drain', settle);\n res.off('close', settle);\n res.off('error', settle);\n resolve();\n };\n res.once('drain', settle);\n res.once('close', settle);\n res.once('error', settle);\n });\n if (clientGone) break;\n }\n }\n } catch {\n // Reader cancelled (client gone) or write failed — stop streaming.\n } finally {\n res.off('close', onClose);\n }\n }\n\n if (!res.writableEnded) {\n res.end();\n }\n }\n\n /**\n * Generate fetch handler function (for serverless environments)\n */\n generateHandler(): (req: Request) => Promise<Response> {\n return (req) => this.handleRequest(req);\n }\n\n /**\n * Main request handler using native Bun APIs\n */\n private async handleRequest(req: Request): Promise<Response> {\n const url = new URL(req.url);\n\n // Handle CORS preflight\n if (req.method === 'OPTIONS' && this.config.enableCors) {\n return this.createCorsResponse(req);\n }\n\n // Handle custom routes first\n if (this.config.customRoutes) {\n for (const [path, handler] of Object.entries(this.config.customRoutes)) {\n if (url.pathname === `${this.config.basePath}${path}`) {\n const response = await handler(req);\n return this.addCorsHeaders(response, req);\n }\n }\n }\n\n // Change-feed route (#1758): auth-guarded, tenant-scoped cursor read\n // over the _smrt_changes log. Logic lives in ./changes-route.ts.\n if (url.pathname === `${this.config.basePath}/_changes`) {\n const response = await handleChangesRoute(req, {\n authMiddleware: this.config.authMiddleware,\n db: this.resolveContextDb(),\n });\n return this.addCorsHeaders(response, req);\n }\n\n // Live change-signal SSE route (#1763): auth-guarded, tenant-scoped\n // Server-Sent-Events stream of coarse signals (no row payloads). Logic\n // lives in ./events-route.ts. Wrapped in addCorsHeaders so a cross-origin\n // credentialed EventSource can subscribe when `allowCredentials` + an\n // allow-listed origin are configured (#1861); with the fail-closed default\n // (`allowCredentials: false`) this stays same-origin only, exactly as\n // before. The stream body passes through untouched — addCorsHeaders only\n // re-wraps headers. Fail-closed auth is unchanged: the CORS layer never\n // authorizes; it only lets an already-authorized cookie reach the guard.\n if (url.pathname === `${this.config.basePath}/_events`) {\n const response = await handleEventsRoute(req, {\n authMiddleware: this.config.authMiddleware,\n db: this.resolveContextDb(),\n manifestHash: this.resolveManifestHash(),\n maxSubscribers: this.config.eventsRoute?.maxSubscribers,\n });\n return this.addCorsHeaders(response, req);\n }\n\n // Handle object routes\n if (url.pathname.startsWith(this.config.basePath || '')) {\n const response = await this.handleObjectRoute(req, url);\n return this.addCorsHeaders(response, req);\n }\n\n // Not found\n return this.createErrorResponse(404, 'Not found');\n }\n\n /**\n * Handle CRUD routes for SMRT objects\n */\n private async handleObjectRoute(req: Request, url: URL): Promise<Response> {\n const pathParts = url.pathname\n .replace(this.config.basePath || '', '')\n .split('/')\n .filter(Boolean);\n\n if (pathParts.length === 0) {\n return this.createErrorResponse(400, 'Object type required');\n }\n\n // Reserved batch write contract route (#1759): POST {basePath}/sync/apply.\n if (\n pathParts.length === SYNC_APPLY_ROUTE_SEGMENTS.length &&\n SYNC_APPLY_ROUTE_SEGMENTS.every((segment, i) => pathParts[i] === segment)\n ) {\n if (req.method !== 'POST') {\n return this.createErrorResponse(405, 'Method not allowed');\n }\n return await this.handleSyncApply(req);\n }\n\n const objectType = pathParts[0];\n const objectId = pathParts[1];\n\n // Check for explicitly registered collection first\n if (this.collections.has(objectType)) {\n const collection = this.collections.get(objectType);\n if (!collection) throw new Error(`Collection ${objectType} not found`);\n\n const objectName = this.getCollectionObjectName(collection) || objectType;\n\n // Apply auth middleware if configured\n if (this.config.authMiddleware) {\n const authCheck = this.config.authMiddleware(\n objectName,\n req.method.toLowerCase(),\n );\n const authResult = await authCheck(req);\n if (authResult instanceof Response) {\n return authResult; // Auth failed\n }\n // Auth passed, use the potentially modified request\n req = authResult;\n } else if (!this.isRoutePublic(objectName, req.method)) {\n // Fail-closed (#1540): no auth middleware wired and the object isn't\n // marked `@smrt({ api: { public } })` → refuse rather than serve open.\n return this.createErrorResponse(401, 'Authentication required');\n }\n\n // Use registered collection directly\n return await this.executeCrudOperation(\n req,\n collection,\n objectId,\n url,\n objectName,\n );\n }\n\n // Fall back to auto-discovery via ObjectRegistry, matching the URL segment\n // against the canonical manifest `collection` value (#1794).\n const classInfo = this.findClassByCollectionSegment(objectType);\n\n if (!classInfo) {\n return this.createErrorResponse(\n 404,\n `Object type '${objectType}' not found`,\n );\n }\n\n // Apply auth middleware if configured\n if (this.config.authMiddleware) {\n const authCheck = this.config.authMiddleware(\n classInfo.name,\n req.method.toLowerCase(),\n );\n const authResult = await authCheck(req);\n if (authResult instanceof Response) {\n return authResult; // Auth failed\n }\n // Auth passed, use the potentially modified request\n req = authResult;\n } else if (!this.isRoutePublic(classInfo.name, req.method)) {\n // Fail-closed (#1540): see registered-collection branch above.\n return this.createErrorResponse(401, 'Authentication required');\n }\n\n // Get or create collection\n const collection = await this.getCollection(classInfo);\n\n return await this.executeCrudOperation(\n req,\n collection,\n objectId,\n url,\n classInfo.name,\n );\n }\n\n /**\n * Execute CRUD operation on a collection\n */\n private async executeCrudOperation(\n req: Request,\n collection: SmrtCollection<SmrtObject>,\n objectId: string | undefined,\n url: URL,\n objectName?: string,\n ): Promise<Response> {\n try {\n const action = this.getCrudAction(req.method, objectId);\n if (action && !this.isApiActionEnabled(objectName, action)) {\n return this.createErrorResponse(405, 'Method not allowed');\n }\n\n // Handle special /count endpoint\n if (objectId === 'count' && req.method === 'GET') {\n return await this.handleCount(collection, url.searchParams, objectName);\n }\n\n // Route to appropriate CRUD operation\n switch (req.method) {\n case 'GET':\n return objectId\n ? await this.handleGet(collection, objectId, req, objectName)\n : await this.handleList(\n collection,\n url.searchParams,\n req,\n objectName,\n );\n\n case 'POST':\n return await this.handleCreate(collection, req, objectName);\n\n case 'PUT':\n case 'PATCH':\n if (!objectId) {\n return this.createErrorResponse(\n 400,\n 'Object ID required for update',\n );\n }\n return await this.handleUpdate(collection, objectId, req, objectName);\n\n case 'DELETE':\n if (!objectId) {\n return this.createErrorResponse(\n 400,\n 'Object ID required for delete',\n );\n }\n return await this.handleDelete(collection, objectId);\n\n default:\n return this.createErrorResponse(405, 'Method not allowed');\n }\n } catch (error) {\n console.error('API Error:', error);\n return this.createErrorResponse(500, 'Internal server error');\n }\n }\n\n private getCrudAction(\n method: string,\n objectId: string | undefined,\n ): 'list' | 'get' | 'create' | 'update' | 'delete' | null {\n switch (method) {\n case 'GET':\n return objectId && objectId !== 'count' ? 'get' : 'list';\n case 'POST':\n return 'create';\n case 'PUT':\n case 'PATCH':\n return 'update';\n case 'DELETE':\n return 'delete';\n default:\n return null;\n }\n }\n\n /**\n * Fail-closed authorization posture (#1540). Returns true only when the\n * object opts out of auth via `@smrt({ api: { public } })`:\n * - `public: true` → all methods are public.\n * - `public: 'read'` → only safe (GET) methods are public.\n * Everything else requires an `authMiddleware` to be configured.\n */\n private isRoutePublic(\n objectName: string | undefined,\n method: string,\n ): boolean {\n if (!objectName) return false;\n const apiConfig = ObjectRegistry.getConfig(objectName)?.api;\n if (!apiConfig || typeof apiConfig !== 'object') return false;\n const publicAccess = (apiConfig as { public?: boolean | 'read' }).public;\n if (publicAccess === true) return true;\n if (publicAccess === 'read') return method.toUpperCase() === 'GET';\n return false;\n }\n\n private isApiActionEnabled(\n objectName: string | undefined,\n action: 'list' | 'get' | 'create' | 'update' | 'delete',\n ): boolean {\n if (!objectName) {\n return true;\n }\n\n const config = ObjectRegistry.getConfig(objectName);\n const apiConfig = config.api;\n\n if (apiConfig === false) {\n return false;\n }\n\n if (apiConfig && typeof apiConfig === 'object') {\n if (apiConfig.include && !apiConfig.include.includes(action)) {\n return false;\n }\n\n if (apiConfig.exclude?.includes(action)) {\n return false;\n }\n }\n\n return true;\n }\n\n private getCollectionObjectName(\n collection: SmrtCollection<SmrtObject>,\n ): string | undefined {\n // `_itemClass` lives on the instance (protected getter) or the collection\n // constructor (static). Read it through a structural shape rather than the\n // class's private surface; behavior is unchanged.\n const itemClass: SmrtObjectConstructor | undefined =\n (collection as unknown as { _itemClass?: SmrtObjectConstructor })\n ._itemClass ||\n (\n collection.constructor as unknown as {\n _itemClass?: SmrtObjectConstructor;\n }\n )?._itemClass;\n\n if (!itemClass) {\n return undefined;\n }\n\n const registered = ObjectRegistry.getClassByConstructor(itemClass);\n return registered?.qualifiedName || registered?.name || itemClass.name;\n }\n\n /**\n * Fail-closed tenant read scope (#1782).\n *\n * A `@TenantScoped` model served over a public/anonymous read has no ambient\n * tenant context, so the tenancy interceptor (optional mode) passes the query\n * through UNFILTERED and returns every tenant's rows. When tenancy is enabled\n * but no tenant is active, this returns a `{ tenantId: null }` filter so reads\n * fail closed to NULL-tenant (global) rows only — mirroring the dispatch\n * resolver's \"enforced, no active tenant → global rows only\" convention\n * (`resolveDispatchTenantScope` is the core-level trust anchor tenancy fills\n * in; core cannot import tenancy directly). Returns undefined when a tenant IS\n * active (the interceptor filters by it) or tenancy is disabled (no isolation\n * to enforce).\n *\n * Tenant scoping is recognized across BOTH registration forms (#1782): the\n * `@smrt({ tenantScoped })` config / manifest-merged form via\n * `ObjectRegistry.isTenantScoped`, and the standalone `@TenantScoped()`\n * decorator via the tenancy-filled `isTenantScopedClassResolved` hook — so a\n * `@TenantScoped()`-only public model can't slip past the guard regardless of\n * manifest timing.\n */\n private resolveTenantReadScope(\n objectName?: string,\n ): { tenantId: null } | undefined {\n if (\n !objectName ||\n !(\n ObjectRegistry.isTenantScoped(objectName) ||\n !!ObjectRegistry.getConfig(objectName)?.tenantScoped ||\n isTenantScopedClassResolved(objectName)\n )\n ) {\n return undefined;\n }\n const scope = resolveDispatchTenantScope();\n return scope.enforced && scope.tenantId === null\n ? { tenantId: null }\n : undefined;\n }\n\n /**\n * Merge the fail-closed tenant read scope (#1782) into a query's WHERE clause.\n * When the scope is active (global-only), any client-supplied tenant filter is\n * dropped first so a `?tenantId=...` / `?tenant_id[ne]=...` query param can\n * never widen the scope, then NULL-tenant is forced. Returns the original\n * `where` untouched when the scope is inactive.\n */\n private applyTenantReadScope(\n objectName: string | undefined,\n where: Record<string, string | string[]> | undefined,\n ): Record<string, unknown> | undefined {\n const scope = this.resolveTenantReadScope(objectName);\n if (!scope) {\n return where;\n }\n const cleaned: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(where ?? {})) {\n // A key may carry an operator suffix, e.g. \"tenant_id !=\" — match on the\n // field portion so no operator variant slips a client tenant filter past.\n const field = key.split(/\\s+/)[0];\n if (field === 'tenantId' || field === 'tenant_id') {\n continue;\n }\n cleaned[key] = value;\n }\n cleaned.tenantId = null;\n return cleaned;\n }\n\n /**\n * Handle GET /objects/:id\n */\n private async handleGet(\n collection: SmrtCollection<SmrtObject>,\n id: string,\n req: Request,\n objectName?: string,\n ): Promise<Response> {\n const cacheControl = this.resolveReadCachePolicy(objectName);\n\n if (this.hasReadPermissionFields(objectName)) {\n // Field-level read permissions make the response body vary by caller\n // permissions, so the validator must cover the redacted body returned to\n // this caller rather than only the table version.\n const scope = this.resolveTenantReadScope(objectName);\n const object = scope\n ? await collection.get({ id, ...scope })\n : await collection.get(id);\n if (!object) {\n return this.createErrorResponse(404, 'Object not found');\n }\n return conditionalJsonResponse(\n req,\n this.toPublicData(object),\n cacheControl,\n );\n }\n\n // ETag v2 (#1765): compute the table-version ETag first. A CONCRETE\n // If-None-Match short-circuits into a 304 BEFORE the row is fetched — a\n // delete advances the table version (tombstone), so a stale cached\n // representation of a since-deleted row can never concretely match. A\n // wildcard `*` is deferred until AFTER the fetch confirms the row exists,\n // so a missing row still returns 404 (not a false 304).\n const etag = await this.computeReadEtag(collection, req, objectName);\n const ifNoneMatch = req.headers.get('if-none-match');\n const notModified = (): Response =>\n new Response(null, {\n status: 304,\n headers: { 'Cache-Control': cacheControl, ETag: etag },\n });\n if (ifNoneMatchHasConcreteMatch(ifNoneMatch, etag)) {\n return notModified();\n }\n\n // #1782: scope a public/anonymous read of a tenant-scoped model to global\n // (NULL-tenant) rows when no tenant context is active.\n const scope = this.resolveTenantReadScope(objectName);\n const object = scope\n ? await collection.get({ id, ...scope })\n : await collection.get(id);\n if (!object) {\n return this.createErrorResponse(404, 'Object not found');\n }\n // Row exists → a wildcard `*` may now be honored as a 304.\n if (ifNoneMatchSatisfied(ifNoneMatch, etag)) {\n return notModified();\n }\n return new Response(JSON.stringify(this.toPublicData(object)), {\n status: 200,\n headers: {\n 'Cache-Control': cacheControl,\n 'Content-Type': 'application/json',\n ETag: etag,\n },\n });\n }\n\n /**\n * Handle GET /objects (list with query params)\n */\n private async handleList(\n collection: SmrtCollection<SmrtObject>,\n params: URLSearchParams,\n req: Request,\n objectName?: string,\n ): Promise<Response> {\n const cacheControl = this.resolveReadCachePolicy(objectName);\n\n const buildPayload = async () => {\n const limit = Number.parseInt(params.get('limit') || '50', 10);\n const offset = Number.parseInt(params.get('offset') || '0', 10);\n const orderBy = params.get('orderBy') || 'created_at DESC';\n\n // Build where clause from query params\n // Convert REST-style operators (price[gt]) to SQL-style (price >)\n const where: Record<string, string | string[]> = {};\n for (const [key, value] of params.entries()) {\n if (!['limit', 'offset', 'orderBy'].includes(key)) {\n // Parse REST operator format: field[operator]\n const match = key.match(/^(.+)\\[(.+)\\]$/);\n if (match) {\n const field = match[1];\n const operator = match[2];\n // Map REST operators to SQL operators\n const operatorMap: Record<string, string> = {\n gt: '>',\n gte: '>=',\n lt: '<',\n lte: '<=',\n ne: '!=',\n in: 'in',\n like: 'like',\n };\n const sqlOperator = operatorMap[operator] || operator;\n const sqlKey = `${field} ${sqlOperator}`;\n // Handle 'in' operator - convert comma-separated string to array\n where[sqlKey] = operator === 'in' ? value.split(',') : value;\n } else {\n where[key] = value;\n }\n }\n }\n\n // #1782: fail closed to global (NULL-tenant) rows for a public/anonymous\n // read of a tenant-scoped model with no active tenant context.\n const scopedWhere = this.applyTenantReadScope(objectName, where);\n\n const objects = await collection.list({\n where:\n scopedWhere && Object.keys(scopedWhere).length > 0\n ? scopedWhere\n : undefined,\n limit,\n offset,\n orderBy,\n });\n\n return objects.map((object: SmrtObject) => this.toPublicData(object));\n };\n\n if (this.hasReadPermissionFields(objectName)) {\n // Field-level read permissions make the response body vary by caller\n // permissions, so use the v1 body-hash path over the redacted payload.\n return conditionalJsonResponse(req, await buildPayload(), cacheControl);\n }\n\n // ETag v2 (#1765): resolve the policy + table-version ETag first, then\n // hand the list query to versionConditionalResponse as a thunk. On a\n // matching If-None-Match it returns a 304 and the thunk — the collection\n // query — never runs, so an unchanged table revalidates with no table scan.\n const etag = await this.computeReadEtag(collection, req, objectName);\n return versionConditionalResponse(req, etag, cacheControl, buildPayload);\n }\n\n /**\n * Handle GET /objects/count\n */\n private async handleCount(\n collection: SmrtCollection<SmrtObject>,\n params: URLSearchParams,\n objectName?: string,\n ): Promise<Response> {\n // Build where clause from query params (same logic as handleList)\n const where: Record<string, string | string[]> = {};\n for (const [key, value] of params.entries()) {\n // Parse REST operator format: field[operator]\n const match = key.match(/^(.+)\\[(.+)\\]$/);\n if (match) {\n const field = match[1];\n const operator = match[2];\n // Map REST operators to SQL operators\n const operatorMap: Record<string, string> = {\n gt: '>',\n gte: '>=',\n lt: '<',\n lte: '<=',\n ne: '!=',\n in: 'in',\n like: 'like',\n };\n const sqlOperator = operatorMap[operator] || operator;\n const sqlKey = `${field} ${sqlOperator}`;\n // Handle 'in' operator - convert comma-separated string to array\n where[sqlKey] = operator === 'in' ? value.split(',') : value;\n } else {\n where[key] = value;\n }\n }\n\n // #1782: a count leaks cross-tenant cardinality just as a list leaks rows,\n // so apply the same fail-closed global scope for anonymous tenant reads.\n const scopedWhere = this.applyTenantReadScope(objectName, where);\n\n const count = await collection.count({\n where:\n scopedWhere && Object.keys(scopedWhere).length > 0\n ? scopedWhere\n : undefined,\n });\n\n return this.createJsonResponse({ count });\n }\n\n /**\n * Handle POST /objects\n */\n private async handleCreate(\n collection: SmrtCollection<SmrtObject>,\n req: Request,\n objectName?: string,\n ): Promise<Response> {\n const data = this.applyWritablePolicy(objectName, await req.json());\n const object = await collection.create({ ...data, _skipLoad: true });\n await object.save();\n return this.createJsonResponse(this.toPublicData(object), 201);\n }\n\n /**\n * Handle PUT/PATCH /objects/:id\n */\n private async handleUpdate(\n collection: SmrtCollection<SmrtObject>,\n id: string,\n req: Request,\n objectName?: string,\n ): Promise<Response> {\n const data = this.applyWritablePolicy(objectName, await req.json());\n const object = await collection.get(id);\n\n if (!object) {\n return this.createErrorResponse(404, 'Object not found');\n }\n\n // Update object properties\n Object.assign(object, data);\n await object.save();\n\n return this.createJsonResponse(this.toPublicData(object));\n }\n\n /**\n * Handle DELETE /objects/:id\n */\n private async handleDelete(\n collection: SmrtCollection<SmrtObject>,\n id: string,\n ): Promise<Response> {\n const object = await collection.get(id);\n\n if (!object) {\n return this.createErrorResponse(404, 'Object not found');\n }\n\n await object.delete();\n return new Response(null, { status: 204 });\n }\n\n /**\n * Handle POST /sync/apply — the idempotent batch write contract (#1759).\n * All processing lives in `sync/apply.ts`; this method only adapts the\n * generator's existing collection resolution, auth, action gating, and\n * writable policy into a {@link SyncApplyTarget} per item.\n */\n private async handleSyncApply(req: Request): Promise<Response> {\n // Buffer the body once. Request bodies are single-read streams, and the\n // per-item auth middleware below must receive a readable body exactly as\n // it does on CRUD routes (where auth runs before parsing) — so each\n // middleware invocation gets a fresh Request rebuilt from this buffer.\n let rawBody: string;\n let body: unknown;\n try {\n rawBody = await req.text();\n body = JSON.parse(rawBody);\n } catch {\n return this.createErrorResponse(400, 'Invalid JSON body');\n }\n\n const outcome = await processSyncApplyBatch(body, {\n resolveTarget: (objectSegment) =>\n this.resolveSyncApplyTarget(objectSegment, req, rawBody),\n });\n return this.createJsonResponse(outcome.body, outcome.status);\n }\n\n /**\n * Resolve a sync item's `object` segment exactly like `handleObjectRoute`\n * resolves a CRUD URL segment (registered collections first, then registry\n * auto-discovery), and wrap the generator's per-object machinery.\n */\n private async resolveSyncApplyTarget(\n objectSegment: string,\n req: Request,\n rawBody: string,\n ): Promise<SyncApplyTarget | null> {\n let collection: SmrtCollection<SmrtObject> | null = null;\n let objectName: string | null = null;\n\n const registered = this.collections.get(objectSegment);\n if (registered) {\n collection = registered;\n objectName = this.getCollectionObjectName(registered) || objectSegment;\n } else {\n // Same canonical-`collection` match as the CRUD path so a client and the\n // batch contract resolve identical segments (#1794).\n const info = this.findClassByCollectionSegment(objectSegment);\n if (info) {\n collection = await this.getCollection(info);\n objectName = info.name;\n }\n }\n\n if (!collection || !objectName) {\n return null;\n }\n\n const resolvedName = objectName;\n const resolvedCollection = collection;\n return {\n objectName: resolvedName,\n collection: resolvedCollection,\n isOpAllowed: (op: SyncApplyOp) =>\n this.isApiActionEnabled(resolvedName, op),\n authorize: async (op: SyncApplyOp) => {\n if (this.config.authMiddleware) {\n const verb =\n op === 'create' ? 'post' : op === 'update' ? 'put' : 'delete';\n const authCheck = this.config.authMiddleware(resolvedName, verb);\n // Fresh Request per invocation: the batch handler already consumed\n // the original body, and middleware may read it (body-based auth,\n // request signing) exactly as it can on CRUD routes.\n const authResult = await authCheck(\n new Request(req.url, {\n method: req.method,\n headers: req.headers,\n body: rawBody,\n }),\n );\n if (authResult instanceof Response) {\n return authResult.status === 401 ? 'auth_required' : 'forbidden';\n }\n return 'ok';\n }\n // Fail-closed (#1540): every sync op is mutating, so only\n // `@smrt({ api: { public: true } })` objects apply without auth.\n return this.isRoutePublic(resolvedName, 'POST')\n ? 'ok'\n : 'auth_required';\n },\n prepare: (payload) => this.applyWritablePolicy(resolvedName, payload),\n };\n }\n\n /**\n * Get or create collection instance\n */\n private async getCollection(\n classInfo: RegisteredClass,\n ): Promise<SmrtCollection<SmrtObject>> {\n if (!this.collections.has(classInfo.name)) {\n // `collectionConstructor` is typed optional on RegisteredClass, but the\n // auto-discovery path only reaches here for classes that declare one.\n // Narrow to the non-optional constructor type before instantiating.\n const ctor = classInfo.collectionConstructor as NonNullable<\n RegisteredClass['collectionConstructor']\n >;\n const collection = new ctor({\n ai: this.context.ai,\n db: this.context.db,\n });\n // Await initialize() so the auto-discovered collection is actually usable\n // (its DB is wired). Without this, list()/get() throw \"Database accessed\n // before initialization\" — a latent bug that was masked while the\n // generated client's plural URLs never matched the singular-only\n // auto-discovery segment (#1794). The explicit-registerCollection() path\n // receives an already-initialized collection from the caller, so this\n // only affects the auto-discovery factory.\n await collection.initialize();\n this.collections.set(classInfo.name, collection);\n }\n const collection = this.collections.get(classInfo.name);\n if (!collection) throw new Error(`Collection ${classInfo.name} not found`);\n return collection;\n }\n\n /**\n * Mass-assignment guard (#1540): strip framework/server-managed and\n * `@field({ readonly: true })` fields from a create/update body, and — when an\n * `@smrt({ api: { writable: [...] } })` allowlist is set — intersect with it.\n */\n private applyWritablePolicy(\n objectName: string | undefined,\n data: unknown,\n ): Record<string, unknown> {\n if (!data || typeof data !== 'object') {\n return {};\n }\n\n const serverManaged = new Set([\n 'id',\n 'tenantId',\n 'tenant_id',\n 'createdAt',\n 'created_at',\n 'updatedAt',\n 'updated_at',\n ]);\n\n const readonly = new Set<string>();\n let writable: string[] | null = null;\n\n if (objectName) {\n const apiConfig = ObjectRegistry.getConfig(objectName)?.api;\n if (\n apiConfig &&\n typeof apiConfig === 'object' &&\n Array.isArray((apiConfig as { writable?: unknown }).writable)\n ) {\n writable = (apiConfig as { writable: string[] }).writable;\n }\n\n for (const [name, def] of ObjectRegistry.getFields(objectName)) {\n if (def && (def.readonly === true || def._meta?.readonly === true)) {\n readonly.add(name);\n }\n }\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(data)) {\n if (key.startsWith('_')) continue;\n if (serverManaged.has(key)) continue;\n if (readonly.has(key)) continue;\n if (writable && !writable.includes(key)) continue;\n result[key] = value;\n }\n return result;\n }\n\n /**\n * Serialize a SmrtObject for a network response, excluding sensitive fields\n * (#1540). Falls back to the value unchanged for non-SmrtObject payloads.\n */\n private toPublicData(object: unknown): unknown {\n const serializable = object as {\n toPublicJSON?: (options?: PublicJsonOptions) => unknown;\n } | null;\n return typeof serializable?.toPublicJSON === 'function'\n ? serializable.toPublicJSON(this.getPublicJsonOptions())\n : object;\n }\n\n private getPublicJsonOptions(): PublicJsonOptions {\n return { permissions: this.context.permissions };\n }\n\n /**\n * Resolve the Cache-Control policy for a generated read and fire the\n * one-time policy warnings (#1757): private + revalidatable by default;\n * shared `s-maxage` only for public models that opt in; always private for\n * tenant-scoped models, whose bodies vary with tenant context that URL-keyed\n * shared caches cannot see. Field read-permission models are also private\n * because the body varies by caller permissions.\n */\n private resolveReadCachePolicy(objectName: string | undefined): string {\n const config = objectName\n ? ObjectRegistry.getConfig(objectName)\n : undefined;\n const apiConfig = config?.api;\n // Canonical accessor covers both `@smrt({ tenantScoped })` and the\n // manifest-merged `@TenantScoped()` decorator form; the raw config flag is\n // a belt-and-braces fallback for registrations not yet normalized.\n const tenantScoped = objectName\n ? ObjectRegistry.isTenantScoped(objectName) || !!config?.tenantScoped\n : false;\n const permissionScoped = this.hasReadPermissionFields(objectName);\n if (objectName) {\n warnIfSharedCacheNeutralized(\n objectName,\n apiConfig,\n tenantScoped,\n permissionScoped,\n );\n warnIfTenantScopedPublicRead(objectName, apiConfig, tenantScoped);\n }\n return resolveReadCacheControl(apiConfig, {\n tenantScoped,\n permissionScoped,\n });\n }\n\n private hasReadPermissionFields(objectName: string | undefined): boolean {\n if (!objectName) return false;\n for (const fields of this.getFieldMapsForPublicPolicy(objectName)) {\n for (const [, def] of fields) {\n if (\n typeof def?.readPermission === 'string' ||\n typeof def?._meta?.readPermission === 'string'\n ) {\n return true;\n }\n }\n }\n return false;\n }\n\n private getFieldMapsForPublicPolicy(\n objectName: string,\n ): Array<ReturnType<typeof ObjectRegistry.getFields>> {\n const registered = ObjectRegistry.getClass(objectName);\n const className =\n registered?.qualifiedName ?? registered?.name ?? objectName;\n const fieldMaps: Array<ReturnType<typeof ObjectRegistry.getFields>> = [\n registered?.inheritedFields || ObjectRegistry.getFields(className),\n ];\n const stiBase = ObjectRegistry.getSTIBase(className);\n if (stiBase) {\n fieldMaps.push(\n ObjectRegistry.getClass(stiBase)?.inheritedFields ||\n ObjectRegistry.getFields(stiBase),\n );\n for (const descendant of ObjectRegistry.getDescendants(stiBase)) {\n fieldMaps.push(\n ObjectRegistry.getClass(descendant)?.inheritedFields ||\n ObjectRegistry.getFields(descendant),\n );\n }\n }\n return fieldMaps;\n }\n\n /**\n * Compute the ETag v2 (#1765) for a generated read: the table's change-feed\n * version ({@link getTableVersion}) keyed by the request representation, so a\n * matching `If-None-Match` can short-circuit into a 304 BEFORE the collection\n * query runs. The representation folds in the active tenant for tenant-scoped\n * models so one tenant's cached ETag never satisfies another's read. When an\n * web-collection manifest hash is folded into the digest (#1764), so a\n * shape-only deploy busts every read validator. An explicit\n * `APIConfig.manifestHash` wins; otherwise the hash is computed from the\n * runtime registry on first use (#1862).\n */\n private async computeReadEtag(\n collection: SmrtCollection<SmrtObject>,\n req: Request,\n objectName: string | undefined,\n ): Promise<string> {\n const version = await getTableVersion(collection.db, collection.tableName);\n const representation = canonicalReadRepresentation(\n req,\n this.readTenantDiscriminator(objectName),\n );\n // Salt the ETag with the web-collection shape digest (#1764) so a\n // shape-only deploy busts every read validator. Runtime APIGenerator\n // deployments compute the hash from ObjectRegistry when no explicit override\n // is configured (#1862).\n return computeTableVersionEtag(\n version,\n representation,\n this.resolveManifestHash(),\n );\n }\n\n private resolveManifestHash(): string {\n if (this.config.manifestHash !== undefined) {\n return this.config.manifestHash;\n }\n this.runtimeManifestHash ??= computeRuntimeWebManifestHash();\n return this.runtimeManifestHash;\n }\n\n /**\n * A per-tenant ETag discriminator for tenant-scoped models: the active tenant\n * id (or `global`) so tenant A's cached ETag never satisfies tenant B's read\n * of the same table and params. `undefined` for non-tenant-scoped models,\n * whose bodies do not vary by tenant.\n */\n private readTenantDiscriminator(objectName?: string): string | undefined {\n if (!objectName) return undefined;\n const tenantScoped =\n ObjectRegistry.isTenantScoped(objectName) ||\n !!ObjectRegistry.getConfig(objectName)?.tenantScoped ||\n isTenantScopedClassResolved(objectName);\n if (!tenantScoped) return undefined;\n // Shared with the generated SvelteKit route so both transports key the ETag\n // on the active tenant identically (cross-tenant false-304 guard).\n return resolveTenantEtagDiscriminator();\n }\n\n /**\n * Create JSON response with proper headers\n */\n private createJsonResponse(data: unknown, status = 200): Response {\n return new Response(JSON.stringify(data), {\n status,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n }\n\n /**\n * Create error response\n */\n private createErrorResponse(status: number, message: string): Response {\n return new Response(JSON.stringify({ error: message }), {\n status,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n }\n\n /**\n * Resolve the allowed `Access-Control-Allow-Origin` for a request (#1540).\n * Returns the request's `Origin` only when it is in the configured allowlist;\n * never `*`. Returns null when CORS should not be applied.\n */\n private resolveAllowedOrigin(req: Request): string | null {\n if (!this.config.enableCors) return null;\n const allowed = this.config.allowedOrigins;\n if (!allowed || allowed.length === 0) return null;\n const origin = req.headers.get('origin');\n return origin && allowed.includes(origin) ? origin : null;\n }\n\n /**\n * Whether to emit `Access-Control-Allow-Credentials: true` (#1861). Only when\n * explicitly opted in AND an origin actually resolved — credentials are never\n * paired with a wildcard/absent origin (`resolveAllowedOrigin` already never\n * returns `*`).\n */\n private shouldAllowCredentials(): boolean {\n return this.config.allowCredentials === true;\n }\n\n /**\n * Create CORS preflight response\n */\n private createCorsResponse(req: Request): Response {\n const headers: Record<string, string> = {\n 'Access-Control-Allow-Methods': 'GET,POST,PUT,PATCH,DELETE,OPTIONS',\n // `Last-Event-ID` is allow-listed for the `_events` SSE route (#1861): a\n // fetch-based cross-origin SSE client that resumes from a cursor sends it\n // as a request header, which is not CORS-safelisted and would otherwise\n // fail preflight. Harmless on the other routes, which ignore it.\n 'Access-Control-Allow-Headers':\n 'Content-Type,Authorization,Last-Event-ID',\n 'Access-Control-Max-Age': '86400',\n };\n const origin = this.resolveAllowedOrigin(req);\n if (origin) {\n headers['Access-Control-Allow-Origin'] = origin;\n headers.Vary = 'Origin';\n if (this.shouldAllowCredentials()) {\n headers['Access-Control-Allow-Credentials'] = 'true';\n }\n }\n return new Response(null, { status: 200, headers });\n }\n\n /**\n * Add CORS headers to response\n */\n private addCorsHeaders(response: Response, req: Request): Response {\n const origin = this.resolveAllowedOrigin(req);\n if (!origin) return response;\n\n const headers = new Headers(response.headers);\n headers.set('Access-Control-Allow-Origin', origin);\n headers.set('Vary', 'Origin');\n headers.set(\n 'Access-Control-Allow-Methods',\n 'GET,POST,PUT,PATCH,DELETE,OPTIONS',\n );\n // `Last-Event-ID` so a fetch-based cross-origin SSE client can resume the\n // `_events` stream from a cursor (#1861); see createCorsResponse.\n headers.set(\n 'Access-Control-Allow-Headers',\n 'Content-Type,Authorization,Last-Event-ID',\n );\n // Credentialed CORS (#1861): only when opted in, and only alongside a\n // concrete echoed origin (never `*`) so cookies can flow to an allow-listed\n // cross-origin client (e.g. a credentialed EventSource on `_events`).\n if (this.shouldAllowCredentials()) {\n headers.set('Access-Control-Allow-Credentials', 'true');\n }\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n }\n\n /**\n * Resolve a URL/collection segment to a registered class via auto-discovery.\n *\n * The segment IS the canonical `collection` value from the manifest\n * (`RegisteredClass.collection`, e.g. `products` for `Product`) — the same\n * value the generated client, the SvelteKit route generator, and the registry\n * all derive. Match it VERBATIM; do not re-pluralize. The previous\n * implementation pluralized both the URL segment and the class name and\n * compared them, turning an already-plural client URL (`/products`) into\n * `productses`, so the generated client 404'd against auto-discovered routes\n * (#1794). Shared by the CRUD path and the `sync/apply` batch path so they can\n * never drift.\n *\n * @param segment - The URL/collection path segment (e.g. `products`).\n * @returns The matching registered class, or null if none matches.\n */\n private findClassByCollectionSegment(\n segment: string,\n ): RegisteredClass | null {\n for (const [key, info] of ObjectRegistry.getAllClasses()) {\n // Primary match: the canonical manifest `collection` segment.\n if (info.collection === segment) {\n return info;\n }\n // Back-compat fallback for classes registered without a `collection`\n // (inline/test stubs): derive the plural segment from the simple name and\n // compare to the raw URL segment. Issue #951: use the simple name\n // (info.name), not the qualified map key.\n if (\n !info.collection &&\n this.pluralize((info.name || key).toLowerCase()) === segment\n ) {\n return info;\n }\n }\n return null;\n }\n\n /**\n * Simple pluralization (basic implementation)\n */\n private pluralize(word: string): string {\n if (word.endsWith('y')) {\n return `${word.slice(0, -1)}ies`;\n }\n if (word.endsWith('s') || word.endsWith('sh') || word.endsWith('ch')) {\n return `${word}es`;\n }\n return `${word}s`;\n }\n}\n\n// REST Server Utilities\n\nexport interface RestServerConfig extends APIConfig {\n healthCheck?: {\n enabled?: boolean;\n path?: string;\n customChecks?: (() => Promise<boolean>)[];\n };\n}\n\n/**\n * Create REST server with health checks using Bun\n */\nexport function createRestServer(\n objects: (typeof SmrtObject)[],\n context: APIContext = {},\n config: RestServerConfig = {},\n): { server: http.Server; url: string } {\n // Register objects if not already registered\n objects.forEach((obj) => {\n if (!ObjectRegistry.hasClass(obj.name)) {\n console.warn(`Object ${obj.name} not registered with @smrt decorator`);\n }\n });\n\n const generator = new APIGenerator(config, context);\n const { server, url } = generator.createServer();\n\n console.log(`🚀 smrt REST API server running at ${url}`);\n\n return { server, url };\n}\n\n/**\n * Start server with graceful shutdown\n */\nexport function startRestServer(\n objects: (typeof SmrtObject)[],\n context: APIContext = {},\n config: RestServerConfig = {},\n): Promise<() => Promise<void>> {\n return new Promise((resolve) => {\n const { server, url } = createRestServer(objects, context, config);\n\n // Graceful shutdown function\n const shutdown = (): Promise<void> => {\n return new Promise((shutdownResolve) => {\n console.log('🛑 Shutting down server gracefully...');\n // Node's http.Server#close stops accepting new connections and invokes\n // the callback once in-flight ones drain. (The prior `.stop()` was a\n // Bun-era API absent on http.Server — it would have thrown.)\n server.close(() => {\n console.log('✅ Server shut down complete');\n shutdownResolve();\n });\n });\n };\n\n // Handle shutdown signals\n process.on('SIGTERM', shutdown);\n process.on('SIGINT', shutdown);\n\n resolve(shutdown);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA6GA,SAAS,2BACP,QACiC;CACjC,MAAM,SAA0C,CAAC;CACjD,KAAK,MAAM,CAAC,MAAM,UAAU,QAAQ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I;AACvB;;;;AAKA,SAAgB,gBACd,SACA,UAAsB,CAAC,GACvB,SAA2B,CAAC,GACE;CAC9B,OAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,EAAE,QAAQ,QAAQ,iBAAiB,SAAS,SAAS,MAAM;EAGjE,MAAM,iBAAgC;GACpC,OAAO,IAAI,SAAS,oBAAoB;IACtC,QAAQ,IAAI,uCAAuC;IAInD,OAAO,YAAY;KACjB,QAAQ,IAAI,6BAA6B;KACzC,gBAAgB;IAClB,CAAC;GACH,CAAC;EACH;EAGA,QAAQ,GAAG,WAAW,QAAQ;EAC9B,QAAQ,GAAG,UAAU,QAAQ;EAE7B,QAAQ,QAAQ;CAClB,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"rest.js","names":[],"sources":["../../src/generators/rest.ts"],"sourcesContent":["/**\n * High-performance REST API generator for smrt objects using Node.js HTTP server\n *\n * Designed for minimal bundle size and maximum performance\n */\n\nimport http from 'node:http';\nimport { getTableVersion } from '../change-feed';\nimport type { SmrtCollection } from '../collection';\nimport {\n isTenantScopedClassResolved,\n resolveDispatchTenantScope,\n} from '../dispatch';\nimport type { PublicJsonOptions, SmrtObject } from '../object';\nimport { ObjectRegistry } from '../registry';\nimport type {\n ApiCustomRouteConfig,\n RegisteredClass,\n RegisteredField,\n SmrtObjectConstructor,\n} from '../registry/types';\nimport type {\n FieldDefinition,\n MethodDefinition,\n SmartObjectDefinition,\n SmartObjectManifest,\n} from '../scanner/types';\nimport {\n processSyncApplyBatch,\n SYNC_APPLY_ROUTE_SEGMENTS,\n type SyncApplyOp,\n type SyncApplyTarget,\n} from '../sync/apply';\nimport { computeWebManifestHash } from '../vite-plugin/web-collections';\nimport { handleChangesRoute } from './changes-route';\nimport {\n canonicalReadRepresentation,\n computeTableVersionEtag,\n conditionalJsonResponse,\n ifNoneMatchHasConcreteMatch,\n ifNoneMatchSatisfied,\n resolveReadCacheControl,\n resolveTenantEtagDiscriminator,\n versionConditionalResponse,\n warnIfSharedCacheNeutralized,\n warnIfTenantScopedPublicRead,\n} from './conditional-get';\nimport {\n buildCustomActionInvocationArgs,\n normalizeCustomActionFailure,\n resolveCustomActionMetadata,\n} from './custom-action';\nimport { handleEventsRoute } from './events-route';\n\nexport interface APIConfig {\n basePath?: string;\n enableCors?: boolean;\n /**\n * Explicit CORS origin allowlist (#1540). Required when `enableCors` is true —\n * the generator never emits `Access-Control-Allow-Origin: *`. A request's\n * `Origin` is echoed only when it appears here.\n */\n allowedOrigins?: string[];\n /**\n * Opt into credentialed CORS (#1861). When true, CORS responses to an\n * allow-listed origin also carry `Access-Control-Allow-Credentials: true`, so\n * a cross-origin browser client may send cookies (the only auth an\n * `EventSource` can carry — it cannot set an `Authorization` header). Requires\n * `enableCors` + a non-empty `allowedOrigins`: credentials are NEVER paired\n * with a wildcard origin, and the origin is still echoed only when it is\n * explicitly allow-listed. Fail-closed default (`false`): same-origin only,\n * even when CORS is otherwise enabled, so a plain `enableCors` never silently\n * starts flowing cookies cross-origin.\n */\n allowCredentials?: boolean;\n customRoutes?: Record<string, (req: Request) => Promise<Response>>;\n authMiddleware?: (\n objectName: string,\n action: string,\n ) => (req: Request) => Promise<Request | Response>;\n port?: number;\n hostname?: string;\n /**\n * Live `_events` route options. `maxSubscribers` caps active SSE streams per\n * process (#1860); over-cap connections receive a retryable 503. Set to 0\n * for no cap.\n */\n eventsRoute?: {\n maxSubscribers?: number;\n };\n /**\n * The build's web-collection SHAPE digest (#1764) — the same value the\n * generated `@happyvertical/smrt-virt-web` module exports. When supplied it is\n * folded into every read ETag via {@link computeTableVersionEtag}, so a\n * shape-only deploy (no table write) busts every read validator, closing\n * the documented v2 staleness gap. When omitted, APIGenerator computes the\n * same digest from the runtime registry on first read (#1862). The generated\n * SvelteKit routes bake the same constant in directly rather than going\n * through this runtime server.\n */\n manifestHash?: string;\n}\n\nexport interface APIContext {\n db?: unknown;\n ai?: unknown;\n user?: {\n id: string;\n username?: string;\n roles?: string[];\n };\n /** Resolved permission slugs held by the caller. */\n permissions?: Iterable<string>;\n}\n\nfunction registeredFieldsToManifest(\n fields: Map<string, RegisteredField>,\n): Record<string, FieldDefinition> {\n const result: Record<string, FieldDefinition> = {};\n for (const [name, field] of fields) {\n if (!field || typeof field.type !== 'string') continue;\n const defaultValue =\n field.default !== undefined ? field.default : field._meta?.default;\n result[name] = {\n type: field.type as FieldDefinition['type'],\n ...(field.required !== undefined ? { required: field.required } : {}),\n ...(defaultValue !== undefined ? { default: defaultValue } : {}),\n ...(field.related !== undefined ? { related: field.related } : {}),\n ...(field.transient !== undefined ? { transient: field.transient } : {}),\n ...(field.sensitive !== undefined ? { sensitive: field.sensitive } : {}),\n ...(field.readonly !== undefined ? { readonly: field.readonly } : {}),\n ...(field.readPermission !== undefined\n ? { readPermission: field.readPermission }\n : {}),\n ...(field._meta !== undefined ? { _meta: field._meta } : {}),\n };\n }\n return result;\n}\n\nfunction registeredMethodsToManifest(\n methods: Map<string, MethodDefinition> | undefined,\n): Record<string, MethodDefinition> {\n return Object.fromEntries(methods ?? []);\n}\n\nfunction pluralizeRuntimeCollectionName(className: string): string {\n const lower = className.toLowerCase();\n if (lower.endsWith('y')) return `${lower.slice(0, -1)}ies`;\n if (lower.endsWith('s') || lower.endsWith('x') || lower.endsWith('z')) {\n return `${lower}es`;\n }\n if (lower.endsWith('ch') || lower.endsWith('sh')) return `${lower}es`;\n return `${lower}s`;\n}\n\nfunction runtimeObjectDefinition(\n key: string,\n info: RegisteredClass,\n): SmartObjectDefinition {\n const className = info.name || key;\n return {\n className,\n name: className.toLowerCase(),\n collection: info.collection || pluralizeRuntimeCollectionName(className),\n filePath: info.sourceFilePath || '',\n fields: registeredFieldsToManifest(info.inheritedFields || info.fields),\n methods: registeredMethodsToManifest(info.inheritedMethods || info.methods),\n decoratorConfig: info.config || {},\n ...(info.qualifiedName ? { qualifiedName: info.qualifiedName } : {}),\n ...(info.packageName ? { packageName: info.packageName } : {}),\n ...(info.visibility ? { visibility: info.visibility } : {}),\n ...(info.extends ? { extends: info.extends } : {}),\n ...(info.extendsTypeArg ? { extendsTypeArg: info.extendsTypeArg } : {}),\n ...(info.tools ? { tools: info.tools } : {}),\n };\n}\n\n/**\n * Compute the runtime REST web-manifest hash from the registered object graph\n * (#1862). This mirrors the Vite/SvelteKit source (`computeWebManifestHash`)\n * but builds the manifest from `ObjectRegistry` for APIGenerator deployments.\n */\nexport function computeRuntimeWebManifestHash(\n classes: Iterable<[string, RegisteredClass]> = ObjectRegistry.getAllClasses(),\n): string {\n const objects: SmartObjectManifest['objects'] = {};\n const seen = new Set<RegisteredClass>();\n for (const [key, info] of classes) {\n if (seen.has(info)) continue;\n seen.add(info);\n const manifestKey = info.qualifiedName || key;\n objects[manifestKey] = runtimeObjectDefinition(key, info);\n }\n return computeWebManifestHash({\n version: 'runtime',\n timestamp: 0,\n objects,\n });\n}\n\n/**\n * High-performance API generator using native Bun\n */\nexport class APIGenerator {\n private config: APIConfig;\n private collections = new Map<string, SmrtCollection<SmrtObject>>();\n private context: APIContext;\n private runtimeManifestHash: string | undefined;\n\n constructor(config: APIConfig = {}, context: APIContext = {}) {\n this.config = {\n basePath: '/api/v1',\n // Security defaults (#1540): bind to loopback and keep CORS off unless an\n // explicit origin allowlist is supplied. No `Access-Control-Allow-Origin: *`.\n enableCors: false,\n port: 3000,\n hostname: '127.0.0.1',\n ...config,\n };\n this.context = context;\n }\n\n /**\n * Register a pre-configured collection instance for API exposure\n *\n * @param name - URL path segment for the collection (e.g., 'products' for /api/products)\n * @param collection - Pre-initialized SmrtCollection instance\n */\n registerCollection(\n name: string,\n collection: SmrtCollection<SmrtObject>,\n ): void {\n this.collections.set(name, collection);\n this.runtimeManifestHash = undefined;\n }\n\n /**\n * Resolve the database for generator-level routes that are not object-scoped\n * (currently the `_changes` feed, #1758).\n *\n * Prefers the explicit `APIContext.db`, but falls back to the first\n * registered collection's live handle so the feed works under the documented\n * `registerCollection()` wiring, where callers configure collections with a\n * database but never populate `APIContext.db`. Without the fallback the feed\n * would 503 even though the database is reachable.\n */\n private resolveContextDb(): unknown {\n return (\n this.context.db ?? this.collections.values().next().value?.db ?? undefined\n );\n }\n\n /**\n * Create Node.js HTTP server with all routes\n */\n createServer(): { server: http.Server; url: string } {\n const server = http.createServer(async (req, res) => {\n try {\n const request = await this.nodeRequestToWebRequest(req);\n const response = await this.handleRequest(request);\n await this.webResponseToNodeResponse(response, res);\n } catch (_error) {\n res.statusCode = 500;\n res.end('Internal Server Error');\n }\n });\n\n server.listen(this.config.port, this.config.hostname);\n\n return {\n server,\n url: `http://${this.config.hostname}:${this.config.port}`,\n };\n }\n\n /**\n * Convert stream to string\n */\n private async streamToString(stream: http.IncomingMessage): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of stream) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n return Buffer.concat(chunks).toString('utf-8');\n }\n\n /**\n * Convert Node.js IncomingMessage to Web Request\n */\n private async nodeRequestToWebRequest(\n req: http.IncomingMessage,\n ): Promise<Request> {\n const url = `http://${this.config.hostname}:${this.config.port}${req.url}`;\n const method = req.method || 'GET';\n const headers = new Headers();\n\n for (const [key, value] of Object.entries(req.headers)) {\n if (value) {\n headers.set(key, Array.isArray(value) ? value[0] : value);\n }\n }\n\n let body: string | undefined;\n if (method !== 'GET' && method !== 'HEAD') {\n body = await this.streamToString(req);\n }\n\n return new Request(url, {\n method,\n headers,\n body,\n });\n }\n\n /**\n * Convert Web Response to Node.js ServerResponse\n */\n private async webResponseToNodeResponse(\n webResponse: Response,\n res: http.ServerResponse,\n ): Promise<void> {\n res.statusCode = webResponse.status;\n\n // Set headers\n webResponse.headers.forEach((value, key) => {\n res.setHeader(key, value);\n });\n\n // Send body\n if (webResponse.body) {\n const reader = webResponse.body.getReader();\n\n // Client disconnect handling — essential for the long-lived `_events` SSE\n // stream (#1763): a never-ending stream is only torn down when its reader\n // is cancelled, and nothing cancels it unless we detect the socket close.\n // On `res`/socket 'close' before the response finished, cancel the reader\n // so the source stream's `cancel()` fires (unsubscribe + clear heartbeat).\n let clientGone = false;\n const onClose = () => {\n if (res.writableFinished) return; // normal completion, not a disconnect\n clientGone = true;\n void reader.cancel().catch(() => {});\n };\n res.on('close', onClose);\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done || clientGone) break;\n if (!res.write(value)) {\n // Respect back-pressure so a slow/absent consumer can't unbounded-\n // buffer in the Node socket. Resolve on 'drain' OR on 'close'/\n // 'error' — a disconnect while back-pressured never fires 'drain',\n // so waiting only for it would hang this frame forever (leaking it\n // and pinning the reader for the long-lived `_events` stream). Race\n // the three and remove the losers so one-shot listeners don't pile\n // up across many drains.\n await new Promise<void>((resolve) => {\n const settle = () => {\n res.off('drain', settle);\n res.off('close', settle);\n res.off('error', settle);\n resolve();\n };\n res.once('drain', settle);\n res.once('close', settle);\n res.once('error', settle);\n });\n if (clientGone) break;\n }\n }\n } catch {\n // Reader cancelled (client gone) or write failed — stop streaming.\n } finally {\n res.off('close', onClose);\n }\n }\n\n if (!res.writableEnded) {\n res.end();\n }\n }\n\n /**\n * Generate fetch handler function (for serverless environments)\n */\n generateHandler(): (req: Request) => Promise<Response> {\n return (req) => this.handleRequest(req);\n }\n\n /**\n * Main request handler using native Bun APIs\n */\n private async handleRequest(req: Request): Promise<Response> {\n const url = new URL(req.url);\n\n // Handle CORS preflight\n if (req.method === 'OPTIONS' && this.config.enableCors) {\n return this.createCorsResponse(req);\n }\n\n // Handle custom routes first\n if (this.config.customRoutes) {\n for (const [path, handler] of Object.entries(this.config.customRoutes)) {\n if (url.pathname === `${this.config.basePath}${path}`) {\n const response = await handler(req);\n return this.addCorsHeaders(response, req);\n }\n }\n }\n\n // Change-feed route (#1758): auth-guarded, tenant-scoped cursor read\n // over the _smrt_changes log. Logic lives in ./changes-route.ts.\n if (url.pathname === `${this.config.basePath}/_changes`) {\n const response = await handleChangesRoute(req, {\n authMiddleware: this.config.authMiddleware,\n db: this.resolveContextDb(),\n });\n return this.addCorsHeaders(response, req);\n }\n\n // Live change-signal SSE route (#1763): auth-guarded, tenant-scoped\n // Server-Sent-Events stream of coarse signals (no row payloads). Logic\n // lives in ./events-route.ts. Wrapped in addCorsHeaders so a cross-origin\n // credentialed EventSource can subscribe when `allowCredentials` + an\n // allow-listed origin are configured (#1861); with the fail-closed default\n // (`allowCredentials: false`) this stays same-origin only, exactly as\n // before. The stream body passes through untouched — addCorsHeaders only\n // re-wraps headers. Fail-closed auth is unchanged: the CORS layer never\n // authorizes; it only lets an already-authorized cookie reach the guard.\n if (url.pathname === `${this.config.basePath}/_events`) {\n const response = await handleEventsRoute(req, {\n authMiddleware: this.config.authMiddleware,\n db: this.resolveContextDb(),\n manifestHash: this.resolveManifestHash(),\n maxSubscribers: this.config.eventsRoute?.maxSubscribers,\n });\n return this.addCorsHeaders(response, req);\n }\n\n // Handle object routes\n if (url.pathname.startsWith(this.config.basePath || '')) {\n const response = await this.handleObjectRoute(req, url);\n return this.addCorsHeaders(response, req);\n }\n\n // Not found\n return this.createErrorResponse(404, 'Not found');\n }\n\n /**\n * Handle CRUD routes for SMRT objects\n */\n private async handleObjectRoute(req: Request, url: URL): Promise<Response> {\n const pathParts = url.pathname\n .replace(this.config.basePath || '', '')\n .split('/')\n .filter(Boolean);\n\n if (pathParts.length === 0) {\n return this.createErrorResponse(400, 'Object type required');\n }\n\n // Reserved batch write contract route (#1759): POST {basePath}/sync/apply.\n if (\n pathParts.length === SYNC_APPLY_ROUTE_SEGMENTS.length &&\n SYNC_APPLY_ROUTE_SEGMENTS.every((segment, i) => pathParts[i] === segment)\n ) {\n if (req.method !== 'POST') {\n return this.createErrorResponse(405, 'Method not allowed');\n }\n return await this.handleSyncApply(req);\n }\n\n const objectType = pathParts[0];\n const objectId = pathParts[1];\n\n // Check for explicitly registered collection first\n if (this.collections.has(objectType)) {\n const collection = this.collections.get(objectType);\n if (!collection) throw new Error(`Collection ${objectType} not found`);\n\n const objectName = this.getCollectionObjectName(collection) || objectType;\n\n // Apply auth middleware if configured\n if (this.config.authMiddleware) {\n const authCheck = this.config.authMiddleware(\n objectName,\n req.method.toLowerCase(),\n );\n const authResult = await authCheck(req);\n if (authResult instanceof Response) {\n return authResult; // Auth failed\n }\n // Auth passed, use the potentially modified request\n req = authResult;\n } else if (!this.isRoutePublic(objectName, req.method)) {\n // Fail-closed (#1540): no auth middleware wired and the object isn't\n // marked `@smrt({ api: { public } })` → refuse rather than serve open.\n return this.createErrorResponse(401, 'Authentication required');\n }\n\n // Use registered collection directly\n return await this.executeCrudOperation(\n req,\n collection,\n objectId,\n url,\n objectName,\n );\n }\n\n // Fall back to auto-discovery via ObjectRegistry, matching the URL segment\n // against the canonical manifest `collection` value (#1794).\n const classInfo = this.findClassByCollectionSegment(objectType);\n\n if (!classInfo) {\n return this.createErrorResponse(\n 404,\n `Object type '${objectType}' not found`,\n );\n }\n\n // Apply auth middleware if configured\n if (this.config.authMiddleware) {\n const authCheck = this.config.authMiddleware(\n classInfo.name,\n req.method.toLowerCase(),\n );\n const authResult = await authCheck(req);\n if (authResult instanceof Response) {\n return authResult; // Auth failed\n }\n // Auth passed, use the potentially modified request\n req = authResult;\n } else if (!this.isRoutePublic(classInfo.name, req.method)) {\n // Fail-closed (#1540): see registered-collection branch above.\n return this.createErrorResponse(401, 'Authentication required');\n }\n\n // Get or create collection\n const collection = await this.getCollection(classInfo);\n\n return await this.executeCrudOperation(\n req,\n collection,\n objectId,\n url,\n classInfo.name,\n );\n }\n\n /**\n * Execute CRUD operation on a collection\n */\n private async executeCrudOperation(\n req: Request,\n collection: SmrtCollection<SmrtObject>,\n objectId: string | undefined,\n url: URL,\n objectName?: string,\n ): Promise<Response> {\n try {\n // Decorator-declared custom collection actions dispatch BEFORE CRUD\n // routing: without this, `POST /<collection>/<action>` would fall into\n // `handleCreate` with the action segment silently discarded (#2047).\n if (objectId && objectName) {\n const customResponse = await this.dispatchCustomCollectionAction(\n req,\n collection,\n objectId,\n url,\n objectName,\n );\n if (customResponse) {\n return customResponse;\n }\n }\n\n const action = this.getCrudAction(req.method, objectId);\n if (action && !this.isApiActionEnabled(objectName, action)) {\n return this.createErrorResponse(405, 'Method not allowed');\n }\n\n // Handle special /count endpoint\n if (objectId === 'count' && req.method === 'GET') {\n return await this.handleCount(collection, url.searchParams, objectName);\n }\n\n // Route to appropriate CRUD operation\n switch (req.method) {\n case 'GET':\n return objectId\n ? await this.handleGet(collection, objectId, req, objectName)\n : await this.handleList(\n collection,\n url.searchParams,\n req,\n objectName,\n );\n\n case 'POST':\n return await this.handleCreate(collection, req, objectName);\n\n case 'PUT':\n case 'PATCH':\n if (!objectId) {\n return this.createErrorResponse(\n 400,\n 'Object ID required for update',\n );\n }\n return await this.handleUpdate(collection, objectId, req, objectName);\n\n case 'DELETE':\n if (!objectId) {\n return this.createErrorResponse(\n 400,\n 'Object ID required for delete',\n );\n }\n return await this.handleDelete(collection, objectId);\n\n default:\n return this.createErrorResponse(405, 'Method not allowed');\n }\n } catch (error) {\n console.error('API Error:', error);\n return this.createErrorResponse(500, 'Internal server error');\n }\n }\n\n private getCrudAction(\n method: string,\n objectId: string | undefined,\n ): 'list' | 'get' | 'create' | 'update' | 'delete' | null {\n switch (method) {\n case 'GET':\n return objectId && objectId !== 'count' ? 'get' : 'list';\n case 'POST':\n return 'create';\n case 'PUT':\n case 'PATCH':\n return 'update';\n case 'DELETE':\n return 'delete';\n default:\n return null;\n }\n }\n\n /**\n * Fail-closed authorization posture (#1540). Returns true only when the\n * object opts out of auth via `@smrt({ api: { public } })`:\n * - `public: true` → all methods are public.\n * - `public: 'read'` → only safe (GET) methods are public.\n * Everything else requires an `authMiddleware` to be configured.\n */\n private isRoutePublic(\n objectName: string | undefined,\n method: string,\n ): boolean {\n if (!objectName) return false;\n const apiConfig = ObjectRegistry.getConfig(objectName)?.api;\n if (!apiConfig || typeof apiConfig !== 'object') return false;\n const publicAccess = (apiConfig as { public?: boolean | 'read' }).public;\n if (publicAccess === true) return true;\n if (publicAccess === 'read') return method.toUpperCase() === 'GET';\n return false;\n }\n\n private isApiActionEnabled(\n objectName: string | undefined,\n action: 'list' | 'get' | 'create' | 'update' | 'delete',\n ): boolean {\n if (!objectName) {\n return true;\n }\n\n const config = ObjectRegistry.getConfig(objectName);\n const apiConfig = config.api;\n\n if (apiConfig === false) {\n return false;\n }\n\n if (apiConfig && typeof apiConfig === 'object') {\n if (apiConfig.include && !apiConfig.include.includes(action)) {\n return false;\n }\n\n if (apiConfig.exclude?.includes(action)) {\n return false;\n }\n }\n\n return true;\n }\n\n private getCollectionObjectName(\n collection: SmrtCollection<SmrtObject>,\n ): string | undefined {\n // `_itemClass` lives on the instance (protected getter) or the collection\n // constructor (static). Read it through a structural shape rather than the\n // class's private surface; behavior is unchanged.\n const itemClass: SmrtObjectConstructor | undefined =\n (collection as unknown as { _itemClass?: SmrtObjectConstructor })\n ._itemClass ||\n (\n collection.constructor as unknown as {\n _itemClass?: SmrtObjectConstructor;\n }\n )?._itemClass;\n\n if (!itemClass) {\n return undefined;\n }\n\n const registered = ObjectRegistry.getClassByConstructor(itemClass);\n return registered?.qualifiedName || registered?.name || itemClass.name;\n }\n\n /**\n * Dispatch a decorator-declared custom COLLECTION-scoped action —\n * `@smrt({ api: { include: [...], routes: { action: { scope: 'collection',\n * method, path } } } })` — on the runtime transport (#2047). The generated\n * SvelteKit transport already dispatches these routes; this keeps the two\n * transports coherent for the same decorator metadata.\n *\n * Deliberately narrow, matching this router's URL shape: single-segment\n * collection-scoped paths only (multi-segment custom paths remain a\n * SvelteKit-transport feature), the action must be exposed by `api.include`\n * (and not excluded), and the HTTP method must match the route metadata.\n * Non-matching requests fall through to CRUD handling unchanged.\n *\n * Scope is resolved through the shared `resolveCustomActionMetadata`\n * contract, not read off the route alone: `scope` is OPTIONAL and defaults\n * to `collection` for statics and `item` for instance methods, so requiring\n * a literal `scope: 'collection'` would skip a valid static action and let\n * `POST /<collection>/<action>` fall through into `create`. The receiver\n * decides — a route-only scope cannot manufacture one — so an action with no\n * collection-hosted receiver falls through unless the route explicitly\n * declared `scope: 'collection'`, in which case it is declared-but-missing\n * and returns 501 rather than degrading into a malformed CRUD write.\n *\n * Arguments, failures, and result shaping all reuse the shared custom-action\n * helpers so this transport matches generated REST/CLI/MCP exactly: declared\n * parameters are projected (a zero-parameter action takes no body at all, an\n * `options` bag is passed through, named parameters are read off the body),\n * a returned `{ ok: false, ... }` failure becomes its requested non-2xx\n * status with a redacted payload, and success wraps as `{ action, result }`.\n */\n private async dispatchCustomCollectionAction(\n req: Request,\n collection: SmrtCollection<SmrtObject>,\n pathSegment: string,\n url: URL,\n objectName: string,\n ): Promise<Response | null> {\n const apiConfig = ObjectRegistry.getConfig(objectName)?.api;\n if (!apiConfig || typeof apiConfig !== 'object' || !apiConfig.routes) {\n return null;\n }\n\n for (const [actionName, routeConfig] of Object.entries(\n apiConfig.routes as Record<string, ApiCustomRouteConfig>,\n )) {\n const routePath = routeConfig?.path || actionName;\n if (routePath.includes('/') || routePath !== pathSegment) {\n continue;\n }\n const routeMethod = (routeConfig?.method || 'POST').toUpperCase();\n if (routeMethod !== req.method.toUpperCase()) {\n continue;\n }\n // Explicit exposure only: same include/exclude gating as the SvelteKit\n // generator applies to custom actions.\n if (apiConfig.include && !apiConfig.include.includes(actionName)) {\n continue;\n }\n if (apiConfig.exclude?.includes(actionName)) {\n continue;\n }\n\n // Receiver: an instance method on the registered collection, or a\n // static on the item class (the two hosts the generators support).\n const collectionMethod = (\n collection as unknown as Record<string, unknown>\n )[actionName];\n const itemConstructor = ObjectRegistry.getClass(objectName)\n ?.constructor as unknown as Record<string, unknown> | undefined;\n const staticMethod = itemConstructor?.[actionName];\n const isCollectionHosted = typeof collectionMethod === 'function';\n const isStaticHosted =\n !isCollectionHosted && typeof staticMethod === 'function';\n\n if (!isCollectionHosted && !isStaticHosted) {\n // Declared collection routes must not degrade into a CRUD write;\n // anything else (an item-scoped action reached at the collection URL,\n // or an unrelated segment) falls through unchanged.\n if (routeConfig?.scope === 'collection') {\n return this.createErrorResponse(\n 501,\n `Custom action '${actionName}' is declared but not implemented`,\n );\n }\n continue;\n }\n\n const metadata = resolveCustomActionMetadata({\n actionName,\n apiConfig,\n method: ObjectRegistry.getMethods(objectName)?.get(actionName),\n // A collection instance method is collection-hosted even when it is\n // not static; a static on the item class already defaults the same\n // way. Either receiver makes this route collection-targeted.\n defaultScope: 'collection',\n });\n if (metadata.scope !== 'collection') {\n continue;\n }\n\n const invoke = isCollectionHosted\n ? (args: unknown[]) =>\n (collectionMethod as (...a: unknown[]) => unknown).apply(\n collection,\n args,\n )\n : (args: unknown[]) =>\n (staticMethod as (...a: unknown[]) => unknown).apply(\n itemConstructor,\n args,\n );\n\n // An ABSENT body is \"no input\", not a malformed one — a zero-parameter\n // action is legitimately called with no body at all. A body that is\n // present but unparseable stays a 400 rather than degrading into a CRUD\n // write. GET reads the query string instead.\n let options: unknown;\n if (routeMethod === 'GET') {\n options = Object.fromEntries(url.searchParams.entries());\n } else {\n let rawBody = '';\n try {\n rawBody = await req.text();\n } catch {\n rawBody = '';\n }\n if (rawBody.trim() !== '') {\n try {\n options = JSON.parse(rawBody);\n } catch {\n return this.createErrorResponse(400, 'Invalid JSON body');\n }\n }\n }\n\n // Project declared parameters only when the registry actually knows\n // them. Without metadata the historical single-options call is kept\n // verbatim, so an opaque body (an array, or any non-record payload an\n // existing action already accepts) still arrives unchanged rather than\n // being silently normalized away.\n const invocationArgs = metadata.parameters\n ? buildCustomActionInvocationArgs(metadata, {\n ...(options &&\n typeof options === 'object' &&\n !Array.isArray(options)\n ? (options as Record<string, unknown>)\n : {}),\n options,\n })\n : [options];\n\n const result = await invoke(invocationArgs);\n\n const failure = normalizeCustomActionFailure(result);\n if (failure) {\n return this.createJsonResponse({ error: failure }, failure.status);\n }\n\n return this.createJsonResponse({\n action: actionName,\n result: this.sanitizeActionResult(result),\n });\n }\n\n return null;\n }\n\n /**\n * Public-safe projection for custom-action results, mirroring the generated\n * SvelteKit routes' `toPublicResult`: a `SmrtObject` (anything exposing\n * `toPublicJSON`) becomes its public projection with the caller's\n * permissions, arrays and plain objects are walked, non-plain instances and\n * primitives pass through, and a cycle guard breaks reference loops.\n */\n private sanitizeActionResult(\n value: unknown,\n seen: WeakSet<object> = new WeakSet(),\n ): unknown {\n if (value === null || typeof value !== 'object') {\n return value;\n }\n if (seen.has(value)) {\n return null;\n }\n const serializable = value as {\n toPublicJSON?: (options?: PublicJsonOptions) => unknown;\n };\n if (typeof serializable.toPublicJSON === 'function') {\n seen.add(value);\n return this.sanitizeActionResult(\n serializable.toPublicJSON(this.getPublicJsonOptions()),\n seen,\n );\n }\n if (Array.isArray(value)) {\n seen.add(value);\n return value.map((entry) => this.sanitizeActionResult(entry, seen));\n }\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null) {\n return value;\n }\n seen.add(value);\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n out[key] = this.sanitizeActionResult(entry, seen);\n }\n return out;\n }\n\n /**\n * Fail-closed tenant read scope (#1782).\n *\n * A `@TenantScoped` model served over a public/anonymous read has no ambient\n * tenant context, so the tenancy interceptor (optional mode) passes the query\n * through UNFILTERED and returns every tenant's rows. When tenancy is enabled\n * but no tenant is active, this returns a `{ tenantId: null }` filter so reads\n * fail closed to NULL-tenant (global) rows only — mirroring the dispatch\n * resolver's \"enforced, no active tenant → global rows only\" convention\n * (`resolveDispatchTenantScope` is the core-level trust anchor tenancy fills\n * in; core cannot import tenancy directly). Returns undefined when a tenant IS\n * active (the interceptor filters by it) or tenancy is disabled (no isolation\n * to enforce).\n *\n * Tenant scoping is recognized across BOTH registration forms (#1782): the\n * `@smrt({ tenantScoped })` config / manifest-merged form via\n * `ObjectRegistry.isTenantScoped`, and the standalone `@TenantScoped()`\n * decorator via the tenancy-filled `isTenantScopedClassResolved` hook — so a\n * `@TenantScoped()`-only public model can't slip past the guard regardless of\n * manifest timing.\n */\n private resolveTenantReadScope(\n objectName?: string,\n ): { tenantId: null } | undefined {\n if (\n !objectName ||\n !(\n ObjectRegistry.isTenantScoped(objectName) ||\n !!ObjectRegistry.getConfig(objectName)?.tenantScoped ||\n isTenantScopedClassResolved(objectName)\n )\n ) {\n return undefined;\n }\n const scope = resolveDispatchTenantScope();\n return scope.enforced && scope.tenantId === null\n ? { tenantId: null }\n : undefined;\n }\n\n /**\n * Merge the fail-closed tenant read scope (#1782) into a query's WHERE clause.\n * When the scope is active (global-only), any client-supplied tenant filter is\n * dropped first so a `?tenantId=...` / `?tenant_id[ne]=...` query param can\n * never widen the scope, then NULL-tenant is forced. Returns the original\n * `where` untouched when the scope is inactive.\n */\n private applyTenantReadScope(\n objectName: string | undefined,\n where: Record<string, string | string[]> | undefined,\n ): Record<string, unknown> | undefined {\n const scope = this.resolveTenantReadScope(objectName);\n if (!scope) {\n return where;\n }\n const cleaned: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(where ?? {})) {\n // A key may carry an operator suffix, e.g. \"tenant_id !=\" — match on the\n // field portion so no operator variant slips a client tenant filter past.\n const field = key.split(/\\s+/)[0];\n if (field === 'tenantId' || field === 'tenant_id') {\n continue;\n }\n cleaned[key] = value;\n }\n cleaned.tenantId = null;\n return cleaned;\n }\n\n /**\n * Handle GET /objects/:id\n */\n private async handleGet(\n collection: SmrtCollection<SmrtObject>,\n id: string,\n req: Request,\n objectName?: string,\n ): Promise<Response> {\n const cacheControl = this.resolveReadCachePolicy(objectName);\n\n if (this.hasReadPermissionFields(objectName)) {\n // Field-level read permissions make the response body vary by caller\n // permissions, so the validator must cover the redacted body returned to\n // this caller rather than only the table version.\n const scope = this.resolveTenantReadScope(objectName);\n const object = scope\n ? await collection.get({ id, ...scope })\n : await collection.get(id);\n if (!object) {\n return this.createErrorResponse(404, 'Object not found');\n }\n return conditionalJsonResponse(\n req,\n this.toPublicData(object),\n cacheControl,\n );\n }\n\n // ETag v2 (#1765): compute the table-version ETag first. A CONCRETE\n // If-None-Match short-circuits into a 304 BEFORE the row is fetched — a\n // delete advances the table version (tombstone), so a stale cached\n // representation of a since-deleted row can never concretely match. A\n // wildcard `*` is deferred until AFTER the fetch confirms the row exists,\n // so a missing row still returns 404 (not a false 304).\n const etag = await this.computeReadEtag(collection, req, objectName);\n const ifNoneMatch = req.headers.get('if-none-match');\n const notModified = (): Response =>\n new Response(null, {\n status: 304,\n headers: { 'Cache-Control': cacheControl, ETag: etag },\n });\n if (ifNoneMatchHasConcreteMatch(ifNoneMatch, etag)) {\n return notModified();\n }\n\n // #1782: scope a public/anonymous read of a tenant-scoped model to global\n // (NULL-tenant) rows when no tenant context is active.\n const scope = this.resolveTenantReadScope(objectName);\n const object = scope\n ? await collection.get({ id, ...scope })\n : await collection.get(id);\n if (!object) {\n return this.createErrorResponse(404, 'Object not found');\n }\n // Row exists → a wildcard `*` may now be honored as a 304.\n if (ifNoneMatchSatisfied(ifNoneMatch, etag)) {\n return notModified();\n }\n return new Response(JSON.stringify(this.toPublicData(object)), {\n status: 200,\n headers: {\n 'Cache-Control': cacheControl,\n 'Content-Type': 'application/json',\n ETag: etag,\n },\n });\n }\n\n /**\n * Handle GET /objects (list with query params)\n */\n private async handleList(\n collection: SmrtCollection<SmrtObject>,\n params: URLSearchParams,\n req: Request,\n objectName?: string,\n ): Promise<Response> {\n const cacheControl = this.resolveReadCachePolicy(objectName);\n\n const buildPayload = async () => {\n const limit = Number.parseInt(params.get('limit') || '50', 10);\n const offset = Number.parseInt(params.get('offset') || '0', 10);\n const orderBy = params.get('orderBy') || 'created_at DESC';\n\n // Build where clause from query params\n // Convert REST-style operators (price[gt]) to SQL-style (price >)\n const where: Record<string, string | string[]> = {};\n for (const [key, value] of params.entries()) {\n if (!['limit', 'offset', 'orderBy'].includes(key)) {\n // Parse REST operator format: field[operator]\n const match = key.match(/^(.+)\\[(.+)\\]$/);\n if (match) {\n const field = match[1];\n const operator = match[2];\n // Map REST operators to SQL operators\n const operatorMap: Record<string, string> = {\n gt: '>',\n gte: '>=',\n lt: '<',\n lte: '<=',\n ne: '!=',\n in: 'in',\n like: 'like',\n };\n const sqlOperator = operatorMap[operator] || operator;\n const sqlKey = `${field} ${sqlOperator}`;\n // Handle 'in' operator - convert comma-separated string to array\n where[sqlKey] = operator === 'in' ? value.split(',') : value;\n } else {\n where[key] = value;\n }\n }\n }\n\n // #1782: fail closed to global (NULL-tenant) rows for a public/anonymous\n // read of a tenant-scoped model with no active tenant context.\n const scopedWhere = this.applyTenantReadScope(objectName, where);\n\n const objects = await collection.list({\n where:\n scopedWhere && Object.keys(scopedWhere).length > 0\n ? scopedWhere\n : undefined,\n limit,\n offset,\n orderBy,\n });\n\n return objects.map((object: SmrtObject) => this.toPublicData(object));\n };\n\n if (this.hasReadPermissionFields(objectName)) {\n // Field-level read permissions make the response body vary by caller\n // permissions, so use the v1 body-hash path over the redacted payload.\n return conditionalJsonResponse(req, await buildPayload(), cacheControl);\n }\n\n // ETag v2 (#1765): resolve the policy + table-version ETag first, then\n // hand the list query to versionConditionalResponse as a thunk. On a\n // matching If-None-Match it returns a 304 and the thunk — the collection\n // query — never runs, so an unchanged table revalidates with no table scan.\n const etag = await this.computeReadEtag(collection, req, objectName);\n return versionConditionalResponse(req, etag, cacheControl, buildPayload);\n }\n\n /**\n * Handle GET /objects/count\n */\n private async handleCount(\n collection: SmrtCollection<SmrtObject>,\n params: URLSearchParams,\n objectName?: string,\n ): Promise<Response> {\n // Build where clause from query params (same logic as handleList)\n const where: Record<string, string | string[]> = {};\n for (const [key, value] of params.entries()) {\n // Parse REST operator format: field[operator]\n const match = key.match(/^(.+)\\[(.+)\\]$/);\n if (match) {\n const field = match[1];\n const operator = match[2];\n // Map REST operators to SQL operators\n const operatorMap: Record<string, string> = {\n gt: '>',\n gte: '>=',\n lt: '<',\n lte: '<=',\n ne: '!=',\n in: 'in',\n like: 'like',\n };\n const sqlOperator = operatorMap[operator] || operator;\n const sqlKey = `${field} ${sqlOperator}`;\n // Handle 'in' operator - convert comma-separated string to array\n where[sqlKey] = operator === 'in' ? value.split(',') : value;\n } else {\n where[key] = value;\n }\n }\n\n // #1782: a count leaks cross-tenant cardinality just as a list leaks rows,\n // so apply the same fail-closed global scope for anonymous tenant reads.\n const scopedWhere = this.applyTenantReadScope(objectName, where);\n\n const count = await collection.count({\n where:\n scopedWhere && Object.keys(scopedWhere).length > 0\n ? scopedWhere\n : undefined,\n });\n\n return this.createJsonResponse({ count });\n }\n\n /**\n * Handle POST /objects\n */\n private async handleCreate(\n collection: SmrtCollection<SmrtObject>,\n req: Request,\n objectName?: string,\n ): Promise<Response> {\n const data = this.applyWritablePolicy(objectName, await req.json());\n const object = await collection.create({ ...data, _skipLoad: true });\n await object.save();\n return this.createJsonResponse(this.toPublicData(object), 201);\n }\n\n /**\n * Handle PUT/PATCH /objects/:id\n */\n private async handleUpdate(\n collection: SmrtCollection<SmrtObject>,\n id: string,\n req: Request,\n objectName?: string,\n ): Promise<Response> {\n const data = this.applyWritablePolicy(objectName, await req.json());\n const object = await collection.get(id);\n\n if (!object) {\n return this.createErrorResponse(404, 'Object not found');\n }\n\n // Update object properties\n Object.assign(object, data);\n await object.save();\n\n return this.createJsonResponse(this.toPublicData(object));\n }\n\n /**\n * Handle DELETE /objects/:id\n */\n private async handleDelete(\n collection: SmrtCollection<SmrtObject>,\n id: string,\n ): Promise<Response> {\n const object = await collection.get(id);\n\n if (!object) {\n return this.createErrorResponse(404, 'Object not found');\n }\n\n await object.delete();\n return new Response(null, { status: 204 });\n }\n\n /**\n * Handle POST /sync/apply — the idempotent batch write contract (#1759).\n * All processing lives in `sync/apply.ts`; this method only adapts the\n * generator's existing collection resolution, auth, action gating, and\n * writable policy into a {@link SyncApplyTarget} per item.\n */\n private async handleSyncApply(req: Request): Promise<Response> {\n // Buffer the body once. Request bodies are single-read streams, and the\n // per-item auth middleware below must receive a readable body exactly as\n // it does on CRUD routes (where auth runs before parsing) — so each\n // middleware invocation gets a fresh Request rebuilt from this buffer.\n let rawBody: string;\n let body: unknown;\n try {\n rawBody = await req.text();\n body = JSON.parse(rawBody);\n } catch {\n return this.createErrorResponse(400, 'Invalid JSON body');\n }\n\n const outcome = await processSyncApplyBatch(body, {\n resolveTarget: (objectSegment) =>\n this.resolveSyncApplyTarget(objectSegment, req, rawBody),\n });\n return this.createJsonResponse(outcome.body, outcome.status);\n }\n\n /**\n * Resolve a sync item's `object` segment exactly like `handleObjectRoute`\n * resolves a CRUD URL segment (registered collections first, then registry\n * auto-discovery), and wrap the generator's per-object machinery.\n */\n private async resolveSyncApplyTarget(\n objectSegment: string,\n req: Request,\n rawBody: string,\n ): Promise<SyncApplyTarget | null> {\n let collection: SmrtCollection<SmrtObject> | null = null;\n let objectName: string | null = null;\n\n const registered = this.collections.get(objectSegment);\n if (registered) {\n collection = registered;\n objectName = this.getCollectionObjectName(registered) || objectSegment;\n } else {\n // Same canonical-`collection` match as the CRUD path so a client and the\n // batch contract resolve identical segments (#1794).\n const info = this.findClassByCollectionSegment(objectSegment);\n if (info) {\n collection = await this.getCollection(info);\n objectName = info.name;\n }\n }\n\n if (!collection || !objectName) {\n return null;\n }\n\n const resolvedName = objectName;\n const resolvedCollection = collection;\n return {\n objectName: resolvedName,\n collection: resolvedCollection,\n isOpAllowed: (op: SyncApplyOp) =>\n this.isApiActionEnabled(resolvedName, op),\n authorize: async (op: SyncApplyOp) => {\n if (this.config.authMiddleware) {\n const verb =\n op === 'create' ? 'post' : op === 'update' ? 'put' : 'delete';\n const authCheck = this.config.authMiddleware(resolvedName, verb);\n // Fresh Request per invocation: the batch handler already consumed\n // the original body, and middleware may read it (body-based auth,\n // request signing) exactly as it can on CRUD routes.\n const authResult = await authCheck(\n new Request(req.url, {\n method: req.method,\n headers: req.headers,\n body: rawBody,\n }),\n );\n if (authResult instanceof Response) {\n return authResult.status === 401 ? 'auth_required' : 'forbidden';\n }\n return 'ok';\n }\n // Fail-closed (#1540): every sync op is mutating, so only\n // `@smrt({ api: { public: true } })` objects apply without auth.\n return this.isRoutePublic(resolvedName, 'POST')\n ? 'ok'\n : 'auth_required';\n },\n prepare: (payload) => this.applyWritablePolicy(resolvedName, payload),\n };\n }\n\n /**\n * Get or create collection instance\n */\n private async getCollection(\n classInfo: RegisteredClass,\n ): Promise<SmrtCollection<SmrtObject>> {\n if (!this.collections.has(classInfo.name)) {\n // `collectionConstructor` is typed optional on RegisteredClass, but the\n // auto-discovery path only reaches here for classes that declare one.\n // Narrow to the non-optional constructor type before instantiating.\n const ctor = classInfo.collectionConstructor as NonNullable<\n RegisteredClass['collectionConstructor']\n >;\n const collection = new ctor({\n ai: this.context.ai,\n db: this.context.db,\n });\n // Await initialize() so the auto-discovered collection is actually usable\n // (its DB is wired). Without this, list()/get() throw \"Database accessed\n // before initialization\" — a latent bug that was masked while the\n // generated client's plural URLs never matched the singular-only\n // auto-discovery segment (#1794). The explicit-registerCollection() path\n // receives an already-initialized collection from the caller, so this\n // only affects the auto-discovery factory.\n await collection.initialize();\n this.collections.set(classInfo.name, collection);\n }\n const collection = this.collections.get(classInfo.name);\n if (!collection) throw new Error(`Collection ${classInfo.name} not found`);\n return collection;\n }\n\n /**\n * Mass-assignment guard (#1540): strip framework/server-managed and\n * `@field({ readonly: true })` fields from a create/update body, and — when an\n * `@smrt({ api: { writable: [...] } })` allowlist is set — intersect with it.\n */\n private applyWritablePolicy(\n objectName: string | undefined,\n data: unknown,\n ): Record<string, unknown> {\n if (!data || typeof data !== 'object') {\n return {};\n }\n\n const serverManaged = new Set([\n 'id',\n 'tenantId',\n 'tenant_id',\n 'createdAt',\n 'created_at',\n 'updatedAt',\n 'updated_at',\n ]);\n\n const readonly = new Set<string>();\n let writable: string[] | null = null;\n\n if (objectName) {\n const apiConfig = ObjectRegistry.getConfig(objectName)?.api;\n if (\n apiConfig &&\n typeof apiConfig === 'object' &&\n Array.isArray((apiConfig as { writable?: unknown }).writable)\n ) {\n writable = (apiConfig as { writable: string[] }).writable;\n }\n\n for (const [name, def] of ObjectRegistry.getFields(objectName)) {\n if (def && (def.readonly === true || def._meta?.readonly === true)) {\n readonly.add(name);\n }\n }\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(data)) {\n if (key.startsWith('_')) continue;\n if (serverManaged.has(key)) continue;\n if (readonly.has(key)) continue;\n if (writable && !writable.includes(key)) continue;\n result[key] = value;\n }\n return result;\n }\n\n /**\n * Serialize a SmrtObject for a network response, excluding sensitive fields\n * (#1540). Falls back to the value unchanged for non-SmrtObject payloads.\n */\n private toPublicData(object: unknown): unknown {\n const serializable = object as {\n toPublicJSON?: (options?: PublicJsonOptions) => unknown;\n } | null;\n return typeof serializable?.toPublicJSON === 'function'\n ? serializable.toPublicJSON(this.getPublicJsonOptions())\n : object;\n }\n\n private getPublicJsonOptions(): PublicJsonOptions {\n return { permissions: this.context.permissions };\n }\n\n /**\n * Resolve the Cache-Control policy for a generated read and fire the\n * one-time policy warnings (#1757): private + revalidatable by default;\n * shared `s-maxage` only for public models that opt in; always private for\n * tenant-scoped models, whose bodies vary with tenant context that URL-keyed\n * shared caches cannot see. Field read-permission models are also private\n * because the body varies by caller permissions.\n */\n private resolveReadCachePolicy(objectName: string | undefined): string {\n const config = objectName\n ? ObjectRegistry.getConfig(objectName)\n : undefined;\n const apiConfig = config?.api;\n // Canonical accessor covers both `@smrt({ tenantScoped })` and the\n // manifest-merged `@TenantScoped()` decorator form; the raw config flag is\n // a belt-and-braces fallback for registrations not yet normalized.\n const tenantScoped = objectName\n ? ObjectRegistry.isTenantScoped(objectName) || !!config?.tenantScoped\n : false;\n const permissionScoped = this.hasReadPermissionFields(objectName);\n if (objectName) {\n warnIfSharedCacheNeutralized(\n objectName,\n apiConfig,\n tenantScoped,\n permissionScoped,\n );\n warnIfTenantScopedPublicRead(objectName, apiConfig, tenantScoped);\n }\n return resolveReadCacheControl(apiConfig, {\n tenantScoped,\n permissionScoped,\n });\n }\n\n private hasReadPermissionFields(objectName: string | undefined): boolean {\n if (!objectName) return false;\n for (const fields of this.getFieldMapsForPublicPolicy(objectName)) {\n for (const [, def] of fields) {\n if (\n typeof def?.readPermission === 'string' ||\n typeof def?._meta?.readPermission === 'string'\n ) {\n return true;\n }\n }\n }\n return false;\n }\n\n private getFieldMapsForPublicPolicy(\n objectName: string,\n ): Array<ReturnType<typeof ObjectRegistry.getFields>> {\n const registered = ObjectRegistry.getClass(objectName);\n const className =\n registered?.qualifiedName ?? registered?.name ?? objectName;\n const fieldMaps: Array<ReturnType<typeof ObjectRegistry.getFields>> = [\n registered?.inheritedFields || ObjectRegistry.getFields(className),\n ];\n const stiBase = ObjectRegistry.getSTIBase(className);\n if (stiBase) {\n fieldMaps.push(\n ObjectRegistry.getClass(stiBase)?.inheritedFields ||\n ObjectRegistry.getFields(stiBase),\n );\n for (const descendant of ObjectRegistry.getDescendants(stiBase)) {\n fieldMaps.push(\n ObjectRegistry.getClass(descendant)?.inheritedFields ||\n ObjectRegistry.getFields(descendant),\n );\n }\n }\n return fieldMaps;\n }\n\n /**\n * Compute the ETag v2 (#1765) for a generated read: the table's change-feed\n * version ({@link getTableVersion}) keyed by the request representation, so a\n * matching `If-None-Match` can short-circuit into a 304 BEFORE the collection\n * query runs. The representation folds in the active tenant for tenant-scoped\n * models so one tenant's cached ETag never satisfies another's read. When an\n * web-collection manifest hash is folded into the digest (#1764), so a\n * shape-only deploy busts every read validator. An explicit\n * `APIConfig.manifestHash` wins; otherwise the hash is computed from the\n * runtime registry on first use (#1862).\n */\n private async computeReadEtag(\n collection: SmrtCollection<SmrtObject>,\n req: Request,\n objectName: string | undefined,\n ): Promise<string> {\n const version = await getTableVersion(collection.db, collection.tableName);\n const representation = canonicalReadRepresentation(\n req,\n this.readTenantDiscriminator(objectName),\n );\n // Salt the ETag with the web-collection shape digest (#1764) so a\n // shape-only deploy busts every read validator. Runtime APIGenerator\n // deployments compute the hash from ObjectRegistry when no explicit override\n // is configured (#1862).\n return computeTableVersionEtag(\n version,\n representation,\n this.resolveManifestHash(),\n );\n }\n\n private resolveManifestHash(): string {\n if (this.config.manifestHash !== undefined) {\n return this.config.manifestHash;\n }\n this.runtimeManifestHash ??= computeRuntimeWebManifestHash();\n return this.runtimeManifestHash;\n }\n\n /**\n * A per-tenant ETag discriminator for tenant-scoped models: the active tenant\n * id (or `global`) so tenant A's cached ETag never satisfies tenant B's read\n * of the same table and params. `undefined` for non-tenant-scoped models,\n * whose bodies do not vary by tenant.\n */\n private readTenantDiscriminator(objectName?: string): string | undefined {\n if (!objectName) return undefined;\n const tenantScoped =\n ObjectRegistry.isTenantScoped(objectName) ||\n !!ObjectRegistry.getConfig(objectName)?.tenantScoped ||\n isTenantScopedClassResolved(objectName);\n if (!tenantScoped) return undefined;\n // Shared with the generated SvelteKit route so both transports key the ETag\n // on the active tenant identically (cross-tenant false-304 guard).\n return resolveTenantEtagDiscriminator();\n }\n\n /**\n * Create JSON response with proper headers\n */\n private createJsonResponse(data: unknown, status = 200): Response {\n return new Response(JSON.stringify(data), {\n status,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n }\n\n /**\n * Create error response\n */\n private createErrorResponse(status: number, message: string): Response {\n return new Response(JSON.stringify({ error: message }), {\n status,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n }\n\n /**\n * Resolve the allowed `Access-Control-Allow-Origin` for a request (#1540).\n * Returns the request's `Origin` only when it is in the configured allowlist;\n * never `*`. Returns null when CORS should not be applied.\n */\n private resolveAllowedOrigin(req: Request): string | null {\n if (!this.config.enableCors) return null;\n const allowed = this.config.allowedOrigins;\n if (!allowed || allowed.length === 0) return null;\n const origin = req.headers.get('origin');\n return origin && allowed.includes(origin) ? origin : null;\n }\n\n /**\n * Whether to emit `Access-Control-Allow-Credentials: true` (#1861). Only when\n * explicitly opted in AND an origin actually resolved — credentials are never\n * paired with a wildcard/absent origin (`resolveAllowedOrigin` already never\n * returns `*`).\n */\n private shouldAllowCredentials(): boolean {\n return this.config.allowCredentials === true;\n }\n\n /**\n * Create CORS preflight response\n */\n private createCorsResponse(req: Request): Response {\n const headers: Record<string, string> = {\n 'Access-Control-Allow-Methods': 'GET,POST,PUT,PATCH,DELETE,OPTIONS',\n // `Last-Event-ID` is allow-listed for the `_events` SSE route (#1861): a\n // fetch-based cross-origin SSE client that resumes from a cursor sends it\n // as a request header, which is not CORS-safelisted and would otherwise\n // fail preflight. Harmless on the other routes, which ignore it.\n 'Access-Control-Allow-Headers':\n 'Content-Type,Authorization,Last-Event-ID',\n 'Access-Control-Max-Age': '86400',\n };\n const origin = this.resolveAllowedOrigin(req);\n if (origin) {\n headers['Access-Control-Allow-Origin'] = origin;\n headers.Vary = 'Origin';\n if (this.shouldAllowCredentials()) {\n headers['Access-Control-Allow-Credentials'] = 'true';\n }\n }\n return new Response(null, { status: 200, headers });\n }\n\n /**\n * Add CORS headers to response\n */\n private addCorsHeaders(response: Response, req: Request): Response {\n const origin = this.resolveAllowedOrigin(req);\n if (!origin) return response;\n\n const headers = new Headers(response.headers);\n headers.set('Access-Control-Allow-Origin', origin);\n headers.set('Vary', 'Origin');\n headers.set(\n 'Access-Control-Allow-Methods',\n 'GET,POST,PUT,PATCH,DELETE,OPTIONS',\n );\n // `Last-Event-ID` so a fetch-based cross-origin SSE client can resume the\n // `_events` stream from a cursor (#1861); see createCorsResponse.\n headers.set(\n 'Access-Control-Allow-Headers',\n 'Content-Type,Authorization,Last-Event-ID',\n );\n // Credentialed CORS (#1861): only when opted in, and only alongside a\n // concrete echoed origin (never `*`) so cookies can flow to an allow-listed\n // cross-origin client (e.g. a credentialed EventSource on `_events`).\n if (this.shouldAllowCredentials()) {\n headers.set('Access-Control-Allow-Credentials', 'true');\n }\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n }\n\n /**\n * Resolve a URL/collection segment to a registered class via auto-discovery.\n *\n * The segment IS the canonical `collection` value from the manifest\n * (`RegisteredClass.collection`, e.g. `products` for `Product`) — the same\n * value the generated client, the SvelteKit route generator, and the registry\n * all derive. Match it VERBATIM; do not re-pluralize. The previous\n * implementation pluralized both the URL segment and the class name and\n * compared them, turning an already-plural client URL (`/products`) into\n * `productses`, so the generated client 404'd against auto-discovered routes\n * (#1794). Shared by the CRUD path and the `sync/apply` batch path so they can\n * never drift.\n *\n * @param segment - The URL/collection path segment (e.g. `products`).\n * @returns The matching registered class, or null if none matches.\n */\n private findClassByCollectionSegment(\n segment: string,\n ): RegisteredClass | null {\n for (const [key, info] of ObjectRegistry.getAllClasses()) {\n // Primary match: the canonical manifest `collection` segment.\n if (info.collection === segment) {\n return info;\n }\n // Back-compat fallback for classes registered without a `collection`\n // (inline/test stubs): derive the plural segment from the simple name and\n // compare to the raw URL segment. Issue #951: use the simple name\n // (info.name), not the qualified map key.\n if (\n !info.collection &&\n this.pluralize((info.name || key).toLowerCase()) === segment\n ) {\n return info;\n }\n }\n return null;\n }\n\n /**\n * Simple pluralization (basic implementation)\n */\n private pluralize(word: string): string {\n if (word.endsWith('y')) {\n return `${word.slice(0, -1)}ies`;\n }\n if (word.endsWith('s') || word.endsWith('sh') || word.endsWith('ch')) {\n return `${word}es`;\n }\n return `${word}s`;\n }\n}\n\n// REST Server Utilities\n\nexport interface RestServerConfig extends APIConfig {\n healthCheck?: {\n enabled?: boolean;\n path?: string;\n customChecks?: (() => Promise<boolean>)[];\n };\n}\n\n/**\n * Create REST server with health checks using Bun\n */\nexport function createRestServer(\n objects: (typeof SmrtObject)[],\n context: APIContext = {},\n config: RestServerConfig = {},\n): { server: http.Server; url: string } {\n // Register objects if not already registered\n objects.forEach((obj) => {\n if (!ObjectRegistry.hasClass(obj.name)) {\n console.warn(`Object ${obj.name} not registered with @smrt decorator`);\n }\n });\n\n const generator = new APIGenerator(config, context);\n const { server, url } = generator.createServer();\n\n console.log(`🚀 smrt REST API server running at ${url}`);\n\n return { server, url };\n}\n\n/**\n * Start server with graceful shutdown\n */\nexport function startRestServer(\n objects: (typeof SmrtObject)[],\n context: APIContext = {},\n config: RestServerConfig = {},\n): Promise<() => Promise<void>> {\n return new Promise((resolve) => {\n const { server, url } = createRestServer(objects, context, config);\n\n // Graceful shutdown function\n const shutdown = (): Promise<void> => {\n return new Promise((shutdownResolve) => {\n console.log('🛑 Shutting down server gracefully...');\n // Node's http.Server#close stops accepting new connections and invokes\n // the callback once in-flight ones drain. (The prior `.stop()` was a\n // Bun-era API absent on http.Server — it would have thrown.)\n server.close(() => {\n console.log('✅ Server shut down complete');\n shutdownResolve();\n });\n });\n };\n\n // Handle shutdown signals\n process.on('SIGTERM', shutdown);\n process.on('SIGINT', shutdown);\n\n resolve(shutdown);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAmHA,SAAS,2BACP,QACiC;CACjC,MAAM,SAA0C,CAAC;CACjD,KAAK,MAAM,CAAC,MAAM,UAAU,QAAQ;EAClC,IAAI,CAAC,SAAS,OAAO,MAAM,SAAS,UAAU;EAC9C,MAAM,eACJ,MAAM,YAAY,KAAA,IAAY,MAAM,UAAU,MAAM,OAAO;EAC7D,OAAO,QAAQ;GACb,MAAM,MAAM;GACZ,GAAI,MAAM,aAAa,KAAA,IAAY,EAAE,UAAU,MAAM,SAAS,IAAI,CAAC;GACnE,GAAI,iBAAiB,KAAA,IAAY,EAAE,SAAS,aAAa,IAAI,CAAC;GAC9D,GAAI,MAAM,YAAY,KAAA,IAAY,EAAE,SAAS,MAAM,QAAQ,IAAI,CAAC;GAChE,GAAI,MAAM,cAAc,KAAA,IAAY,EAAE,WAAW,MAAM,UAAU,IAAI,CAAC;GACtE,GAAI,MAAM,cAAc,KAAA,IAAY,EAAE,WAAW,MAAM,UAAU,IAAI,CAAC;GACtE,GAAI,MAAM,aAAa,KAAA,IAAY,EAAE,UAAU,MAAM,SAAS,IAAI,CAAC;GACnE,GAAI,MAAM,mBAAmB,KAAA,IACzB,EAAE,gBAAgB,MAAM,eAAe,IACvC,CAAC;GACL,GAAI,MAAM,UAAU,KAAA,IAAY,EAAE,OAAO,MAAM,MAAM,IAAI,CAAC;EAC5D;CACF;CACA,OAAO;AACT;AAEA,SAAS,4BACP,SACkC;CAClC,OAAO,OAAO,YAAY,WAAW,CAAC,CAAC;AACzC;AAEA,SAAS,+BAA+B,WAA2B;CACjE,MA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