hono-crud 0.13.11 → 0.13.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/dist/api-version/index.js +1 -1
- package/dist/audit/index.d.ts +1 -1
- package/dist/auth/index.d.ts +3 -3
- package/dist/auth/index.js +1 -1
- package/dist/chunk-5F2VPG4B.js +11 -0
- package/dist/chunk-6XVCICWS.js +1 -0
- package/dist/{chunk-NEBNG4DP.js → chunk-A7ZLZUMJ.js} +1 -1
- package/dist/chunk-H5D4D6Y7.js +1 -0
- package/dist/chunk-KTDHELSH.js +1 -0
- package/dist/config/index.d.ts +4 -4
- package/dist/functional/index.d.ts +2 -2
- package/dist/{helpers-C3xy6C9u.d.ts → helpers--TefHzCj.d.ts} +1 -1
- package/dist/{index-BWwvlRfM.d.ts → index-B1PgVRqD.d.ts} +12 -58
- package/dist/{index-CZZ12W3j.d.ts → index-B3hpRLJg.d.ts} +2 -2
- package/dist/{index-DHJ4DeUp.d.ts → index-Cjm4QRuE.d.ts} +66 -196
- package/dist/index.d.ts +7 -7
- package/dist/index.js +1 -1
- package/dist/internal.d.ts +9 -9
- package/dist/internal.js +1 -1
- package/dist/multi-tenant/index.d.ts +5 -3
- package/dist/multi-tenant/index.js +1 -1
- package/dist/{route-BULuf1Xl.d.ts → route-BHXjgMro.d.ts} +1 -1
- package/dist/storage/index.d.ts +2 -2
- package/dist/{types-C_OAPSsu.d.ts → types-DKPLu-9p.d.ts} +14 -1
- package/dist/{types-DXVXRfuq.d.ts → types-O7tEXxjA.d.ts} +1 -1
- package/dist/versioning/index.d.ts +1 -1
- package/package.json +1 -1
- package/dist/chunk-5HFTJZQX.js +0 -11
- package/dist/chunk-A3O6KC4L.js +0 -1
- package/dist/chunk-QFPEE4LH.js +0 -1
- package/dist/chunk-WECW5WB3.js +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.13.12
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 1b4c5dd: Error-shape unification (breaking, patch): every failure the library emits now uses the one canonical envelope `{ success: false, error: { code, message, details? } }` with a stable machine-readable code, and the OpenAPI docs tell the same story as the wire.
|
|
8
|
+
|
|
9
|
+
- Validation is one shape on one status: `openApiValidationHook` now throws `InputValidationException` instead of returning a 422 ZodError-style body, so the hook path and the thrown path produce the identical 400 `VALIDATION_ERROR` envelope with `details: [{path, message, code}]`. `createValidationHook`'s default status flips 422 → 400 (explicit 422 still accepted). `fromHono` installs the canonical hook as `defaultHook` when none is set, so bare apps stop leaking `@hono/zod-validator`'s raw ZodError body.
|
|
10
|
+
- Library throw-sites get real codes instead of generic `HTTP_ERROR`: write-policy denial → 403 `FORBIDDEN` (as its docblock always claimed), missing tenant → 400 `TENANT_REQUIRED` (endpoint and middleware paths), failed tenant validation → 400 `INVALID_TENANT`. Aggregate allow-list/limit denials change from 500 `INTERNAL_ERROR` to 400 `AGGREGATION_ERROR`; search min-query and subscribe failures now throw typed exceptions (same codes/statuses) so custom response envelopes apply.
|
|
11
|
+
- Doc truthfulness: list and export endpoints now declare the 400 response their failable query schemas can produce; bulk-patch's hand-written 400 body is replaced with the canonical schema; new `validationIssueSchema` describes the `details` items.
|
|
12
|
+
- Hardening: `ApiException.getResponse()` returns the canonical JSON envelope, so apps without `createErrorHandler` no longer get Hono's plain-text fallback; falsy `details` values (0, '', false) are no longer dropped.
|
|
13
|
+
- Removed orphan exports (never emitted by anything): `successResponse`, `errorResponse`, `HttpErrorSchema`, `ZodErrorSchema`, `ZodIssueSchema`, `createErrorSchema`, `createOneOfErrorSchema`, `httpErrorContent`, `commonResponses`, `ValidationHookResult` — use `errorResponseSchema` / `errorResponses` / `validationIssueSchema` / the canonical envelope schemas instead.
|
|
14
|
+
|
|
3
15
|
## 0.13.11
|
|
4
16
|
|
|
5
17
|
### Patch Changes
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as apiVersion,b as getApiVersion,c as getApiVersionConfig,d as versionedResponse}from'../chunk-
|
|
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';
|
package/dist/audit/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Context } from 'hono';
|
|
2
|
-
import { A as AuditConfig, f as AuditLogEntry, g as AuditAction } from '../types-
|
|
2
|
+
import { A as AuditConfig, f as AuditLogEntry, g as AuditAction } from '../types-DKPLu-9p.js';
|
|
3
3
|
import { S as StorageRegistry } from '../registry-3p4qTDGZ.js';
|
|
4
4
|
import 'zod';
|
|
5
5
|
import '../types-B5wq2iKZ.js';
|
package/dist/auth/index.d.ts
CHANGED
|
@@ -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,
|
|
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-
|
|
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';
|
|
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-
|
|
8
|
+
import '../route-BHXjgMro.js';
|
|
9
9
|
import 'hono/utils/http-status';
|
package/dist/auth/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{
|
|
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';
|
|
@@ -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-KTDHELSH.js';import {G}from'./chunk-DALXO46J.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 {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 {e as e$1,f as f$1}from'./chunk-6MS7YXSZ.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={docs_url:"/docs",redoc_url:"/redoc",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 vo(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 Fo(n){return n!=null&&n!==""}function rt(n,e,t,o){let r={...n},i$1=e.primaryKeys[0];if(!Fo(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 Io=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")&&Io.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 vt=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 Ft=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 It=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 Fs(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})}},ve=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})}},Fe=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})}},Ie=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 ve(this.meta)}read(){return new Fe(this.meta)}update(){return new Ie(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,Fs as Da,lt as E,nr as Ea,ct as F,ir as Fa,pt as G,Pe as Ga,ut as H,ve as Ha,mt as I,Fe as Ia,Yt as J,Ie 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,vt as ea,ye as f,Ft as fa,po as g,It 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,vo 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 {HTTPException}from'hono/http-exception';var e=class extends HTTPException{code;details;constructor(t,s=500,r="INTERNAL_ERROR",R){super(s,{message:t}),this.name="ApiException",this.code=r,this.details=R;}toJSON(){let t={code:this.code,message:this.message};return this.details!==void 0&&(t.details=this.details),{success:false,error:t}}getResponse(){return Response.json(this.toJSON(),{status:this.status})}get statusCode(){return this.status}},n=class o extends e{constructor(t,s){super(t,400,"VALIDATION_ERROR",s),this.name="InputValidationException";}static fromZodError(t){let s=t.issues.map(r=>({path:r.path.join("."),message:r.message,code:r.code}));return new o("Validation failed",s)}},i=class extends e{constructor(t="Resource",s){let r=s?`${t} with id '${s}' not found`:`${t} not found`;super(r,404,"NOT_FOUND"),this.name="NotFoundException";}},a=class extends e{constructor(t="Resource already exists",s){super(t,409,"CONFLICT",s),this.name="ConflictException";}},u=class extends e{constructor(t="Unauthorized"){super(t,401,"UNAUTHORIZED"),this.name="UnauthorizedException";}},d=class extends e{constructor(t="Forbidden"){super(t,403,"FORBIDDEN"),this.name="ForbiddenException";}},c=class extends e{constructor(t,s){super(t,400,"AGGREGATION_ERROR",s),this.name="AggregationException";}},p=class extends e{constructor(t,s){super(t,500,"CACHE_ERROR",s),this.name="CacheException";}},l=class extends e{constructor(t,s){super(t,500,"CONFIGURATION_ERROR",s),this.name="ConfigurationException";}};export{e as a,n as b,i as c,a as d,u as e,d as f,c as g,p as h,l as i};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a}from'./chunk-
|
|
1
|
+
import {a}from'./chunk-6XVCICWS.js';import {a as a$1}from'./chunk-6GO5LUOZ.js';function l(e,n){return e.req.header(n)??void 0}function w(e,n){return e.req.query(n)??void 0}function C(e,n){let i=e.req.path,a=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace("\\{version\\}","([^/]+)"),d=new RegExp(`^${a}`);return i.match(d)?.[1]}function h(e){let{versions:n,strategy:i="header",headerName:p="Accept-Version",queryParam:a$2="version",urlPattern:d="/v{version}",extractVersion:f,addHeaders:c=true}=e,V=e.defaultVersion??n[0]?.version,u=new Map;for(let r of n)u.set(r.version,r);return async(r,m)=>{let t=f?f(r):{header:()=>l(r,p),query:()=>w(r,a$2),url:()=>C(r,d)}[i]();if(t=t??V,!t)throw new a("API version is required",400,"VERSION_REQUIRED");let o=u.get(t);if(!o)throw new a(`Unsupported API version: ${t}`,400,"UNSUPPORTED_VERSION");if(r.set(a$1.apiVersion,t),r.set(a$1.apiVersionConfig,o),c&&(r.header("X-API-Version",t),o.deprecated&&r.header("Deprecation",o.deprecated),o.sunset&&r.header("Sunset",o.sunset)),o.middleware&&o.middleware.length>0)for(let y of o.middleware)await y(r,async()=>{});await m();}}function v(e){return e.get(a$1.apiVersion)}function A(e){return e.get(a$1.apiVersionConfig)}function E(){return async(e,n)=>{await n();let i=e.get(a$1.apiVersionConfig);if(!(!i?.responseTransformer||!e.res.headers.get("content-type")?.includes("application/json")))try{let a=await e.res.json(),d=i.responseTransformer(a);e.res=new Response(JSON.stringify(d),{status:e.res.status,headers:e.res.headers});}catch{}}}export{h as a,v as b,A as c,E as d};
|
|
@@ -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 M(c={}){let{source:a$2="header",headerName:m="X-Tenant-ID",pathParam:l="tenantId",queryParam:E="tenantId",jwtClaim:f="tenantId",extractor:i,contextKey:g="tenantId",required:p=true,errorMessage:x="Tenant ID is required",onMissing:o,validate:s,invalidMessage:w="Invalid tenant ID"}=c;if(a$2==="custom"&&!i)throw new Error("multiTenant: source 'custom' requires an `extractor` function. Provide `extractor`, or choose a different `source`.");let h={header:e=>e.req.header(m),path:e=>e.req.param(l),query:e=>e.req.query(E),jwt:e=>{let t=e.get(a$1.jwtPayload);if(t&&typeof t=="object")return t[f]},custom:e=>i?.(e)};return async(e,t)=>{let y=h[a$2],n=await y(e);if(!n){if(p){if(o)return o(e);throw new a(x,400,"TENANT_REQUIRED")}return t()}if(s&&!await s(n,e))throw new a(w,400,"INVALID_TENANT");return b(e,g,n),t()}}export{M as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {k as k$1,p}from'./chunk-DALXO46J.js';import {a as a$2}from'./chunk-NWOJZP4P.js';import {e,i,f}from'./chunk-6XVCICWS.js';import {b as b$1}from'./chunk-DMGP7QDL.js';import {b,a as a$1}from'./chunk-VJRDAVID.js';import {a}from'./chunk-6GO5LUOZ.js';import {z as z$1}from'zod';import {decode,verify}from'hono/jwt';var U=["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512"],M=z$1.object({sub:z$1.string().optional(),iss:z$1.string().optional(),aud:z$1.union([z$1.string(),z$1.array(z$1.string())]).optional(),exp:z$1.number().int().optional(),nbf:z$1.number().int().optional(),iat:z$1.number().int().optional(),jti:z$1.string().optional(),email:z$1.string().optional(),role:z$1.string().optional(),roles:z$1.union([z$1.array(z$1.string()),z$1.string()]).optional(),permissions:z$1.union([z$1.array(z$1.string()),z$1.string()]).optional(),metadata:z$1.record(z$1.string(),z$1.unknown()).optional()}).passthrough();function oe(e){return M.parse(e)}function K(e){return M.safeParse(e)}z$1.object({id:z$1.string(),tenantId:z$1.string().optional(),organizationId:z$1.string().optional(),userId:z$1.string().optional(),actorUserId:z$1.string().optional(),onBehalfOfUserId:z$1.string().optional(),agentId:z$1.string().optional(),agentRunId:z$1.string().optional(),toolCallId:z$1.string().optional(),source:z$1.enum(["http","agent-mcp","agent-code-mode","workflow","job","system"]),toolName:z$1.string(),input:z$1.unknown(),status:z$1.enum(["pending","approved","rejected","expired"]),createdAt:z$1.iso.datetime(),expiresAt:z$1.iso.datetime(),reason:z$1.string(),approvedBy:z$1.string().optional(),approvedAt:z$1.iso.datetime().optional(),rejectedBy:z$1.string().optional(),rejectedReason:z$1.string().optional()});function C(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 Y(e){if(!U.includes(e))throw new Error(`Unsupported algorithm: ${e}`);return e}function se(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 G(e){if(e!==void 0)return Array.isArray(e)?e:[e]}function ie(e){return {id:String(e.sub||e.id||""),email:e.email,roles:G(e.roles??e.role),permissions:G(e.permissions),metadata:e.metadata}}function z(e$1){let t=Y(e$1.algorithm||"HS256"),n=e$1.clockTolerance||0,r=e$1.extractToken||se,o=e$1.extractUser||ie;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=K(y);if(!g.success)throw new e("Invalid token claims");let A=g.data;C(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 ae(e$1,t){let n=Y(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 C(u,{clockTolerance:r,issuer:t.issuer,audience:t.audience}),u}function ue(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}async function N(e){let n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n),o=new Uint8Array(r);return Array.from(o).map(s=>s.toString(16).padStart(2,"0")).join("")}function de(e){return {id:e.userId,roles:e.roles,permissions:e.permissions,metadata:{...e.metadata,apiKeyId:e.id,apiKeyName:e.name}}}function le(e,t){return e.req.header(t)||null}function ce(e,t){return e.req.query(t)||null}function W(e$1){let t=e$1.headerName||"X-API-Key",n=e$1.queryParam??null,r=e$1.hashKey||N,o=e$1.extractUser||de;return async(s,u)=>{let d=le(s,t);if(!d&&n&&(d=ce(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 pe(e,t){let r=await(t.hashKey||N)(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 J(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?z(e$1.jwt):null,u=e$1.apiKey?W(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 he(e){return J({...e,requireAuth:false})}function ge(e){return J({...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 me=/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/;function _(e){let t=me.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 fe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var H,ee=false;function ye(){return H||(H=new R),ee||(ee=true,b$1().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.")),H}var te=a.policies;function Ae(...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 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.every(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.permissions||[];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.some(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");if(!await e$1(r,t))throw new f("Access denied");await n();}}function Re(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 ve(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 Pe(...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 Ce(e="Access denied"){return async()=>{throw new f(e)}}function ke(){return async(e,t)=>{await t();}}function Ie(){return async(e$1,t)=>{if(!e$1.var.user)throw new e("Authentication required");await t();}}function Se(e){return async(t,n)=>{b(t,te,e),await n();}}function qe(e){let t=e.approvalStorage??ye(),n=e.resumeMarker??"_resume_",r=_(e.expiresAfter??"P1D"),o=z$1.object({[n]:z$1.string()}).loose();return async(s,u)=>{let d={};try{let x=await s.req.json();fe(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`);Oe(s,x.input),await u();return}let y=a$1(s,a.userId),g=a$1(s,a.agentId),A=a$1(s,a.agentRunId),m=a$1(s,a.onBehalfOfUserId),h=a$1(s,a.toolCallId),v=a$1(s,a.tenantId),Z=a$1(s,a.organizationId),ne=a$1(s,a.actionSource)??(g?"agent-mcp":"http"),L=Date.now(),P={id:crypto.randomUUID(),tenantId:v,organizationId:Z,userId:y,actorUserId:y,onBehalfOfUserId:m,agentId:g,agentRunId:A,toolCallId:h,source:ne,toolName:e.toolName??`${s.req.method} ${s.req.path}`,input:d,status:"pending",createdAt:new Date(L).toISOString(),expiresAt:new Date(L+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 Oe(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 Ue=["eq","ne","gt","gte","lt","lte","in","nin","like","ilike","null","between"];function Tt(e){return Ue.includes(e)}function Et(e){throw new Error(`Unhandled discriminated union member: ${String(e)}`)}var Rt=["asc","desc"],vt=["any","all","phrase"],Pt=["count","sum","avg","min","max","countDistinct"];function bt(e){return e}function Ct(e){return e}var kt=z$1.object({path:z$1.string(),message:z$1.string(),code:z$1.string()}),Me=z$1.object({code:z$1.string(),message:z$1.string(),details:z$1.unknown().optional(),requestId:z$1.string().optional(),stack:z$1.string().optional()}).passthrough(),It=z$1.object({success:z$1.literal(false),error:Me});function St(e){return z$1.object({success:z$1.literal(true),result:e})}var Ke=a.responseEnvelope;function re(e){return e?.var?.[Ke]}function D(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=D(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=D(t,"query");o===void 0&&(o=t.req.query()),o!==void 0&&(r.query=o);}if(n.request?.params){let o=D(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 re(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$2(this.getContext());n?n(t):t.catch(r=>{b$1().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 Kt(e){return typeof e=="function"&&"isRoute"in e&&e.isRoute===true}function je(){return z$1.object({success:z$1.literal(false),error:z$1.object({code:z$1.string(),message:z$1.string(),details:z$1.unknown().optional()})})}function E(e){return {description:e??"Error",content:{"application/json":{schema:je()}}}}function Nt(e){let t={};for(let[n,r]of Object.entries(e))t[Number(n)]=E(r);return t}var F=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 ze(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{F as $,ve as A,Pe as B,be as C,Ce as D,ke as E,Ie as F,Se as G,qe as H,je as I,E as J,Nt as K,U as L,M,oe as N,K as O,C as P,se as Q,z as R,ae as S,ue as T,k as U,N as V,W,pe as X,J as Y,he as Z,ge as _,Ue as a,ze as aa,Tt as b,Et as c,Rt as d,vt as e,Pt as f,bt as g,Ct as h,kt as i,Me as j,It as k,St as l,Ke as m,re as n,I as o,S as p,Kt as q,R as r,_ as s,te as t,Ae as u,we as v,xe as w,Te as x,Ee as y,Re as z};
|
package/dist/config/index.d.ts
CHANGED
|
@@ -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-
|
|
4
|
-
import '../route-
|
|
5
|
-
import '../types-
|
|
6
|
-
import '../types-
|
|
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';
|
|
7
7
|
import '@hono/zod-openapi';
|
|
8
8
|
import 'hono/utils/http-status';
|
|
9
9
|
import '../types-B5wq2iKZ.js';
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Env, MiddlewareHandler } from 'hono';
|
|
2
|
-
import { M as MetaInput, O as OpenAPIRouteSchema, H as HookMode, F as FilterConfig, S as SortSpec, c as SortDirection } from '../types-
|
|
3
|
-
import { M as ModelObject } from '../types-
|
|
2
|
+
import { M as MetaInput, O as OpenAPIRouteSchema, H as HookMode, F as FilterConfig, S as SortSpec, c as SortDirection } from '../types-DKPLu-9p.js';
|
|
3
|
+
import { M as ModelObject } from '../types-O7tEXxjA.js';
|
|
4
4
|
import 'zod';
|
|
5
5
|
import '../types-B5wq2iKZ.js';
|
|
6
6
|
import '../types-Drjma4gp.js';
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Env, MiddlewareHandler, Context } from 'hono';
|
|
2
2
|
import { S as StorageRegistry } from './registry-3p4qTDGZ.js';
|
|
3
3
|
import { AuditLogStorage } from './audit/index.js';
|
|
4
|
-
import {
|
|
4
|
+
import { aX as APIKeyStorage } from './types-DKPLu-9p.js';
|
|
5
5
|
import { e as LoggingStorage } from './middleware-DBIpdsJ1.js';
|
|
6
6
|
import { VersioningStorage } from './versioning/index.js';
|
|
7
7
|
import { a as CrudEventEmitter } from './emitter-B6dLhiMF.js';
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { Env, Context, MiddlewareHandler, Hono } from 'hono';
|
|
2
2
|
import { ZodObject, ZodRawShape } from 'zod';
|
|
3
3
|
import { OpenAPIHono } from '@hono/zod-openapi';
|
|
4
|
-
import { O as OpenAPIRoute } from './route-
|
|
5
|
-
import { O as OpenAPIRouteSchema, a as ResponseEnvelope, M as MetaInput, H as HookMode, F as FilterConfig, c as SortDirection } from './types-
|
|
6
|
-
import { M as ModelObject } from './types-
|
|
4
|
+
import { O as OpenAPIRoute } from './route-BHXjgMro.js';
|
|
5
|
+
import { O as OpenAPIRouteSchema, a as ResponseEnvelope, M as MetaInput, H as HookMode, F as FilterConfig, c as SortDirection } from './types-DKPLu-9p.js';
|
|
6
|
+
import { M as ModelObject } from './types-O7tEXxjA.js';
|
|
7
7
|
|
|
8
8
|
interface OpenAPIConfig$1 {
|
|
9
9
|
openapi?: string;
|
|
@@ -138,6 +138,14 @@ declare class HonoOpenAPIHandler<E extends Env = Env> {
|
|
|
138
138
|
* Pass an OpenAPIHono instance to use middleware with your routes.
|
|
139
139
|
* Middleware should be applied directly to the app using `app.use()`.
|
|
140
140
|
*
|
|
141
|
+
* Installs the canonical validation hook (`openApiValidationHook`) as the
|
|
142
|
+
* app's `defaultHook` when none is set, so request-schema failures emit the
|
|
143
|
+
* canonical 400 `VALIDATION_ERROR` envelope. To override, pass a
|
|
144
|
+
* pre-configured `new OpenAPIHono({ defaultHook })` — a user-supplied hook
|
|
145
|
+
* always wins. Note: routes registered on a pre-configured `OpenAPIHono`
|
|
146
|
+
* *before* calling `fromHono` keep whatever hook they captured at
|
|
147
|
+
* registration time.
|
|
148
|
+
*
|
|
141
149
|
* @example
|
|
142
150
|
* ```ts
|
|
143
151
|
* import { OpenAPIHono } from '@hono/zod-openapi';
|
|
@@ -298,60 +306,6 @@ declare function contentJson<T>(schema: T): {
|
|
|
298
306
|
};
|
|
299
307
|
};
|
|
300
308
|
};
|
|
301
|
-
/**
|
|
302
|
-
* Creates a standardized success response schema.
|
|
303
|
-
*/
|
|
304
|
-
declare function successResponse<T>(schema: T): {
|
|
305
|
-
content: {
|
|
306
|
-
'application/json': {
|
|
307
|
-
schema: {
|
|
308
|
-
type: "object";
|
|
309
|
-
properties: {
|
|
310
|
-
success: {
|
|
311
|
-
type: "boolean";
|
|
312
|
-
enum: boolean[];
|
|
313
|
-
};
|
|
314
|
-
result: T;
|
|
315
|
-
};
|
|
316
|
-
required: string[];
|
|
317
|
-
};
|
|
318
|
-
};
|
|
319
|
-
};
|
|
320
|
-
description: string;
|
|
321
|
-
};
|
|
322
|
-
/**
|
|
323
|
-
* Creates a standardized error response schema.
|
|
324
|
-
*/
|
|
325
|
-
declare function errorResponse(description?: string): {
|
|
326
|
-
content: {
|
|
327
|
-
'application/json': {
|
|
328
|
-
schema: {
|
|
329
|
-
type: "object";
|
|
330
|
-
properties: {
|
|
331
|
-
success: {
|
|
332
|
-
type: "boolean";
|
|
333
|
-
enum: boolean[];
|
|
334
|
-
};
|
|
335
|
-
error: {
|
|
336
|
-
type: "object";
|
|
337
|
-
properties: {
|
|
338
|
-
code: {
|
|
339
|
-
type: "string";
|
|
340
|
-
};
|
|
341
|
-
message: {
|
|
342
|
-
type: "string";
|
|
343
|
-
};
|
|
344
|
-
details: {};
|
|
345
|
-
};
|
|
346
|
-
required: string[];
|
|
347
|
-
};
|
|
348
|
-
};
|
|
349
|
-
required: string[];
|
|
350
|
-
};
|
|
351
|
-
};
|
|
352
|
-
};
|
|
353
|
-
description: string;
|
|
354
|
-
};
|
|
355
309
|
|
|
356
310
|
/**
|
|
357
311
|
* Config-Based API for defining CRUD endpoints.
|
|
@@ -938,4 +892,4 @@ interface GeneratedEndpoints<E extends Env = Env> {
|
|
|
938
892
|
*/
|
|
939
893
|
declare function defineEndpoints<M extends MetaInput, E extends Env = Env>(config: EndpointsConfig<M>, adapters: AdapterBundle<E>): GeneratedEndpoints<E>;
|
|
940
894
|
|
|
941
|
-
export { type AdapterBundle as A, type BatchCreateEndpointConfig as B, type CrudEndpoints as C, type DeleteEndpointConfig as D, type ExportEndpointConfig as E, type GeneratedEndpoints as G, type HonoOpenAPIApp as H, type ImportEndpointConfig as I, type ListEndpointConfig as L, type OpenAPIConfig$1 as O, type ReadEndpointConfig as R, type SearchEndpointConfig as S, type UpdateEndpointConfig as U, type AggregateEndpointConfig as a, type BatchDeleteEndpointConfig as b, type BatchRestoreEndpointConfig as c, type BatchUpdateEndpointConfig as d, type BatchUpsertEndpointConfig as e, type CloneEndpointConfig as f, type CreateEndpointConfig as g, type RestoreEndpointConfig as h, type UpsertEndpointConfig as i, type CrudEndpointName as j, type EndpointClass as k, type EndpointMiddlewares as l, type EndpointsConfig as m, HonoOpenAPIHandler as n, type RegisterCrudOptions as o, type RegisteredRoute as p, type RouterOptions as q, contentJson as r, defineEndpoints as s,
|
|
895
|
+
export { type AdapterBundle as A, type BatchCreateEndpointConfig as B, type CrudEndpoints as C, type DeleteEndpointConfig as D, type ExportEndpointConfig as E, type GeneratedEndpoints as G, type HonoOpenAPIApp as H, type ImportEndpointConfig as I, type ListEndpointConfig as L, type OpenAPIConfig$1 as O, type ReadEndpointConfig as R, type SearchEndpointConfig as S, type UpdateEndpointConfig as U, type AggregateEndpointConfig as a, type BatchDeleteEndpointConfig as b, type BatchRestoreEndpointConfig as c, type BatchUpdateEndpointConfig as d, type BatchUpsertEndpointConfig as e, type CloneEndpointConfig as f, type CreateEndpointConfig as g, type RestoreEndpointConfig as h, type UpsertEndpointConfig as i, type CrudEndpointName as j, type EndpointClass as k, type EndpointMiddlewares as l, type EndpointsConfig as m, HonoOpenAPIHandler as n, type RegisterCrudOptions as o, type RegisteredRoute as p, type RouterOptions as q, contentJson as r, defineEndpoints as s, fromHono as t, getHandlerForApp as u, registerCrud as v };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { C as AuthEnv, a8 as JWTConfig, a6 as JWTClaims, n as APIKeyConfig, o as APIKeyEntry, B as AuthConfig, Z as Guard, y as ApprovalConfig, G as AuthorizationCheck, ao as OwnershipExtractor, ab as ModelPolicies, z as ApprovalStorage, ar as PendingAction, E as AuthUser, M as MetaInput, O as OpenAPIRouteSchema, T as Constructor, U as EndpointAuthConfig,
|
|
1
|
+
import { C as AuthEnv, a8 as JWTConfig, a6 as JWTClaims, n as APIKeyConfig, o as APIKeyEntry, B as AuthConfig, Z as Guard, y as ApprovalConfig, G as AuthorizationCheck, ao as OwnershipExtractor, ab as ModelPolicies, z as ApprovalStorage, ar as PendingAction, E as AuthUser, M as MetaInput, O as OpenAPIRouteSchema, T as Constructor, U as EndpointAuthConfig, aX as APIKeyStorage, p as APIKeyLookupResult } from './types-DKPLu-9p.js';
|
|
2
2
|
import { MiddlewareHandler, Context } from 'hono';
|
|
3
|
-
import { O as OpenAPIRoute } from './route-
|
|
3
|
+
import { O as OpenAPIRoute } from './route-BHXjgMro.js';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Default function to extract a Bearer token from the `Authorization` header.
|