hono-crud 0.13.12 → 0.13.13

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.
Files changed (43) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/api-version/index.d.ts +19 -13
  3. package/dist/api-version/index.js +1 -1
  4. package/dist/audit/index.d.ts +1 -1
  5. package/dist/auth/index.d.ts +3 -3
  6. package/dist/auth/index.js +1 -1
  7. package/dist/chunk-BSQHHUG2.js +11 -0
  8. package/dist/chunk-CPIXFQGF.js +1 -0
  9. package/dist/chunk-EC6JI76L.js +1 -0
  10. package/dist/chunk-IOWLCLF6.js +1 -0
  11. package/dist/chunk-JITAQDZZ.js +1 -0
  12. package/dist/chunk-OLSYHJGK.js +1 -0
  13. package/dist/chunk-RVKM7SXJ.js +1 -0
  14. package/dist/{chunk-4KMRJFCY.js → chunk-TILULOEV.js} +1 -1
  15. package/dist/config/index.d.ts +4 -4
  16. package/dist/config/index.js +1 -1
  17. package/dist/functional/index.d.ts +3 -6
  18. package/dist/functional/index.js +1 -1
  19. package/dist/{helpers--TefHzCj.d.ts → helpers-CJpjtX-9.d.ts} +1 -1
  20. package/dist/{index-B1PgVRqD.d.ts → index-DFYo-Us4.d.ts} +5 -9
  21. package/dist/{index-B3hpRLJg.d.ts → index-DgV651ue.d.ts} +20 -18
  22. package/dist/{index-Cjm4QRuE.d.ts → index-bMu1-qqN.d.ts} +7 -7
  23. package/dist/index.d.ts +9 -9
  24. package/dist/index.js +1 -1
  25. package/dist/internal.d.ts +11 -11
  26. package/dist/internal.js +1 -1
  27. package/dist/logging/index.js +1 -1
  28. package/dist/multi-tenant/index.d.ts +17 -17
  29. package/dist/multi-tenant/index.js +1 -1
  30. package/dist/{route-BHXjgMro.d.ts → route-C6T6CTON.d.ts} +1 -1
  31. package/dist/storage/index.d.ts +2 -2
  32. package/dist/storage/index.js +1 -1
  33. package/dist/{types-DKPLu-9p.d.ts → types-tthfGTqv.d.ts} +19 -6
  34. package/dist/{types-O7tEXxjA.d.ts → types-zAClTFVv.d.ts} +1 -1
  35. package/dist/versioning/index.d.ts +1 -1
  36. package/package.json +1 -1
  37. package/dist/chunk-2T3DGA4L.js +0 -1
  38. package/dist/chunk-5F2VPG4B.js +0 -11
  39. package/dist/chunk-A7ZLZUMJ.js +0 -1
  40. package/dist/chunk-DALXO46J.js +0 -1
  41. package/dist/chunk-H5D4D6Y7.js +0 -1
  42. package/dist/chunk-KTDHELSH.js +0 -1
  43. package/dist/chunk-WKCG5D5U.js +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.13.13
4
+
5
+ ### Patch Changes
6
+
7
+ - 66f789c: Naming + docs sweep (breaking, patch): one name per role across the whole library, and the docs now document the code that exists.
8
+
9
+ - Middleware factories: `idempotency()` → `createIdempotencyMiddleware()`. (`multiTenant()`/`apiVersion()` keep their feature-named forms — each anchors an accessor family sharing its prefix; the doctrine in CLAUDE.md documents the rule and the exceptions.)
10
+ - Surface packages are Hono-idiomatic factories you mount yourself: swagger's `setupSwaggerUI`/`setupReDoc`/`setupDocsIndex` (app mutators) become `swaggerUI()`/`redocUI()`/`docsIndex()` returning `MiddlewareHandler` with `SwaggerUIConfig`/`RedocUIConfig`/`DocsIndexConfig` (adopting scalar's `specUrl`/`pageTitle` vocabulary; `UIOptions` deleted); scalar's `setupScalar` is deleted (`app.get(path, scalarUI(config))`); health's `createHealthEndpoints`/`createHealthHandler` collapse into `createHealthRoutes(config): Hono` mounted via `app.route()`.
11
+ - The word "Versioning" now means record history only: HTTP negotiation renames to `ApiVersioningConfig` (was `VersioningMiddlewareConfig`), `ApiVersionStrategy`, `ApiVersionTransformer`, `apiVersionedResponse()`.
12
+ - Multi-tenant has one source-of-truth union: new exported `TenantIdSource` owned by the model-level `MultiTenantConfig`; the middleware config derives from it and renames to `MultiTenantMiddlewareConfig` (was `*Options`). Runtime defaults unchanged.
13
+ - `CrudMcpOptions` → `CrudMcpConfig` per the now-documented Config-vs-Options rule.
14
+ - Rate-limit key prefix unified: one exported `DEFAULT_RATE_LIMIT_KEY_PREFIX = 'rl'`; the KV and Redis storage prefixes no longer add their own divergent defaults ('rl:'/'ratelimit:'), so all backends build identical keys. In-flight rate-limit windows under old prefixes expire naturally.
15
+ - Vestigial `RouterOptions.base`/`docs_url`/`redoc_url` deleted (UI paths live in the swagger/scalar packages; `openapi_url` stays).
16
+ - One API-key hasher: the canonical `hashAPIKey` moves to `auth/hash.ts` and `defaultHashAPIKey` is now an alias of it — hashing is byte-identical, stored keys keep matching.
17
+ - Sorting aliases removed from the functional config: `orderByFields`/`defaultOrderBy`/`defaultOrderDirection` and `SortingConfig.defaultDirection` are gone — canonical `sortFields`/`defaultSort`/`defaultOrder` only.
18
+ - Drizzle's stale 5-verb `DrizzleAdapters` bundle in factory.ts is deleted; the 17-entry bundle in the package barrel is the only one, mirroring prisma and memory.
19
+ - Docs: CLAUDE.md/AGENTS.md gain the naming doctrine and a corrected Drizzle Adapter Pattern section using the real type names (`DrizzleDatabaseConstraint`, `Database<Row>`, `QueryBuilder<Row>`, `cast<Row>()`); all docs/READMEs/examples migrated to the new names and call patterns.
20
+
3
21
  ## 0.13.12
4
22
 
5
23
  ### Patch Changes
@@ -3,14 +3,15 @@ import { MiddlewareHandler, Env, Context } from 'hono';
3
3
  /**
4
4
  * Strategy for extracting the API version from requests.
5
5
  */
6
- type VersionStrategy = 'url' | 'header' | 'query';
6
+ type ApiVersionStrategy = 'url' | 'header' | 'query';
7
7
  /**
8
8
  * A version transformer function that converts request/response data
9
9
  * between API versions.
10
10
  */
11
- type VersionTransformer = (data: Record<string, unknown>) => Record<string, unknown>;
11
+ type ApiVersionTransformer = (data: Record<string, unknown>) => Record<string, unknown>;
12
12
  /**
13
- * Configuration for a single API version.
13
+ * One version entry consumed by apiVersion() via {@link ApiVersioningConfig}.versions
14
+ * — not the record-history config in core/types.
14
15
  */
15
16
  interface ApiVersionConfig {
16
17
  /** Version identifier (e.g. '1', '2', '2024-01-15') */
@@ -18,24 +19,27 @@ interface ApiVersionConfig {
18
19
  /** Optional middleware to apply for this version */
19
20
  middleware?: MiddlewareHandler[];
20
21
  /** Transform incoming request body from this version to latest */
21
- requestTransformer?: VersionTransformer;
22
+ requestTransformer?: ApiVersionTransformer;
22
23
  /** Transform outgoing response data from latest to this version */
23
- responseTransformer?: VersionTransformer;
24
+ responseTransformer?: ApiVersionTransformer;
24
25
  /** ISO date string when this version was deprecated */
25
26
  deprecated?: string;
26
27
  /** ISO date string when this version will be removed */
27
28
  sunset?: string;
28
29
  }
29
30
  /**
30
- * Configuration for the API versioning middleware.
31
+ * Top-level bag for the apiVersion() middleware.
32
+ * NOT to be confused with {@link ApiVersionConfig}, which describes ONE version entry
33
+ * inside `versions`. (Unrelated to the record-history feature's config in core/types,
34
+ * which governs stored record versions, not HTTP API negotiation.)
31
35
  */
32
- interface VersioningMiddlewareConfig {
36
+ interface ApiVersioningConfig {
33
37
  /** Available API versions. First is treated as default if no defaultVersion specified. */
34
38
  versions: ApiVersionConfig[];
35
39
  /** Default version when none is specified by client */
36
40
  defaultVersion?: string;
37
41
  /** Version extraction strategy. @default 'header' */
38
- strategy?: VersionStrategy;
42
+ strategy?: ApiVersionStrategy;
39
43
  /** Header name for header strategy. @default 'Accept-Version' */
40
44
  headerName?: string;
41
45
  /** Query parameter name for query strategy. @default 'version' */
@@ -89,7 +93,7 @@ interface ApiVersionEnv extends Env {
89
93
  * }));
90
94
  * ```
91
95
  */
92
- declare function apiVersion(config: VersioningMiddlewareConfig): MiddlewareHandler;
96
+ declare function apiVersion(config: ApiVersioningConfig): MiddlewareHandler;
93
97
  /**
94
98
  * Get the current API version from context.
95
99
  */
@@ -100,15 +104,17 @@ declare function getApiVersion(ctx: Context): string | undefined;
100
104
  declare function getApiVersionConfig(ctx: Context): ApiVersionConfig | undefined;
101
105
  /**
102
106
  * Middleware that transforms response JSON using the active version's responseTransformer.
103
- * Apply AFTER your route handlers.
107
+ * Register it BEFORE your route handlers (and after apiVersion()) — like all Hono
108
+ * middleware it wraps the handler via `await next()` and rewrites the response on the
109
+ * way out. Middleware registered after a response-producing handler never runs.
104
110
  *
105
111
  * @example
106
112
  * ```ts
107
113
  * app.use('*', apiVersion({ ... }));
114
+ * app.use('*', apiVersionedResponse());
108
115
  * app.get('/users/:id', handler);
109
- * app.use('*', versionedResponse());
110
116
  * ```
111
117
  */
112
- declare function versionedResponse(): MiddlewareHandler;
118
+ declare function apiVersionedResponse(): MiddlewareHandler;
113
119
 
114
- export { type ApiVersionConfig, type ApiVersionEnv, type VersionStrategy, type VersionTransformer, type VersioningMiddlewareConfig, apiVersion, getApiVersion, getApiVersionConfig, versionedResponse };
120
+ export { type ApiVersionConfig, type ApiVersionEnv, type ApiVersionStrategy, type ApiVersionTransformer, type ApiVersioningConfig, apiVersion, apiVersionedResponse, getApiVersion, getApiVersionConfig };
@@ -1 +1 @@
1
- export{a as apiVersion,b as getApiVersion,c as getApiVersionConfig,d as versionedResponse}from'../chunk-A7ZLZUMJ.js';import'../chunk-6XVCICWS.js';import'../chunk-6GO5LUOZ.js';
1
+ export{a as apiVersion,d as apiVersionedResponse,b as getApiVersion,c as getApiVersionConfig}from'../chunk-OLSYHJGK.js';import'../chunk-6XVCICWS.js';import'../chunk-6GO5LUOZ.js';
@@ -1,5 +1,5 @@
1
1
  import { Context } from 'hono';
2
- import { A as AuditConfig, f as AuditLogEntry, g as AuditAction } from '../types-DKPLu-9p.js';
2
+ import { A as AuditConfig, f as AuditLogEntry, g as AuditAction } from '../types-tthfGTqv.js';
3
3
  import { S as StorageRegistry } from '../registry-3p4qTDGZ.js';
4
4
  import 'zod';
5
5
  import '../types-B5wq2iKZ.js';
@@ -1,9 +1,9 @@
1
- export { n as APIKeyConfig, o as APIKeyEntry, p as APIKeyLookupResult, q as ActionSource, y as ApprovalConfig, z as ApprovalStorage, B as AuthConfig, C as AuthEnv, D as AuthType, E as AuthUser, G as AuthorizationCheck, U as EndpointAuthConfig, Z as Guard, a5 as JWTAlgorithm, a6 as JWTClaims, a7 as JWTClaimsSchema, a8 as JWTConfig, a9 as JWT_ALGORITHMS, ao as OwnershipExtractor, aY as PathPattern, ar as PendingAction, as as PendingActionStatus, aL as ValidatedJWTClaims, aS as parseJWTClaims, aT as safeParseJWTClaims } from '../types-DKPLu-9p.js';
2
- export { A as AuthEndpointMethods, a as AuthenticatedEndpoint, J as JWTClaimsValidationOptions, M as MemoryAPIKeyStorage, b as MemoryApprovalStorage, P as POLICIES_CONTEXT_KEY, c as allOf, d as allowAll, e as anyOf, f as createAPIKeyMiddleware, g as createAuthMiddleware, h as createJWTMiddleware, i as decodeJWT, j as defaultHashAPIKey, k as denyAll, m as generateAPIKey, n as getAPIKeyStorage, o as hashAPIKey, p as isValidAPIKeyFormat, q as optionalAuth, r as parseIso8601Duration, s as requireAllRoles, t as requireAnyPermission, u as requireApproval, v as requireAuth, w as requireAuthenticated, x as requireAuthentication, y as requireOwnership, z as requireOwnershipOrRole, B as requirePermissions, C as requirePolicy, D as requireRoles, E as setAPIKeyStorage, F as validateAPIKey, G as validateAPIKeyEntry, H as validateJWTClaims, I as verifyJWT, K as withAuth } from '../index-B3hpRLJg.js';
1
+ export { n as APIKeyConfig, o as APIKeyEntry, p as APIKeyLookupResult, q as ActionSource, y as ApprovalConfig, z as ApprovalStorage, B as AuthConfig, C as AuthEnv, D as AuthType, E as AuthUser, G as AuthorizationCheck, W as EndpointAuthConfig, _ as Guard, a6 as JWTAlgorithm, a7 as JWTClaims, a8 as JWTClaimsSchema, a9 as JWTConfig, aa as JWT_ALGORITHMS, ao as OwnershipExtractor, aZ as PathPattern, ar as PendingAction, as as PendingActionStatus, aM as ValidatedJWTClaims, aT as parseJWTClaims, aU as safeParseJWTClaims } from '../types-tthfGTqv.js';
2
+ export { A as AuthEndpointMethods, a as AuthenticatedEndpoint, J as JWTClaimsValidationOptions, M as MemoryAPIKeyStorage, b as MemoryApprovalStorage, P as POLICIES_CONTEXT_KEY, c as allOf, d as allowAll, e as anyOf, f as createAPIKeyMiddleware, g as createAuthMiddleware, h as createJWTMiddleware, i as decodeJWT, j as defaultHashAPIKey, k as denyAll, m as generateAPIKey, n as getAPIKeyStorage, o as hashAPIKey, p as isValidAPIKeyFormat, q as optionalAuth, r as parseIso8601Duration, s as requireAllRoles, t as requireAnyPermission, u as requireApproval, v as requireAuth, w as requireAuthenticated, x as requireAuthentication, y as requireOwnership, z as requireOwnershipOrRole, B as requirePermissions, C as requirePolicy, D as requireRoles, E as setAPIKeyStorage, F as validateAPIKey, G as validateAPIKeyEntry, H as validateJWTClaims, I as verifyJWT, K as withAuth } from '../index-DgV651ue.js';
3
3
  import 'hono';
4
4
  import 'zod';
5
5
  import '../types-B5wq2iKZ.js';
6
6
  import '../types-Drjma4gp.js';
7
7
  import '@hono/zod-openapi';
8
- import '../route-BHXjgMro.js';
8
+ import '../route-C6T6CTON.js';
9
9
  import 'hono/utils/http-status';
@@ -1 +1 @@
1
- export{$ as AuthenticatedEndpoint,M as JWTClaimsSchema,L as JWT_ALGORITHMS,r as MemoryApprovalStorage,t as POLICIES_CONTEXT_KEY,B as allOf,E as allowAll,C as anyOf,W as createAPIKeyMiddleware,Y as createAuthMiddleware,R as createJWTMiddleware,T as decodeJWT,V as defaultHashAPIKey,D as denyAll,Z as optionalAuth,s as parseIso8601Duration,N as parseJWTClaims,v as requireAllRoles,x as requireAnyPermission,H as requireApproval,y as requireAuth,F as requireAuthenticated,_ as requireAuthentication,z as requireOwnership,A as requireOwnershipOrRole,w as requirePermissions,G as requirePolicy,u as requireRoles,O as safeParseJWTClaims,X as validateAPIKey,U as validateAPIKeyEntry,P as validateJWTClaims,S as verifyJWT,aa as withAuth}from'../chunk-KTDHELSH.js';export{a as MemoryAPIKeyStorage,b as generateAPIKey,e as getAPIKeyStorage,c as hashAPIKey,d as isValidAPIKeyFormat,f as setAPIKeyStorage}from'../chunk-DALXO46J.js';import'../chunk-NWOJZP4P.js';import'../chunk-VESRPXGC.js';import'../chunk-6XVCICWS.js';import'../chunk-MCXQ77DB.js';import'../chunk-EX4S3Q4M.js';import'../chunk-DMGP7QDL.js';import'../chunk-OCJC5XWY.js';import'../chunk-VJRDAVID.js';import'../chunk-6GO5LUOZ.js';
1
+ export{$ as AuthenticatedEndpoint,M as JWTClaimsSchema,L as JWT_ALGORITHMS,r as MemoryApprovalStorage,t as POLICIES_CONTEXT_KEY,B as allOf,E as allowAll,C as anyOf,W as createAPIKeyMiddleware,Y as createAuthMiddleware,R as createJWTMiddleware,T as decodeJWT,V as defaultHashAPIKey,D as denyAll,Z as optionalAuth,s as parseIso8601Duration,N as parseJWTClaims,v as requireAllRoles,x as requireAnyPermission,H as requireApproval,y as requireAuth,F as requireAuthenticated,_ as requireAuthentication,z as requireOwnership,A as requireOwnershipOrRole,w as requirePermissions,G as requirePolicy,u as requireRoles,O as safeParseJWTClaims,X as validateAPIKey,U as validateAPIKeyEntry,P as validateJWTClaims,S as verifyJWT,aa as withAuth}from'../chunk-JITAQDZZ.js';export{b as MemoryAPIKeyStorage,c as generateAPIKey,e as getAPIKeyStorage,a as hashAPIKey,d as isValidAPIKeyFormat,f as setAPIKeyStorage}from'../chunk-IOWLCLF6.js';import'../chunk-NWOJZP4P.js';import'../chunk-VESRPXGC.js';import'../chunk-6XVCICWS.js';import'../chunk-MCXQ77DB.js';import'../chunk-EX4S3Q4M.js';import'../chunk-DMGP7QDL.js';import'../chunk-OCJC5XWY.js';import'../chunk-VJRDAVID.js';import'../chunk-6GO5LUOZ.js';
@@ -0,0 +1,11 @@
1
+ import {a as a$6,b as b$3}from'./chunk-PDHKGPGZ.js';import {n,o,q,f,b as b$2,J,d as d$1,c as c$1,e,p,t,m}from'./chunk-JITAQDZZ.js';import {G}from'./chunk-IOWLCLF6.js';import {h,a as a$5}from'./chunk-VESRPXGC.js';import {b,a,i,d,c,g,f as f$2}from'./chunk-6XVCICWS.js';import {g as g$1}from'./chunk-MCXQ77DB.js';import {a as a$3}from'./chunk-EX4S3Q4M.js';import {a as a$2}from'./chunk-STAO4FWC.js';import {e as e$1,f as f$1}from'./chunk-6MS7YXSZ.js';import {d as d$2}from'./chunk-JNRSTMFA.js';import {b as b$1}from'./chunk-DMGP7QDL.js';import {a as a$1,b as b$4}from'./chunk-VJRDAVID.js';import {a as a$4}from'./chunk-6GO5LUOZ.js';import {OpenAPIHono,createRoute}from'@hono/zod-openapi';import {z,ZodError}from'zod';import {HTTPException}from'hono/http-exception';import {streamSSE,stream}from'hono/streaming';function so(n,e){return {content:{"application/json":{schema:n}},description:e}}function ao(n,e){return {content:{"application/json":{schema:n}},description:e,required:true}}var Xe=n=>{if(!n.success)throw b.fromZodError(n.error)};function lo(n,e=400){return (t,o)=>{if(!t.success)return o.json(n(t.error),e)}}var Kt=new WeakMap;function et(n){return Kt.get(n)}var ye=class{app;options;routes=new Map;constructor(e,t={}){this.app=e,this.options={openapi_url:"/openapi.json",...t};}registerRoute(e,t,o$1,r=[]){let i=`${e.toUpperCase()} ${t}`,s=o$1,l=new s().getSchema();this.routes.set(i,{method:e,path:t,schema:l,routeClass:o$1});let c=createRoute({method:e,path:this.convertPath(t),...l,responses:l.responses||{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}});if(r.length>0)for(let a of r)this.app.use(t,async(d,p)=>{if(d.req.method.toLowerCase()===e)return a(d,p);await p();});this.app.openapi(c,async a$1=>{let d=new s;d.setContext(a$1);try{return await d.handle()}catch(p){if(p instanceof a){let m=p.toJSON(),h=n(a$1);return h?o(a$1,h.error(m.error),p.status):o(a$1,m,p.status)}throw p}});}convertPath(e){return e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}setupDocs(e,t){let o=e??this.options.openapi_url??"/openapi.json";this.app.doc(o,{openapi:t.openapi||"3.1.0",info:t.info,servers:t.servers,security:t.security});}getApp(){return this.app}getRegisteredRoutes(){return this.routes}toOpenApiPath(e){return this.convertPath(e)}};function po(n=new OpenAPIHono,e={}){let t="openAPIRegistry"in n?n:new OpenAPIHono;t.defaultHook??=Xe;let o=new ye(t,e),r=["get","post","put","patch","delete","options","head"],i=new Proxy(t,{get(s,u){if(r.includes(u))return (c,...a)=>{let d=a[a.length-1];if(q(d)){let p=a.slice(0,-1);return o.registerRoute(u,c,d,p),i}return s[u](c,...a)};if(u==="doc")return (c,a)=>{o.setupDocs(c,a);};if(u==="use")return (...c)=>(s[u](...c),i);let l=s[u];return typeof l=="function"?l.bind(s):l}});return Kt.set(i,o),i}var fo=6e4,go={openapi:"3.1.0",info:{title:"API",version:"1.0.0"}};async function bo(n,e,t={}){let o=et(n);if(!o)throw new Error("buildPerTenantOpenApi: app was not produced by fromHono(...). Cannot find route registry.");let r=t.config??go,i=`openapi:${e.tenantId??"global"}:${r.info.version}`;if(t.cache){let c=await t.cache.get(i);if(c!=null)return c}let s=new OpenAPIHono;for(let c of o.getRegisteredRoutes().values()){let a=c.routeClass,d=new a,p=yo(e);d.setContext(p),typeof d.resolveModelSchema=="function"&&await d.resolveModelSchema();let m=d.getSchema(),h=createRoute({...m,method:c.method,path:o.toOpenApiPath(c.path),responses:m.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});s.openapi(h,()=>new Response);}let u={openapi:r.openapi??"3.1.0",info:r.info,servers:r.servers,security:r.security},l=t.spec==="3.0"?s.getOpenAPIDocument(u):s.getOpenAPI31Document(u);return t.cache&&await t.cache.set(i,l,t.cacheTtlMs??fo),l}function yo(n){let e={};n.tenantId!==void 0&&(e.tenantId=n.tenantId),n.organizationId!==void 0&&(e.organizationId=n.organizationId);let t=n.request??new Request("http://localhost/");return {var:e,env:n.env,req:{raw:t,header:()=>{},query:()=>{},param:()=>{}},set(o,r){e[o]=r;},get(o){return e[o]},executionCtx:void 0}}function wo(n){return {async get(e){let t=await n.get(e);return t?t.data:void 0},async set(e,t,o){await n.set(e,t,o!=null?{ttlMs:o}:void 0);}}}var So=[["create","post",""],["list","get",""],["batchCreate","post","/batch"],["batchUpdate","patch","/batch"],["batchDelete","delete","/batch"],["batchRestore","post","/batch/restore"],["batchUpsert","post","/batch/upsert"],["search","get","/search"],["aggregate","get","/aggregate"],["export","get","/export"],["import","post","/import"],["upsert","post","/upsert"],["read","get","/:id"],["update","patch","/:id"],["delete","delete","/:id"],["restore","post","/:id/restore"],["clone","post","/:id/clone"]];function xo(n){return n.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}function Oo(n,e){let o=`/${n}/${e}`.replace(/\/{2,}/g,"/");return o.length>1&&o.endsWith("/")?o.slice(0,-1):o}function ko(n,e={}){let t=e.basePath??"",o=e.tag,r=new OpenAPIHono,i=0;for(let[l,c,a]of So){let d=n[l];if(!d)continue;let m=new d().getSchema(),h=o!==void 0?{...m,tags:[o]}:m,f=Oo(t,xo(a)),y=createRoute({...h,method:c,path:f,responses:h.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});r.openapi(y,()=>new Response),i+=1;}return i===0?{}:r.getOpenAPI31Document({openapi:"3.1.0",info:{title:"hono-crud",version:"1.0.0"}}).paths??{}}var Wt=n=>{if(n instanceof ZodError)return b.fromZodError(n)};function Io(n={}){let{mappers:e=[],hooks:t=[],includeRequestId:o$1=true,includeStackTrace:r=false,defaultErrorCode:i="INTERNAL_ERROR",defaultErrorMessage:s="An internal error occurred",logUnmappedErrors:u=true,onHookError:l,responseEnvelope:c}=n,a$1=[...e,Wt];return async(d,p)=>{let m,h=false;if(d instanceof a)m=d,h=true;else if(d instanceof HTTPException)m=new a(d.message,d.status,"HTTP_ERROR"),h=true;else {for(let g of a$1)try{let S=await g(d,p);if(S){m=S,h=!0;break}}catch{}h||(u&&b$1().error("Unmapped error",{error:d instanceof Error?d.message:String(d)}),m=new a(s,500,i));}for(let g of t)try{let S=g(d,p,m);S instanceof Promise&&S.catch(j=>{l&&l(j,d,p);});}catch(S){l&&l(S,d,p);}let f=m.toJSON();if(o$1){let g=G(p);g&&(f.error.requestId=g);}r&&d.stack&&(f.error.stack=d.stack);let y=Gt(p,c),b=y?y.error(f.error):f;return o(p,b,m.status)}}function Gt(n$1,e){return n(n$1)??e}var tt="createdAt",ot="updatedAt";function ie(n){return n?n===true?{enabled:true,createdAt:tt,updatedAt:ot}:{enabled:true,createdAt:n.createdAt??tt,updatedAt:n.updatedAt??ot}:{enabled:false,createdAt:tt,updatedAt:ot}}function H(n,e={}){let{includePrimaryKeys:t=true}=e,o=new Set;if(t)for(let i of n.primaryKeys)o.add(i);let r=ie(n.timestamps);return r.enabled&&(o.add(r.createdAt),o.add(r.updatedAt)),[...o]}function vo(n){return n!=null&&n!==""}function rt(n,e,t,o){let r={...n},i$1=e.primaryKeys[0];if(!vo(r[i$1])){let u=e.id;if(typeof u=="function")r[i$1]=u();else if(u==="database"){if(t==="memory")throw new i("MemoryAdapter does not support id:'database' (no database to generate the key)");delete r[i$1];}else r[i$1]=o?o():crypto.randomUUID();}let s=ie(e.timestamps);if(s.enabled){let u=Date.now();s.createdAt in n||(r[s.createdAt]=u),s.updatedAt in n||(r[s.updatedAt]=u);}return r}function nt(n,e){let t=ie(e.timestamps);return t.enabled?{...n,[t.updatedAt]:Date.now()}:{...n}}function it(n,e){if(e==="memory"&&n.id==="database")throw new i("MemoryAdapter does not support id:'database' (no database to generate the key)")}function st(n,e){let t={...n};for(let o of H(e))delete t[o];return t}var Fo=new Set(["P2002","SQLITE_CONSTRAINT_UNIQUE","SQLITE_CONSTRAINT","23505","ER_DUP_ENTRY",1062,"1062"]),jo=/UNIQUE constraint failed|duplicate key value violates unique constraint|Duplicate entry/i;function Ao(n){if(!n||typeof n!="object")return false;let{code:e,message:t}=n;return (typeof e=="string"||typeof e=="number")&&Fo.has(e)?true:typeof t=="string"&&jo.test(t)}function*Qt(n,e=8){for(let t=n,o=0;o<e&&t!=null&&typeof t=="object";o++)yield t,t=t.cause;}function we(n){for(let e of Qt(n))if(Ao(e))return new d("Unique constraint violation");return null}function K(n){throw we(n)??n}function _o(n){return btoa(String(n))}function To(n){try{return atob(n)}catch{return null}}async function se(n,e){if(!e||Object.keys(e).length===0)return n;let t={...n};for(let[o,r]of Object.entries(e))try{let i=await r.compute(n);t[o]=i;}catch{t[o]=void 0;}return t}async function at(n,e){return !e||Object.keys(e).length===0?n:Promise.all(n.map(t=>se(t,e)))}function X(n,e){let t={},o={};for(let[r,i]of Object.entries(n))e.includes(r)&&i!==void 0?o[r]=i:t[r]=i;return {mainData:t,nestedData:o}}function he(n){if(Array.isArray(n))return true;if(typeof n=="object"&&n!==null){let e=Object.keys(n),t=["create","update","delete","connect","disconnect","set"];return !e.some(o=>t.includes(o))}return false}function No(n){let e=n.split(":");if(e.length<2)return null;let t=e[0].toLowerCase();return f.map(i=>i.toLowerCase()).includes(t)?{operation:t==="countdistinct"?"countDistinct":t,field:e[1],alias:e[2]}:null}function dt(n){let e=[],t={};for(let a of f){let d=n[a];if(d){let p=Array.isArray(d)?d:[d];for(let m of p)typeof m=="string"&&e.push({operation:a,field:m==="true"||m===""?"*":m});}}let o;if(n.groupBy){let a=n.groupBy;typeof a=="string"?o=a.split(",").map(d=>d.trim()):Array.isArray(a)&&(o=a.filter(d=>typeof d=="string"));}let r;for(let[a,d]of Object.entries(n)){let p=a.match(/^having\[(\w+)\]\[(\w+)\]$/);if(p){let[,m,h]=p;r||(r={}),r[m]||(r[m]={}),r[m][h]=d;}}let i=typeof n.orderBy=="string"?n.orderBy:void 0,s=n.orderDirection==="desc"?"desc":"asc",u=typeof n.limit=="string"?Number.parseInt(n.limit,10):void 0,l=typeof n.offset=="string"?Number.parseInt(n.offset,10):void 0,c=[...f,"groupBy","orderBy","orderDirection","limit","offset"];for(let[a,d]of Object.entries(n))!c.includes(a)&&!a.startsWith("having[")&&(t[a]=d);return {aggregations:e,groupBy:o,filters:Object.keys(t).length>0?t:void 0,having:r,orderBy:i,orderDirection:s,limit:u,offset:l}}function lt(n){return n?n===true?{enabled:true,field:"deletedAt",allowQueryDeleted:true,queryParam:"withDeleted"}:{enabled:true,field:n.field??"deletedAt",allowQueryDeleted:n.allowQueryDeleted??true,queryParam:n.queryParam??"withDeleted"}:{enabled:false,field:"deletedAt",allowQueryDeleted:true,queryParam:"withDeleted"}}function ct(n){let e={enabled:false,field:"tenantId",source:"context",headerName:"X-Tenant-ID",contextKey:"tenantId",pathParam:"tenantId",required:true,errorMessage:"Tenant ID is required"};return n?n===true?{...e,enabled:true}:{enabled:true,field:n.field??e.field,source:n.source??e.source,headerName:n.headerName??e.headerName,contextKey:n.contextKey??e.contextKey,pathParam:n.pathParam??e.pathParam,getTenantId:n.getTenantId,required:n.required??e.required,errorMessage:n.errorMessage??e.errorMessage}:e}function pt(n,e){return e.enabled?{header:()=>n.req.header(e.headerName),context:()=>a$1(n,e.contextKey),path:()=>n.req.param(e.pathParam),custom:()=>e.getTenantId?.(n)}[e.source]?.():void 0}var Do=new Set(["a","an","and","are","as","at","be","by","for","from","has","he","in","is","it","its","of","on","or","that","the","to","was","were","will","with"]);function ut(n,e=true){if(!n||typeof n!="string")return [];let t=n.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(Boolean);return e?t.filter(o=>!Do.has(o)&&o.length>1):t}function mt(n,e){return e==="phrase"?[n.toLowerCase().trim()]:ut(n)}function Yt(n,e){return e.length===0?0:e.filter(o=>o===n||o.includes(n)).length/e.length}function ht(n,e,t,o){if(e.length===0)return {score:0,matchedFields:[]};let r=0,i=0,s=[];for(let[l,c]of Object.entries(t)){let a=n[l];if(a==null)continue;let d=c.weight??1;i+=d;let p;c.type==="array"&&Array.isArray(a)?p=a.join(" "):p=String(a);let m=ut(p,false),h=p.toLowerCase(),f=0,y=0;if(o==="phrase"){let b=e[0];h.includes(b)&&(f=1,y=1);}else {for(let b of e){let g=Yt(b,m);g>0?(y++,f+=g):h.includes(b)&&(y++,f+=.5/e.length);}e.length>0&&(f=f/e.length);}o==="all"&&y<e.length&&(f=0),f>0&&(s.push(l),r+=f*d);}return {score:i>0?Math.min(1,r/i):0,matchedFields:s}}function ft(n,e,t,o="mark",r=150){if(n==null)return [];let i;if(Array.isArray(n)?i=n.join(" "):i=String(n),!i||e.length===0)return [];let s=[],u=i.toLowerCase();if(t==="phrase"){let l=e[0],c=u.indexOf(l);if(c!==-1){let a=Jt(i,c,l.length,r,o);a&&s.push(a);}}else {let l=[];for(let a of e){let d=0;for(;d<u.length;){let p=u.indexOf(a,d);if(p===-1)break;l.push({start:p,length:a.length}),d=p+1;}}l.sort((a,d)=>a.start-d.start);let c=new Set;for(let a of l){if(Array.from(c).some(m=>Math.abs(m-a.start)<r))continue;let p=Jt(i,a.start,a.length,r,o);if(p&&(s.push(p),c.add(a.start)),s.length>=3)break}}return s}function Jt(n,e,t,o,r){let i=Math.floor(o/2),s=Math.max(0,e-i),u=Math.min(n.length,e+t+i);if(s>0){let a=n.indexOf(" ",s);a!==-1&&a<e&&(s=a+1);}if(u<n.length){let a=n.lastIndexOf(" ",u);a!==-1&&a>e+t&&(u=a);}let l=n.slice(s,u);return s>0&&(l="..."+l),u<n.length&&(l=l+"..."),Ho(l,[n.slice(e,e+t)],r)}function Ho(n,e,t){let o=n,r=n.toLowerCase(),i=[...e].sort((s,u)=>u.length-s.length);for(let s of i){let u=s.toLowerCase(),l=0,c="",a=0;for(;a<r.length;){let d=r.indexOf(u,a);if(d===-1)break;c+=o.slice(l,d),c+=`<${t}>${o.slice(d,d+s.length)}</${t}>`,l=d+s.length,a=l;}c&&(c+=o.slice(l),o=c);}return o}function gt(n,e){if(!n)return Object.keys(e);let t=n.split(",").map(r=>r.trim()).filter(Boolean),o=Object.keys(e);return t.filter(r=>o.includes(r))}function bt(n,e){let t={};for(let o of n)t[o]={weight:e?.[o]??1};return t}function yt(n){return n==="all"||n==="phrase"?n:"any"}function wt(n){if(n===null||typeof n!="object")return n;if(Array.isArray(n))return n.map(wt);let e={};for(let t of Object.keys(n).sort())e[t]=wt(n[t]);return e}async function ae(n){let e=JSON.stringify(wt(n)),t=new TextEncoder().encode(e),o=await crypto.subtle.digest("SHA-256",t);return `"${Array.from(new Uint8Array(o)).map(s=>s.toString(16).padStart(2,"0")).join("").substring(0,32)}"`}function Mt(n,e){return n?n==="*"?true:n.split(",").map(t=>t.trim()).includes(e):false}function Rt(n,e){return !n||n==="*"?true:n.split(",").map(t=>t.trim()).includes(e)}function Xt(n,e){return n==="in"||n==="nin"||n==="between"?e.split(",").map(t=>t.trim()):n==="null"?e.toLowerCase()==="true":e}function Vo(n){let e=n.match(/^\[([a-z]+)\](.*)$/);if(e&&b$2(e[1])){let t=e[1];return {operator:t,value:Xt(t,e[2])}}return {operator:"eq",value:n}}function ee(n,e){let t=[],o={},{filterFields:r=[],filterConfig:i={},searchFields:s=[],searchFieldName:u="search",sortFields:l=[],defaultSort:c,defaultPerPage:a=20,maxPerPage:d=100,cursorPaginationEnabled:p=false,softDeleteQueryParam:m="withDeleted",allowedIncludes:h=[],fieldSelectionEnabled:f=false,allowedSelectFields:y=[],blockedSelectFields:b=[],alwaysIncludeFields:g=[],defaultSelectFields:S=[]}=e,j={};for(let A of r)j[A]=["eq"];Object.assign(j,i);for(let[A,_e]of Object.entries(n)){if(_e==null)continue;let L=String(_e);if(p&&A==="cursor"){o.cursor=L;continue}if(p&&A==="limit"){o.limit=Math.min(d,Math.max(1,Number.parseInt(L,10)||a));continue}if(A==="page"){o.page=Math.max(1,Number.parseInt(L,10)||1);continue}if(A==="per_page"){o.per_page=Math.min(d,Math.max(1,Number.parseInt(L,10)||a));continue}if(A==="sort"){(l.length===0||l.includes(L))&&(o.order_by=L);continue}if(A==="order"){(L==="asc"||L==="desc")&&(o.order_by_direction=L);continue}if(A===u&&s.length>0){o.search=L;continue}if(A===m){o.withDeleted=L.toLowerCase()==="true";continue}if(A==="onlyDeleted"){o.onlyDeleted=L.toLowerCase()==="true";continue}if(A==="include"){let oe=L.split(",").map(z=>z.trim()).filter(Boolean);h&&h.length>0?o.include=oe.filter(z=>h.includes(z)):o.include=oe;continue}if(A==="fields"&&f){let z=L.split(",").map(de=>de.trim()).filter(Boolean);y.length>0&&(z=z.filter(de=>y.includes(de))),b.length>0&&(z=z.filter(de=>!b.includes(de))),g.length>0&&(z=[...new Set([...g,...z])]),o.fields=z;continue}let Te=A.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([a-z]+)\]$/);if(Te){let oe=Te[1],z=Te[2];j[oe]?.includes(z)&&t.push({field:oe,operator:z,value:Xt(z,L)});continue}j[A]&&t.push({field:A,operator:"eq",value:L});}if(o.page||(o.page=1),o.per_page||(o.per_page=a),!o.order_by&&c?.field&&(o.order_by=c.field),o.order_by_direction||(o.order_by_direction=c?.order??"asc"),f&&!o.fields&&S.length>0){let A=[...S];g.length>0&&(A=[...new Set([...g,...A])]),o.fields=A;}return {filters:t,options:o}}function V(n,e=[]){if(e.length===0)return n;let t=new Set(Object.keys(n.shape)),o=e.filter(i=>t.has(i));if(o.length===0)return n;let r=Object.fromEntries(o.map(i=>[i,true]));return n.omit(r)}function Zo(n,e={},t=[],o=[],r=[]){let{allowedFields:i=[],blockedFields:s=[],alwaysIncludeFields:u=[],defaultFields:l=[],allowComputedFields:c=true,allowRelationFields:a=true}=e;if(!n||typeof n!="string"||n.trim()==="")return l.length>0?{fields:[...new Set([...u,...l])],isActive:false}:{fields:[],isActive:false};let d=n.split(",").map(f=>f.trim()).filter(Boolean),p=new Set;for(let f of t)(i.length===0||i.includes(f))&&(s.includes(f)||p.add(f));if(c)for(let f of o)(i.length===0||i.includes(f))&&(s.includes(f)||p.add(f));if(a)for(let f of r)(i.length===0||i.includes(f))&&(s.includes(f)||p.add(f));let m=d.filter(f=>p.has(f));return {fields:[...new Set([...u,...m])],isActive:true}}function Me(n,e){if(!e.isActive||e.fields.length===0)return n;let t={};for(let o of e.fields)o in n&&(t[o]=n[o]);return t}function Et(n,e){return !e.isActive||e.fields.length===0?n:n.map(t=>Me(t,e))}var eo="__honoCrudResolvedSchema:";function Lo(n){return typeof n.getBodySchema=="function"}var x=class extends p{_auditLogger;_versionManager;_tx;getAuditLogger(){return this._auditLogger||(this._auditLogger=g$1(this._meta.model.audit,void 0,this.context??void 0)),this._auditLogger}getAuditConfig(){return a$3(this._meta.model.audit)}isAuditEnabled(){return this.getAuditConfig().enabled}getAuditUserId(){let e=this.getAuditConfig();return e.getUserId&&this.context?e.getUserId(this.context):this.context?a$1(this.context,a$4.userId):void 0}getVersionManager(){return this._versionManager||(this._versionManager=h(this._meta.model.versioning,this._meta.model.tableName,void 0,this.context??void 0)),this._versionManager}getVersioningConfig(){return a$5(this._meta.model.versioning,this._meta.model.tableName)}isVersioningEnabled(){return this.getVersioningConfig().enabled}getVersioningUserId(){let e=this.getVersioningConfig();return e.getUserId&&this.context?e.getUserId(this.context):this.context?a$1(this.context,a$4.userId):void 0}getSoftDeleteConfig(){return lt(this._meta.model.softDelete)}isSoftDeleteEnabled(){return this.getSoftDeleteConfig().enabled}getMultiTenantConfig(){return ct(this._meta.model.multiTenant)}isMultiTenantEnabled(){return this.getMultiTenantConfig().enabled}applyManagedInsertFields(e,t,o){return rt(e,this._meta.model,t,o)}applyManagedUpdateFields(e){return nt(e,this._meta.model)}assertIdStrategySupported(e){it(this._meta.model,e);}getTimestampsConfig(){return ie(this._meta.model.timestamps)}getTenantId(){if(!this.context)return;let e=this.getMultiTenantConfig();return pt(this.context,e)}validateTenantId(){let e=this.getMultiTenantConfig();if(!e.enabled)return;let t=this.getTenantId();if(!t&&e.required)throw new a(e.errorMessage,400,"TENANT_REQUIRED");return t}injectTenantId(e){let t=this.getMultiTenantConfig();if(!t.enabled)return e;let o=this.getTenantId();return o?{...e,[t.field]:o}:e}async emitEvent(e,t){let o=d$2(this.context??void 0);o&&await o.emit({type:e,table:this._meta.model.tableName,recordId:t.recordId,data:t.data??null,previousData:t.previousData,userId:this.getAuditUserId(),tenantId:this.context?this.getTenantId():void 0,organizationId:this.context?a$1(this.context,a$4.organizationId):void 0,timestamp:new Date().toISOString(),metadata:t.metadata});}async encryptOnWrite(e){let t=this._meta.model.fieldEncryption;return t?await e$1(e,t.fields,t.keyProvider):e}async decryptOnRead(e){let t=this._meta.model.fieldEncryption;return t?await f$1(e,t.fields,t.keyProvider):e}applyProfile(e){let t=this._meta.model.serializationProfile;return t?a$6(e,t):e}applyProfileToArray(e){let t=this._meta.model.serializationProfile;return t?b$3(e,t):e}transform(e){return e}async finalizeRecord(e,t){let o=this._meta.model,r=e;o.computedFields&&(r=await se(r,o.computedFields));let i=o.serializer?o.serializer(r):r,s=this.applyProfile(i),u=this.transform(s);return t?.isActive&&t.fields.length>0?Me(u,t):u}async finalizeArray(e,t){let o=this._meta.model,r=e;o.computedFields&&(r=await at(r,o.computedFields));let i=o.serializer?r.map(l=>o.serializer(l)):r,u=this.applyProfileToArray(i).map(l=>this.transform(l));return t?.isActive&&t.fields.length>0?Et(u,t):u}getRecordId(e){if(e===null||typeof e!="object")return null;let t=this._meta.model.primaryKeys[0],o=e[t];return typeof o=="string"||typeof o=="number"?o:null}getParentId(e){return this.getRecordId(e)}getPolicies(){if(this.context){let e=a$1(this.context,t);if(e)return e}return this._meta.model.policies}buildPolicyContext(){let e=this.context;return {user:e?a$1(e,a$4.user):void 0,userId:e?a$1(e,a$4.userId):void 0,tenantId:e?a$1(e,a$4.tenantId):void 0,organizationId:e?a$1(e,a$4.organizationId):void 0,request:e?.req?.raw??new Request("http://localhost/")}}async applyReadPolicy(e){let t=this.getPolicies();if(!t)return e;let o=this.buildPolicyContext();if(t.read&&!await t.read(o,e))return null;if(t.fields){let r=t.fields(o,e);return {...e,...r}}return e}async applyReadPolicyToArray(e){if(!this.getPolicies())return e;let o=[];for(let r of e){let i=await this.applyReadPolicy(r);i!==null&&o.push(i);}return o}async applyWritePolicy(e){let t=this.getPolicies();if(!t?.write)return;if(!await t.write(this.buildPolicyContext(),e))throw new f$2("Forbidden by policy")}applyReadPushdown(e){let t=this.getPolicies();if(!t?.readPushdown)return;let o=t.readPushdown(this.buildPolicyContext());o&&o.length>0&&e.filters.push(...o);}buildHookContext(){let e=this.context;return {db:{tx:this._tx},request:e?.req?.raw,tenantId:e?this.getTenantId():void 0,organizationId:e?a$1(e,a$4.organizationId):void 0,userId:e?a$1(e,a$4.userId):void 0,agentId:e?a$1(e,a$4.agentId):void 0,agentRunId:e?a$1(e,a$4.agentRunId):void 0}}getModelSchema(){if(this.context&&this._meta.model.resolveSchema){let e=a$1(this.context,eo+this._meta.model.tableName);if(e)return e}return this._meta.model.schema}async resolveModelSchema(){let e=this._meta.model.resolveSchema;if(!e||!this.context)return this._meta.model.schema;let t=eo+this._meta.model.tableName,o=a$1(this.context,t);if(o)return o;let r={tenantId:a$1(this.context,a$4.tenantId),organizationId:a$1(this.context,a$4.organizationId),request:this.context.req?.raw,env:this.context.env},i;try{i=await e(r);}catch(s){throw new a(s instanceof Error?s.message:"Schema resolution failed",500,"SCHEMA_RESOLVE_ERROR",s instanceof Error?{cause:s.message}:void 0)}return b$4(this.context,t,i),i}async getValidatedData(){await this.resolveModelSchema();let e=await super.getValidatedData();if(this.context&&e.body!==void 0&&Lo(this)){let t=e.body;try{t=await this.context.req.json();}catch{}let r=this.getBodySchema().safeParse(t);if(!r.success)throw b.fromZodError(r.error);e.body=r.data;}return e}};var St=class extends x{beforeHookMode="sequential";afterHookMode="sequential";allowNestedCreate=[];getBodySchema(){let e,t=H(this._meta.model),o=this.getMultiTenantConfig();o.enabled&&t.push(o.field),this._meta.fields?e=this._meta.fields:e=V(this.getModelSchema(),t);let r=this.getNestedWritableRelations();if(r.length===0)return e;let i={...e.shape};for(let s of r){let u=this._meta.model.relations?.[s];if(!u?.schema)continue;let l=["id",u.foreignKey],c=V(u.schema,l);u.type==="hasMany"?i[s]=z.array(c).optional():i[s]=c.optional();}return z.object(i)}getNestedWritableRelations(){if(this.allowNestedCreate.length>0)return this.allowNestedCreate;let e=this._meta.model.relations;return e?Object.entries(e).filter(([t,o])=>o.nestedWrites?.allowCreate===true).map(([t])=>t):[]}extractNestedData(e){let t=this.getNestedWritableRelations();return X(e,t)}getSchema(){let e=this.getBodySchema();return {...this.schema,request:{body:{content:{"application/json":{schema:e}},required:true}},responses:{201:{description:"Resource created successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:J("Validation error")}}}async getObject(){let{body:e}=await this.getValidatedData();return e}async before(e,t){return e}async after(e,t){return e}transform(e){return e}async createNested(e,t,o,r,i){return b$1().warn(`Nested writes not implemented for ${t}. Override createNested() in your adapter.`),[]}async handle(){this.validateTenantId();let e=await this.getObject(),{mainData:t,nestedData:o}=this.extractNestedData(e),r=t;r=this.injectTenantId(r);let i=this.buildHookContext();r=await this.before(r,i),r=await this.encryptOnWrite(r),r=await this.create(r,i.db.tx).catch(K),r=await this.decryptOnRead(r);let s=this.getParentId(r),u={};if(Object.keys(o).length>0&&s!==null)for(let[c,a]of Object.entries(o)){if(a==null)continue;let d=this._meta.model.relations?.[c];if(!d)continue;let p=await this.createNested(s,c,d,a);u[c]=p;}if(Object.keys(u).length>0){let c={};for(let[a,d]of Object.entries(u)){let p=this._meta.model.relations?.[a];p&&(p.type==="hasMany"?c[a]=d:c[a]=d[0]||null);}r={...r,...c};}if(this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(r,i))):r=await this.after(r,i),this.isAuditEnabled()&&s!==null){let c=this.getAuditLogger();this.runAfterResponse(c.logCreate(this._meta.model.tableName,s,r,this.getAuditUserId()));}s!==null&&this.runAfterResponse(this.emitEvent("created",{recordId:s,data:r}));let l=await this.finalizeRecord(r);return this.success(l,201)}};var xt=class extends x{lookupField="id";lookupFields;additionalFilters;etagEnabled=false;allowedIncludes=[];fieldSelectionEnabled=false;allowedSelectFields=[];blockedSelectFields=[];alwaysIncludeFields=[];defaultSelectFields=[];getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){let e={};if(this.additionalFilters?.length)for(let t of this.additionalFilters)e[t]=z.string().optional();if(this.allowedIncludes.length>0&&(e.include=z.string().optional().meta({description:`Comma-separated list of relations to include. Allowed: ${this.allowedIncludes.join(", ")}`})),this.fieldSelectionEnabled){let t=this.getAvailableSelectFields();e.fields=z.string().optional().meta({description:`Comma-separated list of fields to return. Available: ${t.join(", ")}`});}if(Object.keys(e).length!==0)return z.object(e)}getAvailableSelectFields(){let e=Object.keys(this.getModelSchema().shape),t=this._meta.model.computedFields?Object.keys(this._meta.model.computedFields):[],o=this._meta.model.relations?Object.keys(this._meta.model.relations):[],r=[...e,...t,...o];return this.allowedSelectFields.length>0&&(r=r.filter(i=>this.allowedSelectFields.includes(i))),this.blockedSelectFields.length>0&&(r=r.filter(i=>!this.blockedSelectFields.includes(i))),r}getSchema(){let e=this.getQuerySchema();return {...this.schema,request:{params:this.getParamsSchema(),...e&&{query:e}},responses:{200:{description:"Resource retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},404:J("Resource not found")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async getIncludeOptions(){let{query:e}=await this.getValidatedData(),t=e?.include;if(!t||typeof t!="string")return {relations:[]};let o=t.split(",").map(r=>r.trim()).filter(Boolean);return this.allowedIncludes.length>0?{relations:o.filter(r=>this.allowedIncludes.includes(r))}:{relations:o}}async getFieldSelection(){if(!this.fieldSelectionEnabled)return {fields:[],isActive:false};let{query:e}=await this.getValidatedData(),t=e?.fields;if(!t||typeof t!="string"||t.trim()==="")return this.defaultSelectFields.length>0?{fields:[...new Set([...this.alwaysIncludeFields,...this.defaultSelectFields])],isActive:true}:{fields:[],isActive:false};let o=t.split(",").map(s=>s.trim()).filter(Boolean),r=new Set(this.getAvailableSelectFields()),i=o.filter(s=>r.has(s));return this.alwaysIncludeFields.length>0&&(i=[...new Set([...this.alwaysIncludeFields,...i])]),{fields:i,isActive:true}}async after(e){return e}transform(e){return e}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getAdditionalFilters(),r=await this.getIncludeOptions(),i=await this.getFieldSelection();if(e){let c=this.getMultiTenantConfig();o[c.field]=e;}let s=await this.read(t,o,r);if(!s)throw new c(this._meta.model.tableName,t);s=await this.decryptOnRead(s);let u=await this.applyReadPolicy(s);if(u===null)throw new c(this._meta.model.tableName,t);s=u,s=await this.after(s);let l=await this.finalizeRecord(s,i);if(this.etagEnabled){let c=await ae(l),a=this.getContext(),d=a.req.header("If-None-Match");if(Mt(d,c))return new Response(null,{status:304,headers:{ETag:c}});a.header("ETag",c);}return this.success(l)}};var Ot=class extends x{lookupField="id";lookupFields;additionalFilters;allowedUpdateFields;blockedUpdateFields;beforeHookMode="sequential";afterHookMode="sequential";allowNestedWrites=[];etagEnabled=false;getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getBodySchema(){let e;if(this._meta.fields)e=this._meta.fields.partial();else {let r=H(this._meta.model);this.blockedUpdateFields&&(r=[...r,...this.blockedUpdateFields]);let i=V(this.getModelSchema(),r);if(this.allowedUpdateFields){let s={};for(let u of this.allowedUpdateFields)s[u]=true;i=i.pick(s);}e=i.partial();}let t=this.getNestedWritableRelations();if(t.length===0)return e;let o={...e.shape};for(let r of t){let i=this._meta.model.relations?.[r];if(!i?.schema)continue;let s=i.schema,u=z.object({create:z.union([s.partial(),z.array(s.partial())]).optional(),update:z.array(s.partial().extend({id:z.union([z.string(),z.number()])})).optional(),delete:z.array(z.union([z.string(),z.number()])).optional(),connect:z.array(z.union([z.string(),z.number()])).optional(),disconnect:z.array(z.union([z.string(),z.number()])).optional(),set:s.partial().nullable().optional()}).optional();o[r]=u;}return z.object(o)}getNestedWritableRelations(){if(this.allowNestedWrites.length>0)return this.allowNestedWrites;let e=this._meta.model.relations;return e?Object.entries(e).filter(([t,o])=>{let r=o.nestedWrites;return r&&(r.allowCreate||r.allowUpdate||r.allowDelete||r.allowConnect||r.allowDisconnect)}).map(([t])=>t):[]}extractNestedData(e){let t=this.getNestedWritableRelations();return X(e,t)}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),body:{content:{"application/json":{schema:this.getBodySchema()}},required:true}},responses:{200:{description:"Resource updated successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:J("Validation error"),404:J("Resource not found")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getObject(){let{body:e}=await this.getValidatedData();return e}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async before(e,t){return e}async after(e,t,o){return t}transform(e){return e}async findExisting(e,t,o){return null}async processNestedWrites(e,t,o,r,i){return b$1().warn(`Nested writes not implemented for ${t}. Override processNestedWrites() in your adapter.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]}}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getAdditionalFilters();if(e){let b=this.getMultiTenantConfig();o[b.field]=e;}let r=await this.getObject(),{mainData:i,nestedData:s}=this.extractNestedData(r),u=this.getPolicies(),l=await this.findExisting(t,o,this._tx);if(l&&u?.write&&await this.applyWritePolicy(l),this.etagEnabled&&l){let b=this.getContext().req.header("If-Match");if(b){let g=await ae(l);if(!Rt(b,g))return this.error("Resource has been modified by another request","CONFLICT",409)}}let c$1;if(this.isVersioningEnabled()&&l){let b=this.getVersionManager(),g=this.getParentId(l);g!==null&&(c$1=await b.saveVersion(g,l,void 0,this.getVersioningUserId()));}let a=i;if(this.isVersioningEnabled()&&c$1!==void 0){let b=this.getVersioningConfig().field;a[b]=c$1;}let d=this.buildHookContext();a=await this.before(a,d),a=await this.encryptOnWrite(a);let p=await this.update(t,a,o,d.db.tx);if(!p)throw new c(this._meta.model.tableName,t);p=await this.decryptOnRead(p);let m=this.getParentId(p),h={};if(Object.keys(s).length>0&&m!==null)for(let[b,g]of Object.entries(s)){if(g==null)continue;let S=this._meta.model.relations?.[b];if(!S)continue;let j;he(g)?j={create:g}:j=g;let A=await this.processNestedWrites(m,b,S,j);h[b]=A;}if(Object.keys(h).length>0)for(let[b,g]of Object.entries(h)){let S=this._meta.model.relations?.[b];S&&(S.type==="hasMany"?p[b]=[...g.created,...g.updated]:p[b]=g.created[0]||g.updated[0]||null);}let f=l??p;if(this.afterHookMode==="fire-and-forget")this.runAfterResponse(Promise.resolve(this.after(f,p,d)));else {let b=await this.after(f,p,d);b!=null&&(p=b);}if(this.isAuditEnabled()&&m!==null&&l){let b=this.getAuditLogger();this.runAfterResponse(b.logUpdate(this._meta.model.tableName,m,l,p,this.getAuditUserId()));}m!==null&&this.runAfterResponse(this.emitEvent("updated",{recordId:m,data:p,previousData:l??void 0}));let y=await this.finalizeRecord(p);if(this.etagEnabled){let b=await ae(y);this.getContext().header("ETag",b);}return this.success(y)}};var kt=class extends x{lookupField="id";lookupFields;additionalFilters;beforeHookMode="sequential";afterHookMode="sequential";includeCascadeResults=false;getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getCascadeRelations(e){let t=this._meta.model.relations;return t?Object.entries(t).filter(([o,r])=>{let i=r.cascade?.[e];return i&&i!=="noAction"}).map(([o,r])=>({name:o,config:r,action:r.cascade[e]})):[]}getSchema(){let e=this.includeCascadeResults?z.object({deleted:z.literal(true),cascade:z.object({deleted:z.record(z.string(),z.number()),nullified:z.record(z.string(),z.number())}).optional()}):z.object({deleted:z.literal(true)});return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Resource deleted successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:e})}}},404:J("Resource not found"),409:{description:"Cannot delete - related records exist (restrict)",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.object({relation:z.string(),count:z.number()}).optional()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async before(e,t){}async after(e,t){}async countRelated(e,t,o,r){return b$1().warn(`countRelated not implemented for ${t}. Override in your adapter for restrict cascade to work.`),0}async deleteRelated(e,t,o,r){return b$1().warn(`deleteRelated not implemented for ${t}. Override in your adapter for cascade delete to work.`),0}async nullifyRelated(e,t,o,r){return b$1().warn(`nullifyRelated not implemented for ${t}. Override in your adapter for setNull cascade to work.`),0}async processCascade(e,t,o){let r=t?"onSoftDelete":"onDelete",i=this.getCascadeRelations(r),s={deleted:{},nullified:{}};for(let{name:u,config:l,action:c}of i)if(c==="cascade"){let a=await this.deleteRelated(e,u,l,o);a>0&&(s.deleted[u]=a);}else if(c==="setNull"){let a=await this.nullifyRelated(e,u,l,o);a>0&&(s.nullified[u]=a);}return s}async checkRestrictConstraints(e,t,o){let r=t?"onSoftDelete":"onDelete",i=this.getCascadeRelations(r);for(let{name:s,config:u,action:l}of i)if(l==="restrict"){let c=await this.countRelated(e,s,u,o);if(c>0)throw new d(`Cannot delete: ${c} related ${s} record(s) exist. Remove them first or change the cascade configuration.`,{relation:s,count:c})}}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getAdditionalFilters();if(e){let d=this.getMultiTenantConfig();o[d.field]=e;}let r=this.isSoftDeleteEnabled(),i=await this.findForDelete(t,o,this._tx);if(!i)throw new c(this._meta.model.tableName,t);let s=this.getParentId(i);s!==null&&await this.checkRestrictConstraints(s,r),await this.applyWritePolicy(i);let u=this.buildHookContext();if(await this.before(t,u),!await this.delete(t,o,u.db.tx))throw new c(this._meta.model.tableName,t);let c$1;if(s!==null&&(c$1=await this.processCascade(s,r)),this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(i,u))):await this.after(i,u),this.isAuditEnabled()&&s!==null){let d=this.getAuditLogger();this.runAfterResponse(d.logDelete(this._meta.model.tableName,s,i,this.getAuditUserId()));}s!==null&&this.runAfterResponse(this.emitEvent("deleted",{recordId:s,previousData:i}));let a={deleted:true};if(this.includeCascadeResults&&c$1){let d=Object.keys(c$1.deleted).length>0,p=Object.keys(c$1.nullified).length>0;(d||p)&&(a.cascade=c$1);}return this.success(a)}};var fe=class extends x{filterFields=[];filterConfig;searchFields=[];searchFieldName="search";sortFields=[];defaultSort;defaultPerPage=20;maxPerPage=100;cursorPaginationEnabled=false;cursorField;allowedIncludes=[];fieldSelectionEnabled=false;allowedSelectFields=[];blockedSelectFields=[];alwaysIncludeFields=[];defaultSelectFields=[];getQuerySchema(){let e={page:z.string().optional(),per_page:z.string().optional()};this.sortFields.length>0&&(e.sort=z.enum(this.sortFields).optional().meta({description:"Field to sort by"}),e.order=z.enum(d$1).optional().meta({description:"Sort direction (asc or desc)"})),this.searchFields.length>0&&(e[this.searchFieldName]=z.string().optional());for(let o of this.filterFields)e[o]=z.string().optional();if(this.filterConfig)for(let[o,r]of Object.entries(this.filterConfig)){for(let i of r)e[`${o}[${i}]`]=z.string().optional();e[o]=z.string().optional();}let t=this.getSoftDeleteConfig();if(t.enabled&&t.allowQueryDeleted&&(e[t.queryParam]=z.enum(["true","false"]).optional(),e.onlyDeleted=z.enum(["true","false"]).optional()),this.allowedIncludes.length>0&&(e.include=z.string().optional().meta({description:`Comma-separated list of relations to include. Allowed: ${this.allowedIncludes.join(", ")}`})),this.fieldSelectionEnabled){let o=this.getAvailableSelectFields();e.fields=z.string().optional().meta({description:`Comma-separated list of fields to return. Available: ${o.join(", ")}`});}return this.cursorPaginationEnabled&&(e.cursor=z.string().optional().meta({description:"Opaque cursor for fetching the next page"}),e.limit=z.string().optional().meta({description:"Number of items to return (cursor pagination)"})),z.object(e)}getAvailableSelectFields(){let e=Object.keys(this.getModelSchema().shape),t=this._meta.model.computedFields?Object.keys(this._meta.model.computedFields):[],o=this._meta.model.relations?Object.keys(this._meta.model.relations):[],r=[...e,...t,...o];return this.allowedSelectFields.length>0&&(r=r.filter(i=>this.allowedSelectFields.includes(i))),this.blockedSelectFields.length>0&&(r=r.filter(i=>!this.blockedSelectFields.includes(i))),r}getSchema(){return {...this.schema,request:{query:this.getQuerySchema()},responses:{200:{description:"List of resources",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.array(this.getModelSchema()),result_info:z.object({page:z.number(),per_page:z.number(),total_count:z.number().optional(),total_pages:z.number().optional(),has_next_page:z.boolean(),has_prev_page:z.boolean(),next_cursor:z.string().optional(),prev_cursor:z.string().optional()})})}}},400:J("Validation error")}}}async getFilters(){let{query:e}=await this.getValidatedData(),t=this.getSoftDeleteConfig(),o={filterFields:this.filterFields,filterConfig:this.filterConfig,searchFields:this.searchFields,searchFieldName:this.searchFieldName,sortFields:this.sortFields,defaultSort:this.defaultSort,defaultPerPage:this.defaultPerPage,maxPerPage:this.maxPerPage,cursorPaginationEnabled:this.cursorPaginationEnabled,cursorField:this.cursorField,softDeleteQueryParam:t.queryParam,allowedIncludes:this.allowedIncludes,fieldSelectionEnabled:this.fieldSelectionEnabled,allowedSelectFields:this.allowedSelectFields,blockedSelectFields:this.blockedSelectFields,alwaysIncludeFields:this.alwaysIncludeFields,defaultSelectFields:this.defaultSelectFields};return ee(e||{},o)}async after(e){return e}transform(e){return e}async handle(){let e=this.validateTenantId(),t=await this.getFilters();if(e){let c=this.getMultiTenantConfig();t.filters.push({field:c.field,operator:"eq",value:e});}this.applyReadPushdown(t);let o=await this.list(t),r=await Promise.all(o.result.map(c=>this.decryptOnRead(c))),i=await this.applyReadPolicyToArray(r),s=await this.after(i),u=this.fieldSelectionEnabled&&t.options.fields&&t.options.fields.length>0?{fields:t.options.fields,isActive:true}:void 0,l=await this.finalizeArray(s,u);return this.successPaginated(l,o.result_info)}};var Ct=class extends x{lookupField="id";excludeFromClone=[];getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getBodySchema(){let e=[...H(this._meta.model),...this.excludeFromClone];return V(this.getModelSchema(),e).partial()}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),body:{content:{"application/json":{schema:this.getBodySchema()}},required:false}},responses:{201:{description:"Resource cloned successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},404:J("Source resource not found"),409:J("Unique-constraint violation (e.g. natural-key collision)")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getOverrides(){let{body:e}=await this.getValidatedData();return e||{}}async before(e){return e}async after(e){return e}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getOverrides(),r={};if(e){let a=this.getMultiTenantConfig();r[a.field]=e;}let i=await this.findSource(t,r);if(!i)throw new c(this._meta.model.tableName,t);let s=st(i,this._meta.model);for(let a of this.excludeFromClone)delete s[a];Object.assign(s,o);let u=await this.before(s),l=await this.createClone(u).catch(K);l=await this.after(l);let c$1=await this.finalizeRecord(l);return this.success(c$1,201)}};var ge=new Map,Bo=["password","token","secret","apiKey","creditCard","ssn"];function Se(n,e){if(n==null||typeof n!="object")return n;if(Array.isArray(n))return n.map(o=>Se(o,e));let t={};for(let[o,r]of Object.entries(n))e.includes(o)||(t[o]=typeof r=="object"&&r!==null?Se(r,e):r);return t}function qo(n){let{table:e,events:t,emitter:o,filter:r,heartbeatInterval:i=3e4,maxConnections:s=1e3,connectionTimeout:u=3e5,excludeFields:l=Bo}=n;return c=>{let a$1=d$2(c,o);if(!a$1)throw new a("Event emitter not configured",500,"EVENT_EMITTER_NOT_CONFIGURED");let d=ge.get(e)||0;if(d>=s)throw new a("Too many SSE connections",503,"TOO_MANY_CONNECTIONS");return ge.set(e,d+1),streamSSE(c,async p=>{let m,h=async g=>{if(t&&t.length>0&&!t.includes(g.type)||r&&!r(g,c))return;let S=l.length>0?Se(g.data,l):g.data,j=g.previousData&&l.length>0?Se(g.previousData,l):g.previousData;try{await p.writeSSE({event:`${g.table}.${g.type}`,data:JSON.stringify({type:g.type,table:g.table,recordId:g.recordId,data:S,previousData:j,timestamp:g.timestamp}),id:`${g.table}-${g.recordId}-${Date.now()}`});}catch{}};m=a$1.onTable(e,h);let f=()=>{m.unsubscribe();let g=ge.get(e)||1;g<=1?ge.delete(e):ge.set(e,g-1);};p.onAbort(()=>{f();});let y=Date.now(),b=y;for(;!p.closed;){await p.sleep(1e3);let g=Date.now();if(g-y>=u){p.abort();break}if(g-b>=i){b=g;try{await p.writeSSE({event:"heartbeat",data:JSON.stringify({timestamp:new Date().toISOString()})});}catch{break}}}})}}var Pt=class extends x{lookupField="id";lookupFields;additionalFilters;beforeHookMode="sequential";afterHookMode="sequential";getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Resource restored successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:J("Soft delete not enabled or record not deleted"),404:J("Resource not found")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async before(e,t){}async after(e,t){return e}async handle(){if(!this.isSoftDeleteEnabled())throw new a("Soft delete is not enabled for this model",400,"SOFT_DELETE_NOT_ENABLED");let e=await this.getLookupValue(),t=await this.getAdditionalFilters();await this.before(e);let o=await this.restore(e,t);if(!o)throw new c(this._meta.model.tableName,e);this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(o))):o=await this.after(o);let r=this.getRecordId(o);if(this.isAuditEnabled()&&r!==null){let s=this.getAuditLogger();this.runAfterResponse(s.logRestore(this._meta.model.tableName,r,o,this.getAuditUserId()));}r!==null&&this.runAfterResponse(this.emitEvent("restored",{recordId:r,data:o}));let i=await this.finalizeRecord(o);return this.success(i)}};var It=class extends x{upsertKeys;useNativeUpsert=false;createOnlyFields;updateOnlyFields;beforeHookMode="sequential";afterHookMode="sequential";allowNestedWrites=[];getUpsertKeys(){return this.upsertKeys||this._meta.model.primaryKeys}getBodySchema(){let e;if(this._meta.fields)e=this._meta.fields;else {let r=this.getUpsertKeys(),i=H(this._meta.model,{includePrimaryKeys:false});for(let l of this._meta.model.primaryKeys)r.includes(l)||i.push(l);let s=V(this.getModelSchema(),i),u={};for(let[l,c]of Object.entries(s.shape))r.includes(l)?u[l]=c:u[l]=c.optional();e=z.object(u);}let t=this.getNestedWritableRelations();if(t.length===0)return e;let o={...e.shape};for(let r of t){let i=this._meta.model.relations?.[r];if(!i?.schema)continue;let s=i.schema,u=z.union([i.type==="hasMany"?z.array(s.partial()):s.partial(),z.object({create:z.union([s.partial(),z.array(s.partial())]).optional(),update:z.array(s.partial().extend({id:z.union([z.string(),z.number()])})).optional(),upsert:z.union([s.partial(),z.array(s.partial())]).optional(),delete:z.array(z.union([z.string(),z.number()])).optional(),connect:z.array(z.union([z.string(),z.number()])).optional(),disconnect:z.array(z.union([z.string(),z.number()])).optional(),set:s.partial().nullable().optional()})]).optional();o[r]=u;}return z.object(o)}getNestedWritableRelations(){if(this.allowNestedWrites.length>0)return this.allowNestedWrites;let e=this._meta.model.relations;return e?Object.entries(e).filter(([t,o])=>{let r=o.nestedWrites;return r&&(r.allowCreate||r.allowUpdate||r.allowDelete||r.allowConnect||r.allowDisconnect)}).map(([t])=>t):[]}extractNestedData(e){let t=this.getNestedWritableRelations();return X(e,t)}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}},required:true}},responses:{200:{description:"Resource updated (upsert)",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema(),created:z.literal(false)})}}},201:{description:"Resource created (upsert)",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema(),created:z.literal(true)})}}},400:J("Validation error")}}}async getObject(){let{body:e}=await this.getValidatedData();return e}async before(e,t,o){return e}async beforeCreate(e,t){return e}async beforeUpdate(e,t,o){return e}async after(e,t,o){return e}async nativeUpsert(e,t){return b$1().warn("Native upsert not implemented for this adapter. Falling back to find-then-insert/update pattern."),this.performStandardUpsert(e,t)}async performStandardUpsert(e,t){let o=await this.findExisting(e,t);if(o){let r={...e};if(this.createOnlyFields)for(let s of this.createOnlyFields)delete r[s];return r=await this.beforeUpdate(r,o,t),{data:await this.update(o,r,t),created:false}}else {let r={...e};if(this.updateOnlyFields)for(let s of this.updateOnlyFields)delete r[s];return r=await this.beforeCreate(r,t),{data:await this.create(r,t),created:true}}}async upsert(e,t){return this.useNativeUpsert?this.nativeUpsert(e,t):this.performStandardUpsert(e,t)}async processNestedWrites(e,t,o,r,i){return b$1().warn(`Nested writes not implemented for ${t}. Override processNestedWrites() in your adapter.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]}}async handle(){this.validateTenantId();let e=await this.getObject(),{mainData:t,nestedData:o}=this.extractNestedData(e),r=t;r=this.injectTenantId(r);let i=await this.findExisting(r),s=!i;r=await this.before(r,s);let u=await this.upsert(r).catch(K),l=u.data,c=this.getParentId(l),a={};if(Object.keys(o).length>0&&c!==null)for(let[p,m]of Object.entries(o)){if(m==null)continue;let h=this._meta.model.relations?.[p];if(!h)continue;let f;he(m)?f={create:m}:f=m;let y=await this.processNestedWrites(c,p,h,f);a[p]=y;}if(Object.keys(a).length>0)for(let[p,m]of Object.entries(a)){let h=this._meta.model.relations?.[p];h&&(h.type==="hasMany"?l[p]=[...m.created,...m.updated]:l[p]=m.created[0]||m.updated[0]||null);}if(this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(l,u.created))):l=await this.after(l,u.created),this.isAuditEnabled()&&c!==null){let p=this.getAuditLogger();this.runAfterResponse(p.logUpsert(this._meta.model.tableName,c,l,i,u.created,this.getAuditUserId()));}let d=await this.finalizeRecord(l);return this.json({success:true,result:d,created:u.created},u.created?201:200)}};var vt=class extends x{maxBatchSize=100;stopOnError=true;beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){let e=this._meta.fields?this._meta.fields:V(this.getModelSchema(),H(this._meta.model));return z.object({items:z.array(e).min(1).max(this.maxBatchSize)})}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{201:{description:"Resources created successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({created:z.array(this.getModelSchema()),count:z.number()})})}}},207:{description:"Partial success (some items failed)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({created:z.array(this.getModelSchema()),count:z.number(),errors:z.array(z.object({index:z.number(),error:z.string()})).optional()})})}}},400:J("Validation error")}}}async getItems(){let{body:e}=await this.getValidatedData();return e?.items||[]}async before(e,t,o){return e}async after(e,t,o){return e}transform(e){return e}async handle(){let e=await this.getItems(),t=[],o=[];for(let c=0;c<e.length;c++)try{let a=await this.before(e[c],c);o.push(a);}catch(a){if(this.stopOnError)throw a;t.push({index:c,error:a instanceof Error?a.message:String(a)});}let r=await this.batchCreate(o).catch(K),i=[];for(let c=0;c<r.length;c++)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(r[c],c))),i.push(r[c])):i.push(await this.after(r[c],c));}catch(a){if(this.stopOnError)throw a;t.push({index:c,error:a instanceof Error?a.message:String(a)}),i.push(r[c]);}if(this.isAuditEnabled()){let c=this.getAuditLogger(),a=i.map(d=>{let p=this.getRecordId(d);return p===null?null:{recordId:p,record:d}}).filter(d=>d!==null);a.length>0&&this.runAfterResponse(c.logBatch("batch_create",this._meta.model.tableName,a,this.getAuditUserId()));}let s=await this.finalizeArray(i),u={success:true,result:{created:s,count:s.length,...t.length>0&&{errors:t}}},l=t.length>0?207:201;return this.json(u,l)}};var Ft=class extends x{maxBatchSize=100;stopOnError=false;lookupField="id";allowedUpdateFields;blockedUpdateFields;beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){let e=this._meta.fields?this._meta.fields:V(this.getModelSchema(),H(this._meta.model));return z.object({items:z.array(z.object({id:z.string(),data:e.partial()})).min(1).max(this.maxBatchSize)})}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{200:{description:"Resources updated successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({updated:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional()})})}}},207:{description:"Partial success (some items failed or not found)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({updated:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional(),errors:z.array(z.object({id:z.string(),error:z.string()})).optional()})})}}},400:J("Validation error")}}}async getItems(){let{body:e}=await this.getValidatedData();return e?.items||[]}filterUpdateData(e){let t={...e};if(this.allowedUpdateFields){let o=new Set(this.allowedUpdateFields);t=Object.fromEntries(Object.entries(t).filter(([r])=>o.has(r)));}if(this.blockedUpdateFields)for(let o of this.blockedUpdateFields)delete t[o];for(let o of this._meta.model.primaryKeys)delete t[o];return t}async before(e,t,o){return t}async after(e,t){return e}async handle(){let e=await this.getItems(),t=[],o=[];for(let a of e)try{let d=this.filterUpdateData(a.data),p=await this.before(a.id,d);o.push({id:a.id,data:p});}catch(d){if(this.stopOnError)throw d;t.push({id:a.id,error:d instanceof Error?d.message:String(d)});}let{updated:r,notFound:i}=await this.batchUpdate(o),s=[];for(let a of r)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(a))),s.push(a)):s.push(await this.after(a));}catch(d){let p=String(a[this.lookupField]);if(this.stopOnError)throw d;t.push({id:p,error:d instanceof Error?d.message:String(d)}),s.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),d=s.map(p=>{let m=this.getRecordId(p);return m===null?null:{recordId:m,record:p}}).filter(p=>p!==null);d.length>0&&this.runAfterResponse(a.logBatch("batch_update",this._meta.model.tableName,d,this.getAuditUserId()));}let u=await this.finalizeArray(s),l={success:true,result:{updated:u,count:u.length,...i.length>0&&{notFound:i},...t.length>0&&{errors:t}}},c=t.length>0||i.length>0?207:200;return this.json(l,c)}};var jt=class extends x{maxBatchSize=100;stopOnError=false;lookupField="id";beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){return z.object({ids:z.array(z.string()).min(1).max(this.maxBatchSize)})}getSchema(){let e=this.isSoftDeleteEnabled();return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{200:{description:e?"Resources soft-deleted successfully":"Resources deleted successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({deleted:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional()})})}}},207:{description:"Partial success (some items failed or not found)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({deleted:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional(),errors:z.array(z.object({id:z.string(),error:z.string()})).optional()})})}}},400:J("Validation error")}}}async getIds(){let{body:e}=await this.getValidatedData();return e?.ids||[]}async before(e,t){}async after(e,t){return e}async handle(){let e=await this.getIds(),t=[],o=[];for(let a of e)try{await this.before(a),o.push(a);}catch(d){if(this.stopOnError)throw d;t.push({id:a,error:d instanceof Error?d.message:String(d)});}let{deleted:r,notFound:i}=await this.batchDelete(o),s=[];for(let a of r)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(a))),s.push(a)):s.push(await this.after(a));}catch(d){let p=String(a[this.lookupField]);if(this.stopOnError)throw d;t.push({id:p,error:d instanceof Error?d.message:String(d)}),s.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),d=s.map(p=>{let m=this.getRecordId(p);return m===null?null:{recordId:m,previousRecord:p}}).filter(p=>p!==null);d.length>0&&this.runAfterResponse(a.logBatch("batch_delete",this._meta.model.tableName,d,this.getAuditUserId()));}let u=this._meta.model.serializer?s.map(a=>this._meta.model.serializer(a)):s,l={success:true,result:{deleted:u,count:u.length,...i.length>0&&{notFound:i},...t.length>0&&{errors:t}}},c=t.length>0||i.length>0?207:200;return this.json(l,c)}};var At=class extends x{maxBatchSize=100;stopOnError=false;lookupField="id";beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){return z.object({ids:z.array(z.string()).min(1).max(this.maxBatchSize)})}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{200:{description:"Resources restored successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({restored:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional()})})}}},207:{description:"Partial success (some items failed or not found)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({restored:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional(),errors:z.array(z.object({id:z.string(),error:z.string()})).optional()})})}}},400:J("Soft delete not enabled or validation error")}}}async getIds(){let{body:e}=await this.getValidatedData();return e?.ids||[]}async before(e,t){}async after(e,t){return e}async handle(){if(!this.isSoftDeleteEnabled())throw new a("Soft delete is not enabled for this model",400,"SOFT_DELETE_NOT_ENABLED");let e=await this.getIds(),t=[],o=[];for(let a of e)try{await this.before(a),o.push(a);}catch(d){if(this.stopOnError)throw d;t.push({id:a,error:d instanceof Error?d.message:String(d)});}let{restored:r,notFound:i}=await this.batchRestore(o),s=[];for(let a of r)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(a))),s.push(a)):s.push(await this.after(a));}catch(d){let p=String(a[this.lookupField]);if(this.stopOnError)throw d;t.push({id:p,error:d instanceof Error?d.message:String(d)}),s.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),d=s.map(p=>{let m=this.getRecordId(p);return m===null?null:{recordId:m,record:p}}).filter(p=>p!==null);d.length>0&&this.runAfterResponse(a.logBatch("batch_restore",this._meta.model.tableName,d,this.getAuditUserId()));}let u=await this.finalizeArray(s),l={success:true,result:{restored:u,count:u.length,...i.length>0&&{notFound:i},...t.length>0&&{errors:t}}},c=t.length>0||i.length>0?207:200;return this.json(l,c)}};var _t=class extends x{upsertKeys;createOnlyFields;updateOnlyFields;maxBatchSize=100;continueOnError=false;useNativeUpsert=false;beforeHookMode="sequential";afterHookMode="sequential";getUpsertKeys(){return this.upsertKeys||this._meta.model.primaryKeys}getItemSchema(){if(this._meta.fields)return this._meta.fields;let e=this.getUpsertKeys(),t=H(this._meta.model,{includePrimaryKeys:false});for(let i of this._meta.model.primaryKeys)e.includes(i)||t.push(i);let o=V(this.getModelSchema(),t),r={};for(let[i,s]of Object.entries(o.shape))e.includes(i)?r[i]=s:r[i]=s.optional();return z.object(r)}getBodySchema(){return z.array(this.getItemSchema()).max(this.maxBatchSize)}getSchema(){let e=z.object({data:this.getModelSchema(),created:z.boolean(),index:z.number()});return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}},required:true}},responses:{200:{description:"Batch upsert completed",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({items:z.array(e),createdCount:z.number(),updatedCount:z.number(),totalCount:z.number(),errors:z.array(z.object({index:z.number(),error:z.string()})).optional()})})}}},400:J("Validation error")}}}async getItems(){let{body:e}=await this.getValidatedData();return e}async beforeItem(e,t,o,r){return e}async afterItem(e,t,o,r){return e}async beforeBatch(e,t){return e}async afterBatch(e,t){return e}async upsertOne(e,t,o){let r=await this.findExisting(e,o),i=!r,s=await this.beforeItem(e,t,i,o),u;if(r){if(this.createOnlyFields)for(let l of this.createOnlyFields)delete s[l];u=await this.update(r,s,o);}else {if(this.updateOnlyFields)for(let l of this.updateOnlyFields)delete s[l];u=await this.create(s,o);}return u=await this.afterItem(u,t,i,o),{data:u,created:i,index:t}}async nativeBatchUpsert(e,t){return b$1().warn("Native batch upsert not implemented for this adapter. Falling back to item-by-item pattern."),this.performStandardBatchUpsert(e,t)}async performStandardBatchUpsert(e,t){let o=[],r=[],i=0,s=0;for(let l=0;l<e.length;l++)try{let c=await this.upsertOne(e[l],l,t);o.push(c),c.created?i++:s++;}catch(c){if(this.continueOnError)r.push({index:l,error:c instanceof Error?c.message:String(c)});else throw c}let u={items:o,createdCount:i,updatedCount:s,totalCount:o.length};return r.length>0&&(u.errors=r),u}async batchUpsert(e,t){return this.useNativeUpsert?this.nativeBatchUpsert(e,t):this.performStandardBatchUpsert(e,t)}async handle(){let e=await this.getItems();e=await this.beforeBatch(e);let t=await this.batchUpsert(e).catch(K);if(t=await this.afterBatch(t),this._meta.model.computedFields&&(t.items=await Promise.all(t.items.map(async o=>({...o,data:await se(o.data,this._meta.model.computedFields)})))),this.isAuditEnabled()){let o=this.getAuditLogger(),r=t.items.map(i=>{let s=this.getRecordId(i.data);return s===null?null:{recordId:s,record:i.data}}).filter(i=>i!==null);r.length>0&&this.runAfterResponse(o.logBatch("batch_upsert",this._meta.model.tableName,r,this.getAuditUserId()));}return t.items=t.items.map(o=>{let r=this._meta.model.serializer?this._meta.model.serializer(o.data):o.data,i=this.applyProfile(r);return {...o,data:this.transform(i)}}),this.success(t)}};var Tt=class extends x{maxBulkSize=1e3;confirmThreshold=100;returnRecords=false;hookMode="parallel";filterFields;getSchema(){return {request:{body:{content:{"application/json":{schema:this.getUpdateSchema().partial()}}},query:z.object({dryRun:z.string().optional()}).passthrough()},responses:{200:{description:"Bulk patch result",content:{"application/json":{schema:z.object({success:z.boolean(),matched:z.number(),updated:z.number(),dryRun:z.boolean()})}}},400:J("Bulk patch rejected (empty body, size limit, or missing confirmation)")}}}async handle(){let e=this.getContext(),o=(await this.getValidatedData()).body;if(!o||Object.keys(o).length===0)return this.error("Request body is required with at least one field to update","EMPTY_BODY",400);let r=e.req.query("dryRun"),i=r==="true"||r==="1",s=ee(e.req.query(),{filterFields:this.filterFields,defaultPerPage:this.maxBulkSize,maxPerPage:this.maxBulkSize}),u=await this.countMatching(s);if(u===0)return this.json({success:true,matched:0,updated:0,dryRun:i});if(u>this.maxBulkSize)return this.error(`Bulk patch affects ${u} records, exceeding the maximum of ${this.maxBulkSize}. Use more specific filters.`,"BULK_TOO_LARGE",400);if(u>=this.confirmThreshold&&e.req.header("X-Confirm-Bulk")!=="true")return this.error(`This operation will affect ${u} records. Set X-Confirm-Bulk: true header to confirm.`,"CONFIRMATION_REQUIRED",400);if(i)return this.json({success:true,matched:u,updated:0,dryRun:true});let l=o;this.beforeBulkPatch&&(l=await this.beforeBulkPatch(l,s,u));let c=await this.applyPatch(l,s),a={matched:u,updated:c.updated,dryRun:false,records:this.returnRecords?c.records:void 0};return this.afterBulkPatch&&await this.afterBulkPatch(a),this.json({success:true,matched:a.matched,updated:a.updated,dryRun:false,...this.returnRecords&&a.records?{records:a.records}:{}})}};var to=z.object({id:z.string(),recordId:z.union([z.string(),z.number()]),version:z.number(),data:z.record(z.string(),z.unknown()),createdAt:z.date(),changedBy:z.string().optional(),changeReason:z.string().optional(),changes:z.array(z.object({field:z.string(),oldValue:z.unknown().optional(),newValue:z.unknown().optional()})).optional()}),Nt=class extends x{lookupField="id";defaultLimit=20;maxLimit=100;getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){return z.object({limit:z.coerce.number().min(1).max(this.maxLimit).optional(),offset:z.coerce.number().min(0).optional()})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),query:this.getQuerySchema()},responses:{200:{description:"Version history retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({versions:z.array(to),totalVersions:z.number()})})}}},400:J("Versioning not enabled"),404:J("Record not found")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getPaginationOptions(){let{query:e}=await this.getValidatedData();return {limit:e?.limit?Number(e.limit):this.defaultLimit,offset:e?.offset?Number(e.offset):0}}async recordExists(e){return true}async handle(){if(!this.isVersioningEnabled())throw new a("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),{limit:t,offset:o}=await this.getPaginationOptions();if(!await this.recordExists(e))throw new c(this._meta.model.tableName,e);let i=this.getVersionManager(),s=await i.getVersions(e,{limit:t,offset:o}),u=await i.getLatestVersion(e);return this.success({versions:s,totalVersions:u})}},Dt=class extends x{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string(),version:z.coerce.number().min(1)})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Version retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:to})}}},400:J("Versioning not enabled"),404:J("Version not found")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getVersionNumber(){let{params:e}=await this.getValidatedData();return e?.version?Number(e.version):0}async handle(){if(!this.isVersioningEnabled())throw new a("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),t=await this.getVersionNumber(),r=await this.getVersionManager().getVersion(e,t);if(!r)throw new c(`version ${t}`,e);return this.success(r)}},Ht=class extends x{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){return z.object({from:z.coerce.number().min(1),to:z.coerce.number().min(1)})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),query:this.getQuerySchema()},responses:{200:{description:"Version comparison completed",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({from:z.number(),to:z.number(),changes:z.array(z.object({field:z.string(),oldValue:z.unknown().optional(),newValue:z.unknown().optional()}))})})}}},400:J("Versioning not enabled or invalid parameters"),404:J("Version not found")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getVersionNumbers(){let{query:e}=await this.getValidatedData();return {from:e?.from?Number(e.from):0,to:e?.to?Number(e.to):0}}async handle(){if(!this.isVersioningEnabled())throw new a("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),{from:t,to:o}=await this.getVersionNumbers(),i=await this.getVersionManager().compareVersions(e,t,o);return this.success({from:t,to:o,changes:i})}},Vt=class extends x{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string(),version:z.coerce.number().min(1)})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Record rolled back successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:J("Versioning not enabled"),404:J("Version not found")}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getVersionNumber(){let{params:e}=await this.getValidatedData();return e?.version?Number(e.version):0}async handle(){if(!this.isVersioningEnabled())throw new a("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),t=await this.getVersionNumber(),o=this.getVersionManager(),r=await o.getVersion(e,t);if(!r)throw new c(`version ${t}`,e);let s=await o.getLatestVersion(e)+1,u=await this.rollback(e,r.data,s),l=this._meta.model.serializer?this._meta.model.serializer(u):u;return this.success(l)}};var zo={sumFields:[],avgFields:[],minMaxFields:[],countDistinctFields:[],groupByFields:[],defaultLimit:100,maxLimit:1e3},Lt=class extends x{aggregateConfig={};maxGroupByFields=5;filterFields=[];getAggregateConfig(){return {...zo,...this.aggregateConfig}}getQuerySchema(){return z.object({count:z.union([z.string(),z.array(z.string())]).optional(),sum:z.union([z.string(),z.array(z.string())]).optional(),avg:z.union([z.string(),z.array(z.string())]).optional(),min:z.union([z.string(),z.array(z.string())]).optional(),max:z.union([z.string(),z.array(z.string())]).optional(),countDistinct:z.union([z.string(),z.array(z.string())]).optional(),groupBy:z.string().optional(),orderBy:z.string().optional(),orderDirection:z.enum(d$1).optional(),limit:z.coerce.number().optional(),offset:z.coerce.number().optional(),withDeleted:z.coerce.boolean().optional()}).passthrough()}getSchema(){let e=z.object({key:z.record(z.string(),z.unknown()),values:z.record(z.string(),z.number().nullable())});return {...this.schema,request:{query:this.getQuerySchema()},responses:{200:{description:"Aggregation result",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({values:z.record(z.string(),z.number().nullable()).optional(),groups:z.array(e).optional(),totalGroups:z.number().optional()})})}}},400:J("Invalid aggregation request")}}}async getAggregateOptions(){let{query:e}=await this.getValidatedData();return dt(e||{})}validateAggregations(e){let t=this.getAggregateConfig();for(let o of e.aggregations)if(!(o.operation==="count"&&o.field==="*"))switch(o.operation){case "count":break;case "sum":if(t.sumFields.length>0&&!t.sumFields.includes(o.field))throw new g(`Field '${o.field}' is not allowed for SUM aggregation`);break;case "avg":if(t.avgFields.length>0&&!t.avgFields.includes(o.field))throw new g(`Field '${o.field}' is not allowed for AVG aggregation`);break;case "min":case "max":if(t.minMaxFields.length>0&&!t.minMaxFields.includes(o.field))throw new g(`Field '${o.field}' is not allowed for MIN/MAX aggregation`);break;case "countDistinct":if(t.countDistinctFields.length>0&&!t.countDistinctFields.includes(o.field))throw new g(`Field '${o.field}' is not allowed for COUNT DISTINCT aggregation`);break;default:c$1(o.operation);}if(e.groupBy){if(e.groupBy.length>this.maxGroupByFields)throw new g(`Maximum ${this.maxGroupByFields} GROUP BY fields allowed`);for(let o of e.groupBy)if(t.groupByFields.length>0&&!t.groupByFields.includes(o))throw new g(`Field '${o}' is not allowed for GROUP BY`)}if(e.limit!==void 0&&e.limit>t.maxLimit)throw new g(`Limit cannot exceed ${t.maxLimit}`)}getAggregateAlias(e){return e.alias?e.alias:e.field==="*"?e.operation:`${e.operation}${e.field.charAt(0).toUpperCase()}${e.field.slice(1)}`}async handle(){let e=await this.getAggregateOptions();e.aggregations.length===0&&e.aggregations.push({operation:"count",field:"*"}),this.validateAggregations(e);let t=this.getAggregateConfig();e.groupBy&&e.groupBy.length>0&&e.limit===void 0&&(e.limit=t.defaultLimit);let o=await this.aggregate(e);return this.success(o)}},$o={eq:(n,e)=>n===e,ne:(n,e)=>n!==e,gt:(n,e)=>n>e,gte:(n,e)=>n>=e,lt:(n,e)=>n<e,lte:(n,e)=>n<=e};function Ko(n,e){let t=n.get(e);if(t)return t;let o=[];return n.set(e,o),o}function Wo(n,e){let{aggregations:t,groupBy:o,having:r,orderBy:i,orderDirection:s,limit:u,offset:l}=e;if(!o||o.length===0){let p={};for(let m of t){let h=ro(m);p[h]=oo(n,m);}return {values:p}}let c=new Map;for(let p of n){let h=o.map(f=>String(p[f]??"null")).join("|");Ko(c,h).push(p);}let a=[];for(let[p,m]of c){let h=p.split("|"),f={};o.forEach((b,g)=>{f[b]=h[g]==="null"?null:h[g];});let y={};for(let b of t){let g=ro(b);y[g]=oo(m,b);}a.push({key:f,values:y});}r&&(a=a.filter(p=>{for(let[m,h]of Object.entries(r)){let f=p.values[m];if(f!==null)for(let[y,b]of Object.entries(h)){let g=$o[y];if(g&&!g(f,Number(b)))return false}}return true}));let d=a.length;if(i){let p=s==="desc"?-1:1;a.sort((m,h)=>{if(i in m.values){let f=m.values[i]??0,y=h.values[i]??0;return (f-y)*p}if(i in m.key){let f=String(m.key[i]??""),y=String(h.key[i]??"");return f.localeCompare(y)*p}return 0});}if(l!==void 0||u!==void 0){let p=l||0,m=u?p+u:void 0;a=a.slice(p,m);}return {groups:a,totalGroups:d}}function Zt(n,e){return n.map(t=>t[e]).filter(t=>typeof t=="number")}var Go={count:(n,e)=>e==="*"?n.length:n.filter(t=>t[e]!==null&&t[e]!==void 0).length,countDistinct:(n,e)=>new Set(n.map(o=>o[e]).filter(o=>o!=null).map(o=>String(o))).size,sum:(n,e)=>{let t=0;for(let o of n){let r=o[e];typeof r=="number"&&(t+=r);}return t},avg:(n,e)=>{let t=Zt(n,e);return t.length===0?null:t.reduce((r,i)=>r+i,0)/t.length},min:(n,e)=>{let t=Zt(n,e);return t.length===0?null:Math.min(...t)},max:(n,e)=>{let t=Zt(n,e);return t.length===0?null:Math.max(...t)}};function oo(n,e){if(n.length===0)return e.operation==="count"?0:null;let t=Go[e.operation];return t?t(n,e.field):null}function ro(n){return n.alias?n.alias:n.field==="*"?n.operation:`${n.operation}${n.field.charAt(0).toUpperCase()}${n.field.slice(1)}`}function Qo(n){if(n instanceof z.ZodString)return true;let e=n;return e?e._def?.type==="string"||e._def?.typeName==="ZodString"||e.def?.type==="string":false}var Ut=class extends x{searchableFields={};searchFields=[];fieldWeights={};defaultMode="any";minQueryLength=2;maxQueryLength=500;highlightTag="mark";snippetLength=150;defaultMinScore=0;searchParamName="q";filterFields=[];filterConfig;sortFields=[];defaultSort;defaultPerPage=20;maxPerPage=100;allowedIncludes=[];fieldSelectionEnabled=false;allowedSelectFields=[];blockedSelectFields=[];alwaysIncludeFields=[];defaultSelectFields=[];getSearchableFields(){if(Object.keys(this.searchableFields).length>0)return this.searchableFields;if(this.searchFields.length>0)return bt(this.searchFields,this.fieldWeights);let e=this.getModelSchema().shape,t={};for(let[o,r]of Object.entries(e))Qo(r)&&(t[o]={weight:1});return t}getQuerySchema(){let t={[this.searchParamName||"q"]:z.string().min(this.minQueryLength).max(this.maxQueryLength).meta({description:"Search query"}),fields:z.string().optional().meta({description:`Comma-separated fields to search. Available: ${Object.keys(this.getSearchableFields()).join(", ")}`}),mode:z.enum(e).optional().meta({description:"Search mode: any (OR), all (AND), phrase (exact)"}),highlight:z.enum(["true","false"]).optional().meta({description:"Include highlighted snippets"}),minScore:z.string().optional().meta({description:"Minimum relevance score threshold (0-1)"}),page:z.string().optional(),per_page:z.string().optional()};this.sortFields.length>0&&(t.sort=z.enum(this.sortFields).optional().meta({description:"Field to sort by"}),t.order=z.enum(d$1).optional().meta({description:"Sort direction (asc or desc)"}));for(let r of this.filterFields)t[r]=z.string().optional();if(this.filterConfig)for(let[r,i]of Object.entries(this.filterConfig)){for(let s of i)t[`${r}[${s}]`]=z.string().optional();t[r]=z.string().optional();}let o=this.getSoftDeleteConfig();if(o.enabled&&o.allowQueryDeleted&&(t[o.queryParam]=z.enum(["true","false"]).optional(),t.onlyDeleted=z.enum(["true","false"]).optional()),this.allowedIncludes.length>0&&(t.include=z.string().optional().meta({description:`Comma-separated list of relations to include. Allowed: ${this.allowedIncludes.join(", ")}`})),this.fieldSelectionEnabled){let r=this.getAvailableSelectFields();t.fields=z.string().optional().meta({description:`Comma-separated list of fields to return. Available: ${r.join(", ")}`});}return z.object(t)}getAvailableSelectFields(){let e=Object.keys(this.getModelSchema().shape),t=this._meta.model.computedFields?Object.keys(this._meta.model.computedFields):[],o=this._meta.model.relations?Object.keys(this._meta.model.relations):[],r=[...e,...t,...o];return this.allowedSelectFields.length>0&&(r=r.filter(i=>this.allowedSelectFields.includes(i))),this.blockedSelectFields.length>0&&(r=r.filter(i=>!this.blockedSelectFields.includes(i))),r}getSchema(){let e=z.object({item:this.getModelSchema(),score:z.number().min(0).max(1),highlights:z.record(z.string(),z.array(z.string())).optional(),matchedFields:z.array(z.string())});return {...this.schema,request:{query:this.getQuerySchema()},responses:{200:{description:"Search results",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.array(e),result_info:z.object({page:z.number(),per_page:z.number(),total_count:z.number().optional(),total_pages:z.number().optional(),query:z.string(),searchedFields:z.array(z.string())})})}}},400:J("Invalid search request")}}}async getSearchOptions(){let{query:e}=await this.getValidatedData(),t=this.searchParamName||"q",o=e?.[t],r=e?.fields,i=yt(e?.mode),s=e?.highlight==="true",u=e?.minScore?Math.max(0,Math.min(1,Number.parseFloat(e.minScore)||0)):this.defaultMinScore,l=this.getSearchableFields(),c=gt(r,l);return {query:o,fields:c.length>0?c:Object.keys(l),mode:i??this.defaultMode,highlight:s,minScore:u}}async getFilters(){let{query:e}=await this.getValidatedData(),t=this.getSoftDeleteConfig(),o={filterFields:this.filterFields,filterConfig:this.filterConfig,searchFields:[],searchFieldName:"q",sortFields:this.sortFields,defaultSort:this.defaultSort,defaultPerPage:this.defaultPerPage,maxPerPage:this.maxPerPage,softDeleteQueryParam:t.queryParam,allowedIncludes:this.allowedIncludes,fieldSelectionEnabled:this.fieldSelectionEnabled,allowedSelectFields:this.allowedSelectFields,blockedSelectFields:this.blockedSelectFields,alwaysIncludeFields:this.alwaysIncludeFields,defaultSelectFields:this.defaultSelectFields};return ee(e||{},o)}async beforeSearch(e){return e}async afterSearch(e){return e}async handle(){let e=await this.getSearchOptions(),t=await this.getFilters();if(!e.query||e.query.length<this.minQueryLength)throw new a(`Search query must be at least ${this.minQueryLength} characters`,400,"INVALID_QUERY");e=await this.beforeSearch(e);let o=await this.search(e,t),r=await this.afterSearch(o.items),i=this.fieldSelectionEnabled&&t.options.fields&&t.options.fields.length>0?{fields:t.options.fields,isActive:true}:void 0,s=await this.finalizeArray(r.map(p=>p.item),i),u=r.map((p,m)=>({...p,item:s[m]})),l=o.postFilteredCount??o.totalCount,c=t.options.page||1,a$1=t.options.per_page||this.defaultPerPage,d=Math.ceil(l/a$1);return this.successPaginated(u,{page:c,per_page:a$1,total_count:l,total_pages:d,query:e.query,searchedFields:e.fields||Object.keys(this.getSearchableFields())})}};function Jo(n,e,t){let o=mt(e.query,e.mode),r={},i=e.fields||Object.keys(t);for(let u of i)t[u]&&(r[u]=t[u]);let s=[];for(let u of n){let{score:l,matchedFields:c}=ht(u,o,r,e.mode);if(l<e.minScore||c.length===0)continue;let a;if(e.highlight){a={};for(let d of c){let p=ft(u[d],o,e.mode);p.length>0&&(a[d]=p);}}s.push({item:u,score:l,highlights:a&&Object.keys(a).length>0?a:void 0,matchedFields:c});}return s.sort((u,l)=>l.score-u.score),s}function W(n,e={}){let{delimiter:t=",",nullValue:o="",dateFormat:r="iso"}=e;if(n==null)return o;if(n instanceof Date)switch(r){case "timestamp":return String(n.getTime());case "locale":return n.toLocaleString();default:return n.toISOString()}if(typeof n=="object")return W(JSON.stringify(n),e);if(typeof n=="boolean")return n?"true":"false";let i=String(n),s=i.charAt(0);return s==="="||s==="+"||s==="-"||s==="@"||s===" "||s==="\r"?`" ${i.replace(/"/g,'""')}"`:i.includes(t)||i.includes('"')||i.includes(`
2
+ `)||i.includes("\r")?`"${i.replace(/"/g,'""')}"`:i}function Oe(n,e={}){let{delimiter:t=",",rowDelimiter:o=`\r
3
+ `,includeHeader:r=true,formatters:i={},excludeFields:s=[],headerLabels:u={},nullValue:l="",dateFormat:c="iso"}=e;if(n.length===0)return "";let a=e.headers;a?a=a.filter(p=>!s.includes(p)):a=Object.keys(n[0]).filter(p=>!s.includes(p));let d=[];if(r){let p=a.map(m=>{let h=u[m]||m;return W(h,{delimiter:t,nullValue:l,dateFormat:c})});d.push(p.join(t));}for(let p of n){let m=a.map(h=>{let f=p[h];return i[h]&&(f=i[h](f)),W(f,{delimiter:t,nullValue:l,dateFormat:c})});d.push(m.join(t));}return d.join(o)}function Yo(n,e={}){let{delimiter:t=",",rowDelimiter:o=`\r
4
+ `,includeHeader:r=true,formatters:i={},excludeFields:s=[],headerLabels:u={},nullValue:l="",dateFormat:c="iso"}=e,a=new TextEncoder,d=0,p=false,m=e.headers;return !m&&n.length>0?m=Object.keys(n[0]).filter(h=>!s.includes(h)):m?m=m.filter(h=>!s.includes(h)):m=[],new ReadableStream({pull(h){if(r&&!p&&m.length>0){let b=m.map(g=>{let S=u[g]||g;return W(S,{delimiter:t,nullValue:l,dateFormat:c})});h.enqueue(a.encode(b.join(t)+o)),p=true;return}let f=100,y=[];for(;d<n.length&&y.length<f;){let b=n[d],g=m.map(S=>{let j=b[S];return i[S]&&(j=i[S](j)),W(j,{delimiter:t,nullValue:l,dateFormat:c})});y.push(g.join(t)),d++;}y.length>0&&h.enqueue(a.encode(y.join(o)+o)),d>=n.length&&h.close();}})}function no(n,e){let t=[],o="",r=false,i=0;for(;i<n.length;){let s=n[i];if(r){if(s==='"'){if(i+1<n.length&&n[i+1]==='"'){o+='"',i+=2;continue}r=false,i++;continue}o+=s,i++;}else {if(s==='"'){r=true,i++;continue}if(s===e){t.push(o),o="",i++;continue}o+=s,i++;}}return t.push(o),t}function Xo(n){let e=[],t="",o=false;for(let r=0;r<n.length;r++){let i=n[r];if(i==='"'){if(o&&r+1<n.length&&n[r+1]==='"'){t+='""',r++;continue}o=!o,t+=i;continue}if(!o&&(i===`
5
+ `||i==="\r")){i==="\r"&&r+1<n.length&&n[r+1]===`
6
+ `&&r++,t.length>0&&(e.push(t),t="");continue}t+=i;}return t.length>0&&e.push(t),e}function ke(n,e={}){let{delimiter:t=",",hasHeader:o=true,trimValues:r=true,skipEmptyRows:i=true,parsers:s={},emptyValue:u="empty"}=e,l={data:[],headers:[],errors:[]},c=Xo(n);if(c.length===0)return l;let a=0;if(o){let p=c[0];l.headers=no(p,t).map(m=>r?m.trim():m),a=1;}else e.headers&&(l.headers=e.headers);let d=e.headers||l.headers;for(let p=a;p<c.length;p++){let m=c[p],h=p+1;if(!(i&&m.trim()===""))try{let f=no(m,t),y={};for(let b=0;b<d.length;b++){let g=d[b],S=b<f.length?f[b]:"";if(r&&typeof S=="string"&&(S=S.trim()),S==="")switch(u){case "null":S=null;break;case "undefined":S=void 0;break}if(s[g]&&typeof S=="string")try{S=s[g](S);}catch(j){l.errors.push({row:h,message:`Failed to parse field "${g}": ${j instanceof Error?j.message:String(j)}`,content:m});}y[g]=S;}l.data.push(y);}catch(f){l.errors.push({row:h,message:`Failed to parse row: ${f instanceof Error?f.message:String(f)}`,content:m});}}return l}function Bt(n,e,t={}){let{allowUnknownFields:o=false,optionalFields:r=[]}=t,i=e.shape,s=Object.keys(i),l=s.filter(p=>r.includes(p)?false:!i[p].isOptional()).filter(p=>!n.includes(p)),c=n.filter(p=>!s.includes(p)),a=n.filter(p=>s.includes(p));return {valid:l.length===0&&(o||c.length===0),missingFields:l,unknownFields:c,validFields:a}}function er(n,e){if(n){let t=n.toLowerCase().split(".").pop();if(t==="csv")return "csv";if(t==="json")return "json"}if(e){let t=e.trim();if(t.startsWith("[")||t.startsWith("{"))return "json";if(t.includes(",")||t.includes(`
7
+ `))return "csv"}return "unknown"}function tr(n,e={}){return Oe(n,e)}function or(n,e={}){return ke(n,e).data}var qt=class extends fe{maxExportRecords=1e4;enableStreaming=true;streamPageSize=500;excludedExportFields=[];defaultFormat="json";csvOptions={};exportFilename;getExportQuerySchema(){return this.getQuerySchema().extend({format:z.enum(["json","csv"]).optional().meta({description:"Export format"}),stream:z.enum(["true","false"]).optional().meta({description:"Enable streaming for large exports"})})}getSchema(){return {...this.schema,request:{query:this.getExportQuerySchema()},responses:{200:{description:"Export successful",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({data:z.array(this.getModelSchema()),count:z.number(),format:z.enum(["json","csv"]),exportedAt:z.string()})})},"text/csv":{schema:z.string()}}},400:J("Validation error")}}}async getExportOptions(){let{query:e}=await this.getValidatedData(),t=e?.format||this.defaultFormat,o=e?.stream==="true"&&this.enableStreaming;return {format:t,stream:o,fields:e?.fields?String(e.fields).split(","):void 0}}getExportFilename(e){let o=(this.exportFilename||this._meta.model.tableName).replace(/[^a-zA-Z0-9_-]/g,"_"),r=new Date().toISOString().replace(/[:.]/g,"-");return `${o}-export-${r}.${e}`}prepareRecordsForExport(e){return this.excludedExportFields.length===0?e:e.map(t=>{let o={};for(let[r,i]of Object.entries(t))this.excludedExportFields.includes(r)||(o[r]=i);return o})}exportAsJson(e,t){let o={data:e,count:e.length,format:t,exportedAt:new Date().toISOString()};return new Response(JSON.stringify({success:true,result:o},null,2),{status:200,headers:{"Content-Type":"application/json","Content-Disposition":`attachment; filename="${this.getExportFilename(t)}"`}})}exportAsCsv(e,t){let o=Oe(e,{...this.csvOptions,excludeFields:this.excludedExportFields});return new Response(o,{status:200,headers:{"Content-Type":"text/csv; charset=utf-8","Content-Disposition":`attachment; filename="${this.getExportFilename(t)}"`}})}exportAsCsvStream(e,t){let o=this.getContext(),r=this.getExportFilename(t),i=this.csvOptions,s=this.excludedExportFields;return stream(o,async u=>{if(o.header("Content-Type","text/csv; charset=utf-8"),o.header("Content-Disposition",`attachment; filename="${r}"`),e.length===0)return;let l=Object.keys(e[0]).filter(d=>!s.includes(d)),c=l.map(d=>W(d,i)).join(",")+`
8
+ `;await u.write(c);let a=100;for(let d=0;d<e.length;d+=a)for(let p of e.slice(d,d+a)){let m=l.map(h=>W(p[h],i)).join(",")+`
9
+ `;await u.write(m);}})}exportAsCsvStreamPaginated(e,t){let o=this.getExportFilename(t),r=this.streamPageSize,i=Math.min(this.maxExportRecords,1e5),s=this.excludedExportFields,u=this.csvOptions,l=null,c=new ReadableStream({start:async a=>{let d=new TextEncoder,p=1,m=0;try{for(;m<i;){let h={...e,options:{...e.options,page:p,per_page:r}},y=(await this.list(h)).result;if(y.length===0)break;y.length>i-m&&(y=y.slice(0,i-m)),y=await this.after(y),y=await this.beforeExport(y);let b=this.prepareRecordsForExport(y);if(!l&&b.length>0){l=Object.keys(b[0]).filter(S=>!s.includes(S));let g=l.map(S=>W(S,u)).join(",")+`
10
+ `;a.enqueue(d.encode(g));}if(l)for(let g of b){let S=l.map(j=>W(g[j],u)).join(",")+`
11
+ `;a.enqueue(d.encode(S));}if(m+=y.length,p++,y.length<r)break}}catch(h){a.error(h);return}a.close();}});return new Response(c,{status:200,headers:{"Content-Type":"text/csv; charset=utf-8","Content-Disposition":`attachment; filename="${o}"`}})}async beforeExport(e){return e}async fetchAllForExport(e){let t=Math.min(this.maxExportRecords,1e5),o={...e,options:{...e.options,page:1,per_page:t}};return (await this.list(o)).result}async handle(){let e=await this.getExportOptions(),t=await this.getFilters();if(e.format==="csv"&&e.stream)return this.exportAsCsvStreamPaginated(t,e.format);let o=await this.fetchAllForExport(t);o=await this.after(o),o=await this.beforeExport(o);let r=this.prepareRecordsForExport(o);return e.format==="csv"?this.exportAsCsv(r,e.format):this.exportAsJson(r,e.format)}};var zt=class extends x{maxBatchSize=1e3;importBatchSize=100;stopOnError=false;skipInvalidRows=true;defaultMode="create";upsertKeys;immutableFields=[];csvOptions={};maxBodySize=10*1024*1024;optionalImportFields=[];getUpsertKeys(){return this.upsertKeys||this._meta.model.primaryKeys}getImportSchema(){let e=this._meta.fields?this._meta.fields:V(this.getModelSchema(),H(this._meta.model));return z.object({items:z.array(e.partial()).min(1).max(this.maxBatchSize)})}getSchema(){return {...this.schema,request:{query:z.object({mode:z.enum(["create","upsert"]).optional().meta({description:"Import mode"}),skipInvalid:z.enum(["true","false"]).optional().meta({description:"Skip invalid rows"}),stopOnError:z.enum(["true","false"]).optional().meta({description:"Stop on first error"})})},responses:{200:{description:"Import completed successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({summary:z.object({total:z.number(),created:z.number(),updated:z.number(),skipped:z.number(),failed:z.number()}),results:z.array(z.object({rowNumber:z.number(),status:z.enum(["created","updated","skipped","failed"]),data:z.unknown().optional(),error:z.string().optional(),code:z.string().optional(),validationErrors:z.array(z.object({path:z.string(),message:z.string()})).optional()}))})})}}},207:{description:"Import completed with partial failures",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({summary:z.object({total:z.number(),created:z.number(),updated:z.number(),skipped:z.number(),failed:z.number()}),results:z.array(z.object({rowNumber:z.number(),status:z.enum(["created","updated","skipped","failed"]),data:z.unknown().optional(),error:z.string().optional(),code:z.string().optional(),validationErrors:z.array(z.object({path:z.string(),message:z.string()})).optional()}))})})}}},400:J("Validation error")}}}async getImportOptions(){let{query:e}=await this.getValidatedData(),t=e?.skipInvalid==="true"?true:e?.skipInvalid==="false"?false:this.skipInvalidRows,o=e?.stopOnError==="true"?true:e?.stopOnError==="false"?false:this.stopOnError;return {mode:e?.mode||this.defaultMode,skipInvalidRows:t,stopOnError:o}}async parseImportData(){let e=this.context;if(!e)throw new b("No request available");let t=e.req.header("content-type")||"";if(t.includes("application/json")){let o=await e.req.json();if(!o)throw new b("Request body is empty");if(!o.items||!Array.isArray(o.items))throw new b('Request body must contain an "items" array');if(o.items.length>this.maxBatchSize)throw new b(`Maximum ${this.maxBatchSize} items allowed per import`);return o.items}if(t.includes("text/csv")){let o=await e.req.text();if(o.length>this.maxBodySize)throw new b(`Request body exceeds maximum size of ${this.maxBodySize} bytes`);return this.parseCsvData(o)}if(t.includes("multipart/form-data")){let r=(await e.req.formData()).get("file");if(!r)throw new b("No file provided in form data");let i=await r.text();if(i.length>this.maxBodySize)throw new b(`Uploaded file exceeds maximum size of ${this.maxBodySize} bytes`);let s=r.name.toLowerCase();if(s.endsWith(".json")){let l;try{l=JSON.parse(i);}catch{throw new b("Invalid JSON content in uploaded file")}let c=Array.isArray(l)?l:l.items;if(!c||!Array.isArray(c))throw new b('JSON file must contain an array or an object with "items" array');if(c.length>this.maxBatchSize)throw new b(`Maximum ${this.maxBatchSize} items allowed per import`);return c}if(s.endsWith(".csv"))return this.parseCsvData(i);let u=i.trim();if(u.startsWith("[")||u.startsWith("{")){let l;try{l=JSON.parse(i);}catch{throw new b("Invalid JSON content in uploaded file")}let c=Array.isArray(l)?l:l.items;if(!c||!Array.isArray(c))throw new b('JSON file must contain an array or an object with "items" array');return c}return this.parseCsvData(i)}throw new b("Unsupported content type. Use application/json, text/csv, or multipart/form-data")}parseCsvData(e){let t=ke(e,this.csvOptions);if(t.errors.length>0)throw new b(`CSV parsing errors: ${t.errors.map(i=>`Row ${i.row}: ${i.message}`).join("; ")}`);if(t.data.length===0)throw new b("CSV file is empty");if(t.data.length>this.maxBatchSize)throw new b(`Maximum ${this.maxBatchSize} items allowed per import`);let o=this._meta.fields||this.getModelSchema(),r=Bt(t.headers,o,{allowUnknownFields:true,optionalFields:this.optionalImportFields});if(!r.valid&&r.missingFields.length>0)throw new b(`Missing required fields in CSV: ${r.missingFields.join(", ")}`);return t.data}validateRow(e,t){let o=this._meta.fields||this.getModelSchema(),r={};for(let s of H(this._meta.model))r[s]=true;for(let s of this.optionalImportFields)r[s]=true;let i=o.partial(r);try{return i.parse(e),{valid:!0}}catch(s){return s instanceof z.ZodError?{valid:false,errors:s.issues.map(l=>({path:l.path.join("."),message:l.message}))}:{valid:false,errors:[{path:"",message:s instanceof Error?s.message:String(s)}]}}}removeImmutableFields(e){if(this.immutableFields.length===0)return e;let t={};for(let[o,r]of Object.entries(e))this.immutableFields.includes(o)||(t[o]=r);return t}async before(e,t,o,r){return e}async after(e,t,o,r){return e}async processRow(e,t,o,r){let i=this.validateRow(e,t);if(!i.valid)return o.skipInvalidRows?{rowNumber:t,status:"skipped",error:"Validation failed",validationErrors:i.errors}:{rowNumber:t,status:"failed",error:"Validation failed",validationErrors:i.errors};try{let s=await this.before(e,t,o.mode,r);if(o.mode==="upsert"){let l=await this.findExisting(s,r);if(l){let c=this.removeImmutableFields(s),a=await this.update(l,c,r);return {rowNumber:t,status:"updated",data:a}}}else if(await this.findExisting(s,r))return o.skipInvalidRows?{rowNumber:t,status:"skipped",error:"Record already exists"}:{rowNumber:t,status:"failed",error:"Record already exists (duplicate key)"};let u=await this.create(s,r);return {rowNumber:t,status:"created",data:u}}catch(s){let u=we(s);return u?{rowNumber:t,status:"failed",code:"CONFLICT",error:u.message}:{rowNumber:t,status:"failed",error:s instanceof Error?s.message:String(s)}}}async handle(){let e=await this.getImportOptions(),t=await this.parseImportData();if(!Number.isInteger(this.importBatchSize)||this.importBatchSize<1)throw new i("importBatchSize must be a positive integer");let o={total:t.length,created:0,updated:0,skipped:0,failed:0},r=[],i$1=false,s=e.stopOnError?1:this.importBatchSize;for(let c=0;c<t.length&&!i$1;c+=s){let a=t.slice(c,c+s),d=await Promise.all(a.map(async(p,m)=>{let h=c+m+1,f=await this.processRow(p,h,e);return f=await this.after(f,h,e.mode),f}));for(let p of d){switch(r.push(p),p.status){case "created":o.created++;break;case "updated":o.updated++;break;case "skipped":o.skipped++;break;case "failed":o.failed++;break}if(e.stopOnError&&p.status==="failed"){i$1=true;break}}}if(this.isAuditEnabled()){let c=this.getAuditLogger(),a=r.filter(d=>d.status==="created"||d.status==="updated");if(a.length>0){let d=a.map(p=>{if(!p.data)return null;let m=this.getRecordId(p.data);return m===null?null:{recordId:m,record:p.data}}).filter(p=>p!==null);d.length>0&&this.runAfterResponse(c.logBatch(e.mode==="upsert"?"batch_upsert":"batch_create",this._meta.model.tableName,d,this.getAuditUserId()));}}let u={summary:o,results:r},l=o.failed>0&&o.failed<o.total?207:200;return this.json({success:true,result:u},l)}};var Ce=Symbol.for("hono-crud.resource-registry");function io(n,e,t){let o=n;o[Ce]||(o[Ce]=[]),o[Ce].push({path:e,endpoints:t});}function vs(n){return n[Ce]??[]}function nr(n,e,t,o={}){let r=e.endsWith("/")?e.slice(0,-1):e,i=n,{middlewares:s=[],endpointMiddlewares:u={},responseEnvelope:l}=o,c=l?async(p,m$1)=>{b$4(p,m,l),await m$1();}:void 0,a=p=>{let m=t[p],h=m&&"_middlewares"in m?m._middlewares||[]:[];return [...c?[c]:[],...s,...u[p]||[],...h]},d=(p,m,h,f)=>{let y=a(h),b=i[p];y.length>0?b(m,...y,f):b(m,f);};t.create&&d("post",r,"create",t.create),t.list&&d("get",r,"list",t.list),t.batchCreate&&d("post",`${r}/batch`,"batchCreate",t.batchCreate),t.batchUpdate&&d("patch",`${r}/batch`,"batchUpdate",t.batchUpdate),t.batchDelete&&d("delete",`${r}/batch`,"batchDelete",t.batchDelete),t.batchRestore&&d("post",`${r}/batch/restore`,"batchRestore",t.batchRestore),t.batchUpsert&&d("post",`${r}/batch/upsert`,"batchUpsert",t.batchUpsert),t.search&&d("get",`${r}/search`,"search",t.search),t.aggregate&&d("get",`${r}/aggregate`,"aggregate",t.aggregate),t.export&&d("get",`${r}/export`,"export",t.export),t.import&&d("post",`${r}/import`,"import",t.import),t.upsert&&d("post",`${r}/upsert`,"upsert",t.upsert),t.bulkPatch&&d("patch",`${r}/bulk`,"bulkPatch",t.bulkPatch),t.read&&d("get",`${r}/:id`,"read",t.read),t.update&&d("patch",`${r}/:id`,"update",t.update),t.delete&&d("delete",`${r}/:id`,"delete",t.delete),t.restore&&d("post",`${r}/:id/restore`,"restore",t.restore),t.clone&&d("post",`${r}/:id/clone`,"clone",t.clone),t.versionHistory&&d("get",`${r}/:id/versions`,"versionHistory",t.versionHistory),t.versionCompare&&d("get",`${r}/:id/versions/compare`,"versionCompare",t.versionCompare),t.versionRead&&d("get",`${r}/:id/versions/:version`,"versionRead",t.versionRead),t.versionRollback&&d("post",`${r}/:id/versions/:version/rollback`,"versionRollback",t.versionRollback),io(n,r,t);}function ir(n){return {content:{"application/json":{schema:n}}}}var Pe=class{constructor(e){this.meta=e;}_schema={};_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_allowNestedCreate=[];_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}nestedCreate(...e){return this._allowNestedCreate=e,this}build(e){return a$2(e,{meta:this.meta,schema:this._schema,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,allowNestedCreate:this._allowNestedCreate,middlewares:this._middlewares})}},Ie=class{constructor(e){this.meta=e;}_schema={};_filterFields=[];_filterConfig;_searchFields=[];_searchFieldName="search";_sortFields=[];_defaultSort;_defaultPerPage=20;_maxPerPage=100;_allowedIncludes=[];_fieldSelectionEnabled=false;_allowedSelectFields=[];_blockedSelectFields=[];_alwaysIncludeFields=[];_defaultSelectFields=[];_after;_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}filter(...e){return this._filterFields=e,this}filterWith(e){return this._filterConfig=e,this}search(...e){return this._searchFields=e,this}searchParam(e){return this._searchFieldName=e,this}sortable(...e){return this._sortFields=e,this}orderBy(...e){return this.sortable(...e)}defaultSort(e,t="asc"){return this._defaultSort={field:e,order:t},this}defaultOrder(e,t="asc"){return this.defaultSort(e,t)}pagination(e,t){return this._defaultPerPage=e,t!==void 0&&(this._maxPerPage=t),this}include(...e){return this._allowedIncludes=e,this}fieldSelection(e){return this._fieldSelectionEnabled=true,e?.allowed&&(this._allowedSelectFields=e.allowed),e?.blocked&&(this._blockedSelectFields=e.blocked),e?.alwaysInclude&&(this._alwaysIncludeFields=e.alwaysInclude),e?.defaults&&(this._defaultSelectFields=e.defaults),this}after(e){return this._after=e,this}transform(e){return this._transform=e,this}build(e){return a$2(e,{meta:this.meta,schema:this._schema,filterFields:this._filterFields,filterConfig:this._filterConfig,searchFields:this._searchFields,searchFieldName:this._searchFieldName,sortFields:this._sortFields,defaultSort:this._defaultSort,defaultPerPage:this._defaultPerPage,maxPerPage:this._maxPerPage,allowedIncludes:this._allowedIncludes,fieldSelectionEnabled:this._fieldSelectionEnabled,allowedSelectFields:this._allowedSelectFields,blockedSelectFields:this._blockedSelectFields,alwaysIncludeFields:this._alwaysIncludeFields,defaultSelectFields:this._defaultSelectFields,after:this._after,transform:this._transform,middlewares:this._middlewares})}},ve=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_allowedIncludes=[];_fieldSelectionEnabled=false;_allowedSelectFields=[];_blockedSelectFields=[];_alwaysIncludeFields=[];_defaultSelectFields=[];_after;_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}include(...e){return this._allowedIncludes=e,this}fieldSelection(e){return this._fieldSelectionEnabled=true,e?.allowed&&(this._allowedSelectFields=e.allowed),e?.blocked&&(this._blockedSelectFields=e.blocked),e?.alwaysInclude&&(this._alwaysIncludeFields=e.alwaysInclude),e?.defaults&&(this._defaultSelectFields=e.defaults),this}after(e){return this._after=e,this}transform(e){return this._transform=e,this}build(e){return a$2(e,{meta:this.meta,schema:this._schema,lookupField:this._lookupField,additionalFilters:this._additionalFilters,allowedIncludes:this._allowedIncludes,fieldSelectionEnabled:this._fieldSelectionEnabled,allowedSelectFields:this._allowedSelectFields,blockedSelectFields:this._blockedSelectFields,alwaysIncludeFields:this._alwaysIncludeFields,defaultSelectFields:this._defaultSelectFields,after:this._after,transform:this._transform,middlewares:this._middlewares})}},Fe=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_allowedUpdateFields;_blockedUpdateFields;_allowNestedWrites=[];_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}allowedFields(...e){return this._allowedUpdateFields=e,this}blockedFields(...e){return this._blockedUpdateFields=e,this}nestedWrites(...e){return this._allowNestedWrites=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}transform(e){return this._transform=e,this}build(e){return a$2(e,{meta:this.meta,schema:this._schema,lookupField:this._lookupField,additionalFilters:this._additionalFilters,allowedUpdateFields:this._allowedUpdateFields,blockedUpdateFields:this._blockedUpdateFields,allowNestedWrites:this._allowNestedWrites,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,transform:this._transform,middlewares:this._middlewares})}},je=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_includeCascadeResults=false;_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}includeCascade(e=true){return this._includeCascadeResults=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}build(e){return a$2(e,{meta:this.meta,schema:this._schema,lookupField:this._lookupField,additionalFilters:this._additionalFilters,includeCascadeResults:this._includeCascadeResults,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,middlewares:this._middlewares})}},Ae=class{constructor(e){this.meta=e;}create(){return new Pe(this.meta)}list(){return new Ie(this.meta)}read(){return new ve(this.meta)}update(){return new Fe(this.meta)}delete(){return new je(this.meta)}};function sr(n){return new Ae(n)}export{kt as $,X as A,or as Aa,he as B,qt as Ba,No as C,zt as Ca,dt as D,vs as Da,lt as E,nr as Ea,ct as F,ir as Fa,pt as G,Pe as Ga,ut as H,Ie as Ha,mt as I,ve as Ia,Yt as J,Fe as Ja,ht as K,je as Ka,ft as L,Ae as La,gt as M,sr as Ma,bt as N,yt as O,ae as P,Mt as Q,Rt as R,Vo as S,ee as T,V as U,Zo as V,Me as W,Et as X,St as Y,xt as Z,Ot as _,so as a,fe as aa,ao as b,Ct as ba,Xe as c,qo as ca,lo as d,Pt as da,et as e,It as ea,ye as f,vt as fa,po as g,Ft as ga,bo as h,jt as ha,wo as i,At as ia,ko as j,_t as ja,Wt as k,Tt as ka,Io as l,Nt as la,Gt as m,Dt as ma,ie as n,Ht as na,H as o,Vt as oa,rt as p,Lt as pa,nt as q,Wo as qa,it as r,Ut as ra,st as s,Jo as sa,Qt as t,W as ta,we as u,Oe as ua,K as v,Yo as va,_o as w,ke as wa,To as x,Bt as xa,se as y,er as ya,at as z,tr as za};
@@ -0,0 +1 @@
1
+ import {a}from'./chunk-STAO4FWC.js';function n(e,d){return a(d,{meta:e.meta,schema:e.schema,middlewares:e.middlewares,before:e.before,after:e.after,beforeHookMode:e.beforeHookMode,afterHookMode:e.afterHookMode,allowNestedCreate:e.allowNestedCreate})}function l(e,d){return a(d,{meta:e.meta,schema:e.schema,middlewares:e.middlewares,after:e.after,transform:e.transform,filterFields:e.filterFields,filterConfig:e.filterConfig,searchFields:e.searchFields,searchFieldName:e.searchFieldName,sortFields:e.sortFields,defaultSort:e.defaultSort,defaultPerPage:e.defaultPerPage,maxPerPage:e.maxPerPage,allowedIncludes:e.allowedIncludes,fieldSelectionEnabled:e.fieldSelectionEnabled,allowedSelectFields:e.allowedSelectFields,blockedSelectFields:e.blockedSelectFields,alwaysIncludeFields:e.alwaysIncludeFields,defaultSelectFields:e.defaultSelectFields})}function o(e,d){return a(d,{meta:e.meta,schema:e.schema,middlewares:e.middlewares,after:e.after,transform:e.transform,lookupField:e.lookupField,additionalFilters:e.additionalFilters,allowedIncludes:e.allowedIncludes,fieldSelectionEnabled:e.fieldSelectionEnabled,allowedSelectFields:e.allowedSelectFields,blockedSelectFields:e.blockedSelectFields,alwaysIncludeFields:e.alwaysIncludeFields,defaultSelectFields:e.defaultSelectFields})}function r(e,d){return a(d,{meta:e.meta,schema:e.schema,middlewares:e.middlewares,before:e.before,after:e.after,transform:e.transform,beforeHookMode:e.beforeHookMode,afterHookMode:e.afterHookMode,lookupField:e.lookupField,additionalFilters:e.additionalFilters,allowedUpdateFields:e.allowedUpdateFields,blockedUpdateFields:e.blockedUpdateFields,allowNestedWrites:e.allowNestedWrites})}function s(e,d){return a(d,{meta:e.meta,schema:e.schema,middlewares:e.middlewares,before:e.before,after:e.after,beforeHookMode:e.beforeHookMode,afterHookMode:e.afterHookMode,lookupField:e.lookupField,additionalFilters:e.additionalFilters,includeCascadeResults:e.includeCascadeResults})}export{n as a,l as b,o as c,r as d,s as e};
@@ -0,0 +1 @@
1
+ import {a}from'./chunk-6XVCICWS.js';import {b}from'./chunk-VJRDAVID.js';import {a as a$1}from'./chunk-6GO5LUOZ.js';function C(c={}){let{source:a$2="header",headerName:l="X-Tenant-ID",pathParam:f="tenantId",queryParam:m="tenantId",jwtClaim:x="tenantId",extractor:o,contextKey:E="tenantId",required:g=true,errorMessage:p="Tenant ID is required",onMissing:i,validate:s,invalidMessage:T="Invalid tenant ID"}=c;if(a$2==="custom"&&!o)throw new Error("multiTenant: source 'custom' requires an `extractor` function. Provide `extractor`, or choose a different `source`.");let w={header:e=>e.req.header(l),path:e=>e.req.param(f),query:e=>e.req.query(m),jwt:e=>{let n=e.get(a$1.jwtPayload);if(n&&typeof n=="object")return n[x]},custom:e=>o?.(e)};return async(e,n)=>{let y=w[a$2],t=await y(e);if(!t){if(g){if(i)return i(e);throw new a(p,400,"TENANT_REQUIRED")}return n()}if(s&&!await s(t,e))throw new a(T,400,"INVALID_TENANT");return b(e,E,t),n()}}export{C as a};
@@ -0,0 +1 @@
1
+ import {c}from'./chunk-VESRPXGC.js';import {b as b$3}from'./chunk-MCXQ77DB.js';import {b as b$2}from'./chunk-DMGP7QDL.js';import {o,a as a$1,b}from'./chunk-OCJC5XWY.js';import {e,a as a$2,b as b$1}from'./chunk-VJRDAVID.js';import {a}from'./chunk-6GO5LUOZ.js';async function Z(e){let r=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",r),o=new Uint8Array(n);return Array.from(o).map(i=>i.toString(16).padStart(2,"0")).join("")}var W=class{keys=new Map;hashToId=new Map;async store(t){this.keys.set(t.id,t),this.hashToId.set(t.keyHash,t.id);}async lookup(t){let r=this.hashToId.get(t);return r&&this.keys.get(r)||null}async getById(t){return this.keys.get(t)||null}async getByUserId(t){let r=[];for(let n of this.keys.values())n.userId===t&&r.push(n);return r}async revoke(t){let r=this.keys.get(t);return r?(r.active=false,true):false}async delete(t){let r=this.keys.get(t);return r?(this.hashToId.delete(r.keyHash),this.keys.delete(t),true):false}async updateLastUsed(t){let r=this.keys.get(t);r&&(r.lastUsedAt=new Date);}async generateKey(t){let r=t.prefix||"sk",n=we(r),o=await Z(n),i={id:crypto.randomUUID(),keyHash:o,userId:t.userId,name:t.name,roles:t.roles,permissions:t.permissions,expiresAt:t.expiresAt??null,active:true,createdAt:new Date,metadata:t.metadata};return await this.store(i),{key:n,entry:i}}getAllKeys(){return Array.from(this.keys.values())}clear(){this.keys.clear(),this.hashToId.clear();}};function we(e="sk",t=32){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=new Uint8Array(t);crypto.getRandomValues(n);let o="";for(let i=0;i<t;i++)o+=r[n[i]%r.length];return `${e}_${o}`}function He(e,t){if(!e||typeof e!="string")return false;let r=e.split("_");if(r.length!==2)return false;let[n,o]=r;return !(t&&n!==t||!/^[A-Za-z0-9]{16,}$/.test(o))}var w=o({contextKey:a.apiKeyStorage}),ee=w.registry,De=w.get;w.getRequired;var _e=w.set;function D(e){return e instanceof Error?e:new Error(String(e))}function Be(e,t){let r=D(e),n=new Error(`${t}: ${r.message}`);return n.cause=r,n}function Oe(e){return e instanceof Error?e.message:String(e)}var te="\0DOUBLE_STAR\0",re="\0SINGLE_STAR\0";function E(e,t){if(t instanceof RegExp)return t.test(e);if(!t.includes("*"))return e===t;let r=t.replace(/\*\*/g,te).replace(/\*/g,re).replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(new RegExp(te,"g"),".*").replace(new RegExp(re,"g"),"[^/]*");return new RegExp(`^${r}$`).test(e)}function ne(e,t){for(let r of t)if(E(e,r))return true;return false}function Ve(e,t,r){return ne(e,r)?false:t.length===0?true:ne(e,t)}function A(e,t){let r=e.toLowerCase();for(let n of t){if(n instanceof RegExp){if(n.test(e))return true;continue}let o=n.toLowerCase();if(o.includes("*")){let i=o.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");if(new RegExp(`^${i}$`).test(r))return true}else if(r===o)return true}return false}function I(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(n=>I(n,t));if(typeof e!="object")return e;let r={};for(let[n,o]of Object.entries(e))A(n,t)?r[n]="[REDACTED]":typeof o=="object"&&o!==null?r[n]=I(o,t):r[n]=o;return r}function oe(e,t){let r={};for(let[n,o]of Object.entries(e))r[n]=A(n,t)?"[REDACTED]":o;return r}function je(e,t){return A(e,t)}function F(e,t){return I(e,t)}function _(e,t){return oe(e,t)}function Je(e,t){return E(e,t)}function se(e,t,r){for(let n of r)if(E(e,n))return true;if(t.length===0)return false;for(let n of t)if(E(e,n))return false;return true}function ae(e,t="X-Forwarded-For",r=false){return a$1(e,{ipHeader:t,trustProxy:r||true})}function U(e){let t={};return e.forEach((r,n)=>{t[n.toLowerCase()]=r;}),t}function ie(e){let t={};return new URL(e.req.url).searchParams.forEach((n,o)=>{t[o]=n;}),t}function x(e,t){if(typeof e=="string")return e.length>t?e.substring(0,t)+"... [TRUNCATED]":e;let r=JSON.stringify(e);return r.length>t?{_truncated:true,_originalSize:r.length,_maxSize:t}:e}function ue(e,t){if(!e)return false;if(t.length===0)return true;let r=e.toLowerCase();for(let n of t)if(r.includes(n.toLowerCase()))return true;return false}function de(e){return b(e)}function ge(){return e()}var v=o({contextKey:a.loggingStorage}),le=v.registry,st=v.set,Ie=v.get,Ae=v.getRequired,ve=["authorization","cookie","x-api-key","x-auth-token"],ke=["password","token","secret","apiKey","api_key","accessToken","access_token","refreshToken","refresh_token","creditCard","credit_card","ssn","socialSecurityNumber"],Le=["/health","/healthz","/ready","/readyz","/live","/livez","/metrics","/favicon.ico"];function at(e){return a$2(e,a.requestId)}function it(e){return a$2(e,a.requestStartTime)}function ut(e={}){let t=e.enabled??true,r=e.level??"info",n=e.includePaths??[],o=e.excludePaths??Le,i=e.redactHeaders??ve,B=e.redactBodyFields??ke,S=e.requestBody??{enabled:false},R=e.responseBody??{enabled:false},O=e.includeHeaders??true,fe=e.includeQuery??true,pe=e.includeClientIp??true,ye=e.ipHeader??"X-Forwarded-For",me=e.trustProxy??false,he=e.minResponseTimeMs??0,Ee=e.generateRequestId??ge;return async(s,k)=>{if(!t)return k();let z=s.req.path;if(se(z,n,o))return k();let L=Ee(),C=Date.now();b$1(s,a.requestId,L),b$1(s,a.requestStartTime,C),s.header("X-Request-ID",L);let xe=s.req.method,Se=s.req.url,V;if(O){let g=U(s.req.raw.headers);V=_(g,i);}let $;fe&&($=ie(s));let M;pe&&(M=ae(s,ye,me));let Re=de(s),K;if(S.enabled){let g=s.req.header("content-type"),m=S.contentTypes??[];if(ue(g,m))try{let y=await s.req.raw.clone().text();if(y)try{let d=JSON.parse(y);d=F(d,B);let u=S.maxSize??10240;K=x(d,u);}catch{let d=S.maxSize??10240;K=x(y,d);}}catch{}}let c,T;try{await k();}catch(g){throw c=g instanceof Error?g:new Error(String(g)),g}finally{let m=Date.now()-C;if(m<he)return;let p=s.res.status,y;if(O){let a=U(s.res.headers);y=_(a,i);}if(R.enabled&&!c){let a=R.statusCodes??[];if(a.length===0||a.includes(p))try{let q=await s.res.clone().text();if(q)try{let h=JSON.parse(q);h=F(h,B);let Pe=R.maxSize??10240;T=x(h,Pe);}catch{let h=R.maxSize??10240;T=x(q,h);}}catch{}}let d=r;e.levelResolver?d=e.levelResolver(s,m,p,c):c||p>=500?d="error":p>=400&&(d="warn");let u={id:L,timestamp:new Date(C).toISOString(),level:d,request:{method:xe,path:z,url:Se,headers:V,query:$,body:K,clientIp:M,userId:Re},response:{statusCode:p,headers:y,body:T,responseTimeMs:m}};if(c&&(u.error={message:c.message,name:c.name,stack:c.stack}),e.metadata){let a=typeof e.metadata=="function"?e.metadata(s):e.metadata;u.metadata=a;}e.formatter&&(u=e.formatter(u));let N=ce(s,e.storage);(async()=>{if(N)try{await N.store(u);}catch(a){e.onError&&e.onError(a instanceof Error?a:new Error(String(a)),u);}if(e.handlers)for(let a of e.handlers)try{await a(u);}catch(f){e.onError&&e.onError(f instanceof Error?f:new Error(String(f)),u);}})().catch(a=>{let f=D(a);e.onError?e.onError(f,u):b$2().error("Failed to process log entry",{error:f.message});});}}}function Et(e,t){return e.var[t]}function ce(e,t){return le.resolve(e,t)}function xt(e,t){return b$3.resolve(e,t)}function St(e,t){return c.resolve(e,t)}function Rt(e,t){return ee.resolve(e,t)}export{ue as A,de as B,ge as C,st as D,Ie as E,Ae as F,at as G,it as H,ut as I,Z as a,W as b,we as c,He as d,De as e,_e as f,Et as g,ce as h,xt as i,St as j,Rt as k,D as l,Be as m,Oe as n,E as o,ne as p,Ve as q,je as r,F as s,_ as t,Je as u,se as v,ae as w,U as x,ie as y,x as z};
@@ -0,0 +1 @@
1
+ import {a as a$1,k as k$1,p}from'./chunk-IOWLCLF6.js';import {a as a$3}from'./chunk-NWOJZP4P.js';import {e,i,f}from'./chunk-6XVCICWS.js';import {b as b$2}from'./chunk-DMGP7QDL.js';import {b as b$1,a as a$2}from'./chunk-VJRDAVID.js';import {a}from'./chunk-6GO5LUOZ.js';import {z}from'zod';import {decode,verify}from'hono/jwt';var M=["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512"],K=z.object({sub:z.string().optional(),iss:z.string().optional(),aud:z.union([z.string(),z.array(z.string())]).optional(),exp:z.number().int().optional(),nbf:z.number().int().optional(),iat:z.number().int().optional(),jti:z.string().optional(),email:z.string().optional(),role:z.string().optional(),roles:z.union([z.array(z.string()),z.string()]).optional(),permissions:z.union([z.array(z.string()),z.string()]).optional(),metadata:z.record(z.string(),z.unknown()).optional()}).passthrough();function se(e){return K.parse(e)}function j(e){return K.safeParse(e)}z.object({id:z.string(),tenantId:z.string().optional(),organizationId:z.string().optional(),userId:z.string().optional(),actorUserId:z.string().optional(),onBehalfOfUserId:z.string().optional(),agentId:z.string().optional(),agentRunId:z.string().optional(),toolCallId:z.string().optional(),source:z.enum(["http","agent-mcp","agent-code-mode","workflow","job","system"]),toolName:z.string(),input:z.unknown(),status:z.enum(["pending","approved","rejected","expired"]),createdAt:z.iso.datetime(),expiresAt:z.iso.datetime(),reason:z.string(),approvedBy:z.string().optional(),approvedAt:z.iso.datetime().optional(),rejectedBy:z.string().optional(),rejectedReason:z.string().optional()});function b(e$1,t={}){let{clockTolerance:n=0,issuer:r,audience:o,skipTimeValidation:s=false}=t;if(!s){let u=Math.floor(Date.now()/1e3);if(e$1.exp!==void 0&&u>e$1.exp+n)throw new e("Token has expired");if(e$1.nbf!==void 0&&u<e$1.nbf-n)throw new e("Token not yet valid")}if(r!==void 0&&e$1.iss!==r)throw new e("Invalid token issuer");if(o!==void 0){let u=Array.isArray(o)?o:[o],d=Array.isArray(e$1.aud)?e$1.aud:[e$1.aud];if(!u.some(y=>d.includes(y)))throw new e("Invalid token audience")}}function Q(e){if(!M.includes(e))throw new Error(`Unsupported algorithm: ${e}`);return e}function ie(e){let t=e.req.header("Authorization");if(!t)return null;let n=t.split(" ");return n.length!==2||n[0].toLowerCase()!=="bearer"?null:n[1]}function X(e){if(e!==void 0)return Array.isArray(e)?e:[e]}function ae(e){return {id:String(e.sub||e.id||""),email:e.email,roles:X(e.roles??e.role),permissions:X(e.permissions),metadata:e.metadata}}function N(e$1){let t=Q(e$1.algorithm||"HS256"),n=e$1.clockTolerance||0,r=e$1.extractToken||ie,o=e$1.extractUser||ae;return async(s,u)=>{let d=r(s);if(!d)throw new e("Missing authentication token");let c=decode(d);if(!c||!c.header)throw new e("Invalid token format");if(c.header.alg!==t)throw new e("Invalid token algorithm");let y;try{y=await verify(d,e$1.secret,t);}catch(h){if(h instanceof Error){if(h.message.includes("expired")||h.name==="JwtTokenExpired")throw new e("Token has expired");if(h.message.includes("signature")||h.name==="JwtTokenSignatureMismatched")throw new e("Invalid token signature");if(h.message.includes("not valid yet")||h.name==="JwtTokenNotYetValid")throw new e("Token not yet valid")}throw new e("Invalid token")}let g=j(y);if(!g.success)throw new e("Invalid token claims");let A=g.data;b(A,{clockTolerance:n,issuer:e$1.issuer,audience:e$1.audience});let m=o(A);s.set(a.userId,m.id),s.set(a.user,m),s.set(a.roles,m.roles||[]),s.set(a.permissions,m.permissions||[]),s.set(a.authType,"jwt"),await u();}}async function ue(e$1,t){let n=Q(t.algorithm||"HS256"),r=t.clockTolerance||0,o=decode(e$1);if(!o||!o.header)throw new e("Invalid token format");if(o.header.alg!==n)throw new e("Invalid token algorithm");let s;try{s=await verify(e$1,t.secret,n);}catch(d){if(d instanceof Error){if(d.message.includes("expired")||d.name==="JwtTokenExpired")throw new e("Token has expired");if(d.message.includes("signature")||d.name==="JwtTokenSignatureMismatched")throw new e("Invalid token signature");if(d.message.includes("not valid yet")||d.name==="JwtTokenNotYetValid")throw new e("Token not yet valid")}throw new e("Invalid token")}let u=s;return b(u,{clockTolerance:r,issuer:t.issuer,audience:t.audience}),u}function de(e){try{let t=decode(e);return !t||!t.header||!t.payload?null:{header:t.header,payload:t.payload}}catch{return null}}function k(e$1){if(!e$1)throw new e("Invalid API key");if(!e$1.active)throw new e("API key has been revoked");if(e$1.expiresAt&&new Date>e$1.expiresAt)throw new e("API key has expired");return e$1}var W=a$1;function le(e){return {id:e.userId,roles:e.roles,permissions:e.permissions,metadata:{...e.metadata,apiKeyId:e.id,apiKeyName:e.name}}}function ce(e,t){return e.req.header(t)||null}function pe(e,t){return e.req.query(t)||null}function J(e$1){let t=e$1.headerName||"X-API-Key",n=e$1.queryParam??null,r=e$1.hashKey||W,o=e$1.extractUser||le;return async(s,u)=>{let d=ce(s,t);if(!d&&n&&(d=pe(s,n)),!d)throw new e("Missing API key");let c=await r(d),y,g=e$1.lookupKey?null:k$1(s,e$1.storage);if(e$1.lookupKey)y=await e$1.lookupKey(c);else if(g)y=await g.lookup(c);else throw new i("API key auth requires lookupKey, storage, or a configured apiKeyStorage");let A=k(y),m=o(A);s.set(a.userId,m.id),s.set(a.user,m),s.set(a.roles,m.roles||[]),s.set(a.permissions,m.permissions||[]),s.set(a.authType,"api-key"),e$1.updateLastUsed?Promise.resolve(e$1.updateLastUsed(A.id)).catch(()=>{}):g&&Promise.resolve(g.updateLastUsed(A.id)).catch(()=>{}),await u();}}async function he(e,t){let r=await(t.hashKey||W)(e),o;if(t.lookupKey)o=await t.lookupKey(r);else {let s=k$1(void 0,t.storage);if(s)o=await s.lookup(r);else throw new i("API key auth requires lookupKey, storage, or a configured apiKeyStorage")}return k(o)}function _(e$1){let t=e$1.requireAuth??true,n=e$1.skipPaths||[],r=e$1.unauthorizedMessage||"Unauthorized",o=e$1.authOrder||["jwt","api-key"],s=e$1.jwt?N(e$1.jwt):null,u=e$1.apiKey?J(e$1.apiKey):null;return async(d,c)=>{let y=d.req.path;if(p(y,n))return d.set(a.authType,"none"),c();let g=false,A=null;for(let m of o)try{if(m==="jwt"&&s&&d.req.header("Authorization")?.toLowerCase().startsWith("bearer ")){await s(d,async()=>{}),g=!0;break}if(m==="api-key"&&u){let h=e$1.apiKey?.headerName||"X-API-Key",v=e$1.apiKey?.queryParam;if(d.req.header(h)||v&&d.req.query(v)){await u(d,async()=>{}),g=!0;break}}}catch(h){A=h instanceof Error?h:new Error(String(h));}if(!g){if(t)throw A instanceof e?A:new e(r);d.set(a.authType,"none");}await c();}}function ge(e){return _({...e,requireAuth:false})}function me(e){return _({...e,requireAuth:true})}var R=class{store=new Map;async create(t){this.store.set(t.id,{...t});}async get(t){let n=this.store.get(t);if(!n)return null;if(n.status==="pending"&&Date.parse(n.expiresAt)<=Date.now()){let r={...n,status:"expired"};return this.store.set(t,r),r}return {...n}}async approve(t,n){let r=await this.get(t);if(!r)throw new Error(`Pending action ${t} not found`);if(r.status!=="pending")throw new Error(`Pending action ${t} cannot be approved from status '${r.status}'`);this.store.set(t,{...r,status:"approved",approvedBy:n,approvedAt:new Date().toISOString()});}async reject(t,n,r){let o=await this.get(t);if(!o)throw new Error(`Pending action ${t} not found`);if(o.status!=="pending")throw new Error(`Pending action ${t} cannot be rejected from status '${o.status}'`);this.store.set(t,{...o,status:"rejected",rejectedBy:n,rejectedReason:r});}clear(){this.store.clear();}};var fe=/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/;function H(e){let t=fe.exec(e);if(!t)throw new Error(`Invalid ISO 8601 duration: ${e}. Use P[nD][T[nH][nM][nS]] (years and months unsupported).`);let[,n,r,o,s]=t,u=(n?Number(n)*864e5:0)+(r?Number(r)*36e5:0)+(o?Number(o)*6e4:0)+(s?Number(s)*1e3:0);if(u===0&&e!=="PT0S"&&e!=="P0D")throw new Error(`ISO 8601 duration ${e} parsed to zero milliseconds \u2014 verify the format.`);return u}function ye(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var D,te=false;function Ae(){return D||(D=new R),te||(te=true,b$2().warn("requireApproval: no approvalStorage configured \u2014 using process-local in-memory storage. NOT safe for multi-instance / serverless / edge-isolate deployments where phase 1 and phase 2 may hit different processes. Pass an explicit approvalStorage (e.g. PostgresApprovalStorage) for production. This warning is logged once per process.")),D}var re=a.policies;function we(...e$1){return async(t,n)=>{let r=t.var.user;if(!r)throw new e("Authentication required");let o=r.roles||[];if(!e$1.some(u=>o.includes(u)))throw new f("Insufficient permissions");await n();}}function xe(...e$1){return async(t,n)=>{let r=t.var.user;if(!r)throw new e("Authentication required");let o=r.roles||[];if(!e$1.every(u=>o.includes(u)))throw new f("Insufficient permissions");await n();}}function Te(...e$1){return async(t,n)=>{let r=t.var.user;if(!r)throw new e("Authentication required");let o=r.permissions||[];if(!e$1.every(u=>o.includes(u)))throw new f("Insufficient permissions");await n();}}function Ee(...e$1){return async(t,n)=>{let r=t.var.user;if(!r)throw new e("Authentication required");let o=r.permissions||[];if(!e$1.some(u=>o.includes(u)))throw new f("Insufficient permissions");await n();}}function Re(e$1){return async(t,n)=>{let r=t.var.user;if(!r)throw new e("Authentication required");if(!await e$1(r,t))throw new f("Access denied");await n();}}function ve(e$1){return async(t,n)=>{let r=t.var.user;if(!r)throw new e("Authentication required");let o=await e$1(t);if(r.id!==o)throw new f("Access denied: not resource owner");await n();}}function Pe(e$1,...t){return async(n,r)=>{let o=n.var.user;if(!o)throw new e("Authentication required");let s=o.roles||[];if(t.some(c=>s.includes(c))){await r();return}let d=await e$1(n);if(o.id===d){await r();return}throw new f("Access denied")}}function Ce(...e){return async(t,n)=>{for(let r of e)await r(t,async()=>{});await n();}}function be(...e){return async(t,n)=>{let r=null;for(let o of e)try{await o(t,async()=>{}),await n();return}catch(s){r=s instanceof Error?s:new Error(String(s));}throw r||new f("Access denied")}}function ke(e="Access denied"){return async()=>{throw new f(e)}}function Ie(){return async(e,t)=>{await t();}}function Se(){return async(e$1,t)=>{if(!e$1.var.user)throw new e("Authentication required");await t();}}function qe(e){return async(t,n)=>{b$1(t,re,e),await n();}}function Oe(e){let t=e.approvalStorage??Ae(),n=e.resumeMarker??"_resume_",r=H(e.expiresAfter??"P1D"),o=z.object({[n]:z.string()}).loose();return async(s,u)=>{let d={};try{let x=await s.req.json();ye(x)&&(d=x);}catch{}let c=o.safeParse(d).data?.[n];if(c){let x=await t.get(c);if(!x)throw new f(`Pending action ${c} not found`);if(x.status==="expired")throw new f(`Pending action ${c} has expired`);if(x.status!=="approved")throw new f(`Pending action ${c} is ${x.status}, cannot resume`);Ue(s,x.input),await u();return}let y=a$2(s,a.userId),g=a$2(s,a.agentId),A=a$2(s,a.agentRunId),m=a$2(s,a.onBehalfOfUserId),h=a$2(s,a.toolCallId),v=a$2(s,a.tenantId),L=a$2(s,a.organizationId),oe=a$2(s,a.actionSource)??(g?"agent-mcp":"http"),V=Date.now(),P={id:crypto.randomUUID(),tenantId:v,organizationId:L,userId:y,actorUserId:y,onBehalfOfUserId:m,agentId:g,agentRunId:A,toolCallId:h,source:oe,toolName:e.toolName??`${s.req.method} ${s.req.path}`,input:d,status:"pending",createdAt:new Date(V).toISOString(),expiresAt:new Date(V+r).toISOString(),reason:e.reason};return await t.create(P),s.json({status:"pending",actionId:P.id,expiresAt:P.expiresAt,reason:P.reason},202)}}function Ue(e,t){let n=e.req,r=Promise.resolve(JSON.stringify(t));n.bodyCache?(n.bodyCache.text=r,delete n.bodyCache.parsedBody,delete n.bodyCache.json):n.bodyCache={text:r};}var Me=["eq","ne","gt","gte","lt","lte","in","nin","like","ilike","null","between"];function Rt(e){return Me.includes(e)}function vt(e){throw new Error(`Unhandled discriminated union member: ${String(e)}`)}var Pt=["asc","desc"],Ct=["any","all","phrase"],bt=["count","sum","avg","min","max","countDistinct"];function kt(e){return e}function It(e){return e}var St=z.object({path:z.string(),message:z.string(),code:z.string()}),Ke=z.object({code:z.string(),message:z.string(),details:z.unknown().optional(),requestId:z.string().optional(),stack:z.string().optional()}).passthrough(),qt=z.object({success:z.literal(false),error:Ke});function Ot(e){return z.object({success:z.literal(true),result:e})}var je=a.responseEnvelope;function ne(e){return e?.var?.[je]}function F(e,t){try{return e.req.valid(t)}catch{return}}function I(e,t,n){return e.json(t,n)}var S=class{static isRoute=true;schema={};params={};context=null;getSchema(){return this.schema}async getValidatedData(){if(!this.context)throw new Error("Context not set. Call setContext() first.");let t=this.context,n=this.getSchema(),r={};if(n.request?.body){let o=F(t,"json");if(o===void 0)try{o=await t.req.json();}catch{}o!==void 0&&(r.body=o);}if(n.request?.query){let o=F(t,"query");o===void 0&&(o=t.req.query()),o!==void 0&&(r.query=o);}if(n.request?.params){let o=F(t,"param");o===void 0&&(o=t.req.param()),o!==void 0&&(r.params=o);}return r}setContext(t){this.context=t;}getContext(){if(!this.context)throw new Error("Context not set");return this.context}json(t,n=200){return I(this.getContext(),t,n)}getResponseEnvelope(){return ne(this.context)}success(t,n=200){let r=this.getResponseEnvelope(),o=r?r.success(t):{success:true,result:t};return I(this.getContext(),o,n)}successPaginated(t,n,r=200){let o=this.getResponseEnvelope(),s=o?o.success(t,n):{success:true,result:t,result_info:n};return I(this.getContext(),s,r)}runAfterResponse(t){let n=a$3(this.getContext());n?n(t):t.catch(r=>{b$2().error("Background task failed",{error:r instanceof Error?r.message:String(r)});});}error(t,n="ERROR",r=400,o){let s={code:n,message:t};o!==void 0&&(s.details=o);let u=this.getResponseEnvelope(),d=u?u.error(s):{success:false,error:s};return I(this.getContext(),d,r)}};function zt(e){return typeof e=="function"&&"isRoute"in e&&e.isRoute===true}function ze(){return z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}function E(e){return {description:e??"Error",content:{"application/json":{schema:ze()}}}}function Jt(e){let t={};for(let[n,r]of Object.entries(e))t[Number(n)]=E(r);return t}var Z=class extends S{requiresAuth=true;requiredRoles;requiredPermissions;requireAllRoles=false;async authorize(t,n){return true}getUser(){let n=this.getContext().var.user;if(!n)throw new e("Authentication required");return n}getUserOrNull(){return this.getContext().var.user}getUserId(){return this.getUser().id}getUserIdOrNull(){return this.getUserOrNull()?.id}getUserRoles(){return this.getUser().roles||[]}getUserPermissions(){return this.getUser().permissions||[]}hasRole(t){return this.getUserRoles().includes(t)}hasAnyRole(...t){let n=this.getUserRoles();return t.some(r=>n.includes(r))}hasAllRoles(...t){let n=this.getUserRoles();return t.every(r=>n.includes(r))}hasPermission(t){return this.getUserPermissions().includes(t)}hasAllPermissions(...t){let n=this.getUserPermissions();return t.every(r=>n.includes(r))}hasAnyPermission(...t){let n=this.getUserPermissions();return t.some(r=>n.includes(r))}async enforceAuth(){let t=this.getContext();if(this.requiresAuth&&!t.var.user)throw new e("Authentication required");let n=t.var.user;if(!n)return;if(this.requiredRoles&&this.requiredRoles.length>0){let o=n.roles||[];if(this.requireAllRoles){if(!this.requiredRoles.every(u=>o.includes(u)))throw new f(`Required roles: ${this.requiredRoles.join(" and ")}`)}else if(!this.requiredRoles.some(u=>o.includes(u)))throw new f(`Required role: ${this.requiredRoles.join(" or ")}`)}if(this.requiredPermissions&&this.requiredPermissions.length>0){let o=n.permissions||[];if(!this.requiredPermissions.every(u=>o.includes(u)))throw new f(`Required permissions: ${this.requiredPermissions.join(", ")}`)}if(!await this.authorize(n,t))throw new f("Access denied")}getSchema(){let t=super.getSchema(),n=this.requiresAuth?[{bearerAuth:[]}]:void 0,r={401:E("Unauthorized - Authentication required"),403:E("Forbidden - Insufficient permissions")};return {...t,security:n,responses:{...t.responses,...this.requiresAuth?r:{}}}}};function Ne(e$1){class t extends e$1{requiresAuth=true;requiredRoles;requiredPermissions;requireAllRoles=false;async authorize(r,o){return true}getUser(){let o=this.getContext().var.user;if(!o)throw new e("Authentication required");return o}getUserOrNull(){return this.getContext().var.user}getUserId(){return this.getUser().id}getUserIdOrNull(){return this.getUserOrNull()?.id}getUserRoles(){return this.getUser().roles||[]}getUserPermissions(){return this.getUser().permissions||[]}hasRole(r){let o=this.getUserOrNull();return o?(o.roles||[]).includes(r):false}hasAnyRole(...r){let o=this.getUserOrNull()?.roles||[];return r.some(s=>o.includes(s))}hasAllRoles(...r){let o=this.getUserOrNull()?.roles||[];return r.every(s=>o.includes(s))}hasPermission(r){let o=this.getUserOrNull();return o?(o.permissions||[]).includes(r):false}hasAllPermissions(...r){let o=this.getUserOrNull()?.permissions||[];return r.every(s=>o.includes(s))}hasAnyPermission(...r){let o=this.getUserOrNull()?.permissions||[];return r.some(s=>o.includes(s))}async enforceAuth(){let r=this.getContext();if(this.requiresAuth&&!r.var.user)throw new e("Authentication required");let o=r.var.user;if(!o)return;if(this.requiredRoles&&this.requiredRoles.length>0){let u=o.roles||[];if(this.requireAllRoles){if(!this.requiredRoles.every(c=>u.includes(c)))throw new f(`Required roles: ${this.requiredRoles.join(" and ")}`)}else if(!this.requiredRoles.some(c=>u.includes(c)))throw new f(`Required role: ${this.requiredRoles.join(" or ")}`)}if(this.requiredPermissions&&this.requiredPermissions.length>0){let u=o.permissions||[];if(!this.requiredPermissions.every(c=>u.includes(c)))throw new f(`Required permissions: ${this.requiredPermissions.join(", ")}`)}if(!await this.authorize(o,r))throw new f("Access denied")}getSchema(){let r=super.getSchema(),o=this.requiresAuth?[{bearerAuth:[]}]:void 0,s={401:E("Unauthorized - Authentication required"),403:E("Forbidden - Insufficient permissions")};return {...r,security:o,responses:{...r.responses,...this.requiresAuth?s:{}}}}}return t}export{Z as $,Pe as A,Ce as B,be as C,ke as D,Ie as E,Se as F,qe as G,Oe as H,ze as I,E as J,Jt as K,M as L,K as M,se as N,j as O,b as P,ie as Q,N as R,ue as S,de as T,k as U,W as V,J as W,he as X,_ as Y,ge as Z,me as _,Me as a,Ne as aa,Rt as b,vt as c,Pt as d,Ct as e,bt as f,kt as g,It as h,St as i,Ke as j,qt as k,Ot as l,je as m,ne as n,I as o,S as p,zt as q,R as r,H as s,re as t,we as u,xe as v,Te as w,Ee as x,Re as y,ve as z};
@@ -0,0 +1 @@
1
+ import {a}from'./chunk-6XVCICWS.js';import {a as a$1}from'./chunk-6GO5LUOZ.js';function C(e,r){return e.req.header(r)??void 0}function h(e,r){return e.req.query(r)??void 0}function l(e,r){let t=e.req.path,a=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace("\\{version\\}","([^/]+)"),p=new RegExp(`^${a}`);return t.match(p)?.[1]}function A(e){let{versions:r,strategy:t="header",headerName:d="Accept-Version",queryParam:a$2="version",urlPattern:p="/v{version}",extractVersion:f,addHeaders:c=true}=e,V=e.defaultVersion??r[0]?.version,u=new Map;for(let n of r)u.set(n.version,n);return async(n,m)=>{let o=f?f(n):{header:()=>C(n,d),query:()=>h(n,a$2),url:()=>l(n,p)}[t]();if(o=o??V,!o)throw new a("API version is required",400,"VERSION_REQUIRED");let i=u.get(o);if(!i)throw new a(`Unsupported API version: ${o}`,400,"UNSUPPORTED_VERSION");if(n.set(a$1.apiVersion,o),n.set(a$1.apiVersionConfig,i),c&&(n.header("X-API-Version",o),i.deprecated&&n.header("Deprecation",i.deprecated),i.sunset&&n.header("Sunset",i.sunset)),i.middleware&&i.middleware.length>0)for(let y of i.middleware)await y(n,async()=>{});await m();}}function w(e){return e.get(a$1.apiVersion)}function v(e){return e.get(a$1.apiVersionConfig)}function E(){return async(e,r)=>{await r();let t=e.get(a$1.apiVersionConfig);if(!(!t?.responseTransformer||!e.res.headers.get("content-type")?.includes("application/json")))try{let a=await e.res.json(),p=t.responseTransformer(a);e.res=new Response(JSON.stringify(p),{status:e.res.status,headers:e.res.headers});}catch{}}}export{A as a,w as b,v as c,E as d};
@@ -0,0 +1 @@
1
+ import {a}from'./chunk-STAO4FWC.js';function s(o,t){let d={};if(o.create!==void 0){let e=o.create;d.create=a(t.CreateEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,bodySchema:e.bodySchema,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,allowNestedCreate:e.nestedCreate,before:e.hooks?.before,after:e.hooks?.after});}if(o.list!==void 0){let e=o.list;d.list=a(t.ListEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,filterFields:e.filtering?.fields,filterConfig:e.filtering?.config,searchFields:e.search?.fields,searchFieldName:e.search?.paramName,sortFields:e.sorting?.fields,defaultSort:e.sorting?.default?{field:e.sorting.default,order:e.sorting.defaultOrder??"asc"}:void 0,defaultPerPage:e.pagination?.defaultPerPage,maxPerPage:e.pagination?.maxPerPage,allowedIncludes:e.includes,fieldSelectionEnabled:e.fieldSelection?.enabled,allowedSelectFields:e.fieldSelection?.allowed,blockedSelectFields:e.fieldSelection?.blocked,alwaysIncludeFields:e.fieldSelection?.alwaysInclude,defaultSelectFields:e.fieldSelection?.defaults,after:e.hooks?.after,transform:e.hooks?.transform});}if(o.read!==void 0){let e=o.read;d.read=a(t.ReadEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,lookupField:e.lookupField,additionalFilters:e.additionalFilters,allowedIncludes:e.includes,fieldSelectionEnabled:e.fieldSelection?.enabled,allowedSelectFields:e.fieldSelection?.allowed,blockedSelectFields:e.fieldSelection?.blocked,alwaysIncludeFields:e.fieldSelection?.alwaysInclude,defaultSelectFields:e.fieldSelection?.defaults,after:e.hooks?.after,transform:e.hooks?.transform});}if(o.update!==void 0){let e=o.update;d.update=a(t.UpdateEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,bodySchema:e.bodySchema,lookupField:e.lookupField,additionalFilters:e.additionalFilters,allowedUpdateFields:e.fields?.allowed,blockedUpdateFields:e.fields?.blocked,allowNestedWrites:e.nestedWrites,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,transform:e.hooks?.transform});}if(o.delete!==void 0){let e=o.delete;d.delete=a(t.DeleteEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,lookupField:e.lookupField,additionalFilters:e.additionalFilters,includeCascadeResults:e.includeCascadeResults,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after});}if(o.search!==void 0&&t.SearchEndpoint){let e=o.search,n={};e.fields!==void 0&&(n.searchFields=e.fields),e.mode!==void 0&&(n.defaultMode=e.mode),e.paramName!==void 0&&(n.searchParamName=e.paramName),d.search=a(t.SearchEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,after:e.hooks?.after,extras:n});}if(o.aggregate!==void 0&&t.AggregateEndpoint){let e=o.aggregate,n={};e.fields!==void 0&&(n.filterFields=e.fields),d.aggregate=a(t.AggregateEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,after:e.hooks?.after,extras:n});}if(o.restore!==void 0&&t.RestoreEndpoint){let e=o.restore;d.restore=a(t.RestoreEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after});}if(o.batchCreate!==void 0&&t.BatchCreateEndpoint){let e=o.batchCreate,n={};e.maxBatchSize!==void 0&&(n.maxBatchSize=e.maxBatchSize),d.batchCreate=a(t.BatchCreateEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,bodySchema:e.bodySchema,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:n});}if(o.batchUpdate!==void 0&&t.BatchUpdateEndpoint){let e=o.batchUpdate,n={};e.maxBatchSize!==void 0&&(n.maxBatchSize=e.maxBatchSize),d.batchUpdate=a(t.BatchUpdateEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:n});}if(o.batchDelete!==void 0&&t.BatchDeleteEndpoint){let e=o.batchDelete,n={};e.maxBatchSize!==void 0&&(n.maxBatchSize=e.maxBatchSize),d.batchDelete=a(t.BatchDeleteEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:n});}if(o.batchRestore!==void 0&&t.BatchRestoreEndpoint){let e=o.batchRestore,n={};e.maxBatchSize!==void 0&&(n.maxBatchSize=e.maxBatchSize),d.batchRestore=a(t.BatchRestoreEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:n});}if(o.batchUpsert!==void 0&&t.BatchUpsertEndpoint){let e=o.batchUpsert,n=typeof e.conflictTarget=="string"?[e.conflictTarget]:e.conflictTarget,r={};e.maxBatchSize!==void 0&&(r.maxBatchSize=e.maxBatchSize),n!==void 0&&(r.upsertKeys=n),d.batchUpsert=a(t.BatchUpsertEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,bodySchema:e.bodySchema,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:r});}if(o.export!==void 0&&t.ExportEndpoint){let e=o.export,n={};e.maxRows!==void 0&&(n.maxExportRecords=e.maxRows),e.formats!==void 0&&e.formats.length>0&&(n.defaultFormat=e.formats[0]),d.export=a(t.ExportEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,extras:n});}if(o.import!==void 0&&t.ImportEndpoint){let e=o.import,n={};e.maxRows!==void 0&&(n.maxBatchSize=e.maxRows),d.import=a(t.ImportEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,before:e.hooks?.before,after:e.hooks?.after,extras:n});}if(o.upsert!==void 0&&t.UpsertEndpoint){let e=o.upsert,n=typeof e.conflictTarget=="string"?[e.conflictTarget]:e.conflictTarget,r={};n!==void 0&&(r.upsertKeys=n),d.upsert=a(t.UpsertEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,bodySchema:e.bodySchema,beforeHookMode:e.hooks?.beforeMode,afterHookMode:e.hooks?.afterMode,before:e.hooks?.before,after:e.hooks?.after,extras:r});}if(o.clone!==void 0&&t.CloneEndpoint){let e=o.clone,n={};e.fieldsToReset!==void 0&&(n.excludeFromClone=e.fieldsToReset),d.clone=a(t.CloneEndpoint,{meta:o.meta,schema:e.openapi,middlewares:e.middlewares,before:e.hooks?.before,after:e.hooks?.after,extras:n});}return d}export{s as a};
@@ -1 +1 @@
1
- import {u}from'./chunk-DALXO46J.js';var m=class{entriesById=new Map;entryIds=[];maxEntries;maxAge;cleanupInterval;lastCleanup=0;constructor(e){this.maxEntries=e?.maxEntries??1e4,this.maxAge=e?.maxAge??864e5,this.cleanupInterval=e?.cleanupInterval??3e5;}maybeCleanup(){if(this.cleanupInterval<=0||this.maxAge<=0)return;let e=Date.now();e-this.lastCleanup>=this.cleanupInterval&&(this.lastCleanup=e,this.deleteOlderThanSync(this.maxAge));}deleteOlderThanSync(e){let s=Date.now()-e,a=0;for(let t=this.entryIds.length-1;t>=0;t--){let n=this.entryIds[t],r=this.entriesById.get(n);if(r)if(new Date(r.timestamp).getTime()<s)this.entriesById.delete(n),this.entryIds.splice(t,1),a++;else break}return a}async store(e){for(this.maybeCleanup();this.entryIds.length>=this.maxEntries;){let s=this.entryIds.pop();s&&this.entriesById.delete(s);}this.entriesById.set(e.id,e),this.entryIds.unshift(e.id);}async query(e){this.maybeCleanup();let s=this.getFilteredEntries(e);if(e?.sort){let{field:n,direction:r}=e.sort;s=s.sort((i,o)=>{let g,d;switch(n){case "timestamp":g=new Date(i.timestamp).getTime(),d=new Date(o.timestamp).getTime();break;case "responseTimeMs":g=i.response.responseTimeMs,d=o.response.responseTimeMs;break;case "statusCode":g=i.response.statusCode,d=o.response.statusCode;break;default:return 0}return r==="asc"?g-d:d-g});}let a=e?.offset??0,t=e?.limit??s.length;return s.slice(a,a+t)}async getById(e){return this.entriesById.get(e)??null}async count(e){return this.getFilteredEntries(e).length}async deleteOlderThan(e){return this.deleteOlderThanSync(e)}async clear(){let e=this.entriesById.size;return this.entriesById.clear(),this.entryIds=[],e}destroy(){this.entriesById.clear(),this.entryIds=[];}getSize(){return this.entriesById.size}getFilteredEntries(e){if(!e)return Array.from(this.entriesById.values());let s=[];for(let a of this.entryIds){let t=this.entriesById.get(a);if(t&&!(e.level&&!(Array.isArray(e.level)?e.level:[e.level]).includes(t.level))&&!(e.method&&!(Array.isArray(e.method)?e.method:[e.method]).map(r=>r.toUpperCase()).includes(t.request.method.toUpperCase()))&&!(e.path&&!u(t.request.path,e.path))){if(e.statusCode){let{min:n,max:r}=e.statusCode,i=t.response.statusCode;if(n!==void 0&&i<n||r!==void 0&&i>r)continue}if(e.timeRange){let n=new Date(t.timestamp).getTime(),{start:r,end:i}=e.timeRange;if(r){let o=typeof r=="string"?new Date(r).getTime():r.getTime();if(n<o)continue}if(i){let o=typeof i=="string"?new Date(i).getTime():i.getTime();if(n>o)continue}}e.userId&&t.request.userId!==e.userId||e.clientIp&&t.request.clientIp!==e.clientIp||e.requestId&&t.id!==e.requestId||e.errorMessage&&(!t.error?.message||!t.error.message.toLowerCase().includes(e.errorMessage.toLowerCase()))||s.push(t);}}return s}};export{m as a};
1
+ import {u}from'./chunk-IOWLCLF6.js';var m=class{entriesById=new Map;entryIds=[];maxEntries;maxAge;cleanupInterval;lastCleanup=0;constructor(e){this.maxEntries=e?.maxEntries??1e4,this.maxAge=e?.maxAge??864e5,this.cleanupInterval=e?.cleanupInterval??3e5;}maybeCleanup(){if(this.cleanupInterval<=0||this.maxAge<=0)return;let e=Date.now();e-this.lastCleanup>=this.cleanupInterval&&(this.lastCleanup=e,this.deleteOlderThanSync(this.maxAge));}deleteOlderThanSync(e){let s=Date.now()-e,a=0;for(let t=this.entryIds.length-1;t>=0;t--){let n=this.entryIds[t],r=this.entriesById.get(n);if(r)if(new Date(r.timestamp).getTime()<s)this.entriesById.delete(n),this.entryIds.splice(t,1),a++;else break}return a}async store(e){for(this.maybeCleanup();this.entryIds.length>=this.maxEntries;){let s=this.entryIds.pop();s&&this.entriesById.delete(s);}this.entriesById.set(e.id,e),this.entryIds.unshift(e.id);}async query(e){this.maybeCleanup();let s=this.getFilteredEntries(e);if(e?.sort){let{field:n,direction:r}=e.sort;s=s.sort((i,o)=>{let g,d;switch(n){case "timestamp":g=new Date(i.timestamp).getTime(),d=new Date(o.timestamp).getTime();break;case "responseTimeMs":g=i.response.responseTimeMs,d=o.response.responseTimeMs;break;case "statusCode":g=i.response.statusCode,d=o.response.statusCode;break;default:return 0}return r==="asc"?g-d:d-g});}let a=e?.offset??0,t=e?.limit??s.length;return s.slice(a,a+t)}async getById(e){return this.entriesById.get(e)??null}async count(e){return this.getFilteredEntries(e).length}async deleteOlderThan(e){return this.deleteOlderThanSync(e)}async clear(){let e=this.entriesById.size;return this.entriesById.clear(),this.entryIds=[],e}destroy(){this.entriesById.clear(),this.entryIds=[];}getSize(){return this.entriesById.size}getFilteredEntries(e){if(!e)return Array.from(this.entriesById.values());let s=[];for(let a of this.entryIds){let t=this.entriesById.get(a);if(t&&!(e.level&&!(Array.isArray(e.level)?e.level:[e.level]).includes(t.level))&&!(e.method&&!(Array.isArray(e.method)?e.method:[e.method]).map(r=>r.toUpperCase()).includes(t.request.method.toUpperCase()))&&!(e.path&&!u(t.request.path,e.path))){if(e.statusCode){let{min:n,max:r}=e.statusCode,i=t.response.statusCode;if(n!==void 0&&i<n||r!==void 0&&i>r)continue}if(e.timeRange){let n=new Date(t.timestamp).getTime(),{start:r,end:i}=e.timeRange;if(r){let o=typeof r=="string"?new Date(r).getTime():r.getTime();if(n<o)continue}if(i){let o=typeof i=="string"?new Date(i).getTime():i.getTime();if(n>o)continue}}e.userId&&t.request.userId!==e.userId||e.clientIp&&t.request.clientIp!==e.clientIp||e.requestId&&t.id!==e.requestId||e.errorMessage&&(!t.error?.message||!t.error.message.toLowerCase().includes(e.errorMessage.toLowerCase()))||s.push(t);}}return s}};export{m as a};
@@ -1,9 +1,9 @@
1
1
  import 'hono';
2
2
  import 'zod';
3
- export { A as AdapterBundle, a as AggregateEndpointConfig, B as BatchCreateEndpointConfig, b as BatchDeleteEndpointConfig, c as BatchRestoreEndpointConfig, d as BatchUpdateEndpointConfig, e as BatchUpsertEndpointConfig, f as CloneEndpointConfig, g as CreateEndpointConfig, D as DeleteEndpointConfig, m as EndpointsConfig, E as ExportEndpointConfig, G as GeneratedEndpoints, I as ImportEndpointConfig, L as ListEndpointConfig, R as ReadEndpointConfig, h as RestoreEndpointConfig, S as SearchEndpointConfig, U as UpdateEndpointConfig, i as UpsertEndpointConfig, s as defineEndpoints } from '../index-B1PgVRqD.js';
4
- import '../route-BHXjgMro.js';
5
- import '../types-DKPLu-9p.js';
6
- import '../types-O7tEXxjA.js';
3
+ export { A as AdapterBundle, a as AggregateEndpointConfig, B as BatchCreateEndpointConfig, b as BatchDeleteEndpointConfig, c as BatchRestoreEndpointConfig, d as BatchUpdateEndpointConfig, e as BatchUpsertEndpointConfig, f as CloneEndpointConfig, g as CreateEndpointConfig, D as DeleteEndpointConfig, m as EndpointsConfig, E as ExportEndpointConfig, G as GeneratedEndpoints, I as ImportEndpointConfig, L as ListEndpointConfig, R as ReadEndpointConfig, h as RestoreEndpointConfig, S as SearchEndpointConfig, U as UpdateEndpointConfig, i as UpsertEndpointConfig, s as defineEndpoints } from '../index-DFYo-Us4.js';
4
+ import '../route-C6T6CTON.js';
5
+ import '../types-tthfGTqv.js';
6
+ import '../types-zAClTFVv.js';
7
7
  import '@hono/zod-openapi';
8
8
  import 'hono/utils/http-status';
9
9
  import '../types-B5wq2iKZ.js';
@@ -1 +1 @@
1
- export{a as defineEndpoints}from'../chunk-2T3DGA4L.js';import'../chunk-STAO4FWC.js';
1
+ export{a as defineEndpoints}from'../chunk-RVKM7SXJ.js';import'../chunk-STAO4FWC.js';