hono-crud 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/README.md +18 -0
  3. package/dist/adapters/drizzle/index.d.ts +14 -9
  4. package/dist/adapters/drizzle/index.js +2 -2
  5. package/dist/adapters/memory/index.d.ts +10 -5
  6. package/dist/adapters/memory/index.js +1 -1
  7. package/dist/adapters/prisma/index.d.ts +9 -4
  8. package/dist/adapters/prisma/index.js +1 -1
  9. package/dist/api-version/index.d.ts +114 -0
  10. package/dist/api-version/index.js +1 -0
  11. package/dist/audit/index.d.ts +152 -0
  12. package/dist/audit/index.js +1 -0
  13. package/dist/auth/index.d.ts +132 -5
  14. package/dist/auth/index.js +1 -1
  15. package/dist/{bulk-patch-D-Snxx42.d.ts → bulk-patch-CoEduhTf.d.ts} +4 -13
  16. package/dist/cache/index.d.ts +5 -3
  17. package/dist/cache/index.js +1 -1
  18. package/dist/chunk-2M5BM4VD.js +1 -0
  19. package/dist/chunk-7DDNX2F2.js +1 -0
  20. package/dist/chunk-BJTWQHEV.js +0 -0
  21. package/dist/chunk-BSL6R76X.js +1 -0
  22. package/dist/chunk-CCGZ5UPB.js +0 -0
  23. package/dist/chunk-DMGP7QDL.js +1 -0
  24. package/dist/chunk-FC56WWPB.js +1 -0
  25. package/dist/chunk-FXIMMYFV.js +1 -0
  26. package/dist/chunk-GASDSU4U.js +1 -0
  27. package/dist/chunk-GBQQ3YQX.js +1 -0
  28. package/dist/chunk-GF2EC5G4.js +1 -0
  29. package/dist/{chunk-CLNKDHBG.js → chunk-H3H65KZF.js} +1 -1
  30. package/dist/chunk-HAUN4LQO.js +1 -0
  31. package/dist/chunk-KKLMXJY4.js +1 -0
  32. package/dist/chunk-L4X7KFWN.js +1 -0
  33. package/dist/chunk-MDHMZPXK.js +1 -0
  34. package/dist/chunk-NIWM7GOK.js +1 -0
  35. package/dist/{chunk-WCQ3LO6R.js → chunk-OXBPASZN.js} +1 -1
  36. package/dist/chunk-Q2D5AUPJ.js +1 -0
  37. package/dist/chunk-Q4FF5JVS.js +11 -0
  38. package/dist/chunk-QRXEQTNE.js +1 -0
  39. package/dist/chunk-QXFY6NYI.js +1 -0
  40. package/dist/chunk-RFT77JBK.js +1 -0
  41. package/dist/chunk-SDNXN7M5.js +1 -0
  42. package/dist/chunk-VJRDAVID.js +1 -0
  43. package/dist/chunk-W4FHI5YI.js +1 -0
  44. package/dist/chunk-XH7DEPW2.js +1 -0
  45. package/dist/emitter-Npan0uNZ.d.ts +104 -0
  46. package/dist/encryption/index.d.ts +42 -0
  47. package/dist/encryption/index.js +1 -0
  48. package/dist/events/index.d.ts +87 -0
  49. package/dist/events/index.js +1 -0
  50. package/dist/health/index.d.ts +103 -0
  51. package/dist/health/index.js +1 -0
  52. package/dist/idempotency/index.d.ts +80 -0
  53. package/dist/idempotency/index.js +1 -0
  54. package/dist/{import-D5BPlFB5.d.ts → import-BHD2B1u8.d.ts} +111 -186
  55. package/dist/{index-BlgcrFpZ.d.ts → index-BNIzQvcO.d.ts} +2 -2
  56. package/dist/{index-C0ebqb3b.d.ts → index-DhCIATbD.d.ts} +5 -43
  57. package/dist/index.d.ts +65 -1005
  58. package/dist/index.js +1 -1
  59. package/dist/logging/index.d.ts +1 -86
  60. package/dist/logging/index.js +1 -1
  61. package/dist/multi-tenant/index.d.ts +136 -0
  62. package/dist/multi-tenant/index.js +1 -0
  63. package/dist/rate-limit/index.d.ts +2 -2
  64. package/dist/rate-limit/index.js +1 -1
  65. package/dist/registry-PNJjvSvm.d.ts +147 -0
  66. package/dist/{route-DwSID3du.d.ts → route-BmtmmHSO.d.ts} +1 -9
  67. package/dist/serialization/index.d.ts +26 -0
  68. package/dist/serialization/index.js +1 -0
  69. package/dist/storage/index.d.ts +260 -8
  70. package/dist/storage/index.js +1 -1
  71. package/dist/types/cloudflare.d.ts +1 -1
  72. package/dist/{types-CA784ZtV.d.ts → types-5BBVU0EY.d.ts} +28 -1
  73. package/dist/types-B5wq2iKZ.d.ts +30 -0
  74. package/dist/types-BAcN7U0B.d.ts +40 -0
  75. package/dist/types-BCsipBBX.d.ts +38 -0
  76. package/dist/types-BNui1SQl.d.ts +89 -0
  77. package/dist/{memory-B_NZbOQP.d.ts → types-Di38wHnA.d.ts} +21 -126
  78. package/dist/{versioning-BG3T0q1q.d.ts → versioning/index.d.ts} +14 -138
  79. package/dist/versioning/index.js +1 -0
  80. package/package.json +37 -1
  81. package/dist/chunk-HX7QWSYF.js +0 -1
  82. package/dist/chunk-JFFTAQOR.js +0 -1
  83. package/dist/chunk-K3226EHO.js +0 -1
  84. package/dist/chunk-LE4MKODL.js +0 -1
  85. package/dist/chunk-SFCD22UI.js +0 -11
  86. package/dist/chunk-TWBEVCH3.js +0 -1
  87. package/dist/chunk-UT3KYWDL.js +0 -1
  88. package/dist/chunk-WRFHCN2W.js +0 -1
  89. package/dist/index-BgD-_6bM.d.ts +0 -621
  90. /package/dist/{kv-types-ByUEHhBc.d.ts → cloudflare-kv-types-ByUEHhBc.d.ts} +0 -0
package/CHANGELOG.md CHANGED
@@ -19,6 +19,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
19
19
  %b
20
20
  %b
21
21
  %b
22
+ %b
23
+ %b
22
24
  ## [0.1.0] - 2025-01-29
23
25
 
24
26
  ### Added
@@ -54,3 +56,5 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
54
56
  [0.4.3]: https://github.com/kshdotdev/hono-crud/compare/v0.4.2...v0.4.3
55
57
  [0.4.4]: https://github.com/kshdotdev/hono-crud/compare/v0.4.3...v0.4.4
56
58
  [0.5.0]: https://github.com/kshdotdev/hono-crud/compare/v0.4.4...v0.5.0
59
+ [0.5.1]: https://github.com/kshdotdev/hono-crud/compare/v0.5.0...v0.5.1
60
+ [0.5.2]: https://github.com/kshdotdev/hono-crud/compare/v0.5.1...v0.5.2
package/README.md CHANGED
@@ -317,6 +317,24 @@ See [docs/logging.md](./docs/logging.md).
317
317
 
318
318
  See [docs/advanced-features.md](./docs/advanced-features.md) for examples of every feature.
319
319
 
320
+ ### Subpath Imports
321
+
322
+ Every advanced feature is also exposed as a tree-shakeable subpath, so apps that only need one feature can import it directly without pulling in the rest of the library:
323
+
324
+ ```typescript
325
+ import { multiTenant } from 'hono-crud/multi-tenant';
326
+ import { createAuditLogger, MemoryAuditLogStorage } from 'hono-crud/audit';
327
+ import { VersionManager, MemoryVersioningStorage } from 'hono-crud/versioning';
328
+ import { CrudEventEmitter, registerWebhooks } from 'hono-crud/events';
329
+ import { idempotency, MemoryIdempotencyStorage } from 'hono-crud/idempotency';
330
+ import { createHealthEndpoints } from 'hono-crud/health';
331
+ import { encryptFields, decryptFields, StaticKeyProvider } from 'hono-crud/encryption';
332
+ import { applyProfile, type SerializationProfile } from 'hono-crud/serialization';
333
+ import { apiVersion, getApiVersion } from 'hono-crud/api-version';
334
+ ```
335
+
336
+ The same symbols remain available from `'hono-crud'` for convenience.
337
+
320
338
  ## API Documentation
321
339
 
322
340
  ```typescript
@@ -1,13 +1,18 @@
1
1
  import { Table, SQL, Column } from 'drizzle-orm';
2
- import { M as MetaInput, I as IncludeOptions, F as FilterCondition, g as RelationConfig, h as NestedUpdateInput, i as NestedWriteResult, L as ListFilters, P as PaginatedResult, j as AggregateOptions, k as AggregateResult, S as SearchOptions, l as SearchResult } from '../../types-CA784ZtV.js';
2
+ import { M as MetaInput, I as IncludeOptions, F as FilterCondition, f as RelationConfig, N as NestedUpdateInput, g as NestedWriteResult, L as ListFilters, P as PaginatedResult, h as AggregateOptions, i as AggregateResult, S as SearchOptions, j as SearchResult } from '../../types-5BBVU0EY.js';
3
3
  import { Env } from 'hono';
4
- import { C as CreateEndpoint, M as ModelObject, R as ReadEndpoint, U as UpdateEndpoint, D as DeleteEndpoint, L as ListEndpoint, a as RestoreEndpoint, B as BatchCreateEndpoint, b as BatchDeleteEndpoint, c as BatchRestoreEndpoint, d as BatchUpdateEndpoint, e as BatchUpdateItem, A as AggregateEndpoint, f as BatchUpsertEndpoint, g as UpsertEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, V as VersionCompareEndpoint, h as VersionHistoryEndpoint, i as VersionReadEndpoint, j as VersionRollbackEndpoint } from '../../import-D5BPlFB5.js';
5
- import { A as AdapterBundle } from '../../index-BlgcrFpZ.js';
4
+ import { a as CreateEndpoint, M as ModelObject, R as ReadEndpoint, U as UpdateEndpoint, D as DeleteEndpoint, L as ListEndpoint, b as RestoreEndpoint, B as BatchCreateEndpoint, c as BatchDeleteEndpoint, d as BatchRestoreEndpoint, e as BatchUpdateEndpoint, f as BatchUpdateItem, A as AggregateEndpoint, g as BatchUpsertEndpoint, h as UpsertEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, V as VersionCompareEndpoint, i as VersionHistoryEndpoint, j as VersionReadEndpoint, k as VersionRollbackEndpoint } from '../../import-BHD2B1u8.js';
5
+ import { A as AdapterBundle } from '../../index-BNIzQvcO.js';
6
6
  import { z } from 'zod';
7
+ import '../../types-B5wq2iKZ.js';
8
+ import '../../types-BAcN7U0B.js';
7
9
  import '@hono/zod-openapi';
8
- import '../../route-DwSID3du.js';
10
+ import '../../route-BmtmmHSO.js';
9
11
  import 'hono/utils/http-status';
10
- import '../../versioning-BG3T0q1q.js';
12
+ import '../../audit/index.js';
13
+ import '../../registry-PNJjvSvm.js';
14
+ import '../../versioning/index.js';
15
+ import '../../types-BCsipBBX.js';
11
16
 
12
17
  /**
13
18
  * Internal query builder interface used for type-safe method calls.
@@ -188,7 +193,7 @@ declare abstract class DrizzleCreateEndpoint<E extends Env = Env, M extends Meta
188
193
  */
189
194
  protected useTransaction: boolean;
190
195
  /** Current transaction context (set during transaction execution) */
191
- private _tx?;
196
+ protected _tx?: DrizzleDatabase;
192
197
  /**
193
198
  * Gets the database instance to use. Checks in order:
194
199
  * 1. Transaction context (if in transaction)
@@ -246,7 +251,7 @@ declare abstract class DrizzleUpdateEndpoint<E extends Env = Env, M extends Meta
246
251
  */
247
252
  protected useTransaction: boolean;
248
253
  /** Current transaction context (set during transaction execution) */
249
- private _tx?;
254
+ protected _tx?: DrizzleDatabase;
250
255
  /** Gets the database instance from property, transaction, or context */
251
256
  protected getDb(): DrizzleDatabase;
252
257
  protected getTable(): Table;
@@ -286,7 +291,7 @@ declare abstract class DrizzleDeleteEndpoint<E extends Env = Env, M extends Meta
286
291
  */
287
292
  protected useTransaction: boolean;
288
293
  /** Current transaction context (set during transaction execution) */
289
- private _tx?;
294
+ protected _tx?: DrizzleDatabase;
290
295
  /** Gets the database instance from property, transaction, or context */
291
296
  protected getDb(): DrizzleDatabase;
292
297
  protected getTable(): Table;
@@ -352,7 +357,7 @@ declare abstract class DrizzleRestoreEndpoint<E extends Env = Env, M extends Met
352
357
  */
353
358
  protected useTransaction: boolean;
354
359
  /** Current transaction context (set during transaction execution) */
355
- private _tx?;
360
+ protected _tx?: DrizzleDatabase;
356
361
  /** Gets the database instance from property, transaction, or context */
357
362
  protected getDb(): DrizzleDatabase;
358
363
  protected getTable(): Table;
@@ -1,4 +1,4 @@
1
- import {j as j$1,k,l,m,n,o,q as q$1,r,s,t,p,u,v as v$1,w,x,y,z as z$1,A as A$1,I as I$1,J,S as S$1,T}from'../../chunk-SFCD22UI.js';import'../../chunk-WRFHCN2W.js';import'../../chunk-HX7QWSYF.js';import {b}from'../../chunk-K3226EHO.js';import {getTableColumns,eq,inArray,between,isNull,isNotNull,ilike,like,notInArray,lte,lt as lt$1,gte,gt,ne,and,sql,or,desc,asc}from'drizzle-orm';import {z}from'zod';function A(l){return l}function f(l){if(!l.model.table)throw new Error(`Model ${l.model.tableName} does not have a table reference`);return l.model.table}function g(l,e){let r=getTableColumns(l),n=r[e];if(!n)throw new Error(`Column '${e}' not found in table. Available columns: ${Object.keys(r).join(", ")}`);return n}async function Ce(l,e,r,n){if(!n.table)return e;let t=n.table;switch(n.type){case "hasOne":{let o=n.localKey||"id",s=e[o];if(s==null)return e;let a=g(t,n.foreignKey),i=await l.select().from(t).where(eq(a,s)).limit(1);return {...e,[r]:i[0]||null}}case "hasMany":{let o=n.localKey||"id",s=e[o];if(s==null)return {...e,[r]:[]};let a=g(t,n.foreignKey),i=await l.select().from(t).where(eq(a,s));return {...e,[r]:i}}case "belongsTo":{let o=e[n.foreignKey];if(o==null)return {...e,[r]:null};let s=g(t,n.localKey||"id"),a=await l.select().from(t).where(eq(s,o)).limit(1);return {...e,[r]:a[0]||null}}default:return e}}async function Y(l,e,r,n){if(!n?.relations?.length||!r.model.relations)return e;let t={...e};for(let o of n.relations){let s=r.model.relations[o];s&&(t=await Ce(l,t,o,s));}return t}async function v(l,e,r,n){if(!e.length||!n?.relations?.length||!r.model.relations)return e;let t=e.map(o=>({...o}));for(let o of n.relations){let s=r.model.relations[o];if(!s||!s.table)continue;let a=s.table;switch(s.type){case "hasOne":case "hasMany":{let i=s.localKey||"id",u=[...new Set(t.map(b=>b[i]).filter(b=>b!=null))];if(u.length===0){t=t.map(b=>({...b,[o]:s.type==="hasMany"?[]:null}));continue}let d=g(a,s.foreignKey),c=await l.select().from(a).where(inArray(d,u)),p=new Map;for(let b of c){let m=b[s.foreignKey];p.has(m)||p.set(m,[]),p.get(m).push(b);}t=t.map(b=>{let m=b[i],D=p.get(m)||[];return {...b,[o]:s.type==="hasMany"?D:D[0]||null}});break}case "belongsTo":{let i=s.localKey||"id",u=[...new Set(t.map(b=>b[s.foreignKey]).filter(b=>b!=null))];if(u.length===0){t=t.map(b=>({...b,[o]:null}));continue}let d=g(a,i),c=await l.select().from(a).where(inArray(d,u)),p=new Map;for(let b of c){let m=b[i];p.set(m,b);}t=t.map(b=>{let m=b[s.foreignKey];return {...b,[o]:p.get(m)||null}});break}}}return t}function R(l,e){let r=g(l,e.field);switch(e.operator){case "eq":return eq(r,e.value);case "ne":return ne(r,e.value);case "gt":return gt(r,e.value);case "gte":return gte(r,e.value);case "lt":return lt$1(r,e.value);case "lte":return lte(r,e.value);case "in":return inArray(r,e.value);case "nin":return notInArray(r,e.value);case "like":return like(r,e.value);case "ilike":return ilike(r,e.value);case "null":return e.value?isNull(r):isNotNull(r);case "between":{let[n,t]=e.value;return between(r,n,t)}default:return}}var S=class extends j$1{db;useTransaction=false;_tx;getDb(){if(this._tx)return this._tx;if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error(`Database not configured. Either:
1
+ import {k,l,m as m$1,n,o,p,r,s,t,u,q as q$1,v as v$1,w,x,y as y$1,z as z$1,A,B as B$1,J,K,T,U as U$1}from'../../chunk-Q4FF5JVS.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-W4FHI5YI.js';import'../../chunk-HAUN4LQO.js';import'../../chunk-NIWM7GOK.js';import'../../chunk-RFT77JBK.js';import'../../chunk-FC56WWPB.js';import'../../chunk-GBQQ3YQX.js';import'../../chunk-QRXEQTNE.js';import'../../chunk-QXFY6NYI.js';import {b}from'../../chunk-DMGP7QDL.js';import'../../chunk-MDHMZPXK.js';import'../../chunk-VJRDAVID.js';import {getTableColumns,eq,inArray,between,isNull,isNotNull,ilike,like,notInArray,lte,lt as lt$1,gte,gt as gt$1,ne,and,sql,or,desc,asc}from'drizzle-orm';import {z}from'zod';function L(l){return l}function f(l){if(!l.model.table)throw new Error(`Model ${l.model.tableName} does not have a table reference`);return l.model.table}function m(l,e){let o=getTableColumns(l),n=o[e];if(!n)throw new Error(`Column '${e}' not found in table. Available columns: ${Object.keys(o).join(", ")}`);return n}async function Te(l,e,o,n){if(!n.table)return e;let t=n.table;switch(n.type){case "hasOne":{let r=n.localKey||"id",s=e[r];if(s==null)return e;let a=m(t,n.foreignKey),i=await l.select().from(t).where(eq(a,s)).limit(1);return {...e,[o]:i[0]||null}}case "hasMany":{let r=n.localKey||"id",s=e[r];if(s==null)return {...e,[o]:[]};let a=m(t,n.foreignKey),i=await l.select().from(t).where(eq(a,s));return {...e,[o]:i}}case "belongsTo":{let r=e[n.foreignKey];if(r==null)return {...e,[o]:null};let s=m(t,n.localKey||"id"),a=await l.select().from(t).where(eq(s,r)).limit(1);return {...e,[o]:a[0]||null}}default:return e}}async function ee(l,e,o,n){if(!n?.relations?.length||!o.model.relations)return e;let t={...e};for(let r of n.relations){let s=o.model.relations[r];s&&(t=await Te(l,t,r,s));}return t}async function v(l,e,o,n){if(!e.length||!n?.relations?.length||!o.model.relations)return e;let t=e.map(r=>({...r}));for(let r of n.relations){let s=o.model.relations[r];if(!s||!s.table)continue;let a=s.table;switch(s.type){case "hasOne":case "hasMany":{let i=s.localKey||"id",u=[...new Set(t.map(p=>p[i]).filter(p=>p!=null))];if(u.length===0){t=t.map(p=>({...p,[r]:s.type==="hasMany"?[]:null}));continue}let c=m(a,s.foreignKey),d=await l.select().from(a).where(inArray(c,u)),g=new Map;for(let p of d){let b=p[s.foreignKey];g.has(b)||g.set(b,[]),g.get(b).push(p);}t=t.map(p=>{let b=p[i],D=g.get(b)||[];return {...p,[r]:s.type==="hasMany"?D:D[0]||null}});break}case "belongsTo":{let i=s.localKey||"id",u=[...new Set(t.map(p=>p[s.foreignKey]).filter(p=>p!=null))];if(u.length===0){t=t.map(p=>({...p,[r]:null}));continue}let c=m(a,i),d=await l.select().from(a).where(inArray(c,u)),g=new Map;for(let p of d){let b=p[i];g.set(b,p);}t=t.map(p=>{let b=p[s.foreignKey];return {...p,[r]:g.get(b)||null}});break}}}return t}function E(l,e){let o=m(l,e.field);switch(e.operator){case "eq":return eq(o,e.value);case "ne":return ne(o,e.value);case "gt":return gt$1(o,e.value);case "gte":return gte(o,e.value);case "lt":return lt$1(o,e.value);case "lte":return lte(o,e.value);case "in":return inArray(o,e.value);case "nin":return notInArray(o,e.value);case "like":return like(o,e.value);case "ilike":return ilike(o,e.value);case "null":return e.value?isNull(o):isNotNull(o);case "between":{let[n,t]=e.value;return between(o,n,t)}default:return}}function y(l){let e=l;if(e._tx)return e._tx;if(e.db)return e.db;let o=e.context?.get?.("db");if(o)return o;throw new Error(`Database not configured. Either:
2
2
  1. Set db property: db = myDb;
3
3
  2. Use middleware: c.set("db", myDb);
4
- 3. Use factory: createDrizzleCrud(db, meta)`)}getTable(){return f(this._meta)}getRelatedTable(e){return e.table}async create(e,r){let n=r??this.getDb(),t=this.getTable(),o=this._meta.model.primaryKeys[0],s={...e,[o]:e[o]||crypto.randomUUID()};return (await n.insert(t).values(s).returning())[0]}async createNested(e,r,n,t,o){let s=o??this.getDb(),a=this.getRelatedTable(n);if(!a)return b().warn(`Related table not found for ${r}. Add 'table' to the relation config.`),[];let i=Array.isArray(t)?t:[t],u=[];for(let d of i){if(typeof d!="object"||d===null)continue;let c={...d,id:crypto.randomUUID(),[n.foreignKey]:e},p=await s.insert(a).values(c).returning();p[0]&&u.push(p[0]);}return u}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},j=class extends k{db;getDb(){if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}async read(e,r,n){let t=this.getTable(),o=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),a=[eq(o,e)];if(r)for(let[d,c]of Object.entries(r))a.push(eq(this.getColumn(d),c));s.enabled&&a.push(isNull(this.getColumn(s.field)));let i=await this.getDb().select().from(t).where(and(...a)).limit(1);return i[0]?await Y(this.getDb(),i[0],this._meta,n):null}},_=class extends l{db;useTransaction=false;_tx;getDb(){if(this._tx)return this._tx;if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}getRelatedTable(e){return e.table}async findExisting(e,r,n){let t=n??this.getDb(),o=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),i=[eq(s,e)];if(r)for(let[d,c]of Object.entries(r))i.push(eq(this.getColumn(d),c));return a.enabled&&i.push(isNull(this.getColumn(a.field))),(await t.select().from(o).where(and(...i)).limit(1))[0]||null}async update(e,r,n,t){let o=t??this.getDb(),s=this.getTable(),a=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),u=[eq(a,e)];if(n)for(let[c,p]of Object.entries(n))u.push(eq(this.getColumn(c),p));return i.enabled&&u.push(isNull(this.getColumn(i.field))),(await o.update(s).set(r).where(and(...u)).returning())[0]||null}async processNestedWrites(e,r,n,t,o){let s=o??this.getDb(),a=this.getRelatedTable(n);if(!a)return b().warn(`Related table not found for ${r}. Add 'table' to the relation config.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]};let i={created:[],updated:[],deleted:[],connected:[],disconnected:[]},u=g(a,n.foreignKey),d=g(a,"id");if(t.create){let c=Array.isArray(t.create)?t.create:[t.create];for(let p of c){if(typeof p!="object"||p===null)continue;let b={...p,id:crypto.randomUUID(),[n.foreignKey]:e},m=await s.insert(a).values(b).returning();m[0]&&i.created.push(m[0]);}}if(t.update)for(let c of t.update){if(!c.id||!(await s.select().from(a).where(and(eq(d,c.id),eq(u,e))).limit(1))[0])continue;let{id:b,...m}=c,D=await s.update(a).set(m).where(eq(d,b)).returning();D[0]&&i.updated.push(D[0]);}if(t.delete)for(let c of t.delete)(await s.delete(a).where(and(eq(d,c),eq(u,e))).returning())[0]&&i.deleted.push(c);if(t.connect)for(let c of t.connect)(await s.update(a).set({[n.foreignKey]:e}).where(eq(d,c)).returning())[0]&&i.connected.push(c);if(t.disconnect)for(let c of t.disconnect)(await s.update(a).set({[n.foreignKey]:null}).where(and(eq(d,c),eq(u,e))).returning())[0]&&i.disconnected.push(c);return i}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},I=class extends m{db;useTransaction=false;_tx;getDb(){if(this._tx)return this._tx;if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}getRelatedTable(e){return e.table}async findForDelete(e,r,n){let t=n??this.getDb(),o=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),i=[eq(s,e)];if(r)for(let[d,c]of Object.entries(r))i.push(eq(this.getColumn(d),c));return a.enabled&&i.push(isNull(this.getColumn(a.field))),(await t.select().from(o).where(and(...i)).limit(1))[0]||null}async delete(e,r,n){let t=n??this.getDb(),o=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),i=[eq(s,e)];if(r)for(let[u,d]of Object.entries(r))i.push(eq(this.getColumn(u),d));return a.enabled&&i.push(isNull(this.getColumn(a.field))),a.enabled?(await t.update(o).set({[a.field]:new Date}).where(and(...i)).returning())[0]||null:(await t.delete(o).where(and(...i)).returning())[0]||null}async countRelated(e,r,n,t){let o=t??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=g(s,n.foreignKey),i=await o.select({count:sql`count(*)`}).from(s).where(eq(a,e));return Number(i[0]?.count)||0}async deleteRelated(e,r,n,t){let o=t??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=g(s,n.foreignKey);return (await o.delete(s).where(eq(a,e)).returning()).length}async nullifyRelated(e,r,n,t){let o=t??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=g(s,n.foreignKey);return (await o.update(s).set({[n.foreignKey]:null}).where(eq(a,e)).returning()).length}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},P=class extends n{db;getDb(){if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}async list(e){let r=this.getTable(),n=[],t=this.getSoftDeleteConfig();if(t.enabled){let y=this.getColumn(t.field);e.options.onlyDeleted?n.push(isNotNull(y)):e.options.withDeleted||n.push(isNull(y));}for(let y of e.filters){let x=R(r,y);x&&n.push(x);}if(e.options.search&&this.searchFields.length>0){let y=this.searchFields.map(x=>{let G=this.getColumn(x);return sql`LOWER(${G}) LIKE LOWER(${`%${e.options.search}%`})`});n.push(or(...y));}let o=n.length>0?and(...n):void 0,s=this.getDb(),a=await s.select({count:sql`count(*)`}).from(r).where(o),i=Number(a[0]?.count)||0,u=s.select().from(r).where(o);if(e.options.order_by){let y=this.getColumn(e.options.order_by),x=e.options.order_by_direction==="desc"?desc:asc;u=u.orderBy(x(y));}let d=e.options.page||1,c=e.options.per_page||this.defaultPerPage;u=u.limit(c).offset((d-1)*c);let p=await u,b={relations:e.options.include||[]},m=await v(this.getDb(),p,this._meta,b),D=Math.ceil(i/c);return {result:m,result_info:{page:d,per_page:c,total_count:i,total_pages:D,has_next_page:d<D,has_prev_page:d>1}}}},L=class extends o{db;useTransaction=false;_tx;getDb(){if(this._tx)return this._tx;if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}async restore(e,r,n){let t=n??this.getDb(),o=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),i=[eq(s,e)];if(r)for(let[d,c]of Object.entries(r))i.push(eq(this.getColumn(d),c));return i.push(isNotNull(this.getColumn(a.field))),(await t.update(o).set({[a.field]:null}).where(and(...i)).returning())[0]||null}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}};var Z=class extends q$1{db;getDb(){if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}async batchCreate(e){let r=this.getTable(),n=this._meta.model.primaryKeys[0],t=e.map(s=>({...s,[n]:s[n]||crypto.randomUUID()}));return await this.getDb().insert(r).values(t).returning()}},Q=class extends r{db;getDb(){if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}async batchUpdate(e){let r=this.getTable(),n=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),o=[],s=[];for(let a of e){let i=[eq(n,a.id)];t.enabled&&i.push(isNull(this.getColumn(t.field)));let u=await this.getDb().update(r).set(a.data).where(and(...i)).returning();u[0]?o.push(u[0]):s.push(a.id);}return {updated:o,notFound:s}}},N=class extends s{db;getDb(){if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}async batchDelete(e){let r=this.getTable(),n=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),o=[inArray(n,e)];t.enabled&&o.push(isNull(this.getColumn(t.field)));let s;t.enabled?s=await this.getDb().update(r).set({[t.field]:new Date}).where(and(...o)).returning():s=await this.getDb().delete(r).where(and(...o)).returning();let a=s,i=new Set(a.map(d=>String(d[this.lookupField]))),u=e.filter(d=>!i.has(d));return {deleted:a,notFound:u}}},F=class extends t{db;getDb(){if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}async batchRestore(e){let r=this.getTable(),n=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),o=[inArray(n,e),isNotNull(this.getColumn(t.field))],a=await this.getDb().update(r).set({[t.field]:null}).where(and(...o)).returning(),i=new Set(a.map(d=>String(d[this.lookupField]))),u=e.filter(d=>!i.has(d));return {restored:a,notFound:u}}};var $=class extends p{db;getDb(){if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}async findExisting(e){let r=this.getTable(),n=this.getUpsertKeys(),t=this.getSoftDeleteConfig(),o=[];for(let a of n){let i=e[a];i!==void 0&&o.push(eq(this.getColumn(a),i));}return t.enabled&&o.push(isNull(this.getColumn(t.field))),o.length===0?null:(await this.getDb().select().from(r).where(and(...o)).limit(1))[0]||null}async create(e){let r=this.getTable(),n=this._meta.model.primaryKeys[0],t={...e,[n]:e[n]||crypto.randomUUID()};return (await this.getDb().insert(r).values(t).returning())[0]}async update(e,r){let n=this.getTable(),t=this._meta.model.primaryKeys[0],o=e[t];return (await this.getDb().update(n).set(r).where(eq(this.getColumn(t),o)).returning())[0]}async nativeUpsert(e,r){let n=this.getTable(),t=this.getUpsertKeys(),o=this._meta.model.primaryKeys[0],s=this.getSoftDeleteConfig(),a={...e,[o]:e[o]||crypto.randomUUID()},i={};for(let[c,p]of Object.entries(e))!t.includes(c)&&c!==o&&(this.createOnlyFields?.includes(c)||(i[c]=p));let u=t.map(c=>this.getColumn(c)),d;s.enabled&&(d=isNull(this.getColumn(s.field)));try{return {data:(await this.getDb().insert(n).values(a).onConflictDoUpdate({target:u,set:Object.keys(i).length>0?i:{[o]:sql`${this.getColumn(o)}`},where:d}).returning())[0],created:!1}}catch(c){if(c instanceof Error&&c.message.includes("onConflictDoUpdate"))try{return {data:(await this.getDb().insert(n).values(a).onDuplicateKeyUpdate({set:Object.keys(i).length>0?i:{[o]:sql`${this.getColumn(o)}`}}).returning())[0],created:!1}}catch{return this.performStandardUpsert(e,r)}throw c}}},q=class extends u{db;getDb(){if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}async findExisting(e){let r=this.getTable(),n=this.getUpsertKeys(),t=[];for(let s of n){let a=e[s];a!==void 0&&t.push(eq(this.getColumn(s),a));}return t.length===0?null:(await this.getDb().select().from(r).where(and(...t)).limit(1))[0]||null}async create(e){let r=this.getTable(),n=this._meta.model.primaryKeys[0],t={...e,[n]:e[n]||crypto.randomUUID()};return (await this.getDb().insert(r).values(t).returning())[0]}async update(e,r){let n=this.getTable(),t=this._meta.model.primaryKeys[0],o=e[t];return (await this.getDb().update(n).set(r).where(eq(this.getColumn(t),o)).returning())[0]}async nativeBatchUpsert(e,r){if(e.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let n=this.getTable(),t=this.getUpsertKeys(),o=this._meta.model.primaryKeys[0],s=e.map(d=>({...d,[o]:d[o]||crypto.randomUUID()})),a={},i=e[0];for(let d of Object.keys(i))!t.includes(d)&&d!==o&&(this.createOnlyFields?.includes(d)||(a[d]=sql`excluded.${sql.identifier(d)}`));let u=t.map(d=>this.getColumn(d));try{let c=await this.getDb().insert(n).values(s).onConflictDoUpdate({target:u,set:Object.keys(a).length>0?a:{[o]:sql`${this.getColumn(o)}`}}).returning();return {items:c.map((p,b)=>({data:p,created:!1,index:b})),createdCount:0,updatedCount:c.length,totalCount:c.length}}catch(d){if(d instanceof Error&&d.message.includes("onConflictDoUpdate"))try{let p=await this.getDb().insert(n).values(s).onDuplicateKeyUpdate({set:Object.keys(a).length>0?a:{[o]:sql`${this.getColumn(o)}`}}).returning();return {items:p.map((b,m)=>({data:b,created:!1,index:m})),createdCount:0,updatedCount:p.length,totalCount:p.length}}catch{return this.performStandardBatchUpsert(e,r)}throw d}}},Ee=class extends v$1{db;getDb(){if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}async recordExists(e){let r=this.getTable(),n=await this.getDb().select({count:sql`count(*)`}).from(r).where(eq(this.getColumn("id"),e));return Number(n[0]?.count)>0}},ve=class extends w{},ke=class extends x{},Oe=class extends y{db;getDb(){if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}async rollback(e,r,n){let t=this.getTable(),o=this.getVersioningConfig().field;return (await this.getDb().update(t).set({...r,[o]:n}).where(eq(this.getColumn("id"),e)).returning())[0]}},Se=class extends z$1{db;getDb(){if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}async aggregate(e){let r=this.getTable(),n=[],t=this.getSoftDeleteConfig();if(t.enabled){let{query:a}=await this.getValidatedData();a?.withDeleted===true||a?.withDeleted==="true"||n.push(isNull(this.getColumn(t.field)));}if(e.filters)for(let[a,i]of Object.entries(e.filters))if(typeof i=="object"&&i!==null)for(let[u,d]of Object.entries(i)){let c=R(r,{field:a,operator:u,value:d});c&&n.push(c);}else n.push(eq(this.getColumn(a),i));let o=n.length>0?and(...n):void 0,s=await this.getDb().select().from(r).where(o);return A$1(s,e)}},je=class extends I$1{db;getDb(){if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}useNativeSearch=false;vectorColumn;vectorConfig="english";getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}async search(e,r){let n=this.getTable(),t=[],o=this.getSoftDeleteConfig();o.enabled&&(r.options.onlyDeleted?t.push(isNotNull(this.getColumn(o.field))):r.options.withDeleted||t.push(isNull(this.getColumn(o.field))));for(let w of r.filters){let M=R(n,w);M&&t.push(M);}let s=this.getSearchableFields(),a=e.fields||Object.keys(s);if(this.useNativeSearch&&this.vectorColumn){let w=this.getColumn(this.vectorColumn),M=e.mode==="phrase"?sql`phraseto_tsquery(${this.vectorConfig}, ${e.query})`:e.mode==="all"?sql`plainto_tsquery(${this.vectorConfig}, ${e.query})`:sql`to_tsquery(${this.vectorConfig}, ${e.query.split(/\s+/).join(" | ")})`;t.push(sql`${w} @@ ${M}`);}else {let w=a.map(M=>{try{let Ze=this.getColumn(M);return sql`LOWER(CAST(${Ze} AS TEXT)) LIKE LOWER(${`%${e.query}%`})`}catch{return}}).filter(M=>M!==void 0);w.length>0&&(e.mode==="all"?t.push(and(...w)):t.push(or(...w)));}let i=t.length>0?and(...t):void 0,u=await this.getDb().select({count:sql`count(*)`}).from(n).where(i),d=Number(u[0]?.count)||0,c=this.getDb().select().from(n).where(i);if(r.options.order_by){let w=this.getColumn(r.options.order_by),M=r.options.order_by_direction==="desc"?desc:asc;c=c.orderBy(M(w));}let p=r.options.page||1,b=r.options.per_page||this.defaultPerPage;c=c.limit(b).offset((p-1)*b);let m=await c,D=J(m,e,s),y={relations:r.options.include||[]},x=D.map(w=>w.item),G=await v(this.getDb(),x,this._meta,y);return {items:D.map((w,M)=>({...w,item:G[M]})),totalCount:d}}},_e=class extends S$1{db;getDb(){if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}async list(e){let r=this.getTable(),n=[],t=this.getSoftDeleteConfig();if(t.enabled){let D=this.getColumn(t.field);e.options.onlyDeleted?n.push(isNotNull(D)):e.options.withDeleted||n.push(isNull(D));}for(let D of e.filters){let y=R(r,D);y&&n.push(y);}if(e.options.search&&this.searchFields.length>0){let D=this.searchFields.map(y=>{let x=this.getColumn(y);return sql`LOWER(${x}) LIKE LOWER(${`%${e.options.search}%`})`});n.push(or(...D));}let o=n.length>0?and(...n):void 0,s=await this.getDb().select({count:sql`count(*)`}).from(r).where(o),a=Number(s[0]?.count)||0,i=this.getDb().select().from(r).where(o);if(e.options.order_by){let D=this.getColumn(e.options.order_by),y=e.options.order_by_direction==="desc"?desc:asc;i=i.orderBy(y(D));}let u=e.options.page||1,d=e.options.per_page||this.defaultPerPage;i=i.limit(d).offset((u-1)*d);let c=await i,p={relations:e.options.include||[]},b=await v(this.getDb(),c,this._meta,p),m=Math.ceil(a/d);return {result:b,result_info:{page:u,per_page:d,total_count:a,total_pages:m,has_next_page:u<m,has_prev_page:u>1}}}},Ie=class extends T{db;getDb(){if(this.db)return this.db;let e=this.context?.get?.("db");if(e)return e;throw new Error("Database not configured. Set db property or use middleware.")}getTable(){return f(this._meta)}getColumn(e){return g(this.getTable(),e)}async findExisting(e){let r=this.getTable(),n=this.getUpsertKeys(),t=this.getSoftDeleteConfig(),o=[];for(let a of n){let i=e[a];i!==void 0&&o.push(eq(this.getColumn(a),i));}return t.enabled&&o.push(isNull(this.getColumn(t.field))),o.length===0?null:(await this.getDb().select().from(r).where(and(...o)).limit(1))[0]||null}async create(e){let r=this.getTable(),n=this._meta.model.primaryKeys[0],t={...e,[n]:e[n]||crypto.randomUUID()};return (await this.getDb().insert(r).values(t).returning())[0]}async update(e,r){let n=this.getTable(),t=this._meta.model.primaryKeys[0],o=e[t];return (await this.getDb().update(n).set(r).where(eq(this.getColumn(t),o)).returning())[0]}};function qt(l,e){return {Create:class extends S{_meta=e;db=l},Read:class extends j{_meta=e;db=l},Update:class extends _{_meta=e;db=l},Delete:class extends I{_meta=e;db=l},List:class extends P{_meta=e;db=l},Restore:class extends L{_meta=e;db=l},Upsert:class extends ${_meta=e;db=l},BatchCreate:class extends Z{_meta=e;db=l},BatchUpdate:class extends Q{_meta=e;db=l},BatchDelete:class extends N{_meta=e;db=l},BatchRestore:class extends F{_meta=e;db=l},BatchUpsert:class extends q{_meta=e;db=l}}}var Wt={CreateEndpoint:S,ListEndpoint:P,ReadEndpoint:j,UpdateEndpoint:_,DeleteEndpoint:I};var V=null,Le=false,W=null;async function X(){if(Le){if(W)throw W;return V}Le=true;try{return V=await import('drizzle-zod'),V}catch{throw W=new Error("drizzle-zod is not installed. Please install it: npm install drizzle-zod"),W}}async function st(l,e){return (await X()).createSelectSchema(l,e)}async function at(l,e){return (await X()).createInsertSchema(l,e)}async function it(l,e){let r=await X();return r.createUpdateSchema?r.createUpdateSchema(l,e):r.createInsertSchema(l,e).partial()}async function lt(l,e){let r=await X(),n=e?.coerceDates!==false,t=n?bt(l):new Set,o=r.createSelectSchema(l,e?.selectRefine),s=r.createInsertSchema(l,e?.insertRefine),a;return r.createUpdateSchema?a=r.createUpdateSchema(l,e?.updateRefine):a=r.createInsertSchema(l,e?.updateRefine).partial(),n&&t.size>0&&(s=Be(s,t),a=Be(a,t)),{select:o,insert:s,update:a}}function dt(){return V!==null}var ct=z.preprocess(l=>{if(l instanceof Date)return l;if(typeof l=="string"){let e=new Date(l);if(!isNaN(e.getTime()))return e}return l},z.date()),ut=z.preprocess(l=>{if(l==null)return null;if(l instanceof Date)return l;if(typeof l=="string"){let e=new Date(l);if(!isNaN(e.getTime()))return e}return l},z.date().nullable());function bt(l){let e=new Set,r=l;for(let[n,t]of Object.entries(r)){if(n==="_"||n==="$inferInsert"||n==="$inferSelect")continue;let o=t;if(!o||typeof o!="object")continue;let s=String(o.dataType??"").toLowerCase(),a=String(o.columnType??"").toLowerCase(),i=o.config,u=String(i?.dataType??"").toLowerCase();(s.includes("timestamp")||s.includes("date")||s.includes("datetime")||a.includes("pgtimestamp")||a.includes("pgdate")||a.includes("mysqltimestamp")||a.includes("mysqldate")||a.includes("sqlitetimestamp")||u.includes("timestamp")||u.includes("date"))&&e.add(n);}return e}function Be(l,e){if(e.size===0)return l;let r=l.shape,n={};for(let[t,o]of Object.entries(r))if(e.has(t)){let s=o.isOptional?.()??false,a=o.isNullable?.()??false,i=ct;(a||s)&&(i=ut),s&&(i=i.optional()),n[t]=i;}else n[t]=o;return z.object(n)}export{Wt as DrizzleAdapters,Se as DrizzleAggregateEndpoint,Z as DrizzleBatchCreateEndpoint,N as DrizzleBatchDeleteEndpoint,F as DrizzleBatchRestoreEndpoint,Q as DrizzleBatchUpdateEndpoint,q as DrizzleBatchUpsertEndpoint,S as DrizzleCreateEndpoint,I as DrizzleDeleteEndpoint,_e as DrizzleExportEndpoint,Ie as DrizzleImportEndpoint,P as DrizzleListEndpoint,j as DrizzleReadEndpoint,L as DrizzleRestoreEndpoint,je as DrizzleSearchEndpoint,_ as DrizzleUpdateEndpoint,$ as DrizzleUpsertEndpoint,ke as DrizzleVersionCompareEndpoint,Ee as DrizzleVersionHistoryEndpoint,ve as DrizzleVersionReadEndpoint,Oe as DrizzleVersionRollbackEndpoint,v as batchLoadDrizzleRelations,R as buildWhereCondition,A as cast,qt as createDrizzleCrud,lt as createDrizzleSchemas,at as createInsertSchema,st as createSelectSchema,it as createUpdateSchema,g as getColumn,f as getTable,dt as isDrizzleZodAvailable,Ce as loadDrizzleRelation,Y as loadDrizzleRelations};
4
+ 3. Use factory: createDrizzleCrud(db, meta)`)}var S=class extends k{db;useTransaction=false;_tx;getDb(){return y(this)}getTable(){return f(this._meta)}getRelatedTable(e){return e.table}async create(e,o){let n=o??this.getDb(),t=this.getTable(),r=this._meta.model.primaryKeys[0],s={...e,[r]:e[r]||crypto.randomUUID()};return (await n.insert(t).values(s).returning())[0]}async createNested(e,o,n,t,r){let s=r??this.getDb(),a=this.getRelatedTable(n);if(!a)return b().warn(`Related table not found for ${o}. Add 'table' to the relation config.`),[];let i=Array.isArray(t)?t:[t],u=[];for(let c of i){if(typeof c!="object"||c===null)continue;let d={...c,id:crypto.randomUUID(),[n.foreignKey]:e},g=await s.insert(a).values(d).returning();g[0]&&u.push(g[0]);}return u}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},_=class extends l{db;getDb(){return y(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async read(e,o,n){let t=this.getTable(),r=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),a=[eq(r,e)];if(o)for(let[c,d]of Object.entries(o))a.push(eq(this.getColumn(c),d));s.enabled&&a.push(isNull(this.getColumn(s.field)));let i=await this.getDb().select().from(t).where(and(...a)).limit(1);return i[0]?await ee(this.getDb(),i[0],this._meta,n):null}},I=class extends m$1{db;useTransaction=false;_tx;getDb(){return y(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}getRelatedTable(e){return e.table}async findExisting(e,o,n){let t=n??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),i=[eq(s,e)];if(o)for(let[c,d]of Object.entries(o))i.push(eq(this.getColumn(c),d));return a.enabled&&i.push(isNull(this.getColumn(a.field))),(await t.select().from(r).where(and(...i)).limit(1))[0]||null}async update(e,o,n,t){let r=t??this.getDb(),s=this.getTable(),a=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),u=[eq(a,e)];if(n)for(let[d,g]of Object.entries(n))u.push(eq(this.getColumn(d),g));return i.enabled&&u.push(isNull(this.getColumn(i.field))),(await r.update(s).set(o).where(and(...u)).returning())[0]||null}async processNestedWrites(e,o,n,t,r){let s=r??this.getDb(),a=this.getRelatedTable(n);if(!a)return b().warn(`Related table not found for ${o}. Add 'table' to the relation config.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]};let i={created:[],updated:[],deleted:[],connected:[],disconnected:[]},u=m(a,n.foreignKey),c=m(a,"id");if(t.create){let d=Array.isArray(t.create)?t.create:[t.create];for(let g of d){if(typeof g!="object"||g===null)continue;let p={...g,id:crypto.randomUUID(),[n.foreignKey]:e},b=await s.insert(a).values(p).returning();b[0]&&i.created.push(b[0]);}}if(t.update)for(let d of t.update){if(!d.id||!(await s.select().from(a).where(and(eq(c,d.id),eq(u,e))).limit(1))[0])continue;let{id:p,...b}=d,D=await s.update(a).set(b).where(eq(c,p)).returning();D[0]&&i.updated.push(D[0]);}if(t.delete)for(let d of t.delete)(await s.delete(a).where(and(eq(c,d),eq(u,e))).returning())[0]&&i.deleted.push(d);if(t.connect)for(let d of t.connect)(await s.update(a).set({[n.foreignKey]:e}).where(eq(c,d)).returning())[0]&&i.connected.push(d);if(t.disconnect)for(let d of t.disconnect)(await s.update(a).set({[n.foreignKey]:null}).where(and(eq(c,d),eq(u,e))).returning())[0]&&i.disconnected.push(d);return i}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},P=class extends n{db;useTransaction=false;_tx;getDb(){return y(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}getRelatedTable(e){return e.table}async findForDelete(e,o,n){let t=n??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),i=[eq(s,e)];if(o)for(let[c,d]of Object.entries(o))i.push(eq(this.getColumn(c),d));return a.enabled&&i.push(isNull(this.getColumn(a.field))),(await t.select().from(r).where(and(...i)).limit(1))[0]||null}async delete(e,o,n){let t=n??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),i=[eq(s,e)];if(o)for(let[u,c]of Object.entries(o))i.push(eq(this.getColumn(u),c));return a.enabled&&i.push(isNull(this.getColumn(a.field))),a.enabled?(await t.update(r).set({[a.field]:new Date}).where(and(...i)).returning())[0]||null:(await t.delete(r).where(and(...i)).returning())[0]||null}async countRelated(e,o,n,t){let r=t??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=m(s,n.foreignKey),i=await r.select({count:sql`count(*)`}).from(s).where(eq(a,e));return Number(i[0]?.count)||0}async deleteRelated(e,o,n,t){let r=t??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=m(s,n.foreignKey);return (await r.delete(s).where(eq(a,e)).returning()).length}async nullifyRelated(e,o,n,t){let r=t??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=m(s,n.foreignKey);return (await r.update(s).set({[n.foreignKey]:null}).where(eq(a,e)).returning()).length}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},U=class extends o{db;getDb(){return y(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async list(e){let o=this.getTable(),n=[],t=this.getSoftDeleteConfig();if(t.enabled){let z=this.getColumn(t.field);e.options.onlyDeleted?n.push(isNotNull(z)):e.options.withDeleted||n.push(isNull(z));}for(let z of e.filters){let R=E(o,z);R&&n.push(R);}if(e.options.search&&this.searchFields.length>0){let z=this.searchFields.map(R=>{let H=this.getColumn(R);return sql`LOWER(${H}) LIKE LOWER(${`%${e.options.search}%`})`});n.push(or(...z));}let r=n.length>0?and(...n):void 0,s=this.getDb(),a=await s.select({count:sql`count(*)`}).from(o).where(r),i=Number(a[0]?.count)||0,u=s.select().from(o).where(r);if(e.options.order_by){let z=this.getColumn(e.options.order_by),R=e.options.order_by_direction==="desc"?desc:asc;u=u.orderBy(R(z));}let c=e.options.page||1,d=e.options.per_page||this.defaultPerPage;u=u.limit(d).offset((c-1)*d);let g=await u,p={relations:e.options.include||[]},b=await v(this.getDb(),g,this._meta,p),D=Math.ceil(i/d);return {result:b,result_info:{page:c,per_page:d,total_count:i,total_pages:D,has_next_page:c<D,has_prev_page:c>1}}}},B=class extends p{db;useTransaction=false;_tx;getDb(){return y(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async restore(e,o,n){let t=n??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),i=[eq(s,e)];if(o)for(let[c,d]of Object.entries(o))i.push(eq(this.getColumn(c),d));return i.push(isNotNull(this.getColumn(a.field))),(await t.update(r).set({[a.field]:null}).where(and(...i)).returning())[0]||null}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}};var Q=class extends r{db;getDb(){return y(this)}getTable(){return f(this._meta)}async batchCreate(e){let o=this.getTable(),n=this._meta.model.primaryKeys[0],t=e.map(s=>({...s,[n]:s[n]||crypto.randomUUID()}));return await this.getDb().insert(o).values(t).returning()}},N=class extends s{db;getDb(){return y(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async batchUpdate(e){let o=this.getTable(),n=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),r=[],s=[];for(let a of e){let i=[eq(n,a.id)];t.enabled&&i.push(isNull(this.getColumn(t.field)));let u=await this.getDb().update(o).set(a.data).where(and(...i)).returning();u[0]?r.push(u[0]):s.push(a.id);}return {updated:r,notFound:s}}},F=class extends t{db;getDb(){return y(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async batchDelete(e){let o=this.getTable(),n=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),r=[inArray(n,e)];t.enabled&&r.push(isNull(this.getColumn(t.field)));let s;t.enabled?s=await this.getDb().update(o).set({[t.field]:new Date}).where(and(...r)).returning():s=await this.getDb().delete(o).where(and(...r)).returning();let a=s,i=new Set(a.map(c=>String(c[this.lookupField]))),u=e.filter(c=>!i.has(c));return {deleted:a,notFound:u}}},$=class extends u{db;getDb(){return y(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async batchRestore(e){let o=this.getTable(),n=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),r=[inArray(n,e),isNotNull(this.getColumn(t.field))],a=await this.getDb().update(o).set({[t.field]:null}).where(and(...r)).returning(),i=new Set(a.map(c=>String(c[this.lookupField]))),u=e.filter(c=>!i.has(c));return {restored:a,notFound:u}}};var q=class extends q$1{db;getDb(){return y(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async findExisting(e){let o=this.getTable(),n=this.getUpsertKeys(),t=this.getSoftDeleteConfig(),r=[];for(let a of n){let i=e[a];i!==void 0&&r.push(eq(this.getColumn(a),i));}return t.enabled&&r.push(isNull(this.getColumn(t.field))),r.length===0?null:(await this.getDb().select().from(o).where(and(...r)).limit(1))[0]||null}async create(e){let o=this.getTable(),n=this._meta.model.primaryKeys[0],t={...e,[n]:e[n]||crypto.randomUUID()};return (await this.getDb().insert(o).values(t).returning())[0]}async update(e,o){let n=this.getTable(),t=this._meta.model.primaryKeys[0],r=e[t];return (await this.getDb().update(n).set(o).where(eq(this.getColumn(t),r)).returning())[0]}async nativeUpsert(e,o){let n=this.getTable(),t=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=this.getSoftDeleteConfig(),a={...e,[r]:e[r]||crypto.randomUUID()},i={};for(let[d,g]of Object.entries(e))!t.includes(d)&&d!==r&&(this.createOnlyFields?.includes(d)||(i[d]=g));let u=t.map(d=>this.getColumn(d)),c;s.enabled&&(c=isNull(this.getColumn(s.field)));try{return {data:(await this.getDb().insert(n).values(a).onConflictDoUpdate({target:u,set:Object.keys(i).length>0?i:{[r]:sql`${this.getColumn(r)}`},where:c}).returning())[0],created:!1}}catch(d){if(d instanceof Error&&d.message.includes("onConflictDoUpdate"))try{return {data:(await this.getDb().insert(n).values(a).onDuplicateKeyUpdate({set:Object.keys(i).length>0?i:{[r]:sql`${this.getColumn(r)}`}}).returning())[0],created:!1}}catch{return this.performStandardUpsert(e,o)}throw d}}},W=class extends v$1{db;getDb(){return y(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async findExisting(e){let o=this.getTable(),n=this.getUpsertKeys(),t=[];for(let s of n){let a=e[s];a!==void 0&&t.push(eq(this.getColumn(s),a));}return t.length===0?null:(await this.getDb().select().from(o).where(and(...t)).limit(1))[0]||null}async create(e){let o=this.getTable(),n=this._meta.model.primaryKeys[0],t={...e,[n]:e[n]||crypto.randomUUID()};return (await this.getDb().insert(o).values(t).returning())[0]}async update(e,o){let n=this.getTable(),t=this._meta.model.primaryKeys[0],r=e[t];return (await this.getDb().update(n).set(o).where(eq(this.getColumn(t),r)).returning())[0]}async nativeBatchUpsert(e,o){if(e.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let n=this.getTable(),t=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=e.map(c=>({...c,[r]:c[r]||crypto.randomUUID()})),a={},i=e[0];for(let c of Object.keys(i))!t.includes(c)&&c!==r&&(this.createOnlyFields?.includes(c)||(a[c]=sql`excluded.${sql.identifier(c)}`));let u=t.map(c=>this.getColumn(c));try{let d=await this.getDb().insert(n).values(s).onConflictDoUpdate({target:u,set:Object.keys(a).length>0?a:{[r]:sql`${this.getColumn(r)}`}}).returning();return {items:d.map((g,p)=>({data:g,created:!1,index:p})),createdCount:0,updatedCount:d.length,totalCount:d.length}}catch(c){if(c instanceof Error&&c.message.includes("onConflictDoUpdate"))try{let g=await this.getDb().insert(n).values(s).onDuplicateKeyUpdate({set:Object.keys(a).length>0?a:{[r]:sql`${this.getColumn(r)}`}}).returning();return {items:g.map((p,b)=>({data:p,created:!1,index:b})),createdCount:0,updatedCount:g.length,totalCount:g.length}}catch{return this.performStandardBatchUpsert(e,o)}throw c}}},ke=class extends w{db;getDb(){return y(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async recordExists(e){let o=this.getTable(),n=await this.getDb().select({count:sql`count(*)`}).from(o).where(eq(this.getColumn("id"),e));return Number(n[0]?.count)>0}},ve=class extends x{},Oe=class extends y$1{},je=class extends z$1{db;getDb(){return y(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async rollback(e,o,n){let t=this.getTable(),r=this.getVersioningConfig().field;return (await this.getDb().update(t).set({...o,[r]:n}).where(eq(this.getColumn("id"),e)).returning())[0]}},Se=class extends A{db;getDb(){return y(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async aggregate(e){let o=this.getTable(),n=[],t=this.getSoftDeleteConfig();if(t.enabled){let{query:a}=await this.getValidatedData();a?.withDeleted===true||a?.withDeleted==="true"||n.push(isNull(this.getColumn(t.field)));}if(e.filters)for(let[a,i]of Object.entries(e.filters))if(typeof i=="object"&&i!==null)for(let[u,c]of Object.entries(i)){let d=E(o,{field:a,operator:u,value:c});d&&n.push(d);}else n.push(eq(this.getColumn(a),i));let r=n.length>0?and(...n):void 0,s=await this.getDb().select().from(o).where(r);return B$1(s,e)}},_e=class extends J{db;getDb(){return y(this)}useNativeSearch=false;vectorColumn;vectorConfig="english";getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async search(e,o){let n=this.getTable(),t=[],r=this.getSoftDeleteConfig();r.enabled&&(o.options.onlyDeleted?t.push(isNotNull(this.getColumn(r.field))):o.options.withDeleted||t.push(isNull(this.getColumn(r.field))));for(let w of o.filters){let C=E(n,w);C&&t.push(C);}let s=this.getSearchableFields(),a=e.fields||Object.keys(s);if(this.useNativeSearch&&this.vectorColumn){let w=this.getColumn(this.vectorColumn),C=e.mode==="phrase"?sql`phraseto_tsquery(${this.vectorConfig}, ${e.query})`:e.mode==="all"?sql`plainto_tsquery(${this.vectorConfig}, ${e.query})`:sql`to_tsquery(${this.vectorConfig}, ${e.query.split(/\s+/).join(" | ")})`;t.push(sql`${w} @@ ${C}`);}else {let w=a.map(C=>{try{let Qe=this.getColumn(C);return sql`LOWER(CAST(${Qe} AS TEXT)) LIKE LOWER(${`%${e.query}%`})`}catch{return}}).filter(C=>C!==void 0);w.length>0&&(e.mode==="all"?t.push(and(...w)):t.push(or(...w)));}let i=t.length>0?and(...t):void 0,u=await this.getDb().select({count:sql`count(*)`}).from(n).where(i),c=Number(u[0]?.count)||0,d=this.getDb().select().from(n).where(i);if(o.options.order_by){let w=this.getColumn(o.options.order_by),C=o.options.order_by_direction==="desc"?desc:asc;d=d.orderBy(C(w));}let g=o.options.page||1,p=o.options.per_page||this.defaultPerPage;d=d.limit(p).offset((g-1)*p);let b=await d,D=K(b,e,s),z={relations:o.options.include||[]},R=D.map(w=>w.item),H=await v(this.getDb(),R,this._meta,z);return {items:D.map((w,C)=>({...w,item:H[C]})),totalCount:c}}},Ie=class extends T{db;getDb(){return y(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async list(e){let o=this.getTable(),n=[],t=this.getSoftDeleteConfig();if(t.enabled){let D=this.getColumn(t.field);e.options.onlyDeleted?n.push(isNotNull(D)):e.options.withDeleted||n.push(isNull(D));}for(let D of e.filters){let z=E(o,D);z&&n.push(z);}if(e.options.search&&this.searchFields.length>0){let D=this.searchFields.map(z=>{let R=this.getColumn(z);return sql`LOWER(${R}) LIKE LOWER(${`%${e.options.search}%`})`});n.push(or(...D));}let r=n.length>0?and(...n):void 0,s=await this.getDb().select({count:sql`count(*)`}).from(o).where(r),a=Number(s[0]?.count)||0,i=this.getDb().select().from(o).where(r);if(e.options.order_by){let D=this.getColumn(e.options.order_by),z=e.options.order_by_direction==="desc"?desc:asc;i=i.orderBy(z(D));}let u=e.options.page||1,c=e.options.per_page||this.defaultPerPage;i=i.limit(c).offset((u-1)*c);let d=await i,g={relations:e.options.include||[]},p=await v(this.getDb(),d,this._meta,g),b=Math.ceil(a/c);return {result:p,result_info:{page:u,per_page:c,total_count:a,total_pages:b,has_next_page:u<b,has_prev_page:u>1}}}},Pe=class extends U$1{db;getDb(){return y(this)}getTable(){return f(this._meta)}getColumn(e){return m(this.getTable(),e)}async findExisting(e){let o=this.getTable(),n=this.getUpsertKeys(),t=this.getSoftDeleteConfig(),r=[];for(let a of n){let i=e[a];i!==void 0&&r.push(eq(this.getColumn(a),i));}return t.enabled&&r.push(isNull(this.getColumn(t.field))),r.length===0?null:(await this.getDb().select().from(o).where(and(...r)).limit(1))[0]||null}async create(e){let o=this.getTable(),n=this._meta.model.primaryKeys[0],t={...e,[n]:e[n]||crypto.randomUUID()};return (await this.getDb().insert(o).values(t).returning())[0]}async update(e,o){let n=this.getTable(),t=this._meta.model.primaryKeys[0],r=e[t];return (await this.getDb().update(n).set(o).where(eq(this.getColumn(t),r)).returning())[0]}};function Ht(l,e){return {Create:class extends S{_meta=e;db=l},Read:class extends _{_meta=e;db=l},Update:class extends I{_meta=e;db=l},Delete:class extends P{_meta=e;db=l},List:class extends U{_meta=e;db=l},Restore:class extends B{_meta=e;db=l},Upsert:class extends q{_meta=e;db=l},BatchCreate:class extends Q{_meta=e;db=l},BatchUpdate:class extends N{_meta=e;db=l},BatchDelete:class extends F{_meta=e;db=l},BatchRestore:class extends ${_meta=e;db=l},BatchUpsert:class extends W{_meta=e;db=l}}}var Jt={CreateEndpoint:S,ListEndpoint:U,ReadEndpoint:_,UpdateEndpoint:I,DeleteEndpoint:P};var X=null,Be=false,V=null;async function G(){if(Be){if(V)throw V;return X}Be=true;try{return X=await import('drizzle-zod'),X}catch{throw V=new Error("drizzle-zod is not installed. Please install it: npm install drizzle-zod"),V}}async function at(l,e){return (await G()).createSelectSchema(l,e)}async function it(l,e){return (await G()).createInsertSchema(l,e)}async function lt(l,e){let o=await G();return o.createUpdateSchema?o.createUpdateSchema(l,e):o.createInsertSchema(l,e).partial()}async function ct(l,e){let o=await G(),n=e?.coerceDates!==false,t=n?gt(l):new Set,r=o.createSelectSchema(l,e?.selectRefine),s=o.createInsertSchema(l,e?.insertRefine),a;return o.createUpdateSchema?a=o.createUpdateSchema(l,e?.updateRefine):a=o.createInsertSchema(l,e?.updateRefine).partial(),n&&t.size>0&&(s=Ze(s,t),a=Ze(a,t)),{select:r,insert:s,update:a}}function dt(){return X!==null}var ut=z.preprocess(l=>{if(l instanceof Date)return l;if(typeof l=="string"){let e=new Date(l);if(!isNaN(e.getTime()))return e}return l},z.date()),pt=z.preprocess(l=>{if(l==null)return null;if(l instanceof Date)return l;if(typeof l=="string"){let e=new Date(l);if(!isNaN(e.getTime()))return e}return l},z.date().nullable());function gt(l){let e=new Set,o=l;for(let[n,t]of Object.entries(o)){if(n==="_"||n==="$inferInsert"||n==="$inferSelect")continue;let r=t;if(!r||typeof r!="object")continue;let s=String(r.dataType??"").toLowerCase(),a=String(r.columnType??"").toLowerCase(),i=r.config,u=String(i?.dataType??"").toLowerCase();(s.includes("timestamp")||s.includes("date")||s.includes("datetime")||a.includes("pgtimestamp")||a.includes("pgdate")||a.includes("mysqltimestamp")||a.includes("mysqldate")||a.includes("sqlitetimestamp")||u.includes("timestamp")||u.includes("date"))&&e.add(n);}return e}function Ze(l,e){if(e.size===0)return l;let o=l.shape,n={};for(let[t,r]of Object.entries(o))if(e.has(t)){let s=r.isOptional?.()??false,a=r.isNullable?.()??false,i=ut;(a||s)&&(i=pt),s&&(i=i.optional()),n[t]=i;}else n[t]=r;return z.object(n)}export{Jt as DrizzleAdapters,Se as DrizzleAggregateEndpoint,Q as DrizzleBatchCreateEndpoint,F as DrizzleBatchDeleteEndpoint,$ as DrizzleBatchRestoreEndpoint,N as DrizzleBatchUpdateEndpoint,W as DrizzleBatchUpsertEndpoint,S as DrizzleCreateEndpoint,P as DrizzleDeleteEndpoint,Ie as DrizzleExportEndpoint,Pe as DrizzleImportEndpoint,U as DrizzleListEndpoint,_ as DrizzleReadEndpoint,B as DrizzleRestoreEndpoint,_e as DrizzleSearchEndpoint,I as DrizzleUpdateEndpoint,q as DrizzleUpsertEndpoint,Oe as DrizzleVersionCompareEndpoint,ke as DrizzleVersionHistoryEndpoint,ve as DrizzleVersionReadEndpoint,je as DrizzleVersionRollbackEndpoint,v as batchLoadDrizzleRelations,E as buildWhereCondition,L as cast,Ht as createDrizzleCrud,ct as createDrizzleSchemas,it as createInsertSchema,at as createSelectSchema,lt as createUpdateSchema,m as getColumn,f as getTable,dt as isDrizzleZodAvailable,Te as loadDrizzleRelation,ee as loadDrizzleRelations};
@@ -1,12 +1,17 @@
1
1
  import { Env } from 'hono';
2
- import { C as CreateEndpoint, M as ModelObject, D as DeleteEndpoint, L as ListEndpoint, R as ReadEndpoint, a as RestoreEndpoint, U as UpdateEndpoint, B as BatchCreateEndpoint, b as BatchDeleteEndpoint, c as BatchRestoreEndpoint, d as BatchUpdateEndpoint, e as BatchUpdateItem, f as BatchUpsertEndpoint, A as AggregateEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, g as UpsertEndpoint, V as VersionCompareEndpoint, h as VersionHistoryEndpoint, i as VersionReadEndpoint, j as VersionRollbackEndpoint } from '../../import-D5BPlFB5.js';
3
- import { M as MetaInput, g as RelationConfig, L as ListFilters, P as PaginatedResult, I as IncludeOptions, h as NestedUpdateInput, i as NestedWriteResult, j as AggregateOptions, k as AggregateResult, S as SearchOptions, l as SearchResult } from '../../types-CA784ZtV.js';
4
- import { B as BulkPatchEndpoint, C as CloneEndpoint } from '../../bulk-patch-D-Snxx42.js';
2
+ import { a as CreateEndpoint, M as ModelObject, D as DeleteEndpoint, L as ListEndpoint, R as ReadEndpoint, b as RestoreEndpoint, U as UpdateEndpoint, B as BatchCreateEndpoint, c as BatchDeleteEndpoint, d as BatchRestoreEndpoint, e as BatchUpdateEndpoint, f as BatchUpdateItem, g as BatchUpsertEndpoint, A as AggregateEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, h as UpsertEndpoint, V as VersionCompareEndpoint, i as VersionHistoryEndpoint, j as VersionReadEndpoint, k as VersionRollbackEndpoint } from '../../import-BHD2B1u8.js';
3
+ import { M as MetaInput, f as RelationConfig, L as ListFilters, P as PaginatedResult, I as IncludeOptions, N as NestedUpdateInput, g as NestedWriteResult, h as AggregateOptions, i as AggregateResult, S as SearchOptions, j as SearchResult } from '../../types-5BBVU0EY.js';
4
+ import { B as BulkPatchEndpoint, C as CloneEndpoint } from '../../bulk-patch-CoEduhTf.js';
5
5
  import 'zod';
6
- import '../../route-DwSID3du.js';
6
+ import '../../route-BmtmmHSO.js';
7
7
  import 'hono/utils/http-status';
8
- import '../../versioning-BG3T0q1q.js';
8
+ import '../../audit/index.js';
9
+ import '../../registry-PNJjvSvm.js';
10
+ import '../../types-B5wq2iKZ.js';
11
+ import '../../types-BAcN7U0B.js';
9
12
  import '@hono/zod-openapi';
13
+ import '../../versioning/index.js';
14
+ import '../../types-BCsipBBX.js';
10
15
 
11
16
  /**
12
17
  * Module-level in-memory storage.
@@ -1 +1 @@
1
- export{x as MemoryAggregateEndpoint,m as MemoryBatchCreateEndpoint,o as MemoryBatchDeleteEndpoint,p as MemoryBatchRestoreEndpoint,n as MemoryBatchUpdateEndpoint,q as MemoryBatchUpsertEndpoint,B as MemoryBulkPatchEndpoint,r as MemoryCloneEndpoint,g as MemoryCreateEndpoint,j as MemoryDeleteEndpoint,z as MemoryExportEndpoint,A as MemoryImportEndpoint,k as MemoryListEndpoint,h as MemoryReadEndpoint,l as MemoryRestoreEndpoint,y as MemorySearchEndpoint,i as MemoryUpdateEndpoint,s as MemoryUpsertEndpoint,v as MemoryVersionCompareEndpoint,t as MemoryVersionHistoryEndpoint,u as MemoryVersionReadEndpoint,w as MemoryVersionRollbackEndpoint,e as clearStorage,f as getStorage,d as getStore,c as storage}from'../../chunk-LE4MKODL.js';import'../../chunk-SFCD22UI.js';import'../../chunk-WRFHCN2W.js';import'../../chunk-HX7QWSYF.js';import'../../chunk-K3226EHO.js';
1
+ export{x as MemoryAggregateEndpoint,m as MemoryBatchCreateEndpoint,o as MemoryBatchDeleteEndpoint,p as MemoryBatchRestoreEndpoint,n as MemoryBatchUpdateEndpoint,q as MemoryBatchUpsertEndpoint,B as MemoryBulkPatchEndpoint,r as MemoryCloneEndpoint,g as MemoryCreateEndpoint,j as MemoryDeleteEndpoint,z as MemoryExportEndpoint,A as MemoryImportEndpoint,k as MemoryListEndpoint,h as MemoryReadEndpoint,l as MemoryRestoreEndpoint,y as MemorySearchEndpoint,i as MemoryUpdateEndpoint,s as MemoryUpsertEndpoint,v as MemoryVersionCompareEndpoint,t as MemoryVersionHistoryEndpoint,u as MemoryVersionReadEndpoint,w as MemoryVersionRollbackEndpoint,e as clearStorage,f as getStorage,d as getStore,c as storage}from'../../chunk-Q2D5AUPJ.js';import'../../chunk-Q4FF5JVS.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-W4FHI5YI.js';import'../../chunk-HAUN4LQO.js';import'../../chunk-NIWM7GOK.js';import'../../chunk-RFT77JBK.js';import'../../chunk-FC56WWPB.js';import'../../chunk-GBQQ3YQX.js';import'../../chunk-QRXEQTNE.js';import'../../chunk-QXFY6NYI.js';import'../../chunk-DMGP7QDL.js';import'../../chunk-MDHMZPXK.js';import'../../chunk-VJRDAVID.js';
@@ -1,11 +1,16 @@
1
1
  import { Env } from 'hono';
2
- import { C as CreateEndpoint, M as ModelObject, D as DeleteEndpoint, L as ListEndpoint, R as ReadEndpoint, U as UpdateEndpoint, B as BatchCreateEndpoint, b as BatchDeleteEndpoint, c as BatchRestoreEndpoint, d as BatchUpdateEndpoint, e as BatchUpdateItem, f as BatchUpsertEndpoint, a as RestoreEndpoint, A as AggregateEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, g as UpsertEndpoint, V as VersionCompareEndpoint, h as VersionHistoryEndpoint, i as VersionReadEndpoint, j as VersionRollbackEndpoint } from '../../import-D5BPlFB5.js';
3
- import { M as MetaInput, L as ListFilters, P as PaginatedResult, I as IncludeOptions, j as AggregateOptions, k as AggregateResult, m as AggregateField, S as SearchOptions, l as SearchResult } from '../../types-CA784ZtV.js';
2
+ import { a as CreateEndpoint, M as ModelObject, D as DeleteEndpoint, L as ListEndpoint, R as ReadEndpoint, U as UpdateEndpoint, B as BatchCreateEndpoint, c as BatchDeleteEndpoint, d as BatchRestoreEndpoint, e as BatchUpdateEndpoint, f as BatchUpdateItem, g as BatchUpsertEndpoint, b as RestoreEndpoint, A as AggregateEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, h as UpsertEndpoint, V as VersionCompareEndpoint, i as VersionHistoryEndpoint, j as VersionReadEndpoint, k as VersionRollbackEndpoint } from '../../import-BHD2B1u8.js';
3
+ import { M as MetaInput, L as ListFilters, P as PaginatedResult, I as IncludeOptions, h as AggregateOptions, i as AggregateResult, k as AggregateField, S as SearchOptions, j as SearchResult } from '../../types-5BBVU0EY.js';
4
4
  import 'zod';
5
- import '../../route-DwSID3du.js';
5
+ import '../../route-BmtmmHSO.js';
6
6
  import 'hono/utils/http-status';
7
- import '../../versioning-BG3T0q1q.js';
7
+ import '../../audit/index.js';
8
+ import '../../registry-PNJjvSvm.js';
9
+ import '../../types-B5wq2iKZ.js';
10
+ import '../../types-BAcN7U0B.js';
8
11
  import '@hono/zod-openapi';
12
+ import '../../versioning/index.js';
13
+ import '../../types-BCsipBBX.js';
9
14
 
10
15
  /**
11
16
  * Prisma adapter helpers: types, model resolution, relation loading, query utils.
@@ -1 +1 @@
1
- import {j as j$1,k as k$1,l,m,n,o,q,r,s,t,u,I,J as J$1,S,T,p,v as v$1,w,x,y as y$1,z,A}from'../../chunk-SFCD22UI.js';import'../../chunk-WRFHCN2W.js';import'../../chunk-HX7QWSYF.js';import'../../chunk-K3226EHO.js';var _,j;async function Oe(){if(!_)try{_=(await import('pluralize')).default;}catch{throw new Error('The "pluralize" package is required by the Prisma adapter. Install it with: npm install pluralize')}return _}async function Re(){if(!j)try{j=(await import('fastest-levenshtein')).distance;}catch{throw new Error('The "fastest-levenshtein" package is required by the Prisma adapter. Install it with: npm install fastest-levenshtein')}return j}async function J(i){return (await Oe()).singular(i)}async function Z(i,t){return (await Re())(i,t)}function k(i){if(typeof i=="string"){if(/^-?\d+$/.test(i))return parseInt(i,10);if(/^-?\d+\.\d+$/.test(i))return parseFloat(i);if(i==="true")return true;if(i==="false")return false}return i}function E(i){let t={};for(let e of i){let o=k(e.value);switch(e.operator){case "eq":t[e.field]=o;break;case "ne":t[e.field]={not:o};break;case "gt":t[e.field]={gt:o};break;case "gte":t[e.field]={gte:o};break;case "lt":t[e.field]={lt:o};break;case "lte":t[e.field]={lte:o};break;case "in":{let n=Array.isArray(e.value)?e.value:[e.value];t[e.field]={in:n.map(k)};break}case "nin":{let n=Array.isArray(e.value)?e.value:[e.value];t[e.field]={notIn:n.map(k)};break}case "like":t[e.field]={contains:String(e.value).replace(/%/g,"")};break;case "ilike":t[e.field]={contains:String(e.value).replace(/%/g,""),mode:"insensitive"};break;case "null":t[e.field]=e.value?null:{not:null};break;case "between":{let[n,r]=e.value;t[e.field]={gte:k(n),lte:k(r)};break}}}return t}var ve=500,y=new Map;function ee(i,t){if(y.size>=ve){let e=y.keys().next().value;e!==void 0&&y.delete(e);}y.set(i,t);}var C=new Map;function te(i,t){C.set(i.toLowerCase(),t),y.delete(i);}function _e(i){for(let[t,e]of Object.entries(i))te(t,e);}function je(){C.clear(),y.clear();}async function h(i){let t=y.get(i);if(t)return t;let e=C.get(i.toLowerCase());if(e)return ee(i,e),e;let o=i.replace(/[-_](.)/g,(n,r)=>r.toUpperCase()).replace(/^./,n=>n.toLowerCase());return o=await J(o),ee(i,o),o}function Ee(i){let t=[];for(let e of Object.keys(i)){if(e.startsWith("$")||e.startsWith("_"))continue;let o=i[e];o&&typeof o=="object"&&"create"in o&&t.push(e);}return t}async function Ce(i,t,e=3){if(t.length===0)return [];let o=i.toLowerCase();return (await Promise.all(t.map(async r=>({name:r,distance:await Z(o,r.toLowerCase())})))).filter(r=>r.distance<=Math.max(3,i.length/2)).sort((r,s)=>r.distance-s.distance).slice(0,e).map(r=>r.name)}async function f(i,t){let e=await h(t),o=i[e];if(!o||typeof o.create!="function"){let n=Ee(i),r=await Ce(e,n),s=`Model '${e}' not found in Prisma client. Table name: '${t}'. `;throw r.length>0&&(s+=`Did you mean: ${r.map(a=>`'${a}'`).join(", ")}? `),n.length>0&&n.length<=10&&(s+=`Available models: ${n.join(", ")}. `),s+=`You can register a custom mapping with: registerPrismaModelMapping('${t}', 'yourModelName')`,new Error(s)}return o}async function Ie(i,t,e,o){let n=await h(o.model),r=i[n];if(!r)return t;switch(o.type){case "hasOne":{let s=o.localKey||"id",a=t[s];if(a==null)return {...t,[e]:null};let l=await r.findFirst({where:{[o.foreignKey]:a}});return {...t,[e]:l||null}}case "hasMany":{let s=o.localKey||"id",a=t[s];if(a==null)return {...t,[e]:[]};let l=await r.findMany({where:{[o.foreignKey]:a}});return {...t,[e]:l}}case "belongsTo":{let s=t[o.foreignKey];if(s==null)return {...t,[e]:null};let a=o.localKey||"id",l=await r.findFirst({where:{[a]:s}});return {...t,[e]:l||null}}default:return t}}async function ne(i,t,e,o){if(!o?.relations?.length||!e.model.relations)return t;let n={...t};for(let r of o.relations){let s=e.model.relations[r];s&&(n=await Ie(i,n,r,s));}return n}async function P(i,t,e,o){if(!t.length||!o?.relations?.length||!e.model.relations)return t;let n=t.map(r=>({...r}));for(let r of o.relations){let s=e.model.relations[r];if(!s)continue;let a=await h(s.model),l=i[a];if(l)switch(s.type){case "hasOne":case "hasMany":{let u=s.localKey||"id",c=[...new Set(n.map(m=>m[u]).filter(m=>m!=null))];if(c.length===0){n=n.map(m=>({...m,[r]:s.type==="hasMany"?[]:null}));continue}let d=await l.findMany({where:{[s.foreignKey]:{in:c}}}),p=new Map;for(let m of d){let g=m[s.foreignKey];p.has(g)||p.set(g,[]),p.get(g).push(m);}n=n.map(m=>{let g=m[u],M=p.get(g)||[];return {...m,[r]:s.type==="hasMany"?M:M[0]||null}});break}case "belongsTo":{let u=s.localKey||"id",c=[...new Set(n.map(m=>m[s.foreignKey]).filter(m=>m!=null))];if(c.length===0){n=n.map(m=>({...m,[r]:null}));continue}let d=await l.findMany({where:{[u]:{in:c}}}),p=new Map;for(let m of d){let g=m[u];p.set(g,m);}n=n.map(m=>{let g=m[s.foreignKey];return {...m,[r]:p.get(g)||null}});break}}}return n}async function R(i){let{model:t,filters:e,searchFields:o=[],softDeleteConfig:n,defaultPerPage:r=20,additionalWhere:s={}}=i,a={...E(e.filters),...s};if(n?.enabled){let{withDeleted:g,onlyDeleted:M}=e.options;M?a[n.field]={not:null}:g||(a[n.field]=null);}if(e.options.search&&o.length>0){let g=o.map(M=>({[M]:{contains:e.options.search,mode:"insensitive"}}));a={...a,OR:g};}let l=await t.count({where:a}),u;e.options.order_by&&(u={[e.options.order_by]:e.options.order_by_direction||"asc"});let c=e.options.page||1,d=e.options.per_page||r,p=await t.findMany({where:a,orderBy:u,skip:(c-1)*d,take:d}),m=Math.ceil(l/d);return {records:p,where:a,totalCount:l,page:c,perPage:d,totalPages:m}}function v(i,t){return {result:i,result_info:{page:t.page,per_page:t.perPage,total_count:t.totalCount,total_pages:t.totalPages,has_next_page:t.page<t.totalPages,has_prev_page:t.page>1}}}var oe=class extends j$1{useTransaction=false;async getModel(){return f(this.prisma,this._meta.model.tableName)}async create(t){let e=await this.getModel(),o=this._meta.model.primaryKeys[0],n={...t,[o]:t[o]||crypto.randomUUID()};return await e.create({data:n})}},re=class extends k$1{async getModel(){return f(this.prisma,this._meta.model.tableName)}async read(t,e,o){let n=await this.getModel(),r={[this.lookupField]:t,...e},s=await n.findFirst({where:r});return s?await ne(this.prisma,s,this._meta,o):null}},se=class extends l{useTransaction=false;async getModel(){return f(this.prisma,this._meta.model.tableName)}async update(t,e,o){let n=await this.getModel(),r={[this.lookupField]:t,...o},s=await n.findFirst({where:r});if(!s)return null;let a=this._meta.model.primaryKeys[0];return await n.update({where:{[a]:s[a]},data:e})}},ae=class extends m{useTransaction=false;async getModel(){return f(this.prisma,this._meta.model.tableName)}async findForDelete(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),r={[this.lookupField]:t,...e};return n.enabled&&(r[n.field]=null),await o.findFirst({where:r})}async delete(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),r={[this.lookupField]:t,...e};n.enabled&&(r[n.field]=null);let s=await o.findFirst({where:r});if(!s)return null;let a=this._meta.model.primaryKeys[0],l=s[a];return n.enabled?await o.update({where:{[a]:l},data:{[n.field]:new Date}}):await o.delete({where:{[a]:l}})}},ie=class extends n{async getModel(){return f(this.prisma,this._meta.model.tableName)}async list(t){let e=await R({model:await this.getModel(),filters:t,searchFields:this.searchFields,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage}),o={relations:t.options.include||[]},n=await P(this.prisma,e.records,this._meta,o);return v(n,e)}};var le=class extends o{useTransaction=false;async getModel(){return f(this.prisma,this._meta.model.tableName)}async restore(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),r={[this.lookupField]:t,[n.field]:{not:null},...e},s=await o.findFirst({where:r});if(!s)return null;let a=this._meta.model.primaryKeys[0];return await o.update({where:{[a]:s[a]},data:{[n.field]:null}})}},de=class extends q{async getModel(){return f(this.prisma,this._meta.model.tableName)}async batchCreate(t){let e=this._meta.model.primaryKeys[0],o=t.map(r=>({...r,[e]:r[e]||crypto.randomUUID()})),n=[];return await this.prisma.$transaction(async r=>{let s=r[await h(this._meta.model.tableName)];for(let a of o){let l=await s.create({data:a});n.push(l);}}),n}},ce=class extends r{async getModel(){return f(this.prisma,this._meta.model.tableName)}async batchUpdate(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],r=[],s=[],a=t.map(d=>d.id),l={[this.lookupField]:{in:a}};o.enabled&&(l[o.field]=null);let u=await e.findMany({where:l}),c=new Map;for(let d of u){let p=d[this.lookupField];c.set(p,d);}for(let d of t){let p=c.get(d.id);if(!p){s.push(d.id);continue}let m=await e.update({where:{[n]:p[n]},data:d.data});r.push(m);}return {updated:r,notFound:s}}},ue=class extends s{async getModel(){return f(this.prisma,this._meta.model.tableName)}async batchDelete(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],r=[],s=[],a={[this.lookupField]:{in:t}};o.enabled&&(a[o.field]=null);let l=await e.findMany({where:a}),u=new Map;for(let c of l){let d=c[this.lookupField];u.set(d,c);}for(let c of t)u.has(c)||s.push(c);for(let c of t){let d=u.get(c);if(d)if(o.enabled){let p=await e.update({where:{[n]:d[n]},data:{[o.field]:new Date}});r.push(p);}else {let p=await e.delete({where:{[n]:d[n]}});r.push(p);}}return {deleted:r,notFound:s}}},me=class extends t{async getModel(){return f(this.prisma,this._meta.model.tableName)}async batchRestore(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],r=[],s=[],a={[this.lookupField]:{in:t},[o.field]:{not:null}},l=await e.findMany({where:a}),u=new Map;for(let c of l){let d=c[this.lookupField];u.set(d,c);}for(let c of t){let d=u.get(c);if(!d){s.push(c);continue}let p=await e.update({where:{[n]:d[n]},data:{[o.field]:null}});r.push(p);}return {restored:r,notFound:s}}},ge=class extends u{useTransaction=true;async getModel(){return f(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let s of o){let a=t[s];a!==void 0&&(n[s]=a);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this._meta.model.primaryKeys[0],n={...t,[o]:t[o]||crypto.randomUUID()};return await e.create({data:n})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:e})}async nativeBatchUpsert(t,e){if(t.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let o=this.getUpsertKeys(),n=this._meta.model.primaryKeys[0],r=async l=>{let u=l[await h(this._meta.model.tableName)],c=[],d=[];for(let p=0;p<t.length;p++){let m=t[p];try{let g={};for(let w of o){let x=m[w];x!==void 0&&(g[w]=x);}let M={...m,[n]:m[n]||crypto.randomUUID()},b={};for(let[w,x]of Object.entries(m))!o.includes(w)&&w!==n&&(this.createOnlyFields?.includes(w)||(b[w]=x));let xe=await u.upsert({where:g,create:M,update:Object.keys(b).length>0?b:{}});c.push({data:xe,created:!1,index:p});}catch(g){if(this.continueOnError)d.push({index:p,error:g instanceof Error?g.message:String(g)});else throw g}}return {results:c,errors:d}},s;this.useTransaction?s=await this.prisma.$transaction(r):s=await r(this.prisma);let a={items:s.results,createdCount:0,updatedCount:s.results.length,totalCount:s.results.length};return s.errors.length>0&&(a.errors=s.errors),a}};var pe=class extends I{async getModel(){return f(this.prisma,this._meta.model.tableName)}buildSearchWhere(t,e){let o=E(e.filters),n=this.getSoftDeleteConfig();if(n.enabled){let{withDeleted:l,onlyDeleted:u}=e.options;u?o[n.field]={not:null}:l||(o[n.field]=null);}let r=this.getSearchableFields(),a=(t.fields||Object.keys(r)).map(l=>({[l]:{contains:t.query,mode:"insensitive"}}));return a.length>0&&(t.mode==="all"?o={...o,AND:a}:o={...o,OR:a}),o}async search(t,e){let o=await this.getModel(),n=this.buildSearchWhere(t,e),r=await o.count({where:n}),s=e.options.order_by?{[e.options.order_by]:e.options.order_by_direction||"asc"}:void 0,a=e.options.page||1,l=e.options.per_page||this.defaultPerPage,u=await o.findMany({where:n,orderBy:s,skip:(a-1)*l,take:l}),c=J$1(u,t,this.getSearchableFields()),d={relations:e.options.include||[]},p=c.map(M=>M.item),m=await P(this.prisma,p,this._meta,d);return {items:c.map((M,b)=>({...M,item:m[b]})),totalCount:r}}},fe=class extends S{async getModel(){return f(this.prisma,this._meta.model.tableName)}async list(t){let e=await R({model:await this.getModel(),filters:t,searchFields:this.searchFields,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage}),o={relations:t.options.include||[]},n=await P(this.prisma,e.records,this._meta,o);return v(n,e)}},Me=class extends T{async getModel(){return f(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let s of o){let a=t[s];a!==void 0&&(n[s]=a);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this._meta.model.primaryKeys[0],n={...t,[o]:t[o]||crypto.randomUUID()};return await e.create({data:n})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:e})}},he=class extends p{useTransaction=false;async getModel(){return f(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let s of o){let a=t[s];a!==void 0&&(n[s]=a);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this._meta.model.primaryKeys[0],n={...t,[o]:t[o]||crypto.randomUUID()};return await e.create({data:n})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:e})}async nativeUpsert(t,e){let o=await this.getModel(),n=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s={};for(let c of n){let d=t[c];d!==void 0&&(s[c]=d);}let a={...t,[r]:t[r]||crypto.randomUUID()},l={};for(let[c,d]of Object.entries(t))!n.includes(c)&&c!==r&&(this.createOnlyFields?.includes(c)||(l[c]=d));return {data:await o.upsert({where:s,create:a,update:Object.keys(l).length>0?l:{}}),created:false}}},we=class extends v$1{async getModel(){return f(this.prisma,this._meta.model.tableName)}async recordExists(t){return await(await this.getModel()).count({where:{[this.lookupField]:t}})>0}},ye=class extends w{},be=class extends x{},ke=class extends y$1{async getModel(){return f(this.prisma,this._meta.model.tableName)}async rollback(t,e,o){let n=await this.getModel(),r=this.getVersioningConfig().field,s=this._meta.model.primaryKeys[0],a=await n.findFirst({where:{[this.lookupField]:t}});if(!a)throw new Error(`Record not found: ${t}`);return await n.update({where:{[s]:a[s]},data:{...e,[r]:o}})}},Pe=class extends z{useNativeAggregation=true;async getModel(){return f(this.prisma,this._meta.model.tableName)}async buildAggregateWhere(t){let e={},o=this.getSoftDeleteConfig();if(o.enabled){let{query:n}=await this.getValidatedData();n?.withDeleted===true||n?.withDeleted==="true"||(e[o.field]=null);}if(t.filters)for(let[n,r]of Object.entries(t.filters))if(typeof r=="object"&&r!==null){let s={};for(let[a,l]of Object.entries(r))switch(a){case "eq":s.equals=l;break;case "ne":s.not=l;break;case "gt":s.gt=l;break;case "gte":s.gte=l;break;case "lt":s.lt=l;break;case "lte":s.lte=l;break;case "in":s.in=l;break;case "nin":s.notIn=l;break;default:s[a]=l;}e[n]=s;}else e[n]=r;return e}async aggregate(t){let e=await this.getModel(),o=await this.buildAggregateWhere(t);if(!this.useNativeAggregation||t.having){let n=await e.findMany({where:o});return A(n,t)}return t.groupBy?.length?this.aggregateWithGroupBy(e,o,t):this.aggregateSimple(e,o,t)}groupAggregationsByOperation(t){let e={sum:[],avg:[],min:[],max:[],count:[],countDistinct:[]};for(let o of t)switch(o.operation){case "sum":e.sum.push(o.field);break;case "avg":e.avg.push(o.field);break;case "min":e.min.push(o.field);break;case "max":e.max.push(o.field);break;case "count":e.count.push(o.field);break;case "countDistinct":e.countDistinct.push(o.field);break}return e}async aggregateSimple(t,e,o){let n={where:e},r={},s=this.groupAggregationsByOperation(o.aggregations);if(n._count=true,s.sum.length){n._sum={};for(let u of s.sum)n._sum[u]=true;}if(s.avg.length){n._avg={};for(let u of s.avg)n._avg[u]=true;}if(s.min.length){n._min={};for(let u of s.min)n._min[u]=true;}if(s.max.length){n._max={};for(let u of s.max)n._max[u]=true;}let a=await h(this._meta.model.tableName),l=this.prisma[a];try{let u=await l.aggregate(n);if(u._count!==void 0&&(r.count=typeof u._count=="object"?u._count._all??0:u._count),u._sum&&s.sum.length)for(let c of s.sum){let d=c.charAt(0).toUpperCase()+c.slice(1);r[`sum${d}`]=u._sum[c]??0;}if(u._avg&&s.avg.length)for(let c of s.avg){let d=c.charAt(0).toUpperCase()+c.slice(1);r[`avg${d}`]=u._avg[c]??0;}if(u._min&&s.min.length)for(let c of s.min){let d=c.charAt(0).toUpperCase()+c.slice(1);r[`min${d}`]=u._min[c];}if(u._max&&s.max.length)for(let c of s.max){let d=c.charAt(0).toUpperCase()+c.slice(1);r[`max${d}`]=u._max[c];}return {values:r,groups:[]}}catch{let c=await t.findMany({where:e});return A(c,o)}}async aggregateWithGroupBy(t,e,o){let n={by:o.groupBy,where:e},r=this.groupAggregationsByOperation(o.aggregations);if(n._count=true,r.sum.length){n._sum={};for(let l of r.sum)n._sum[l]=true;}if(r.avg.length){n._avg={};for(let l of r.avg)n._avg[l]=true;}if(r.min.length){n._min={};for(let l of r.min)n._min[l]=true;}if(r.max.length){n._max={};for(let l of r.max)n._max[l]=true;}let s=await h(this._meta.model.tableName),a=this.prisma[s];try{let u=(await a.groupBy(n)).map(d=>{let p={},m={};for(let g of o.groupBy)p[g]=d[g];if(m.count=typeof d._count=="object"?d._count._all??0:d._count??0,d._sum&&r.sum.length)for(let g of r.sum){let M=g.charAt(0).toUpperCase()+g.slice(1);m[`sum${M}`]=d._sum[g]??0;}if(d._avg&&r.avg.length)for(let g of r.avg){let M=g.charAt(0).toUpperCase()+g.slice(1);m[`avg${M}`]=d._avg[g]??0;}if(d._min&&r.min.length)for(let g of r.min){let M=g.charAt(0).toUpperCase()+g.slice(1);m[`min${M}`]=d._min[g];}if(d._max&&r.max.length)for(let g of r.max){let M=g.charAt(0).toUpperCase()+g.slice(1);m[`max${M}`]=d._max[g];}return {key:p,values:m}});return {values:{count:u.reduce((d,p)=>d+(p.values.count||0),0)},groups:u}}catch{let u=await t.findMany({where:e});return A(u,o)}}};export{Pe as PrismaAggregateEndpoint,de as PrismaBatchCreateEndpoint,ue as PrismaBatchDeleteEndpoint,me as PrismaBatchRestoreEndpoint,ce as PrismaBatchUpdateEndpoint,ge as PrismaBatchUpsertEndpoint,oe as PrismaCreateEndpoint,ae as PrismaDeleteEndpoint,fe as PrismaExportEndpoint,Me as PrismaImportEndpoint,ie as PrismaListEndpoint,re as PrismaReadEndpoint,le as PrismaRestoreEndpoint,pe as PrismaSearchEndpoint,se as PrismaUpdateEndpoint,he as PrismaUpsertEndpoint,be as PrismaVersionCompareEndpoint,we as PrismaVersionHistoryEndpoint,ye as PrismaVersionReadEndpoint,ke as PrismaVersionRollbackEndpoint,je as clearPrismaModelMappings,te as registerPrismaModelMapping,_e as registerPrismaModelMappings};
1
+ import {k as k$1,l,m,n,o,p,r,s,t,u,v as v$1,J,K,T,U,q,w,x,y as y$1,z,A,B}from'../../chunk-Q4FF5JVS.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-W4FHI5YI.js';import'../../chunk-HAUN4LQO.js';import'../../chunk-NIWM7GOK.js';import'../../chunk-RFT77JBK.js';import'../../chunk-FC56WWPB.js';import'../../chunk-GBQQ3YQX.js';import'../../chunk-QRXEQTNE.js';import'../../chunk-QXFY6NYI.js';import'../../chunk-DMGP7QDL.js';import'../../chunk-MDHMZPXK.js';import'../../chunk-VJRDAVID.js';var R,v;async function Oe(){if(R)return R;try{return R=(await import('pluralize')).default,R}catch{throw new Error('The "pluralize" package is required. Install it with: npm install pluralize')}}async function Re(){if(v)return v;try{return v=(await import('fastest-levenshtein')).distance,v}catch{throw new Error('The "fastest-levenshtein" package is required. Install it with: npm install fastest-levenshtein')}}async function E(i){return (await Oe()).singular(i)}async function C(i,t){return (await Re())(i,t)}function k(i){if(typeof i=="string"){if(/^-?\d+$/.test(i))return parseInt(i,10);if(/^-?\d+\.\d+$/.test(i))return parseFloat(i);if(i==="true")return true;if(i==="false")return false}return i}function I(i){let t={};for(let e of i){let o=k(e.value);switch(e.operator){case "eq":t[e.field]=o;break;case "ne":t[e.field]={not:o};break;case "gt":t[e.field]={gt:o};break;case "gte":t[e.field]={gte:o};break;case "lt":t[e.field]={lt:o};break;case "lte":t[e.field]={lte:o};break;case "in":{let n=Array.isArray(e.value)?e.value:[e.value];t[e.field]={in:n.map(k)};break}case "nin":{let n=Array.isArray(e.value)?e.value:[e.value];t[e.field]={notIn:n.map(k)};break}case "like":t[e.field]={contains:String(e.value).replace(/%/g,"")};break;case "ilike":t[e.field]={contains:String(e.value).replace(/%/g,""),mode:"insensitive"};break;case "null":t[e.field]=e.value?null:{not:null};break;case "between":{let[n,r]=e.value;t[e.field]={gte:k(n),lte:k(r)};break}}}return t}var ve=500,y=new Map;function ee(i,t){if(y.size>=ve){let e=y.keys().next().value;e!==void 0&&y.delete(e);}y.set(i,t);}var F=new Map;function te(i,t){F.set(i.toLowerCase(),t),y.delete(i);}function _e(i){for(let[t,e]of Object.entries(i))te(t,e);}function je(){F.clear(),y.clear();}async function h(i){let t=y.get(i);if(t)return t;let e=F.get(i.toLowerCase());if(e)return ee(i,e),e;let o=i.replace(/[-_](.)/g,(n,r)=>r.toUpperCase()).replace(/^./,n=>n.toLowerCase());return o=await E(o),ee(i,o),o}function Ee(i){let t=[];for(let e of Object.keys(i)){if(e.startsWith("$")||e.startsWith("_"))continue;let o=i[e];o&&typeof o=="object"&&"create"in o&&t.push(e);}return t}async function Ce(i,t,e=3){if(t.length===0)return [];let o=i.toLowerCase();return (await Promise.all(t.map(async r=>({name:r,distance:await C(o,r.toLowerCase())})))).filter(r=>r.distance<=Math.max(3,i.length/2)).sort((r,s)=>r.distance-s.distance).slice(0,e).map(r=>r.name)}async function f(i,t){let e=await h(t),o=i[e];if(!o||typeof o.create!="function"){let n=Ee(i),r=await Ce(e,n),s=`Model '${e}' not found in Prisma client. Table name: '${t}'. `;throw r.length>0&&(s+=`Did you mean: ${r.map(a=>`'${a}'`).join(", ")}? `),n.length>0&&n.length<=10&&(s+=`Available models: ${n.join(", ")}. `),s+=`You can register a custom mapping with: registerPrismaModelMapping('${t}', 'yourModelName')`,new Error(s)}return o}async function Ie(i,t,e,o){let n=await h(o.model),r=i[n];if(!r)return t;switch(o.type){case "hasOne":{let s=o.localKey||"id",a=t[s];if(a==null)return {...t,[e]:null};let l=await r.findFirst({where:{[o.foreignKey]:a}});return {...t,[e]:l||null}}case "hasMany":{let s=o.localKey||"id",a=t[s];if(a==null)return {...t,[e]:[]};let l=await r.findMany({where:{[o.foreignKey]:a}});return {...t,[e]:l}}case "belongsTo":{let s=t[o.foreignKey];if(s==null)return {...t,[e]:null};let a=o.localKey||"id",l=await r.findFirst({where:{[a]:s}});return {...t,[e]:l||null}}default:return t}}async function ne(i,t,e,o){if(!o?.relations?.length||!e.model.relations)return t;let n={...t};for(let r of o.relations){let s=e.model.relations[r];s&&(n=await Ie(i,n,r,s));}return n}async function P(i,t,e,o){if(!t.length||!o?.relations?.length||!e.model.relations)return t;let n=t.map(r=>({...r}));for(let r of o.relations){let s=e.model.relations[r];if(!s)continue;let a=await h(s.model),l=i[a];if(l)switch(s.type){case "hasOne":case "hasMany":{let u=s.localKey||"id",c=[...new Set(n.map(m=>m[u]).filter(m=>m!=null))];if(c.length===0){n=n.map(m=>({...m,[r]:s.type==="hasMany"?[]:null}));continue}let d=await l.findMany({where:{[s.foreignKey]:{in:c}}}),p=new Map;for(let m of d){let g=m[s.foreignKey];p.has(g)||p.set(g,[]),p.get(g).push(m);}n=n.map(m=>{let g=m[u],M=p.get(g)||[];return {...m,[r]:s.type==="hasMany"?M:M[0]||null}});break}case "belongsTo":{let u=s.localKey||"id",c=[...new Set(n.map(m=>m[s.foreignKey]).filter(m=>m!=null))];if(c.length===0){n=n.map(m=>({...m,[r]:null}));continue}let d=await l.findMany({where:{[u]:{in:c}}}),p=new Map;for(let m of d){let g=m[u];p.set(g,m);}n=n.map(m=>{let g=m[s.foreignKey];return {...m,[r]:p.get(g)||null}});break}}}return n}async function _(i){let{model:t,filters:e,searchFields:o=[],softDeleteConfig:n,defaultPerPage:r=20,additionalWhere:s={}}=i,a={...I(e.filters),...s};if(n?.enabled){let{withDeleted:g,onlyDeleted:M}=e.options;M?a[n.field]={not:null}:g||(a[n.field]=null);}if(e.options.search&&o.length>0){let g=o.map(M=>({[M]:{contains:e.options.search,mode:"insensitive"}}));a={...a,OR:g};}let l=await t.count({where:a}),u;e.options.order_by&&(u={[e.options.order_by]:e.options.order_by_direction||"asc"});let c=e.options.page||1,d=e.options.per_page||r,p=await t.findMany({where:a,orderBy:u,skip:(c-1)*d,take:d}),m=Math.ceil(l/d);return {records:p,where:a,totalCount:l,page:c,perPage:d,totalPages:m}}function j(i,t){return {result:i,result_info:{page:t.page,per_page:t.perPage,total_count:t.totalCount,total_pages:t.totalPages,has_next_page:t.page<t.totalPages,has_prev_page:t.page>1}}}var oe=class extends k$1{useTransaction=false;async getModel(){return f(this.prisma,this._meta.model.tableName)}async create(t){let e=await this.getModel(),o=this._meta.model.primaryKeys[0],n={...t,[o]:t[o]||crypto.randomUUID()};return await e.create({data:n})}},re=class extends l{async getModel(){return f(this.prisma,this._meta.model.tableName)}async read(t,e,o){let n=await this.getModel(),r={[this.lookupField]:t,...e},s=await n.findFirst({where:r});return s?await ne(this.prisma,s,this._meta,o):null}},se=class extends m{useTransaction=false;async getModel(){return f(this.prisma,this._meta.model.tableName)}async update(t,e,o){let n=await this.getModel(),r={[this.lookupField]:t,...o},s=await n.findFirst({where:r});if(!s)return null;let a=this._meta.model.primaryKeys[0];return await n.update({where:{[a]:s[a]},data:e})}},ae=class extends n{useTransaction=false;async getModel(){return f(this.prisma,this._meta.model.tableName)}async findForDelete(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),r={[this.lookupField]:t,...e};return n.enabled&&(r[n.field]=null),await o.findFirst({where:r})}async delete(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),r={[this.lookupField]:t,...e};n.enabled&&(r[n.field]=null);let s=await o.findFirst({where:r});if(!s)return null;let a=this._meta.model.primaryKeys[0],l=s[a];return n.enabled?await o.update({where:{[a]:l},data:{[n.field]:new Date}}):await o.delete({where:{[a]:l}})}},ie=class extends o{async getModel(){return f(this.prisma,this._meta.model.tableName)}async list(t){let e=await _({model:await this.getModel(),filters:t,searchFields:this.searchFields,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage}),o={relations:t.options.include||[]},n=await P(this.prisma,e.records,this._meta,o);return j(n,e)}};var le=class extends p{useTransaction=false;async getModel(){return f(this.prisma,this._meta.model.tableName)}async restore(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),r={[this.lookupField]:t,[n.field]:{not:null},...e},s=await o.findFirst({where:r});if(!s)return null;let a=this._meta.model.primaryKeys[0];return await o.update({where:{[a]:s[a]},data:{[n.field]:null}})}},de=class extends r{async getModel(){return f(this.prisma,this._meta.model.tableName)}async batchCreate(t){let e=this._meta.model.primaryKeys[0],o=t.map(r=>({...r,[e]:r[e]||crypto.randomUUID()})),n=[];return await this.prisma.$transaction(async r=>{let s=r[await h(this._meta.model.tableName)];for(let a of o){let l=await s.create({data:a});n.push(l);}}),n}},ce=class extends s{async getModel(){return f(this.prisma,this._meta.model.tableName)}async batchUpdate(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],r=[],s=[],a=t.map(d=>d.id),l={[this.lookupField]:{in:a}};o.enabled&&(l[o.field]=null);let u=await e.findMany({where:l}),c=new Map;for(let d of u){let p=d[this.lookupField];c.set(p,d);}for(let d of t){let p=c.get(d.id);if(!p){s.push(d.id);continue}let m=await e.update({where:{[n]:p[n]},data:d.data});r.push(m);}return {updated:r,notFound:s}}},ue=class extends t{async getModel(){return f(this.prisma,this._meta.model.tableName)}async batchDelete(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],r=[],s=[],a={[this.lookupField]:{in:t}};o.enabled&&(a[o.field]=null);let l=await e.findMany({where:a}),u=new Map;for(let c of l){let d=c[this.lookupField];u.set(d,c);}for(let c of t)u.has(c)||s.push(c);for(let c of t){let d=u.get(c);if(d)if(o.enabled){let p=await e.update({where:{[n]:d[n]},data:{[o.field]:new Date}});r.push(p);}else {let p=await e.delete({where:{[n]:d[n]}});r.push(p);}}return {deleted:r,notFound:s}}},me=class extends u{async getModel(){return f(this.prisma,this._meta.model.tableName)}async batchRestore(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],r=[],s=[],a={[this.lookupField]:{in:t},[o.field]:{not:null}},l=await e.findMany({where:a}),u=new Map;for(let c of l){let d=c[this.lookupField];u.set(d,c);}for(let c of t){let d=u.get(c);if(!d){s.push(c);continue}let p=await e.update({where:{[n]:d[n]},data:{[o.field]:null}});r.push(p);}return {restored:r,notFound:s}}},ge=class extends v$1{useTransaction=true;async getModel(){return f(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let s of o){let a=t[s];a!==void 0&&(n[s]=a);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this._meta.model.primaryKeys[0],n={...t,[o]:t[o]||crypto.randomUUID()};return await e.create({data:n})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:e})}async nativeBatchUpsert(t,e){if(t.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let o=this.getUpsertKeys(),n=this._meta.model.primaryKeys[0],r=async l=>{let u=l[await h(this._meta.model.tableName)],c=[],d=[];for(let p=0;p<t.length;p++){let m=t[p];try{let g={};for(let w of o){let x=m[w];x!==void 0&&(g[w]=x);}let M={...m,[n]:m[n]||crypto.randomUUID()},b={};for(let[w,x]of Object.entries(m))!o.includes(w)&&w!==n&&(this.createOnlyFields?.includes(w)||(b[w]=x));let xe=await u.upsert({where:g,create:M,update:Object.keys(b).length>0?b:{}});c.push({data:xe,created:!1,index:p});}catch(g){if(this.continueOnError)d.push({index:p,error:g instanceof Error?g.message:String(g)});else throw g}}return {results:c,errors:d}},s;this.useTransaction?s=await this.prisma.$transaction(r):s=await r(this.prisma);let a={items:s.results,createdCount:0,updatedCount:s.results.length,totalCount:s.results.length};return s.errors.length>0&&(a.errors=s.errors),a}};var pe=class extends J{async getModel(){return f(this.prisma,this._meta.model.tableName)}buildSearchWhere(t,e){let o=I(e.filters),n=this.getSoftDeleteConfig();if(n.enabled){let{withDeleted:l,onlyDeleted:u}=e.options;u?o[n.field]={not:null}:l||(o[n.field]=null);}let r=this.getSearchableFields(),a=(t.fields||Object.keys(r)).map(l=>({[l]:{contains:t.query,mode:"insensitive"}}));return a.length>0&&(t.mode==="all"?o={...o,AND:a}:o={...o,OR:a}),o}async search(t,e){let o=await this.getModel(),n=this.buildSearchWhere(t,e),r=await o.count({where:n}),s=e.options.order_by?{[e.options.order_by]:e.options.order_by_direction||"asc"}:void 0,a=e.options.page||1,l=e.options.per_page||this.defaultPerPage,u=await o.findMany({where:n,orderBy:s,skip:(a-1)*l,take:l}),c=K(u,t,this.getSearchableFields()),d={relations:e.options.include||[]},p=c.map(M=>M.item),m=await P(this.prisma,p,this._meta,d);return {items:c.map((M,b)=>({...M,item:m[b]})),totalCount:r}}},fe=class extends T{async getModel(){return f(this.prisma,this._meta.model.tableName)}async list(t){let e=await _({model:await this.getModel(),filters:t,searchFields:this.searchFields,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage}),o={relations:t.options.include||[]},n=await P(this.prisma,e.records,this._meta,o);return j(n,e)}},Me=class extends U{async getModel(){return f(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let s of o){let a=t[s];a!==void 0&&(n[s]=a);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this._meta.model.primaryKeys[0],n={...t,[o]:t[o]||crypto.randomUUID()};return await e.create({data:n})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:e})}},he=class extends q{useTransaction=false;async getModel(){return f(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let s of o){let a=t[s];a!==void 0&&(n[s]=a);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this._meta.model.primaryKeys[0],n={...t,[o]:t[o]||crypto.randomUUID()};return await e.create({data:n})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:e})}async nativeUpsert(t,e){let o=await this.getModel(),n=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s={};for(let c of n){let d=t[c];d!==void 0&&(s[c]=d);}let a={...t,[r]:t[r]||crypto.randomUUID()},l={};for(let[c,d]of Object.entries(t))!n.includes(c)&&c!==r&&(this.createOnlyFields?.includes(c)||(l[c]=d));return {data:await o.upsert({where:s,create:a,update:Object.keys(l).length>0?l:{}}),created:false}}},we=class extends w{async getModel(){return f(this.prisma,this._meta.model.tableName)}async recordExists(t){return await(await this.getModel()).count({where:{[this.lookupField]:t}})>0}},ye=class extends x{},be=class extends y$1{},ke=class extends z{async getModel(){return f(this.prisma,this._meta.model.tableName)}async rollback(t,e,o){let n=await this.getModel(),r=this.getVersioningConfig().field,s=this._meta.model.primaryKeys[0],a=await n.findFirst({where:{[this.lookupField]:t}});if(!a)throw new Error(`Record not found: ${t}`);return await n.update({where:{[s]:a[s]},data:{...e,[r]:o}})}},Pe=class extends A{useNativeAggregation=true;async getModel(){return f(this.prisma,this._meta.model.tableName)}async buildAggregateWhere(t){let e={},o=this.getSoftDeleteConfig();if(o.enabled){let{query:n}=await this.getValidatedData();n?.withDeleted===true||n?.withDeleted==="true"||(e[o.field]=null);}if(t.filters)for(let[n,r]of Object.entries(t.filters))if(typeof r=="object"&&r!==null){let s={};for(let[a,l]of Object.entries(r))switch(a){case "eq":s.equals=l;break;case "ne":s.not=l;break;case "gt":s.gt=l;break;case "gte":s.gte=l;break;case "lt":s.lt=l;break;case "lte":s.lte=l;break;case "in":s.in=l;break;case "nin":s.notIn=l;break;default:s[a]=l;}e[n]=s;}else e[n]=r;return e}async aggregate(t){let e=await this.getModel(),o=await this.buildAggregateWhere(t);if(!this.useNativeAggregation||t.having){let n=await e.findMany({where:o});return B(n,t)}return t.groupBy?.length?this.aggregateWithGroupBy(e,o,t):this.aggregateSimple(e,o,t)}groupAggregationsByOperation(t){let e={sum:[],avg:[],min:[],max:[],count:[],countDistinct:[]};for(let o of t)switch(o.operation){case "sum":e.sum.push(o.field);break;case "avg":e.avg.push(o.field);break;case "min":e.min.push(o.field);break;case "max":e.max.push(o.field);break;case "count":e.count.push(o.field);break;case "countDistinct":e.countDistinct.push(o.field);break}return e}async aggregateSimple(t,e,o){let n={where:e},r={},s=this.groupAggregationsByOperation(o.aggregations);if(n._count=true,s.sum.length){n._sum={};for(let u of s.sum)n._sum[u]=true;}if(s.avg.length){n._avg={};for(let u of s.avg)n._avg[u]=true;}if(s.min.length){n._min={};for(let u of s.min)n._min[u]=true;}if(s.max.length){n._max={};for(let u of s.max)n._max[u]=true;}let a=await h(this._meta.model.tableName),l=this.prisma[a];try{let u=await l.aggregate(n);if(u._count!==void 0&&(r.count=typeof u._count=="object"?u._count._all??0:u._count),u._sum&&s.sum.length)for(let c of s.sum){let d=c.charAt(0).toUpperCase()+c.slice(1);r[`sum${d}`]=u._sum[c]??0;}if(u._avg&&s.avg.length)for(let c of s.avg){let d=c.charAt(0).toUpperCase()+c.slice(1);r[`avg${d}`]=u._avg[c]??0;}if(u._min&&s.min.length)for(let c of s.min){let d=c.charAt(0).toUpperCase()+c.slice(1);r[`min${d}`]=u._min[c];}if(u._max&&s.max.length)for(let c of s.max){let d=c.charAt(0).toUpperCase()+c.slice(1);r[`max${d}`]=u._max[c];}return {values:r,groups:[]}}catch{let c=await t.findMany({where:e});return B(c,o)}}async aggregateWithGroupBy(t,e,o){let n={by:o.groupBy,where:e},r=this.groupAggregationsByOperation(o.aggregations);if(n._count=true,r.sum.length){n._sum={};for(let l of r.sum)n._sum[l]=true;}if(r.avg.length){n._avg={};for(let l of r.avg)n._avg[l]=true;}if(r.min.length){n._min={};for(let l of r.min)n._min[l]=true;}if(r.max.length){n._max={};for(let l of r.max)n._max[l]=true;}let s=await h(this._meta.model.tableName),a=this.prisma[s];try{let u=(await a.groupBy(n)).map(d=>{let p={},m={};for(let g of o.groupBy)p[g]=d[g];if(m.count=typeof d._count=="object"?d._count._all??0:d._count??0,d._sum&&r.sum.length)for(let g of r.sum){let M=g.charAt(0).toUpperCase()+g.slice(1);m[`sum${M}`]=d._sum[g]??0;}if(d._avg&&r.avg.length)for(let g of r.avg){let M=g.charAt(0).toUpperCase()+g.slice(1);m[`avg${M}`]=d._avg[g]??0;}if(d._min&&r.min.length)for(let g of r.min){let M=g.charAt(0).toUpperCase()+g.slice(1);m[`min${M}`]=d._min[g];}if(d._max&&r.max.length)for(let g of r.max){let M=g.charAt(0).toUpperCase()+g.slice(1);m[`max${M}`]=d._max[g];}return {key:p,values:m}});return {values:{count:u.reduce((d,p)=>d+(p.values.count||0),0)},groups:u}}catch{let u=await t.findMany({where:e});return B(u,o)}}};export{Pe as PrismaAggregateEndpoint,de as PrismaBatchCreateEndpoint,ue as PrismaBatchDeleteEndpoint,me as PrismaBatchRestoreEndpoint,ce as PrismaBatchUpdateEndpoint,ge as PrismaBatchUpsertEndpoint,oe as PrismaCreateEndpoint,ae as PrismaDeleteEndpoint,fe as PrismaExportEndpoint,Me as PrismaImportEndpoint,ie as PrismaListEndpoint,re as PrismaReadEndpoint,le as PrismaRestoreEndpoint,pe as PrismaSearchEndpoint,se as PrismaUpdateEndpoint,he as PrismaUpsertEndpoint,be as PrismaVersionCompareEndpoint,we as PrismaVersionHistoryEndpoint,ye as PrismaVersionReadEndpoint,ke as PrismaVersionRollbackEndpoint,je as clearPrismaModelMappings,te as registerPrismaModelMapping,_e as registerPrismaModelMappings};
@@ -0,0 +1,114 @@
1
+ import { MiddlewareHandler, Env, Context } from 'hono';
2
+
3
+ /**
4
+ * Strategy for extracting the API version from requests.
5
+ */
6
+ type VersionStrategy = 'url' | 'header' | 'query';
7
+ /**
8
+ * A version transformer function that converts request/response data
9
+ * between API versions.
10
+ */
11
+ type VersionTransformer = (data: Record<string, unknown>) => Record<string, unknown>;
12
+ /**
13
+ * Configuration for a single API version.
14
+ */
15
+ interface ApiVersionConfig {
16
+ /** Version identifier (e.g. '1', '2', '2024-01-15') */
17
+ version: string;
18
+ /** Optional middleware to apply for this version */
19
+ middleware?: MiddlewareHandler[];
20
+ /** Transform incoming request body from this version to latest */
21
+ requestTransformer?: VersionTransformer;
22
+ /** Transform outgoing response data from latest to this version */
23
+ responseTransformer?: VersionTransformer;
24
+ /** ISO date string when this version was deprecated */
25
+ deprecated?: string;
26
+ /** ISO date string when this version will be removed */
27
+ sunset?: string;
28
+ }
29
+ /**
30
+ * Configuration for the API versioning middleware.
31
+ */
32
+ interface VersioningMiddlewareConfig {
33
+ /** Available API versions. First is treated as default if no defaultVersion specified. */
34
+ versions: ApiVersionConfig[];
35
+ /** Default version when none is specified by client */
36
+ defaultVersion?: string;
37
+ /** Version extraction strategy. @default 'header' */
38
+ strategy?: VersionStrategy;
39
+ /** Header name for header strategy. @default 'Accept-Version' */
40
+ headerName?: string;
41
+ /** Query parameter name for query strategy. @default 'version' */
42
+ queryParam?: string;
43
+ /** URL prefix pattern for URL strategy (e.g. '/v{version}'). @default '/v{version}' */
44
+ urlPattern?: string;
45
+ /** Custom version extractor (overrides strategy) */
46
+ extractVersion?: (ctx: Context) => string | undefined;
47
+ /** Whether to add version headers to responses. @default true */
48
+ addHeaders?: boolean;
49
+ }
50
+ /**
51
+ * Environment type additions for API versioning.
52
+ *
53
+ * Variables are typed optional because they are only set after the api-version
54
+ * middleware has run. Use `extends ApiVersionEnv` on your app's `Env` to opt in.
55
+ */
56
+ interface ApiVersionEnv extends Env {
57
+ Variables: {
58
+ apiVersion?: string;
59
+ apiVersionConfig?: ApiVersionConfig;
60
+ };
61
+ }
62
+
63
+ /**
64
+ * Create API versioning middleware.
65
+ *
66
+ * @example
67
+ * ```ts
68
+ * import { Hono } from 'hono';
69
+ * import { apiVersion } from 'hono-crud';
70
+ *
71
+ * const app = new Hono();
72
+ *
73
+ * app.use('*', apiVersion({
74
+ * versions: [
75
+ * { version: '2', responseTransformer: (data) => data },
76
+ * {
77
+ * version: '1',
78
+ * deprecated: '2024-06-01',
79
+ * sunset: '2025-01-01',
80
+ * responseTransformer: (data) => {
81
+ * // Convert v2 response to v1 format
82
+ * const { firstName, lastName, ...rest } = data;
83
+ * return { ...rest, name: `${firstName} ${lastName}` };
84
+ * },
85
+ * },
86
+ * ],
87
+ * defaultVersion: '2',
88
+ * strategy: 'header',
89
+ * }));
90
+ * ```
91
+ */
92
+ declare function apiVersion(config: VersioningMiddlewareConfig): MiddlewareHandler;
93
+ /**
94
+ * Get the current API version from context.
95
+ */
96
+ declare function getApiVersion(ctx: Context): string | undefined;
97
+ /**
98
+ * Get the full version config from context.
99
+ */
100
+ declare function getApiVersionConfig(ctx: Context): ApiVersionConfig | undefined;
101
+ /**
102
+ * Middleware that transforms response JSON using the active version's responseTransformer.
103
+ * Apply AFTER your route handlers.
104
+ *
105
+ * @example
106
+ * ```ts
107
+ * app.use('*', apiVersion({ ... }));
108
+ * app.get('/users/:id', handler);
109
+ * app.use('*', versionedResponse());
110
+ * ```
111
+ */
112
+ declare function versionedResponse(): MiddlewareHandler;
113
+
114
+ export { type ApiVersionConfig, type ApiVersionEnv, type VersionStrategy, type VersionTransformer, type VersioningMiddlewareConfig, apiVersion, getApiVersion, getApiVersionConfig, versionedResponse };
@@ -0,0 +1 @@
1
+ export{a as apiVersion,b as getApiVersion,c as getApiVersionConfig,d as versionedResponse}from'../chunk-KKLMXJY4.js';import'../chunk-FC56WWPB.js';