hono-crud 0.12.0 → 0.12.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4 -0
- package/dist/adapters/drizzle/index.d.ts +4 -2
- package/dist/adapters/drizzle/index.js +1 -1
- package/dist/adapters/memory/index.d.ts +4 -2
- package/dist/adapters/memory/index.js +1 -1
- package/dist/adapters/prisma/index.d.ts +4 -2
- package/dist/adapters/prisma/index.js +1 -1
- package/dist/{bulk-patch-DE5uhC6m.d.ts → bulk-patch-BXUevk8p.d.ts} +1 -1
- package/dist/cache/index.js +1 -1
- package/dist/{chunk-4CM6OCS3.js → chunk-3DJMHE6N.js} +1 -1
- package/dist/chunk-BEKJR6N7.js +1 -0
- package/dist/chunk-CTK2CYX2.js +11 -0
- package/dist/{chunk-ESMN3MEH.js → chunk-CY77OZ42.js} +1 -1
- package/dist/chunk-S55I5NRE.js +4 -0
- package/dist/chunk-ZYPG22J4.js +1 -0
- package/dist/exceptions-BEvDdXFC.d.ts +70 -0
- package/dist/{import-5Dvy1PMu.d.ts → import-CQ4VqBhO.d.ts} +83 -2
- package/dist/{index-5CxvXfpu.d.ts → index-DGjZ5b4T.d.ts} +1 -1
- package/dist/index.d.ts +8 -7
- package/dist/index.js +2 -2
- package/dist/logging/index.js +1 -1
- package/dist/rate-limit/index.d.ts +383 -4
- package/dist/rate-limit/index.js +1 -1
- package/dist/storage/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-26IVGJU7.js +0 -1
- package/dist/chunk-6WIZTUZK.js +0 -1
- package/dist/chunk-M7YICFXP.js +0 -11
- package/dist/chunk-NIGKMRDM.js +0 -4
- package/dist/index-DhCIATbD.d.ts +0 -449
package/CHANGELOG.md
CHANGED
|
@@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
9
9
|
%b
|
|
10
10
|
%b
|
|
11
11
|
%b
|
|
12
|
+
%b
|
|
13
|
+
%b
|
|
12
14
|
## [0.8.0] — 2026-05-03
|
|
13
15
|
|
|
14
16
|
### Added
|
|
@@ -83,3 +85,5 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
83
85
|
[0.10.0]: https://github.com/kshdotdev/hono-crud/compare/v0.9.0...v0.10.0
|
|
84
86
|
[0.11.0]: https://github.com/kshdotdev/hono-crud/compare/v0.10.0...v0.11.0
|
|
85
87
|
[0.12.0]: https://github.com/kshdotdev/hono-crud/compare/v0.11.0...v0.12.0
|
|
88
|
+
[0.12.1]: https://github.com/kshdotdev/hono-crud/compare/v0.12.0...v0.12.1
|
|
89
|
+
[0.12.2]: https://github.com/kshdotdev/hono-crud/compare/v0.12.1...v0.12.2
|
|
@@ -1,14 +1,16 @@
|
|
|
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-Bg1Mpdsl.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-
|
|
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-CQ4VqBhO.js';
|
|
5
5
|
import { z } from 'zod';
|
|
6
|
-
import { A as AdapterBundle } from '../../index-
|
|
6
|
+
import { A as AdapterBundle } from '../../index-DGjZ5b4T.js';
|
|
7
7
|
import '../../types-B5wq2iKZ.js';
|
|
8
8
|
import '../../types-BAcN7U0B.js';
|
|
9
9
|
import '@hono/zod-openapi';
|
|
10
10
|
import '../../route-Ctv6vIW0.js';
|
|
11
11
|
import 'hono/utils/http-status';
|
|
12
|
+
import '../../exceptions-BEvDdXFC.js';
|
|
13
|
+
import 'hono/http-exception';
|
|
12
14
|
import '../../audit/index.js';
|
|
13
15
|
import '../../registry-PNJjvSvm.js';
|
|
14
16
|
import '../../versioning/index.js';
|
|
@@ -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-
|
|
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-S55I5NRE.js';import'../../chunk-CTK2CYX2.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-4PBGEU64.js';import'../../chunk-3DE2MG3R.js';import'../../chunk-FC56WWPB.js';import'../../chunk-KLBMVJX3.js';import'../../chunk-FHABLABR.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,10 +1,12 @@
|
|
|
1
1
|
import { Env } from 'hono';
|
|
2
|
-
import { a as CreateEndpoint, M as ModelObject, D as DeleteEndpoint, L as ListEndpoint, R as ReadEndpoint, b as RestoreEndpoint, U as UpdateEndpoint, B as BatchCreateEndpoint, c as BatchDeleteEndpoint, d as BatchRestoreEndpoint, e as BatchUpdateEndpoint, f as BatchUpdateItem, g as BatchUpsertEndpoint, A as AggregateEndpoint, h as CloneEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, i as UpsertEndpoint, V as VersionCompareEndpoint, j as VersionHistoryEndpoint, k as VersionReadEndpoint, l as VersionRollbackEndpoint } from '../../import-
|
|
2
|
+
import { a as CreateEndpoint, M as ModelObject, D as DeleteEndpoint, L as ListEndpoint, R as ReadEndpoint, b as RestoreEndpoint, U as UpdateEndpoint, B as BatchCreateEndpoint, c as BatchDeleteEndpoint, d as BatchRestoreEndpoint, e as BatchUpdateEndpoint, f as BatchUpdateItem, g as BatchUpsertEndpoint, A as AggregateEndpoint, h as CloneEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, i as UpsertEndpoint, V as VersionCompareEndpoint, j as VersionHistoryEndpoint, k as VersionReadEndpoint, l as VersionRollbackEndpoint } from '../../import-CQ4VqBhO.js';
|
|
3
3
|
import { M as MetaInput, h as RelationConfig, L as ListFilters, P as PaginatedResult, I as IncludeOptions, N as NestedUpdateInput, i as NestedWriteResult, j as AggregateOptions, k as AggregateResult, S as SearchOptions, l as SearchResult } from '../../types-Bg1Mpdsl.js';
|
|
4
|
-
import { B as BulkPatchEndpoint } from '../../bulk-patch-
|
|
4
|
+
import { B as BulkPatchEndpoint } from '../../bulk-patch-BXUevk8p.js';
|
|
5
5
|
import 'zod';
|
|
6
6
|
import '../../route-Ctv6vIW0.js';
|
|
7
7
|
import 'hono/utils/http-status';
|
|
8
|
+
import '../../exceptions-BEvDdXFC.js';
|
|
9
|
+
import 'hono/http-exception';
|
|
8
10
|
import '../../audit/index.js';
|
|
9
11
|
import '../../registry-PNJjvSvm.js';
|
|
10
12
|
import '../../types-B5wq2iKZ.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{f as MEMORY_NOOP_TX,x as MemoryAggregateEndpoint,m as MemoryBatchCreateEndpoint,o as MemoryBatchDeleteEndpoint,p as MemoryBatchRestoreEndpoint,n as MemoryBatchUpdateEndpoint,q as MemoryBatchUpsertEndpoint,B as MemoryBulkPatchEndpoint,r as MemoryCloneEndpoint,g as MemoryCreateEndpoint,j as MemoryDeleteEndpoint,z as MemoryExportEndpoint,A as MemoryImportEndpoint,k as MemoryListEndpoint,h as MemoryReadEndpoint,l as MemoryRestoreEndpoint,y as MemorySearchEndpoint,i as MemoryUpdateEndpoint,s as MemoryUpsertEndpoint,v as MemoryVersionCompareEndpoint,t as MemoryVersionHistoryEndpoint,u as MemoryVersionReadEndpoint,w as MemoryVersionRollbackEndpoint,d as clearStorage,e as getStorage,c as getStore,b as storage}from'../../chunk-
|
|
1
|
+
export{f as MEMORY_NOOP_TX,x as MemoryAggregateEndpoint,m as MemoryBatchCreateEndpoint,o as MemoryBatchDeleteEndpoint,p as MemoryBatchRestoreEndpoint,n as MemoryBatchUpdateEndpoint,q as MemoryBatchUpsertEndpoint,B as MemoryBulkPatchEndpoint,r as MemoryCloneEndpoint,g as MemoryCreateEndpoint,j as MemoryDeleteEndpoint,z as MemoryExportEndpoint,A as MemoryImportEndpoint,k as MemoryListEndpoint,h as MemoryReadEndpoint,l as MemoryRestoreEndpoint,y as MemorySearchEndpoint,i as MemoryUpdateEndpoint,s as MemoryUpsertEndpoint,v as MemoryVersionCompareEndpoint,t as MemoryVersionHistoryEndpoint,u as MemoryVersionReadEndpoint,w as MemoryVersionRollbackEndpoint,d as clearStorage,e as getStorage,c as getStore,b as storage}from'../../chunk-ZYPG22J4.js';import'../../chunk-CTK2CYX2.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-4PBGEU64.js';import'../../chunk-3DE2MG3R.js';import'../../chunk-FC56WWPB.js';import'../../chunk-KLBMVJX3.js';import'../../chunk-FHABLABR.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,10 +1,12 @@
|
|
|
1
1
|
import { Env } from 'hono';
|
|
2
|
-
import { a as CreateEndpoint, M as ModelObject, D as DeleteEndpoint, L as ListEndpoint, R as ReadEndpoint, U as UpdateEndpoint, B as BatchCreateEndpoint, c as BatchDeleteEndpoint, d as BatchRestoreEndpoint, e as BatchUpdateEndpoint, f as BatchUpdateItem, g as BatchUpsertEndpoint, b as RestoreEndpoint, A as AggregateEndpoint, h as CloneEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, i as UpsertEndpoint, V as VersionCompareEndpoint, j as VersionHistoryEndpoint, k as VersionReadEndpoint, l as VersionRollbackEndpoint } from '../../import-
|
|
2
|
+
import { a as CreateEndpoint, M as ModelObject, D as DeleteEndpoint, L as ListEndpoint, R as ReadEndpoint, U as UpdateEndpoint, B as BatchCreateEndpoint, c as BatchDeleteEndpoint, d as BatchRestoreEndpoint, e as BatchUpdateEndpoint, f as BatchUpdateItem, g as BatchUpsertEndpoint, b as RestoreEndpoint, A as AggregateEndpoint, h as CloneEndpoint, E as ExportEndpoint, I as ImportEndpoint, S as SearchEndpoint, i as UpsertEndpoint, V as VersionCompareEndpoint, j as VersionHistoryEndpoint, k as VersionReadEndpoint, l as VersionRollbackEndpoint } from '../../import-CQ4VqBhO.js';
|
|
3
3
|
import { M as MetaInput, L as ListFilters, P as PaginatedResult, I as IncludeOptions, j as AggregateOptions, k as AggregateResult, m as AggregateField, S as SearchOptions, l as SearchResult } from '../../types-Bg1Mpdsl.js';
|
|
4
|
-
import { A as AdapterBundle } from '../../index-
|
|
4
|
+
import { A as AdapterBundle } from '../../index-DGjZ5b4T.js';
|
|
5
5
|
import 'zod';
|
|
6
6
|
import '../../route-Ctv6vIW0.js';
|
|
7
7
|
import 'hono/utils/http-status';
|
|
8
|
+
import '../../exceptions-BEvDdXFC.js';
|
|
9
|
+
import 'hono/http-exception';
|
|
8
10
|
import '../../audit/index.js';
|
|
9
11
|
import '../../registry-PNJjvSvm.js';
|
|
10
12
|
import '../../types-B5wq2iKZ.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{y as PrismaAdapters,w as PrismaAggregateEndpoint,j as PrismaBatchCreateEndpoint,l as PrismaBatchDeleteEndpoint,m as PrismaBatchRestoreEndpoint,k as PrismaBatchUpdateEndpoint,n as PrismaBatchUpsertEndpoint,x as PrismaCloneEndpoint,d as PrismaCreateEndpoint,g as PrismaDeleteEndpoint,p as PrismaExportEndpoint,q as PrismaImportEndpoint,h as PrismaListEndpoint,e as PrismaReadEndpoint,i as PrismaRestoreEndpoint,o as PrismaSearchEndpoint,f as PrismaUpdateEndpoint,r as PrismaUpsertEndpoint,u as PrismaVersionCompareEndpoint,s as PrismaVersionHistoryEndpoint,t as PrismaVersionReadEndpoint,v as PrismaVersionRollbackEndpoint,c as clearPrismaModelMappings,a as registerPrismaModelMapping,b as registerPrismaModelMappings}from'../../chunk-
|
|
1
|
+
export{y as PrismaAdapters,w as PrismaAggregateEndpoint,j as PrismaBatchCreateEndpoint,l as PrismaBatchDeleteEndpoint,m as PrismaBatchRestoreEndpoint,k as PrismaBatchUpdateEndpoint,n as PrismaBatchUpsertEndpoint,x as PrismaCloneEndpoint,d as PrismaCreateEndpoint,g as PrismaDeleteEndpoint,p as PrismaExportEndpoint,q as PrismaImportEndpoint,h as PrismaListEndpoint,e as PrismaReadEndpoint,i as PrismaRestoreEndpoint,o as PrismaSearchEndpoint,f as PrismaUpdateEndpoint,r as PrismaUpsertEndpoint,u as PrismaVersionCompareEndpoint,s as PrismaVersionHistoryEndpoint,t as PrismaVersionReadEndpoint,v as PrismaVersionRollbackEndpoint,c as clearPrismaModelMappings,a as registerPrismaModelMapping,b as registerPrismaModelMappings}from'../../chunk-BEKJR6N7.js';import'../../chunk-CTK2CYX2.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-4PBGEU64.js';import'../../chunk-3DE2MG3R.js';import'../../chunk-FC56WWPB.js';import'../../chunk-KLBMVJX3.js';import'../../chunk-FHABLABR.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,6 +1,6 @@
|
|
|
1
1
|
import { ZodObject, ZodRawShape } from 'zod';
|
|
2
2
|
import { Env } from 'hono';
|
|
3
|
-
import { C as CrudEndpoint, M as ModelObject } from './import-
|
|
3
|
+
import { C as CrudEndpoint, M as ModelObject } from './import-CQ4VqBhO.js';
|
|
4
4
|
import { M as MetaInput, H as HookMode, L as ListFilters, O as OpenAPIRouteSchema } from './types-Bg1Mpdsl.js';
|
|
5
5
|
|
|
6
6
|
/**
|
package/dist/cache/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{b as KVCacheStorage,a as RedisCacheStorage}from'../chunk-H3H65KZF.js';export{C as MemoryCacheStorage,y as createInvalidationPattern,z as createRelatedPatterns,x as generateCacheKey,E as getCacheStorage,A as matchesPattern,B as parseCacheKey,D as setCacheStorage,F as withCache,G as withCacheInvalidation}from'../chunk-
|
|
1
|
+
export{b as KVCacheStorage,a as RedisCacheStorage}from'../chunk-H3H65KZF.js';export{C as MemoryCacheStorage,y as createInvalidationPattern,z as createRelatedPatterns,x as generateCacheKey,E as getCacheStorage,A as matchesPattern,B as parseCacheKey,D as setCacheStorage,F as withCache,G as withCacheInvalidation}from'../chunk-3DJMHE6N.js';import'../chunk-3DE2MG3R.js';import'../chunk-GF2EC5G4.js';import'../chunk-2M5BM4VD.js';import'../chunk-FC56WWPB.js';import'../chunk-KLBMVJX3.js';import'../chunk-FHABLABR.js';import'../chunk-GBQQ3YQX.js';import'../chunk-DMGP7QDL.js';import'../chunk-MDHMZPXK.js';import'../chunk-VJRDAVID.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {b as b$4}from'./chunk-3DE2MG3R.js';import {a as a$3}from'./chunk-GF2EC5G4.js';import {b as b$3}from'./chunk-KLBMVJX3.js';import {a,g}from'./chunk-2M5BM4VD.js';import {a as a$1,i}from'./chunk-FC56WWPB.js';import {b,c}from'./chunk-GBQQ3YQX.js';import {b as b$2}from'./chunk-DMGP7QDL.js';import {e,a as a$2,b as b$1}from'./chunk-VJRDAVID.js';function B(e,t={}){let{ipHeader:n="X-Forwarded-For",trustProxy:r=true}=t;if(r){let s=e.req.header(n);if(s){let c=s.split(",")[0]?.trim();if(c)return c}let a=e.req.header("X-Real-IP")?.trim();if(a)return a;let i=e.req.header("CF-Connecting-IP")?.trim();if(i)return i}let o=e.req.raw;if(o&&typeof o.socket=="object"&&o.socket?.remoteAddress)return o.socket.remoteAddress;if(o?.cf?.ip)return o.cf.ip}function $(e){return a$2(e,"userId")}function z(e,t){let n=e.toLowerCase();for(let r of t){if(r instanceof RegExp){if(r.test(e))return true;continue}let o=r.toLowerCase();if(o.includes("*")){let s=o.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");if(new RegExp(`^${s}$`).test(n))return true}else if(n===o)return true}return false}function j(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(r=>j(r,t));if(typeof e!="object")return e;let n={};for(let[r,o]of Object.entries(e))z(r,t)?n[r]="[REDACTED]":typeof o=="object"&&o!==null?n[r]=j(o,t):n[r]=o;return n}function he(e,t){let n={};for(let[r,o]of Object.entries(e))n[r]=z(r,t)?"[REDACTED]":o;return n}function Ye(e,t){return z(e,t)}function ee(e,t){return j(e,t)}function te(e,t){return he(e,t)}function Ze(e,t){return a(e,t)}function ye(e,t,n){for(let r of n)if(a(e,r))return true;if(t.length===0)return false;for(let r of t)if(a(e,r))return false;return true}function xe(e,t="X-Forwarded-For",n=false){return B(e,{ipHeader:t,trustProxy:n||true})}function re(e){let t={};return e.forEach((n,r)=>{t[r.toLowerCase()]=n;}),t}function Ce(e){let t={};return new URL(e.req.url).searchParams.forEach((r,o)=>{t[o]=r;}),t}function D(e,t){if(typeof e=="string")return e.length>t?e.substring(0,t)+"... [TRUNCATED]":e;let n=JSON.stringify(e);return n.length>t?{_truncated:true,_originalSize:n.length,_maxSize:t}:e}function Ee(e,t){if(!e)return false;if(t.length===0)return true;let n=e.toLowerCase();for(let r of t)if(n.includes(r.toLowerCase()))return true;return false}function Se(e){return $(e)}function Re(){return e()}var U=class extends a$1{constructor(t="Too many requests",n=60){super(t,429,"RATE_LIMIT_EXCEEDED",{retryAfter:n}),this.name="RateLimitExceededException";}};function q(e,t="X-Forwarded-For",n=false){return B(e,{ipHeader:t,trustProxy:n})??"unknown"}function ne(e){return $(e)??null}function we(e,t="X-API-Key"){return e.req.header(t)||null}function st(e,t){return a(e,t)}function ve(e,t){return t.some(n=>a(e,n))}function Ie(e,...t){let n=t.filter(r=>r!==void 0&&r!=="");return `${e}:${n.join(":")}`}function V(e){return e instanceof Error?e:new Error(String(e))}function Me(e,t){let n=V(e),r=new Error(`${t}: ${n.message}`);return r.cause=n,r}function Oe(e){return e instanceof Error?e.message:String(e)}var X=b("loggingStorage");function ht(e){X.set(e);}function yt(){return X.get()}var De=["authorization","cookie","x-api-key","x-auth-token"],Fe=["password","token","secret","apiKey","api_key","accessToken","access_token","refreshToken","refresh_token","creditCard","credit_card","ssn","socialSecurityNumber"],_e=["/health","/healthz","/ready","/readyz","/live","/livez","/metrics","/favicon.ico"];function xt(e){return a$2(e,"requestId")}function Ct(e){return a$2(e,"requestStartTime")}function Et(e={}){let t=e.enabled??true,n=e.level??"info",r=e.includePaths??[],o=e.excludePaths??_e,s=e.redactHeaders??De,a=e.redactBodyFields??Fe,i=e.requestBody??{enabled:false},c=e.responseBody??{enabled:false},u=e.includeHeaders??true,d=e.includeQuery??true,g=e.includeClientIp??true,C=e.ipHeader??"X-Forwarded-For",m=e.trustProxy??false,h=e.minResponseTimeMs??0,R=e.generateRequestId??Re;return async(l,P)=>{if(!t)return P();let w=l.req.path;if(ye(w,r,o))return P();let f=R(),T=Date.now();b$1(l,"requestId",f),b$1(l,"requestStartTime",T),l.header("X-Request-ID",f);let Ae=l.req.method,qe=l.req.url,oe;if(u){let E=re(l.req.raw.headers);oe=te(E,s);}let se;d&&(se=Ce(l));let ae;g&&(ae=xe(l,C,m));let Ke=Se(l),Q;if(i.enabled){let E=l.req.header("content-type"),H=i.contentTypes??[];if(Ee(E,H))try{let L=await l.req.raw.clone().text();if(L)try{let x=JSON.parse(L);x=ee(x,a);let y=i.maxSize??10240;Q=D(x,y);}catch{let x=i.maxSize??10240;Q=D(L,x);}}catch{}}let S,Y;try{await P();}catch(E){throw S=E instanceof Error?E:new Error(String(E)),E}finally{let H=Date.now()-T;if(H<h)return;let b=l.res.status,L;if(u){let p=re(l.res.headers);L=te(p,s);}if(c.enabled&&!S){let p=c.statusCodes??[];if(p.length===0||p.includes(b))try{let Z=await l.res.clone().text();if(Z)try{let M=JSON.parse(Z);M=ee(M,a);let He=c.maxSize??10240;Y=D(M,He);}catch{let M=c.maxSize??10240;Y=D(Z,M);}}catch{}}let x=n;e.levelResolver?x=e.levelResolver(l,H,b,S):S||b>=500?x="error":b>=400&&(x="warn");let y={id:f,timestamp:new Date(T).toISOString(),level:x,request:{method:Ae,path:w,url:qe,headers:oe,query:se,body:Q,clientIp:ae,userId:Ke},response:{statusCode:b,headers:L,body:Y,responseTimeMs:H}};if(S&&(y.error={message:S.message,name:S.name,stack:S.stack}),e.metadata){let p=typeof e.metadata=="function"?e.metadata(l):e.metadata;y.metadata=p;}e.formatter&&(y=e.formatter(y));let ie=Pe(l,e.storage);(async()=>{if(ie)try{await ie.store(y);}catch(p){e.onError&&e.onError(p instanceof Error?p:new Error(String(p)),y);}if(e.handlers)for(let p of e.handlers)try{await p(y);}catch(v){e.onError&&e.onError(v instanceof Error?v:new Error(String(v)),y);}})().catch(p=>{let v=V(p);e.onError?e.onError(v,y):b$2().error("Failed to process log entry",{error:v.message});});}}}function Te(e){let{tableName:t,method:n,params:r,query:o,keyFields:s,userId:a,prefix:i}=e,c=[];if(i&&c.push(i),c.push(t),c.push(n),r&&Object.keys(r).length>0){let u=Object.keys(r).sort().map(d=>`${d}=${r[d]}`).join("&");c.push(u);}if(o&&Object.keys(o).length>0){let u=Object.keys(o).filter(d=>o[d]!==void 0&&o[d]!==null&&o[d]!=="");if(s&&s.length>0&&(u=u.filter(d=>s.includes(d))),u.length>0){let d=u.sort().map(g=>`${g}=${String(o[g])}`).join("&");c.push(d);}}return a&&c.push(`user=${a}`),c.join(":")}function K(e,t,n){let r=[];if(n&&r.push(n),r.push(e),!t)return r.push("*"),r.join(":");let{method:o,id:s,userId:a}=t;return o?(r.push(o),r.join(":")+"*"):(s!==void 0?(r.push("*"),r.push(`id=${s}*`)):a?(r.push("*"),r.push(`user=${a}`)):r.push("*"),r.join(":"))}function be(e,t,n){return t.map(r=>K(r,void 0,n))}function Le(e,t){let n=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${n}$`).test(e)}function Rt(e){let t=e.split(":"),n=t.length>2&&!["GET","LIST"].includes(t[1]),r=0,o=n?t[r++]:void 0,s=t[r++],a=t[r++],i={tableName:s,method:a};o&&(i.prefix=o);for(let c=r;c<t.length;c++){let u=t[c];if(u.startsWith("user="))i.userId=u.substring(5);else if(u.includes("=")){let d=u.split("&"),g={};for(let C of d){let[m,h]=C.split("=");m&&h!==void 0&&(g[m]=h);}a==="GET"&&!i.params?i.params=g:a==="LIST"&&!i.query||i.params?i.query=g:i.params=g;}}return i}var W=class{storage=new Map;tagIndex=new Map;stats={hits:0,misses:0,size:0};defaultTtl;maxEntries;constructor(t){this.defaultTtl=t?.defaultTtl??300,this.maxEntries=t?.maxEntries??1e4;}async get(t){let n=this.storage.get(t);return n?n.expiresAt&&n.expiresAt<Date.now()?(await this.delete(t),this.stats.misses++,null):(this.stats.hits++,n):(this.stats.misses++,null)}async set(t,n,r){let o=r?.ttl??this.defaultTtl,s=r?.tags;this.maxEntries>0&&this.storage.size>=this.maxEntries&&!this.storage.has(t)&&this.evictOldest();let a=Date.now(),i={data:n,createdAt:a,expiresAt:o>0?a+o*1e3:null,tags:s},c=this.storage.get(t);if(c?.tags)for(let u of c.tags)this.tagIndex.get(u)?.delete(t);if(c&&this.storage.delete(t),this.storage.set(t,i),this.stats.size=this.storage.size,s)for(let u of s)this.tagIndex.has(u)||this.tagIndex.set(u,new Set),this.tagIndex.get(u).add(t);}async delete(t){let n=this.storage.get(t);if(!n)return false;if(n.tags)for(let r of n.tags)this.tagIndex.get(r)?.delete(t);return this.storage.delete(t),this.stats.size=this.storage.size,true}async deletePattern(t){let n=0,r=[];for(let o of this.storage.keys())Le(o,t)&&r.push(o);for(let o of r)await this.delete(o)&&n++;return n}async deleteByTag(t){let n=this.tagIndex.get(t);if(!n||n.size===0)return 0;let r=0,o=Array.from(n);for(let s of o)await this.delete(s)&&r++;return this.tagIndex.delete(t),r}async has(t){let n=this.storage.get(t);return n?n.expiresAt&&n.expiresAt<Date.now()?(await this.delete(t),false):true:false}async clear(){this.storage.clear(),this.tagIndex.clear(),this.stats.size=0;}getStats(){return {...this.stats}}resetStats(){this.stats.hits=0,this.stats.misses=0;}getKeys(){return Array.from(this.storage.keys())}getTags(){return Array.from(this.tagIndex.keys())}evictOldest(){let t=this.storage.keys().next().value;t!==void 0&&this.delete(t).catch(()=>{});}async cleanup(){let t=Date.now(),n=0,r=[];for(let[o,s]of this.storage.entries())s.expiresAt&&s.expiresAt<t&&r.push(o);for(let o of r)await this.delete(o),n++;return n}};function G(e){let n=e._meta?.model?.tableName;if(!n)throw new i("Cache mixin requires `_meta.model.tableName`. Declare `_meta` on the endpoint or remove the cache mixin.");return n}var J=c("cacheStorage",()=>new W);function qt(e){J.set(e);}function Kt(){return J.getRequired()}function Ht(e){class t extends e{cacheConfig;getCacheConfig(){return {enabled:true,ttl:300,perUser:false,...this.cacheConfig}}async generateCacheKey(){let r=this.getCacheConfig(),o=this.getContext(),s=G(this),a=await this.getValidatedData(),i=a.params,c=a.query,u=i&&Object.keys(i).length>0?"GET":"LIST",d;return r.perUser&&(d=o.var?.userId),Te({tableName:s,method:u,params:i,query:c,keyFields:r.keyFields,userId:d,prefix:r.prefix})}_cacheHit=false;async getCachedResponse(){if(!this.getCacheConfig().enabled)return this._cacheHit=false,null;let o=await this.generateCacheKey(),s=this.getContext(),a=F(s);if(!a)return this._cacheHit=false,null;let i=await a.get(o);return this._cacheHit=i!==null,i?.data??null}getCacheStatus(){return this._cacheHit?"HIT":"MISS"}successWithCache(r,o=200){return new Response(JSON.stringify({success:true,result:r}),{status:o,headers:{"Content-Type":"application/json","X-Cache":this.getCacheStatus()}})}jsonWithCache(r,o=200){return new Response(JSON.stringify(r),{status:o,headers:{"Content-Type":"application/json","X-Cache":this.getCacheStatus()}})}async setCachedResponse(r){let o=this.getCacheConfig();if(!o.enabled)return;let s=await this.generateCacheKey(),a=this.getContext(),i=F(a);if(!i)return;let c=o.tags?[...o.tags]:[],u=this._meta;u?.model?.tableName&&c.push(u.model.tableName),await i.set(s,r,{ttl:o.ttl,tags:c.length>0?c:void 0});}async invalidateCache(r){let o=this.getContext(),s=F(o);if(!s)return;let a=this.getCacheConfig();if(r?.pattern)await s.deletePattern(r.pattern);else if(r?.tags&&s.deleteByTag)for(let i of r.tags)await s.deleteByTag(i);else {let i=G(this),c=K(i,void 0,a.prefix);await s.deletePattern(c);}}}return t}function Mt(e){class t extends e{cacheInvalidation;getCacheInvalidationConfig(){return {strategy:"all",...this.cacheInvalidation}}async performCacheInvalidation(r){let o=this.getCacheInvalidationConfig(),s=this.getContext(),a=F(s);if(!a)return;let i=G(this);switch(o.strategy??"all"){case "single":if(r!==void 0){let g=K(i,{id:r});await a.deletePattern(g);}break;case "list":let u=K(i,{method:"LIST"});await a.deletePattern(u);break;case "all":let d=K(i);await a.deletePattern(d);break;case "pattern":o.pattern&&await a.deletePattern(o.pattern);break;case "tags":if(o.tags&&a.deleteByTag)for(let g of o.tags)await a.deleteByTag(g);break}if(o.relatedModels&&o.relatedModels.length>0){let u=be(i,o.relatedModels);for(let d of u)await a.deletePattern(d);}}async handle(){let r=await super.handle();if(r.status>=200&&r.status<300){let o;try{o=(await r.clone().json())?.result?.id;}catch{}let s=G(this);this.performCacheInvalidation(o).catch(a=>{b$2().error("Cache invalidation failed",{error:a instanceof Error?a.message:String(a),tableName:s,recordId:o});});}return r}}return t}function ke(e,t){return _.resolve(e,t)}function Pe(e,t){return X.resolve(e,t)}function F(e,t){return J.resolve(e,t)}function zt(e,t){return b$3.resolve(e,t)}function Ut(e,t){return b$4.resolve(e,t)}function Vt(e,t){return g.resolve(e,t)}function Xt(e,t){return a$3.resolve(e,t)}var _=b("rateLimitStorage");function tr(e){_.set(e);}function rr(){return _.get()}function Ne(){return {ip:e=>t=>q(t,e.ipHeader,e.trustProxy),user:e=>t=>{let n=ne(t);return n?`user:${n}`:q(t,e.ipHeader,e.trustProxy)},"api-key":e=>t=>{let n=we(t,e.apiKeyHeader);return n?`apikey:${n.substring(0,8)}`:q(t,e.ipHeader,e.trustProxy)},combined:e=>t=>{let n=q(t,e.ipHeader,e.trustProxy),r=ne(t);return r?`${n}:user:${r}`:n}}}function Be(e,t){if(typeof e=="function")return e;let r=Ne()[e];return r?r(t):o=>q(o,t.ipHeader,t.trustProxy)}async function $e(e,t,n,r){let o=await e.increment(t,r),s=Math.ceil((o.windowStart+r)/1e3),a=Math.max(0,n-o.count),i=o.count<=n;return {allowed:i,limit:n,remaining:a,resetAt:s,retryAfter:i?void 0:Math.ceil((o.windowStart+r-Date.now())/1e3)}}async function je(e,t,n,r){let o=Date.now(),s=await e.addTimestamp(t,r,o),a=s.timestamps.length,i=Math.max(0,n-a),c=a<=n,u=s.timestamps.length>0?Math.min(...s.timestamps):o,d=Math.ceil((u+r)/1e3),g;if(!c&&s.timestamps.length>0){let C=[...s.timestamps].sort((h,R)=>h-R),m=a-n;if(m>0&&C.length>=m){let h=C[m-1];g=Math.max(1,Math.ceil((h+r-o)/1e3));}}return {allowed:c,limit:n,remaining:i,resetAt:d,retryAfter:g}}function nr(e={}){let t=e.limit??100,n=e.windowSeconds??60,r=e.algorithm??"sliding-window",o=e.keyStrategy??"ip",s=e.keyPrefix??"rl",a=e.skipPaths??[],i=e.includeHeaders??true,c=e.errorMessage??"Too many requests",u=Be(o,e);return async(d,g)=>{let C=d.req.path;if(a.length>0&&ve(C,a))return g();let m=ke(d,e.storage);if(!m)return b$2().warn("Rate limit storage not configured. Skipping rate limiting."),g();let h=u(d);if(!h)return g();let R=t,l=n;if(e.getTier){let T=await e.getTier(d);R=T.limit,l=T.windowSeconds??n;}let P=l*1e3,w=Ie(s,C,h),f;if(r==="fixed-window"?f=await $e(m,w,R,P):f=await je(m,w,R,P),b$1(d,"rateLimit",f),b$1(d,"rateLimitKey",w),i&&(d.header("X-RateLimit-Limit",String(f.limit)),d.header("X-RateLimit-Remaining",String(f.remaining)),d.header("X-RateLimit-Reset",String(f.resetAt))),!f.allowed)throw f.retryAfter&&d.header("Retry-After",String(f.retryAfter)),e.onRateLimitExceeded&&await e.onRateLimitExceeded(d,f,w),new U(c,f.retryAfter??60);await g();}}async function or(e,t){let n=t??_.get();if(!n)throw new Error("Rate limit storage not configured");await n.reset(e);}export{Le as A,Rt as B,W as C,qt as D,Kt as E,Ht as F,Mt as G,ke as H,Pe as I,F as J,zt as K,Ut as L,Vt as M,Xt as N,V as O,Me as P,Oe as Q,ht as R,yt as S,xt as T,Ct as U,Et as V,Ye as a,ee as b,te as c,Ze as d,ye as e,xe as f,re as g,Ce as h,D as i,Ee as j,Se as k,Re as l,U as m,q as n,ne as o,we as p,st as q,ve as r,Ie as s,tr as t,rr as u,nr as v,or as w,Te as x,K as y,be as z};
|
|
1
|
+
import {b as b$4}from'./chunk-3DE2MG3R.js';import {a as a$3}from'./chunk-GF2EC5G4.js';import {a,g}from'./chunk-2M5BM4VD.js';import {a as a$1,i}from'./chunk-FC56WWPB.js';import {b as b$3}from'./chunk-KLBMVJX3.js';import {b,c}from'./chunk-GBQQ3YQX.js';import {b as b$2}from'./chunk-DMGP7QDL.js';import {e,a as a$2,b as b$1}from'./chunk-VJRDAVID.js';function B(e,t={}){let{ipHeader:n="X-Forwarded-For",trustProxy:r=true}=t;if(r){let s=e.req.header(n);if(s){let c=s.split(",")[0]?.trim();if(c)return c}let a=e.req.header("X-Real-IP")?.trim();if(a)return a;let i=e.req.header("CF-Connecting-IP")?.trim();if(i)return i}let o=e.req.raw;if(o&&typeof o.socket=="object"&&o.socket?.remoteAddress)return o.socket.remoteAddress;if(o?.cf?.ip)return o.cf.ip}function $(e){return a$2(e,"userId")}function z(e,t){let n=e.toLowerCase();for(let r of t){if(r instanceof RegExp){if(r.test(e))return true;continue}let o=r.toLowerCase();if(o.includes("*")){let s=o.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");if(new RegExp(`^${s}$`).test(n))return true}else if(n===o)return true}return false}function j(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(r=>j(r,t));if(typeof e!="object")return e;let n={};for(let[r,o]of Object.entries(e))z(r,t)?n[r]="[REDACTED]":typeof o=="object"&&o!==null?n[r]=j(o,t):n[r]=o;return n}function he(e,t){let n={};for(let[r,o]of Object.entries(e))n[r]=z(r,t)?"[REDACTED]":o;return n}function Ye(e,t){return z(e,t)}function ee(e,t){return j(e,t)}function te(e,t){return he(e,t)}function Ze(e,t){return a(e,t)}function ye(e,t,n){for(let r of n)if(a(e,r))return true;if(t.length===0)return false;for(let r of t)if(a(e,r))return false;return true}function xe(e,t="X-Forwarded-For",n=false){return B(e,{ipHeader:t,trustProxy:n||true})}function re(e){let t={};return e.forEach((n,r)=>{t[r.toLowerCase()]=n;}),t}function Ce(e){let t={};return new URL(e.req.url).searchParams.forEach((r,o)=>{t[o]=r;}),t}function D(e,t){if(typeof e=="string")return e.length>t?e.substring(0,t)+"... [TRUNCATED]":e;let n=JSON.stringify(e);return n.length>t?{_truncated:true,_originalSize:n.length,_maxSize:t}:e}function Ee(e,t){if(!e)return false;if(t.length===0)return true;let n=e.toLowerCase();for(let r of t)if(n.includes(r.toLowerCase()))return true;return false}function Se(e){return $(e)}function Re(){return e()}var U=class extends a$1{constructor(t="Too many requests",n=60){super(t,429,"RATE_LIMIT_EXCEEDED",{retryAfter:n}),this.name="RateLimitExceededException";}};function q(e,t="X-Forwarded-For",n=false){return B(e,{ipHeader:t,trustProxy:n})??"unknown"}function ne(e){return $(e)??null}function we(e,t="X-API-Key"){return e.req.header(t)||null}function st(e,t){return a(e,t)}function ve(e,t){return t.some(n=>a(e,n))}function Ie(e,...t){let n=t.filter(r=>r!==void 0&&r!=="");return `${e}:${n.join(":")}`}function V(e){return e instanceof Error?e:new Error(String(e))}function Me(e,t){let n=V(e),r=new Error(`${t}: ${n.message}`);return r.cause=n,r}function Oe(e){return e instanceof Error?e.message:String(e)}var X=b("loggingStorage");function ht(e){X.set(e);}function yt(){return X.get()}var De=["authorization","cookie","x-api-key","x-auth-token"],Fe=["password","token","secret","apiKey","api_key","accessToken","access_token","refreshToken","refresh_token","creditCard","credit_card","ssn","socialSecurityNumber"],_e=["/health","/healthz","/ready","/readyz","/live","/livez","/metrics","/favicon.ico"];function xt(e){return a$2(e,"requestId")}function Ct(e){return a$2(e,"requestStartTime")}function Et(e={}){let t=e.enabled??true,n=e.level??"info",r=e.includePaths??[],o=e.excludePaths??_e,s=e.redactHeaders??De,a=e.redactBodyFields??Fe,i=e.requestBody??{enabled:false},c=e.responseBody??{enabled:false},u=e.includeHeaders??true,d=e.includeQuery??true,g=e.includeClientIp??true,C=e.ipHeader??"X-Forwarded-For",m=e.trustProxy??false,h=e.minResponseTimeMs??0,R=e.generateRequestId??Re;return async(l,P)=>{if(!t)return P();let w=l.req.path;if(ye(w,r,o))return P();let f=R(),T=Date.now();b$1(l,"requestId",f),b$1(l,"requestStartTime",T),l.header("X-Request-ID",f);let Ae=l.req.method,qe=l.req.url,oe;if(u){let E=re(l.req.raw.headers);oe=te(E,s);}let se;d&&(se=Ce(l));let ae;g&&(ae=xe(l,C,m));let Ke=Se(l),Q;if(i.enabled){let E=l.req.header("content-type"),H=i.contentTypes??[];if(Ee(E,H))try{let L=await l.req.raw.clone().text();if(L)try{let x=JSON.parse(L);x=ee(x,a);let y=i.maxSize??10240;Q=D(x,y);}catch{let x=i.maxSize??10240;Q=D(L,x);}}catch{}}let S,Y;try{await P();}catch(E){throw S=E instanceof Error?E:new Error(String(E)),E}finally{let H=Date.now()-T;if(H<h)return;let b=l.res.status,L;if(u){let p=re(l.res.headers);L=te(p,s);}if(c.enabled&&!S){let p=c.statusCodes??[];if(p.length===0||p.includes(b))try{let Z=await l.res.clone().text();if(Z)try{let M=JSON.parse(Z);M=ee(M,a);let He=c.maxSize??10240;Y=D(M,He);}catch{let M=c.maxSize??10240;Y=D(Z,M);}}catch{}}let x=n;e.levelResolver?x=e.levelResolver(l,H,b,S):S||b>=500?x="error":b>=400&&(x="warn");let y={id:f,timestamp:new Date(T).toISOString(),level:x,request:{method:Ae,path:w,url:qe,headers:oe,query:se,body:Q,clientIp:ae,userId:Ke},response:{statusCode:b,headers:L,body:Y,responseTimeMs:H}};if(S&&(y.error={message:S.message,name:S.name,stack:S.stack}),e.metadata){let p=typeof e.metadata=="function"?e.metadata(l):e.metadata;y.metadata=p;}e.formatter&&(y=e.formatter(y));let ie=Pe(l,e.storage);(async()=>{if(ie)try{await ie.store(y);}catch(p){e.onError&&e.onError(p instanceof Error?p:new Error(String(p)),y);}if(e.handlers)for(let p of e.handlers)try{await p(y);}catch(v){e.onError&&e.onError(v instanceof Error?v:new Error(String(v)),y);}})().catch(p=>{let v=V(p);e.onError?e.onError(v,y):b$2().error("Failed to process log entry",{error:v.message});});}}}function Te(e){let{tableName:t,method:n,params:r,query:o,keyFields:s,userId:a,prefix:i}=e,c=[];if(i&&c.push(i),c.push(t),c.push(n),r&&Object.keys(r).length>0){let u=Object.keys(r).sort().map(d=>`${d}=${r[d]}`).join("&");c.push(u);}if(o&&Object.keys(o).length>0){let u=Object.keys(o).filter(d=>o[d]!==void 0&&o[d]!==null&&o[d]!=="");if(s&&s.length>0&&(u=u.filter(d=>s.includes(d))),u.length>0){let d=u.sort().map(g=>`${g}=${String(o[g])}`).join("&");c.push(d);}}return a&&c.push(`user=${a}`),c.join(":")}function K(e,t,n){let r=[];if(n&&r.push(n),r.push(e),!t)return r.push("*"),r.join(":");let{method:o,id:s,userId:a}=t;return o?(r.push(o),r.join(":")+"*"):(s!==void 0?(r.push("*"),r.push(`id=${s}*`)):a?(r.push("*"),r.push(`user=${a}`)):r.push("*"),r.join(":"))}function be(e,t,n){return t.map(r=>K(r,void 0,n))}function Le(e,t){let n=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${n}$`).test(e)}function Rt(e){let t=e.split(":"),n=t.length>2&&!["GET","LIST"].includes(t[1]),r=0,o=n?t[r++]:void 0,s=t[r++],a=t[r++],i={tableName:s,method:a};o&&(i.prefix=o);for(let c=r;c<t.length;c++){let u=t[c];if(u.startsWith("user="))i.userId=u.substring(5);else if(u.includes("=")){let d=u.split("&"),g={};for(let C of d){let[m,h]=C.split("=");m&&h!==void 0&&(g[m]=h);}a==="GET"&&!i.params?i.params=g:a==="LIST"&&!i.query||i.params?i.query=g:i.params=g;}}return i}var W=class{storage=new Map;tagIndex=new Map;stats={hits:0,misses:0,size:0};defaultTtl;maxEntries;constructor(t){this.defaultTtl=t?.defaultTtl??300,this.maxEntries=t?.maxEntries??1e4;}async get(t){let n=this.storage.get(t);return n?n.expiresAt&&n.expiresAt<Date.now()?(await this.delete(t),this.stats.misses++,null):(this.stats.hits++,n):(this.stats.misses++,null)}async set(t,n,r){let o=r?.ttl??this.defaultTtl,s=r?.tags;this.maxEntries>0&&this.storage.size>=this.maxEntries&&!this.storage.has(t)&&this.evictOldest();let a=Date.now(),i={data:n,createdAt:a,expiresAt:o>0?a+o*1e3:null,tags:s},c=this.storage.get(t);if(c?.tags)for(let u of c.tags)this.tagIndex.get(u)?.delete(t);if(c&&this.storage.delete(t),this.storage.set(t,i),this.stats.size=this.storage.size,s)for(let u of s)this.tagIndex.has(u)||this.tagIndex.set(u,new Set),this.tagIndex.get(u).add(t);}async delete(t){let n=this.storage.get(t);if(!n)return false;if(n.tags)for(let r of n.tags)this.tagIndex.get(r)?.delete(t);return this.storage.delete(t),this.stats.size=this.storage.size,true}async deletePattern(t){let n=0,r=[];for(let o of this.storage.keys())Le(o,t)&&r.push(o);for(let o of r)await this.delete(o)&&n++;return n}async deleteByTag(t){let n=this.tagIndex.get(t);if(!n||n.size===0)return 0;let r=0,o=Array.from(n);for(let s of o)await this.delete(s)&&r++;return this.tagIndex.delete(t),r}async has(t){let n=this.storage.get(t);return n?n.expiresAt&&n.expiresAt<Date.now()?(await this.delete(t),false):true:false}async clear(){this.storage.clear(),this.tagIndex.clear(),this.stats.size=0;}getStats(){return {...this.stats}}resetStats(){this.stats.hits=0,this.stats.misses=0;}getKeys(){return Array.from(this.storage.keys())}getTags(){return Array.from(this.tagIndex.keys())}evictOldest(){let t=this.storage.keys().next().value;t!==void 0&&this.delete(t).catch(()=>{});}async cleanup(){let t=Date.now(),n=0,r=[];for(let[o,s]of this.storage.entries())s.expiresAt&&s.expiresAt<t&&r.push(o);for(let o of r)await this.delete(o),n++;return n}};function G(e){let n=e._meta?.model?.tableName;if(!n)throw new i("Cache mixin requires `_meta.model.tableName`. Declare `_meta` on the endpoint or remove the cache mixin.");return n}var J=c("cacheStorage",()=>new W);function qt(e){J.set(e);}function Kt(){return J.getRequired()}function Ht(e){class t extends e{cacheConfig;getCacheConfig(){return {enabled:true,ttl:300,perUser:false,...this.cacheConfig}}async generateCacheKey(){let r=this.getCacheConfig(),o=this.getContext(),s=G(this),a=await this.getValidatedData(),i=a.params,c=a.query,u=i&&Object.keys(i).length>0?"GET":"LIST",d;return r.perUser&&(d=o.var?.userId),Te({tableName:s,method:u,params:i,query:c,keyFields:r.keyFields,userId:d,prefix:r.prefix})}_cacheHit=false;async getCachedResponse(){if(!this.getCacheConfig().enabled)return this._cacheHit=false,null;let o=await this.generateCacheKey(),s=this.getContext(),a=F(s);if(!a)return this._cacheHit=false,null;let i=await a.get(o);return this._cacheHit=i!==null,i?.data??null}getCacheStatus(){return this._cacheHit?"HIT":"MISS"}successWithCache(r,o=200){return new Response(JSON.stringify({success:true,result:r}),{status:o,headers:{"Content-Type":"application/json","X-Cache":this.getCacheStatus()}})}jsonWithCache(r,o=200){return new Response(JSON.stringify(r),{status:o,headers:{"Content-Type":"application/json","X-Cache":this.getCacheStatus()}})}async setCachedResponse(r){let o=this.getCacheConfig();if(!o.enabled)return;let s=await this.generateCacheKey(),a=this.getContext(),i=F(a);if(!i)return;let c=o.tags?[...o.tags]:[],u=this._meta;u?.model?.tableName&&c.push(u.model.tableName),await i.set(s,r,{ttl:o.ttl,tags:c.length>0?c:void 0});}async invalidateCache(r){let o=this.getContext(),s=F(o);if(!s)return;let a=this.getCacheConfig();if(r?.pattern)await s.deletePattern(r.pattern);else if(r?.tags&&s.deleteByTag)for(let i of r.tags)await s.deleteByTag(i);else {let i=G(this),c=K(i,void 0,a.prefix);await s.deletePattern(c);}}}return t}function Mt(e){class t extends e{cacheInvalidation;getCacheInvalidationConfig(){return {strategy:"all",...this.cacheInvalidation}}async performCacheInvalidation(r){let o=this.getCacheInvalidationConfig(),s=this.getContext(),a=F(s);if(!a)return;let i=G(this);switch(o.strategy??"all"){case "single":if(r!==void 0){let g=K(i,{id:r});await a.deletePattern(g);}break;case "list":let u=K(i,{method:"LIST"});await a.deletePattern(u);break;case "all":let d=K(i);await a.deletePattern(d);break;case "pattern":o.pattern&&await a.deletePattern(o.pattern);break;case "tags":if(o.tags&&a.deleteByTag)for(let g of o.tags)await a.deleteByTag(g);break}if(o.relatedModels&&o.relatedModels.length>0){let u=be(i,o.relatedModels);for(let d of u)await a.deletePattern(d);}}async handle(){let r=await super.handle();if(r.status>=200&&r.status<300){let o;try{o=(await r.clone().json())?.result?.id;}catch{}let s=G(this);this.performCacheInvalidation(o).catch(a=>{b$2().error("Cache invalidation failed",{error:a instanceof Error?a.message:String(a),tableName:s,recordId:o});});}return r}}return t}function ke(e,t){return _.resolve(e,t)}function Pe(e,t){return X.resolve(e,t)}function F(e,t){return J.resolve(e,t)}function zt(e,t){return b$3.resolve(e,t)}function Ut(e,t){return b$4.resolve(e,t)}function Vt(e,t){return g.resolve(e,t)}function Xt(e,t){return a$3.resolve(e,t)}var _=b("rateLimitStorage");function tr(e){_.set(e);}function rr(){return _.get()}function Ne(){return {ip:e=>t=>q(t,e.ipHeader,e.trustProxy),user:e=>t=>{let n=ne(t);return n?`user:${n}`:q(t,e.ipHeader,e.trustProxy)},"api-key":e=>t=>{let n=we(t,e.apiKeyHeader);return n?`apikey:${n.substring(0,8)}`:q(t,e.ipHeader,e.trustProxy)},combined:e=>t=>{let n=q(t,e.ipHeader,e.trustProxy),r=ne(t);return r?`${n}:user:${r}`:n}}}function Be(e,t){if(typeof e=="function")return e;let r=Ne()[e];return r?r(t):o=>q(o,t.ipHeader,t.trustProxy)}async function $e(e,t,n,r){let o=await e.increment(t,r),s=Math.ceil((o.windowStart+r)/1e3),a=Math.max(0,n-o.count),i=o.count<=n;return {allowed:i,limit:n,remaining:a,resetAt:s,retryAfter:i?void 0:Math.ceil((o.windowStart+r-Date.now())/1e3)}}async function je(e,t,n,r){let o=Date.now(),s=await e.addTimestamp(t,r,o),a=s.timestamps.length,i=Math.max(0,n-a),c=a<=n,u=s.timestamps.length>0?Math.min(...s.timestamps):o,d=Math.ceil((u+r)/1e3),g;if(!c&&s.timestamps.length>0){let C=[...s.timestamps].sort((h,R)=>h-R),m=a-n;if(m>0&&C.length>=m){let h=C[m-1];g=Math.max(1,Math.ceil((h+r-o)/1e3));}}return {allowed:c,limit:n,remaining:i,resetAt:d,retryAfter:g}}function nr(e={}){let t=e.limit??100,n=e.windowSeconds??60,r=e.algorithm??"sliding-window",o=e.keyStrategy??"ip",s=e.keyPrefix??"rl",a=e.skipPaths??[],i=e.includeHeaders??true,c=e.errorMessage??"Too many requests",u=Be(o,e);return async(d,g)=>{let C=d.req.path;if(a.length>0&&ve(C,a))return g();let m=ke(d,e.storage);if(!m)return b$2().warn("Rate limit storage not configured. Skipping rate limiting."),g();let h=u(d);if(!h)return g();let R=t,l=n;if(e.getTier){let T=await e.getTier(d);R=T.limit,l=T.windowSeconds??n;}let P=l*1e3,w=Ie(s,C,h),f;if(r==="fixed-window"?f=await $e(m,w,R,P):f=await je(m,w,R,P),b$1(d,"rateLimit",f),b$1(d,"rateLimitKey",w),i&&(d.header("X-RateLimit-Limit",String(f.limit)),d.header("X-RateLimit-Remaining",String(f.remaining)),d.header("X-RateLimit-Reset",String(f.resetAt))),!f.allowed)throw f.retryAfter&&d.header("Retry-After",String(f.retryAfter)),e.onRateLimitExceeded&&await e.onRateLimitExceeded(d,f,w),new U(c,f.retryAfter??60);await g();}}async function or(e,t){let n=t??_.get();if(!n)throw new Error("Rate limit storage not configured");await n.reset(e);}export{Le as A,Rt as B,W as C,qt as D,Kt as E,Ht as F,Mt as G,ke as H,Pe as I,F as J,zt as K,Ut as L,Vt as M,Xt as N,V as O,Me as P,Oe as Q,ht as R,yt as S,xt as T,Ct as U,Et as V,Ye as a,ee as b,te as c,Ze as d,ye as e,xe as f,re as g,Ce as h,D as i,Ee as j,Se as k,Re as l,U as m,q as n,ne as o,we as p,st as q,ve as r,Ie as s,tr as t,rr as u,nr as v,or as w,Te as x,K as y,be as z};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {r,s,t,u,v as v$1,x,z as z$1,A as A$1,B as B$1,C as C$1,D as D$1,R,S as S$1,$ as $$1,aa,y as y$1,E as E$1,F as F$1,G as G$1,H as H$1,I as I$1,J as J$1,w as w$1}from'./chunk-CTK2CYX2.js';var E,v;async function Ce(){if(E)return E;try{return E=(await import('pluralize')).default,E}catch{throw new Error('The "pluralize" package is required. Install it with: npm install pluralize')}}async function Fe(){if(v)return v;try{return v=(await import('fastest-levenshtein')).distance,v}catch{throw new Error('The "fastest-levenshtein" package is required. Install it with: npm install fastest-levenshtein')}}async function G(a){return (await Ce()).singular(a)}async function H(a,t){return (await Fe())(a,t)}function ke(a,t){return a[t]}function Ie(a){return typeof a=="object"&&a!==null&&"create"in a&&typeof a.create=="function"}function h(a,t){let e=ke(a,t);return Ie(e)?e:void 0}function X(a){if(typeof a.$transaction!="function")throw new Error("Prisma client does not support $transaction");return a.$transaction.bind(a)}function P(a){if(typeof a=="string"){if(/^-?\d+$/.test(a))return parseInt(a,10);if(/^-?\d+\.\d+$/.test(a))return parseFloat(a);if(a==="true")return true;if(a==="false")return false}return a}function Y(a){let t={};for(let e of a){let o=P(e.value);switch(e.operator){case "eq":t[e.field]=o;break;case "ne":t[e.field]={not:o};break;case "gt":t[e.field]={gt:o};break;case "gte":t[e.field]={gte:o};break;case "lt":t[e.field]={lt:o};break;case "lte":t[e.field]={lte:o};break;case "in":{let n=Array.isArray(e.value)?e.value:[e.value];t[e.field]={in:n.map(P)};break}case "nin":{let n=Array.isArray(e.value)?e.value:[e.value];t[e.field]={notIn:n.map(P)};break}case "like":t[e.field]={contains:String(e.value).replace(/%/g,"")};break;case "ilike":t[e.field]={contains:String(e.value).replace(/%/g,""),mode:"insensitive"};break;case "null":t[e.field]=e.value?null:{not:null};break;case "between":{let[n,s]=e.value;t[e.field]={gte:P(n),lte:P(s)};break}}}return t}var De=500,y=new Map;function Pe(a,t){if(y.size>=De){let e=y.keys().next().value;e!==void 0&&y.delete(e);}y.set(a,t);}var J=new Map;function xe(a,t){J.set(a.toLowerCase(),t),y.delete(a);}function Ae(a){for(let[t,e]of Object.entries(a))xe(t,e);}function Ke(){J.clear(),y.clear();}async function w(a){let t=y.get(a);if(t)return t;let e=J.get(a.toLowerCase());if(e)return Pe(a,e),e;let o=a.replace(/[-_](.)/g,(n,s)=>s.toUpperCase()).replace(/^./,n=>n.toLowerCase());return o=await G(o),Pe(a,o),o}function Ne(a){let t=[];for(let e of Object.keys(a)){if(e.startsWith("$")||e.startsWith("_"))continue;let o=ke(a,e);o&&typeof o=="object"&&"create"in o&&t.push(e);}return t}async function Se(a,t,e=3){if(t.length===0)return [];let o=a.toLowerCase();return (await Promise.all(t.map(async s=>({name:s,distance:await H(o,s.toLowerCase())})))).filter(s=>s.distance<=Math.max(3,a.length/2)).sort((s,r)=>s.distance-r.distance).slice(0,e).map(s=>s.name)}async function M(a,t){let e=await w(t),o=h(a,e);if(!o){let n=Ne(a),s=await Se(e,n),r=`Model '${e}' not found in Prisma client. Table name: '${t}'. `;throw s.length>0&&(r+=`Did you mean: ${s.map(i=>`'${i}'`).join(", ")}? `),n.length>0&&n.length<=10&&(r+=`Available models: ${n.join(", ")}. `),r+=`You can register a custom mapping with: registerPrismaModelMapping('${t}', 'yourModelName')`,new Error(r)}return o}async function Ue(a,t,e,o){let n=await w(o.model),s=h(a,n);if(!s)return t;switch(o.type){case "hasOne":{let r=o.localKey||"id",i=t[r];if(i==null)return {...t,[e]:null};let d=await s.findFirst({where:{[o.foreignKey]:i}});return {...t,[e]:d||null}}case "hasMany":{let r=o.localKey||"id",i=t[r];if(i==null)return {...t,[e]:[]};let d=await s.findMany({where:{[o.foreignKey]:i}});return {...t,[e]:d}}case "belongsTo":{let r=t[o.foreignKey];if(r==null)return {...t,[e]:null};let i=o.localKey||"id",d=await s.findFirst({where:{[i]:r}});return {...t,[e]:d||null}}default:return t}}async function Oe(a,t,e,o){if(!o?.relations?.length||!e.model.relations)return t;let n={...t};for(let s of o.relations){let r=e.model.relations[s];r&&(n=await Ue(a,n,s,r));}return n}async function k(a,t,e,o){if(!t.length||!o?.relations?.length||!e.model.relations)return t;let n=t.map(s=>({...s}));for(let s of o.relations){let r=e.model.relations[s];if(!r)continue;let i=await w(r.model),d=h(a,i);if(d)switch(r.type){case "hasOne":case "hasMany":{let c=r.localKey||"id",u=[...new Set(n.map(m=>m[c]).filter(m=>m!=null))];if(u.length===0){n=n.map(m=>({...m,[s]:r.type==="hasMany"?[]:null}));continue}let l=await d.findMany({where:{[r.foreignKey]:{in:u}}}),g=new Map;for(let m of l){let p=m[r.foreignKey];g.has(p)||g.set(p,[]),g.get(p).push(m);}n=n.map(m=>{let p=m[c],f=g.get(p)||[];return {...m,[s]:r.type==="hasMany"?f:f[0]||null}});break}case "belongsTo":{let c=r.localKey||"id",u=[...new Set(n.map(m=>m[r.foreignKey]).filter(m=>m!=null))];if(u.length===0){n=n.map(m=>({...m,[s]:null}));continue}let l=await d.findMany({where:{[c]:{in:u}}}),g=new Map;for(let m of l){let p=m[c];g.set(p,m);}n=n.map(m=>{let p=m[r.foreignKey];return {...m,[s]:g.get(p)||null}});break}}}return n}async function _(a){let{model:t,filters:e,searchFields:o=[],softDeleteConfig:n,defaultPerPage:s=20,additionalWhere:r={}}=a,i={...Y(e.filters),...r};if(n?.enabled){let{withDeleted:p,onlyDeleted:f}=e.options;f?i[n.field]={not:null}:p||(i[n.field]=null);}if(e.options.search&&o.length>0){let p=o.map(f=>({[f]:{contains:e.options.search,mode:"insensitive"}}));i={...i,OR:p};}let d=await t.count({where:i}),c;e.options.order_by&&(c={[e.options.order_by]:e.options.order_by_direction||"asc"});let u=e.options.page||1,l=e.options.per_page||s,g=await t.findMany({where:i,orderBy:c,skip:(u-1)*l,take:l}),m=Math.ceil(d/l);return {records:g,where:i,totalCount:d,page:u,perPage:l,totalPages:m}}function j(a,t){return {result:a,result_info:{page:t.page,per_page:t.perPage,total_count:t.totalCount,total_pages:t.totalPages,has_next_page:t.page<t.totalPages,has_prev_page:t.page>1}}}var C=class extends r{useTransaction=false;async getModel(){return M(this.prisma,this._meta.model.tableName)}async create(t){let e=await this.getModel(),o=this.applyManagedInsertFields(t,"prisma");return await e.create({data:o})}},F=class extends s{async getModel(){return M(this.prisma,this._meta.model.tableName)}async read(t,e,o){let n=await this.getModel(),s={[this.lookupField]:t,...e},r=await n.findFirst({where:s});return r?await Oe(this.prisma,r,this._meta,o):null}},I=class extends t{useTransaction=false;async getModel(){return M(this.prisma,this._meta.model.tableName)}async update(t,e,o){let n=await this.getModel(),s={[this.lookupField]:t,...o},r=await n.findFirst({where:s});if(!r)return null;let i=this._meta.model.primaryKeys[0];return await n.update({where:{[i]:r[i]},data:this.applyManagedUpdateFields(e)})}},D=class extends u{useTransaction=false;async getModel(){return M(this.prisma,this._meta.model.tableName)}async findForDelete(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),s={[this.lookupField]:t,...e};return n.enabled&&(s[n.field]=null),await o.findFirst({where:s})}async delete(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),s={[this.lookupField]:t,...e};n.enabled&&(s[n.field]=null);let r=await o.findFirst({where:s});if(!r)return null;let i=this._meta.model.primaryKeys[0],d=r[i];return n.enabled?await o.update({where:{[i]:d},data:{[n.field]:new Date}}):await o.delete({where:{[i]:d}})}},A=class extends v$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async list(t){let e=await _({model:await this.getModel(),filters:t,searchFields:this.searchFields,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage}),o={relations:t.options.include||[]},n=await k(this.prisma,e.records,this._meta,o);return j(n,e)}};var K=class extends x{useTransaction=false;async getModel(){return M(this.prisma,this._meta.model.tableName)}async restore(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),s={[this.lookupField]:t,[n.field]:{not:null},...e},r=await o.findFirst({where:s});if(!r)return null;let i=this._meta.model.primaryKeys[0];return await o.update({where:{[i]:r[i]},data:{[n.field]:null}})}},N=class extends z$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async batchCreate(t){let e=t.map(n=>this.applyManagedInsertFields(n,"prisma")),o=[];return await X(this.prisma)(async n=>{let s=h(n,await w(this._meta.model.tableName));if(!s)throw new Error(`Model '${this._meta.model.tableName}' not found in Prisma transaction client`);for(let r of e){let i=await s.create({data:r});o.push(i);}}),o}},S=class extends A$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async batchUpdate(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],s=[],r=[],i=t.map(l=>l.id),d={[this.lookupField]:{in:i}};o.enabled&&(d[o.field]=null);let c=await e.findMany({where:d}),u=new Map;for(let l of c){let g=l[this.lookupField];u.set(g,l);}for(let l of t){let g=u.get(l.id);if(!g){r.push(l.id);continue}let m=await e.update({where:{[n]:g[n]},data:this.applyManagedUpdateFields(l.data)});s.push(m);}return {updated:s,notFound:r}}},U=class extends B$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async batchDelete(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],s=[],r=[],i={[this.lookupField]:{in:t}};o.enabled&&(i[o.field]=null);let d=await e.findMany({where:i}),c=new Map;for(let u of d){let l=u[this.lookupField];c.set(l,u);}for(let u of t)c.has(u)||r.push(u);for(let u of t){let l=c.get(u);if(l)if(o.enabled){let g=await e.update({where:{[n]:l[n]},data:{[o.field]:new Date}});s.push(g);}else {let g=await e.delete({where:{[n]:l[n]}});s.push(g);}}return {deleted:s,notFound:r}}},T=class extends C$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async batchRestore(t){let e=await this.getModel(),o=this.getSoftDeleteConfig(),n=this._meta.model.primaryKeys[0],s=[],r=[],i={[this.lookupField]:{in:t},[o.field]:{not:null}},d=await e.findMany({where:i}),c=new Map;for(let u of d){let l=u[this.lookupField];c.set(l,u);}for(let u of t){let l=c.get(u);if(!l){r.push(u);continue}let g=await e.update({where:{[n]:l[n]},data:{[o.field]:null}});s.push(g);}return {restored:s,notFound:r}}},B=class extends D$1{useTransaction=true;async getModel(){return M(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let r of o){let i=t[r];i!==void 0&&(n[r]=i);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this.applyManagedInsertFields(t,"prisma");return await e.create({data:o})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:this.applyManagedUpdateFields(e)})}async nativeBatchUpsert(t,e){if(t.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let o=this.getUpsertKeys(),n=this._meta.model.primaryKeys[0],s=this.getTimestampsConfig(),r=async c=>{let u=h(c,await w(this._meta.model.tableName));if(!u)throw new Error(`Model '${this._meta.model.tableName}' not found in Prisma client`);let l=[],g=[];for(let m=0;m<t.length;m++){let p=t[m];try{let f={};for(let b of o){let O=p[b];O!==void 0&&(f[b]=O);}let q=this.applyManagedInsertFields(p,"prisma"),x={};for(let[b,O]of Object.entries(p))!o.includes(b)&&b!==n&&(this.createOnlyFields?.includes(b)||(x[b]=O));s.enabled&&(x[s.updatedAt]=Date.now());let je=await u.upsert({where:f,create:q,update:Object.keys(x).length>0?x:{}});l.push({data:je,created:!1,index:m});}catch(f){if(this.continueOnError)g.push({index:m,error:f instanceof Error?f.message:String(f)});else throw f}}return {results:l,errors:g}},i;this.useTransaction?i=await X(this.prisma)(r):i=await r(this.prisma);let d={items:i.results,createdCount:0,updatedCount:i.results.length,totalCount:i.results.length};return i.errors.length>0&&(d.errors=i.errors),d}};var $=class extends R{async getModel(){return M(this.prisma,this._meta.model.tableName)}buildSearchWhere(t,e){let o=Y(e.filters),n=this.getSoftDeleteConfig();if(n.enabled){let{withDeleted:d,onlyDeleted:c}=e.options;c?o[n.field]={not:null}:d||(o[n.field]=null);}let s=this.getSearchableFields(),i=(t.fields||Object.keys(s)).map(d=>({[d]:{contains:t.query,mode:"insensitive"}}));return i.length>0&&(t.mode==="all"?o={...o,AND:i}:o={...o,OR:i}),o}async search(t,e){let o=await this.getModel(),n=this.buildSearchWhere(t,e),s=await o.count({where:n}),r=e.options.order_by?{[e.options.order_by]:e.options.order_by_direction||"asc"}:void 0,i=e.options.page||1,d=e.options.per_page||this.defaultPerPage,c=await o.findMany({where:n,orderBy:r,skip:(i-1)*d,take:d}),u=S$1(c,t,this.getSearchableFields()),l={relations:e.options.include||[]},g=u.map(f=>f.item),m=await k(this.prisma,g,this._meta,l);return {items:u.map((f,q)=>({...f,item:m[q]})),totalCount:s}}},L=class extends $$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async list(t){let e=await _({model:await this.getModel(),filters:t,searchFields:this.searchFields,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage}),o={relations:t.options.include||[]},n=await k(this.prisma,e.records,this._meta,o);return j(n,e)}},W=class extends aa{async getModel(){return M(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let r of o){let i=t[r];i!==void 0&&(n[r]=i);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this.applyManagedInsertFields(t,"prisma");return await e.create({data:o})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:this.applyManagedUpdateFields(e)})}},V=class extends y$1{useTransaction=false;async getModel(){return M(this.prisma,this._meta.model.tableName)}async findExisting(t){let e=await this.getModel(),o=this.getUpsertKeys(),n={};for(let r of o){let i=t[r];i!==void 0&&(n[r]=i);}return Object.keys(n).length===0?null:await e.findFirst({where:n})||null}async create(t){let e=await this.getModel(),o=this.applyManagedInsertFields(t,"prisma");return await e.create({data:o})}async update(t,e){let o=await this.getModel(),n=this._meta.model.primaryKeys[0];return await o.update({where:{[n]:t[n]},data:this.applyManagedUpdateFields(e)})}async nativeUpsert(t,e){let o=await this.getModel(),n=this.getUpsertKeys(),s=this._meta.model.primaryKeys[0],r=this.getTimestampsConfig(),i={};for(let l of n){let g=t[l];g!==void 0&&(i[l]=g);}let d=this.applyManagedInsertFields(t,"prisma"),c={};for(let[l,g]of Object.entries(t))!n.includes(l)&&l!==s&&(this.createOnlyFields?.includes(l)||(c[l]=g));return r.enabled&&(c[r.updatedAt]=Date.now()),{data:await o.upsert({where:i,create:d,update:Object.keys(c).length>0?c:{}}),created:false}}},Re=class extends E$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async recordExists(t){return await(await this.getModel()).count({where:{[this.lookupField]:t}})>0}},Ee=class extends F$1{},ve=class extends G$1{},_e=class extends H$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}async rollback(t,e,o){let n=await this.getModel(),s=this.getVersioningConfig().field,r=this._meta.model.primaryKeys[0],i=await n.findFirst({where:{[this.lookupField]:t}});if(!i)throw new Error(`Record not found: ${t}`);return await n.update({where:{[r]:i[r]},data:{...e,[s]:o}})}},Q=class extends I$1{useNativeAggregation=true;async getModel(){return M(this.prisma,this._meta.model.tableName)}async buildAggregateWhere(t){let e={},o=this.getSoftDeleteConfig();if(o.enabled){let{query:n}=await this.getValidatedData();n?.withDeleted===true||n?.withDeleted==="true"||(e[o.field]=null);}if(t.filters)for(let[n,s]of Object.entries(t.filters))if(typeof s=="object"&&s!==null){let r={};for(let[i,d]of Object.entries(s))switch(i){case "eq":r.equals=d;break;case "ne":r.not=d;break;case "gt":r.gt=d;break;case "gte":r.gte=d;break;case "lt":r.lt=d;break;case "lte":r.lte=d;break;case "in":r.in=d;break;case "nin":r.notIn=d;break;default:r[i]=d;}e[n]=r;}else e[n]=s;return e}async aggregate(t){let e=await this.getModel(),o=await this.buildAggregateWhere(t);if(!this.useNativeAggregation||t.having){let n=await e.findMany({where:o});return J$1(n,t)}return t.groupBy?.length?this.aggregateWithGroupBy(e,o,t):this.aggregateSimple(e,o,t)}groupAggregationsByOperation(t){let e={sum:[],avg:[],min:[],max:[],count:[],countDistinct:[]};for(let o of t)switch(o.operation){case "sum":e.sum.push(o.field);break;case "avg":e.avg.push(o.field);break;case "min":e.min.push(o.field);break;case "max":e.max.push(o.field);break;case "count":e.count.push(o.field);break;case "countDistinct":e.countDistinct.push(o.field);break}return e}async aggregateSimple(t,e,o){let n={where:e},s={},r=this.groupAggregationsByOperation(o.aggregations);if(n._count=true,r.sum.length){n._sum={};for(let c of r.sum)n._sum[c]=true;}if(r.avg.length){n._avg={};for(let c of r.avg)n._avg[c]=true;}if(r.min.length){n._min={};for(let c of r.min)n._min[c]=true;}if(r.max.length){n._max={};for(let c of r.max)n._max[c]=true;}let i=await w(this._meta.model.tableName),d=h(this.prisma,i);if(!d)throw new Error(`Model '${i}' not found in Prisma client`);try{let c=await d.aggregate(n);if(c._count!==void 0&&(s.count=typeof c._count=="object"?c._count._all??0:c._count),c._sum&&r.sum.length)for(let u of r.sum){let l=u.charAt(0).toUpperCase()+u.slice(1);s[`sum${l}`]=c._sum[u]??0;}if(c._avg&&r.avg.length)for(let u of r.avg){let l=u.charAt(0).toUpperCase()+u.slice(1);s[`avg${l}`]=c._avg[u]??0;}if(c._min&&r.min.length)for(let u of r.min){let l=u.charAt(0).toUpperCase()+u.slice(1);s[`min${l}`]=c._min[u];}if(c._max&&r.max.length)for(let u of r.max){let l=u.charAt(0).toUpperCase()+u.slice(1);s[`max${l}`]=c._max[u];}return {values:s,groups:[]}}catch{let u=await t.findMany({where:e});return J$1(u,o)}}async aggregateWithGroupBy(t,e,o){let n={by:o.groupBy,where:e},s=this.groupAggregationsByOperation(o.aggregations);if(n._count=true,s.sum.length){n._sum={};for(let d of s.sum)n._sum[d]=true;}if(s.avg.length){n._avg={};for(let d of s.avg)n._avg[d]=true;}if(s.min.length){n._min={};for(let d of s.min)n._min[d]=true;}if(s.max.length){n._max={};for(let d of s.max)n._max[d]=true;}let r=await w(this._meta.model.tableName),i=h(this.prisma,r);if(!i)throw new Error(`Model '${r}' not found in Prisma client`);try{let c=(await i.groupBy(n)).map(l=>{let g={},m={};for(let p of o.groupBy)g[p]=l[p];if(m.count=typeof l._count=="object"?l._count._all??0:l._count??0,l._sum&&s.sum.length)for(let p of s.sum){let f=p.charAt(0).toUpperCase()+p.slice(1);m[`sum${f}`]=l._sum[p]??0;}if(l._avg&&s.avg.length)for(let p of s.avg){let f=p.charAt(0).toUpperCase()+p.slice(1);m[`avg${f}`]=l._avg[p]??0;}if(l._min&&s.min.length)for(let p of s.min){let f=p.charAt(0).toUpperCase()+p.slice(1);m[`min${f}`]=l._min[p];}if(l._max&&s.max.length)for(let p of s.max){let f=p.charAt(0).toUpperCase()+p.slice(1);m[`max${f}`]=l._max[p];}return {key:g,values:m}});return {values:{count:c.reduce((l,g)=>l+(g.values.count||0),0)},groups:c}}catch{let c=await t.findMany({where:e});return J$1(c,o)}}},z=class extends w$1{async getModel(){return M(this.prisma,this._meta.model.tableName)}generateId(){return crypto.randomUUID()}async findSource(t,e){let o=await this.getModel(),n=this.getSoftDeleteConfig(),s={[this.lookupField]:t,...e};n.enabled&&(s[n.field]=null);let r=await o.findFirst({where:s});return r||null}async createClone(t){let e=await this.getModel(),o=this.applyManagedInsertFields(t,"prisma",()=>this.generateId());return await e.create({data:o})}};var ht={CreateEndpoint:C,ListEndpoint:A,ReadEndpoint:F,UpdateEndpoint:I,DeleteEndpoint:D,RestoreEndpoint:K,BatchCreateEndpoint:N,BatchUpdateEndpoint:S,BatchDeleteEndpoint:U,BatchRestoreEndpoint:T,BatchUpsertEndpoint:B,SearchEndpoint:$,AggregateEndpoint:Q,ExportEndpoint:L,ImportEndpoint:W,UpsertEndpoint:V,CloneEndpoint:z};export{xe as a,Ae as b,Ke as c,C as d,F as e,I as f,D as g,A as h,K as i,N as j,S as k,U as l,T as m,B as n,$ as o,L as p,W as q,V as r,Re as s,Ee as t,ve as u,_e as v,Q as w,z as x,ht as y};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import {a as a$1,b as b$1}from'./chunk-SDNXN7M5.js';import {b,f as f$2}from'./chunk-4PBGEU64.js';import {f as f$1}from'./chunk-3DE2MG3R.js';import {i,d,a as a$2,b as b$3,c as c$1}from'./chunk-FC56WWPB.js';import {f}from'./chunk-KLBMVJX3.js';import {e,g,n,o,p,c,j,d as d$3,k,i as i$1,r}from'./chunk-FHABLABR.js';import {d as d$2,e as e$1}from'./chunk-QRXEQTNE.js';import {d as d$1}from'./chunk-QXFY6NYI.js';import {b as b$4}from'./chunk-DMGP7QDL.js';import {a,b as b$2}from'./chunk-VJRDAVID.js';import {z}from'zod';import {HTTPException}from'hono/http-exception';import {stream}from'hono/streaming';var pe="createdAt",me="updatedAt";function ne(i){return i?i===true?{enabled:true,createdAt:pe,updatedAt:me}:{enabled:true,createdAt:i.createdAt??pe,updatedAt:i.updatedAt??me}:{enabled:false,createdAt:pe,updatedAt:me}}function Z(i,e={}){let{includePrimaryKeys:t=true}=e,o=new Set;if(t)for(let s of i.primaryKeys)o.add(s);let r=ne(i.timestamps);return r.enabled&&(o.add(r.createdAt),o.add(r.updatedAt)),[...o]}function Rt(i){return i!=null&&i!==""}function Ze(i$1,e,t,o){let r={...i$1},s=e.primaryKeys[0];if(!Rt(r[s])){let u=e.id;if(typeof u=="function")r[s]=u();else if(u==="database"){if(t==="memory")throw new i("MemoryAdapter does not support id:'database' (no database to generate the key)");delete r[s];}else r[s]=o?o():crypto.randomUUID();}let n=ne(e.timestamps);if(n.enabled){let u=Date.now();n.createdAt in i$1||(r[n.createdAt]=u),n.updatedAt in i$1||(r[n.updatedAt]=u);}return r}function De(i,e){let t=ne(e.timestamps);return t.enabled?{...i,[t.updatedAt]:Date.now()}:{...i}}function ze(i$1,e){if(e==="memory"&&i$1.id==="database")throw new i("MemoryAdapter does not support id:'database' (no database to generate the key)")}function Le(i,e){let t={...i};for(let o of Z(e))delete t[o];return t}function qe(i){let e=i;for(let t=0;t<8&&e&&typeof e=="object";t++){let o=e,r=typeof o.code=="string"||typeof o.code=="number"?o.code:"",s=typeof o.name=="string"?o.name:"",n=typeof o.message=="string"?o.message:"";if(r==="P2002")return new d("Unique constraint violation");if(r==="SQLITE_CONSTRAINT_UNIQUE"||r==="SQLITE_CONSTRAINT"||/UNIQUE constraint failed/i.test(n))return new d("Unique constraint violation");if(r==="23505")return new d("Unique constraint violation");if(r==="ER_DUP_ENTRY"||r===1062||r==="1062")return new d("Unique constraint violation");if(s==="PrismaClientKnownRequestError"&&r==="P2002")return new d("Unique constraint violation");e=o.cause;}return null}function he(i){if(i===null||typeof i!="object")return i;if(Array.isArray(i))return i.map(he);let e={};for(let t of Object.keys(i).sort())e[t]=he(i[t]);return e}async function oe(i){let e=JSON.stringify(he(i)),t=new TextEncoder().encode(e),o=await crypto.subtle.digest("SHA-256",t);return `"${Array.from(new Uint8Array(o)).map(n=>n.toString(16).padStart(2,"0")).join("").substring(0,32)}"`}function ge(i,e){return i?i==="*"?true:i.split(",").map(t=>t.trim()).includes(e):false}function fe(i,e){return !i||i==="*"?true:i.split(",").map(t=>t.trim()).includes(e)}function Ue(i,e){return i==="in"||i==="nin"||i==="between"?e.split(",").map(t=>t.trim()):i==="null"?e.toLowerCase()==="true":e}function zt(i){let e=i.match(/^\[([a-z]+)\](.*)$/);if(e){let t=e[1];return {operator:t,value:Ue(t,e[2])}}return {operator:"eq",value:i}}function le(i,e){let t=[],o={},{filterFields:r=[],filterConfig:s={},searchFields:n=[],searchFieldName:u="search",sortFields:l=[],defaultSort:p,defaultPerPage:a=20,maxPerPage:c=100,cursorPaginationEnabled:d=false,softDeleteQueryParam:m="withDeleted",allowedIncludes:f=[],fieldSelectionEnabled:g=false,allowedSelectFields:j=[],blockedSelectFields:x=[],alwaysIncludeFields:k=[],defaultSelectFields:y=[]}=e,F={};for(let v of r)F[v]=["eq"];Object.assign(F,s);for(let[v,X]of Object.entries(i)){if(X==null)continue;let V=String(X);if(d&&v==="cursor"){o.cursor=V;continue}if(d&&v==="limit"){o.limit=Math.min(c,Math.max(1,parseInt(V,10)||a));continue}if(v==="page"){o.page=Math.max(1,parseInt(V,10)||1);continue}if(v==="per_page"){o.per_page=Math.min(c,Math.max(1,parseInt(V,10)||a));continue}if(v==="sort"){(l.length===0||l.includes(V))&&(o.order_by=V);continue}if(v==="order"){(V==="asc"||V==="desc")&&(o.order_by_direction=V);continue}if(v===u&&n.length>0){o.search=V;continue}if(v===m){o.withDeleted=V.toLowerCase()==="true";continue}if(v==="onlyDeleted"){o.onlyDeleted=V.toLowerCase()==="true";continue}if(v==="include"){let ee=V.split(",").map(L=>L.trim()).filter(Boolean);f&&f.length>0?o.include=ee.filter(L=>f.includes(L)):o.include=ee;continue}if(v==="fields"&&g){let L=V.split(",").map(re=>re.trim()).filter(Boolean);j.length>0&&(L=L.filter(re=>j.includes(re))),x.length>0&&(L=L.filter(re=>!x.includes(re))),k.length>0&&(L=[...new Set([...k,...L])]),o.fields=L;continue}let ue=v.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([a-z]+)\]$/);if(ue){let ee=ue[1],L=ue[2];F[ee]?.includes(L)&&t.push({field:ee,operator:L,value:Ue(L,V)});continue}F[v]&&t.push({field:v,operator:"eq",value:V});}if(o.page||(o.page=1),o.per_page||(o.per_page=a),!o.order_by&&p?.field&&(o.order_by=p.field),o.order_by_direction||(o.order_by_direction=p?.order??"asc"),g&&!o.fields&&y.length>0){let v=[...y];k.length>0&&(v=[...new Set([...k,...v])]),o.fields=v;}return {filters:t,options:o}}function D(i,e=[]){if(e.length===0)return i;let t=new Set(Object.keys(i.shape)),o=e.filter(s=>t.has(s));if(o.length===0)return i;let r=Object.fromEntries(o.map(s=>[s,true]));return i.omit(r)}function Lt(i,e={},t=[],o=[],r=[]){let{allowedFields:s=[],blockedFields:n=[],alwaysIncludeFields:u=[],defaultFields:l=[],allowComputedFields:p=true,allowRelationFields:a=true}=e;if(!i||typeof i!="string"||i.trim()==="")return l.length>0?{fields:[...new Set([...u,...l])],isActive:false}:{fields:[],isActive:false};let c=i.split(",").map(g=>g.trim()).filter(Boolean),d=new Set;for(let g of t)(s.length===0||s.includes(g))&&(n.includes(g)||d.add(g));if(p)for(let g of o)(s.length===0||s.includes(g))&&(n.includes(g)||d.add(g));if(a)for(let g of r)(s.length===0||s.includes(g))&&(n.includes(g)||d.add(g));let m=c.filter(g=>d.has(g));return {fields:[...new Set([...u,...m])],isActive:true}}function be(i,e){if(!e.isActive||e.fields.length===0)return i;let t={};for(let o of e.fields)o in i&&(t[o]=i[o]);return t}function de(i,e){return !e.isActive||e.fields.length===0?i:i.map(t=>be(t,e))}var He="__honoCrudResolvedSchema:";function kt(i){return typeof i.getBodySchema=="function"}var S=class extends b{_auditLogger;_versionManager;_tx;getAuditLogger(){return this._auditLogger||(this._auditLogger=f(this._meta.model.audit)),this._auditLogger}getAuditConfig(){return e(this._meta.model.audit)}isAuditEnabled(){return this.getAuditConfig().enabled}getAuditUserId(){let e=this.getAuditConfig();return e.getUserId&&this.context?e.getUserId(this.context):this.context?.var?.userId}getVersionManager(){return this._versionManager||(this._versionManager=f$1(this._meta.model.versioning,this._meta.model.tableName)),this._versionManager}getVersioningConfig(){return g(this._meta.model.versioning,this._meta.model.tableName)}isVersioningEnabled(){return this.getVersioningConfig().enabled}getVersioningUserId(){let e=this.getVersioningConfig();return e.getUserId&&this.context?e.getUserId(this.context):this.context?.var?.userId}getSoftDeleteConfig(){return n(this._meta.model.softDelete)}isSoftDeleteEnabled(){return this.getSoftDeleteConfig().enabled}getMultiTenantConfig(){return o(this._meta.model.multiTenant)}isMultiTenantEnabled(){return this.getMultiTenantConfig().enabled}applyManagedInsertFields(e,t,o){return Ze(e,this._meta.model,t,o)}applyManagedUpdateFields(e){return De(e,this._meta.model)}assertIdStrategySupported(e){ze(this._meta.model,e);}getTimestampsConfig(){return ne(this._meta.model.timestamps)}getTenantId(){if(!this.context)return;let e=this.getMultiTenantConfig();return p(this.context,e)}validateTenantId(){let e=this.getMultiTenantConfig();if(!e.enabled)return;let t=this.getTenantId();if(!t&&e.required)throw new HTTPException(400,{message:e.errorMessage});return t}injectTenantId(e){let t=this.getMultiTenantConfig();if(!t.enabled)return e;let o=this.getTenantId();return o?{...e,[t.field]:o}:e}async emitEvent(e,t){let o=d$1(this.context??void 0);o&&await o.emit({type:e,table:this._meta.model.tableName,recordId:t.recordId,data:t.data??null,previousData:t.previousData,userId:this.getAuditUserId(),tenantId:this.context?this.getTenantId():void 0,organizationId:this.context?a(this.context,"organizationId"):void 0,timestamp:new Date().toISOString(),metadata:t.metadata});}async encryptOnWrite(e){let t=this._meta.model.fieldEncryption;return t?await d$2(e,t.fields,t.keyProvider):e}async decryptOnRead(e){let t=this._meta.model.fieldEncryption;return t?await e$1(e,t.fields,t.keyProvider):e}applyProfile(e){let t=this._meta.model.serializationProfile;return t?a$1(e,t):e}applyProfileToArray(e){let t=this._meta.model.serializationProfile;return t?b$1(e,t):e}getRecordId(e){if(e===null||typeof e!="object")return null;let t=this._meta.model.primaryKeys[0],o=e[t];return typeof o=="string"||typeof o=="number"?o:null}getParentId(e){return this.getRecordId(e)}getPolicies(){if(this.context){let e=a(this.context,f$2);if(e)return e}return this._meta.model.policies}buildPolicyContext(){let e=this.context;return {user:e?a(e,"user"):void 0,userId:e?a(e,"userId"):void 0,tenantId:e?a(e,"tenantId"):void 0,organizationId:e?a(e,"organizationId"):void 0,request:e?.req?.raw??new Request("http://localhost/")}}async applyReadPolicy(e){let t=this.getPolicies();if(!t)return e;let o=this.buildPolicyContext();if(t.read&&!await t.read(o,e))return null;if(t.fields){let r=t.fields(o,e);return {...e,...r}}return e}async applyReadPolicyToArray(e){if(!this.getPolicies())return e;let o=[];for(let r of e){let s=await this.applyReadPolicy(r);s!==null&&o.push(s);}return o}async applyWritePolicy(e){let t=this.getPolicies();if(!t?.write)return;if(!await t.write(this.buildPolicyContext(),e))throw new HTTPException(403,{message:"Forbidden by policy"})}applyReadPushdown(e){let t=this.getPolicies();if(!t?.readPushdown)return;let o=t.readPushdown(this.buildPolicyContext());o&&o.length>0&&e.filters.push(...o);}buildHookContext(){let e=this.context;return {db:{tx:this._tx},request:e?.req?.raw,tenantId:e?this.getTenantId():void 0,organizationId:e?a(e,"organizationId"):void 0,userId:e?a(e,"userId"):void 0,agentId:e?a(e,"agentId"):void 0,agentRunId:e?a(e,"agentRunId"):void 0}}getModelSchema(){if(this.context&&this._meta.model.resolveSchema){let e=a(this.context,He+this._meta.model.tableName);if(e)return e}return this._meta.model.schema}async resolveModelSchema(){let e=this._meta.model.resolveSchema;if(!e||!this.context)return this._meta.model.schema;let t=He+this._meta.model.tableName,o=a(this.context,t);if(o)return o;let r={tenantId:a(this.context,"tenantId"),organizationId:a(this.context,"organizationId"),request:this.context.req?.raw,env:this.context.env},s;try{s=await e(r);}catch(n){throw new a$2(n instanceof Error?n.message:"Schema resolution failed",500,"SCHEMA_RESOLVE_ERROR",n instanceof Error?{cause:n.message}:void 0)}return b$2(this.context,t,s),s}async getValidatedData(){await this.resolveModelSchema();let e=await super.getValidatedData();if(this.context&&e.body!==void 0&&kt(this)){let t=e.body;try{t=await this.context.req.json();}catch{}let r=this.getBodySchema().safeParse(t);if(!r.success)throw b$3.fromZodError(r.error);e.body=r.data;}return e}};var $e=class extends S{beforeHookMode="sequential";afterHookMode="sequential";allowNestedCreate=[];getBodySchema(){let e,t=Z(this._meta.model),o=this.getMultiTenantConfig();o.enabled&&t.push(o.field),this._meta.fields?e=this._meta.fields:e=D(this.getModelSchema(),t);let r=this.getNestedWritableRelations();if(r.length===0)return e;let s={...e.shape};for(let n of r){let u=this._meta.model.relations?.[n];if(!u?.schema)continue;let l=["id",u.foreignKey],p=D(u.schema,l);u.type==="hasMany"?s[n]=z.array(p).optional():s[n]=p.optional();}return z.object(s)}getNestedWritableRelations(){if(this.allowNestedCreate.length>0)return this.allowNestedCreate;let e=this._meta.model.relations;return e?Object.entries(e).filter(([t,o])=>o.nestedWrites?.allowCreate===true).map(([t])=>t):[]}extractNestedData(e){let t=this.getNestedWritableRelations();return c(e,t)}getSchema(){let e=this.getBodySchema();return {...this.schema,request:{body:{content:{"application/json":{schema:e}},required:true}},responses:{201:{description:"Resource created successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}}}}}}async getObject(){let{body:e}=await this.getValidatedData();return e}async before(e,t){return e}async after(e,t){return e}transform(e){return e}async createNested(e,t,o,r,s){return b$4().warn(`Nested writes not implemented for ${t}. Override createNested() in your adapter.`),[]}async handle(){this.validateTenantId();let e=await this.getObject(),{mainData:t,nestedData:o}=this.extractNestedData(e),r=t;r=this.injectTenantId(r);let s=this.buildHookContext();r=await this.before(r,s),r=await this.encryptOnWrite(r),r=await this.create(r,s.db.tx),r=await this.decryptOnRead(r);let n=this.getParentId(r),u={};if(Object.keys(o).length>0&&n!==null)for(let[c,d]of Object.entries(o)){if(d==null)continue;let m=this._meta.model.relations?.[c];if(!m)continue;let f=await this.createNested(n,c,m,d);u[c]=f;}if(Object.keys(u).length>0){let c={};for(let[d,m]of Object.entries(u)){let f=this._meta.model.relations?.[d];f&&(f.type==="hasMany"?c[d]=m:c[d]=m[0]||null);}r={...r,...c};}if(this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(r,s))):r=await this.after(r,s),this.isAuditEnabled()&&n!==null){let c=this.getAuditLogger();this.runAfterResponse(c.logCreate(this._meta.model.tableName,n,r,this.getAuditUserId()));}n!==null&&this.runAfterResponse(this.emitEvent("created",{recordId:n,data:r})),this._meta.model.computedFields&&(r=await j(r,this._meta.model.computedFields));let l=this._meta.model.serializer?this._meta.model.serializer(r):r,p=this.applyProfile(l),a=this.transform(p);return this.success(a,201)}};var Ke=class extends S{lookupField="id";lookupFields;additionalFilters;etagEnabled=false;allowedIncludes=[];fieldSelectionEnabled=false;allowedSelectFields=[];blockedSelectFields=[];alwaysIncludeFields=[];defaultSelectFields=[];getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){let e={};if(this.additionalFilters?.length)for(let t of this.additionalFilters)e[t]=z.string().optional();if(this.allowedIncludes.length>0&&(e.include=z.string().optional().describe(`Comma-separated list of relations to include. Allowed: ${this.allowedIncludes.join(", ")}`)),this.fieldSelectionEnabled){let t=this.getAvailableSelectFields();e.fields=z.string().optional().describe(`Comma-separated list of fields to return. Available: ${t.join(", ")}`);}if(Object.keys(e).length!==0)return z.object(e)}getAvailableSelectFields(){let e=Object.keys(this.getModelSchema().shape),t=this._meta.model.computedFields?Object.keys(this._meta.model.computedFields):[],o=this._meta.model.relations?Object.keys(this._meta.model.relations):[],r=[...e,...t,...o];return this.allowedSelectFields.length>0&&(r=r.filter(s=>this.allowedSelectFields.includes(s))),this.blockedSelectFields.length>0&&(r=r.filter(s=>!this.blockedSelectFields.includes(s))),r}getSchema(){let e=this.getQuerySchema();return {...this.schema,request:{params:this.getParamsSchema(),...e&&{query:e}},responses:{200:{description:"Resource retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},404:{description:"Resource not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async getIncludeOptions(){let{query:e}=await this.getValidatedData(),t=e?.include;if(!t||typeof t!="string")return {relations:[]};let o=t.split(",").map(r=>r.trim()).filter(Boolean);return this.allowedIncludes.length>0?{relations:o.filter(r=>this.allowedIncludes.includes(r))}:{relations:o}}async getFieldSelection(){if(!this.fieldSelectionEnabled)return {fields:[],isActive:false};let{query:e}=await this.getValidatedData(),t=e?.fields;if(!t||typeof t!="string"||t.trim()==="")return this.defaultSelectFields.length>0?{fields:[...new Set([...this.alwaysIncludeFields,...this.defaultSelectFields])],isActive:true}:{fields:[],isActive:false};let o=t.split(",").map(n=>n.trim()).filter(Boolean),r=new Set(this.getAvailableSelectFields()),s=o.filter(n=>r.has(n));return this.alwaysIncludeFields.length>0&&(s=[...new Set([...this.alwaysIncludeFields,...s])]),{fields:s,isActive:true}}async after(e){return e}transform(e){return e}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getAdditionalFilters(),r=await this.getIncludeOptions(),s=await this.getFieldSelection();if(e){let d=this.getMultiTenantConfig();o[d.field]=e;}let n=await this.read(t,o,r);if(!n)throw new c$1(this._meta.model.tableName,t);n=await this.decryptOnRead(n);let u=await this.applyReadPolicy(n);if(u===null)throw new c$1(this._meta.model.tableName,t);n=u,n=await this.after(n),this._meta.model.computedFields&&(n=await j(n,this._meta.model.computedFields));let l=this._meta.model.serializer?this._meta.model.serializer(n):n,p=this.applyProfile(l),a=this.transform(p),c=s.isActive&&s.fields.length>0?be(a,s):a;if(this.etagEnabled){let d=await oe(c),m=this.getContext(),f=m.req.header("If-None-Match");if(ge(f,d))return new Response(null,{status:304,headers:{ETag:d}});m.header("ETag",d);}return this.success(c)}};var We=class extends S{lookupField="id";lookupFields;additionalFilters;allowedUpdateFields;blockedUpdateFields;beforeHookMode="sequential";afterHookMode="sequential";allowNestedWrites=[];etagEnabled=false;getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getBodySchema(){let e;if(this._meta.fields)e=this._meta.fields.partial();else {let r=Z(this._meta.model);this.blockedUpdateFields&&(r=[...r,...this.blockedUpdateFields]);let s=D(this.getModelSchema(),r);if(this.allowedUpdateFields){let n=this.allowedUpdateFields.reduce((u,l)=>({...u,[l]:true}),{});s=s.pick(n);}e=s.partial();}let t=this.getNestedWritableRelations();if(t.length===0)return e;let o={...e.shape};for(let r of t){let s=this._meta.model.relations?.[r];if(!s?.schema)continue;let n=s.schema,u=z.object({create:z.union([n.partial(),z.array(n.partial())]).optional(),update:z.array(n.partial().extend({id:z.union([z.string(),z.number()])})).optional(),delete:z.array(z.union([z.string(),z.number()])).optional(),connect:z.array(z.union([z.string(),z.number()])).optional(),disconnect:z.array(z.union([z.string(),z.number()])).optional(),set:n.partial().nullable().optional()}).optional();o[r]=u;}return z.object(o)}getNestedWritableRelations(){if(this.allowNestedWrites.length>0)return this.allowNestedWrites;let e=this._meta.model.relations;return e?Object.entries(e).filter(([t,o])=>{let r=o.nestedWrites;return r&&(r.allowCreate||r.allowUpdate||r.allowDelete||r.allowConnect||r.allowDisconnect)}).map(([t])=>t):[]}extractNestedData(e){let t=this.getNestedWritableRelations();return c(e,t)}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),body:{content:{"application/json":{schema:this.getBodySchema()}},required:true}},responses:{200:{description:"Resource updated successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}}},404:{description:"Resource not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getObject(){let{body:e}=await this.getValidatedData();return e}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async before(e,t){return e}async after(e,t,o){return t}transform(e){return e}async findExisting(e,t,o){return null}async processNestedWrites(e,t,o,r,s){return b$4().warn(`Nested writes not implemented for ${t}. Override processNestedWrites() in your adapter.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]}}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getAdditionalFilters();if(e){let y=this.getMultiTenantConfig();o[y.field]=e;}let r=await this.getObject(),{mainData:s,nestedData:n}=this.extractNestedData(r),u=this.getPolicies(),l=await this.findExisting(t,o,this._tx);if(l&&u?.write&&await this.applyWritePolicy(l),this.etagEnabled&&l){let y=this.getContext().req.header("If-Match");if(y){let F=await oe(l);if(!fe(y,F))return this.error("Resource has been modified by another request","CONFLICT",409)}}let p;if(this.isVersioningEnabled()&&l){let y=this.getVersionManager(),F=this.getParentId(l);F!==null&&(p=await y.saveVersion(F,l,void 0,this.getVersioningUserId()));}let a=s;if(this.isVersioningEnabled()&&p!==void 0){let y=this.getVersioningConfig().field;a[y]=p;}let c=this.buildHookContext();a=await this.before(a,c),a=await this.encryptOnWrite(a);let d=await this.update(t,a,o,c.db.tx);if(!d)throw new c$1(this._meta.model.tableName,t);d=await this.decryptOnRead(d);let m=this.getParentId(d),f={};if(Object.keys(n).length>0&&m!==null)for(let[y,F]of Object.entries(n)){if(F==null)continue;let v=this._meta.model.relations?.[y];if(!v)continue;let X;d$3(F)?X={create:F}:X=F;let V=await this.processNestedWrites(m,y,v,X);f[y]=V;}if(Object.keys(f).length>0)for(let[y,F]of Object.entries(f)){let v=this._meta.model.relations?.[y];v&&(v.type==="hasMany"?d[y]=[...F.created,...F.updated]:d[y]=F.created[0]||F.updated[0]||null);}let g=l??d;if(this.afterHookMode==="fire-and-forget")this.runAfterResponse(Promise.resolve(this.after(g,d,c)));else {let y=await this.after(g,d,c);y!=null&&(d=y);}if(this.isAuditEnabled()&&m!==null&&l){let y=this.getAuditLogger();this.runAfterResponse(y.logUpdate(this._meta.model.tableName,m,l,d,this.getAuditUserId()));}m!==null&&this.runAfterResponse(this.emitEvent("updated",{recordId:m,data:d,previousData:l??void 0})),this._meta.model.computedFields&&(d=await j(d,this._meta.model.computedFields));let j$1=this._meta.model.serializer?this._meta.model.serializer(d):d,x=this.applyProfile(j$1),k=this.transform(x);if(this.etagEnabled){let y=await oe(k);this.getContext().header("ETag",y);}return this.success(k)}};var Qe=class extends S{lookupField="id";lookupFields;additionalFilters;beforeHookMode="sequential";afterHookMode="sequential";includeCascadeResults=false;getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getCascadeRelations(e){let t=this._meta.model.relations;return t?Object.entries(t).filter(([o,r])=>{let s=r.cascade?.[e];return s&&s!=="noAction"}).map(([o,r])=>({name:o,config:r,action:r.cascade[e]})):[]}getSchema(){let e=this.includeCascadeResults?z.object({deleted:z.literal(true),cascade:z.object({deleted:z.record(z.string(),z.number()),nullified:z.record(z.string(),z.number())}).optional()}):z.object({deleted:z.literal(true)});return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Resource deleted successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:e})}}},404:{description:"Resource not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}},409:{description:"Cannot delete - related records exist (restrict)",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.object({relation:z.string(),count:z.number()}).optional()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async before(e,t){}async after(e,t){}async countRelated(e,t,o,r){return b$4().warn(`countRelated not implemented for ${t}. Override in your adapter for restrict cascade to work.`),0}async deleteRelated(e,t,o,r){return b$4().warn(`deleteRelated not implemented for ${t}. Override in your adapter for cascade delete to work.`),0}async nullifyRelated(e,t,o,r){return b$4().warn(`nullifyRelated not implemented for ${t}. Override in your adapter for setNull cascade to work.`),0}async processCascade(e,t,o){let r=t?"onSoftDelete":"onDelete",s=this.getCascadeRelations(r),n={deleted:{},nullified:{}};for(let{name:u,config:l,action:p}of s)if(p==="cascade"){let a=await this.deleteRelated(e,u,l,o);a>0&&(n.deleted[u]=a);}else if(p==="setNull"){let a=await this.nullifyRelated(e,u,l,o);a>0&&(n.nullified[u]=a);}return n}async checkRestrictConstraints(e,t,o){let r=t?"onSoftDelete":"onDelete",s=this.getCascadeRelations(r);for(let{name:n,config:u,action:l}of s)if(l==="restrict"){let p=await this.countRelated(e,n,u,o);if(p>0)throw new d(`Cannot delete: ${p} related ${n} record(s) exist. Remove them first or change the cascade configuration.`,{relation:n,count:p})}}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getAdditionalFilters();if(e){let c=this.getMultiTenantConfig();o[c.field]=e;}let r=this.isSoftDeleteEnabled(),s=await this.findForDelete(t,o,this._tx);if(!s)throw new c$1(this._meta.model.tableName,t);let n=this.getParentId(s);n!==null&&await this.checkRestrictConstraints(n,r),await this.applyWritePolicy(s);let u=this.buildHookContext();if(await this.before(t,u),!await this.delete(t,o,u.db.tx))throw new c$1(this._meta.model.tableName,t);let p;if(n!==null&&(p=await this.processCascade(n,r)),this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(s,u))):await this.after(s,u),this.isAuditEnabled()&&n!==null){let c=this.getAuditLogger();this.runAfterResponse(c.logDelete(this._meta.model.tableName,n,s,this.getAuditUserId()));}n!==null&&this.runAfterResponse(this.emitEvent("deleted",{recordId:n,previousData:s}));let a={deleted:true};if(this.includeCascadeResults&&p){let c=Object.keys(p.deleted).length>0,d=Object.keys(p.nullified).length>0;(c||d)&&(a.cascade=p);}return this.success(a)}};var ce=class extends S{filterFields=[];filterConfig;searchFields=[];searchFieldName="search";sortFields=[];defaultSort;defaultPerPage=20;maxPerPage=100;cursorPaginationEnabled=false;cursorField;allowedIncludes=[];fieldSelectionEnabled=false;allowedSelectFields=[];blockedSelectFields=[];alwaysIncludeFields=[];defaultSelectFields=[];getQuerySchema(){let e={page:z.string().optional(),per_page:z.string().optional()};this.sortFields.length>0&&(e.sort=z.enum(this.sortFields).optional().describe("Field to sort by"),e.order=z.enum(["asc","desc"]).optional().describe("Sort direction (asc or desc)")),this.searchFields.length>0&&(e[this.searchFieldName]=z.string().optional());for(let o of this.filterFields)e[o]=z.string().optional();if(this.filterConfig)for(let[o,r]of Object.entries(this.filterConfig)){for(let s of r)e[`${o}[${s}]`]=z.string().optional();e[o]=z.string().optional();}let t=this.getSoftDeleteConfig();if(t.enabled&&t.allowQueryDeleted&&(e[t.queryParam]=z.enum(["true","false"]).optional(),e.onlyDeleted=z.enum(["true","false"]).optional()),this.allowedIncludes.length>0&&(e.include=z.string().optional().describe(`Comma-separated list of relations to include. Allowed: ${this.allowedIncludes.join(", ")}`)),this.fieldSelectionEnabled){let o=this.getAvailableSelectFields();e.fields=z.string().optional().describe(`Comma-separated list of fields to return. Available: ${o.join(", ")}`);}return this.cursorPaginationEnabled&&(e.cursor=z.string().optional().describe("Opaque cursor for fetching the next page"),e.limit=z.string().optional().describe("Number of items to return (cursor pagination)")),z.object(e)}getAvailableSelectFields(){let e=Object.keys(this.getModelSchema().shape),t=this._meta.model.computedFields?Object.keys(this._meta.model.computedFields):[],o=this._meta.model.relations?Object.keys(this._meta.model.relations):[],r=[...e,...t,...o];return this.allowedSelectFields.length>0&&(r=r.filter(s=>this.allowedSelectFields.includes(s))),this.blockedSelectFields.length>0&&(r=r.filter(s=>!this.blockedSelectFields.includes(s))),r}getSchema(){return {...this.schema,request:{query:this.getQuerySchema()},responses:{200:{description:"List of resources",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.array(this.getModelSchema()),result_info:z.object({page:z.number(),per_page:z.number(),total_count:z.number().optional(),total_pages:z.number().optional(),has_next_page:z.boolean(),has_prev_page:z.boolean(),next_cursor:z.string().optional(),prev_cursor:z.string().optional()})})}}}}}}async getFilters(){let{query:e}=await this.getValidatedData(),t=this.getSoftDeleteConfig(),o={filterFields:this.filterFields,filterConfig:this.filterConfig,searchFields:this.searchFields,searchFieldName:this.searchFieldName,sortFields:this.sortFields,defaultSort:this.defaultSort,defaultPerPage:this.defaultPerPage,maxPerPage:this.maxPerPage,cursorPaginationEnabled:this.cursorPaginationEnabled,cursorField:this.cursorField,softDeleteQueryParam:t.queryParam,allowedIncludes:this.allowedIncludes,fieldSelectionEnabled:this.fieldSelectionEnabled,allowedSelectFields:this.allowedSelectFields,blockedSelectFields:this.blockedSelectFields,alwaysIncludeFields:this.alwaysIncludeFields,defaultSelectFields:this.defaultSelectFields};return le(e||{},o)}async after(e){return e}transform(e){return e}async handle(){let e=this.validateTenantId(),t=await this.getFilters();if(e){let a=this.getMultiTenantConfig();t.filters.push({field:a.field,operator:"eq",value:e});}this.applyReadPushdown(t);let o=await this.list(t),r=await Promise.all(o.result.map(a=>this.decryptOnRead(a))),s=await this.applyReadPolicyToArray(r),n=await this.after(s);this._meta.model.computedFields&&(n=await k(n,this._meta.model.computedFields)),this._meta.model.serializer&&(n=n.map(a=>this._meta.model.serializer(a)));let l=this.applyProfileToArray(n).map(a=>this.transform(a)),p=this.fieldSelectionEnabled&&t.options.fields&&t.options.fields.length>0?de(l,{fields:t.options.fields,isActive:true}):l;return this.successPaginated(p,o.result_info)}};var Ge=class extends S{lookupField="id";excludeFromClone=[];getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getBodySchema(){let e=[...Z(this._meta.model),...this.excludeFromClone];return D(this.getModelSchema(),e).partial()}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),body:{content:{"application/json":{schema:this.getBodySchema()}},required:false}},responses:{201:{description:"Resource cloned successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},404:{description:"Source resource not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}},409:{description:"Unique-constraint violation (e.g. natural-key collision)",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getOverrides(){let{body:e}=await this.getValidatedData();return e||{}}async before(e){return e}async after(e){return e}async handle(){let e=this.validateTenantId(),t=await this.getLookupValue(),o=await this.getOverrides(),r={};if(e){let a=this.getMultiTenantConfig();r[a.field]=e;}let s=await this.findSource(t,r);if(!s)throw new c$1(this._meta.model.tableName,t);let n=Le(s,this._meta.model);for(let a of this.excludeFromClone)delete n[a];Object.assign(n,o);let u=await this.before(n),l;try{l=await this.createClone(u);}catch(a){let c=qe(a);throw c||a}l=await this.after(l),this._meta.model.computedFields&&(l=await j(l,this._meta.model.computedFields));let p=this._meta.model.serializer?this._meta.model.serializer(l):l;return this.success(p,201)}};var Je=class extends S{lookupField="id";lookupFields;additionalFilters;beforeHookMode="sequential";afterHookMode="sequential";getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Resource restored successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:{description:"Soft delete not enabled or record not deleted",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}},404:{description:"Resource not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getAdditionalFilters(){if(!this.additionalFilters?.length)return {};let{query:e}=await this.getValidatedData(),t={};for(let o of this.additionalFilters)e?.[o]&&(t[o]=String(e[o]));return t}async before(e,t){}async after(e,t){return e}async handle(){if(!this.isSoftDeleteEnabled())throw new a$2("Soft delete is not enabled for this model",400,"SOFT_DELETE_NOT_ENABLED");let e=await this.getLookupValue(),t=await this.getAdditionalFilters();await this.before(e);let o=await this.restore(e,t);if(!o)throw new c$1(this._meta.model.tableName,e);this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(o))):o=await this.after(o);let r=this.getRecordId(o);if(this.isAuditEnabled()&&r!==null){let n=this.getAuditLogger();this.runAfterResponse(n.logRestore(this._meta.model.tableName,r,o,this.getAuditUserId()));}r!==null&&this.runAfterResponse(this.emitEvent("restored",{recordId:r,data:o}));let s=this._meta.model.serializer?this._meta.model.serializer(o):o;return this.success(s)}};var Ye=class extends S{upsertKeys;useNativeUpsert=false;createOnlyFields;updateOnlyFields;beforeHookMode="sequential";afterHookMode="sequential";allowNestedWrites=[];getUpsertKeys(){return this.upsertKeys||this._meta.model.primaryKeys}getBodySchema(){let e;if(this._meta.fields)e=this._meta.fields;else {let r=this.getUpsertKeys(),s=Z(this._meta.model,{includePrimaryKeys:false});for(let l of this._meta.model.primaryKeys)r.includes(l)||s.push(l);let n=D(this.getModelSchema(),s),u={};for(let[l,p]of Object.entries(n.shape))r.includes(l)?u[l]=p:u[l]=p.optional();e=z.object(u);}let t=this.getNestedWritableRelations();if(t.length===0)return e;let o={...e.shape};for(let r of t){let s=this._meta.model.relations?.[r];if(!s?.schema)continue;let n=s.schema,u=z.union([s.type==="hasMany"?z.array(n.partial()):n.partial(),z.object({create:z.union([n.partial(),z.array(n.partial())]).optional(),update:z.array(n.partial().extend({id:z.union([z.string(),z.number()])})).optional(),upsert:z.union([n.partial(),z.array(n.partial())]).optional(),delete:z.array(z.union([z.string(),z.number()])).optional(),connect:z.array(z.union([z.string(),z.number()])).optional(),disconnect:z.array(z.union([z.string(),z.number()])).optional(),set:n.partial().nullable().optional()})]).optional();o[r]=u;}return z.object(o)}getNestedWritableRelations(){if(this.allowNestedWrites.length>0)return this.allowNestedWrites;let e=this._meta.model.relations;return e?Object.entries(e).filter(([t,o])=>{let r=o.nestedWrites;return r&&(r.allowCreate||r.allowUpdate||r.allowDelete||r.allowConnect||r.allowDisconnect)}).map(([t])=>t):[]}extractNestedData(e){let t=this.getNestedWritableRelations();return c(e,t)}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}},required:true}},responses:{200:{description:"Resource updated (upsert)",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema(),created:z.literal(false)})}}},201:{description:"Resource created (upsert)",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema(),created:z.literal(true)})}}},400:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}}}}}}async getObject(){let{body:e}=await this.getValidatedData();return e}async before(e,t,o){return e}async beforeCreate(e,t){return e}async beforeUpdate(e,t,o){return e}async after(e,t,o){return e}async nativeUpsert(e,t){return b$4().warn("Native upsert not implemented for this adapter. Falling back to find-then-insert/update pattern."),this.performStandardUpsert(e,t)}async performStandardUpsert(e,t){let o=await this.findExisting(e,t);if(o){let r={...e};if(this.createOnlyFields)for(let n of this.createOnlyFields)delete r[n];return r=await this.beforeUpdate(r,o,t),{data:await this.update(o,r,t),created:false}}else {let r={...e};if(this.updateOnlyFields)for(let n of this.updateOnlyFields)delete r[n];return r=await this.beforeCreate(r,t),{data:await this.create(r,t),created:true}}}async upsert(e,t){return this.useNativeUpsert?this.nativeUpsert(e,t):this.performStandardUpsert(e,t)}async processNestedWrites(e,t,o,r,s){return b$4().warn(`Nested writes not implemented for ${t}. Override processNestedWrites() in your adapter.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]}}async handle(){this.validateTenantId();let e=await this.getObject(),{mainData:t,nestedData:o}=this.extractNestedData(e),r=t;r=this.injectTenantId(r);let s=await this.findExisting(r),n=!s;r=await this.before(r,n);let u=await this.upsert(r),l=u.data,p=this.getParentId(l),a={};if(Object.keys(o).length>0&&p!==null)for(let[d,m]of Object.entries(o)){if(m==null)continue;let f=this._meta.model.relations?.[d];if(!f)continue;let g;d$3(m)?g={create:m}:g=m;let j=await this.processNestedWrites(p,d,f,g);a[d]=j;}if(Object.keys(a).length>0)for(let[d,m]of Object.entries(a)){let f=this._meta.model.relations?.[d];f&&(f.type==="hasMany"?l[d]=[...m.created,...m.updated]:l[d]=m.created[0]||m.updated[0]||null);}if(this.afterHookMode==="fire-and-forget"?this.runAfterResponse(Promise.resolve(this.after(l,u.created))):l=await this.after(l,u.created),this.isAuditEnabled()&&p!==null){let d=this.getAuditLogger();this.runAfterResponse(d.logUpsert(this._meta.model.tableName,p,l,s,u.created,this.getAuditUserId()));}this._meta.model.computedFields&&(l=await j(l,this._meta.model.computedFields));let c=this._meta.model.serializer?this._meta.model.serializer(l):l;return this.json({success:true,result:c,created:u.created},u.created?201:200)}};var Xe=class extends S{maxBatchSize=100;stopOnError=true;beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){let e=this._meta.fields?this._meta.fields:D(this.getModelSchema(),Z(this._meta.model));return z.object({items:z.array(e).min(1).max(this.maxBatchSize)})}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{201:{description:"Resources created successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({created:z.array(this.getModelSchema()),count:z.number()})})}}},207:{description:"Partial success (some items failed)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({created:z.array(this.getModelSchema()),count:z.number(),errors:z.array(z.object({index:z.number(),error:z.string()})).optional()})})}}},400:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getItems(){let{body:e}=await this.getValidatedData();return e?.items||[]}async before(e,t,o){return e}async after(e,t,o){return e}transform(e){return e}async handle(){let e=await this.getItems(),t=[],o=[];for(let a=0;a<e.length;a++)try{let c=await this.before(e[a],a);o.push(c);}catch(c){if(this.stopOnError)throw c;t.push({index:a,error:c instanceof Error?c.message:String(c)});}let r=await this.batchCreate(o),s=[];for(let a=0;a<r.length;a++)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(r[a],a))),s.push(r[a])):s.push(await this.after(r[a],a));}catch(c){if(this.stopOnError)throw c;t.push({index:a,error:c instanceof Error?c.message:String(c)}),s.push(r[a]);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),c=s.map(d=>{let m=this.getRecordId(d);return m===null?null:{recordId:m,record:d}}).filter(d=>d!==null);c.length>0&&this.runAfterResponse(a.logBatch("batch_create",this._meta.model.tableName,c,this.getAuditUserId()));}let u=(this._meta.model.serializer?s.map(a=>this._meta.model.serializer(a)):s).map(a=>this.transform(a)),l={success:true,result:{created:u,count:u.length,...t.length>0&&{errors:t}}},p=t.length>0?207:201;return this.json(l,p)}};var et=class extends S{maxBatchSize=100;stopOnError=false;lookupField="id";allowedUpdateFields;blockedUpdateFields;beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){let e=this._meta.fields?this._meta.fields:D(this.getModelSchema(),Z(this._meta.model));return z.object({items:z.array(z.object({id:z.string(),data:e.partial()})).min(1).max(this.maxBatchSize)})}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{200:{description:"Resources updated successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({updated:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional()})})}}},207:{description:"Partial success (some items failed or not found)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({updated:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional(),errors:z.array(z.object({id:z.string(),error:z.string()})).optional()})})}}},400:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getItems(){let{body:e}=await this.getValidatedData();return e?.items||[]}filterUpdateData(e){let t={...e};if(this.allowedUpdateFields){let o=new Set(this.allowedUpdateFields);t=Object.fromEntries(Object.entries(t).filter(([r])=>o.has(r)));}if(this.blockedUpdateFields)for(let o of this.blockedUpdateFields)delete t[o];for(let o of this._meta.model.primaryKeys)delete t[o];return t}async before(e,t,o){return t}async after(e,t){return e}async handle(){let e=await this.getItems(),t=[],o=[];for(let a of e)try{let c=this.filterUpdateData(a.data),d=await this.before(a.id,c);o.push({id:a.id,data:d});}catch(c){if(this.stopOnError)throw c;t.push({id:a.id,error:c instanceof Error?c.message:String(c)});}let{updated:r,notFound:s}=await this.batchUpdate(o),n=[];for(let a of r)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(a))),n.push(a)):n.push(await this.after(a));}catch(c){let d=String(a[this.lookupField]);if(this.stopOnError)throw c;t.push({id:d,error:c instanceof Error?c.message:String(c)}),n.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),c=n.map(d=>{let m=this.getRecordId(d);return m===null?null:{recordId:m,record:d}}).filter(d=>d!==null);c.length>0&&this.runAfterResponse(a.logBatch("batch_update",this._meta.model.tableName,c,this.getAuditUserId()));}let u=this._meta.model.serializer?n.map(a=>this._meta.model.serializer(a)):n,l={success:true,result:{updated:u,count:u.length,...s.length>0&&{notFound:s},...t.length>0&&{errors:t}}},p=t.length>0||s.length>0?207:200;return this.json(l,p)}};var tt=class extends S{maxBatchSize=100;stopOnError=false;lookupField="id";beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){return z.object({ids:z.array(z.string()).min(1).max(this.maxBatchSize)})}getSchema(){let e=this.isSoftDeleteEnabled();return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{200:{description:e?"Resources soft-deleted successfully":"Resources deleted successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({deleted:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional()})})}}},207:{description:"Partial success (some items failed or not found)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({deleted:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional(),errors:z.array(z.object({id:z.string(),error:z.string()})).optional()})})}}},400:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getIds(){let{body:e}=await this.getValidatedData();return e?.ids||[]}async before(e,t){}async after(e,t){return e}async handle(){let e=await this.getIds(),t=[],o=[];for(let a of e)try{await this.before(a),o.push(a);}catch(c){if(this.stopOnError)throw c;t.push({id:a,error:c instanceof Error?c.message:String(c)});}let{deleted:r,notFound:s}=await this.batchDelete(o),n=[];for(let a of r)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(a))),n.push(a)):n.push(await this.after(a));}catch(c){let d=String(a[this.lookupField]);if(this.stopOnError)throw c;t.push({id:d,error:c instanceof Error?c.message:String(c)}),n.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),c=n.map(d=>{let m=this.getRecordId(d);return m===null?null:{recordId:m,previousRecord:d}}).filter(d=>d!==null);c.length>0&&this.runAfterResponse(a.logBatch("batch_delete",this._meta.model.tableName,c,this.getAuditUserId()));}let u=this._meta.model.serializer?n.map(a=>this._meta.model.serializer(a)):n,l={success:true,result:{deleted:u,count:u.length,...s.length>0&&{notFound:s},...t.length>0&&{errors:t}}},p=t.length>0||s.length>0?207:200;return this.json(l,p)}};var ot=class extends S{maxBatchSize=100;stopOnError=false;lookupField="id";beforeHookMode="sequential";afterHookMode="sequential";getBodySchema(){return z.object({ids:z.array(z.string()).min(1).max(this.maxBatchSize)})}getSchema(){return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}}}},responses:{200:{description:"Resources restored successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({restored:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional()})})}}},207:{description:"Partial success (some items failed or not found)",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({restored:z.array(this.getModelSchema()),count:z.number(),notFound:z.array(z.string()).optional(),errors:z.array(z.object({id:z.string(),error:z.string()})).optional()})})}}},400:{description:"Soft delete not enabled or validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getIds(){let{body:e}=await this.getValidatedData();return e?.ids||[]}async before(e,t){}async after(e,t){return e}async handle(){if(!this.isSoftDeleteEnabled())throw new a$2("Soft delete is not enabled for this model",400,"SOFT_DELETE_NOT_ENABLED");let e=await this.getIds(),t=[],o=[];for(let a of e)try{await this.before(a),o.push(a);}catch(c){if(this.stopOnError)throw c;t.push({id:a,error:c instanceof Error?c.message:String(c)});}let{restored:r,notFound:s}=await this.batchRestore(o),n=[];for(let a of r)try{this.afterHookMode==="fire-and-forget"?(this.runAfterResponse(Promise.resolve(this.after(a))),n.push(a)):n.push(await this.after(a));}catch(c){let d=String(a[this.lookupField]);if(this.stopOnError)throw c;t.push({id:d,error:c instanceof Error?c.message:String(c)}),n.push(a);}if(this.isAuditEnabled()){let a=this.getAuditLogger(),c=n.map(d=>{let m=this.getRecordId(d);return m===null?null:{recordId:m,record:d}}).filter(d=>d!==null);c.length>0&&this.runAfterResponse(a.logBatch("batch_restore",this._meta.model.tableName,c,this.getAuditUserId()));}let u=this._meta.model.serializer?n.map(a=>this._meta.model.serializer(a)):n,l={success:true,result:{restored:u,count:u.length,...s.length>0&&{notFound:s},...t.length>0&&{errors:t}}},p=t.length>0||s.length>0?207:200;return this.json(l,p)}};var rt=class extends S{upsertKeys;createOnlyFields;updateOnlyFields;maxBatchSize=100;continueOnError=false;useNativeUpsert=false;beforeHookMode="sequential";afterHookMode="sequential";getUpsertKeys(){return this.upsertKeys||this._meta.model.primaryKeys}getItemSchema(){if(this._meta.fields)return this._meta.fields;let e=this.getUpsertKeys(),t=Z(this._meta.model,{includePrimaryKeys:false});for(let s of this._meta.model.primaryKeys)e.includes(s)||t.push(s);let o=D(this.getModelSchema(),t),r={};for(let[s,n]of Object.entries(o.shape))e.includes(s)?r[s]=n:r[s]=n.optional();return z.object(r)}getBodySchema(){return z.array(this.getItemSchema()).max(this.maxBatchSize)}getSchema(){let e=z.object({data:this.getModelSchema(),created:z.boolean(),index:z.number()});return {...this.schema,request:{body:{content:{"application/json":{schema:this.getBodySchema()}},required:true}},responses:{200:{description:"Batch upsert completed",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({items:z.array(e),createdCount:z.number(),updatedCount:z.number(),totalCount:z.number(),errors:z.array(z.object({index:z.number(),error:z.string()})).optional()})})}}},400:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}}}}}}async getItems(){let{body:e}=await this.getValidatedData();return e}async beforeItem(e,t,o,r){return e}async afterItem(e,t,o,r){return e}async beforeBatch(e,t){return e}async afterBatch(e,t){return e}async upsertOne(e,t,o){let r=await this.findExisting(e,o),s=!r,n=await this.beforeItem(e,t,s,o),u;if(r){if(this.createOnlyFields)for(let l of this.createOnlyFields)delete n[l];u=await this.update(r,n,o);}else {if(this.updateOnlyFields)for(let l of this.updateOnlyFields)delete n[l];u=await this.create(n,o);}return u=await this.afterItem(u,t,s,o),{data:u,created:s,index:t}}async nativeBatchUpsert(e,t){return b$4().warn("Native batch upsert not implemented for this adapter. Falling back to item-by-item pattern."),this.performStandardBatchUpsert(e,t)}async performStandardBatchUpsert(e,t){let o=[],r=[],s=0,n=0;for(let l=0;l<e.length;l++)try{let p=await this.upsertOne(e[l],l,t);o.push(p),p.created?s++:n++;}catch(p){if(this.continueOnError)r.push({index:l,error:p instanceof Error?p.message:String(p)});else throw p}let u={items:o,createdCount:s,updatedCount:n,totalCount:o.length};return r.length>0&&(u.errors=r),u}async batchUpsert(e,t){return this.useNativeUpsert?this.nativeBatchUpsert(e,t):this.performStandardBatchUpsert(e,t)}async handle(){let e=await this.getItems();e=await this.beforeBatch(e);let t=await this.batchUpsert(e);if(t=await this.afterBatch(t),this._meta.model.computedFields&&(t.items=await Promise.all(t.items.map(async o=>({...o,data:await j(o.data,this._meta.model.computedFields)})))),this.isAuditEnabled()){let o=this.getAuditLogger(),r=t.items.map(s=>{let n=this.getRecordId(s.data);return n===null?null:{recordId:n,record:s.data}}).filter(s=>s!==null);r.length>0&&this.runAfterResponse(o.logBatch("batch_upsert",this._meta.model.tableName,r,this.getAuditUserId()));}return this._meta.model.serializer&&(t.items=t.items.map(o=>({...o,data:this._meta.model.serializer(o.data)}))),this.success(t)}};var lt=z.object({id:z.string(),recordId:z.union([z.string(),z.number()]),version:z.number(),data:z.record(z.string(),z.unknown()),createdAt:z.date(),changedBy:z.string().optional(),changeReason:z.string().optional(),changes:z.array(z.object({field:z.string(),oldValue:z.unknown().optional(),newValue:z.unknown().optional()})).optional()}),st=class extends S{lookupField="id";defaultLimit=20;maxLimit=100;getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){return z.object({limit:z.coerce.number().min(1).max(this.maxLimit).optional(),offset:z.coerce.number().min(0).optional()})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),query:this.getQuerySchema()},responses:{200:{description:"Version history retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({versions:z.array(lt),totalVersions:z.number()})})}}},400:{description:"Versioning not enabled",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}},404:{description:"Record not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getPaginationOptions(){let{query:e}=await this.getValidatedData();return {limit:e?.limit?Number(e.limit):this.defaultLimit,offset:e?.offset?Number(e.offset):0}}async recordExists(e){return true}async handle(){if(!this.isVersioningEnabled())throw new a$2("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),{limit:t,offset:o}=await this.getPaginationOptions();if(!await this.recordExists(e))throw new c$1(this._meta.model.tableName,e);let s=this.getVersionManager(),n=await s.getVersions(e,{limit:t,offset:o}),u=await s.getLatestVersion(e);return this.success({versions:n,totalVersions:u})}},nt=class extends S{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string(),version:z.coerce.number().min(1)})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Version retrieved successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:lt})}}},400:{description:"Versioning not enabled",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}},404:{description:"Version not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getVersionNumber(){let{params:e}=await this.getValidatedData();return e?.version?Number(e.version):0}async handle(){if(!this.isVersioningEnabled())throw new a$2("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),t=await this.getVersionNumber(),r=await this.getVersionManager().getVersion(e,t);if(!r)throw new c$1(`version ${t}`,e);return this.success(r)}},it=class extends S{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string()})}getQuerySchema(){return z.object({from:z.coerce.number().min(1),to:z.coerce.number().min(1)})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema(),query:this.getQuerySchema()},responses:{200:{description:"Version comparison completed",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({from:z.number(),to:z.number(),changes:z.array(z.object({field:z.string(),oldValue:z.unknown().optional(),newValue:z.unknown().optional()}))})})}}},400:{description:"Versioning not enabled or invalid parameters",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}},404:{description:"Version not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getVersionNumbers(){let{query:e}=await this.getValidatedData();return {from:e?.from?Number(e.from):0,to:e?.to?Number(e.to):0}}async handle(){if(!this.isVersioningEnabled())throw new a$2("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),{from:t,to:o}=await this.getVersionNumbers(),s=await this.getVersionManager().compareVersions(e,t,o);return this.success({from:t,to:o,changes:s})}},at=class extends S{lookupField="id";getParamsSchema(){return z.object({[this.lookupField]:z.string(),version:z.coerce.number().min(1)})}getSchema(){return {...this.schema,request:{params:this.getParamsSchema()},responses:{200:{description:"Record rolled back successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:this.getModelSchema()})}}},400:{description:"Versioning not enabled",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}},404:{description:"Version not found",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string()})})}}}}}}async getLookupValue(){let{params:e}=await this.getValidatedData();return e?.[this.lookupField]||""}async getVersionNumber(){let{params:e}=await this.getValidatedData();return e?.version?Number(e.version):0}async handle(){if(!this.isVersioningEnabled())throw new a$2("Versioning is not enabled for this model",400,"VERSIONING_NOT_ENABLED");let e=await this.getLookupValue(),t=await this.getVersionNumber(),o=this.getVersionManager(),r=await o.getVersion(e,t);if(!r)throw new c$1(`version ${t}`,e);let n=await o.getLatestVersion(e)+1,u=await this.rollback(e,r.data,n),l=this._meta.model.serializer?this._meta.model.serializer(u):u;return this.success(l)}};var xt={sumFields:[],avgFields:[],minMaxFields:[],countDistinctFields:[],groupByFields:[],defaultLimit:100,maxLimit:1e3},dt=class extends S{aggregateConfig={};maxGroupByFields=5;filterFields=[];getAggregateConfig(){return {...xt,...this.aggregateConfig}}getQuerySchema(){return z.object({count:z.union([z.string(),z.array(z.string())]).optional(),sum:z.union([z.string(),z.array(z.string())]).optional(),avg:z.union([z.string(),z.array(z.string())]).optional(),min:z.union([z.string(),z.array(z.string())]).optional(),max:z.union([z.string(),z.array(z.string())]).optional(),countDistinct:z.union([z.string(),z.array(z.string())]).optional(),groupBy:z.string().optional(),orderBy:z.string().optional(),orderDirection:z.enum(["asc","desc"]).optional(),limit:z.coerce.number().optional(),offset:z.coerce.number().optional(),withDeleted:z.coerce.boolean().optional()}).passthrough()}getSchema(){let e=z.object({key:z.record(z.string(),z.unknown()),values:z.record(z.string(),z.number().nullable())});return {...this.schema,request:{query:this.getQuerySchema()},responses:{200:{description:"Aggregation result",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({values:z.record(z.string(),z.number().nullable()).optional(),groups:z.array(e).optional(),totalGroups:z.number().optional()})})}}},400:{description:"Invalid aggregation request",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}}}}}}async getAggregateOptions(){let{query:e}=await this.getValidatedData();return i$1(e||{})}validateAggregations(e){let t=this.getAggregateConfig();for(let o of e.aggregations)if(!(o.operation==="count"&&o.field==="*"))switch(o.operation){case "sum":if(t.sumFields.length>0&&!t.sumFields.includes(o.field))throw new Error(`Field '${o.field}' is not allowed for SUM aggregation`);break;case "avg":if(t.avgFields.length>0&&!t.avgFields.includes(o.field))throw new Error(`Field '${o.field}' is not allowed for AVG aggregation`);break;case "min":case "max":if(t.minMaxFields.length>0&&!t.minMaxFields.includes(o.field))throw new Error(`Field '${o.field}' is not allowed for MIN/MAX aggregation`);break;case "countDistinct":if(t.countDistinctFields.length>0&&!t.countDistinctFields.includes(o.field))throw new Error(`Field '${o.field}' is not allowed for COUNT DISTINCT aggregation`);break}if(e.groupBy){if(e.groupBy.length>this.maxGroupByFields)throw new b$3(`Maximum ${this.maxGroupByFields} GROUP BY fields allowed`);for(let o of e.groupBy)if(t.groupByFields.length>0&&!t.groupByFields.includes(o))throw new Error(`Field '${o}' is not allowed for GROUP BY`)}if(e.limit!==void 0&&e.limit>t.maxLimit)throw new Error(`Limit cannot exceed ${t.maxLimit}`)}getAggregateAlias(e){return e.alias?e.alias:e.field==="*"?e.operation:`${e.operation}${e.field.charAt(0).toUpperCase()}${e.field.slice(1)}`}async handle(){let e=await this.getAggregateOptions();e.aggregations.length===0&&e.aggregations.push({operation:"count",field:"*"}),this.validateAggregations(e);let t=this.getAggregateConfig();e.groupBy&&e.groupBy.length>0&&e.limit===void 0&&(e.limit=t.defaultLimit);let o=await this.aggregate(e);return this.success(o)}},Ft={eq:(i,e)=>i===e,ne:(i,e)=>i!==e,gt:(i,e)=>i>e,gte:(i,e)=>i>=e,lt:(i,e)=>i<e,lte:(i,e)=>i<=e};function Pt(i,e){let t=i.get(e);if(t)return t;let o=[];return i.set(e,o),o}function _r(i,e){let{aggregations:t,groupBy:o,having:r,orderBy:s,orderDirection:n,limit:u,offset:l}=e;if(!o||o.length===0){let d={};for(let m of t){let f=ut(m);d[f]=ct(i,m);}return {values:d}}let p=new Map;for(let d of i){let f=o.map(g=>String(d[g]??"null")).join("|");Pt(p,f).push(d);}let a=[];for(let[d,m]of p){let f=d.split("|"),g={};o.forEach((x,k)=>{g[x]=f[k]==="null"?null:f[k];});let j={};for(let x of t){let k=ut(x);j[k]=ct(m,x);}a.push({key:g,values:j});}r&&(a=a.filter(d=>{for(let[m,f]of Object.entries(r)){let g=d.values[m];if(g!==null)for(let[j,x]of Object.entries(f)){let k=Ft[j];if(k&&!k(g,Number(x)))return false}}return true}));let c=a.length;if(s){let d=n==="desc"?-1:1;a.sort((m,f)=>{if(s in m.values){let g=m.values[s]??0,j=f.values[s]??0;return (g-j)*d}if(s in m.key){let g=String(m.key[s]??""),j=String(f.key[s]??"");return g.localeCompare(j)*d}return 0});}if(l!==void 0||u!==void 0){let d=l||0,m=u?d+u:void 0;a=a.slice(d,m);}return {groups:a,totalGroups:c}}function we(i,e){return i.map(t=>t[e]).filter(t=>typeof t=="number")}var It={count:(i,e)=>e==="*"?i.length:i.filter(t=>t[e]!==null&&t[e]!==void 0).length,countDistinct:(i,e)=>new Set(i.map(o=>o[e]).filter(o=>o!=null).map(o=>String(o))).size,sum:(i,e)=>{let t=0;for(let o of i){let r=o[e];typeof r=="number"&&(t+=r);}return t},avg:(i,e)=>{let t=we(i,e);return t.length===0?null:t.reduce((r,s)=>r+s,0)/t.length},min:(i,e)=>{let t=we(i,e);return t.length===0?null:Math.min(...t)},max:(i,e)=>{let t=we(i,e);return t.length===0?null:Math.max(...t)}};function ct(i,e){if(i.length===0)return e.operation==="count"?0:null;let t=It[e.operation];return t?t(i,e.field):null}function ut(i){return i.alias?i.alias:i.field==="*"?i.operation:`${i.operation}${i.field.charAt(0).toUpperCase()}${i.field.slice(1)}`}var Et=new Set(["a","an","and","are","as","at","be","by","for","from","has","he","in","is","it","its","of","on","or","that","the","to","was","were","will","with"]);function mt(i,e=true){if(!i||typeof i!="string")return [];let t=i.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(Boolean);return e?t.filter(o=>!Et.has(o)&&o.length>1):t}function ht(i,e){return e==="phrase"?[i.toLowerCase().trim()]:mt(i)}function vt(i,e){return e.length===0?0:e.filter(o=>o===i||o.includes(i)).length/e.length}function gt(i,e,t,o){if(e.length===0)return {score:0,matchedFields:[]};let r=0,s=0,n=[];for(let[l,p]of Object.entries(t)){let a=i[l];if(a==null)continue;let c=p.weight??1;s+=c;let d;p.type==="array"&&Array.isArray(a)?d=a.join(" "):d=String(a);let m=mt(d,false),f=d.toLowerCase(),g=0,j=0;if(o==="phrase"){let x=e[0];f.includes(x)&&(g=1,j=1);}else {for(let x of e){let k=vt(x,m);k>0?(j++,g+=k):f.includes(x)&&(j++,g+=.5/e.length);}e.length>0&&(g=g/e.length);}o==="all"&&j<e.length&&(g=0),g>0&&(n.push(l),r+=g*c);}return {score:s>0?Math.min(1,r/s):0,matchedFields:n}}function ft(i,e,t,o="mark",r=150){if(i==null)return [];let s;if(Array.isArray(i)?s=i.join(" "):s=String(i),!s||e.length===0)return [];let n=[],u=s.toLowerCase();if(t==="phrase"){let l=e[0],p=u.indexOf(l);if(p!==-1){let a=pt(s,p,l.length,r,o);a&&n.push(a);}}else {let l=[];for(let a of e){let c=0;for(;c<u.length;){let d=u.indexOf(a,c);if(d===-1)break;l.push({start:d,length:a.length}),c=d+1;}}l.sort((a,c)=>a.start-c.start);let p=new Set;for(let a of l){if(Array.from(p).some(m=>Math.abs(m-a.start)<r))continue;let d=pt(s,a.start,a.length,r,o);if(d&&(n.push(d),p.add(a.start)),n.length>=3)break}}return n}function pt(i,e,t,o,r){let s=Math.floor(o/2),n=Math.max(0,e-s),u=Math.min(i.length,e+t+s);if(n>0){let a=i.indexOf(" ",n);a!==-1&&a<e&&(n=a+1);}if(u<i.length){let a=i.lastIndexOf(" ",u);a!==-1&&a>e+t&&(u=a);}let l=i.slice(n,u);return n>0&&(l="..."+l),u<i.length&&(l=l+"..."),Ct(l,[i.slice(e,e+t)],r)}function Ct(i,e,t){let o=i,r=i.toLowerCase(),s=[...e].sort((n,u)=>u.length-n.length);for(let n of s){let u=n.toLowerCase(),l=0,p="",a=0;for(;a<r.length;){let c=r.indexOf(u,a);if(c===-1)break;p+=o.slice(l,c),p+=`<${t}>${o.slice(c,c+n.length)}</${t}>`,l=c+n.length,a=l;}p&&(p+=o.slice(l),o=p);}return o}function bt(i,e){if(!i)return Object.keys(e);let t=i.split(",").map(r=>r.trim()).filter(Boolean),o=Object.keys(e);return t.filter(r=>o.includes(r))}function wt(i,e){let t={};for(let o of i)t[o]={weight:e?.[o]??1};return t}var yt=class extends S{searchableFields={};searchFields=[];fieldWeights={};defaultMode="any";minQueryLength=2;maxQueryLength=500;highlightTag="mark";snippetLength=150;defaultMinScore=0;filterFields=[];filterConfig;sortFields=[];defaultSort;defaultPerPage=20;maxPerPage=100;allowedIncludes=[];fieldSelectionEnabled=false;allowedSelectFields=[];blockedSelectFields=[];alwaysIncludeFields=[];defaultSelectFields=[];getSearchableFields(){if(Object.keys(this.searchableFields).length>0)return this.searchableFields;if(this.searchFields.length>0)return wt(this.searchFields,this.fieldWeights);let e=this.getModelSchema().shape,t={};for(let[o,r]of Object.entries(e))r._def?.typeName==="ZodString"&&(t[o]={weight:1});return t}getQuerySchema(){let e={q:z.string().min(this.minQueryLength).max(this.maxQueryLength).describe("Search query"),fields:z.string().optional().describe(`Comma-separated fields to search. Available: ${Object.keys(this.getSearchableFields()).join(", ")}`),mode:z.enum(["any","all","phrase"]).optional().describe("Search mode: any (OR), all (AND), phrase (exact)"),highlight:z.enum(["true","false"]).optional().describe("Include highlighted snippets"),minScore:z.string().optional().describe("Minimum relevance score threshold (0-1)"),page:z.string().optional(),per_page:z.string().optional()};this.sortFields.length>0&&(e.sort=z.enum(this.sortFields).optional().describe("Field to sort by"),e.order=z.enum(["asc","desc"]).optional().describe("Sort direction (asc or desc)"));for(let o of this.filterFields)e[o]=z.string().optional();if(this.filterConfig)for(let[o,r]of Object.entries(this.filterConfig)){for(let s of r)e[`${o}[${s}]`]=z.string().optional();e[o]=z.string().optional();}let t=this.getSoftDeleteConfig();if(t.enabled&&t.allowQueryDeleted&&(e[t.queryParam]=z.enum(["true","false"]).optional(),e.onlyDeleted=z.enum(["true","false"]).optional()),this.allowedIncludes.length>0&&(e.include=z.string().optional().describe(`Comma-separated list of relations to include. Allowed: ${this.allowedIncludes.join(", ")}`)),this.fieldSelectionEnabled){let o=this.getAvailableSelectFields();e.fields=z.string().optional().describe(`Comma-separated list of fields to return. Available: ${o.join(", ")}`);}return z.object(e)}getAvailableSelectFields(){let e=Object.keys(this.getModelSchema().shape),t=this._meta.model.computedFields?Object.keys(this._meta.model.computedFields):[],o=this._meta.model.relations?Object.keys(this._meta.model.relations):[],r=[...e,...t,...o];return this.allowedSelectFields.length>0&&(r=r.filter(s=>this.allowedSelectFields.includes(s))),this.blockedSelectFields.length>0&&(r=r.filter(s=>!this.blockedSelectFields.includes(s))),r}getSchema(){let e=z.object({item:this.getModelSchema(),score:z.number().min(0).max(1),highlights:z.record(z.string(),z.array(z.string())).optional(),matchedFields:z.array(z.string())});return {...this.schema,request:{query:this.getQuerySchema()},responses:{200:{description:"Search results",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.array(e),result_info:z.object({page:z.number(),per_page:z.number(),total_count:z.number().optional(),total_pages:z.number().optional(),query:z.string(),searchedFields:z.array(z.string())})})}}},400:{description:"Invalid search request",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}}}}}}async getSearchOptions(){let{query:e}=await this.getValidatedData(),t=e?.q,o=e?.fields,r$1=r(e?.mode),s=e?.highlight==="true",n=e?.minScore?Math.max(0,Math.min(1,parseFloat(e.minScore)||0)):this.defaultMinScore,u=this.getSearchableFields(),l=bt(o,u);return {query:t,fields:l.length>0?l:Object.keys(u),mode:r$1??this.defaultMode,highlight:s,minScore:n}}async getFilters(){let{query:e}=await this.getValidatedData(),t=this.getSoftDeleteConfig(),o={filterFields:this.filterFields,filterConfig:this.filterConfig,searchFields:[],searchFieldName:"q",sortFields:this.sortFields,defaultSort:this.defaultSort,defaultPerPage:this.defaultPerPage,maxPerPage:this.maxPerPage,softDeleteQueryParam:t.queryParam,allowedIncludes:this.allowedIncludes,fieldSelectionEnabled:this.fieldSelectionEnabled,allowedSelectFields:this.allowedSelectFields,blockedSelectFields:this.blockedSelectFields,alwaysIncludeFields:this.alwaysIncludeFields,defaultSelectFields:this.defaultSelectFields};return le(e||{},o)}async beforeSearch(e){return e}async afterSearch(e){return e}async handle(){let e=await this.getSearchOptions(),t=await this.getFilters();if(!e.query||e.query.length<this.minQueryLength)return this.json({success:false,error:{code:"INVALID_QUERY",message:`Search query must be at least ${this.minQueryLength} characters`}},400);e=await this.beforeSearch(e);let o=await this.search(e,t),r=await this.afterSearch(o.items);if(this._meta.model.computedFields){let p=r.map(c=>c.item),a=await k(p,this._meta.model.computedFields);r=r.map((c,d)=>({...c,item:a[d]}));}this._meta.model.serializer&&(r=r.map(p=>({...p,item:this._meta.model.serializer(p.item)})));let s=r;this.fieldSelectionEnabled&&t.options.fields&&t.options.fields.length>0&&(s=r.map(p=>({...p,item:de([p.item],{fields:t.options.fields,isActive:true})[0]})));let n=t.options.page||1,u=t.options.per_page||this.defaultPerPage,l=Math.ceil(o.totalCount/u);return this.successPaginated(s,{page:n,per_page:u,total_count:o.totalCount,total_pages:l,query:e.query,searchedFields:e.fields||Object.keys(this.getSearchableFields())})}};function Ur(i,e,t){let o=ht(e.query,e.mode),r={},s=e.fields||Object.keys(t);for(let u of s)t[u]&&(r[u]=t[u]);let n=[];for(let u of i){let{score:l,matchedFields:p}=gt(u,o,r,e.mode);if(l<e.minScore||p.length===0)continue;let a;if(e.highlight){a={};for(let c of p){let d=ft(u[c],o,e.mode);d.length>0&&(a[c]=d);}}n.push({item:u,score:l,highlights:a&&Object.keys(a).length>0?a:void 0,matchedFields:p});}return n.sort((u,l)=>l.score-u.score),n}function G(i,e={}){let{delimiter:t=",",nullValue:o="",dateFormat:r="iso"}=e;if(i==null)return o;if(i instanceof Date)switch(r){case "timestamp":return String(i.getTime());case "locale":return i.toLocaleString();default:return i.toISOString()}if(typeof i=="object")return G(JSON.stringify(i),e);if(typeof i=="boolean")return i?"true":"false";let s=String(i),n=s.charAt(0);return n==="="||n==="+"||n==="-"||n==="@"||n===" "||n==="\r"?`" ${s.replace(/"/g,'""')}"`:s.includes(t)||s.includes('"')||s.includes(`
|
|
2
|
+
`)||s.includes("\r")?`"${s.replace(/"/g,'""')}"`:s}function ye(i,e={}){let{delimiter:t=",",rowDelimiter:o=`\r
|
|
3
|
+
`,includeHeader:r=true,formatters:s={},excludeFields:n=[],headerLabels:u={},nullValue:l="",dateFormat:p="iso"}=e;if(i.length===0)return "";let a=e.headers;a?a=a.filter(d=>!n.includes(d)):a=Object.keys(i[0]).filter(d=>!n.includes(d));let c=[];if(r){let d=a.map(m=>{let f=u[m]||m;return G(f,{delimiter:t,nullValue:l,dateFormat:p})});c.push(d.join(t));}for(let d of i){let m=a.map(f=>{let g=d[f];return s[f]&&(g=s[f](g)),G(g,{delimiter:t,nullValue:l,dateFormat:p})});c.push(m.join(t));}return c.join(o)}function Hr(i,e={}){let{delimiter:t=",",rowDelimiter:o=`\r
|
|
4
|
+
`,includeHeader:r=true,formatters:s={},excludeFields:n=[],headerLabels:u={},nullValue:l="",dateFormat:p="iso"}=e,a=new TextEncoder,c=0,d=false,m=e.headers;return !m&&i.length>0?m=Object.keys(i[0]).filter(f=>!n.includes(f)):m?m=m.filter(f=>!n.includes(f)):m=[],new ReadableStream({pull(f){if(r&&!d&&m.length>0){let x=m.map(k=>{let y=u[k]||k;return G(y,{delimiter:t,nullValue:l,dateFormat:p})});f.enqueue(a.encode(x.join(t)+o)),d=true;return}let g=100,j=[];for(;c<i.length&&j.length<g;){let x=i[c],k=m.map(y=>{let F=x[y];return s[y]&&(F=s[y](F)),G(F,{delimiter:t,nullValue:l,dateFormat:p})});j.push(k.join(t)),c++;}j.length>0&&f.enqueue(a.encode(j.join(o)+o)),c>=i.length&&f.close();}})}function Mt(i,e){let t=[],o="",r=false,s=0;for(;s<i.length;){let n=i[s];if(r){if(n==='"'){if(s+1<i.length&&i[s+1]==='"'){o+='"',s+=2;continue}r=false,s++;continue}o+=n,s++;}else {if(n==='"'){r=true,s++;continue}if(n===e){t.push(o),o="",s++;continue}o+=n,s++;}}return t.push(o),t}function At(i){let e=[],t="",o=false;for(let r=0;r<i.length;r++){let s=i[r];if(s==='"'){if(o&&r+1<i.length&&i[r+1]==='"'){t+='""',r++;continue}o=!o,t+=s;continue}if(!o&&(s===`
|
|
5
|
+
`||s==="\r")){s==="\r"&&r+1<i.length&&i[r+1]===`
|
|
6
|
+
`&&r++,t.length>0&&(e.push(t),t="");continue}t+=s;}return t.length>0&&e.push(t),e}function Me(i,e={}){let{delimiter:t=",",hasHeader:o=true,trimValues:r=true,skipEmptyRows:s=true,parsers:n={},emptyValue:u="empty"}=e,l={data:[],headers:[],errors:[]},p=At(i);if(p.length===0)return l;let a=0;if(o){let d=p[0];l.headers=Mt(d,t).map(m=>r?m.trim():m),a=1;}else e.headers&&(l.headers=e.headers);let c=e.headers||l.headers;for(let d=a;d<p.length;d++){let m=p[d],f=d+1;if(!(s&&m.trim()===""))try{let g=Mt(m,t),j={};for(let x=0;x<c.length;x++){let k=c[x],y=x<g.length?g[x]:"";if(r&&typeof y=="string"&&(y=y.trim()),y==="")switch(u){case "null":y=null;break;case "undefined":y=void 0;break}if(n[k]&&typeof y=="string")try{y=n[k](y);}catch(F){l.errors.push({row:f,message:`Failed to parse field "${k}": ${F instanceof Error?F.message:String(F)}`,content:m});}j[k]=y;}l.data.push(j);}catch(g){l.errors.push({row:f,message:`Failed to parse row: ${g instanceof Error?g.message:String(g)}`,content:m});}}return l}function jt(i,e,t={}){let{allowUnknownFields:o=false,optionalFields:r=[]}=t,s=e.shape,n=Object.keys(s),l=n.filter(d=>r.includes(d)?false:!s[d].isOptional()).filter(d=>!i.includes(d)),p=i.filter(d=>!n.includes(d)),a=i.filter(d=>n.includes(d));return {valid:l.length===0&&(o||p.length===0),missingFields:l,unknownFields:p,validFields:a}}function $r(i,e){if(i){let t=i.toLowerCase().split(".").pop();if(t==="csv")return "csv";if(t==="json")return "json"}if(e){let t=e.trim();if(t.startsWith("[")||t.startsWith("{"))return "json";if(t.includes(",")||t.includes(`
|
|
7
|
+
`))return "csv"}return "unknown"}function Kr(i,e={}){return ye(i,e)}function Wr(i,e={}){return Me(i,e).data}var St=class extends ce{maxExportRecords=1e4;enableStreaming=true;streamPageSize=500;excludedExportFields=[];defaultFormat="json";csvOptions={};exportFilename;getExportQuerySchema(){return this.getQuerySchema().extend({format:z.enum(["json","csv"]).optional().describe("Export format"),stream:z.enum(["true","false"]).optional().describe("Enable streaming for large exports")})}getSchema(){return {...this.schema,request:{query:this.getExportQuerySchema()},responses:{200:{description:"Export successful",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({data:z.array(this.getModelSchema()),count:z.number(),format:z.enum(["json","csv"]),exportedAt:z.string()})})},"text/csv":{schema:z.string()}}}}}}async getExportOptions(){let{query:e}=await this.getValidatedData(),t=e?.format||this.defaultFormat,o=e?.stream==="true"&&this.enableStreaming;return {format:t,stream:o,fields:e?.fields?String(e.fields).split(","):void 0}}getExportFilename(e){let o=(this.exportFilename||this._meta.model.tableName).replace(/[^a-zA-Z0-9_-]/g,"_"),r=new Date().toISOString().replace(/[:.]/g,"-");return `${o}-export-${r}.${e}`}prepareRecordsForExport(e){return this.excludedExportFields.length===0?e:e.map(t=>{let o={};for(let[r,s]of Object.entries(t))this.excludedExportFields.includes(r)||(o[r]=s);return o})}exportAsJson(e,t){let o={data:e,count:e.length,format:t,exportedAt:new Date().toISOString()};return new Response(JSON.stringify({success:true,result:o},null,2),{status:200,headers:{"Content-Type":"application/json","Content-Disposition":`attachment; filename="${this.getExportFilename(t)}"`}})}exportAsCsv(e,t){let o=ye(e,{...this.csvOptions,excludeFields:this.excludedExportFields});return new Response(o,{status:200,headers:{"Content-Type":"text/csv; charset=utf-8","Content-Disposition":`attachment; filename="${this.getExportFilename(t)}"`}})}exportAsCsvStream(e,t){let o=this.getContext(),r=this.getExportFilename(t),s=this.csvOptions,n=this.excludedExportFields;return stream(o,async u=>{if(o.header("Content-Type","text/csv; charset=utf-8"),o.header("Content-Disposition",`attachment; filename="${r}"`),e.length===0)return;let l=Object.keys(e[0]).filter(c=>!n.includes(c)),p=l.map(c=>G(c,s)).join(",")+`
|
|
8
|
+
`;await u.write(p);let a=100;for(let c=0;c<e.length;c+=a)for(let d of e.slice(c,c+a)){let m=l.map(f=>G(d[f],s)).join(",")+`
|
|
9
|
+
`;await u.write(m);}})}exportAsCsvStreamPaginated(e,t){let o=this.getExportFilename(t),r=this.streamPageSize,s=Math.min(this.maxExportRecords,1e5),n=this.excludedExportFields,u=this.csvOptions,l=null,p=new ReadableStream({start:async a=>{let c=new TextEncoder,d=1,m=0;try{for(;m<s;){let f={...e,options:{...e.options,page:d,per_page:r}},j=(await this.list(f)).result;if(j.length===0)break;j.length>s-m&&(j=j.slice(0,s-m)),j=await this.after(j),j=await this.beforeExport(j);let x=this.prepareRecordsForExport(j);if(!l&&x.length>0){l=Object.keys(x[0]).filter(y=>!n.includes(y));let k=l.map(y=>G(y,u)).join(",")+`
|
|
10
|
+
`;a.enqueue(c.encode(k));}if(l)for(let k of x){let y=l.map(F=>G(k[F],u)).join(",")+`
|
|
11
|
+
`;a.enqueue(c.encode(y));}if(m+=j.length,d++,j.length<r)break}}catch(f){a.error(f);return}a.close();}});return new Response(p,{status:200,headers:{"Content-Type":"text/csv; charset=utf-8","Content-Disposition":`attachment; filename="${o}"`}})}async beforeExport(e){return e}async fetchAllForExport(e){let t=Math.min(this.maxExportRecords,1e5),o={...e,options:{...e.options,page:1,per_page:t}};return (await this.list(o)).result}async handle(){let e=await this.getExportOptions(),t=await this.getFilters();if(e.format==="csv"&&e.stream)return this.exportAsCsvStreamPaginated(t,e.format);let o=await this.fetchAllForExport(t);o=await this.after(o),o=await this.beforeExport(o);let r=this.prepareRecordsForExport(o);return e.format==="csv"?this.exportAsCsv(r,e.format):this.exportAsJson(r,e.format)}};var Ot=class extends S{maxBatchSize=1e3;importBatchSize=100;stopOnError=false;skipInvalidRows=true;defaultMode="create";upsertKeys;immutableFields=[];csvOptions={};maxBodySize=10*1024*1024;optionalImportFields=[];getUpsertKeys(){return this.upsertKeys||this._meta.model.primaryKeys}getImportSchema(){let e=this._meta.fields?this._meta.fields:D(this.getModelSchema(),Z(this._meta.model));return z.object({items:z.array(e.partial()).min(1).max(this.maxBatchSize)})}getSchema(){return {...this.schema,request:{query:z.object({mode:z.enum(["create","upsert"]).optional().describe("Import mode"),skipInvalid:z.enum(["true","false"]).optional().describe("Skip invalid rows"),stopOnError:z.enum(["true","false"]).optional().describe("Stop on first error")})},responses:{200:{description:"Import completed successfully",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({summary:z.object({total:z.number(),created:z.number(),updated:z.number(),skipped:z.number(),failed:z.number()}),results:z.array(z.object({rowNumber:z.number(),status:z.enum(["created","updated","skipped","failed"]),data:z.unknown().optional(),error:z.string().optional(),validationErrors:z.array(z.object({path:z.string(),message:z.string()})).optional()}))})})}}},207:{description:"Import completed with partial failures",content:{"application/json":{schema:z.object({success:z.literal(true),result:z.object({summary:z.object({total:z.number(),created:z.number(),updated:z.number(),skipped:z.number(),failed:z.number()}),results:z.array(z.object({rowNumber:z.number(),status:z.enum(["created","updated","skipped","failed"]),data:z.unknown().optional(),error:z.string().optional(),validationErrors:z.array(z.object({path:z.string(),message:z.string()})).optional()}))})})}}},400:{description:"Validation error",content:{"application/json":{schema:z.object({success:z.literal(false),error:z.object({code:z.string(),message:z.string(),details:z.unknown().optional()})})}}}}}}async getImportOptions(){let{query:e}=await this.getValidatedData(),t=e?.skipInvalid==="true"?true:e?.skipInvalid==="false"?false:this.skipInvalidRows,o=e?.stopOnError==="true"?true:e?.stopOnError==="false"?false:this.stopOnError;return {mode:e?.mode||this.defaultMode,skipInvalidRows:t,stopOnError:o}}async parseImportData(){let e=this.context;if(!e)throw new b$3("No request available");let t=e.req.header("content-type")||"";if(t.includes("application/json")){let o=await e.req.json();if(!o)throw new b$3("Request body is empty");if(!o.items||!Array.isArray(o.items))throw new b$3('Request body must contain an "items" array');if(o.items.length>this.maxBatchSize)throw new b$3(`Maximum ${this.maxBatchSize} items allowed per import`);return o.items}if(t.includes("text/csv")){let o=await e.req.text();if(o.length>this.maxBodySize)throw new b$3(`Request body exceeds maximum size of ${this.maxBodySize} bytes`);return this.parseCsvData(o)}if(t.includes("multipart/form-data")){let r=(await e.req.formData()).get("file");if(!r)throw new b$3("No file provided in form data");let s=await r.text();if(s.length>this.maxBodySize)throw new b$3(`Uploaded file exceeds maximum size of ${this.maxBodySize} bytes`);let n=r.name.toLowerCase();if(n.endsWith(".json")){let l;try{l=JSON.parse(s);}catch{throw new b$3("Invalid JSON content in uploaded file")}let p=Array.isArray(l)?l:l.items;if(!p||!Array.isArray(p))throw new b$3('JSON file must contain an array or an object with "items" array');if(p.length>this.maxBatchSize)throw new b$3(`Maximum ${this.maxBatchSize} items allowed per import`);return p}if(n.endsWith(".csv"))return this.parseCsvData(s);let u=s.trim();if(u.startsWith("[")||u.startsWith("{")){let l;try{l=JSON.parse(s);}catch{throw new b$3("Invalid JSON content in uploaded file")}let p=Array.isArray(l)?l:l.items;if(!p||!Array.isArray(p))throw new b$3('JSON file must contain an array or an object with "items" array');return p}return this.parseCsvData(s)}throw new b$3("Unsupported content type. Use application/json, text/csv, or multipart/form-data")}parseCsvData(e){let t=Me(e,this.csvOptions);if(t.errors.length>0)throw new b$3(`CSV parsing errors: ${t.errors.map(s=>`Row ${s.row}: ${s.message}`).join("; ")}`);if(t.data.length===0)throw new b$3("CSV file is empty");if(t.data.length>this.maxBatchSize)throw new b$3(`Maximum ${this.maxBatchSize} items allowed per import`);let o=this._meta.fields||this.getModelSchema(),r=jt(t.headers,o,{allowUnknownFields:true,optionalFields:this.optionalImportFields});if(!r.valid&&r.missingFields.length>0)throw new b$3(`Missing required fields in CSV: ${r.missingFields.join(", ")}`);return t.data}validateRow(e,t){let o=this._meta.fields||this.getModelSchema(),r={};for(let n of Z(this._meta.model))r[n]=true;for(let n of this.optionalImportFields)r[n]=true;let s=o.partial(r);try{return s.parse(e),{valid:!0}}catch(n){return n instanceof z.ZodError?{valid:false,errors:n.issues.map(l=>({path:l.path.join("."),message:l.message}))}:{valid:false,errors:[{path:"",message:n instanceof Error?n.message:String(n)}]}}}removeImmutableFields(e){if(this.immutableFields.length===0)return e;let t={};for(let[o,r]of Object.entries(e))this.immutableFields.includes(o)||(t[o]=r);return t}async before(e,t,o,r){return e}async after(e,t,o,r){return e}async processRow(e,t,o,r){let s=this.validateRow(e,t);if(!s.valid)return o.skipInvalidRows?{rowNumber:t,status:"skipped",error:"Validation failed",validationErrors:s.errors}:{rowNumber:t,status:"failed",error:"Validation failed",validationErrors:s.errors};try{let n=await this.before(e,t,o.mode,r);if(o.mode==="upsert"){let l=await this.findExisting(n,r);if(l){let p=this.removeImmutableFields(n),a=await this.update(l,p,r);return {rowNumber:t,status:"updated",data:a}}}else if(await this.findExisting(n,r))return o.skipInvalidRows?{rowNumber:t,status:"skipped",error:"Record already exists"}:{rowNumber:t,status:"failed",error:"Record already exists (duplicate key)"};let u=await this.create(n,r);return {rowNumber:t,status:"created",data:u}}catch(n){return {rowNumber:t,status:"failed",error:n instanceof Error?n.message:String(n)}}}async handle(){let e=await this.getImportOptions(),t=await this.parseImportData();if(!Number.isInteger(this.importBatchSize)||this.importBatchSize<1)throw new i("importBatchSize must be a positive integer");let o={total:t.length,created:0,updated:0,skipped:0,failed:0},r=[],s=false,n=e.stopOnError?1:this.importBatchSize;for(let p=0;p<t.length&&!s;p+=n){let a=t.slice(p,p+n),c=await Promise.all(a.map(async(d,m)=>{let f=p+m+1,g=await this.processRow(d,f,e);return g=await this.after(g,f,e.mode),g}));for(let d of c){switch(r.push(d),d.status){case "created":o.created++;break;case "updated":o.updated++;break;case "skipped":o.skipped++;break;case "failed":o.failed++;break}if(e.stopOnError&&d.status==="failed"){s=true;break}}}if(this.isAuditEnabled()){let p=this.getAuditLogger(),a=r.filter(c=>c.status==="created"||c.status==="updated");if(a.length>0){let c=a.map(d=>{if(!d.data)return null;let m=this.getRecordId(d.data);return m===null?null:{recordId:m,record:d.data}}).filter(d=>d!==null);c.length>0&&this.runAfterResponse(p.logBatch(e.mode==="upsert"?"batch_upsert":"batch_create",this._meta.model.tableName,c,this.getAuditUserId()));}}let u={summary:o,results:r},l=o.failed>0&&o.failed<o.total?207:200;return this.json({success:true,result:u},l)}};export{St as $,et as A,tt as B,ot as C,rt as D,st as E,nt as F,it as G,at as H,dt as I,_r as J,mt as K,ht as L,vt as M,gt as N,ft as O,bt as P,wt as Q,yt as R,Ur as S,G as T,ye as U,Hr as V,Me as W,jt as X,$r as Y,Kr as Z,Wr as _,ne as a,Ot as aa,Z as b,Ze as c,De as d,ze as e,Le as f,qe as g,oe as h,ge as i,fe as j,S as k,zt as l,le as m,D as n,Lt as o,be as p,de as q,$e as r,Ke as s,We as t,Qe as u,ce as v,Ge as w,Je as x,Ye as y,Xe as z};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {d}from'./chunk-
|
|
1
|
+
import {d}from'./chunk-3DJMHE6N.js';var m=class{entriesById=new Map;entryIds=[];maxEntries;maxAge;cleanupInterval;lastCleanup=0;constructor(e){this.maxEntries=e?.maxEntries??1e4,this.maxAge=e?.maxAge??864e5,this.cleanupInterval=e?.cleanupInterval??3e5;}maybeCleanup(){if(this.cleanupInterval<=0||this.maxAge<=0)return;let e=Date.now();e-this.lastCleanup>=this.cleanupInterval&&(this.lastCleanup=e,this.deleteOlderThanSync(this.maxAge));}deleteOlderThanSync(e){let n=Date.now()-e,a=0;for(let t=this.entryIds.length-1;t>=0;t--){let s=this.entryIds[t],r=this.entriesById.get(s);if(r)if(new Date(r.timestamp).getTime()<n)this.entriesById.delete(s),this.entryIds.splice(t,1),a++;else break}return a}async store(e){for(this.maybeCleanup();this.entryIds.length>=this.maxEntries;){let n=this.entryIds.pop();n&&this.entriesById.delete(n);}this.entriesById.set(e.id,e),this.entryIds.unshift(e.id);}async query(e){this.maybeCleanup();let n=this.getFilteredEntries(e);if(e?.sort){let{field:s,direction:r}=e.sort;n=n.sort((i,o)=>{let g,u;switch(s){case "timestamp":g=new Date(i.timestamp).getTime(),u=new Date(o.timestamp).getTime();break;case "responseTimeMs":g=i.response.responseTimeMs,u=o.response.responseTimeMs;break;case "statusCode":g=i.response.statusCode,u=o.response.statusCode;break;default:return 0}return r==="asc"?g-u:u-g});}let a=e?.offset??0,t=e?.limit??n.length;return n.slice(a,a+t)}async getById(e){return this.entriesById.get(e)??null}async count(e){return this.getFilteredEntries(e).length}async deleteOlderThan(e){return this.deleteOlderThanSync(e)}async clear(){let e=this.entriesById.size;return this.entriesById.clear(),this.entryIds=[],e}destroy(){this.entriesById.clear(),this.entryIds=[];}getSize(){return this.entriesById.size}getFilteredEntries(e){if(!e)return Array.from(this.entriesById.values());let n=[];for(let a of this.entryIds){let t=this.entriesById.get(a);if(t&&!(e.level&&!(Array.isArray(e.level)?e.level:[e.level]).includes(t.level))&&!(e.method&&!(Array.isArray(e.method)?e.method:[e.method]).map(r=>r.toUpperCase()).includes(t.request.method.toUpperCase()))&&!(e.path&&!d(t.request.path,e.path))){if(e.statusCode){let{min:s,max:r}=e.statusCode,i=t.response.statusCode;if(s!==void 0&&i<s||r!==void 0&&i>r)continue}if(e.timeRange){let s=new Date(t.timestamp).getTime(),{start:r,end:i}=e.timeRange;if(r){let o=typeof r=="string"?new Date(r).getTime():r.getTime();if(s<o)continue}if(i){let o=typeof i=="string"?new Date(i).getTime():i.getTime();if(s>o)continue}}e.userId&&t.request.userId!==e.userId||e.clientIp&&t.request.clientIp!==e.clientIp||e.requestId&&t.id!==e.requestId||e.errorMessage&&(!t.error?.message||!t.error.message.toLowerCase().includes(e.errorMessage.toLowerCase()))||n.push(t);}}return n}};export{m as a};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import {r,s,t,u,v as v$1,x,z as z$2,A as A$1,B as B$1,C,y,D,E,F as F$1,G as G$1,H as H$1,I as I$1,J as J$1,R,S as S$1,$,aa,w}from'./chunk-CTK2CYX2.js';import {b}from'./chunk-DMGP7QDL.js';import {getTableColumns,eq,inArray,between,isNull,isNotNull,ilike,like,notInArray,lte,lt as lt$1,gte,gt as gt$1,ne,and,sql,or,desc,asc}from'drizzle-orm';import {z as z$1}from'zod';function q(l){return l}function h(l){if(!l.model.table)throw new Error(`Model ${l.model.tableName} does not have a table reference`);return l.model.table}function m(l,e){let 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 ve(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=m(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=m(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=m(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 se(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 ve(l,t,r,s));}return t}async function v(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",c=[...new Set(t.map(p=>p[a]).filter(p=>p!=null))];if(c.length===0){t=t.map(p=>({...p,[r]:s.type==="hasMany"?[]:null}));continue}let u=m(i,s.foreignKey),d=await l.select().from(i).where(inArray(u,c)),g=new Map;for(let p of d){let b=p[s.foreignKey];g.has(b)||g.set(b,[]),g.get(b).push(p);}t=t.map(p=>{let b=p[a],D=g.get(b)||[];return {...p,[r]:s.type==="hasMany"?D:D[0]||null}});break}case "belongsTo":{let a=s.localKey||"id",c=[...new Set(t.map(p=>p[s.foreignKey]).filter(p=>p!=null))];if(c.length===0){t=t.map(p=>({...p,[r]:null}));continue}let u=m(i,a),d=await l.select().from(i).where(inArray(u,c)),g=new Map;for(let p of d){let b=p[a];g.set(b,p);}t=t.map(p=>{let b=p[s.foreignKey];return {...p,[r]:g.get(b)||null}});break}}}return t}function k(l,e){let n=m(l,e.field);switch(e.operator){case "eq":return eq(n,e.value);case "ne":return ne(n,e.value);case "gt":return gt$1(n,e.value);case "gte":return gte(n,e.value);case "lt":return lt$1(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 z(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 S=class extends r{db;useTransaction=false;getDb(){return z(this)}getTable(){return h(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().warn(`Related table not found for ${n}. Add 'table' to the relation config.`),[];let a=Array.isArray(t)?t:[t],c=[];for(let u of a){if(typeof u!="object"||u===null)continue;let d={...u,id:crypto.randomUUID(),[o.foreignKey]:e},g=await s.insert(i).values(d).returning();g[0]&&c.push(g[0]);}return c}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},_=class extends s{db;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(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,d]of Object.entries(n))i.push(eq(this.getColumn(u),d));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 se(this.getDb(),a[0],this._meta,o):null}},I=class extends t{db;useTransaction=false;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(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,d]of Object.entries(n))a.push(eq(this.getColumn(u),d));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(),c=[eq(i,e)];if(o)for(let[d,g]of Object.entries(o))c.push(eq(this.getColumn(d),g));return a.enabled&&c.push(isNull(this.getColumn(a.field))),(await r.update(s).set(this.applyManagedUpdateFields(n)).where(and(...c)).returning())[0]||null}async processNestedWrites(e,n,o,t,r){let s=r??this.getDb(),i=this.getRelatedTable(o);if(!i)return b().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:[]},c=m(i,o.foreignKey),u=m(i,"id");if(t.create){let d=Array.isArray(t.create)?t.create:[t.create];for(let g of d){if(typeof g!="object"||g===null)continue;let p={...g,id:crypto.randomUUID(),[o.foreignKey]:e},b=await s.insert(i).values(p).returning();b[0]&&a.created.push(b[0]);}}if(t.update)for(let d of t.update){if(!d.id||!(await s.select().from(i).where(and(eq(u,d.id),eq(c,e))).limit(1))[0])continue;let{id:p,...b}=d,D=await s.update(i).set(b).where(eq(u,p)).returning();D[0]&&a.updated.push(D[0]);}if(t.delete)for(let d of t.delete)(await s.delete(i).where(and(eq(u,d),eq(c,e))).returning())[0]&&a.deleted.push(d);if(t.connect)for(let d of t.connect)(await s.update(i).set({[o.foreignKey]:e}).where(eq(u,d)).returning())[0]&&a.connected.push(d);if(t.disconnect)for(let d of t.disconnect)(await s.update(i).set({[o.foreignKey]:null}).where(and(eq(u,d),eq(c,e))).returning())[0]&&a.disconnected.push(d);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()}},P=class extends u{db;useTransaction=false;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(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,d]of Object.entries(n))a.push(eq(this.getColumn(u),d));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[c,u]of Object.entries(n))a.push(eq(this.getColumn(c),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=m(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=m(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=m(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()}},U=class extends v$1{db;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(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=k(n,y);R&&o.push(R);}if(e.options.search&&this.searchFields.length>0){let y=this.searchFields.map(R=>{let ne=this.getColumn(R);return sql`LOWER(${ne}) 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,c=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;c=c.orderBy(R(y));}let u=e.options.page||1,d=e.options.per_page||this.defaultPerPage;c=c.limit(d).offset((u-1)*d);let g=await c,p={relations:e.options.include||[]},b=await v(this.getDb(),g,this._meta,p),D=Math.ceil(a/d);return {result:b,result_info:{page:u,per_page:d,total_count:a,total_pages:D,has_next_page:u<D,has_prev_page:u>1}}}},B=class extends x{db;useTransaction=false;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(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,d]of Object.entries(n))a.push(eq(this.getColumn(u),d));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 A=class extends z$2{db;getDb(){return z(this)}getTable(){return h(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()}},L=class extends A$1{db;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(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 c=await this.getDb().update(n).set(this.applyManagedUpdateFields(i.data)).where(and(...a)).returning();c[0]?r.push(c[0]):s.push(i.id);}return {updated:r,notFound:s}}},K=class extends B$1{db;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(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]))),c=e.filter(u=>!a.has(u));return {deleted:i,notFound:c}}},Z=class extends C{db;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(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]))),c=e.filter(u=>!a.has(u));return {restored:i,notFound:c}}};var Q=class extends y{db;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(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"),c={};for(let[g,p]of Object.entries(e))!t.includes(g)&&g!==r&&(this.createOnlyFields?.includes(g)||(c[g]=p));i.enabled&&(c[i.updatedAt]=Date.now());let u=t.map(g=>this.getColumn(g)),d;s.enabled&&(d=isNull(this.getColumn(s.field)));try{return {data:(await this.getDb().insert(o).values(a).onConflictDoUpdate({target:u,set:Object.keys(c).length>0?c:{[r]:sql`${this.getColumn(r)}`},where:d}).returning())[0],created:!1}}catch(g){if(g instanceof Error&&g.message.includes("onConflictDoUpdate"))try{return {data:(await this.getDb().insert(o).values(a).onDuplicateKeyUpdate({set:Object.keys(c).length>0?c:{[r]:sql`${this.getColumn(r)}`}}).returning())[0],created:!1}}catch{return this.performStandardUpsert(e,n)}throw g}}},F=class extends D{db;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(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(d=>this.applyManagedInsertFields(d,"drizzle")),a={},c=e[0];for(let d of Object.keys(c))!t.includes(d)&&d!==r&&(this.createOnlyFields?.includes(d)||(a[d]=sql`excluded.${sql.identifier(d)}`));s.enabled&&(a[s.updatedAt]=Date.now());let u=t.map(d=>this.getColumn(d));try{let g=await this.getDb().insert(o).values(i).onConflictDoUpdate({target:u,set:Object.keys(a).length>0?a:{[r]:sql`${this.getColumn(r)}`}}).returning();return {items:g.map((p,b)=>({data:p,created:!1,index:b})),createdCount:0,updatedCount:g.length,totalCount:g.length}}catch(d){if(d instanceof Error&&d.message.includes("onConflictDoUpdate"))try{let p=await this.getDb().insert(o).values(i).onDuplicateKeyUpdate({set:Object.keys(a).length>0?a:{[r]:sql`${this.getColumn(r)}`}}).returning();return {items:p.map((b,D)=>({data:b,created:!1,index:D})),createdCount:0,updatedCount:p.length,totalCount:p.length}}catch{return this.performStandardBatchUpsert(e,n)}throw d}}},Ie=class extends E{db;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(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}},Pe=class extends F$1{},Ue=class extends G$1{},Be=class extends H$1{db;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(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]}},V=class extends I$1{db;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(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[c,u]of Object.entries(a)){let d=k(n,{field:i,operator:c,value:u});d&&o.push(d);}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 J$1(s,e)}},X=class extends R{db;getDb(){return z(this)}useNativeSearch=false;vectorColumn;vectorConfig="english";getTable(){return h(this._meta)}getColumn(e){return m(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 C of n.filters){let w=k(o,C);w&&t.push(w);}let s=this.getSearchableFields(),i=e.fields||Object.keys(s);if(this.useNativeSearch&&this.vectorColumn){let C=this.getColumn(this.vectorColumn),w=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`${C} @@ ${w}`);}else {let C=i.map(w=>{try{let Ne=this.getColumn(w);return sql`LOWER(CAST(${Ne} AS TEXT)) LIKE LOWER(${`%${e.query}%`})`}catch{return}}).filter(w=>w!==void 0);C.length>0&&(e.mode==="all"?t.push(and(...C)):t.push(or(...C)));}let a=t.length>0?and(...t):void 0,c=await this.getDb().select({count:sql`count(*)`}).from(o).where(a),u=Number(c[0]?.count)||0,d=this.getDb().select().from(o).where(a);if(n.options.order_by){let C=this.getColumn(n.options.order_by),w=n.options.order_by_direction==="desc"?desc:asc;d=d.orderBy(w(C));}let g=n.options.page||1,p=n.options.per_page||this.defaultPerPage;d=d.limit(p).offset((g-1)*p);let b=await d,D=S$1(b,e,s),y={relations:n.options.include||[]},R=D.map(C=>C.item),ne=await v(this.getDb(),R,this._meta,y);return {items:D.map((C,w)=>({...C,item:ne[w]})),totalCount:u}}},G=class extends ${db;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(this.getTable(),e)}async list(e){let n=this.getTable(),o=[],t=this.getSoftDeleteConfig();if(t.enabled){let D=this.getColumn(t.field);e.options.onlyDeleted?o.push(isNotNull(D)):e.options.withDeleted||o.push(isNull(D));}for(let D of e.filters){let y=k(n,D);y&&o.push(y);}if(e.options.search&&this.searchFields.length>0){let D=this.searchFields.map(y=>{let R=this.getColumn(y);return sql`LOWER(${R}) LIKE LOWER(${`%${e.options.search}%`})`});o.push(or(...D));}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 D=this.getColumn(e.options.order_by),y=e.options.order_by_direction==="desc"?desc:asc;a=a.orderBy(y(D));}let c=e.options.page||1,u=e.options.per_page||this.defaultPerPage;a=a.limit(u).offset((c-1)*u);let d=await a,g={relations:e.options.include||[]},p=await v(this.getDb(),d,this._meta,g),b=Math.ceil(i/u);return {result:p,result_info:{page:c,per_page:u,total_count:i,total_pages:b,has_next_page:c<b,has_prev_page:c>1}}}},H=class extends aa{db;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(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]}},J=class extends w{db;getDb(){return z(this)}getTable(){return h(this._meta)}getColumn(e){return m(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,c]of Object.entries(n))s.push(eq(this.getColumn(a),c));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 en(l,e){return {Create:class extends S{_meta=e;db=l},Read:class extends _{_meta=e;db=l},Update:class extends I{_meta=e;db=l},Delete:class extends P{_meta=e;db=l},List:class extends U{_meta=e;db=l},Restore:class extends B{_meta=e;db=l},Upsert:class extends Q{_meta=e;db=l},BatchCreate:class extends A{_meta=e;db=l},BatchUpdate:class extends L{_meta=e;db=l},BatchDelete:class extends K{_meta=e;db=l},BatchRestore:class extends Z{_meta=e;db=l},BatchUpsert:class extends F{_meta=e;db=l}}}var ee=null,Qe=false,Y=null;async function te(){if(Qe){if(Y)throw Y;return ee}Qe=true;try{return ee=await import('drizzle-zod'),ee}catch{throw Y=new Error("drizzle-zod is not installed. Please install it: npm install drizzle-zod"),Y}}async function lt(l,e){return (await te()).createSelectSchema(l,e)}async function dt(l,e){return (await te()).createInsertSchema(l,e)}async function ct(l,e){let n=await te();return n.createUpdateSchema?n.createUpdateSchema(l,e):n.createInsertSchema(l,e).partial()}async function ut(l,e){let n=await te(),o=e?.coerceDates!==false,t=o?bt(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=Fe(s,t),i=Fe(i,t)),{select:r,insert:s,update:i}}function pt(){return ee!==null}var gt=z$1.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$1.date()),mt=z$1.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$1.date().nullable());function bt(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,c=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")||c.includes("timestamp")||c.includes("date"))&&e.add(o);}return e}function Fe(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=gt;(i||s)&&(a=mt),s&&(a=a.optional()),o[t]=a;}else o[t]=r;return z$1.object(o)}var yn={CreateEndpoint:S,ListEndpoint:U,ReadEndpoint:_,UpdateEndpoint:I,DeleteEndpoint:P,RestoreEndpoint:B,BatchCreateEndpoint:A,BatchUpdateEndpoint:L,BatchDeleteEndpoint:K,BatchRestoreEndpoint:Z,BatchUpsertEndpoint:F,SearchEndpoint:X,AggregateEndpoint:V,ExportEndpoint:G,ImportEndpoint:H,UpsertEndpoint:Q,CloneEndpoint:J};export{H as A,J as B,en as C,lt as D,dt as E,ct as F,ut as G,pt as H,yn as I,q as a,h as b,m as c,ve as d,se as e,v as f,k as g,S as h,_ as i,I as j,P as k,U as l,B as m,A as n,L as o,K as p,Z as q,Q as r,F as s,Ie as t,Pe as u,Ue as v,Be as w,V as x,X as y,G as z};
|