hono-crud 0.13.0 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -15,6 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
15
15
  %b
16
16
  %b
17
17
  %b
18
+ %b
18
19
  ## [0.8.0] — 2026-05-03
19
20
 
20
21
  ### Added
@@ -95,3 +96,4 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
95
96
  [0.12.4]: https://github.com/kshdotdev/hono-crud/compare/v0.12.3...v0.12.4
96
97
  [0.12.5]: https://github.com/kshdotdev/hono-crud/compare/v0.12.4...v0.12.5
97
98
  [0.13.0]: https://github.com/kshdotdev/hono-crud/compare/v0.12.5...v0.13.0
99
+ [0.13.1]: https://github.com/kshdotdev/hono-crud/compare/v0.13.0...v0.13.1
@@ -1,7 +1,7 @@
1
1
  import { Table, SQL, Column } from 'drizzle-orm';
2
2
  import { M as MetaInput, I as IncludeOptions, n as FilterCondition, h as RelationConfig, N 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-Dfi9RdjS.js';
3
3
  import { Env } from 'hono';
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 CloneEndpoint, i as UpsertEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, V as VersionCompareEndpoint, j as VersionHistoryEndpoint, k as VersionReadEndpoint, l as VersionRollbackEndpoint } from '../../import-Gx0ZUJjI.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 CloneEndpoint, i as UpsertEndpoint, S as SearchEndpoint, E as ExportEndpoint, I as ImportEndpoint, V as VersionCompareEndpoint, j as VersionHistoryEndpoint, k as VersionReadEndpoint, l as VersionRollbackEndpoint } from '../../import-Gx0ZUJjI.js';
5
5
  import { z } from 'zod';
6
6
  import { A as AdapterBundle } from '../../index-B1QEfh5v.js';
7
7
  import '../../types-B5wq2iKZ.js';
@@ -448,6 +448,26 @@ declare abstract class DrizzleBatchRestoreEndpoint<E extends Env = Env, M extend
448
448
  }>;
449
449
  }
450
450
 
451
+ /**
452
+ * Emit a dialect-correct case-insensitive substring-match SQL expression.
453
+ *
454
+ * Replaces the previous `LOWER(col) LIKE LOWER('%needle%') ESCAPE '\\'`
455
+ * approach: by using the native substring-position function for each
456
+ * dialect, the needle is never injected into a pattern, so LIKE
457
+ * wildcards (`%`, `_`) and the LIKE escape character lose their
458
+ * special meaning entirely — no wildcard surface means no escape
459
+ * needed.
460
+ *
461
+ * Dialect mapping:
462
+ * - `'sqlite'` → `INSTR(LOWER(col), LOWER(needle)) > 0`
463
+ * - `'pg'` → `POSITION(LOWER(needle) IN LOWER(col)) > 0`
464
+ * - `'mysql'` → `LOCATE(LOWER(needle), LOWER(col)) > 0`
465
+ *
466
+ * All three return a 1-based position (or 0 for "not found"), so
467
+ * `> 0` is the dialect-agnostic predicate that means "needle is a
468
+ * substring of col".
469
+ */
470
+ declare function substringMatch(col: Column | SQL, needle: string, dialect: DrizzleDialect): SQL;
451
471
  /**
452
472
  * Drizzle Upsert endpoint.
453
473
  * Creates a record if it doesn't exist, updates it if it does.
@@ -582,11 +602,12 @@ declare abstract class DrizzleAggregateEndpoint<E extends Env = Env, M extends M
582
602
  * Provides full-text search with relevance scoring and highlighting.
583
603
  *
584
604
  * For PostgreSQL, this can leverage native tsvector/tsquery for better performance.
585
- * For SQLite/MySQL, it falls back to LIKE-based searching with in-memory scoring.
605
+ * For SQLite/MySQL/PostgreSQL non-vector mode, it falls back to dialect-native
606
+ * substring-position search (INSTR/POSITION/LOCATE) with in-memory scoring.
586
607
  *
587
608
  * Features:
588
609
  * - PostgreSQL: Uses to_tsvector() and plainto_tsquery() for native full-text search
589
- * - SQLite/MySQL: Falls back to LIKE/ILIKE with in-memory scoring
610
+ * - Fallback: dialect-native substring match with in-memory scoring
590
611
  * - Configurable field weights
591
612
  * - Search modes: 'any' (OR), 'all' (AND), 'phrase' (exact)
592
613
  * - Highlighted snippets
@@ -608,12 +629,24 @@ declare abstract class DrizzleAggregateEndpoint<E extends Env = Env, M extends M
608
629
  declare abstract class DrizzleSearchEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends SearchEndpoint<E, M> {
609
630
  /** Drizzle database instance. Can be undefined if using context injection. */
610
631
  db?: DrizzleDatabase;
632
+ /**
633
+ * SQL dialect of the underlying Drizzle database.
634
+ *
635
+ * Drives the substring-match function emitted on the fallback search path:
636
+ * `INSTR` for sqlite, `POSITION` for pg, `LOCATE` for mysql. Set via
637
+ * {@link createDrizzleCrud}'s `options.dialect`, or override in your
638
+ * subclass. Defaults to `'sqlite'` for backward compatibility with
639
+ * pre-existing portable behavior.
640
+ *
641
+ * See {@link DrizzleUpsertEndpoint.dialect} for full semantics.
642
+ */
643
+ protected dialect: DrizzleDialect;
611
644
  /** Gets the database instance from property or context. */
612
645
  protected getDb(): DrizzleDatabase;
613
646
  /**
614
647
  * Enable PostgreSQL native full-text search.
615
648
  * When true and vectorColumn is set, uses tsvector/tsquery.
616
- * When false, uses LIKE-based search with in-memory scoring.
649
+ * When false, uses substring-position-based search with in-memory scoring.
617
650
  */
618
651
  protected useNativeSearch: boolean;
619
652
  /**
@@ -639,6 +672,12 @@ declare abstract class DrizzleSearchEndpoint<E extends Env = Env, M extends Meta
639
672
  declare abstract class DrizzleExportEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends ExportEndpoint<E, M> {
640
673
  /** Drizzle database instance. Can be undefined if using context injection. */
641
674
  db?: DrizzleDatabase;
675
+ /**
676
+ * SQL dialect of the underlying Drizzle database. Drives the
677
+ * substring-match function emitted on the `?search=` path. See
678
+ * {@link DrizzleUpsertEndpoint.dialect} for full semantics.
679
+ */
680
+ protected dialect: DrizzleDialect;
642
681
  /** Gets the database instance from property or context. */
643
682
  protected getDb(): DrizzleDatabase;
644
683
  protected getTable(): Table;
@@ -716,6 +755,7 @@ interface DrizzleCrudClasses<M extends MetaInput, E extends Env = Env> {
716
755
  List: ConfiguredDrizzleEndpoint<DrizzleListEndpoint<E, M>, M>;
717
756
  Restore: ConfiguredDrizzleEndpoint<DrizzleRestoreEndpoint<E, M>, M>;
718
757
  Upsert: ConfiguredDrizzleEndpoint<DrizzleUpsertEndpoint<E, M>, M>;
758
+ Search: ConfiguredDrizzleEndpoint<DrizzleSearchEndpoint<E, M>, M>;
719
759
  BatchCreate: ConfiguredDrizzleEndpoint<DrizzleBatchCreateEndpoint<E, M>, M>;
720
760
  BatchUpdate: ConfiguredDrizzleEndpoint<DrizzleBatchUpdateEndpoint<E, M>, M>;
721
761
  BatchDelete: ConfiguredDrizzleEndpoint<DrizzleBatchDeleteEndpoint<E, M>, M>;
@@ -947,4 +987,4 @@ declare function isDrizzleZodAvailable(): boolean;
947
987
  */
948
988
  declare const DrizzleAdapters: AdapterBundle;
949
989
 
950
- export { type CreateDrizzleCrudOptions, type Database, DrizzleAdapters, DrizzleAggregateEndpoint, DrizzleBatchCreateEndpoint, DrizzleBatchDeleteEndpoint, DrizzleBatchRestoreEndpoint, DrizzleBatchUpdateEndpoint, DrizzleBatchUpsertEndpoint, DrizzleCloneEndpoint, DrizzleCreateEndpoint, type DrizzleCrudClasses, type DrizzleDB, type DrizzleDatabase, type DrizzleDatabaseConstraint, DrizzleDeleteEndpoint, type DrizzleDialect, type DrizzleEnv, DrizzleExportEndpoint, DrizzleImportEndpoint, DrizzleListEndpoint, DrizzleReadEndpoint, DrizzleRestoreEndpoint, type DrizzleSchemas, DrizzleSearchEndpoint, DrizzleUpdateEndpoint, DrizzleUpsertEndpoint, DrizzleVersionCompareEndpoint, DrizzleVersionHistoryEndpoint, DrizzleVersionReadEndpoint, DrizzleVersionRollbackEndpoint, type QueryBuilder, batchLoadDrizzleRelations, buildWhereCondition, cast, createDrizzleCrud, createDrizzleSchemas, createInsertSchema, createSelectSchema, createUpdateSchema, getColumn, getTable, isDrizzleZodAvailable, loadDrizzleRelation, loadDrizzleRelations };
990
+ export { type CreateDrizzleCrudOptions, type Database, DrizzleAdapters, DrizzleAggregateEndpoint, DrizzleBatchCreateEndpoint, DrizzleBatchDeleteEndpoint, DrizzleBatchRestoreEndpoint, DrizzleBatchUpdateEndpoint, DrizzleBatchUpsertEndpoint, DrizzleCloneEndpoint, DrizzleCreateEndpoint, type DrizzleCrudClasses, type DrizzleDB, type DrizzleDatabase, type DrizzleDatabaseConstraint, DrizzleDeleteEndpoint, type DrizzleDialect, type DrizzleEnv, DrizzleExportEndpoint, DrizzleImportEndpoint, DrizzleListEndpoint, DrizzleReadEndpoint, DrizzleRestoreEndpoint, type DrizzleSchemas, DrizzleSearchEndpoint, DrizzleUpdateEndpoint, DrizzleUpsertEndpoint, DrizzleVersionCompareEndpoint, DrizzleVersionHistoryEndpoint, DrizzleVersionReadEndpoint, DrizzleVersionRollbackEndpoint, type QueryBuilder, batchLoadDrizzleRelations, buildWhereCondition, cast, createDrizzleCrud, createDrizzleSchemas, createInsertSchema, createSelectSchema, createUpdateSchema, getColumn, getTable, isDrizzleZodAvailable, loadDrizzleRelation, loadDrizzleRelations, substringMatch };
@@ -1 +1 @@
1
- export{I as DrizzleAdapters,x as DrizzleAggregateEndpoint,n as DrizzleBatchCreateEndpoint,p as DrizzleBatchDeleteEndpoint,q as DrizzleBatchRestoreEndpoint,o as DrizzleBatchUpdateEndpoint,s as DrizzleBatchUpsertEndpoint,B as DrizzleCloneEndpoint,h as DrizzleCreateEndpoint,k as DrizzleDeleteEndpoint,z as DrizzleExportEndpoint,A as DrizzleImportEndpoint,l as DrizzleListEndpoint,i as DrizzleReadEndpoint,m as DrizzleRestoreEndpoint,y as DrizzleSearchEndpoint,j as DrizzleUpdateEndpoint,r as DrizzleUpsertEndpoint,v as DrizzleVersionCompareEndpoint,t as DrizzleVersionHistoryEndpoint,u as DrizzleVersionReadEndpoint,w as DrizzleVersionRollbackEndpoint,f as batchLoadDrizzleRelations,g as buildWhereCondition,a as cast,C as createDrizzleCrud,G as createDrizzleSchemas,E as createInsertSchema,D as createSelectSchema,F as createUpdateSchema,c as getColumn,b as getTable,H as isDrizzleZodAvailable,d as loadDrizzleRelation,e as loadDrizzleRelations}from'../../chunk-WXIFQDJI.js';import'../../chunk-ZBCVLQ3W.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-XI7HT5ZM.js';import'../../chunk-NGUMNUOP.js';import'../../chunk-FC56WWPB.js';import'../../chunk-FJCWFB5L.js';import'../../chunk-KUFOENSK.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
+ export{J as DrizzleAdapters,y as DrizzleAggregateEndpoint,n as DrizzleBatchCreateEndpoint,p as DrizzleBatchDeleteEndpoint,q as DrizzleBatchRestoreEndpoint,o as DrizzleBatchUpdateEndpoint,t as DrizzleBatchUpsertEndpoint,C as DrizzleCloneEndpoint,h as DrizzleCreateEndpoint,k as DrizzleDeleteEndpoint,A as DrizzleExportEndpoint,B as DrizzleImportEndpoint,l as DrizzleListEndpoint,i as DrizzleReadEndpoint,m as DrizzleRestoreEndpoint,z as DrizzleSearchEndpoint,j as DrizzleUpdateEndpoint,s as DrizzleUpsertEndpoint,w as DrizzleVersionCompareEndpoint,u as DrizzleVersionHistoryEndpoint,v as DrizzleVersionReadEndpoint,x as DrizzleVersionRollbackEndpoint,f as batchLoadDrizzleRelations,g as buildWhereCondition,a as cast,D as createDrizzleCrud,H as createDrizzleSchemas,F as createInsertSchema,E as createSelectSchema,G as createUpdateSchema,c as getColumn,b as getTable,I as isDrizzleZodAvailable,d as loadDrizzleRelation,e as loadDrizzleRelations,r as substringMatch}from'../../chunk-DJOJGLOT.js';import'../../chunk-ZBCVLQ3W.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-XI7HT5ZM.js';import'../../chunk-NGUMNUOP.js';import'../../chunk-FC56WWPB.js';import'../../chunk-FJCWFB5L.js';import'../../chunk-KUFOENSK.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';
@@ -0,0 +1,4 @@
1
+ import {t,u,v,w,x,z as z$1,B as B$1,C,D as D$1,E,A as A$1,F as F$1,G,H as H$1,I as I$1,J as J$1,K as K$1,L as L$1,T,U as U$1,ba,ca,y}from'./chunk-ZBCVLQ3W.js';import {b as b$1}from'./chunk-DMGP7QDL.js';import {getTableColumns,eq,inArray,between,isNull,isNotNull,ilike,like,notInArray,lte,lt,gte,gt as gt$1,ne as ne$1,and,sql,or,desc,asc}from'drizzle-orm';import {z}from'zod';function X(a){return a}function f(a){if(!a.model.table)throw new Error(`Model ${a.model.tableName} does not have a table reference`);return a.model.table}function b(a,e){let t=getTableColumns(a),o=t[e];if(!o)throw new Error(`Column '${e}' not found in table. Available columns: ${Object.keys(t).join(", ")}`);return o}async function Pe(a,e,t,o){if(!o.table)return e;let n=o.table;switch(o.type){case "hasOne":{let r=o.localKey||"id",s=e[r];if(s==null)return e;let i=b(n,o.foreignKey),l=await a.select().from(n).where(eq(i,s)).limit(1);return {...e,[t]:l[0]||null}}case "hasMany":{let r=o.localKey||"id",s=e[r];if(s==null)return {...e,[t]:[]};let i=b(n,o.foreignKey),l=await a.select().from(n).where(eq(i,s));return {...e,[t]:l}}case "belongsTo":{let r=e[o.foreignKey];if(r==null)return {...e,[t]:null};let s=b(n,o.localKey||"id"),i=await a.select().from(n).where(eq(s,r)).limit(1);return {...e,[t]:i[0]||null}}default:return e}}async function le(a,e,t,o){if(!o?.relations?.length||!t.model.relations)return e;let n={...e};for(let r of o.relations){let s=t.model.relations[r];s&&(n=await Pe(a,n,r,s));}return n}async function S(a,e,t,o){if(!e.length||!o?.relations?.length||!t.model.relations)return e;let n=e.map(r=>({...r}));for(let r of o.relations){let s=t.model.relations[r];if(!s||!s.table)continue;let i=s.table;switch(s.type){case "hasOne":case "hasMany":{let l=s.localKey||"id",d=[...new Set(n.map(p=>p[l]).filter(p=>p!=null))];if(d.length===0){n=n.map(p=>({...p,[r]:s.type==="hasMany"?[]:null}));continue}let u=b(i,s.foreignKey),c=await a.select().from(i).where(inArray(u,d)),m=new Map;for(let p of c){let g=p[s.foreignKey];m.has(g)||m.set(g,[]),m.get(g).push(p);}n=n.map(p=>{let g=p[l],h=m.get(g)||[];return {...p,[r]:s.type==="hasMany"?h:h[0]||null}});break}case "belongsTo":{let l=s.localKey||"id",d=[...new Set(n.map(p=>p[s.foreignKey]).filter(p=>p!=null))];if(d.length===0){n=n.map(p=>({...p,[r]:null}));continue}let u=b(i,l),c=await a.select().from(i).where(inArray(u,d)),m=new Map;for(let p of c){let g=p[l];m.set(g,p);}n=n.map(p=>{let g=p[s.foreignKey];return {...p,[r]:m.get(g)||null}});break}}}return n}function O(a,e){let t=b(a,e.field);switch(e.operator){case "eq":return eq(t,e.value);case "ne":return ne$1(t,e.value);case "gt":return gt$1(t,e.value);case "gte":return gte(t,e.value);case "lt":return lt(t,e.value);case "lte":return lte(t,e.value);case "in":return inArray(t,e.value);case "nin":return notInArray(t,e.value);case "like":return like(t,e.value);case "ilike":return ilike(t,e.value);case "null":return e.value?isNull(t):isNotNull(t);case "between":{let[o,n]=e.value;return between(t,o,n)}default:return}}function D(a){let e=a;if(e._tx)return e._tx;if(e.db)return e.db;let t=e.context?.get?.("db");if(t)return t;throw new Error(`Database not configured. Either:
2
+ 1. Set db property: db = myDb;
3
+ 2. Use middleware: c.set("db", myDb);
4
+ 3. Use factory: createDrizzleCrud(db, meta)`)}var _=class extends t{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getRelatedTable(e){return e.table}async create(e,t){let o=t??this.getDb(),n=this.getTable(),r=this.applyManagedInsertFields(e,"drizzle");return (await o.insert(n).values(r).returning())[0]}async createNested(e,t,o,n,r){let s=r??this.getDb(),i=this.getRelatedTable(o);if(!i)return b$1().warn(`Related table not found for ${t}. Add 'table' to the relation config.`),[];let l=Array.isArray(n)?n:[n],d=[];for(let u of l){if(typeof u!="object"||u===null)continue;let c={...u,id:crypto.randomUUID(),[o.foreignKey]:e},m=await s.insert(i).values(c).returning();m[0]&&d.push(m[0]);}return d}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 u{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async read(e,t,o){let n=this.getTable(),r=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),i=[eq(r,e)];if(t)for(let[u,c]of Object.entries(t))i.push(eq(this.getColumn(u),c));s.enabled&&i.push(isNull(this.getColumn(s.field)));let l=await this.getDb().select().from(n).where(and(...i)).limit(1);return l[0]?await le(this.getDb(),l[0],this._meta,o):null}},P=class extends v{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}getRelatedTable(e){return e.table}async findExisting(e,t,o){let n=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return i.enabled&&l.push(isNull(this.getColumn(i.field))),(await n.select().from(r).where(and(...l)).limit(1))[0]||null}async update(e,t,o,n){let r=n??this.getDb(),s=this.getTable(),i=this.getColumn(this.lookupField),l=this.getSoftDeleteConfig(),d=[eq(i,e)];if(o)for(let[c,m]of Object.entries(o))d.push(eq(this.getColumn(c),m));return l.enabled&&d.push(isNull(this.getColumn(l.field))),(await r.update(s).set(this.applyManagedUpdateFields(t)).where(and(...d)).returning())[0]||null}async processNestedWrites(e,t,o,n,r){let s=r??this.getDb(),i=this.getRelatedTable(o);if(!i)return b$1().warn(`Related table not found for ${t}. Add 'table' to the relation config.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]};let l={created:[],updated:[],deleted:[],connected:[],disconnected:[]},d=b(i,o.foreignKey),u=b(i,"id");if(n.create){let c=Array.isArray(n.create)?n.create:[n.create];for(let m of c){if(typeof m!="object"||m===null)continue;let p={...m,id:crypto.randomUUID(),[o.foreignKey]:e},g=await s.insert(i).values(p).returning();g[0]&&l.created.push(g[0]);}}if(n.update)for(let c of n.update){if(!c.id||!(await s.select().from(i).where(and(eq(u,c.id),eq(d,e))).limit(1))[0])continue;let{id:p,...g}=c,h=await s.update(i).set(g).where(eq(u,p)).returning();h[0]&&l.updated.push(h[0]);}if(n.delete)for(let c of n.delete)(await s.delete(i).where(and(eq(u,c),eq(d,e))).returning())[0]&&l.deleted.push(c);if(n.connect)for(let c of n.connect)(await s.update(i).set({[o.foreignKey]:e}).where(eq(u,c)).returning())[0]&&l.connected.push(c);if(n.disconnect)for(let c of n.disconnect)(await s.update(i).set({[o.foreignKey]:null}).where(and(eq(u,c),eq(d,e))).returning())[0]&&l.disconnected.push(c);return l}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 w{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}getRelatedTable(e){return e.table}async findForDelete(e,t,o){let n=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return i.enabled&&l.push(isNull(this.getColumn(i.field))),(await n.select().from(r).where(and(...l)).limit(1))[0]||null}async delete(e,t,o){let n=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[d,u]of Object.entries(t))l.push(eq(this.getColumn(d),u));return i.enabled&&l.push(isNull(this.getColumn(i.field))),i.enabled?(await n.update(r).set({[i.field]:new Date}).where(and(...l)).returning())[0]||null:(await n.delete(r).where(and(...l)).returning())[0]||null}async countRelated(e,t,o,n){let r=n??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=b(s,o.foreignKey),l=await r.select({count:sql`count(*)`}).from(s).where(eq(i,e));return Number(l[0]?.count)||0}async deleteRelated(e,t,o,n){let r=n??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=b(s,o.foreignKey);return (await r.delete(s).where(eq(i,e)).returning()).length}async nullifyRelated(e,t,o,n){let r=n??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=b(s,o.foreignKey);return (await r.update(s).set({[o.foreignKey]:null}).where(eq(i,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()}},B=class extends x{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async list(e){let t=this.getTable(),o=[],n=this.getSoftDeleteConfig();if(n.enabled){let y=this.getColumn(n.field);e.options.onlyDeleted?o.push(isNotNull(y)):e.options.withDeleted||o.push(isNull(y));}for(let y of e.filters){let R=O(t,y);R&&o.push(R);}if(e.options.search&&this.searchFields.length>0){let y=this.searchFields.map(R=>{let $=this.getColumn(R);return sql`LOWER(${$}) LIKE LOWER(${`%${e.options.search}%`})`});o.push(or(...y));}let r=o.length>0?and(...o):void 0,s=this.getDb(),i=await s.select({count:sql`count(*)`}).from(t).where(r),l=Number(i[0]?.count)||0,d=s.select().from(t).where(r);if(e.options.order_by){let y=this.getColumn(e.options.order_by),R=e.options.order_by_direction==="desc"?desc:asc;d=d.orderBy(R(y));}let u=e.options.page||1,c=e.options.per_page||this.defaultPerPage;d=d.limit(c).offset((u-1)*c);let m=await d,p={relations:e.options.include||[]},g=await S(this.getDb(),m,this._meta,p),h=Math.ceil(l/c);return {result:g,result_info:{page:u,per_page:c,total_count:l,total_pages:h,has_next_page:u<h,has_prev_page:u>1}}}},L=class extends z$1{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async restore(e,t,o){let n=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return l.push(isNotNull(this.getColumn(i.field))),(await n.update(r).set({[i.field]:null}).where(and(...l)).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 A=class extends B$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}async batchCreate(e){let t=this.getTable(),o=e.map(r=>this.applyManagedInsertFields(r,"drizzle"));return await this.getDb().insert(t).values(o).returning()}},K=class extends C{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async batchUpdate(e){let t=this.getTable(),o=this.getColumn(this.lookupField),n=this.getSoftDeleteConfig(),r=[],s=[];for(let i of e){let l=[eq(o,i.id)];n.enabled&&l.push(isNull(this.getColumn(n.field)));let d=await this.getDb().update(t).set(this.applyManagedUpdateFields(i.data)).where(and(...l)).returning();d[0]?r.push(d[0]):s.push(i.id);}return {updated:r,notFound:s}}},Z=class extends D$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async batchDelete(e){let t=this.getTable(),o=this.getColumn(this.lookupField),n=this.getSoftDeleteConfig(),r=[inArray(o,e)];n.enabled&&r.push(isNull(this.getColumn(n.field)));let s;n.enabled?s=await this.getDb().update(t).set({[n.field]:new Date}).where(and(...r)).returning():s=await this.getDb().delete(t).where(and(...r)).returning();let i=s,l=new Set(i.map(u=>String(u[this.lookupField]))),d=e.filter(u=>!l.has(u));return {deleted:i,notFound:d}}},F=class extends E{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async batchRestore(e){let t=this.getTable(),o=this.getColumn(this.lookupField),n=this.getSoftDeleteConfig(),r=[inArray(o,e),isNotNull(this.getColumn(n.field))],i=await this.getDb().update(t).set({[n.field]:null}).where(and(...r)).returning(),l=new Set(i.map(u=>String(u[this.lookupField]))),d=e.filter(u=>!l.has(u));return {restored:i,notFound:d}}};function $e(a,e,t){switch(t){case "pg":return sql`POSITION(LOWER(${e}) IN LOWER(${a})) > 0`;case "mysql":return sql`LOCATE(LOWER(${e}), LOWER(${a})) > 0`;default:return sql`INSTR(LOWER(${a}), LOWER(${e})) > 0`}}function gt(a){return a.split(/\s+/).filter(e=>e.length>0)}var Q=class extends A$1{db;dialect="sqlite";getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async findExisting(e){let t=this.getTable(),o=this.getUpsertKeys(),n=this.getSoftDeleteConfig(),r=[];for(let i of o){let l=e[i];l!==void 0&&r.push(eq(this.getColumn(i),l));}return n.enabled&&r.push(isNull(this.getColumn(n.field))),r.length===0?null:(await this.getDb().select().from(t).where(and(...r)).limit(1))[0]||null}async create(e){let t=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(o).returning())[0]}async update(e,t){let o=this.getTable(),n=this._meta.model.primaryKeys[0],r=e[n];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(n),r)).returning())[0]}async nativeUpsert(e,t){let o=this.getTable(),n=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=this.getSoftDeleteConfig(),i=this.getTimestampsConfig(),l=this.applyManagedInsertFields(e,"drizzle"),d={};for(let[h,y]of Object.entries(e))!n.includes(h)&&h!==r&&(this.createOnlyFields?.includes(h)||(d[h]=y));i.enabled&&(d[i.updatedAt]=Date.now());let u=n.map(h=>this.getColumn(h)),c;s.enabled&&(c=isNull(this.getColumn(s.field)));let m=Object.keys(d).length>0?d:{[r]:sql`${this.getColumn(r)}`},p=this.getDb().insert(o).values(l);return this.dialect==="mysql"?{data:(await p.onDuplicateKeyUpdate({set:m}).returning())[0],created:false}:{data:(await p.onConflictDoUpdate({target:u,set:m,where:c}).returning())[0],created:false}}},N=class extends F$1{db;dialect="sqlite";getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async findExisting(e){let t=this.getTable(),o=this.getUpsertKeys(),n=[];for(let s of o){let i=e[s];i!==void 0&&n.push(eq(this.getColumn(s),i));}return n.length===0?null:(await this.getDb().select().from(t).where(and(...n)).limit(1))[0]||null}async create(e){let t=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(o).returning())[0]}async update(e,t){let o=this.getTable(),n=this._meta.model.primaryKeys[0],r=e[n];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(n),r)).returning())[0]}async nativeBatchUpsert(e,t){if(e.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let o=this.getTable(),n=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=this.getTimestampsConfig(),i=e.map(g=>this.applyManagedInsertFields(g,"drizzle")),l={},d=e[0];for(let g of Object.keys(d))!n.includes(g)&&g!==r&&(this.createOnlyFields?.includes(g)||(l[g]=sql`excluded.${sql.identifier(g)}`));s.enabled&&(l[s.updatedAt]=Date.now());let u=n.map(g=>this.getColumn(g)),c=Object.keys(l).length>0?l:{[r]:sql`${this.getColumn(r)}`},m=this.getDb().insert(o).values(i),p=await(this.dialect==="mysql"?m.onDuplicateKeyUpdate({set:c}):m.onConflictDoUpdate({target:u,set:c})).returning();return {items:p.map((g,h)=>({data:g,created:false,index:h})),createdCount:0,updatedCount:p.length,totalCount:p.length}}},Ae=class extends G{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async recordExists(e){let t=this.getTable(),o=await this.getDb().select({count:sql`count(*)`}).from(t).where(eq(this.getColumn("id"),e));return Number(o[0]?.count)>0}},Ke=class extends H$1{},Ze=class extends I$1{},Fe=class extends J$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async rollback(e,t,o){let n=this.getTable(),r=this.getVersioningConfig().field;return (await this.getDb().update(n).set({...t,[r]:o}).where(eq(this.getColumn("id"),e)).returning())[0]}},H=class extends K$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async aggregate(e){let t=this.getTable(),o=[],n=this.getSoftDeleteConfig();if(n.enabled){let{query:i}=await this.getValidatedData();i?.withDeleted===true||i?.withDeleted==="true"||o.push(isNull(this.getColumn(n.field)));}if(e.filters)for(let[i,l]of Object.entries(e.filters))if(typeof l=="object"&&l!==null)for(let[d,u]of Object.entries(l)){let c=O(t,{field:i,operator:d,value:u});c&&o.push(c);}else o.push(eq(this.getColumn(i),l));let r=o.length>0?and(...o):void 0,s=await this.getDb().select().from(t).where(r);return L$1(s,e)}},q=class extends T{db;dialect="sqlite";getDb(){return D(this)}useNativeSearch=false;vectorColumn;vectorConfig="english";getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async search(e,t){let o=this.getTable(),n=[],r=this.getSoftDeleteConfig();r.enabled&&(t.options.onlyDeleted?n.push(isNotNull(this.getColumn(r.field))):t.options.withDeleted||n.push(isNull(this.getColumn(r.field))));for(let w of t.filters){let M=O(o,w);M&&n.push(M);}let s=this.getSearchableFields(),i=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(" | ")})`;n.push(sql`${w} @@ ${M}`);}else {let w=(M,x)=>{try{let re=this.getColumn(M);return $e(sql`CAST(${re} AS TEXT)`,x,this.dialect)}catch{return}};if(e.mode==="all"){let M=gt(e.query);if(M.length>0){let x=[];for(let re of M){let ue=i.map(se=>w(se,re)).filter(se=>se!==void 0);ue.length>0&&x.push(or(...ue));}x.length>0&&n.push(and(...x));}}else {let M=i.map(x=>w(x,e.query)).filter(x=>x!==void 0);M.length>0&&n.push(or(...M));}}let l=n.length>0?and(...n):void 0,d=await this.getDb().select({count:sql`count(*)`}).from(o).where(l),u=Number(d[0]?.count)||0,c=this.getDb().select().from(o).where(l);if(t.options.order_by){let w=this.getColumn(t.options.order_by),M=t.options.order_by_direction==="desc"?desc:asc;c=c.orderBy(M(w));}let m=t.options.page||1,p=t.options.per_page||this.defaultPerPage;c=c.limit(p).offset((m-1)*p);let g=await c,h=e.mode==="all"?{...e,mode:"any"}:e,y=U$1(g,h,s),R={relations:t.options.include||[]},$=y.map(w=>w.item),Xe=await S(this.getDb(),$,this._meta,R);return {items:y.map((w,M)=>({...w,item:Xe[M]})),totalCount:u}}},J=class extends ba{db;dialect="sqlite";getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async list(e){let t=this.getTable(),o=[],n=this.getSoftDeleteConfig();if(n.enabled){let h=this.getColumn(n.field);e.options.onlyDeleted?o.push(isNotNull(h)):e.options.withDeleted||o.push(isNull(h));}for(let h of e.filters){let y=O(t,h);y&&o.push(y);}if(e.options.search&&this.searchFields.length>0){let h=e.options.search,y=this.searchFields.map(R=>{let $=this.getColumn(R);return $e($,h,this.dialect)});o.push(or(...y));}let r=o.length>0?and(...o):void 0,s=await this.getDb().select({count:sql`count(*)`}).from(t).where(r),i=Number(s[0]?.count)||0,l=this.getDb().select().from(t).where(r);if(e.options.order_by){let h=this.getColumn(e.options.order_by),y=e.options.order_by_direction==="desc"?desc:asc;l=l.orderBy(y(h));}let d=e.options.page||1,u=e.options.per_page||this.defaultPerPage;l=l.limit(u).offset((d-1)*u);let c=await l,m={relations:e.options.include||[]},p=await S(this.getDb(),c,this._meta,m),g=Math.ceil(i/u);return {result:p,result_info:{page:d,per_page:u,total_count:i,total_pages:g,has_next_page:d<g,has_prev_page:d>1}}}},Y=class extends ca{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async findExisting(e){let t=this.getTable(),o=this.getUpsertKeys(),n=this.getSoftDeleteConfig(),r=[];for(let i of o){let l=e[i];l!==void 0&&r.push(eq(this.getColumn(i),l));}return n.enabled&&r.push(isNull(this.getColumn(n.field))),r.length===0?null:(await this.getDb().select().from(t).where(and(...r)).limit(1))[0]||null}async create(e){let t=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(o).returning())[0]}async update(e,t){let o=this.getTable(),n=this._meta.model.primaryKeys[0],r=e[n];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(n),r)).returning())[0]}},ee=class extends y{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}generateId(){return crypto.randomUUID()}async findSource(e,t){let o=this.getTable(),n=this.getColumn(this.lookupField),r=this.getSoftDeleteConfig(),s=[eq(n,e)];if(t)for(let[l,d]of Object.entries(t))s.push(eq(this.getColumn(l),d));r.enabled&&s.push(isNull(this.getColumn(r.field)));let i=await this.getDb().select().from(o).where(and(...s)).limit(1);return i[0]?i[0]:null}async createClone(e){let t=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle",()=>this.generateId());return (await this.getDb().insert(t).values(o).returning())[0]}};function an(a,e,t){let o=t?.dialect??"sqlite";return {Create:class extends _{_meta=e;db=a},Read:class extends I{_meta=e;db=a},Update:class extends P{_meta=e;db=a},Delete:class extends U{_meta=e;db=a},List:class extends B{_meta=e;db=a},Restore:class extends L{_meta=e;db=a},Upsert:class extends Q{_meta=e;db=a;dialect=o},Search:class extends q{_meta=e;db=a;dialect=o},BatchCreate:class extends A{_meta=e;db=a},BatchUpdate:class extends K{_meta=e;db=a},BatchDelete:class extends Z{_meta=e;db=a},BatchRestore:class extends F{_meta=e;db=a},BatchUpsert:class extends N{_meta=e;db=a;dialect=o}}}var ne=null,We=false,te=null;async function oe(){if(We){if(te)throw te;return ne}We=true;try{return ne=await import('drizzle-zod'),ne}catch{throw te=new Error("drizzle-zod is not installed. Please install it: npm install drizzle-zod"),te}}async function mt(a,e){return (await oe()).createSelectSchema(a,e)}async function bt(a,e){return (await oe()).createInsertSchema(a,e)}async function ht(a,e){let t=await oe();return t.createUpdateSchema?t.createUpdateSchema(a,e):t.createInsertSchema(a,e).partial()}async function ft(a,e){let t=await oe(),o=e?.coerceDates!==false,n=o?Mt(a):new Set,r=t.createSelectSchema(a,e?.selectRefine),s=t.createInsertSchema(a,e?.insertRefine),i;return t.createUpdateSchema?i=t.createUpdateSchema(a,e?.updateRefine):i=t.createInsertSchema(a,e?.updateRefine).partial(),o&&n.size>0&&(s=Ve(s,n),i=Ve(i,n)),{select:r,insert:s,update:i}}function zt(){return ne!==null}var Dt=z.preprocess(a=>{if(a instanceof Date)return a;if(typeof a=="string"){let e=new Date(a);if(!isNaN(e.getTime()))return e}return a},z.date()),yt=z.preprocess(a=>{if(a==null)return null;if(a instanceof Date)return a;if(typeof a=="string"){let e=new Date(a);if(!isNaN(e.getTime()))return e}return a},z.date().nullable());function Mt(a){let e=new Set,t=a;for(let[o,n]of Object.entries(t)){if(o==="_"||o==="$inferInsert"||o==="$inferSelect")continue;let r=n;if(!r||typeof r!="object")continue;let s=String(r.dataType??"").toLowerCase(),i=String(r.columnType??"").toLowerCase(),l=r.config,d=String(l?.dataType??"").toLowerCase();(s.includes("timestamp")||s.includes("date")||s.includes("datetime")||i.includes("pgtimestamp")||i.includes("pgdate")||i.includes("mysqltimestamp")||i.includes("mysqldate")||i.includes("sqlitetimestamp")||d.includes("timestamp")||d.includes("date"))&&e.add(o);}return e}function Ve(a,e){if(e.size===0)return a;let t=a.shape,o={};for(let[n,r]of Object.entries(t))if(e.has(n)){let s=r.isOptional?.()??false,i=r.isNullable?.()??false,l=Dt;(i||s)&&(l=yt),s&&(l=l.optional()),o[n]=l;}else o[n]=r;return z.object(o)}var xn={CreateEndpoint:_,ListEndpoint:B,ReadEndpoint:I,UpdateEndpoint:P,DeleteEndpoint:U,RestoreEndpoint:L,BatchCreateEndpoint:A,BatchUpdateEndpoint:K,BatchDeleteEndpoint:Z,BatchRestoreEndpoint:F,BatchUpsertEndpoint:N,SearchEndpoint:q,AggregateEndpoint:H,ExportEndpoint:J,ImportEndpoint:Y,UpsertEndpoint:Q,CloneEndpoint:ee};export{J as A,Y as B,ee as C,an as D,mt as E,bt as F,ht as G,ft as H,zt as I,xn as J,X as a,f as b,b as c,Pe as d,le as e,S as f,O as g,_ as h,I as i,P as j,U as k,B as l,L as m,A as n,K as o,Z as p,F as q,$e as r,Q as s,N as t,Ae as u,Ke as v,Ze as w,Fe as x,H as y,q as z};
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- export{I as DrizzleAdapters}from'./chunk-WXIFQDJI.js';import {r,s,A as A$1,z as z$1,q as q$1,p,o,n,m,l,x,y as y$1,j as j$1,i,h,k,g}from'./chunk-BXWKFJXP.js';export{a as BulkPatchEndpoint}from'./chunk-BXWKFJXP.js';export{y as PrismaAdapters}from'./chunk-FOTF3T22.js';export{K as AggregateEndpoint,B as BatchCreateEndpoint,D as BatchDeleteEndpoint,E as BatchRestoreEndpoint,C as BatchUpdateEndpoint,F as BatchUpsertEndpoint,y as CloneEndpoint,t as CreateEndpoint,w as DeleteEndpoint,ba as ExportEndpoint,ca as ImportEndpoint,x as ListEndpoint,u as ReadEndpoint,z as RestoreEndpoint,T as SearchEndpoint,v as UpdateEndpoint,A as UpsertEndpoint,I as VersionCompareEndpoint,G as VersionHistoryEndpoint,H as VersionReadEndpoint,J as VersionRollbackEndpoint,r as applyFieldSelection,s as applyFieldSelectionToArray,c as applyManagedInsertFields,d as applyManagedUpdateFields,e as assertIdStrategySupported,S as buildSearchConfig,P as calculateScore,g as causeChain,L as computeAggregations,X as createCsvStream,aa as csvToJson,V as escapeCsvValue,W as generateCsv,j as generateETag,Q as generateHighlights,b as getManagedInputExclusions,p as getSchemaFields,a as getTimestampsConfig,_ as inferCsvContentType,$ as jsonToCsv,h as mapUniqueViolation,l as matchesIfMatch,k as matchesIfNoneMatch,Y as parseCsv,q as parseFieldSelection,n as parseFilterValue,o as parseListFilters,R as parseSearchFields,i as rethrowAsConstraintError,U as searchInMemory,f as stripManagedInsertFields,O as termFrequency,M as tokenize,N as tokenizeQuery,Z as validateCsvHeaders}from'./chunk-ZBCVLQ3W.js';export{a as createHealthEndpoints,b as createHealthHandler}from'./chunk-XH7DEPW2.js';export{a as MemoryIdempotencyStorage}from'./chunk-FXIMMYFV.js';export{a as MemoryLoggingStorage}from'./chunk-3UHTK7SB.js';export{a as multiTenant}from'./chunk-L4X7KFWN.js';export{c as KVRateLimitStorage,a as MemoryRateLimitStorage,b as RedisRateLimitStorage}from'./chunk-EWKQ6BPV.js';import'./chunk-BJTWQHEV.js';export{a as applyProfile,b as applyProfileToArray,e as createArraySerializer,d as createSerializer,c as resolveProfile}from'./chunk-SDNXN7M5.js';export{g as createAPIKeyStorageMiddleware,e as createAuditStorageMiddleware,d as createCacheStorageMiddleware,c as createLoggingStorageMiddleware,b as createRateLimitStorageMiddleware,a as createStorageMiddleware,f as createVersioningStorageMiddleware}from'./chunk-R3WESU6C.js';export{a as scalarUI,e as setupDocs,f as setupDocsIndex,d as setupReDoc,b as setupScalar,c as setupSwaggerUI}from'./chunk-SPICOFUM.js';export{a as apiVersion,b as getApiVersion,c as getApiVersionConfig,d as versionedResponse}from'./chunk-KKLMXJY4.js';export{o as AuthenticatedEndpoint,a as JWTClaimsSchema,j as createAPIKeyMiddleware,l as createAuthMiddleware,e as createJWTMiddleware,g as decodeJWT,i as defaultHashAPIKey,m as optionalAuth,b as parseJWTClaims,n as requireAuthentication,c as safeParseJWTClaims,k as validateAPIKey,h as validateAPIKeyEntry,d as validateJWTClaims,f as verifyJWT,p as withAuth}from'./chunk-7ZUZICKI.js';import {a as a$1,c}from'./chunk-XI7HT5ZM.js';export{e as MemoryApprovalStorage,b as OpenAPIRoute,f as POLICIES_CONTEXT_KEY,n as allOf,q as allowAll,o as anyOf,p as denyAll,c as isRouteClass,d as parseIso8601Duration,h as requireAllRoles,j as requireAnyPermission,t as requireApproval,k as requireAuth,r as requireAuthenticated,l as requireOwnership,m as requireOwnershipOrRole,i as requirePermissions,s as requirePolicy,g as requireRoles}from'./chunk-XI7HT5ZM.js';export{b as KVCacheStorage,a as RedisCacheStorage}from'./chunk-H3H65KZF.js';import {T}from'./chunk-UANCAA7V.js';export{C as MemoryCacheStorage,m as RateLimitExceededException,y as createInvalidationPattern,V as createLoggingMiddleware,v as createRateLimitMiddleware,z as createRelatedPatterns,p as extractAPIKey,f as extractClientIp,g as extractHeaders,n as extractIP,k as extractLoggingUserId,h as extractQuery,o as extractUserId,x as generateCacheKey,s as generateKey,l as generateRequestId,E as getCacheStorage,Q as getErrorMessage,S as getLoggingStorage,u as getRateLimitStorage,T as getRequestId,U as getRequestStartTime,j as isAllowedContentType,d as matchLoggingPath,q as matchPath,A as matchesPattern,B as parseCacheKey,c as redactHeaders,b as redactObject,w as resetRateLimit,M as resolveAPIKeyStorage,K as resolveAuditStorage,J as resolveCacheStorage,N as resolveIdempotencyStorage,I as resolveLoggingStorage,H as resolveRateLimitStorage,L as resolveVersioningStorage,D as setCacheStorage,R as setLoggingStorage,t as setRateLimitStorage,e as shouldExcludePath,a as shouldRedact,r as shouldSkipPath,O as toError,i as truncateBody,F as withCache,G as withCacheInvalidation,P as wrapError}from'./chunk-UANCAA7V.js';export{a as MemoryVersioningStorage,e as VersionManager,f as createVersionManager,d as getVersioningStorage,c as setVersioningStorage}from'./chunk-NGUMNUOP.js';export{c as getIdempotencyStorage,d as idempotency,b as setIdempotencyStorage}from'./chunk-GF2EC5G4.js';export{c as MemoryAPIKeyStorage,d as generateAPIKey,h as getAPIKeyStorage,e as hashAPIKey,f as isValidAPIKeyFormat,i as setAPIKeyStorage}from'./chunk-2M5BM4VD.js';import {a,b}from'./chunk-FC56WWPB.js';export{g as AggregationException,a as ApiException,h as CacheException,i as ConfigurationException,d as ConflictException,f as ForbiddenException,b as InputValidationException,c as NotFoundException,e as UnauthorizedException}from'./chunk-FC56WWPB.js';export{e as AuditLogger,a as MemoryAuditLogStorage,f as createAuditLogger,d as getAuditStorage,c as setAuditStorage}from'./chunk-FJCWFB5L.js';import {q as q$2}from'./chunk-KUFOENSK.js';export{q as RESPONSE_ENVELOPE_CONTEXT_KEY,j as applyComputedFields,k as applyComputedFieldsToArray,f as calculateChanges,b as decodeCursor,m as defineMeta,l as defineModel,a as encodeCursor,c as extractNestedData,p as extractTenantId,e as getAuditConfig,o as getMultiTenantConfig,n as getSoftDeleteConfig,g as getVersioningConfig,d as isDirectNestedData,h as parseAggregateField,i as parseAggregateQuery,r as parseSearchMode}from'./chunk-KUFOENSK.js';export{a as StorageRegistry,b as createNullableRegistry,c as createRegistryWithDefault}from'./chunk-GBQQ3YQX.js';import'./chunk-CCGZ5UPB.js';export{f as StaticKeyProvider,e as decryptFields,b as decryptValue,d as encryptFields,a as encryptValue,c as isEncryptedValue}from'./chunk-QRXEQTNE.js';export{a as registerWebhooks}from'./chunk-7DDNX2F2.js';import {d as d$1}from'./chunk-QXFY6NYI.js';export{a as CrudEventEmitter,b as getEventEmitter,d as resolveEventEmitter,c as setEventEmitter}from'./chunk-QXFY6NYI.js';import {b as b$1}from'./chunk-DMGP7QDL.js';export{b as getLogger,a as setLogger}from'./chunk-DMGP7QDL.js';export{e as getAuthType,b as getUser,a as getUserId,d as getUserPermissions,c as getUserRoles,j as hasAllPermissions,h as hasAllRoles,i as hasAnyRole,g as hasPermission,f as hasRole}from'./chunk-MDHMZPXK.js';import {b as b$2}from'./chunk-VJRDAVID.js';export{c as getContextRequestId,a as getContextVar,d as getTenantId,b as setContextVar}from'./chunk-VJRDAVID.js';import {OpenAPIHono,createRoute}from'@hono/zod-openapi';import {z,ZodError}from'zod';import {HTTPException}from'hono/http-exception';import {streamSSE}from'hono/streaming';var pe=new WeakMap;function V(o){return pe.get(o)}var P=class{app;options;routes=new Map;constructor(e,n={}){this.app=e,this.options={docs_url:"/docs",redoc_url:"/redoc",openapi_url:"/openapi.json",...n};}registerRoute(e,n,t,r=[]){let m=`${e.toUpperCase()} ${n}`,f=t,c=new f().getSchema();this.routes.set(m,{method:e,path:n,schema:c,routeClass:t});let i=createRoute({method:e,path:this.convertPath(n),...c,responses:c.responses||{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}});if(r.length>0)for(let u of r)this.app.use(n,async(a,s)=>{if(a.req.method.toLowerCase()===e)return u(a,s);await s();});this.app.openapi(i,async u=>{let a$2=new f;a$2.setContext(u);try{return await a$2.handle()}catch(s){if(s instanceof a){let p=s.toJSON(),g=u?.var?.[q$2];return g?a$1(u,g.error(p.error),s.status):a$1(u,p,s.status)}throw s}});}convertPath(e){return e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}setupDocs(e,n){let t=e??this.options.openapi_url??"/openapi.json";this.app.doc(t,{openapi:n.openapi||"3.1.0",info:n.info,servers:n.servers,security:n.security});}getApp(){return this.app}getRegisteredRoutes(){return this.routes}toOpenApiPath(e){return this.convertPath(e)}};function qr(o=new OpenAPIHono,e={}){let n="openAPIRegistry"in o?o:new OpenAPIHono,t=new P(n,e),r=["get","post","put","patch","delete","options","head"],m=new Proxy(n,{get(f,h){if(r.includes(h))return (i,...u)=>{let a=u[u.length-1];if(c(a)){let s=u.slice(0,-1);return t.registerRoute(h,i,a,s),m}return f[h](i,...u)};if(h==="doc")return (i,u)=>{t.setupDocs(i,u);};if(h==="use")return (...i)=>(f[h](...i),m);let c$1=f[h];return typeof c$1=="function"?c$1.bind(f):c$1}});return pe.set(m,t),m}var $r=6e4,Gr={openapi:"3.1.0",info:{title:"API",version:"1.0.0"}};async function Jr(o,e,n={}){let t=V(o);if(!t)throw new Error("buildPerTenantOpenApi: app was not produced by fromHono(...). Cannot find route registry.");let r=n.config??Gr,m=`openapi:${e.tenantId??"global"}:${r.info.version}`;if(n.cache){let i=await n.cache.get(m);if(i!=null)return i}let f=new OpenAPIHono;for(let i of t.getRegisteredRoutes().values()){let u=i.routeClass,a=new u,s=Yr(e);a.setContext(s),typeof a.resolveModelSchema=="function"&&await a.resolveModelSchema();let p=a.getSchema(),g=createRoute({...p,method:i.method,path:t.toOpenApiPath(i.path),responses:p.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});f.openapi(g,()=>new Response);}let h={openapi:r.openapi??"3.1.0",info:r.info,servers:r.servers,security:r.security},c=n.spec==="3.0"?f.getOpenAPIDocument(h):f.getOpenAPI31Document(h);return n.cache&&await n.cache.set(m,c,n.cacheTtlMs??$r),c}function Yr(o){let e={};o.tenantId!==void 0&&(e.tenantId=o.tenantId),o.organizationId!==void 0&&(e.organizationId=o.organizationId);let n=o.request??new Request("http://localhost/");return {var:e,env:o.env,req:{raw:n,header:()=>{},query:()=>{},param:()=>{}},set(t,r){e[t]=r;},get(t){return e[t]},executionCtx:void 0}}function Xr(o){return {async get(e){let n=await o.get(e);return n?n.data:void 0},async set(e,n,t){let r=t?Math.ceil(t/1e3):void 0;await o.set(e,n,r?{ttl:r}:void 0);}}}var oa=[["create","post",""],["list","get",""],["batchCreate","post","/batch"],["batchUpdate","patch","/batch"],["batchDelete","delete","/batch"],["batchRestore","post","/batch/restore"],["batchUpsert","post","/batch/upsert"],["search","get","/search"],["aggregate","get","/aggregate"],["export","get","/export"],["import","post","/import"],["upsert","post","/upsert"],["read","get","/:id"],["update","patch","/:id"],["delete","delete","/:id"],["restore","post","/:id/restore"],["clone","post","/:id/clone"]];function na(o){return o.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}function ra(o,e){let t=`/${o}/${e}`.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function aa(o,e={}){let n=e.basePath??"",t=e.tag,r=new OpenAPIHono,m=0;for(let[c,i,u]of oa){let a=o[c];if(!a)continue;let p=new a().getSchema(),g=t!==void 0?{...p,tags:[t]}:p,M=ra(n,na(u)),w=createRoute({...g,method:i,path:M,responses:g.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});r.openapi(w,()=>new Response),m+=1;}return m===0?{}:r.getOpenAPI31Document({openapi:"3.1.0",info:{title:"hono-crud",version:"1.0.0"}}).paths??{}}var ce=o=>{if(o instanceof ZodError)return b.fromZodError(o)};function da(o={}){let{mappers:e=[],hooks:n=[],includeRequestId:t=true,includeStackTrace:r=false,defaultErrorCode:m="INTERNAL_ERROR",defaultErrorMessage:f="An internal error occurred",logUnmappedErrors:h=true,onHookError:c,responseEnvelope:i}=o,u=[...e,ce];return async(a$2,s)=>{let p,g=false;if(a$2 instanceof a)p=a$2,g=true;else if(a$2 instanceof HTTPException)p=new a(a$2.message,a$2.status,"HTTP_ERROR"),g=true;else {for(let l of u)try{let k=await l(a$2,s);if(k){p=k,g=!0;break}}catch{}g||(h&&b$1().error("Unmapped error",{error:a$2 instanceof Error?a$2.message:String(a$2)}),p=new a(f,500,m));}for(let l of n)try{let k=l(a$2,s,p);k instanceof Promise&&k.catch(B=>{c&&c(B,a$2,s);});}catch(k){c&&c(k,a$2,s);}let M=p.toJSON();if(t){let l=T(s);l&&(M.error.requestId=l);}r&&a$2.stack&&(M.error.stack=a$2.stack);let w=ue(s,i),C=w?w.error(M.error):M;return a$1(s,C,p.status)}}function ue(o,e){return o?.var?.[q$2]??e}var O=new Map,pa=["password","token","secret","apiKey","creditCard","ssn"];function I(o,e){if(o==null||typeof o!="object")return o;if(Array.isArray(o))return o.map(t=>I(t,e));let n={};for(let[t,r]of Object.entries(o))e.includes(t)||(n[t]=typeof r=="object"&&r!==null?I(r,e):r);return n}function ca(o){let{table:e,events:n,emitter:t,filter:r,heartbeatInterval:m=3e4,maxConnections:f=1e3,connectionTimeout:h=3e5,excludeFields:c=pa}=o;return i=>{let u=d$1(i,t);if(!u)return i.json({success:false,error:{code:"EVENT_EMITTER_NOT_CONFIGURED",message:"Event emitter not configured"}},500);let a=O.get(e)||0;return a>=f?i.json({success:false,error:{code:"TOO_MANY_CONNECTIONS",message:"Too many SSE connections"}},503):(O.set(e,a+1),streamSSE(i,async s=>{let p,g=async l=>{if(n&&n.length>0&&!n.includes(l.type)||r&&!r(l,i))return;let k=c.length>0?I(l.data,c):l.data,B=l.previousData&&c.length>0?I(l.previousData,c):l.previousData;try{await s.writeSSE({event:`${l.table}.${l.type}`,data:JSON.stringify({type:l.type,table:l.table,recordId:l.recordId,data:k,previousData:B,timestamp:l.timestamp}),id:`${l.table}-${l.recordId}-${Date.now()}`});}catch{}};p=u.onTable(e,g);let M=()=>{p.unsubscribe();let l=O.get(e)||1;l<=1?O.delete(e):O.set(e,l-1);};s.onAbort(()=>{M();});let w=Date.now(),C=w;for(;!s.closed;){await s.sleep(1e3);let l=Date.now();if(l-w>=h){s.abort();break}if(l-C>=m){C=l;try{await s.writeSSE({event:"heartbeat",data:JSON.stringify({timestamp:new Date().toISOString()})});}catch{break}}}}))}}function ua(o,e,n,t={}){let r=e.endsWith("/")?e.slice(0,-1):e,m=o,{middlewares:f=[],endpointMiddlewares:h={},responseEnvelope:c}=t,i=c?async(s,p)=>{b$2(s,q$2,c),await p();}:void 0,u=s=>{let p=n[s],g=p&&"_middlewares"in p?p._middlewares||[]:[];return [...i?[i]:[],...f,...h[s]||[],...g]},a=(s,p,g,M)=>{let w=u(g),C=m[s];w.length>0?C(p,...w,M):C(p,M);};n.create&&a("post",r,"create",n.create),n.list&&a("get",r,"list",n.list),n.batchCreate&&a("post",`${r}/batch`,"batchCreate",n.batchCreate),n.batchUpdate&&a("patch",`${r}/batch`,"batchUpdate",n.batchUpdate),n.batchDelete&&a("delete",`${r}/batch`,"batchDelete",n.batchDelete),n.batchRestore&&a("post",`${r}/batch/restore`,"batchRestore",n.batchRestore),n.batchUpsert&&a("post",`${r}/batch/upsert`,"batchUpsert",n.batchUpsert),n.search&&a("get",`${r}/search`,"search",n.search),n.aggregate&&a("get",`${r}/aggregate`,"aggregate",n.aggregate),n.export&&a("get",`${r}/export`,"export",n.export),n.import&&a("post",`${r}/import`,"import",n.import),n.upsert&&a("post",`${r}/upsert`,"upsert",n.upsert),n.read&&a("get",`${r}/:id`,"read",n.read),n.update&&a("patch",`${r}/:id`,"update",n.update),n.delete&&a("delete",`${r}/:id`,"delete",n.delete),n.restore&&a("post",`${r}/:id/restore`,"restore",n.restore),n.clone&&a("post",`${r}/:id/clone`,"clone",n.clone);}function q(o){return {content:{"application/json":{schema:o}}}}function ma(o){return {description:"Success",...q({type:"object",properties:{success:{type:"boolean",enum:[true]},result:o},required:["success","result"]})}}function fa(o="Error"){return {description:o,...q({type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"object",properties:{code:{type:"string"},message:{type:"string"},details:{}},required:["code","message"]}},required:["success","error"]})}}function Z(o,e){return {content:{"application/json":{schema:o}},description:e}}function ha(o,e){return {content:{"application/json":{schema:o}},description:e,required:true}}var me=z.object({code:z.string(),path:z.array(z.union([z.string(),z.number()])),message:z.string()}),v=z.object({success:z.literal(false),error:z.object({name:z.literal("ZodError"),issues:z.array(me)})});function ga(o){return v}function Ea(...o){return v}var Ma=(o,e)=>{if(!o.success)return e.json({success:false,error:{name:"ZodError",issues:o.error.issues}},422)};function wa(o,e=422){return (n,t)=>{if(!n.success)return t.json(o(n.error),e)}}var fe=z.object({success:z.literal(false),error:z.object({message:z.string(),code:z.string().optional()})});function y(o){return Z(fe,o)}var ka={badRequest:y("Bad request"),unauthorized:y("Unauthorized"),forbidden:y("Forbidden"),notFound:y("Resource not found"),conflict:y("Resource conflict"),validationError:Z(v,"Validation error"),internalError:y("Internal server error")};function Ca(o){return async(e,n)=>{o.cache&&e.set("cacheStorage",o.cache),o.rateLimit&&e.set("rateLimitStorage",o.rateLimit),o.audit&&e.set("auditStorage",o.audit),o.versioning&&e.set("versioningStorage",o.versioning),o.logging&&e.set("loggingStorage",o.logging),o.idempotency&&e.set("idempotencyStorage",o.idempotency),o.events&&e.set("eventEmitter",o.events),await n();}}function d(o,e){let n=e.middlewares??[],t=e.extras,r=e.schema??{},m=Array.isArray(r.tags)&&r.tags.length>0,f=e.meta.model.tag??e.meta.model.tableName,h=m?r:{...r,tags:[f]};return class extends o{static _middlewares=n;constructor(){super(),t&&Object.assign(this,t);}_meta=e.meta;schema=h;beforeHookMode=e.beforeHookMode??"sequential";afterHookMode=e.afterHookMode??"sequential";allowNestedCreate=e.allowNestedCreate??[];lookupField=e.lookupField??"id";additionalFilters=e.additionalFilters;allowedUpdateFields=e.allowedUpdateFields;blockedUpdateFields=e.blockedUpdateFields;allowNestedWrites=e.allowNestedWrites??[];includeCascadeResults=e.includeCascadeResults??false;filterFields=e.filterFields??[];filterConfig=e.filterConfig;searchFields=e.searchFields??[];searchFieldName=e.searchFieldName??"search";sortFields=e.sortFields??[];defaultSort=e.defaultSort;defaultPerPage=e.defaultPerPage??20;maxPerPage=e.maxPerPage??100;allowedIncludes=e.allowedIncludes??[];fieldSelectionEnabled=e.fieldSelectionEnabled??false;allowedSelectFields=e.allowedSelectFields??[];blockedSelectFields=e.blockedSelectFields??[];alwaysIncludeFields=e.alwaysIncludeFields??[];defaultSelectFields=e.defaultSelectFields??[];getBodySchema(){return e.bodySchema?e.bodySchema:super.getBodySchema()}async before(...i){return e.before?e.before(...i):super.before(...i)}async after(...i){return e.after?e.after(...i):super.after(...i)}transform(i){return e.transform?e.transform(i):super.transform(i)}}}function ba(o,e){return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,before:o.before,after:o.after,beforeHookMode:o.beforeHookMode,afterHookMode:o.afterHookMode,allowNestedCreate:o.allowNestedCreate})}function xa(o,e){let n=o.defaultSort??(o.defaultOrderBy?{field:o.defaultOrderBy,order:o.defaultOrderDirection??"asc"}:void 0);return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,after:o.after,transform:o.transform,filterFields:o.filterFields,filterConfig:o.filterConfig,searchFields:o.searchFields,searchFieldName:o.searchFieldName,sortFields:o.sortFields??o.orderByFields,defaultSort:n,defaultPerPage:o.defaultPerPage,maxPerPage:o.maxPerPage,allowedIncludes:o.allowedIncludes,fieldSelectionEnabled:o.fieldSelectionEnabled,allowedSelectFields:o.allowedSelectFields,blockedSelectFields:o.blockedSelectFields,alwaysIncludeFields:o.alwaysIncludeFields,defaultSelectFields:o.defaultSelectFields})}function ya(o,e){return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,after:o.after,transform:o.transform,lookupField:o.lookupField,additionalFilters:o.additionalFilters,allowedIncludes:o.allowedIncludes,fieldSelectionEnabled:o.fieldSelectionEnabled,allowedSelectFields:o.allowedSelectFields,blockedSelectFields:o.blockedSelectFields,alwaysIncludeFields:o.alwaysIncludeFields,defaultSelectFields:o.defaultSelectFields})}function Sa(o,e){return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,before:o.before,after:o.after,transform:o.transform,beforeHookMode:o.beforeHookMode,afterHookMode:o.afterHookMode,lookupField:o.lookupField,additionalFilters:o.additionalFilters,allowedUpdateFields:o.allowedUpdateFields,blockedUpdateFields:o.blockedUpdateFields,allowNestedWrites:o.allowNestedWrites})}function Oa(o,e){return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,before:o.before,after:o.after,beforeHookMode:o.beforeHookMode,afterHookMode:o.afterHookMode,lookupField:o.lookupField,additionalFilters:o.additionalFilters,includeCascadeResults:o.includeCascadeResults})}var R=class{constructor(e){this.meta=e;}_schema={};_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_allowNestedCreate=[];_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}nestedCreate(...e){return this._allowNestedCreate=e,this}build(e){return d(e,{meta:this.meta,schema:this._schema,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,allowNestedCreate:this._allowNestedCreate,middlewares:this._middlewares})}},A=class{constructor(e){this.meta=e;}_schema={};_filterFields=[];_filterConfig;_searchFields=[];_searchFieldName="search";_sortFields=[];_defaultSort;_defaultPerPage=20;_maxPerPage=100;_allowedIncludes=[];_fieldSelectionEnabled=false;_allowedSelectFields=[];_blockedSelectFields=[];_alwaysIncludeFields=[];_defaultSelectFields=[];_after;_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}filter(...e){return this._filterFields=e,this}filterWith(e){return this._filterConfig=e,this}search(...e){return this._searchFields=e,this}searchParam(e){return this._searchFieldName=e,this}sortable(...e){return this._sortFields=e,this}orderBy(...e){return this.sortable(...e)}defaultSort(e,n="asc"){return this._defaultSort={field:e,order:n},this}defaultOrder(e,n="asc"){return this.defaultSort(e,n)}pagination(e,n){return this._defaultPerPage=e,n!==void 0&&(this._maxPerPage=n),this}include(...e){return this._allowedIncludes=e,this}fieldSelection(e){return this._fieldSelectionEnabled=true,e?.allowed&&(this._allowedSelectFields=e.allowed),e?.blocked&&(this._blockedSelectFields=e.blocked),e?.alwaysInclude&&(this._alwaysIncludeFields=e.alwaysInclude),e?.defaults&&(this._defaultSelectFields=e.defaults),this}after(e){return this._after=e,this}transform(e){return this._transform=e,this}build(e){return d(e,{meta:this.meta,schema:this._schema,filterFields:this._filterFields,filterConfig:this._filterConfig,searchFields:this._searchFields,searchFieldName:this._searchFieldName,sortFields:this._sortFields,defaultSort:this._defaultSort,defaultPerPage:this._defaultPerPage,maxPerPage:this._maxPerPage,allowedIncludes:this._allowedIncludes,fieldSelectionEnabled:this._fieldSelectionEnabled,allowedSelectFields:this._allowedSelectFields,blockedSelectFields:this._blockedSelectFields,alwaysIncludeFields:this._alwaysIncludeFields,defaultSelectFields:this._defaultSelectFields,after:this._after,transform:this._transform,middlewares:this._middlewares})}},H=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_allowedIncludes=[];_fieldSelectionEnabled=false;_allowedSelectFields=[];_blockedSelectFields=[];_alwaysIncludeFields=[];_defaultSelectFields=[];_after;_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}include(...e){return this._allowedIncludes=e,this}fieldSelection(e){return this._fieldSelectionEnabled=true,e?.allowed&&(this._allowedSelectFields=e.allowed),e?.blocked&&(this._blockedSelectFields=e.blocked),e?.alwaysInclude&&(this._alwaysIncludeFields=e.alwaysInclude),e?.defaults&&(this._defaultSelectFields=e.defaults),this}after(e){return this._after=e,this}transform(e){return this._transform=e,this}build(e){return d(e,{meta:this.meta,schema:this._schema,lookupField:this._lookupField,additionalFilters:this._additionalFilters,allowedIncludes:this._allowedIncludes,fieldSelectionEnabled:this._fieldSelectionEnabled,allowedSelectFields:this._allowedSelectFields,blockedSelectFields:this._blockedSelectFields,alwaysIncludeFields:this._alwaysIncludeFields,defaultSelectFields:this._defaultSelectFields,after:this._after,transform:this._transform,middlewares:this._middlewares})}},F=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_allowedUpdateFields;_blockedUpdateFields;_allowNestedWrites=[];_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}allowedFields(...e){return this._allowedUpdateFields=e,this}blockedFields(...e){return this._blockedUpdateFields=e,this}nestedWrites(...e){return this._allowNestedWrites=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}transform(e){return this._transform=e,this}build(e){return d(e,{meta:this.meta,schema:this._schema,lookupField:this._lookupField,additionalFilters:this._additionalFilters,allowedUpdateFields:this._allowedUpdateFields,blockedUpdateFields:this._blockedUpdateFields,allowNestedWrites:this._allowNestedWrites,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,transform:this._transform,middlewares:this._middlewares})}},_=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_includeCascadeResults=false;_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}includeCascade(e=true){return this._includeCascadeResults=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}build(e){return d(e,{meta:this.meta,schema:this._schema,lookupField:this._lookupField,additionalFilters:this._additionalFilters,includeCascadeResults:this._includeCascadeResults,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,middlewares:this._middlewares})}},j=class{constructor(e){this.meta=e;}create(){return new R(this.meta)}list(){return new A(this.meta)}read(){return new H(this.meta)}update(){return new F(this.meta)}delete(){return new _(this.meta)}};function Pa(o){return new j(o)}var Ia={CreateEndpoint:g,ListEndpoint:k,ReadEndpoint:h,UpdateEndpoint:i,DeleteEndpoint:j$1,SearchEndpoint:y$1,AggregateEndpoint:x,RestoreEndpoint:l,BatchCreateEndpoint:m,BatchUpdateEndpoint:n,BatchDeleteEndpoint:o,BatchRestoreEndpoint:p,BatchUpsertEndpoint:q$1,ExportEndpoint:z$1,ImportEndpoint:A$1,UpsertEndpoint:s,CloneEndpoint:r};function va(o,e){let n={};if(o.create!==void 0){let t=o.create;n.create=d(e.CreateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,allowNestedCreate:t.nestedCreate,before:t.hooks?.before,after:t.hooks?.after});}if(o.list!==void 0){let t=o.list;n.list=d(e.ListEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,filterFields:t.filtering?.fields,filterConfig:t.filtering?.config,searchFields:t.search?.fields,searchFieldName:t.search?.paramName,sortFields:t.sorting?.fields,defaultSort:t.sorting?.default?{field:t.sorting.default,order:t.sorting.defaultOrder??t.sorting.defaultDirection??"asc"}:void 0,defaultPerPage:t.pagination?.defaultPerPage,maxPerPage:t.pagination?.maxPerPage,allowedIncludes:t.includes,fieldSelectionEnabled:t.fieldSelection?.enabled,allowedSelectFields:t.fieldSelection?.allowed,blockedSelectFields:t.fieldSelection?.blocked,alwaysIncludeFields:t.fieldSelection?.alwaysInclude,defaultSelectFields:t.fieldSelection?.defaults,after:t.hooks?.after,transform:t.hooks?.transform});}if(o.read!==void 0){let t=o.read;n.read=d(e.ReadEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,lookupField:t.lookupField,additionalFilters:t.additionalFilters,allowedIncludes:t.includes,fieldSelectionEnabled:t.fieldSelection?.enabled,allowedSelectFields:t.fieldSelection?.allowed,blockedSelectFields:t.fieldSelection?.blocked,alwaysIncludeFields:t.fieldSelection?.alwaysInclude,defaultSelectFields:t.fieldSelection?.defaults,after:t.hooks?.after,transform:t.hooks?.transform});}if(o.update!==void 0){let t=o.update;n.update=d(e.UpdateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,lookupField:t.lookupField,additionalFilters:t.additionalFilters,allowedUpdateFields:t.fields?.allowed,blockedUpdateFields:t.fields?.blocked,allowNestedWrites:t.nestedWrites,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,transform:t.hooks?.transform});}if(o.delete!==void 0){let t=o.delete;n.delete=d(e.DeleteEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,lookupField:t.lookupField,additionalFilters:t.additionalFilters,includeCascadeResults:t.includeCascadeResults,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after});}if(o.search!==void 0&&e.SearchEndpoint){let t=o.search;n.search=d(e.SearchEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,after:t.hooks?.after,extras:{...t.fields!==void 0?{searchFields:t.fields}:{},...t.mode!==void 0?{defaultMode:t.mode}:{},...t.paramName!==void 0?{searchParamName:t.paramName}:{}}});}if(o.aggregate!==void 0&&e.AggregateEndpoint){let t=o.aggregate;n.aggregate=d(e.AggregateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,after:t.hooks?.after,extras:{...t.fields!==void 0?{filterFields:t.fields}:{}}});}if(o.restore!==void 0&&e.RestoreEndpoint){let t=o.restore;n.restore=d(e.RestoreEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after});}if(o.batchCreate!==void 0&&e.BatchCreateEndpoint){let t=o.batchCreate;n.batchCreate=d(e.BatchCreateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{}}});}if(o.batchUpdate!==void 0&&e.BatchUpdateEndpoint){let t=o.batchUpdate;n.batchUpdate=d(e.BatchUpdateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{}}});}if(o.batchDelete!==void 0&&e.BatchDeleteEndpoint){let t=o.batchDelete;n.batchDelete=d(e.BatchDeleteEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{}}});}if(o.batchRestore!==void 0&&e.BatchRestoreEndpoint){let t=o.batchRestore;n.batchRestore=d(e.BatchRestoreEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{}}});}if(o.batchUpsert!==void 0&&e.BatchUpsertEndpoint){let t=o.batchUpsert,r=typeof t.conflictTarget=="string"?[t.conflictTarget]:t.conflictTarget;n.batchUpsert=d(e.BatchUpsertEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{},...r!==void 0?{upsertKeys:r}:{}}});}if(o.export!==void 0&&e.ExportEndpoint){let t=o.export;n.export=d(e.ExportEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,extras:{...t.maxRows!==void 0?{maxExportRecords:t.maxRows}:{},...t.formats!==void 0&&t.formats.length>0?{defaultFormat:t.formats[0]}:{}}});}if(o.import!==void 0&&e.ImportEndpoint){let t=o.import;n.import=d(e.ImportEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxRows!==void 0?{maxBatchSize:t.maxRows}:{}}});}if(o.upsert!==void 0&&e.UpsertEndpoint){let t=o.upsert,r=typeof t.conflictTarget=="string"?[t.conflictTarget]:t.conflictTarget;n.upsert=d(e.UpsertEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...r!==void 0?{upsertKeys:r}:{}}});}if(o.clone!==void 0&&e.CloneEndpoint){let t=o.clone;n.clone=d(e.CloneEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.fieldsToReset!==void 0?{excludeFromClone:t.fieldsToReset}:{}}});}return n}
1
+ import {r,s,A as A$1,z as z$1,q as q$1,p,o,n,m,l,x,y as y$1,j as j$1,i,h,k,g}from'./chunk-BXWKFJXP.js';export{a as BulkPatchEndpoint}from'./chunk-BXWKFJXP.js';export{J as DrizzleAdapters}from'./chunk-DJOJGLOT.js';export{y as PrismaAdapters}from'./chunk-FOTF3T22.js';export{K as AggregateEndpoint,B as BatchCreateEndpoint,D as BatchDeleteEndpoint,E as BatchRestoreEndpoint,C as BatchUpdateEndpoint,F as BatchUpsertEndpoint,y as CloneEndpoint,t as CreateEndpoint,w as DeleteEndpoint,ba as ExportEndpoint,ca as ImportEndpoint,x as ListEndpoint,u as ReadEndpoint,z as RestoreEndpoint,T as SearchEndpoint,v as UpdateEndpoint,A as UpsertEndpoint,I as VersionCompareEndpoint,G as VersionHistoryEndpoint,H as VersionReadEndpoint,J as VersionRollbackEndpoint,r as applyFieldSelection,s as applyFieldSelectionToArray,c as applyManagedInsertFields,d as applyManagedUpdateFields,e as assertIdStrategySupported,S as buildSearchConfig,P as calculateScore,g as causeChain,L as computeAggregations,X as createCsvStream,aa as csvToJson,V as escapeCsvValue,W as generateCsv,j as generateETag,Q as generateHighlights,b as getManagedInputExclusions,p as getSchemaFields,a as getTimestampsConfig,_ as inferCsvContentType,$ as jsonToCsv,h as mapUniqueViolation,l as matchesIfMatch,k as matchesIfNoneMatch,Y as parseCsv,q as parseFieldSelection,n as parseFilterValue,o as parseListFilters,R as parseSearchFields,i as rethrowAsConstraintError,U as searchInMemory,f as stripManagedInsertFields,O as termFrequency,M as tokenize,N as tokenizeQuery,Z as validateCsvHeaders}from'./chunk-ZBCVLQ3W.js';export{a as createHealthEndpoints,b as createHealthHandler}from'./chunk-XH7DEPW2.js';export{a as MemoryIdempotencyStorage}from'./chunk-FXIMMYFV.js';export{a as MemoryLoggingStorage}from'./chunk-3UHTK7SB.js';export{a as multiTenant}from'./chunk-L4X7KFWN.js';export{c as KVRateLimitStorage,a as MemoryRateLimitStorage,b as RedisRateLimitStorage}from'./chunk-EWKQ6BPV.js';import'./chunk-BJTWQHEV.js';export{a as applyProfile,b as applyProfileToArray,e as createArraySerializer,d as createSerializer,c as resolveProfile}from'./chunk-SDNXN7M5.js';export{g as createAPIKeyStorageMiddleware,e as createAuditStorageMiddleware,d as createCacheStorageMiddleware,c as createLoggingStorageMiddleware,b as createRateLimitStorageMiddleware,a as createStorageMiddleware,f as createVersioningStorageMiddleware}from'./chunk-R3WESU6C.js';export{a as scalarUI,e as setupDocs,f as setupDocsIndex,d as setupReDoc,b as setupScalar,c as setupSwaggerUI}from'./chunk-SPICOFUM.js';export{a as apiVersion,b as getApiVersion,c as getApiVersionConfig,d as versionedResponse}from'./chunk-KKLMXJY4.js';export{o as AuthenticatedEndpoint,a as JWTClaimsSchema,j as createAPIKeyMiddleware,l as createAuthMiddleware,e as createJWTMiddleware,g as decodeJWT,i as defaultHashAPIKey,m as optionalAuth,b as parseJWTClaims,n as requireAuthentication,c as safeParseJWTClaims,k as validateAPIKey,h as validateAPIKeyEntry,d as validateJWTClaims,f as verifyJWT,p as withAuth}from'./chunk-7ZUZICKI.js';import {a as a$1,c}from'./chunk-XI7HT5ZM.js';export{e as MemoryApprovalStorage,b as OpenAPIRoute,f as POLICIES_CONTEXT_KEY,n as allOf,q as allowAll,o as anyOf,p as denyAll,c as isRouteClass,d as parseIso8601Duration,h as requireAllRoles,j as requireAnyPermission,t as requireApproval,k as requireAuth,r as requireAuthenticated,l as requireOwnership,m as requireOwnershipOrRole,i as requirePermissions,s as requirePolicy,g as requireRoles}from'./chunk-XI7HT5ZM.js';export{b as KVCacheStorage,a as RedisCacheStorage}from'./chunk-H3H65KZF.js';import {T}from'./chunk-UANCAA7V.js';export{C as MemoryCacheStorage,m as RateLimitExceededException,y as createInvalidationPattern,V as createLoggingMiddleware,v as createRateLimitMiddleware,z as createRelatedPatterns,p as extractAPIKey,f as extractClientIp,g as extractHeaders,n as extractIP,k as extractLoggingUserId,h as extractQuery,o as extractUserId,x as generateCacheKey,s as generateKey,l as generateRequestId,E as getCacheStorage,Q as getErrorMessage,S as getLoggingStorage,u as getRateLimitStorage,T as getRequestId,U as getRequestStartTime,j as isAllowedContentType,d as matchLoggingPath,q as matchPath,A as matchesPattern,B as parseCacheKey,c as redactHeaders,b as redactObject,w as resetRateLimit,M as resolveAPIKeyStorage,K as resolveAuditStorage,J as resolveCacheStorage,N as resolveIdempotencyStorage,I as resolveLoggingStorage,H as resolveRateLimitStorage,L as resolveVersioningStorage,D as setCacheStorage,R as setLoggingStorage,t as setRateLimitStorage,e as shouldExcludePath,a as shouldRedact,r as shouldSkipPath,O as toError,i as truncateBody,F as withCache,G as withCacheInvalidation,P as wrapError}from'./chunk-UANCAA7V.js';export{a as MemoryVersioningStorage,e as VersionManager,f as createVersionManager,d as getVersioningStorage,c as setVersioningStorage}from'./chunk-NGUMNUOP.js';export{c as getIdempotencyStorage,d as idempotency,b as setIdempotencyStorage}from'./chunk-GF2EC5G4.js';export{c as MemoryAPIKeyStorage,d as generateAPIKey,h as getAPIKeyStorage,e as hashAPIKey,f as isValidAPIKeyFormat,i as setAPIKeyStorage}from'./chunk-2M5BM4VD.js';import {a,b}from'./chunk-FC56WWPB.js';export{g as AggregationException,a as ApiException,h as CacheException,i as ConfigurationException,d as ConflictException,f as ForbiddenException,b as InputValidationException,c as NotFoundException,e as UnauthorizedException}from'./chunk-FC56WWPB.js';export{e as AuditLogger,a as MemoryAuditLogStorage,f as createAuditLogger,d as getAuditStorage,c as setAuditStorage}from'./chunk-FJCWFB5L.js';import {q as q$2}from'./chunk-KUFOENSK.js';export{q as RESPONSE_ENVELOPE_CONTEXT_KEY,j as applyComputedFields,k as applyComputedFieldsToArray,f as calculateChanges,b as decodeCursor,m as defineMeta,l as defineModel,a as encodeCursor,c as extractNestedData,p as extractTenantId,e as getAuditConfig,o as getMultiTenantConfig,n as getSoftDeleteConfig,g as getVersioningConfig,d as isDirectNestedData,h as parseAggregateField,i as parseAggregateQuery,r as parseSearchMode}from'./chunk-KUFOENSK.js';export{a as StorageRegistry,b as createNullableRegistry,c as createRegistryWithDefault}from'./chunk-GBQQ3YQX.js';import'./chunk-CCGZ5UPB.js';export{f as StaticKeyProvider,e as decryptFields,b as decryptValue,d as encryptFields,a as encryptValue,c as isEncryptedValue}from'./chunk-QRXEQTNE.js';export{a as registerWebhooks}from'./chunk-7DDNX2F2.js';import {d as d$1}from'./chunk-QXFY6NYI.js';export{a as CrudEventEmitter,b as getEventEmitter,d as resolveEventEmitter,c as setEventEmitter}from'./chunk-QXFY6NYI.js';import {b as b$1}from'./chunk-DMGP7QDL.js';export{b as getLogger,a as setLogger}from'./chunk-DMGP7QDL.js';export{e as getAuthType,b as getUser,a as getUserId,d as getUserPermissions,c as getUserRoles,j as hasAllPermissions,h as hasAllRoles,i as hasAnyRole,g as hasPermission,f as hasRole}from'./chunk-MDHMZPXK.js';import {b as b$2}from'./chunk-VJRDAVID.js';export{c as getContextRequestId,a as getContextVar,d as getTenantId,b as setContextVar}from'./chunk-VJRDAVID.js';import {OpenAPIHono,createRoute}from'@hono/zod-openapi';import {z,ZodError}from'zod';import {HTTPException}from'hono/http-exception';import {streamSSE}from'hono/streaming';var pe=new WeakMap;function V(o){return pe.get(o)}var P=class{app;options;routes=new Map;constructor(e,n={}){this.app=e,this.options={docs_url:"/docs",redoc_url:"/redoc",openapi_url:"/openapi.json",...n};}registerRoute(e,n,t,r=[]){let m=`${e.toUpperCase()} ${n}`,f=t,c=new f().getSchema();this.routes.set(m,{method:e,path:n,schema:c,routeClass:t});let i=createRoute({method:e,path:this.convertPath(n),...c,responses:c.responses||{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}});if(r.length>0)for(let u of r)this.app.use(n,async(a,s)=>{if(a.req.method.toLowerCase()===e)return u(a,s);await s();});this.app.openapi(i,async u=>{let a$2=new f;a$2.setContext(u);try{return await a$2.handle()}catch(s){if(s instanceof a){let p=s.toJSON(),g=u?.var?.[q$2];return g?a$1(u,g.error(p.error),s.status):a$1(u,p,s.status)}throw s}});}convertPath(e){return e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}setupDocs(e,n){let t=e??this.options.openapi_url??"/openapi.json";this.app.doc(t,{openapi:n.openapi||"3.1.0",info:n.info,servers:n.servers,security:n.security});}getApp(){return this.app}getRegisteredRoutes(){return this.routes}toOpenApiPath(e){return this.convertPath(e)}};function qr(o=new OpenAPIHono,e={}){let n="openAPIRegistry"in o?o:new OpenAPIHono,t=new P(n,e),r=["get","post","put","patch","delete","options","head"],m=new Proxy(n,{get(f,h){if(r.includes(h))return (i,...u)=>{let a=u[u.length-1];if(c(a)){let s=u.slice(0,-1);return t.registerRoute(h,i,a,s),m}return f[h](i,...u)};if(h==="doc")return (i,u)=>{t.setupDocs(i,u);};if(h==="use")return (...i)=>(f[h](...i),m);let c$1=f[h];return typeof c$1=="function"?c$1.bind(f):c$1}});return pe.set(m,t),m}var $r=6e4,Gr={openapi:"3.1.0",info:{title:"API",version:"1.0.0"}};async function Jr(o,e,n={}){let t=V(o);if(!t)throw new Error("buildPerTenantOpenApi: app was not produced by fromHono(...). Cannot find route registry.");let r=n.config??Gr,m=`openapi:${e.tenantId??"global"}:${r.info.version}`;if(n.cache){let i=await n.cache.get(m);if(i!=null)return i}let f=new OpenAPIHono;for(let i of t.getRegisteredRoutes().values()){let u=i.routeClass,a=new u,s=Yr(e);a.setContext(s),typeof a.resolveModelSchema=="function"&&await a.resolveModelSchema();let p=a.getSchema(),g=createRoute({...p,method:i.method,path:t.toOpenApiPath(i.path),responses:p.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});f.openapi(g,()=>new Response);}let h={openapi:r.openapi??"3.1.0",info:r.info,servers:r.servers,security:r.security},c=n.spec==="3.0"?f.getOpenAPIDocument(h):f.getOpenAPI31Document(h);return n.cache&&await n.cache.set(m,c,n.cacheTtlMs??$r),c}function Yr(o){let e={};o.tenantId!==void 0&&(e.tenantId=o.tenantId),o.organizationId!==void 0&&(e.organizationId=o.organizationId);let n=o.request??new Request("http://localhost/");return {var:e,env:o.env,req:{raw:n,header:()=>{},query:()=>{},param:()=>{}},set(t,r){e[t]=r;},get(t){return e[t]},executionCtx:void 0}}function Xr(o){return {async get(e){let n=await o.get(e);return n?n.data:void 0},async set(e,n,t){let r=t?Math.ceil(t/1e3):void 0;await o.set(e,n,r?{ttl:r}:void 0);}}}var oa=[["create","post",""],["list","get",""],["batchCreate","post","/batch"],["batchUpdate","patch","/batch"],["batchDelete","delete","/batch"],["batchRestore","post","/batch/restore"],["batchUpsert","post","/batch/upsert"],["search","get","/search"],["aggregate","get","/aggregate"],["export","get","/export"],["import","post","/import"],["upsert","post","/upsert"],["read","get","/:id"],["update","patch","/:id"],["delete","delete","/:id"],["restore","post","/:id/restore"],["clone","post","/:id/clone"]];function na(o){return o.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}function ra(o,e){let t=`/${o}/${e}`.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function aa(o,e={}){let n=e.basePath??"",t=e.tag,r=new OpenAPIHono,m=0;for(let[c,i,u]of oa){let a=o[c];if(!a)continue;let p=new a().getSchema(),g=t!==void 0?{...p,tags:[t]}:p,M=ra(n,na(u)),w=createRoute({...g,method:i,path:M,responses:g.responses??{200:{description:"Success",content:{"application/json":{schema:z.unknown()}}}}});r.openapi(w,()=>new Response),m+=1;}return m===0?{}:r.getOpenAPI31Document({openapi:"3.1.0",info:{title:"hono-crud",version:"1.0.0"}}).paths??{}}var ce=o=>{if(o instanceof ZodError)return b.fromZodError(o)};function da(o={}){let{mappers:e=[],hooks:n=[],includeRequestId:t=true,includeStackTrace:r=false,defaultErrorCode:m="INTERNAL_ERROR",defaultErrorMessage:f="An internal error occurred",logUnmappedErrors:h=true,onHookError:c,responseEnvelope:i}=o,u=[...e,ce];return async(a$2,s)=>{let p,g=false;if(a$2 instanceof a)p=a$2,g=true;else if(a$2 instanceof HTTPException)p=new a(a$2.message,a$2.status,"HTTP_ERROR"),g=true;else {for(let l of u)try{let k=await l(a$2,s);if(k){p=k,g=!0;break}}catch{}g||(h&&b$1().error("Unmapped error",{error:a$2 instanceof Error?a$2.message:String(a$2)}),p=new a(f,500,m));}for(let l of n)try{let k=l(a$2,s,p);k instanceof Promise&&k.catch(B=>{c&&c(B,a$2,s);});}catch(k){c&&c(k,a$2,s);}let M=p.toJSON();if(t){let l=T(s);l&&(M.error.requestId=l);}r&&a$2.stack&&(M.error.stack=a$2.stack);let w=ue(s,i),C=w?w.error(M.error):M;return a$1(s,C,p.status)}}function ue(o,e){return o?.var?.[q$2]??e}var O=new Map,pa=["password","token","secret","apiKey","creditCard","ssn"];function I(o,e){if(o==null||typeof o!="object")return o;if(Array.isArray(o))return o.map(t=>I(t,e));let n={};for(let[t,r]of Object.entries(o))e.includes(t)||(n[t]=typeof r=="object"&&r!==null?I(r,e):r);return n}function ca(o){let{table:e,events:n,emitter:t,filter:r,heartbeatInterval:m=3e4,maxConnections:f=1e3,connectionTimeout:h=3e5,excludeFields:c=pa}=o;return i=>{let u=d$1(i,t);if(!u)return i.json({success:false,error:{code:"EVENT_EMITTER_NOT_CONFIGURED",message:"Event emitter not configured"}},500);let a=O.get(e)||0;return a>=f?i.json({success:false,error:{code:"TOO_MANY_CONNECTIONS",message:"Too many SSE connections"}},503):(O.set(e,a+1),streamSSE(i,async s=>{let p,g=async l=>{if(n&&n.length>0&&!n.includes(l.type)||r&&!r(l,i))return;let k=c.length>0?I(l.data,c):l.data,B=l.previousData&&c.length>0?I(l.previousData,c):l.previousData;try{await s.writeSSE({event:`${l.table}.${l.type}`,data:JSON.stringify({type:l.type,table:l.table,recordId:l.recordId,data:k,previousData:B,timestamp:l.timestamp}),id:`${l.table}-${l.recordId}-${Date.now()}`});}catch{}};p=u.onTable(e,g);let M=()=>{p.unsubscribe();let l=O.get(e)||1;l<=1?O.delete(e):O.set(e,l-1);};s.onAbort(()=>{M();});let w=Date.now(),C=w;for(;!s.closed;){await s.sleep(1e3);let l=Date.now();if(l-w>=h){s.abort();break}if(l-C>=m){C=l;try{await s.writeSSE({event:"heartbeat",data:JSON.stringify({timestamp:new Date().toISOString()})});}catch{break}}}}))}}function ua(o,e,n,t={}){let r=e.endsWith("/")?e.slice(0,-1):e,m=o,{middlewares:f=[],endpointMiddlewares:h={},responseEnvelope:c}=t,i=c?async(s,p)=>{b$2(s,q$2,c),await p();}:void 0,u=s=>{let p=n[s],g=p&&"_middlewares"in p?p._middlewares||[]:[];return [...i?[i]:[],...f,...h[s]||[],...g]},a=(s,p,g,M)=>{let w=u(g),C=m[s];w.length>0?C(p,...w,M):C(p,M);};n.create&&a("post",r,"create",n.create),n.list&&a("get",r,"list",n.list),n.batchCreate&&a("post",`${r}/batch`,"batchCreate",n.batchCreate),n.batchUpdate&&a("patch",`${r}/batch`,"batchUpdate",n.batchUpdate),n.batchDelete&&a("delete",`${r}/batch`,"batchDelete",n.batchDelete),n.batchRestore&&a("post",`${r}/batch/restore`,"batchRestore",n.batchRestore),n.batchUpsert&&a("post",`${r}/batch/upsert`,"batchUpsert",n.batchUpsert),n.search&&a("get",`${r}/search`,"search",n.search),n.aggregate&&a("get",`${r}/aggregate`,"aggregate",n.aggregate),n.export&&a("get",`${r}/export`,"export",n.export),n.import&&a("post",`${r}/import`,"import",n.import),n.upsert&&a("post",`${r}/upsert`,"upsert",n.upsert),n.read&&a("get",`${r}/:id`,"read",n.read),n.update&&a("patch",`${r}/:id`,"update",n.update),n.delete&&a("delete",`${r}/:id`,"delete",n.delete),n.restore&&a("post",`${r}/:id/restore`,"restore",n.restore),n.clone&&a("post",`${r}/:id/clone`,"clone",n.clone);}function q(o){return {content:{"application/json":{schema:o}}}}function ma(o){return {description:"Success",...q({type:"object",properties:{success:{type:"boolean",enum:[true]},result:o},required:["success","result"]})}}function fa(o="Error"){return {description:o,...q({type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"object",properties:{code:{type:"string"},message:{type:"string"},details:{}},required:["code","message"]}},required:["success","error"]})}}function Z(o,e){return {content:{"application/json":{schema:o}},description:e}}function ha(o,e){return {content:{"application/json":{schema:o}},description:e,required:true}}var me=z.object({code:z.string(),path:z.array(z.union([z.string(),z.number()])),message:z.string()}),v=z.object({success:z.literal(false),error:z.object({name:z.literal("ZodError"),issues:z.array(me)})});function ga(o){return v}function Ea(...o){return v}var Ma=(o,e)=>{if(!o.success)return e.json({success:false,error:{name:"ZodError",issues:o.error.issues}},422)};function wa(o,e=422){return (n,t)=>{if(!n.success)return t.json(o(n.error),e)}}var fe=z.object({success:z.literal(false),error:z.object({message:z.string(),code:z.string().optional()})});function y(o){return Z(fe,o)}var ka={badRequest:y("Bad request"),unauthorized:y("Unauthorized"),forbidden:y("Forbidden"),notFound:y("Resource not found"),conflict:y("Resource conflict"),validationError:Z(v,"Validation error"),internalError:y("Internal server error")};function Ca(o){return async(e,n)=>{o.cache&&e.set("cacheStorage",o.cache),o.rateLimit&&e.set("rateLimitStorage",o.rateLimit),o.audit&&e.set("auditStorage",o.audit),o.versioning&&e.set("versioningStorage",o.versioning),o.logging&&e.set("loggingStorage",o.logging),o.idempotency&&e.set("idempotencyStorage",o.idempotency),o.events&&e.set("eventEmitter",o.events),await n();}}function d(o,e){let n=e.middlewares??[],t=e.extras,r=e.schema??{},m=Array.isArray(r.tags)&&r.tags.length>0,f=e.meta.model.tag??e.meta.model.tableName,h=m?r:{...r,tags:[f]};return class extends o{static _middlewares=n;constructor(){super(),t&&Object.assign(this,t);}_meta=e.meta;schema=h;beforeHookMode=e.beforeHookMode??"sequential";afterHookMode=e.afterHookMode??"sequential";allowNestedCreate=e.allowNestedCreate??[];lookupField=e.lookupField??"id";additionalFilters=e.additionalFilters;allowedUpdateFields=e.allowedUpdateFields;blockedUpdateFields=e.blockedUpdateFields;allowNestedWrites=e.allowNestedWrites??[];includeCascadeResults=e.includeCascadeResults??false;filterFields=e.filterFields??[];filterConfig=e.filterConfig;searchFields=e.searchFields??[];searchFieldName=e.searchFieldName??"search";sortFields=e.sortFields??[];defaultSort=e.defaultSort;defaultPerPage=e.defaultPerPage??20;maxPerPage=e.maxPerPage??100;allowedIncludes=e.allowedIncludes??[];fieldSelectionEnabled=e.fieldSelectionEnabled??false;allowedSelectFields=e.allowedSelectFields??[];blockedSelectFields=e.blockedSelectFields??[];alwaysIncludeFields=e.alwaysIncludeFields??[];defaultSelectFields=e.defaultSelectFields??[];getBodySchema(){return e.bodySchema?e.bodySchema:super.getBodySchema()}async before(...i){return e.before?e.before(...i):super.before(...i)}async after(...i){return e.after?e.after(...i):super.after(...i)}transform(i){return e.transform?e.transform(i):super.transform(i)}}}function ba(o,e){return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,before:o.before,after:o.after,beforeHookMode:o.beforeHookMode,afterHookMode:o.afterHookMode,allowNestedCreate:o.allowNestedCreate})}function xa(o,e){let n=o.defaultSort??(o.defaultOrderBy?{field:o.defaultOrderBy,order:o.defaultOrderDirection??"asc"}:void 0);return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,after:o.after,transform:o.transform,filterFields:o.filterFields,filterConfig:o.filterConfig,searchFields:o.searchFields,searchFieldName:o.searchFieldName,sortFields:o.sortFields??o.orderByFields,defaultSort:n,defaultPerPage:o.defaultPerPage,maxPerPage:o.maxPerPage,allowedIncludes:o.allowedIncludes,fieldSelectionEnabled:o.fieldSelectionEnabled,allowedSelectFields:o.allowedSelectFields,blockedSelectFields:o.blockedSelectFields,alwaysIncludeFields:o.alwaysIncludeFields,defaultSelectFields:o.defaultSelectFields})}function ya(o,e){return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,after:o.after,transform:o.transform,lookupField:o.lookupField,additionalFilters:o.additionalFilters,allowedIncludes:o.allowedIncludes,fieldSelectionEnabled:o.fieldSelectionEnabled,allowedSelectFields:o.allowedSelectFields,blockedSelectFields:o.blockedSelectFields,alwaysIncludeFields:o.alwaysIncludeFields,defaultSelectFields:o.defaultSelectFields})}function Sa(o,e){return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,before:o.before,after:o.after,transform:o.transform,beforeHookMode:o.beforeHookMode,afterHookMode:o.afterHookMode,lookupField:o.lookupField,additionalFilters:o.additionalFilters,allowedUpdateFields:o.allowedUpdateFields,blockedUpdateFields:o.blockedUpdateFields,allowNestedWrites:o.allowNestedWrites})}function Oa(o,e){return d(e,{meta:o.meta,schema:o.schema,middlewares:o.middlewares,before:o.before,after:o.after,beforeHookMode:o.beforeHookMode,afterHookMode:o.afterHookMode,lookupField:o.lookupField,additionalFilters:o.additionalFilters,includeCascadeResults:o.includeCascadeResults})}var R=class{constructor(e){this.meta=e;}_schema={};_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_allowNestedCreate=[];_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}nestedCreate(...e){return this._allowNestedCreate=e,this}build(e){return d(e,{meta:this.meta,schema:this._schema,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,allowNestedCreate:this._allowNestedCreate,middlewares:this._middlewares})}},A=class{constructor(e){this.meta=e;}_schema={};_filterFields=[];_filterConfig;_searchFields=[];_searchFieldName="search";_sortFields=[];_defaultSort;_defaultPerPage=20;_maxPerPage=100;_allowedIncludes=[];_fieldSelectionEnabled=false;_allowedSelectFields=[];_blockedSelectFields=[];_alwaysIncludeFields=[];_defaultSelectFields=[];_after;_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}filter(...e){return this._filterFields=e,this}filterWith(e){return this._filterConfig=e,this}search(...e){return this._searchFields=e,this}searchParam(e){return this._searchFieldName=e,this}sortable(...e){return this._sortFields=e,this}orderBy(...e){return this.sortable(...e)}defaultSort(e,n="asc"){return this._defaultSort={field:e,order:n},this}defaultOrder(e,n="asc"){return this.defaultSort(e,n)}pagination(e,n){return this._defaultPerPage=e,n!==void 0&&(this._maxPerPage=n),this}include(...e){return this._allowedIncludes=e,this}fieldSelection(e){return this._fieldSelectionEnabled=true,e?.allowed&&(this._allowedSelectFields=e.allowed),e?.blocked&&(this._blockedSelectFields=e.blocked),e?.alwaysInclude&&(this._alwaysIncludeFields=e.alwaysInclude),e?.defaults&&(this._defaultSelectFields=e.defaults),this}after(e){return this._after=e,this}transform(e){return this._transform=e,this}build(e){return d(e,{meta:this.meta,schema:this._schema,filterFields:this._filterFields,filterConfig:this._filterConfig,searchFields:this._searchFields,searchFieldName:this._searchFieldName,sortFields:this._sortFields,defaultSort:this._defaultSort,defaultPerPage:this._defaultPerPage,maxPerPage:this._maxPerPage,allowedIncludes:this._allowedIncludes,fieldSelectionEnabled:this._fieldSelectionEnabled,allowedSelectFields:this._allowedSelectFields,blockedSelectFields:this._blockedSelectFields,alwaysIncludeFields:this._alwaysIncludeFields,defaultSelectFields:this._defaultSelectFields,after:this._after,transform:this._transform,middlewares:this._middlewares})}},H=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_allowedIncludes=[];_fieldSelectionEnabled=false;_allowedSelectFields=[];_blockedSelectFields=[];_alwaysIncludeFields=[];_defaultSelectFields=[];_after;_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}include(...e){return this._allowedIncludes=e,this}fieldSelection(e){return this._fieldSelectionEnabled=true,e?.allowed&&(this._allowedSelectFields=e.allowed),e?.blocked&&(this._blockedSelectFields=e.blocked),e?.alwaysInclude&&(this._alwaysIncludeFields=e.alwaysInclude),e?.defaults&&(this._defaultSelectFields=e.defaults),this}after(e){return this._after=e,this}transform(e){return this._transform=e,this}build(e){return d(e,{meta:this.meta,schema:this._schema,lookupField:this._lookupField,additionalFilters:this._additionalFilters,allowedIncludes:this._allowedIncludes,fieldSelectionEnabled:this._fieldSelectionEnabled,allowedSelectFields:this._allowedSelectFields,blockedSelectFields:this._blockedSelectFields,alwaysIncludeFields:this._alwaysIncludeFields,defaultSelectFields:this._defaultSelectFields,after:this._after,transform:this._transform,middlewares:this._middlewares})}},F=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_allowedUpdateFields;_blockedUpdateFields;_allowNestedWrites=[];_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_transform;_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}allowedFields(...e){return this._allowedUpdateFields=e,this}blockedFields(...e){return this._blockedUpdateFields=e,this}nestedWrites(...e){return this._allowNestedWrites=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}transform(e){return this._transform=e,this}build(e){return d(e,{meta:this.meta,schema:this._schema,lookupField:this._lookupField,additionalFilters:this._additionalFilters,allowedUpdateFields:this._allowedUpdateFields,blockedUpdateFields:this._blockedUpdateFields,allowNestedWrites:this._allowNestedWrites,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,transform:this._transform,middlewares:this._middlewares})}},_=class{constructor(e){this.meta=e;}_schema={};_lookupField="id";_additionalFilters;_includeCascadeResults=false;_before;_after;_beforeHookMode="sequential";_afterHookMode="sequential";_middlewares=[];middleware(...e){return this._middlewares.push(...e),this}tags(...e){return this._schema.tags=e,this}summary(e){return this._schema.summary=e,this}description(e){return this._schema.description=e,this}lookupField(e){return this._lookupField=e,this}additionalFilters(...e){return this._additionalFilters=e,this}includeCascade(e=true){return this._includeCascadeResults=e,this}before(e){return this._before=e,this}after(e){return this._after=e,this}beforeMode(e){return this._beforeHookMode=e,this}afterMode(e){return this._afterHookMode=e,this}build(e){return d(e,{meta:this.meta,schema:this._schema,lookupField:this._lookupField,additionalFilters:this._additionalFilters,includeCascadeResults:this._includeCascadeResults,before:this._before,after:this._after,beforeHookMode:this._beforeHookMode,afterHookMode:this._afterHookMode,middlewares:this._middlewares})}},j=class{constructor(e){this.meta=e;}create(){return new R(this.meta)}list(){return new A(this.meta)}read(){return new H(this.meta)}update(){return new F(this.meta)}delete(){return new _(this.meta)}};function Pa(o){return new j(o)}var Ia={CreateEndpoint:g,ListEndpoint:k,ReadEndpoint:h,UpdateEndpoint:i,DeleteEndpoint:j$1,SearchEndpoint:y$1,AggregateEndpoint:x,RestoreEndpoint:l,BatchCreateEndpoint:m,BatchUpdateEndpoint:n,BatchDeleteEndpoint:o,BatchRestoreEndpoint:p,BatchUpsertEndpoint:q$1,ExportEndpoint:z$1,ImportEndpoint:A$1,UpsertEndpoint:s,CloneEndpoint:r};function va(o,e){let n={};if(o.create!==void 0){let t=o.create;n.create=d(e.CreateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,allowNestedCreate:t.nestedCreate,before:t.hooks?.before,after:t.hooks?.after});}if(o.list!==void 0){let t=o.list;n.list=d(e.ListEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,filterFields:t.filtering?.fields,filterConfig:t.filtering?.config,searchFields:t.search?.fields,searchFieldName:t.search?.paramName,sortFields:t.sorting?.fields,defaultSort:t.sorting?.default?{field:t.sorting.default,order:t.sorting.defaultOrder??t.sorting.defaultDirection??"asc"}:void 0,defaultPerPage:t.pagination?.defaultPerPage,maxPerPage:t.pagination?.maxPerPage,allowedIncludes:t.includes,fieldSelectionEnabled:t.fieldSelection?.enabled,allowedSelectFields:t.fieldSelection?.allowed,blockedSelectFields:t.fieldSelection?.blocked,alwaysIncludeFields:t.fieldSelection?.alwaysInclude,defaultSelectFields:t.fieldSelection?.defaults,after:t.hooks?.after,transform:t.hooks?.transform});}if(o.read!==void 0){let t=o.read;n.read=d(e.ReadEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,lookupField:t.lookupField,additionalFilters:t.additionalFilters,allowedIncludes:t.includes,fieldSelectionEnabled:t.fieldSelection?.enabled,allowedSelectFields:t.fieldSelection?.allowed,blockedSelectFields:t.fieldSelection?.blocked,alwaysIncludeFields:t.fieldSelection?.alwaysInclude,defaultSelectFields:t.fieldSelection?.defaults,after:t.hooks?.after,transform:t.hooks?.transform});}if(o.update!==void 0){let t=o.update;n.update=d(e.UpdateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,lookupField:t.lookupField,additionalFilters:t.additionalFilters,allowedUpdateFields:t.fields?.allowed,blockedUpdateFields:t.fields?.blocked,allowNestedWrites:t.nestedWrites,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,transform:t.hooks?.transform});}if(o.delete!==void 0){let t=o.delete;n.delete=d(e.DeleteEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,lookupField:t.lookupField,additionalFilters:t.additionalFilters,includeCascadeResults:t.includeCascadeResults,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after});}if(o.search!==void 0&&e.SearchEndpoint){let t=o.search;n.search=d(e.SearchEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,after:t.hooks?.after,extras:{...t.fields!==void 0?{searchFields:t.fields}:{},...t.mode!==void 0?{defaultMode:t.mode}:{},...t.paramName!==void 0?{searchParamName:t.paramName}:{}}});}if(o.aggregate!==void 0&&e.AggregateEndpoint){let t=o.aggregate;n.aggregate=d(e.AggregateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,after:t.hooks?.after,extras:{...t.fields!==void 0?{filterFields:t.fields}:{}}});}if(o.restore!==void 0&&e.RestoreEndpoint){let t=o.restore;n.restore=d(e.RestoreEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after});}if(o.batchCreate!==void 0&&e.BatchCreateEndpoint){let t=o.batchCreate;n.batchCreate=d(e.BatchCreateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{}}});}if(o.batchUpdate!==void 0&&e.BatchUpdateEndpoint){let t=o.batchUpdate;n.batchUpdate=d(e.BatchUpdateEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{}}});}if(o.batchDelete!==void 0&&e.BatchDeleteEndpoint){let t=o.batchDelete;n.batchDelete=d(e.BatchDeleteEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{}}});}if(o.batchRestore!==void 0&&e.BatchRestoreEndpoint){let t=o.batchRestore;n.batchRestore=d(e.BatchRestoreEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{}}});}if(o.batchUpsert!==void 0&&e.BatchUpsertEndpoint){let t=o.batchUpsert,r=typeof t.conflictTarget=="string"?[t.conflictTarget]:t.conflictTarget;n.batchUpsert=d(e.BatchUpsertEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxBatchSize!==void 0?{maxBatchSize:t.maxBatchSize}:{},...r!==void 0?{upsertKeys:r}:{}}});}if(o.export!==void 0&&e.ExportEndpoint){let t=o.export;n.export=d(e.ExportEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,extras:{...t.maxRows!==void 0?{maxExportRecords:t.maxRows}:{},...t.formats!==void 0&&t.formats.length>0?{defaultFormat:t.formats[0]}:{}}});}if(o.import!==void 0&&e.ImportEndpoint){let t=o.import;n.import=d(e.ImportEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.maxRows!==void 0?{maxBatchSize:t.maxRows}:{}}});}if(o.upsert!==void 0&&e.UpsertEndpoint){let t=o.upsert,r=typeof t.conflictTarget=="string"?[t.conflictTarget]:t.conflictTarget;n.upsert=d(e.UpsertEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,bodySchema:t.bodySchema,beforeHookMode:t.hooks?.beforeMode,afterHookMode:t.hooks?.afterMode,before:t.hooks?.before,after:t.hooks?.after,extras:{...r!==void 0?{upsertKeys:r}:{}}});}if(o.clone!==void 0&&e.CloneEndpoint){let t=o.clone;n.clone=d(e.CloneEndpoint,{meta:o.meta,schema:t.openapi,middlewares:t.middlewares,before:t.hooks?.before,after:t.hooks?.after,extras:{...t.fieldsToReset!==void 0?{excludeFromClone:t.fieldsToReset}:{}}});}return n}
2
2
  export{R as CreateBuilder,j as CrudBuilder,_ as DeleteBuilder,P as HonoOpenAPIHandler,fe as HttpErrorSchema,A as ListBuilder,Ia as MemoryAdapters,H as ReadBuilder,F as UpdateBuilder,v as ZodErrorSchema,me as ZodIssueSchema,Jr as buildPerTenantOpenApi,ka as commonResponses,q as contentJson,ba as createCreate,Ca as createCrudMiddleware,Oa as createDelete,da as createErrorHandler,ga as createErrorSchema,xa as createList,Ea as createOneOfErrorSchema,ya as createRead,ca as createSubscribeHandler,Sa as createUpdate,wa as createValidationHook,Pa as crud,va as defineEndpoints,fa as errorResponse,qr as fromHono,V as getHandlerForApp,y as httpErrorContent,Z as jsonContent,ha as jsonContentRequired,Ma as openApiValidationHook,ua as registerCrud,ue as resolveErrorEnvelope,ma as successResponse,aa as toOpenApiPaths,Xr as wrapCacheStorageForOpenApi,ce as zodErrorMapper};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hono-crud",
3
- "version": "0.13.0",
3
+ "version": "0.13.1",
4
4
  "description": "CRUD generator for Hono with Zod validation and OpenAPI generation",
5
5
  "author": "Kauan Guesser <contato@kauan.net>",
6
6
  "license": "MIT",
@@ -1,4 +0,0 @@
1
- import {t,u,v,w,x,z as z$1,B as B$1,C,D as D$1,E,A as A$1,F as F$1,G,H as H$1,I as I$1,J as J$1,K as K$1,L as L$1,T,U as U$1,ba,ca,y}from'./chunk-ZBCVLQ3W.js';import {b as b$1}from'./chunk-DMGP7QDL.js';import {getTableColumns,eq,inArray,between,isNull,isNotNull,ilike,like,notInArray,lte,lt,gte,gt as gt$1,ne as ne$1,and,sql,or,desc,asc}from'drizzle-orm';import {z}from'zod';function X(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 b(l,e){let n=getTableColumns(l),o=n[e];if(!o)throw new Error(`Column '${e}' not found in table. Available columns: ${Object.keys(n).join(", ")}`);return o}async function Pe(l,e,n,o){if(!o.table)return e;let t=o.table;switch(o.type){case "hasOne":{let r=o.localKey||"id",s=e[r];if(s==null)return e;let i=b(t,o.foreignKey),a=await l.select().from(t).where(eq(i,s)).limit(1);return {...e,[n]:a[0]||null}}case "hasMany":{let r=o.localKey||"id",s=e[r];if(s==null)return {...e,[n]:[]};let i=b(t,o.foreignKey),a=await l.select().from(t).where(eq(i,s));return {...e,[n]:a}}case "belongsTo":{let r=e[o.foreignKey];if(r==null)return {...e,[n]:null};let s=b(t,o.localKey||"id"),i=await l.select().from(t).where(eq(s,r)).limit(1);return {...e,[n]:i[0]||null}}default:return e}}async function de(l,e,n,o){if(!o?.relations?.length||!n.model.relations)return e;let t={...e};for(let r of o.relations){let s=n.model.relations[r];s&&(t=await Pe(l,t,r,s));}return t}async function j(l,e,n,o){if(!e.length||!o?.relations?.length||!n.model.relations)return e;let t=e.map(r=>({...r}));for(let r of o.relations){let s=n.model.relations[r];if(!s||!s.table)continue;let i=s.table;switch(s.type){case "hasOne":case "hasMany":{let a=s.localKey||"id",d=[...new Set(t.map(p=>p[a]).filter(p=>p!=null))];if(d.length===0){t=t.map(p=>({...p,[r]:s.type==="hasMany"?[]:null}));continue}let u=b(i,s.foreignKey),c=await l.select().from(i).where(inArray(u,d)),m=new Map;for(let p of c){let g=p[s.foreignKey];m.has(g)||m.set(g,[]),m.get(g).push(p);}t=t.map(p=>{let g=p[a],h=m.get(g)||[];return {...p,[r]:s.type==="hasMany"?h:h[0]||null}});break}case "belongsTo":{let a=s.localKey||"id",d=[...new Set(t.map(p=>p[s.foreignKey]).filter(p=>p!=null))];if(d.length===0){t=t.map(p=>({...p,[r]:null}));continue}let u=b(i,a),c=await l.select().from(i).where(inArray(u,d)),m=new Map;for(let p of c){let g=p[a];m.set(g,p);}t=t.map(p=>{let g=p[s.foreignKey];return {...p,[r]:m.get(g)||null}});break}}}return t}function O(l,e){let n=b(l,e.field);switch(e.operator){case "eq":return eq(n,e.value);case "ne":return ne$1(n,e.value);case "gt":return gt$1(n,e.value);case "gte":return gte(n,e.value);case "lt":return lt(n,e.value);case "lte":return lte(n,e.value);case "in":return inArray(n,e.value);case "nin":return notInArray(n,e.value);case "like":return like(n,e.value);case "ilike":return ilike(n,e.value);case "null":return e.value?isNull(n):isNotNull(n);case "between":{let[o,t]=e.value;return between(n,o,t)}default:return}}function D(l){let e=l;if(e._tx)return e._tx;if(e.db)return e.db;let n=e.context?.get?.("db");if(n)return n;throw new Error(`Database not configured. Either:
2
- 1. Set db property: db = myDb;
3
- 2. Use middleware: c.set("db", myDb);
4
- 3. Use factory: createDrizzleCrud(db, meta)`)}var _=class extends t{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getRelatedTable(e){return e.table}async create(e,n){let o=n??this.getDb(),t=this.getTable(),r=this.applyManagedInsertFields(e,"drizzle");return (await o.insert(t).values(r).returning())[0]}async createNested(e,n,o,t,r){let s=r??this.getDb(),i=this.getRelatedTable(o);if(!i)return b$1().warn(`Related table not found for ${n}. Add 'table' to the relation config.`),[];let a=Array.isArray(t)?t:[t],d=[];for(let u of a){if(typeof u!="object"||u===null)continue;let c={...u,id:crypto.randomUUID(),[o.foreignKey]:e},m=await s.insert(i).values(c).returning();m[0]&&d.push(m[0]);}return d}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 u{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async read(e,n,o){let t=this.getTable(),r=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),i=[eq(r,e)];if(n)for(let[u,c]of Object.entries(n))i.push(eq(this.getColumn(u),c));s.enabled&&i.push(isNull(this.getColumn(s.field)));let a=await this.getDb().select().from(t).where(and(...i)).limit(1);return a[0]?await de(this.getDb(),a[0],this._meta,o):null}},P=class extends v{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}getRelatedTable(e){return e.table}async findExisting(e,n,o){let t=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),a=[eq(s,e)];if(n)for(let[u,c]of Object.entries(n))a.push(eq(this.getColumn(u),c));return i.enabled&&a.push(isNull(this.getColumn(i.field))),(await t.select().from(r).where(and(...a)).limit(1))[0]||null}async update(e,n,o,t){let r=t??this.getDb(),s=this.getTable(),i=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),d=[eq(i,e)];if(o)for(let[c,m]of Object.entries(o))d.push(eq(this.getColumn(c),m));return a.enabled&&d.push(isNull(this.getColumn(a.field))),(await r.update(s).set(this.applyManagedUpdateFields(n)).where(and(...d)).returning())[0]||null}async processNestedWrites(e,n,o,t,r){let s=r??this.getDb(),i=this.getRelatedTable(o);if(!i)return b$1().warn(`Related table not found for ${n}. Add 'table' to the relation config.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]};let a={created:[],updated:[],deleted:[],connected:[],disconnected:[]},d=b(i,o.foreignKey),u=b(i,"id");if(t.create){let c=Array.isArray(t.create)?t.create:[t.create];for(let m of c){if(typeof m!="object"||m===null)continue;let p={...m,id:crypto.randomUUID(),[o.foreignKey]:e},g=await s.insert(i).values(p).returning();g[0]&&a.created.push(g[0]);}}if(t.update)for(let c of t.update){if(!c.id||!(await s.select().from(i).where(and(eq(u,c.id),eq(d,e))).limit(1))[0])continue;let{id:p,...g}=c,h=await s.update(i).set(g).where(eq(u,p)).returning();h[0]&&a.updated.push(h[0]);}if(t.delete)for(let c of t.delete)(await s.delete(i).where(and(eq(u,c),eq(d,e))).returning())[0]&&a.deleted.push(c);if(t.connect)for(let c of t.connect)(await s.update(i).set({[o.foreignKey]:e}).where(eq(u,c)).returning())[0]&&a.connected.push(c);if(t.disconnect)for(let c of t.disconnect)(await s.update(i).set({[o.foreignKey]:null}).where(and(eq(u,c),eq(d,e))).returning())[0]&&a.disconnected.push(c);return a}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 w{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}getRelatedTable(e){return e.table}async findForDelete(e,n,o){let t=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),a=[eq(s,e)];if(n)for(let[u,c]of Object.entries(n))a.push(eq(this.getColumn(u),c));return i.enabled&&a.push(isNull(this.getColumn(i.field))),(await t.select().from(r).where(and(...a)).limit(1))[0]||null}async delete(e,n,o){let t=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),a=[eq(s,e)];if(n)for(let[d,u]of Object.entries(n))a.push(eq(this.getColumn(d),u));return i.enabled&&a.push(isNull(this.getColumn(i.field))),i.enabled?(await t.update(r).set({[i.field]:new Date}).where(and(...a)).returning())[0]||null:(await t.delete(r).where(and(...a)).returning())[0]||null}async countRelated(e,n,o,t){let r=t??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=b(s,o.foreignKey),a=await r.select({count:sql`count(*)`}).from(s).where(eq(i,e));return Number(a[0]?.count)||0}async deleteRelated(e,n,o,t){let r=t??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=b(s,o.foreignKey);return (await r.delete(s).where(eq(i,e)).returning()).length}async nullifyRelated(e,n,o,t){let r=t??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=b(s,o.foreignKey);return (await r.update(s).set({[o.foreignKey]:null}).where(eq(i,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()}},B=class extends x{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async list(e){let n=this.getTable(),o=[],t=this.getSoftDeleteConfig();if(t.enabled){let y=this.getColumn(t.field);e.options.onlyDeleted?o.push(isNotNull(y)):e.options.withDeleted||o.push(isNull(y));}for(let y of e.filters){let R=O(n,y);R&&o.push(R);}if(e.options.search&&this.searchFields.length>0){let y=this.searchFields.map(R=>{let q=this.getColumn(R);return sql`LOWER(${q}) LIKE LOWER(${`%${e.options.search}%`})`});o.push(or(...y));}let r=o.length>0?and(...o):void 0,s=this.getDb(),i=await s.select({count:sql`count(*)`}).from(n).where(r),a=Number(i[0]?.count)||0,d=s.select().from(n).where(r);if(e.options.order_by){let y=this.getColumn(e.options.order_by),R=e.options.order_by_direction==="desc"?desc:asc;d=d.orderBy(R(y));}let u=e.options.page||1,c=e.options.per_page||this.defaultPerPage;d=d.limit(c).offset((u-1)*c);let m=await d,p={relations:e.options.include||[]},g=await j(this.getDb(),m,this._meta,p),h=Math.ceil(a/c);return {result:g,result_info:{page:u,per_page:c,total_count:a,total_pages:h,has_next_page:u<h,has_prev_page:u>1}}}},A=class extends z$1{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async restore(e,n,o){let t=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),a=[eq(s,e)];if(n)for(let[u,c]of Object.entries(n))a.push(eq(this.getColumn(u),c));return a.push(isNotNull(this.getColumn(i.field))),(await t.update(r).set({[i.field]:null}).where(and(...a)).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 L=class extends B$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}async batchCreate(e){let n=this.getTable(),o=e.map(r=>this.applyManagedInsertFields(r,"drizzle"));return await this.getDb().insert(n).values(o).returning()}},K=class extends C{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async batchUpdate(e){let n=this.getTable(),o=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),r=[],s=[];for(let i of e){let a=[eq(o,i.id)];t.enabled&&a.push(isNull(this.getColumn(t.field)));let d=await this.getDb().update(n).set(this.applyManagedUpdateFields(i.data)).where(and(...a)).returning();d[0]?r.push(d[0]):s.push(i.id);}return {updated:r,notFound:s}}},Z=class extends D$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async batchDelete(e){let n=this.getTable(),o=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),r=[inArray(o,e)];t.enabled&&r.push(isNull(this.getColumn(t.field)));let s;t.enabled?s=await this.getDb().update(n).set({[t.field]:new Date}).where(and(...r)).returning():s=await this.getDb().delete(n).where(and(...r)).returning();let i=s,a=new Set(i.map(u=>String(u[this.lookupField]))),d=e.filter(u=>!a.has(u));return {deleted:i,notFound:d}}},F=class extends E{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async batchRestore(e){let n=this.getTable(),o=this.getColumn(this.lookupField),t=this.getSoftDeleteConfig(),r=[inArray(o,e),isNotNull(this.getColumn(t.field))],i=await this.getDb().update(n).set({[t.field]:null}).where(and(...r)).returning(),a=new Set(i.map(u=>String(u[this.lookupField]))),d=e.filter(u=>!a.has(u));return {restored:i,notFound:d}}};function $e(l){return l.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_")}function gt(l){return l.split(/\s+/).filter(e=>e.length>0)}var Q=class extends A$1{db;dialect="sqlite";getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async findExisting(e){let n=this.getTable(),o=this.getUpsertKeys(),t=this.getSoftDeleteConfig(),r=[];for(let i of o){let a=e[i];a!==void 0&&r.push(eq(this.getColumn(i),a));}return t.enabled&&r.push(isNull(this.getColumn(t.field))),r.length===0?null:(await this.getDb().select().from(n).where(and(...r)).limit(1))[0]||null}async create(e){let n=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(n).values(o).returning())[0]}async update(e,n){let o=this.getTable(),t=this._meta.model.primaryKeys[0],r=e[t];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(n)).where(eq(this.getColumn(t),r)).returning())[0]}async nativeUpsert(e,n){let o=this.getTable(),t=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=this.getSoftDeleteConfig(),i=this.getTimestampsConfig(),a=this.applyManagedInsertFields(e,"drizzle"),d={};for(let[h,y]of Object.entries(e))!t.includes(h)&&h!==r&&(this.createOnlyFields?.includes(h)||(d[h]=y));i.enabled&&(d[i.updatedAt]=Date.now());let u=t.map(h=>this.getColumn(h)),c;s.enabled&&(c=isNull(this.getColumn(s.field)));let m=Object.keys(d).length>0?d:{[r]:sql`${this.getColumn(r)}`},p=this.getDb().insert(o).values(a);return this.dialect==="mysql"?{data:(await p.onDuplicateKeyUpdate({set:m}).returning())[0],created:false}:{data:(await p.onConflictDoUpdate({target:u,set:m,where:c}).returning())[0],created:false}}},N=class extends F$1{db;dialect="sqlite";getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async findExisting(e){let n=this.getTable(),o=this.getUpsertKeys(),t=[];for(let s of o){let i=e[s];i!==void 0&&t.push(eq(this.getColumn(s),i));}return t.length===0?null:(await this.getDb().select().from(n).where(and(...t)).limit(1))[0]||null}async create(e){let n=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(n).values(o).returning())[0]}async update(e,n){let o=this.getTable(),t=this._meta.model.primaryKeys[0],r=e[t];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(n)).where(eq(this.getColumn(t),r)).returning())[0]}async nativeBatchUpsert(e,n){if(e.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let o=this.getTable(),t=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=this.getTimestampsConfig(),i=e.map(g=>this.applyManagedInsertFields(g,"drizzle")),a={},d=e[0];for(let g of Object.keys(d))!t.includes(g)&&g!==r&&(this.createOnlyFields?.includes(g)||(a[g]=sql`excluded.${sql.identifier(g)}`));s.enabled&&(a[s.updatedAt]=Date.now());let u=t.map(g=>this.getColumn(g)),c=Object.keys(a).length>0?a:{[r]:sql`${this.getColumn(r)}`},m=this.getDb().insert(o).values(i),p=await(this.dialect==="mysql"?m.onDuplicateKeyUpdate({set:c}):m.onConflictDoUpdate({target:u,set:c})).returning();return {items:p.map((g,h)=>({data:g,created:false,index:h})),createdCount:0,updatedCount:p.length,totalCount:p.length}}},Le=class extends G{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async recordExists(e){let n=this.getTable(),o=await this.getDb().select({count:sql`count(*)`}).from(n).where(eq(this.getColumn("id"),e));return Number(o[0]?.count)>0}},Ke=class extends H$1{},Ze=class extends I$1{},Fe=class extends J$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async rollback(e,n,o){let t=this.getTable(),r=this.getVersioningConfig().field;return (await this.getDb().update(t).set({...n,[r]:o}).where(eq(this.getColumn("id"),e)).returning())[0]}},H=class extends K$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async aggregate(e){let n=this.getTable(),o=[],t=this.getSoftDeleteConfig();if(t.enabled){let{query:i}=await this.getValidatedData();i?.withDeleted===true||i?.withDeleted==="true"||o.push(isNull(this.getColumn(t.field)));}if(e.filters)for(let[i,a]of Object.entries(e.filters))if(typeof a=="object"&&a!==null)for(let[d,u]of Object.entries(a)){let c=O(n,{field:i,operator:d,value:u});c&&o.push(c);}else o.push(eq(this.getColumn(i),a));let r=o.length>0?and(...o):void 0,s=await this.getDb().select().from(n).where(r);return L$1(s,e)}},J=class extends T{db;getDb(){return D(this)}useNativeSearch=false;vectorColumn;vectorConfig="english";getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async search(e,n){let o=this.getTable(),t=[],r=this.getSoftDeleteConfig();r.enabled&&(n.options.onlyDeleted?t.push(isNotNull(this.getColumn(r.field))):n.options.withDeleted||t.push(isNull(this.getColumn(r.field))));for(let w of n.filters){let M=O(o,w);M&&t.push(M);}let s=this.getSearchableFields(),i=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=(M,x)=>{try{let se=this.getColumn(M),W=`%${$e(x)}%`;return sql`LOWER(CAST(${se} AS TEXT)) LIKE LOWER(${W}) ESCAPE '\\'`}catch{return}};if(e.mode==="all"){let M=gt(e.query);if(M.length>0){let x=[];for(let se of M){let W=i.map(ie=>w(ie,se)).filter(ie=>ie!==void 0);W.length>0&&x.push(or(...W));}x.length>0&&t.push(and(...x));}}else {let M=i.map(x=>w(x,e.query)).filter(x=>x!==void 0);M.length>0&&t.push(or(...M));}}let a=t.length>0?and(...t):void 0,d=await this.getDb().select({count:sql`count(*)`}).from(o).where(a),u=Number(d[0]?.count)||0,c=this.getDb().select().from(o).where(a);if(n.options.order_by){let w=this.getColumn(n.options.order_by),M=n.options.order_by_direction==="desc"?desc:asc;c=c.orderBy(M(w));}let m=n.options.page||1,p=n.options.per_page||this.defaultPerPage;c=c.limit(p).offset((m-1)*p);let g=await c,h=e.mode==="all"?{...e,mode:"any"}:e,y=U$1(g,h,s),R={relations:n.options.include||[]},q=y.map(w=>w.item),Xe=await j(this.getDb(),q,this._meta,R);return {items:y.map((w,M)=>({...w,item:Xe[M]})),totalCount:u}}},Y=class extends ba{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async list(e){let n=this.getTable(),o=[],t=this.getSoftDeleteConfig();if(t.enabled){let h=this.getColumn(t.field);e.options.onlyDeleted?o.push(isNotNull(h)):e.options.withDeleted||o.push(isNull(h));}for(let h of e.filters){let y=O(n,h);y&&o.push(y);}if(e.options.search&&this.searchFields.length>0){let h=`%${$e(e.options.search)}%`,y=this.searchFields.map(R=>{let q=this.getColumn(R);return sql`LOWER(${q}) LIKE LOWER(${h}) ESCAPE '\\'`});o.push(or(...y));}let r=o.length>0?and(...o):void 0,s=await this.getDb().select({count:sql`count(*)`}).from(n).where(r),i=Number(s[0]?.count)||0,a=this.getDb().select().from(n).where(r);if(e.options.order_by){let h=this.getColumn(e.options.order_by),y=e.options.order_by_direction==="desc"?desc:asc;a=a.orderBy(y(h));}let d=e.options.page||1,u=e.options.per_page||this.defaultPerPage;a=a.limit(u).offset((d-1)*u);let c=await a,m={relations:e.options.include||[]},p=await j(this.getDb(),c,this._meta,m),g=Math.ceil(i/u);return {result:p,result_info:{page:d,per_page:u,total_count:i,total_pages:g,has_next_page:d<g,has_prev_page:d>1}}}},ee=class extends ca{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async findExisting(e){let n=this.getTable(),o=this.getUpsertKeys(),t=this.getSoftDeleteConfig(),r=[];for(let i of o){let a=e[i];a!==void 0&&r.push(eq(this.getColumn(i),a));}return t.enabled&&r.push(isNull(this.getColumn(t.field))),r.length===0?null:(await this.getDb().select().from(n).where(and(...r)).limit(1))[0]||null}async create(e){let n=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(n).values(o).returning())[0]}async update(e,n){let o=this.getTable(),t=this._meta.model.primaryKeys[0],r=e[t];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(n)).where(eq(this.getColumn(t),r)).returning())[0]}},te=class extends y{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}generateId(){return crypto.randomUUID()}async findSource(e,n){let o=this.getTable(),t=this.getColumn(this.lookupField),r=this.getSoftDeleteConfig(),s=[eq(t,e)];if(n)for(let[a,d]of Object.entries(n))s.push(eq(this.getColumn(a),d));r.enabled&&s.push(isNull(this.getColumn(r.field)));let i=await this.getDb().select().from(o).where(and(...s)).limit(1);return i[0]?i[0]:null}async createClone(e){let n=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle",()=>this.generateId());return (await this.getDb().insert(n).values(o).returning())[0]}};function an(l,e,n){let o=n?.dialect??"sqlite";return {Create:class extends _{_meta=e;db=l},Read:class extends I{_meta=e;db=l},Update:class extends P{_meta=e;db=l},Delete:class extends U{_meta=e;db=l},List:class extends B{_meta=e;db=l},Restore:class extends A{_meta=e;db=l},Upsert:class extends Q{_meta=e;db=l;dialect=o},BatchCreate:class extends L{_meta=e;db=l},BatchUpdate:class extends K{_meta=e;db=l},BatchDelete:class extends Z{_meta=e;db=l},BatchRestore:class extends F{_meta=e;db=l},BatchUpsert:class extends N{_meta=e;db=l;dialect=o}}}var oe=null,We=false,ne=null;async function re(){if(We){if(ne)throw ne;return oe}We=true;try{return oe=await import('drizzle-zod'),oe}catch{throw ne=new Error("drizzle-zod is not installed. Please install it: npm install drizzle-zod"),ne}}async function mt(l,e){return (await re()).createSelectSchema(l,e)}async function bt(l,e){return (await re()).createInsertSchema(l,e)}async function ht(l,e){let n=await re();return n.createUpdateSchema?n.createUpdateSchema(l,e):n.createInsertSchema(l,e).partial()}async function ft(l,e){let n=await re(),o=e?.coerceDates!==false,t=o?Mt(l):new Set,r=n.createSelectSchema(l,e?.selectRefine),s=n.createInsertSchema(l,e?.insertRefine),i;return n.createUpdateSchema?i=n.createUpdateSchema(l,e?.updateRefine):i=n.createInsertSchema(l,e?.updateRefine).partial(),o&&t.size>0&&(s=Ve(s,t),i=Ve(i,t)),{select:r,insert:s,update:i}}function zt(){return oe!==null}var Dt=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()),yt=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 Mt(l){let e=new Set,n=l;for(let[o,t]of Object.entries(n)){if(o==="_"||o==="$inferInsert"||o==="$inferSelect")continue;let r=t;if(!r||typeof r!="object")continue;let s=String(r.dataType??"").toLowerCase(),i=String(r.columnType??"").toLowerCase(),a=r.config,d=String(a?.dataType??"").toLowerCase();(s.includes("timestamp")||s.includes("date")||s.includes("datetime")||i.includes("pgtimestamp")||i.includes("pgdate")||i.includes("mysqltimestamp")||i.includes("mysqldate")||i.includes("sqlitetimestamp")||d.includes("timestamp")||d.includes("date"))&&e.add(o);}return e}function Ve(l,e){if(e.size===0)return l;let n=l.shape,o={};for(let[t,r]of Object.entries(n))if(e.has(t)){let s=r.isOptional?.()??false,i=r.isNullable?.()??false,a=Dt;(i||s)&&(a=yt),s&&(a=a.optional()),o[t]=a;}else o[t]=r;return z.object(o)}var Rn={CreateEndpoint:_,ListEndpoint:B,ReadEndpoint:I,UpdateEndpoint:P,DeleteEndpoint:U,RestoreEndpoint:A,BatchCreateEndpoint:L,BatchUpdateEndpoint:K,BatchDeleteEndpoint:Z,BatchRestoreEndpoint:F,BatchUpsertEndpoint:N,SearchEndpoint:J,AggregateEndpoint:H,ExportEndpoint:Y,ImportEndpoint:ee,UpsertEndpoint:Q,CloneEndpoint:te};export{ee as A,te as B,an as C,mt as D,bt as E,ht as F,ft as G,zt as H,Rn as I,X as a,f as b,b as c,Pe as d,de as e,j as f,O as g,_ as h,I as i,P as j,U as k,B as l,A as m,L as n,K as o,Z as p,F as q,Q as r,N as s,Le as t,Ke as u,Ze as v,Fe as w,H as x,J as y,Y as z};