hono-crud 0.13.0 → 0.13.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 +59 -5
- package/dist/adapters/drizzle/index.js +1 -1
- package/dist/adapters/memory/index.js +1 -1
- package/dist/adapters/prisma/index.js +1 -1
- package/dist/cache/index.js +1 -1
- package/dist/chunk-HRAGVQWS.js +4 -0
- package/dist/{chunk-UANCAA7V.js → chunk-IPMPKM4J.js} +1 -1
- package/dist/{chunk-3UHTK7SB.js → chunk-PCPU5A2Q.js} +1 -1
- package/dist/{chunk-BXWKFJXP.js → chunk-UU7V63VS.js} +1 -1
- package/dist/{chunk-ZBCVLQ3W.js → chunk-V4YEHNEZ.js} +1 -1
- package/dist/{chunk-FOTF3T22.js → chunk-ZAVXHUKP.js} +1 -1
- package/dist/index.js +1 -1
- package/dist/logging/index.js +1 -1
- package/dist/rate-limit/index.js +1 -1
- package/dist/storage/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-WXIFQDJI.js +0 -4
package/CHANGELOG.md
CHANGED
|
@@ -15,6 +15,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
15
15
|
%b
|
|
16
16
|
%b
|
|
17
17
|
%b
|
|
18
|
+
%b
|
|
19
|
+
%b
|
|
18
20
|
## [0.8.0] — 2026-05-03
|
|
19
21
|
|
|
20
22
|
### Added
|
|
@@ -95,3 +97,5 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
95
97
|
[0.12.4]: https://github.com/kshdotdev/hono-crud/compare/v0.12.3...v0.12.4
|
|
96
98
|
[0.12.5]: https://github.com/kshdotdev/hono-crud/compare/v0.12.4...v0.12.5
|
|
97
99
|
[0.13.0]: https://github.com/kshdotdev/hono-crud/compare/v0.12.5...v0.13.0
|
|
100
|
+
[0.13.1]: https://github.com/kshdotdev/hono-crud/compare/v0.13.0...v0.13.1
|
|
101
|
+
[0.13.2]: https://github.com/kshdotdev/hono-crud/compare/v0.13.1...v0.13.2
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Table, SQL, Column } from 'drizzle-orm';
|
|
2
2
|
import { M as MetaInput, I as IncludeOptions, n as FilterCondition, h as RelationConfig, N as NestedUpdateInput, i as NestedWriteResult, L as ListFilters, P as PaginatedResult, j as AggregateOptions, k as AggregateResult, S as SearchOptions, l as SearchResult } from '../../types-Dfi9RdjS.js';
|
|
3
3
|
import { Env } from 'hono';
|
|
4
|
-
import { a as CreateEndpoint, M as ModelObject, R as ReadEndpoint, U as UpdateEndpoint, D as DeleteEndpoint, L as ListEndpoint, b as RestoreEndpoint, B as BatchCreateEndpoint, c as BatchDeleteEndpoint, d as BatchRestoreEndpoint, e as BatchUpdateEndpoint, f as BatchUpdateItem, A as AggregateEndpoint, g as BatchUpsertEndpoint, h as CloneEndpoint, i as UpsertEndpoint,
|
|
4
|
+
import { a as CreateEndpoint, M as ModelObject, R as ReadEndpoint, U as UpdateEndpoint, D as DeleteEndpoint, L as ListEndpoint, b as RestoreEndpoint, B as BatchCreateEndpoint, c as BatchDeleteEndpoint, d as BatchRestoreEndpoint, e as BatchUpdateEndpoint, f as BatchUpdateItem, A as AggregateEndpoint, g as BatchUpsertEndpoint, h as CloneEndpoint, i as UpsertEndpoint, S as SearchEndpoint, E as ExportEndpoint, I as ImportEndpoint, V as VersionCompareEndpoint, j as VersionHistoryEndpoint, k as VersionReadEndpoint, l as VersionRollbackEndpoint } from '../../import-Gx0ZUJjI.js';
|
|
5
5
|
import { z } from 'zod';
|
|
6
6
|
import { A as AdapterBundle } from '../../index-B1QEfh5v.js';
|
|
7
7
|
import '../../types-B5wq2iKZ.js';
|
|
@@ -346,6 +346,20 @@ declare abstract class DrizzleDeleteEndpoint<E extends Env = Env, M extends Meta
|
|
|
346
346
|
declare abstract class DrizzleListEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends ListEndpoint<E, M> {
|
|
347
347
|
/** Drizzle database instance */
|
|
348
348
|
db?: DrizzleDatabase;
|
|
349
|
+
/**
|
|
350
|
+
* SQL dialect of the underlying Drizzle database.
|
|
351
|
+
*
|
|
352
|
+
* Drives the substring-match function emitted on the `?search=` path:
|
|
353
|
+
* `INSTR` for sqlite, `POSITION` for pg, `LOCATE` for mysql — matching
|
|
354
|
+
* how the dedicated search endpoint (`DrizzleSearchEndpoint`) and the
|
|
355
|
+
* export endpoint (`DrizzleExportEndpoint`) emit search SQL. Set via
|
|
356
|
+
* {@link createDrizzleCrud}'s `options.dialect`, or override in your
|
|
357
|
+
* subclass. Defaults to `'sqlite'` for backward compatibility with
|
|
358
|
+
* pre-existing portable behavior.
|
|
359
|
+
*
|
|
360
|
+
* See {@link DrizzleUpsertEndpoint.dialect} for full semantics.
|
|
361
|
+
*/
|
|
362
|
+
protected dialect: DrizzleDialect;
|
|
349
363
|
/** Gets the database instance from property or context */
|
|
350
364
|
protected getDb(): DrizzleDatabase;
|
|
351
365
|
protected getTable(): Table;
|
|
@@ -448,6 +462,26 @@ declare abstract class DrizzleBatchRestoreEndpoint<E extends Env = Env, M extend
|
|
|
448
462
|
}>;
|
|
449
463
|
}
|
|
450
464
|
|
|
465
|
+
/**
|
|
466
|
+
* Emit a dialect-correct case-insensitive substring-match SQL expression.
|
|
467
|
+
*
|
|
468
|
+
* Replaces the previous `LOWER(col) LIKE LOWER('%needle%') ESCAPE '\\'`
|
|
469
|
+
* approach: by using the native substring-position function for each
|
|
470
|
+
* dialect, the needle is never injected into a pattern, so LIKE
|
|
471
|
+
* wildcards (`%`, `_`) and the LIKE escape character lose their
|
|
472
|
+
* special meaning entirely — no wildcard surface means no escape
|
|
473
|
+
* needed.
|
|
474
|
+
*
|
|
475
|
+
* Dialect mapping:
|
|
476
|
+
* - `'sqlite'` → `INSTR(LOWER(col), LOWER(needle)) > 0`
|
|
477
|
+
* - `'pg'` → `POSITION(LOWER(needle) IN LOWER(col)) > 0`
|
|
478
|
+
* - `'mysql'` → `LOCATE(LOWER(needle), LOWER(col)) > 0`
|
|
479
|
+
*
|
|
480
|
+
* All three return a 1-based position (or 0 for "not found"), so
|
|
481
|
+
* `> 0` is the dialect-agnostic predicate that means "needle is a
|
|
482
|
+
* substring of col".
|
|
483
|
+
*/
|
|
484
|
+
declare function substringMatch(col: Column | SQL, needle: string, dialect: DrizzleDialect): SQL;
|
|
451
485
|
/**
|
|
452
486
|
* Drizzle Upsert endpoint.
|
|
453
487
|
* Creates a record if it doesn't exist, updates it if it does.
|
|
@@ -582,11 +616,12 @@ declare abstract class DrizzleAggregateEndpoint<E extends Env = Env, M extends M
|
|
|
582
616
|
* Provides full-text search with relevance scoring and highlighting.
|
|
583
617
|
*
|
|
584
618
|
* For PostgreSQL, this can leverage native tsvector/tsquery for better performance.
|
|
585
|
-
* For SQLite/MySQL, it falls back to
|
|
619
|
+
* For SQLite/MySQL/PostgreSQL non-vector mode, it falls back to dialect-native
|
|
620
|
+
* substring-position search (INSTR/POSITION/LOCATE) with in-memory scoring.
|
|
586
621
|
*
|
|
587
622
|
* Features:
|
|
588
623
|
* - PostgreSQL: Uses to_tsvector() and plainto_tsquery() for native full-text search
|
|
589
|
-
* -
|
|
624
|
+
* - Fallback: dialect-native substring match with in-memory scoring
|
|
590
625
|
* - Configurable field weights
|
|
591
626
|
* - Search modes: 'any' (OR), 'all' (AND), 'phrase' (exact)
|
|
592
627
|
* - Highlighted snippets
|
|
@@ -608,12 +643,24 @@ declare abstract class DrizzleAggregateEndpoint<E extends Env = Env, M extends M
|
|
|
608
643
|
declare abstract class DrizzleSearchEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends SearchEndpoint<E, M> {
|
|
609
644
|
/** Drizzle database instance. Can be undefined if using context injection. */
|
|
610
645
|
db?: DrizzleDatabase;
|
|
646
|
+
/**
|
|
647
|
+
* SQL dialect of the underlying Drizzle database.
|
|
648
|
+
*
|
|
649
|
+
* Drives the substring-match function emitted on the fallback search path:
|
|
650
|
+
* `INSTR` for sqlite, `POSITION` for pg, `LOCATE` for mysql. Set via
|
|
651
|
+
* {@link createDrizzleCrud}'s `options.dialect`, or override in your
|
|
652
|
+
* subclass. Defaults to `'sqlite'` for backward compatibility with
|
|
653
|
+
* pre-existing portable behavior.
|
|
654
|
+
*
|
|
655
|
+
* See {@link DrizzleUpsertEndpoint.dialect} for full semantics.
|
|
656
|
+
*/
|
|
657
|
+
protected dialect: DrizzleDialect;
|
|
611
658
|
/** Gets the database instance from property or context. */
|
|
612
659
|
protected getDb(): DrizzleDatabase;
|
|
613
660
|
/**
|
|
614
661
|
* Enable PostgreSQL native full-text search.
|
|
615
662
|
* When true and vectorColumn is set, uses tsvector/tsquery.
|
|
616
|
-
* When false, uses
|
|
663
|
+
* When false, uses substring-position-based search with in-memory scoring.
|
|
617
664
|
*/
|
|
618
665
|
protected useNativeSearch: boolean;
|
|
619
666
|
/**
|
|
@@ -639,6 +686,12 @@ declare abstract class DrizzleSearchEndpoint<E extends Env = Env, M extends Meta
|
|
|
639
686
|
declare abstract class DrizzleExportEndpoint<E extends Env = Env, M extends MetaInput = MetaInput> extends ExportEndpoint<E, M> {
|
|
640
687
|
/** Drizzle database instance. Can be undefined if using context injection. */
|
|
641
688
|
db?: DrizzleDatabase;
|
|
689
|
+
/**
|
|
690
|
+
* SQL dialect of the underlying Drizzle database. Drives the
|
|
691
|
+
* substring-match function emitted on the `?search=` path. See
|
|
692
|
+
* {@link DrizzleUpsertEndpoint.dialect} for full semantics.
|
|
693
|
+
*/
|
|
694
|
+
protected dialect: DrizzleDialect;
|
|
642
695
|
/** Gets the database instance from property or context. */
|
|
643
696
|
protected getDb(): DrizzleDatabase;
|
|
644
697
|
protected getTable(): Table;
|
|
@@ -716,6 +769,7 @@ interface DrizzleCrudClasses<M extends MetaInput, E extends Env = Env> {
|
|
|
716
769
|
List: ConfiguredDrizzleEndpoint<DrizzleListEndpoint<E, M>, M>;
|
|
717
770
|
Restore: ConfiguredDrizzleEndpoint<DrizzleRestoreEndpoint<E, M>, M>;
|
|
718
771
|
Upsert: ConfiguredDrizzleEndpoint<DrizzleUpsertEndpoint<E, M>, M>;
|
|
772
|
+
Search: ConfiguredDrizzleEndpoint<DrizzleSearchEndpoint<E, M>, M>;
|
|
719
773
|
BatchCreate: ConfiguredDrizzleEndpoint<DrizzleBatchCreateEndpoint<E, M>, M>;
|
|
720
774
|
BatchUpdate: ConfiguredDrizzleEndpoint<DrizzleBatchUpdateEndpoint<E, M>, M>;
|
|
721
775
|
BatchDelete: ConfiguredDrizzleEndpoint<DrizzleBatchDeleteEndpoint<E, M>, M>;
|
|
@@ -947,4 +1001,4 @@ declare function isDrizzleZodAvailable(): boolean;
|
|
|
947
1001
|
*/
|
|
948
1002
|
declare const DrizzleAdapters: AdapterBundle;
|
|
949
1003
|
|
|
950
|
-
export { type CreateDrizzleCrudOptions, type Database, DrizzleAdapters, DrizzleAggregateEndpoint, DrizzleBatchCreateEndpoint, DrizzleBatchDeleteEndpoint, DrizzleBatchRestoreEndpoint, DrizzleBatchUpdateEndpoint, DrizzleBatchUpsertEndpoint, DrizzleCloneEndpoint, DrizzleCreateEndpoint, type DrizzleCrudClasses, type DrizzleDB, type DrizzleDatabase, type DrizzleDatabaseConstraint, DrizzleDeleteEndpoint, type DrizzleDialect, type DrizzleEnv, DrizzleExportEndpoint, DrizzleImportEndpoint, DrizzleListEndpoint, DrizzleReadEndpoint, DrizzleRestoreEndpoint, type DrizzleSchemas, DrizzleSearchEndpoint, DrizzleUpdateEndpoint, DrizzleUpsertEndpoint, DrizzleVersionCompareEndpoint, DrizzleVersionHistoryEndpoint, DrizzleVersionReadEndpoint, DrizzleVersionRollbackEndpoint, type QueryBuilder, batchLoadDrizzleRelations, buildWhereCondition, cast, createDrizzleCrud, createDrizzleSchemas, createInsertSchema, createSelectSchema, createUpdateSchema, getColumn, getTable, isDrizzleZodAvailable, loadDrizzleRelation, loadDrizzleRelations };
|
|
1004
|
+
export { type CreateDrizzleCrudOptions, type Database, DrizzleAdapters, DrizzleAggregateEndpoint, DrizzleBatchCreateEndpoint, DrizzleBatchDeleteEndpoint, DrizzleBatchRestoreEndpoint, DrizzleBatchUpdateEndpoint, DrizzleBatchUpsertEndpoint, DrizzleCloneEndpoint, DrizzleCreateEndpoint, type DrizzleCrudClasses, type DrizzleDB, type DrizzleDatabase, type DrizzleDatabaseConstraint, DrizzleDeleteEndpoint, type DrizzleDialect, type DrizzleEnv, DrizzleExportEndpoint, DrizzleImportEndpoint, DrizzleListEndpoint, DrizzleReadEndpoint, DrizzleRestoreEndpoint, type DrizzleSchemas, DrizzleSearchEndpoint, DrizzleUpdateEndpoint, DrizzleUpsertEndpoint, DrizzleVersionCompareEndpoint, DrizzleVersionHistoryEndpoint, DrizzleVersionReadEndpoint, DrizzleVersionRollbackEndpoint, type QueryBuilder, batchLoadDrizzleRelations, buildWhereCondition, cast, createDrizzleCrud, createDrizzleSchemas, createInsertSchema, createSelectSchema, createUpdateSchema, getColumn, getTable, isDrizzleZodAvailable, loadDrizzleRelation, loadDrizzleRelations, substringMatch };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{
|
|
1
|
+
export{J as DrizzleAdapters,o as DrizzleAggregateEndpoint,z as DrizzleBatchCreateEndpoint,B as DrizzleBatchDeleteEndpoint,C as DrizzleBatchRestoreEndpoint,A as DrizzleBatchUpdateEndpoint,j as DrizzleBatchUpsertEndpoint,s as DrizzleCloneEndpoint,t as DrizzleCreateEndpoint,w as DrizzleDeleteEndpoint,q as DrizzleExportEndpoint,r as DrizzleImportEndpoint,x as DrizzleListEndpoint,u as DrizzleReadEndpoint,y as DrizzleRestoreEndpoint,p as DrizzleSearchEndpoint,v as DrizzleUpdateEndpoint,i as DrizzleUpsertEndpoint,m as DrizzleVersionCompareEndpoint,k as DrizzleVersionHistoryEndpoint,l as DrizzleVersionReadEndpoint,n as DrizzleVersionRollbackEndpoint,f as batchLoadDrizzleRelations,g as buildWhereCondition,a as cast,D as createDrizzleCrud,H as createDrizzleSchemas,F as createInsertSchema,E as createSelectSchema,G as createUpdateSchema,c as getColumn,b as getTable,I as isDrizzleZodAvailable,d as loadDrizzleRelation,e as loadDrizzleRelations,h as substringMatch}from'../../chunk-HRAGVQWS.js';import'../../chunk-V4YEHNEZ.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-XI7HT5ZM.js';import'../../chunk-NGUMNUOP.js';import'../../chunk-FJCWFB5L.js';import'../../chunk-FC56WWPB.js';import'../../chunk-KUFOENSK.js';import'../../chunk-GBQQ3YQX.js';import'../../chunk-QRXEQTNE.js';import'../../chunk-QXFY6NYI.js';import'../../chunk-DMGP7QDL.js';import'../../chunk-MDHMZPXK.js';import'../../chunk-VJRDAVID.js';
|
|
@@ -1 +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-UU7V63VS.js';import'../../chunk-V4YEHNEZ.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-XI7HT5ZM.js';import'../../chunk-NGUMNUOP.js';import'../../chunk-FJCWFB5L.js';import'../../chunk-FC56WWPB.js';import'../../chunk-KUFOENSK.js';import'../../chunk-GBQQ3YQX.js';import'../../chunk-QRXEQTNE.js';import'../../chunk-QXFY6NYI.js';import'../../chunk-DMGP7QDL.js';import'../../chunk-MDHMZPXK.js';import'../../chunk-VJRDAVID.js';
|
|
@@ -1 +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-ZAVXHUKP.js';import'../../chunk-V4YEHNEZ.js';import'../../chunk-SDNXN7M5.js';import'../../chunk-XI7HT5ZM.js';import'../../chunk-NGUMNUOP.js';import'../../chunk-FJCWFB5L.js';import'../../chunk-FC56WWPB.js';import'../../chunk-KUFOENSK.js';import'../../chunk-GBQQ3YQX.js';import'../../chunk-QRXEQTNE.js';import'../../chunk-QXFY6NYI.js';import'../../chunk-DMGP7QDL.js';import'../../chunk-MDHMZPXK.js';import'../../chunk-VJRDAVID.js';
|
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-IPMPKM4J.js';import'../chunk-NGUMNUOP.js';import'../chunk-GF2EC5G4.js';import'../chunk-FJCWFB5L.js';import'../chunk-2M5BM4VD.js';import'../chunk-FC56WWPB.js';import'../chunk-KUFOENSK.js';import'../chunk-GBQQ3YQX.js';import'../chunk-DMGP7QDL.js';import'../chunk-MDHMZPXK.js';import'../chunk-VJRDAVID.js';
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import {A as A$1,F as F$1,G as G$1,H as H$1,I as I$1,J as J$1,K as K$1,L as L$1,T,U as U$1,ba,ca,y,t,u,v,w,x,z as z$1,B as B$1,C,D as D$1,E}from'./chunk-V4YEHNEZ.js';import {b as b$1}from'./chunk-DMGP7QDL.js';import {getTableColumns,eq,inArray,between,isNull,isNotNull,ilike,like,notInArray,lte,lt as lt$1,gte,gt,ne as ne$1,sql,and,or,desc,asc}from'drizzle-orm';import {z}from'zod';function X(a){return a}function f(a){if(!a.model.table)throw new Error(`Model ${a.model.tableName} does not have a table reference`);return a.model.table}function b(a,e){let t=getTableColumns(a),o=t[e];if(!o)throw new Error(`Column '${e}' not found in table. Available columns: ${Object.keys(t).join(", ")}`);return o}async function Ue(a,e,t,o){if(!o.table)return e;let n=o.table;switch(o.type){case "hasOne":{let r=o.localKey||"id",s=e[r];if(s==null)return e;let i=b(n,o.foreignKey),l=await a.select().from(n).where(eq(i,s)).limit(1);return {...e,[t]:l[0]||null}}case "hasMany":{let r=o.localKey||"id",s=e[r];if(s==null)return {...e,[t]:[]};let i=b(n,o.foreignKey),l=await a.select().from(n).where(eq(i,s));return {...e,[t]:l}}case "belongsTo":{let r=e[o.foreignKey];if(r==null)return {...e,[t]:null};let s=b(n,o.localKey||"id"),i=await a.select().from(n).where(eq(s,r)).limit(1);return {...e,[t]:i[0]||null}}default:return e}}async function ce(a,e,t,o){if(!o?.relations?.length||!t.model.relations)return e;let n={...e};for(let r of o.relations){let s=t.model.relations[r];s&&(n=await Ue(a,n,r,s));}return n}async function S(a,e,t,o){if(!e.length||!o?.relations?.length||!t.model.relations)return e;let n=e.map(r=>({...r}));for(let r of o.relations){let s=t.model.relations[r];if(!s||!s.table)continue;let i=s.table;switch(s.type){case "hasOne":case "hasMany":{let l=s.localKey||"id",d=[...new Set(n.map(p=>p[l]).filter(p=>p!=null))];if(d.length===0){n=n.map(p=>({...p,[r]:s.type==="hasMany"?[]:null}));continue}let u=b(i,s.foreignKey),c=await a.select().from(i).where(inArray(u,d)),m=new Map;for(let p of c){let g=p[s.foreignKey];m.has(g)||m.set(g,[]),m.get(g).push(p);}n=n.map(p=>{let g=p[l],h=m.get(g)||[];return {...p,[r]:s.type==="hasMany"?h:h[0]||null}});break}case "belongsTo":{let l=s.localKey||"id",d=[...new Set(n.map(p=>p[s.foreignKey]).filter(p=>p!=null))];if(d.length===0){n=n.map(p=>({...p,[r]:null}));continue}let u=b(i,l),c=await a.select().from(i).where(inArray(u,d)),m=new Map;for(let p of c){let g=p[l];m.set(g,p);}n=n.map(p=>{let g=p[s.foreignKey];return {...p,[r]:m.get(g)||null}});break}}}return n}function O(a,e){let t=b(a,e.field);switch(e.operator){case "eq":return eq(t,e.value);case "ne":return ne$1(t,e.value);case "gt":return gt(t,e.value);case "gte":return gte(t,e.value);case "lt":return lt$1(t,e.value);case "lte":return lte(t,e.value);case "in":return inArray(t,e.value);case "nin":return notInArray(t,e.value);case "like":return like(t,e.value);case "ilike":return ilike(t,e.value);case "null":return e.value?isNull(t):isNotNull(t);case "between":{let[o,n]=e.value;return between(t,o,n)}default:return}}function D(a){let e=a;if(e._tx)return e._tx;if(e.db)return e.db;let t=e.context?.get?.("db");if(t)return t;throw new Error(`Database not configured. Either:
|
|
2
|
+
1. Set db property: db = myDb;
|
|
3
|
+
2. Use middleware: c.set("db", myDb);
|
|
4
|
+
3. Use factory: createDrizzleCrud(db, meta)`)}function ee(a,e,t){switch(t){case "pg":return sql`POSITION(LOWER(${e}) IN LOWER(${a})) > 0`;case "mysql":return sql`LOCATE(LOWER(${e}), LOWER(${a})) > 0`;default:return sql`INSTR(LOWER(${a}), LOWER(${e})) > 0`}}function lt(a){return a.split(/\s+/).filter(e=>e.length>0)}var j=class extends A$1{db;dialect="sqlite";getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async findExisting(e){let t=this.getTable(),o=this.getUpsertKeys(),n=this.getSoftDeleteConfig(),r=[];for(let i of o){let l=e[i];l!==void 0&&r.push(eq(this.getColumn(i),l));}return n.enabled&&r.push(isNull(this.getColumn(n.field))),r.length===0?null:(await this.getDb().select().from(t).where(and(...r)).limit(1))[0]||null}async create(e){let t=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(o).returning())[0]}async update(e,t){let o=this.getTable(),n=this._meta.model.primaryKeys[0],r=e[n];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(n),r)).returning())[0]}async nativeUpsert(e,t){let o=this.getTable(),n=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=this.getSoftDeleteConfig(),i=this.getTimestampsConfig(),l=this.applyManagedInsertFields(e,"drizzle"),d={};for(let[h,y]of Object.entries(e))!n.includes(h)&&h!==r&&(this.createOnlyFields?.includes(h)||(d[h]=y));i.enabled&&(d[i.updatedAt]=Date.now());let u=n.map(h=>this.getColumn(h)),c;s.enabled&&(c=isNull(this.getColumn(s.field)));let m=Object.keys(d).length>0?d:{[r]:sql`${this.getColumn(r)}`},p=this.getDb().insert(o).values(l);return this.dialect==="mysql"?{data:(await p.onDuplicateKeyUpdate({set:m}).returning())[0],created:false}:{data:(await p.onConflictDoUpdate({target:u,set:m,where:c}).returning())[0],created:false}}},_=class extends F$1{db;dialect="sqlite";getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async findExisting(e){let t=this.getTable(),o=this.getUpsertKeys(),n=[];for(let s of o){let i=e[s];i!==void 0&&n.push(eq(this.getColumn(s),i));}return n.length===0?null:(await this.getDb().select().from(t).where(and(...n)).limit(1))[0]||null}async create(e){let t=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(o).returning())[0]}async update(e,t){let o=this.getTable(),n=this._meta.model.primaryKeys[0],r=e[n];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(n),r)).returning())[0]}async nativeBatchUpsert(e,t){if(e.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let o=this.getTable(),n=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],s=this.getTimestampsConfig(),i=e.map(g=>this.applyManagedInsertFields(g,"drizzle")),l={},d=e[0];for(let g of Object.keys(d))!n.includes(g)&&g!==r&&(this.createOnlyFields?.includes(g)||(l[g]=sql`excluded.${sql.identifier(g)}`));s.enabled&&(l[s.updatedAt]=Date.now());let u=n.map(g=>this.getColumn(g)),c=Object.keys(l).length>0?l:{[r]:sql`${this.getColumn(r)}`},m=this.getDb().insert(o).values(i),p=await(this.dialect==="mysql"?m.onDuplicateKeyUpdate({set:c}):m.onConflictDoUpdate({target:u,set:c})).returning();return {items:p.map((g,h)=>({data:g,created:false,index:h})),createdCount:0,updatedCount:p.length,totalCount:p.length}}},Be=class extends G$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async recordExists(e){let t=this.getTable(),o=await this.getDb().select({count:sql`count(*)`}).from(t).where(eq(this.getColumn("id"),e));return Number(o[0]?.count)>0}},Ae=class extends H$1{},Le=class extends I$1{},Ke=class extends J$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async rollback(e,t,o){let n=this.getTable(),r=this.getVersioningConfig().field;return (await this.getDb().update(n).set({...t,[r]:o}).where(eq(this.getColumn("id"),e)).returning())[0]}},G=class extends K$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async aggregate(e){let t=this.getTable(),o=[],n=this.getSoftDeleteConfig();if(n.enabled){let{query:i}=await this.getValidatedData();i?.withDeleted===true||i?.withDeleted==="true"||o.push(isNull(this.getColumn(n.field)));}if(e.filters)for(let[i,l]of Object.entries(e.filters))if(typeof l=="object"&&l!==null)for(let[d,u]of Object.entries(l)){let c=O(t,{field:i,operator:d,value:u});c&&o.push(c);}else o.push(eq(this.getColumn(i),l));let r=o.length>0?and(...o):void 0,s=await this.getDb().select().from(t).where(r);return L$1(s,e)}},I=class extends T{db;dialect="sqlite";getDb(){return D(this)}useNativeSearch=false;vectorColumn;vectorConfig="english";getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async search(e,t){let o=this.getTable(),n=[],r=this.getSoftDeleteConfig();r.enabled&&(t.options.onlyDeleted?n.push(isNotNull(this.getColumn(r.field))):t.options.withDeleted||n.push(isNull(this.getColumn(r.field))));for(let w of t.filters){let M=O(o,w);M&&n.push(M);}let s=this.getSearchableFields(),i=e.fields||Object.keys(s);if(this.useNativeSearch&&this.vectorColumn){let w=this.getColumn(this.vectorColumn),M=e.mode==="phrase"?sql`phraseto_tsquery(${this.vectorConfig}, ${e.query})`:e.mode==="all"?sql`plainto_tsquery(${this.vectorConfig}, ${e.query})`:sql`to_tsquery(${this.vectorConfig}, ${e.query.split(/\s+/).join(" | ")})`;n.push(sql`${w} @@ ${M}`);}else {let w=(M,x)=>{try{let ie=this.getColumn(M);return ee(sql`CAST(${ie} AS TEXT)`,x,this.dialect)}catch{return}};if(e.mode==="all"){let M=lt(e.query);if(M.length>0){let x=[];for(let ie of M){let pe=i.map(ae=>w(ae,ie)).filter(ae=>ae!==void 0);pe.length>0&&x.push(or(...pe));}x.length>0&&n.push(and(...x));}}else {let M=i.map(x=>w(x,e.query)).filter(x=>x!==void 0);M.length>0&&n.push(or(...M));}}let l=n.length>0?and(...n):void 0,d=await this.getDb().select({count:sql`count(*)`}).from(o).where(l),u=Number(d[0]?.count)||0,c=this.getDb().select().from(o).where(l);if(t.options.order_by){let w=this.getColumn(t.options.order_by),M=t.options.order_by_direction==="desc"?desc:asc;c=c.orderBy(M(w));}let m=t.options.page||1,p=t.options.per_page||this.defaultPerPage;c=c.limit(p).offset((m-1)*p);let g=await c,h=e.mode==="all"?{...e,mode:"any"}:e,y=U$1(g,h,s),R={relations:t.options.include||[]},$=y.map(w=>w.item),se=await S(this.getDb(),$,this._meta,R);return {items:y.map((w,M)=>({...w,item:se[M]})),totalCount:u}}},H=class extends ba{db;dialect="sqlite";getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async list(e){let t=this.getTable(),o=[],n=this.getSoftDeleteConfig();if(n.enabled){let h=this.getColumn(n.field);e.options.onlyDeleted?o.push(isNotNull(h)):e.options.withDeleted||o.push(isNull(h));}for(let h of e.filters){let y=O(t,h);y&&o.push(y);}if(e.options.search&&this.searchFields.length>0){let h=e.options.search,y=this.searchFields.map(R=>{let $=this.getColumn(R);return ee($,h,this.dialect)});o.push(or(...y));}let r=o.length>0?and(...o):void 0,s=await this.getDb().select({count:sql`count(*)`}).from(t).where(r),i=Number(s[0]?.count)||0,l=this.getDb().select().from(t).where(r);if(e.options.order_by){let h=this.getColumn(e.options.order_by),y=e.options.order_by_direction==="desc"?desc:asc;l=l.orderBy(y(h));}let d=e.options.page||1,u=e.options.per_page||this.defaultPerPage;l=l.limit(u).offset((d-1)*u);let c=await l,m={relations:e.options.include||[]},p=await S(this.getDb(),c,this._meta,m),g=Math.ceil(i/u);return {result:p,result_info:{page:d,per_page:u,total_count:i,total_pages:g,has_next_page:d<g,has_prev_page:d>1}}}},J=class extends ca{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async findExisting(e){let t=this.getTable(),o=this.getUpsertKeys(),n=this.getSoftDeleteConfig(),r=[];for(let i of o){let l=e[i];l!==void 0&&r.push(eq(this.getColumn(i),l));}return n.enabled&&r.push(isNull(this.getColumn(n.field))),r.length===0?null:(await this.getDb().select().from(t).where(and(...r)).limit(1))[0]||null}async create(e){let t=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(o).returning())[0]}async update(e,t){let o=this.getTable(),n=this._meta.model.primaryKeys[0],r=e[n];return (await this.getDb().update(o).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(n),r)).returning())[0]}},Y=class extends y{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}generateId(){return crypto.randomUUID()}async findSource(e,t){let o=this.getTable(),n=this.getColumn(this.lookupField),r=this.getSoftDeleteConfig(),s=[eq(n,e)];if(t)for(let[l,d]of Object.entries(t))s.push(eq(this.getColumn(l),d));r.enabled&&s.push(isNull(this.getColumn(r.field)));let i=await this.getDb().select().from(o).where(and(...s)).limit(1);return i[0]?i[0]:null}async createClone(e){let t=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle",()=>this.generateId());return (await this.getDb().insert(t).values(o).returning())[0]}};var U=class extends t{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getRelatedTable(e){return e.table}async create(e,t){let o=t??this.getDb(),n=this.getTable(),r=this.applyManagedInsertFields(e,"drizzle");return (await o.insert(n).values(r).returning())[0]}async createNested(e,t,o,n,r){let s=r??this.getDb(),i=this.getRelatedTable(o);if(!i)return b$1().warn(`Related table not found for ${t}. Add 'table' to the relation config.`),[];let l=Array.isArray(n)?n:[n],d=[];for(let u of l){if(typeof u!="object"||u===null)continue;let c={...u,id:crypto.randomUUID(),[o.foreignKey]:e},m=await s.insert(i).values(c).returning();m[0]&&d.push(m[0]);}return d}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},B=class extends u{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async read(e,t,o){let n=this.getTable(),r=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),i=[eq(r,e)];if(t)for(let[u,c]of Object.entries(t))i.push(eq(this.getColumn(u),c));s.enabled&&i.push(isNull(this.getColumn(s.field)));let l=await this.getDb().select().from(n).where(and(...i)).limit(1);return l[0]?await ce(this.getDb(),l[0],this._meta,o):null}},A=class extends v{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}getRelatedTable(e){return e.table}async findExisting(e,t,o){let n=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return i.enabled&&l.push(isNull(this.getColumn(i.field))),(await n.select().from(r).where(and(...l)).limit(1))[0]||null}async update(e,t,o,n){let r=n??this.getDb(),s=this.getTable(),i=this.getColumn(this.lookupField),l=this.getSoftDeleteConfig(),d=[eq(i,e)];if(o)for(let[c,m]of Object.entries(o))d.push(eq(this.getColumn(c),m));return l.enabled&&d.push(isNull(this.getColumn(l.field))),(await r.update(s).set(this.applyManagedUpdateFields(t)).where(and(...d)).returning())[0]||null}async processNestedWrites(e,t,o,n,r){let s=r??this.getDb(),i=this.getRelatedTable(o);if(!i)return b$1().warn(`Related table not found for ${t}. Add 'table' to the relation config.`),{created:[],updated:[],deleted:[],connected:[],disconnected:[]};let l={created:[],updated:[],deleted:[],connected:[],disconnected:[]},d=b(i,o.foreignKey),u=b(i,"id");if(n.create){let c=Array.isArray(n.create)?n.create:[n.create];for(let m of c){if(typeof m!="object"||m===null)continue;let p={...m,id:crypto.randomUUID(),[o.foreignKey]:e},g=await s.insert(i).values(p).returning();g[0]&&l.created.push(g[0]);}}if(n.update)for(let c of n.update){if(!c.id||!(await s.select().from(i).where(and(eq(u,c.id),eq(d,e))).limit(1))[0])continue;let{id:p,...g}=c,h=await s.update(i).set(g).where(eq(u,p)).returning();h[0]&&l.updated.push(h[0]);}if(n.delete)for(let c of n.delete)(await s.delete(i).where(and(eq(u,c),eq(d,e))).returning())[0]&&l.deleted.push(c);if(n.connect)for(let c of n.connect)(await s.update(i).set({[o.foreignKey]:e}).where(eq(u,c)).returning())[0]&&l.connected.push(c);if(n.disconnect)for(let c of n.disconnect)(await s.update(i).set({[o.foreignKey]:null}).where(and(eq(u,c),eq(d,e))).returning())[0]&&l.disconnected.push(c);return l}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},L=class extends w{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}getRelatedTable(e){return e.table}async findForDelete(e,t,o){let n=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return i.enabled&&l.push(isNull(this.getColumn(i.field))),(await n.select().from(r).where(and(...l)).limit(1))[0]||null}async delete(e,t,o){let n=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[d,u]of Object.entries(t))l.push(eq(this.getColumn(d),u));return i.enabled&&l.push(isNull(this.getColumn(i.field))),i.enabled?(await n.update(r).set({[i.field]:new Date}).where(and(...l)).returning())[0]||null:(await n.delete(r).where(and(...l)).returning())[0]||null}async countRelated(e,t,o,n){let r=n??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=b(s,o.foreignKey),l=await r.select({count:sql`count(*)`}).from(s).where(eq(i,e));return Number(l[0]?.count)||0}async deleteRelated(e,t,o,n){let r=n??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=b(s,o.foreignKey);return (await r.delete(s).where(eq(i,e)).returning()).length}async nullifyRelated(e,t,o,n){let r=n??this.getDb(),s=this.getRelatedTable(o);if(!s)return 0;let i=b(s,o.foreignKey);return (await r.update(s).set({[o.foreignKey]:null}).where(eq(i,e)).returning()).length}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}},K=class extends x{db;dialect="sqlite";getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async list(e){let t=this.getTable(),o=[],n=this.getSoftDeleteConfig();if(n.enabled){let y=this.getColumn(n.field);e.options.onlyDeleted?o.push(isNotNull(y)):e.options.withDeleted||o.push(isNull(y));}for(let y of e.filters){let R=O(t,y);R&&o.push(R);}if(e.options.search&&this.searchFields.length>0){let y=e.options.search,R=this.searchFields.map($=>{let se=this.getColumn($);return ee(se,y,this.dialect)});o.push(or(...R));}let r=o.length>0?and(...o):void 0,s=this.getDb(),i=await s.select({count:sql`count(*)`}).from(t).where(r),l=Number(i[0]?.count)||0,d=s.select().from(t).where(r);if(e.options.order_by){let y=this.getColumn(e.options.order_by),R=e.options.order_by_direction==="desc"?desc:asc;d=d.orderBy(R(y));}let u=e.options.page||1,c=e.options.per_page||this.defaultPerPage;d=d.limit(c).offset((u-1)*c);let m=await d,p={relations:e.options.include||[]},g=await S(this.getDb(),m,this._meta,p),h=Math.ceil(l/c);return {result:g,result_info:{page:u,per_page:c,total_count:l,total_pages:h,has_next_page:u<h,has_prev_page:u>1}}}},Z=class extends z$1{db;useTransaction=false;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async restore(e,t,o){let n=o??this.getDb(),r=this.getTable(),s=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return l.push(isNotNull(this.getColumn(i.field))),(await n.update(r).set({[i.field]:null}).where(and(...l)).returning())[0]||null}async handle(){return this.useTransaction?this.getDb().transaction(async e=>{this._tx=e;try{return await super.handle()}finally{this._tx=void 0;}}):super.handle()}};var F=class extends B$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}async batchCreate(e){let t=this.getTable(),o=e.map(r=>this.applyManagedInsertFields(r,"drizzle"));return await this.getDb().insert(t).values(o).returning()}},Q=class extends C{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async batchUpdate(e){let t=this.getTable(),o=this.getColumn(this.lookupField),n=this.getSoftDeleteConfig(),r=[],s=[];for(let i of e){let l=[eq(o,i.id)];n.enabled&&l.push(isNull(this.getColumn(n.field)));let d=await this.getDb().update(t).set(this.applyManagedUpdateFields(i.data)).where(and(...l)).returning();d[0]?r.push(d[0]):s.push(i.id);}return {updated:r,notFound:s}}},N=class extends D$1{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async batchDelete(e){let t=this.getTable(),o=this.getColumn(this.lookupField),n=this.getSoftDeleteConfig(),r=[inArray(o,e)];n.enabled&&r.push(isNull(this.getColumn(n.field)));let s;n.enabled?s=await this.getDb().update(t).set({[n.field]:new Date}).where(and(...r)).returning():s=await this.getDb().delete(t).where(and(...r)).returning();let i=s,l=new Set(i.map(u=>String(u[this.lookupField]))),d=e.filter(u=>!l.has(u));return {deleted:i,notFound:d}}},q=class extends E{db;getDb(){return D(this)}getTable(){return f(this._meta)}getColumn(e){return b(this.getTable(),e)}async batchRestore(e){let t=this.getTable(),o=this.getColumn(this.lookupField),n=this.getSoftDeleteConfig(),r=[inArray(o,e),isNotNull(this.getColumn(n.field))],i=await this.getDb().update(t).set({[n.field]:null}).where(and(...r)).returning(),l=new Set(i.map(u=>String(u[this.lookupField]))),d=e.filter(u=>!l.has(u));return {restored:i,notFound:d}}};function ln(a,e,t){let o=t?.dialect??"sqlite";return {Create:class extends U{_meta=e;db=a},Read:class extends B{_meta=e;db=a},Update:class extends A{_meta=e;db=a},Delete:class extends L{_meta=e;db=a},List:class extends K{_meta=e;db=a;dialect=o},Restore:class extends Z{_meta=e;db=a},Upsert:class extends j{_meta=e;db=a;dialect=o},Search:class extends I{_meta=e;db=a;dialect=o},BatchCreate:class extends F{_meta=e;db=a},BatchUpdate:class extends Q{_meta=e;db=a},BatchDelete:class extends N{_meta=e;db=a},BatchRestore:class extends q{_meta=e;db=a},BatchUpsert:class extends _{_meta=e;db=a;dialect=o}}}var oe=null,Ve=false,ne=null;async function re(){if(Ve){if(ne)throw ne;return oe}Ve=true;try{return oe=await import('drizzle-zod'),oe}catch{throw ne=new Error("drizzle-zod is not installed. Please install it: npm install drizzle-zod"),ne}}async function mt(a,e){return (await re()).createSelectSchema(a,e)}async function bt(a,e){return (await re()).createInsertSchema(a,e)}async function ht(a,e){let t=await re();return t.createUpdateSchema?t.createUpdateSchema(a,e):t.createInsertSchema(a,e).partial()}async function ft(a,e){let t=await re(),o=e?.coerceDates!==false,n=o?Mt(a):new Set,r=t.createSelectSchema(a,e?.selectRefine),s=t.createInsertSchema(a,e?.insertRefine),i;return t.createUpdateSchema?i=t.createUpdateSchema(a,e?.updateRefine):i=t.createInsertSchema(a,e?.updateRefine).partial(),o&&n.size>0&&(s=Xe(s,n),i=Xe(i,n)),{select:r,insert:s,update:i}}function zt(){return oe!==null}var Dt=z.preprocess(a=>{if(a instanceof Date)return a;if(typeof a=="string"){let e=new Date(a);if(!isNaN(e.getTime()))return e}return a},z.date()),yt=z.preprocess(a=>{if(a==null)return null;if(a instanceof Date)return a;if(typeof a=="string"){let e=new Date(a);if(!isNaN(e.getTime()))return e}return a},z.date().nullable());function Mt(a){let e=new Set,t=a;for(let[o,n]of Object.entries(t)){if(o==="_"||o==="$inferInsert"||o==="$inferSelect")continue;let r=n;if(!r||typeof r!="object")continue;let s=String(r.dataType??"").toLowerCase(),i=String(r.columnType??"").toLowerCase(),l=r.config,d=String(l?.dataType??"").toLowerCase();(s.includes("timestamp")||s.includes("date")||s.includes("datetime")||i.includes("pgtimestamp")||i.includes("pgdate")||i.includes("mysqltimestamp")||i.includes("mysqldate")||i.includes("sqlitetimestamp")||d.includes("timestamp")||d.includes("date"))&&e.add(o);}return e}function Xe(a,e){if(e.size===0)return a;let t=a.shape,o={};for(let[n,r]of Object.entries(t))if(e.has(n)){let s=r.isOptional?.()??false,i=r.isNullable?.()??false,l=Dt;(i||s)&&(l=yt),s&&(l=l.optional()),o[n]=l;}else o[n]=r;return z.object(o)}var kn={CreateEndpoint:U,ListEndpoint:K,ReadEndpoint:B,UpdateEndpoint:A,DeleteEndpoint:L,RestoreEndpoint:Z,BatchCreateEndpoint:F,BatchUpdateEndpoint:Q,BatchDeleteEndpoint:N,BatchRestoreEndpoint:q,BatchUpsertEndpoint:_,SearchEndpoint:I,AggregateEndpoint:G,ExportEndpoint:H,ImportEndpoint:J,UpsertEndpoint:j,CloneEndpoint:Y};export{Q as A,N as B,q as C,ln as D,mt as E,bt as F,ht as G,ft as H,zt as I,kn as J,X as a,f as b,b as c,Ue as d,ce as e,S as f,O as g,ee as h,j as i,_ as j,Be as k,Ae as l,Le as m,Ke as n,G as o,I as p,H as q,J as r,Y as s,U as t,B as u,A as v,L as w,K as x,Z as y,F as z};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {b as b$4}from'./chunk-NGUMNUOP.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-FJCWFB5L.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-NGUMNUOP.js';import {a as a$3}from'./chunk-GF2EC5G4.js';import {b as b$3}from'./chunk-FJCWFB5L.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 +1 @@
|
|
|
1
|
-
import {d}from'./chunk-
|
|
1
|
+
import {d}from'./chunk-IPMPKM4J.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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {t,u,v as v$1,w,x,z,B,C,D,E as E$1,F,m as m$1,o,y,A,G,H,I,J,K,L,T,U,ba,ca}from'./chunk-ZBCVLQ3W.js';import {b,a}from'./chunk-KUFOENSK.js';import {z as z$1}from'zod';var E=new Map;function m(u){return E.has(u)||E.set(u,new Map),E.get(u)}function Ee(u,t,a){let n=m(a.model),e=a.localKey||"id",r=u[e];if(r==null)return u;let o=Array.from(n.values()).filter(s=>s[a.foreignKey]===r);switch(a.type){case "hasOne":return {...u,[t]:o[0]||null};case "hasMany":return {...u,[t]:o};case "belongsTo":{let s=u[a.foreignKey];if(s==null)return {...u,[t]:null};let i=Array.from(n.values()).find(d=>d[a.localKey||"id"]===s);return {...u,[t]:i||null}}default:return u}}function v(u,t,a){if(!a?.relations?.length||!t.model.relations)return u;let n={...u};for(let e of a.relations){let r=t.model.relations[e];r&&(n=Ee(n,e,r));}return n}function _e(){E.clear();}function Ie(u){return m(u)}function R(u,t,a){if(u==null||typeof u!="object")return false;let n=u;if(t.enabled){let e=n[t.field];if(e!=null)return false}if(a){for(let[e,r]of Object.entries(a))if(String(n[e])!==r)return false}return true}var P=Object.freeze({__memoryNoopTx:true,rolledBack:false}),se=class extends t{_tx=P;generateId(){return crypto.randomUUID()}async create(t){let a=m(this._meta.model.tableName),n=this._meta.model.primaryKeys[0],e=this.applyManagedInsertFields(t,"memory",()=>this.generateId()),r=String(e[n]);return a.set(r,e),e}async createNested(t,a,n,e){let r=m(n.model),o=[],s=Array.isArray(e)?e:[e];for(let i of s){if(typeof i!="object"||i===null)continue;let d={...i,id:crypto.randomUUID(),[n.foreignKey]:t};r.set(d.id,d),o.push(d);}return o}},ie=class extends u{async read(t,a,n){let r=m(this._meta.model.tableName).get(t),o=this.getSoftDeleteConfig();return !r||!R(r,o,a)?null:v(r,this._meta,n)}},ae=class extends v$1{_tx=P;async findExisting(t,a){let e=m(this._meta.model.tableName).get(t),r=this.getSoftDeleteConfig();return !e||!R(e,r,a)?null:{...e}}async update(t,a,n){let e=m(this._meta.model.tableName),r=e.get(t),o=this.getSoftDeleteConfig();if(!r||!R(r,o,n))return null;let s={...r,...this.applyManagedUpdateFields(a)};return e.set(t,s),s}async processNestedWrites(t,a,n,e){let r=m(n.model),o={created:[],updated:[],deleted:[],connected:[],disconnected:[]};if(e.create){let s=Array.isArray(e.create)?e.create:[e.create];for(let i of s){if(typeof i!="object"||i===null)continue;let d={...i,id:crypto.randomUUID(),[n.foreignKey]:t};r.set(d.id,d),o.created.push(d);}}if(e.update)for(let s of e.update){if(!s.id)continue;let i=r.get(String(s.id));if(!i||i[n.foreignKey]!==t)continue;let d={...i,...s};r.set(String(s.id),d),o.updated.push(d);}if(e.delete)for(let s of e.delete){let i=r.get(String(s));i&&i[n.foreignKey]===t&&(r.delete(String(s)),o.deleted.push(s));}if(e.connect)for(let s of e.connect){let i=r.get(String(s));if(!i)continue;let d={...i,[n.foreignKey]:t};r.set(String(s),d),o.connected.push(s);}if(e.disconnect)for(let s of e.disconnect){let i=r.get(String(s));if(!i||i[n.foreignKey]!==t)continue;let d={...i,[n.foreignKey]:null};r.set(String(s),d),o.disconnected.push(s);}if(e.set!==void 0){let s=Array.from(r.values()).filter(i=>i[n.foreignKey]===t);for(let i of s)if(i.id){let d={...i,[n.foreignKey]:null};r.set(String(i.id),d),o.disconnected.push(i.id);}if(e.set!==null){let i={...e.set,id:crypto.randomUUID(),[n.foreignKey]:t};r.set(i.id,i),o.created.push(i);}}return o}},de=class extends w{_tx=P;async findForDelete(t,a){let e=m(this._meta.model.tableName).get(t),r=this.getSoftDeleteConfig();return !e||!R(e,r,a)?null:e}async countRelated(t,a,n){let e=m(n.model),r=0;for(let o of e.values())o[n.foreignKey]===t&&r++;return r}async deleteRelated(t,a,n){let e=m(n.model),r=0;for(let[o,s]of e.entries())s[n.foreignKey]===t&&(e.delete(o),r++);return r}async nullifyRelated(t,a,n){let e=m(n.model),r=0;for(let[o,s]of e.entries())if(s[n.foreignKey]===t){let i={...s,[n.foreignKey]:null};e.set(o,i),r++;}return r}async delete(t,a){let n=m(this._meta.model.tableName),e=n.get(t),r=this.getSoftDeleteConfig();if(!e||!R(e,r,a))return null;if(r.enabled){let o={...e,[r.field]:new Date};return n.set(t,o),o}else return n.delete(t),e}},le=class extends x{async list(t){let a$1=m(this._meta.model.tableName),n=Array.from(a$1.values()),e=this.getSoftDeleteConfig();e.enabled&&(t.options.onlyDeleted?n=n.filter(l=>{let p=l[e.field];return p!=null}):t.options.withDeleted||(n=n.filter(l=>{let p=l[e.field];return p==null})));for(let l of t.filters)n=n.filter(p=>{let c=p[l.field];switch(l.operator){case "eq":return String(c)===String(l.value);case "ne":return String(c)!==String(l.value);case "gt":return Number(c)>Number(l.value);case "gte":return Number(c)>=Number(l.value);case "lt":return Number(c)<Number(l.value);case "lte":return Number(c)<=Number(l.value);case "in":return l.value.map(String).includes(String(c));case "nin":return !l.value.map(String).includes(String(c));case "like":return String(c).includes(String(l.value).replace(/%/g,""));case "ilike":return String(c).toLowerCase().includes(String(l.value).replace(/%/g,"").toLowerCase());case "null":return l.value?c===null:c!==null;case "between":{let[y,f]=l.value;return Number(c)>=Number(y)&&Number(c)<=Number(f)}default:return true}});if(t.options.search&&this.searchFields.length>0){let l=t.options.search.toLowerCase();n=n.filter(p=>this.searchFields.some(c=>{let y=p[c];return String(y).toLowerCase().includes(l)}));}let r=n.length;if(t.options.order_by){let l=t.options.order_by,p=t.options.order_by_direction==="desc"?-1:1;n.sort((c,y)=>{let f=c[l],b=y[l];return f<b?-1*p:f>b?1*p:0});}if(this.cursorPaginationEnabled&&(t.options.cursor||t.options.limit)){let l=this.cursorField||"id",p=t.options.limit||t.options.per_page||this.defaultPerPage,c=0;if(t.options.cursor){let x=b(t.options.cursor);if(x!==null){let I=n.findIndex(ve=>String(ve[l])===x);I!==-1&&(c=I+1);}}let y=n.slice(c,c+p),f={relations:t.options.include||[]},b$1=y.map(x=>v(x,this._meta,f)),M=c+p<n.length,w=c>0,j,S;if(M&&y.length>0){let x=y[y.length-1];j=a(x[l]);}if(w&&c>0){let x=n[c-1];S=a(x[l]);}return {result:b$1,result_info:{page:0,per_page:p,total_count:r,has_next_page:M,has_prev_page:w,next_cursor:j,prev_cursor:S}}}let o=t.options.page||1,s=t.options.per_page||this.defaultPerPage,i=(o-1)*s,d=n.slice(i,i+s),g={relations:t.options.include||[]},O=d.map(l=>v(l,this._meta,g)),h=Math.ceil(r/s);return {result:O,result_info:{page:o,per_page:s,total_count:r,total_pages:h,has_next_page:o<h,has_prev_page:o>1}}}},ce=class extends z{async restore(t,a){let n=m(this._meta.model.tableName),e=n.get(t),r=this.getSoftDeleteConfig();if(!e)return null;let o=e[r.field];if(o==null)return null;if(a){for(let[i,d]of Object.entries(a))if(String(e[i])!==d)return null}let s={...e,[r.field]:null};return n.set(t,s),s}};var ue=class extends B{generateId(){return crypto.randomUUID()}async batchCreate(t){let a=m(this._meta.model.tableName),n=this._meta.model.primaryKeys[0],e=[];for(let r of t){let o=this.applyManagedInsertFields(r,"memory",()=>this.generateId()),s=String(o[n]);a.set(s,o),e.push(o);}return e}},me=class extends C{async batchUpdate(t){let a=m(this._meta.model.tableName),n=this.getSoftDeleteConfig(),e=[],r=[];for(let o of t){let s=a.get(o.id);if(!s){r.push(o.id);continue}if(!R(s,n)){r.push(o.id);continue}let i={...s,...this.applyManagedUpdateFields(o.data)};a.set(o.id,i),e.push(i);}return {updated:e,notFound:r}}},ge=class extends D{async batchDelete(t){let a=m(this._meta.model.tableName),n=this.getSoftDeleteConfig(),e=[],r=[];for(let o of t){let s=a.get(o);if(!s){r.push(o);continue}if(!R(s,n)){r.push(o);continue}if(n.enabled){let i={...s,[n.field]:new Date};a.set(o,i),e.push(i);}else a.delete(o),e.push(s);}return {deleted:e,notFound:r}}},pe=class extends E$1{async batchRestore(t){let a=m(this._meta.model.tableName),n=this.getSoftDeleteConfig(),e=[],r=[];for(let o of t){let s=a.get(o);if(!s){r.push(o);continue}let i=s[n.field];if(i==null){r.push(o);continue}let d={...s,[n.field]:null};a.set(o,d),e.push(d);}return {restored:e,notFound:r}}},fe=class extends F{generateId(){return crypto.randomUUID()}async findExisting(t){let a=m(this._meta.model.tableName),n=this.getUpsertKeys();for(let e of a.values()){let r=true;for(let o of n){let s=t[o],i=e[o];if(s!==i){r=false;break}}if(r)return e}return null}async create(t){let a=m(this._meta.model.tableName),n=this._meta.model.primaryKeys[0],e=this.applyManagedInsertFields(t,"memory",()=>this.generateId());return a.set(String(e[n]),e),e}async update(t,a){let n=m(this._meta.model.tableName),e=this._meta.model.primaryKeys[0],r=String(t[e]),o={...t,...this.applyManagedUpdateFields(a)};return n.set(r,o),o}async nativeBatchUpsert(t,a){let n=m(this._meta.model.tableName),e=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],o=[],s=0,i=0;for(let d=0;d<t.length;d++){let g=t[d],O=null;for(let h of n.values()){let l=true;for(let p of e){let c=g[p],y=h[p];if(c!==y){l=false;break}}if(l){O=h;break}}if(O){let h={...g};if(this.createOnlyFields)for(let c of this.createOnlyFields)delete h[c];let l=String(O[r]),p={...O,...this.applyManagedUpdateFields(h)};n.set(l,p),o.push({data:p,created:false,index:d}),i++;}else {let h={...g};if(this.updateOnlyFields)for(let c of this.updateOnlyFields)delete h[c];let l=this.applyManagedInsertFields(h,"memory",()=>this.generateId()),p=String(l[r]);n.set(p,l),o.push({data:l,created:true,index:d}),s++;}}return {items:o,createdCount:s,updatedCount:i,totalCount:o.length}}};var _=class extends m$1{maxBulkSize=1e3;confirmThreshold=100;returnRecords=false;hookMode="parallel";filterFields;getSchema(){return {request:{body:{content:{"application/json":{schema:this.getUpdateSchema().partial()}}},query:z$1.object({dryRun:z$1.string().optional()}).passthrough()},responses:{200:{description:"Bulk patch result",content:{"application/json":{schema:z$1.object({success:z$1.boolean(),matched:z$1.number(),updated:z$1.number(),dryRun:z$1.boolean()})}}},400:{description:"Bad request",content:{"application/json":{schema:z$1.object({success:z$1.boolean(),error:z$1.string()})}}}}}}async handle(){let t=this.getContext(),n=(await this.getValidatedData()).body;if(!n||Object.keys(n).length===0)return this.error("Request body is required with at least one field to update","EMPTY_BODY",400);let e=t.req.query("dryRun"),r=e==="true"||e==="1",o$1=o(t.req.query(),{filterFields:this.filterFields,defaultPerPage:this.maxBulkSize,maxPerPage:this.maxBulkSize}),s=await this.countMatching(o$1);if(s===0)return this.json({success:true,matched:0,updated:0,dryRun:r});if(s>this.maxBulkSize)return this.error(`Bulk patch affects ${s} records, exceeding the maximum of ${this.maxBulkSize}. Use more specific filters.`,"BULK_TOO_LARGE",400);if(s>=this.confirmThreshold&&t.req.header("X-Confirm-Bulk")!=="true")return this.error(`This operation will affect ${s} records. Set X-Confirm-Bulk: true header to confirm.`,"CONFIRMATION_REQUIRED",400);if(r)return this.json({success:true,matched:s,updated:0,dryRun:true});let i=n;this.beforeBulkPatch&&(i=await this.beforeBulkPatch(i,o$1,s));let d=await this.applyPatch(i,o$1),g={matched:s,updated:d.updated,dryRun:false,records:this.returnRecords?d.records:void 0};return this.afterBulkPatch&&await this.afterBulkPatch(g),this.json({success:true,matched:g.matched,updated:g.updated,dryRun:false,...this.returnRecords&&g.records?{records:g.records}:{}})}};var Me=class extends y{generateId(){return crypto.randomUUID()}async findSource(t,a){let e=m(this._meta.model.tableName).get(t),r=this.getSoftDeleteConfig();return !e||!R(e,r,a)?null:e}async createClone(t){let a=m(this._meta.model.tableName),n=this._meta.model.primaryKeys[0],e=this.applyManagedInsertFields(t,"memory",()=>this.generateId()),r=String(e[n]);return a.set(r,e),e}},be=class extends A{generateId(){return crypto.randomUUID()}async findExisting(t){let a=m(this._meta.model.tableName),n=this.getUpsertKeys(),e=this.getSoftDeleteConfig();for(let r of a.values()){if(e.enabled){let s=r[e.field];if(s!=null)continue}let o=true;for(let s of n){let i=t[s],d=r[s];if(i!==d){o=false;break}}if(o)return r}return null}async create(t){let a=m(this._meta.model.tableName),n=this._meta.model.primaryKeys[0],e=this.applyManagedInsertFields(t,"memory",()=>this.generateId());return a.set(String(e[n]),e),e}async update(t,a){let n=m(this._meta.model.tableName),e=this._meta.model.primaryKeys[0],r=String(t[e]),o={...t,...this.applyManagedUpdateFields(a)};return n.set(r,o),o}async nativeUpsert(t,a){let n=m(this._meta.model.tableName),e=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],o=this.getSoftDeleteConfig(),s=null;for(let i of n.values()){if(o.enabled){let g=i[o.field];if(g!=null)continue}let d=true;for(let g of e){let O=t[g],h=i[g];if(O!==h){d=false;break}}if(d){s=i;break}}if(s){let i={...t};if(this.createOnlyFields)for(let O of this.createOnlyFields)delete i[O];let d=String(s[r]),g={...s,...this.applyManagedUpdateFields(i)};return n.set(d,g),{data:g,created:false}}else {let i={...t};if(this.updateOnlyFields)for(let O of this.updateOnlyFields)delete i[O];let d=this.applyManagedInsertFields(i,"memory",()=>this.generateId()),g=String(d[r]);return n.set(g,d),{data:d,created:true}}}async processNestedWrites(t,a,n,e){let r=m(n.model),o={created:[],updated:[],deleted:[],connected:[],disconnected:[]};if(e.create){let s=Array.isArray(e.create)?e.create:[e.create];for(let i of s){if(typeof i!="object"||i===null)continue;let d={...i,id:crypto.randomUUID(),[n.foreignKey]:t};r.set(d.id,d),o.created.push(d);}}if(e.update)for(let s of e.update){let i=String(s.id),d=r.get(i);if(d&&d[n.foreignKey]===t){let g={...d,...s};r.set(i,g),o.updated.push(g);}}if(e.delete)for(let s of e.delete){let i=String(s),d=r.get(i);d&&d[n.foreignKey]===t&&(r.delete(i),o.deleted.push(s));}if(e.connect)for(let s of e.connect){let i=String(s),d=r.get(i);if(d){let g={...d,[n.foreignKey]:t};r.set(i,g),o.connected.push(s);}}if(e.disconnect)for(let s of e.disconnect){let i=String(s),d=r.get(i);if(d&&d[n.foreignKey]===t){let g={...d,[n.foreignKey]:null};r.set(i,g),o.disconnected.push(s);}}return o}},he=class extends G{async recordExists(t){return m(this._meta.model.tableName).has(t)}},ye=class extends H{},Oe=class extends I{},xe=class extends J{async rollback(t,a,n){let e=m(this._meta.model.tableName),r=this.getVersioningConfig().field,o={...a,[r]:n};return e.set(t,o),o}},Re=class extends K{async aggregate(t){let a=m(this._meta.model.tableName),n=Array.from(a.values()),e=this.getSoftDeleteConfig();if(e.enabled){let{query:r}=await this.getValidatedData();r?.withDeleted===true||r?.withDeleted==="true"||(n=n.filter(s=>{let i=s[e.field];return i==null}));}if(t.filters)for(let[r,o]of Object.entries(t.filters))n=n.filter(s=>{if(typeof o=="object"&&o!==null){for(let[i,d]of Object.entries(o)){let g=s[r];switch(i){case "eq":return String(g)===String(d);case "ne":return String(g)!==String(d);case "gt":return Number(g)>Number(d);case "gte":return Number(g)>=Number(d);case "lt":return Number(g)<Number(d);case "lte":return Number(g)<=Number(d);case "in":return d.map(String).includes(String(g));default:return true}}return true}return String(s[r])===String(o)});return L(n,t)}},ke=class extends T{async search(t,a){let n=m(this._meta.model.tableName),e=Array.from(n.values()),r=this.getSoftDeleteConfig();r.enabled&&(a.options.onlyDeleted?e=e.filter(f=>{let b=f[r.field];return b!=null}):a.options.withDeleted||(e=e.filter(f=>{let b=f[r.field];return b==null})));for(let f of a.filters)e=e.filter(b=>{let M=b[f.field];switch(f.operator){case "eq":return String(M)===String(f.value);case "ne":return String(M)!==String(f.value);case "gt":return Number(M)>Number(f.value);case "gte":return Number(M)>=Number(f.value);case "lt":return Number(M)<Number(f.value);case "lte":return Number(M)<=Number(f.value);case "in":return f.value.map(String).includes(String(M));case "nin":return !f.value.map(String).includes(String(M));case "like":return String(M).includes(String(f.value).replace(/%/g,""));case "ilike":return String(M).toLowerCase().includes(String(f.value).replace(/%/g,"").toLowerCase());case "null":return f.value?M===null:M!==null;case "between":{let[w,j]=f.value;return Number(M)>=Number(w)&&Number(M)<=Number(j)}default:return true}});let o=this.getSearchableFields(),s=e,i=t;if(t.mode==="all"){let f=t.query.toLowerCase().split(/\s+/).filter(M=>M.length>0),b=t.fields||Object.keys(o);f.length>0&&(s=s.filter(M=>{let w=M;return f.every(j=>b.some(S=>{let x=w[S];return x==null?false:(Array.isArray(x)?x.join(" "):String(x)).toLowerCase().includes(j)}))})),i={...t,mode:"any"};}let d=U(s,i,o),g=d.length;if(a.options.order_by){let f=a.options.order_by,b=a.options.order_by_direction==="desc"?-1:1;d.sort((M,w)=>{let j=M.item[f],S=w.item[f];return j<S?-1*b:j>S?1*b:0});}let O=a.options.page||1,h=a.options.per_page||this.defaultPerPage,l=(O-1)*h,p=d.slice(l,l+h),c={relations:a.options.include||[]};return {items:p.map(f=>({...f,item:v(f.item,this._meta,c)})),totalCount:g}}},je=class extends ba{async list(t){let a=m(this._meta.model.tableName),n=Array.from(a.values()),e=this.getSoftDeleteConfig();e.enabled&&(t.options.onlyDeleted?n=n.filter(l=>{let p=l[e.field];return p!=null}):t.options.withDeleted||(n=n.filter(l=>{let p=l[e.field];return p==null})));for(let l of t.filters)n=n.filter(p=>{let c=p[l.field];switch(l.operator){case "eq":return String(c)===String(l.value);case "ne":return String(c)!==String(l.value);case "gt":return Number(c)>Number(l.value);case "gte":return Number(c)>=Number(l.value);case "lt":return Number(c)<Number(l.value);case "lte":return Number(c)<=Number(l.value);case "in":return l.value.map(String).includes(String(c));case "nin":return !l.value.map(String).includes(String(c));case "like":return String(c).includes(String(l.value).replace(/%/g,""));case "ilike":return String(c).toLowerCase().includes(String(l.value).replace(/%/g,"").toLowerCase());case "null":return l.value?c===null:c!==null;case "between":{let[y,f]=l.value;return Number(c)>=Number(y)&&Number(c)<=Number(f)}default:return true}});if(t.options.search&&this.searchFields.length>0){let l=t.options.search.toLowerCase();n=n.filter(p=>this.searchFields.some(c=>{let y=p[c];return String(y).toLowerCase().includes(l)}));}let r=n.length;if(t.options.order_by){let l=t.options.order_by,p=t.options.order_by_direction==="desc"?-1:1;n.sort((c,y)=>{let f=c[l],b=y[l];return f<b?-1*p:f>b?1*p:0});}let o=t.options.page||1,s=t.options.per_page||this.defaultPerPage,i=(o-1)*s,d=n.slice(i,i+s),g={relations:t.options.include||[]},O=d.map(l=>v(l,this._meta,g)),h=Math.ceil(r/s);return {result:O,result_info:{page:o,per_page:s,total_count:r,total_pages:h,has_next_page:o<h,has_prev_page:o>1}}}},we=class extends ca{generateId(){return crypto.randomUUID()}async findExisting(t){let a=m(this._meta.model.tableName),n=this.getUpsertKeys(),e=this.getSoftDeleteConfig();for(let r of a.values()){if(e.enabled){let s=r[e.field];if(s!=null)continue}let o=true;for(let s of n){let i=t[s],d=r[s];if(i!==d){o=false;break}}if(o)return r}return null}async create(t){let a=m(this._meta.model.tableName),n=this._meta.model.primaryKeys[0],e=this.applyManagedInsertFields(t,"memory",()=>this.generateId());return a.set(String(e[n]),e),e}async update(t,a){let n=m(this._meta.model.tableName),e=this._meta.model.primaryKeys[0],r=String(t[e]),o={...t,...this.applyManagedUpdateFields(a)};return n.set(r,o),o}},Se=class extends _{async countMatching(t){return this.getFilteredItems(t).length}async applyPatch(t,a){let n=m(this._meta.model.tableName),e=this._meta.model.primaryKeys[0],r=this.getFilteredItems(a),o=[];for(let s of r){let i=String(s[e]),d={...s,...t};n.set(i,d),o.push(d);}return {updated:o.length,records:o}}getFilteredItems(t){let a=m(this._meta.model.tableName),n=Array.from(a.values());for(let e of t.filters)n=n.filter(r=>{let o=r[e.field];switch(e.operator){case "eq":return String(o)===String(e.value);case "ne":return String(o)!==String(e.value);case "gt":return Number(o)>Number(e.value);case "gte":return Number(o)>=Number(e.value);case "lt":return Number(o)<Number(e.value);case "lte":return Number(o)<=Number(e.value);case "in":return e.value.map(String).includes(String(o));case "nin":return !e.value.map(String).includes(String(o));case "like":return String(o).includes(String(e.value).replace(/%/g,""));case "ilike":return String(o).toLowerCase().includes(String(e.value).replace(/%/g,"").toLowerCase());case "null":return e.value?o===null:o!==null;default:return true}});return n}};export{we as A,Se as B,_ as a,E as b,m as c,_e as d,Ie as e,P as f,se as g,ie as h,ae as i,de as j,le as k,ce as l,ue as m,me as n,ge as o,pe as p,fe as q,Me as r,be as s,he as t,ye as u,Oe as v,xe as w,Re as x,ke as y,je as z};
|
|
1
|
+
import {t,u,v as v$1,w,x,z,B,C,D,E as E$1,F,m as m$1,o,y,A,G,H,I,J,K,L,T,U,ba,ca}from'./chunk-V4YEHNEZ.js';import {b,a}from'./chunk-KUFOENSK.js';import {z as z$1}from'zod';var E=new Map;function m(u){return E.has(u)||E.set(u,new Map),E.get(u)}function Ee(u,t,a){let n=m(a.model),e=a.localKey||"id",r=u[e];if(r==null)return u;let o=Array.from(n.values()).filter(s=>s[a.foreignKey]===r);switch(a.type){case "hasOne":return {...u,[t]:o[0]||null};case "hasMany":return {...u,[t]:o};case "belongsTo":{let s=u[a.foreignKey];if(s==null)return {...u,[t]:null};let i=Array.from(n.values()).find(d=>d[a.localKey||"id"]===s);return {...u,[t]:i||null}}default:return u}}function v(u,t,a){if(!a?.relations?.length||!t.model.relations)return u;let n={...u};for(let e of a.relations){let r=t.model.relations[e];r&&(n=Ee(n,e,r));}return n}function _e(){E.clear();}function Ie(u){return m(u)}function R(u,t,a){if(u==null||typeof u!="object")return false;let n=u;if(t.enabled){let e=n[t.field];if(e!=null)return false}if(a){for(let[e,r]of Object.entries(a))if(String(n[e])!==r)return false}return true}var P=Object.freeze({__memoryNoopTx:true,rolledBack:false}),se=class extends t{_tx=P;generateId(){return crypto.randomUUID()}async create(t){let a=m(this._meta.model.tableName),n=this._meta.model.primaryKeys[0],e=this.applyManagedInsertFields(t,"memory",()=>this.generateId()),r=String(e[n]);return a.set(r,e),e}async createNested(t,a,n,e){let r=m(n.model),o=[],s=Array.isArray(e)?e:[e];for(let i of s){if(typeof i!="object"||i===null)continue;let d={...i,id:crypto.randomUUID(),[n.foreignKey]:t};r.set(d.id,d),o.push(d);}return o}},ie=class extends u{async read(t,a,n){let r=m(this._meta.model.tableName).get(t),o=this.getSoftDeleteConfig();return !r||!R(r,o,a)?null:v(r,this._meta,n)}},ae=class extends v$1{_tx=P;async findExisting(t,a){let e=m(this._meta.model.tableName).get(t),r=this.getSoftDeleteConfig();return !e||!R(e,r,a)?null:{...e}}async update(t,a,n){let e=m(this._meta.model.tableName),r=e.get(t),o=this.getSoftDeleteConfig();if(!r||!R(r,o,n))return null;let s={...r,...this.applyManagedUpdateFields(a)};return e.set(t,s),s}async processNestedWrites(t,a,n,e){let r=m(n.model),o={created:[],updated:[],deleted:[],connected:[],disconnected:[]};if(e.create){let s=Array.isArray(e.create)?e.create:[e.create];for(let i of s){if(typeof i!="object"||i===null)continue;let d={...i,id:crypto.randomUUID(),[n.foreignKey]:t};r.set(d.id,d),o.created.push(d);}}if(e.update)for(let s of e.update){if(!s.id)continue;let i=r.get(String(s.id));if(!i||i[n.foreignKey]!==t)continue;let d={...i,...s};r.set(String(s.id),d),o.updated.push(d);}if(e.delete)for(let s of e.delete){let i=r.get(String(s));i&&i[n.foreignKey]===t&&(r.delete(String(s)),o.deleted.push(s));}if(e.connect)for(let s of e.connect){let i=r.get(String(s));if(!i)continue;let d={...i,[n.foreignKey]:t};r.set(String(s),d),o.connected.push(s);}if(e.disconnect)for(let s of e.disconnect){let i=r.get(String(s));if(!i||i[n.foreignKey]!==t)continue;let d={...i,[n.foreignKey]:null};r.set(String(s),d),o.disconnected.push(s);}if(e.set!==void 0){let s=Array.from(r.values()).filter(i=>i[n.foreignKey]===t);for(let i of s)if(i.id){let d={...i,[n.foreignKey]:null};r.set(String(i.id),d),o.disconnected.push(i.id);}if(e.set!==null){let i={...e.set,id:crypto.randomUUID(),[n.foreignKey]:t};r.set(i.id,i),o.created.push(i);}}return o}},de=class extends w{_tx=P;async findForDelete(t,a){let e=m(this._meta.model.tableName).get(t),r=this.getSoftDeleteConfig();return !e||!R(e,r,a)?null:e}async countRelated(t,a,n){let e=m(n.model),r=0;for(let o of e.values())o[n.foreignKey]===t&&r++;return r}async deleteRelated(t,a,n){let e=m(n.model),r=0;for(let[o,s]of e.entries())s[n.foreignKey]===t&&(e.delete(o),r++);return r}async nullifyRelated(t,a,n){let e=m(n.model),r=0;for(let[o,s]of e.entries())if(s[n.foreignKey]===t){let i={...s,[n.foreignKey]:null};e.set(o,i),r++;}return r}async delete(t,a){let n=m(this._meta.model.tableName),e=n.get(t),r=this.getSoftDeleteConfig();if(!e||!R(e,r,a))return null;if(r.enabled){let o={...e,[r.field]:new Date};return n.set(t,o),o}else return n.delete(t),e}},le=class extends x{async list(t){let a$1=m(this._meta.model.tableName),n=Array.from(a$1.values()),e=this.getSoftDeleteConfig();e.enabled&&(t.options.onlyDeleted?n=n.filter(l=>{let p=l[e.field];return p!=null}):t.options.withDeleted||(n=n.filter(l=>{let p=l[e.field];return p==null})));for(let l of t.filters)n=n.filter(p=>{let c=p[l.field];switch(l.operator){case "eq":return String(c)===String(l.value);case "ne":return String(c)!==String(l.value);case "gt":return Number(c)>Number(l.value);case "gte":return Number(c)>=Number(l.value);case "lt":return Number(c)<Number(l.value);case "lte":return Number(c)<=Number(l.value);case "in":return l.value.map(String).includes(String(c));case "nin":return !l.value.map(String).includes(String(c));case "like":return String(c).includes(String(l.value).replace(/%/g,""));case "ilike":return String(c).toLowerCase().includes(String(l.value).replace(/%/g,"").toLowerCase());case "null":return l.value?c===null:c!==null;case "between":{let[y,f]=l.value;return Number(c)>=Number(y)&&Number(c)<=Number(f)}default:return true}});if(t.options.search&&this.searchFields.length>0){let l=t.options.search.toLowerCase();n=n.filter(p=>this.searchFields.some(c=>{let y=p[c];return String(y).toLowerCase().includes(l)}));}let r=n.length;if(t.options.order_by){let l=t.options.order_by,p=t.options.order_by_direction==="desc"?-1:1;n.sort((c,y)=>{let f=c[l],b=y[l];return f<b?-1*p:f>b?1*p:0});}if(this.cursorPaginationEnabled&&(t.options.cursor||t.options.limit)){let l=this.cursorField||"id",p=t.options.limit||t.options.per_page||this.defaultPerPage,c=0;if(t.options.cursor){let x=b(t.options.cursor);if(x!==null){let I=n.findIndex(ve=>String(ve[l])===x);I!==-1&&(c=I+1);}}let y=n.slice(c,c+p),f={relations:t.options.include||[]},b$1=y.map(x=>v(x,this._meta,f)),M=c+p<n.length,w=c>0,j,S;if(M&&y.length>0){let x=y[y.length-1];j=a(x[l]);}if(w&&c>0){let x=n[c-1];S=a(x[l]);}return {result:b$1,result_info:{page:0,per_page:p,total_count:r,has_next_page:M,has_prev_page:w,next_cursor:j,prev_cursor:S}}}let o=t.options.page||1,s=t.options.per_page||this.defaultPerPage,i=(o-1)*s,d=n.slice(i,i+s),g={relations:t.options.include||[]},O=d.map(l=>v(l,this._meta,g)),h=Math.ceil(r/s);return {result:O,result_info:{page:o,per_page:s,total_count:r,total_pages:h,has_next_page:o<h,has_prev_page:o>1}}}},ce=class extends z{async restore(t,a){let n=m(this._meta.model.tableName),e=n.get(t),r=this.getSoftDeleteConfig();if(!e)return null;let o=e[r.field];if(o==null)return null;if(a){for(let[i,d]of Object.entries(a))if(String(e[i])!==d)return null}let s={...e,[r.field]:null};return n.set(t,s),s}};var ue=class extends B{generateId(){return crypto.randomUUID()}async batchCreate(t){let a=m(this._meta.model.tableName),n=this._meta.model.primaryKeys[0],e=[];for(let r of t){let o=this.applyManagedInsertFields(r,"memory",()=>this.generateId()),s=String(o[n]);a.set(s,o),e.push(o);}return e}},me=class extends C{async batchUpdate(t){let a=m(this._meta.model.tableName),n=this.getSoftDeleteConfig(),e=[],r=[];for(let o of t){let s=a.get(o.id);if(!s){r.push(o.id);continue}if(!R(s,n)){r.push(o.id);continue}let i={...s,...this.applyManagedUpdateFields(o.data)};a.set(o.id,i),e.push(i);}return {updated:e,notFound:r}}},ge=class extends D{async batchDelete(t){let a=m(this._meta.model.tableName),n=this.getSoftDeleteConfig(),e=[],r=[];for(let o of t){let s=a.get(o);if(!s){r.push(o);continue}if(!R(s,n)){r.push(o);continue}if(n.enabled){let i={...s,[n.field]:new Date};a.set(o,i),e.push(i);}else a.delete(o),e.push(s);}return {deleted:e,notFound:r}}},pe=class extends E$1{async batchRestore(t){let a=m(this._meta.model.tableName),n=this.getSoftDeleteConfig(),e=[],r=[];for(let o of t){let s=a.get(o);if(!s){r.push(o);continue}let i=s[n.field];if(i==null){r.push(o);continue}let d={...s,[n.field]:null};a.set(o,d),e.push(d);}return {restored:e,notFound:r}}},fe=class extends F{generateId(){return crypto.randomUUID()}async findExisting(t){let a=m(this._meta.model.tableName),n=this.getUpsertKeys();for(let e of a.values()){let r=true;for(let o of n){let s=t[o],i=e[o];if(s!==i){r=false;break}}if(r)return e}return null}async create(t){let a=m(this._meta.model.tableName),n=this._meta.model.primaryKeys[0],e=this.applyManagedInsertFields(t,"memory",()=>this.generateId());return a.set(String(e[n]),e),e}async update(t,a){let n=m(this._meta.model.tableName),e=this._meta.model.primaryKeys[0],r=String(t[e]),o={...t,...this.applyManagedUpdateFields(a)};return n.set(r,o),o}async nativeBatchUpsert(t,a){let n=m(this._meta.model.tableName),e=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],o=[],s=0,i=0;for(let d=0;d<t.length;d++){let g=t[d],O=null;for(let h of n.values()){let l=true;for(let p of e){let c=g[p],y=h[p];if(c!==y){l=false;break}}if(l){O=h;break}}if(O){let h={...g};if(this.createOnlyFields)for(let c of this.createOnlyFields)delete h[c];let l=String(O[r]),p={...O,...this.applyManagedUpdateFields(h)};n.set(l,p),o.push({data:p,created:false,index:d}),i++;}else {let h={...g};if(this.updateOnlyFields)for(let c of this.updateOnlyFields)delete h[c];let l=this.applyManagedInsertFields(h,"memory",()=>this.generateId()),p=String(l[r]);n.set(p,l),o.push({data:l,created:true,index:d}),s++;}}return {items:o,createdCount:s,updatedCount:i,totalCount:o.length}}};var _=class extends m$1{maxBulkSize=1e3;confirmThreshold=100;returnRecords=false;hookMode="parallel";filterFields;getSchema(){return {request:{body:{content:{"application/json":{schema:this.getUpdateSchema().partial()}}},query:z$1.object({dryRun:z$1.string().optional()}).passthrough()},responses:{200:{description:"Bulk patch result",content:{"application/json":{schema:z$1.object({success:z$1.boolean(),matched:z$1.number(),updated:z$1.number(),dryRun:z$1.boolean()})}}},400:{description:"Bad request",content:{"application/json":{schema:z$1.object({success:z$1.boolean(),error:z$1.string()})}}}}}}async handle(){let t=this.getContext(),n=(await this.getValidatedData()).body;if(!n||Object.keys(n).length===0)return this.error("Request body is required with at least one field to update","EMPTY_BODY",400);let e=t.req.query("dryRun"),r=e==="true"||e==="1",o$1=o(t.req.query(),{filterFields:this.filterFields,defaultPerPage:this.maxBulkSize,maxPerPage:this.maxBulkSize}),s=await this.countMatching(o$1);if(s===0)return this.json({success:true,matched:0,updated:0,dryRun:r});if(s>this.maxBulkSize)return this.error(`Bulk patch affects ${s} records, exceeding the maximum of ${this.maxBulkSize}. Use more specific filters.`,"BULK_TOO_LARGE",400);if(s>=this.confirmThreshold&&t.req.header("X-Confirm-Bulk")!=="true")return this.error(`This operation will affect ${s} records. Set X-Confirm-Bulk: true header to confirm.`,"CONFIRMATION_REQUIRED",400);if(r)return this.json({success:true,matched:s,updated:0,dryRun:true});let i=n;this.beforeBulkPatch&&(i=await this.beforeBulkPatch(i,o$1,s));let d=await this.applyPatch(i,o$1),g={matched:s,updated:d.updated,dryRun:false,records:this.returnRecords?d.records:void 0};return this.afterBulkPatch&&await this.afterBulkPatch(g),this.json({success:true,matched:g.matched,updated:g.updated,dryRun:false,...this.returnRecords&&g.records?{records:g.records}:{}})}};var Me=class extends y{generateId(){return crypto.randomUUID()}async findSource(t,a){let e=m(this._meta.model.tableName).get(t),r=this.getSoftDeleteConfig();return !e||!R(e,r,a)?null:e}async createClone(t){let a=m(this._meta.model.tableName),n=this._meta.model.primaryKeys[0],e=this.applyManagedInsertFields(t,"memory",()=>this.generateId()),r=String(e[n]);return a.set(r,e),e}},be=class extends A{generateId(){return crypto.randomUUID()}async findExisting(t){let a=m(this._meta.model.tableName),n=this.getUpsertKeys(),e=this.getSoftDeleteConfig();for(let r of a.values()){if(e.enabled){let s=r[e.field];if(s!=null)continue}let o=true;for(let s of n){let i=t[s],d=r[s];if(i!==d){o=false;break}}if(o)return r}return null}async create(t){let a=m(this._meta.model.tableName),n=this._meta.model.primaryKeys[0],e=this.applyManagedInsertFields(t,"memory",()=>this.generateId());return a.set(String(e[n]),e),e}async update(t,a){let n=m(this._meta.model.tableName),e=this._meta.model.primaryKeys[0],r=String(t[e]),o={...t,...this.applyManagedUpdateFields(a)};return n.set(r,o),o}async nativeUpsert(t,a){let n=m(this._meta.model.tableName),e=this.getUpsertKeys(),r=this._meta.model.primaryKeys[0],o=this.getSoftDeleteConfig(),s=null;for(let i of n.values()){if(o.enabled){let g=i[o.field];if(g!=null)continue}let d=true;for(let g of e){let O=t[g],h=i[g];if(O!==h){d=false;break}}if(d){s=i;break}}if(s){let i={...t};if(this.createOnlyFields)for(let O of this.createOnlyFields)delete i[O];let d=String(s[r]),g={...s,...this.applyManagedUpdateFields(i)};return n.set(d,g),{data:g,created:false}}else {let i={...t};if(this.updateOnlyFields)for(let O of this.updateOnlyFields)delete i[O];let d=this.applyManagedInsertFields(i,"memory",()=>this.generateId()),g=String(d[r]);return n.set(g,d),{data:d,created:true}}}async processNestedWrites(t,a,n,e){let r=m(n.model),o={created:[],updated:[],deleted:[],connected:[],disconnected:[]};if(e.create){let s=Array.isArray(e.create)?e.create:[e.create];for(let i of s){if(typeof i!="object"||i===null)continue;let d={...i,id:crypto.randomUUID(),[n.foreignKey]:t};r.set(d.id,d),o.created.push(d);}}if(e.update)for(let s of e.update){let i=String(s.id),d=r.get(i);if(d&&d[n.foreignKey]===t){let g={...d,...s};r.set(i,g),o.updated.push(g);}}if(e.delete)for(let s of e.delete){let i=String(s),d=r.get(i);d&&d[n.foreignKey]===t&&(r.delete(i),o.deleted.push(s));}if(e.connect)for(let s of e.connect){let i=String(s),d=r.get(i);if(d){let g={...d,[n.foreignKey]:t};r.set(i,g),o.connected.push(s);}}if(e.disconnect)for(let s of e.disconnect){let i=String(s),d=r.get(i);if(d&&d[n.foreignKey]===t){let g={...d,[n.foreignKey]:null};r.set(i,g),o.disconnected.push(s);}}return o}},he=class extends G{async recordExists(t){return m(this._meta.model.tableName).has(t)}},ye=class extends H{},Oe=class extends I{},xe=class extends J{async rollback(t,a,n){let e=m(this._meta.model.tableName),r=this.getVersioningConfig().field,o={...a,[r]:n};return e.set(t,o),o}},Re=class extends K{async aggregate(t){let a=m(this._meta.model.tableName),n=Array.from(a.values()),e=this.getSoftDeleteConfig();if(e.enabled){let{query:r}=await this.getValidatedData();r?.withDeleted===true||r?.withDeleted==="true"||(n=n.filter(s=>{let i=s[e.field];return i==null}));}if(t.filters)for(let[r,o]of Object.entries(t.filters))n=n.filter(s=>{if(typeof o=="object"&&o!==null){for(let[i,d]of Object.entries(o)){let g=s[r];switch(i){case "eq":return String(g)===String(d);case "ne":return String(g)!==String(d);case "gt":return Number(g)>Number(d);case "gte":return Number(g)>=Number(d);case "lt":return Number(g)<Number(d);case "lte":return Number(g)<=Number(d);case "in":return d.map(String).includes(String(g));default:return true}}return true}return String(s[r])===String(o)});return L(n,t)}},ke=class extends T{async search(t,a){let n=m(this._meta.model.tableName),e=Array.from(n.values()),r=this.getSoftDeleteConfig();r.enabled&&(a.options.onlyDeleted?e=e.filter(f=>{let b=f[r.field];return b!=null}):a.options.withDeleted||(e=e.filter(f=>{let b=f[r.field];return b==null})));for(let f of a.filters)e=e.filter(b=>{let M=b[f.field];switch(f.operator){case "eq":return String(M)===String(f.value);case "ne":return String(M)!==String(f.value);case "gt":return Number(M)>Number(f.value);case "gte":return Number(M)>=Number(f.value);case "lt":return Number(M)<Number(f.value);case "lte":return Number(M)<=Number(f.value);case "in":return f.value.map(String).includes(String(M));case "nin":return !f.value.map(String).includes(String(M));case "like":return String(M).includes(String(f.value).replace(/%/g,""));case "ilike":return String(M).toLowerCase().includes(String(f.value).replace(/%/g,"").toLowerCase());case "null":return f.value?M===null:M!==null;case "between":{let[w,j]=f.value;return Number(M)>=Number(w)&&Number(M)<=Number(j)}default:return true}});let o=this.getSearchableFields(),s=e,i=t;if(t.mode==="all"){let f=t.query.toLowerCase().split(/\s+/).filter(M=>M.length>0),b=t.fields||Object.keys(o);f.length>0&&(s=s.filter(M=>{let w=M;return f.every(j=>b.some(S=>{let x=w[S];return x==null?false:(Array.isArray(x)?x.join(" "):String(x)).toLowerCase().includes(j)}))})),i={...t,mode:"any"};}let d=U(s,i,o),g=d.length;if(a.options.order_by){let f=a.options.order_by,b=a.options.order_by_direction==="desc"?-1:1;d.sort((M,w)=>{let j=M.item[f],S=w.item[f];return j<S?-1*b:j>S?1*b:0});}let O=a.options.page||1,h=a.options.per_page||this.defaultPerPage,l=(O-1)*h,p=d.slice(l,l+h),c={relations:a.options.include||[]};return {items:p.map(f=>({...f,item:v(f.item,this._meta,c)})),totalCount:g}}},je=class extends ba{async list(t){let a=m(this._meta.model.tableName),n=Array.from(a.values()),e=this.getSoftDeleteConfig();e.enabled&&(t.options.onlyDeleted?n=n.filter(l=>{let p=l[e.field];return p!=null}):t.options.withDeleted||(n=n.filter(l=>{let p=l[e.field];return p==null})));for(let l of t.filters)n=n.filter(p=>{let c=p[l.field];switch(l.operator){case "eq":return String(c)===String(l.value);case "ne":return String(c)!==String(l.value);case "gt":return Number(c)>Number(l.value);case "gte":return Number(c)>=Number(l.value);case "lt":return Number(c)<Number(l.value);case "lte":return Number(c)<=Number(l.value);case "in":return l.value.map(String).includes(String(c));case "nin":return !l.value.map(String).includes(String(c));case "like":return String(c).includes(String(l.value).replace(/%/g,""));case "ilike":return String(c).toLowerCase().includes(String(l.value).replace(/%/g,"").toLowerCase());case "null":return l.value?c===null:c!==null;case "between":{let[y,f]=l.value;return Number(c)>=Number(y)&&Number(c)<=Number(f)}default:return true}});if(t.options.search&&this.searchFields.length>0){let l=t.options.search.toLowerCase();n=n.filter(p=>this.searchFields.some(c=>{let y=p[c];return String(y).toLowerCase().includes(l)}));}let r=n.length;if(t.options.order_by){let l=t.options.order_by,p=t.options.order_by_direction==="desc"?-1:1;n.sort((c,y)=>{let f=c[l],b=y[l];return f<b?-1*p:f>b?1*p:0});}let o=t.options.page||1,s=t.options.per_page||this.defaultPerPage,i=(o-1)*s,d=n.slice(i,i+s),g={relations:t.options.include||[]},O=d.map(l=>v(l,this._meta,g)),h=Math.ceil(r/s);return {result:O,result_info:{page:o,per_page:s,total_count:r,total_pages:h,has_next_page:o<h,has_prev_page:o>1}}}},we=class extends ca{generateId(){return crypto.randomUUID()}async findExisting(t){let a=m(this._meta.model.tableName),n=this.getUpsertKeys(),e=this.getSoftDeleteConfig();for(let r of a.values()){if(e.enabled){let s=r[e.field];if(s!=null)continue}let o=true;for(let s of n){let i=t[s],d=r[s];if(i!==d){o=false;break}}if(o)return r}return null}async create(t){let a=m(this._meta.model.tableName),n=this._meta.model.primaryKeys[0],e=this.applyManagedInsertFields(t,"memory",()=>this.generateId());return a.set(String(e[n]),e),e}async update(t,a){let n=m(this._meta.model.tableName),e=this._meta.model.primaryKeys[0],r=String(t[e]),o={...t,...this.applyManagedUpdateFields(a)};return n.set(r,o),o}},Se=class extends _{async countMatching(t){return this.getFilteredItems(t).length}async applyPatch(t,a){let n=m(this._meta.model.tableName),e=this._meta.model.primaryKeys[0],r=this.getFilteredItems(a),o=[];for(let s of r){let i=String(s[e]),d={...s,...t};n.set(i,d),o.push(d);}return {updated:o.length,records:o}}getFilteredItems(t){let a=m(this._meta.model.tableName),n=Array.from(a.values());for(let e of t.filters)n=n.filter(r=>{let o=r[e.field];switch(e.operator){case "eq":return String(o)===String(e.value);case "ne":return String(o)!==String(e.value);case "gt":return Number(o)>Number(e.value);case "gte":return Number(o)>=Number(e.value);case "lt":return Number(o)<Number(e.value);case "lte":return Number(o)<=Number(e.value);case "in":return e.value.map(String).includes(String(o));case "nin":return !e.value.map(String).includes(String(o));case "like":return String(o).includes(String(e.value).replace(/%/g,""));case "ilike":return String(o).toLowerCase().includes(String(e.value).replace(/%/g,"").toLowerCase());case "null":return e.value?o===null:o!==null;default:return true}});return n}};export{we as A,Se as B,_ as a,E as b,m as c,_e as d,Ie as e,P as f,se as g,ie as h,ae as i,de as j,le as k,ce as l,ue as m,me as n,ge as o,pe as p,fe as q,Me as r,be as s,he as t,ye as u,Oe as v,xe as w,Re as x,ke as y,je as z};
|