@hono-crud/drizzle 0.1.24 → 0.1.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # @hono-crud/drizzle
2
2
 
3
+ ## 0.1.25
4
+
5
+ ### Patch Changes
6
+
7
+ - 9912f26: Cursor pagination now walks both ways. Cursor-mode list responses carry `result_info.prev_cursor` next to `next_cursor`; either one goes back as `?cursor=`, and both pages come back in ascending order. `prev_cursor` is present only while rows precede the page, so the first page looks exactly as before.
8
+
9
+ - The keyset key is the cursor field plus the primary key (the same tie-break sorted reads use since #144), so a non-unique cursor field such as `createdAt` walks every row exactly once in both directions. Before, rows sharing a cursor value at a page boundary were skipped.
10
+ - Compatible with existing callers: when the cursor field is the only primary key (the default `id`), `next_cursor` keeps its old format (`encodeCursor(id)`), and cursors minted by earlier releases are still accepted. Other cursors are URL-safe `c2.` tokens that also carry Date values (timestamp cursor fields on D1).
11
+ - Prisma now uses the same WHERE keyset window as Drizzle and memory instead of its native `cursor` option, so a cursor whose boundary row was deleted continues the walk instead of returning an empty page.
12
+ - The typed RPC client sees `prev_cursor` on `ResultInfo` and `limit` on `CrudListQuery`; the OpenAPI list schema documents `prev_cursor`.
13
+ - `hono-crud/internal` exports the shared keyset helpers (`resolveCursorWindow`, `encodeKeysetCursor`, `decodeKeysetCursor`, `isPastCursor`, `cursorKeyFields`) for adapter authors.
14
+
15
+ - 578bbeb: FTS5 full-text search for SQLite and Cloudflare D1 in `DrizzleSearchEndpoint`.
16
+
17
+ - `defineFts5Index({ table, columns })` describes an external-content FTS5 index once. `index.migration()` returns the statements for the virtual table, the insert/update/delete sync triggers and an initial `'rebuild'` (ready for a D1/wrangler or drizzle-kit migration); `dropMigration()` and `rebuild()` cover teardown and re-indexing. Defaults: `unicode61 remove_diacritics 2` tokenizer (case- and accent-insensitive) and `prefix='2 3'` indexes. A `casing` option matches `drizzle(client, { casing: 'snake_case' })` for columns declared without explicit names.
18
+ - `protected fts5 = index` on a Drizzle search endpoint switches it to an FTS5 `MATCH` ranked by `bm25()` in SQL (weighted by `fieldWeights`), before pagination, so pages are globally ordered and `total_count`/`minScore` are exact. The last term is a prefix by default (`fts5PrefixMatch: 'last' | 'all' | 'none'`), `any`/`all`/`phrase` map to `OR`/`AND`/phrase, and `?fields=` becomes an FTS5 column filter.
19
+ - User input is compiled to quoted FTS5 terms and bound as a parameter: FTS5 operators typed by users are plain text and never cause a syntax error.
20
+ - `?highlight=true` returns FTS5 `snippet()`s with the text HTML-escaped and matches wrapped in `highlightTag`.
21
+ - Soft-delete, filters and tenant scope apply exactly as on List (the shared WHERE builder is now `buildDrizzleListWhere`). A non-`sqlite` dialect or a searchable field that is not indexed is a 500 `CONFIGURATION_ERROR`.
22
+ - `hono-crud/internal` now exports the `SearchFieldConfig` and `SearchMode` types for adapters.
23
+
24
+ - baf37a9: Read-side hooks and adapter methods are typed as the stored row (`InferModelRow`) instead of the public schema: every `after` hook (class, builder, functional and config APIs), clone's `before`, `computedFields[].compute`, `policies.read`/`write`/`fields`, and the adapter methods that read or return records (`read`, `list`, `search`, `findExisting`, `create`'s return, and the rest). A Drizzle `Delete.after(prior)` can read `prior.r2Key` without a cast. Request bodies, `before` hooks on create/update/upsert/import, and `transform` keep the schema type. Migration: overrides annotated with the schema type fail to compile where a Drizzle row differs from the schema (a `text` column behind a `z.enum`, a JSON text column behind `z.array`); annotate them with `InferModelRow<typeof Model>` or drop the annotation.
25
+
3
26
  ## 0.1.24
4
27
 
5
28
  ### Patch Changes
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { MetaInput, IncludeOptions, FilterCondition, RelationConfig, CreateEndpoint, ModelObject, ReadEndpoint, UpdateEndpoint, NestedUpdateInput, NestedWriteResult, DeleteEndpoint, ListEndpoint, ListFilters, PaginatedResult, RestoreEndpoint, BatchCreateEndpoint, BatchDeleteEndpoint, BatchRestoreEndpoint, BatchUpdateEndpoint, BatchUpdateItem, AggregateEndpoint, AggregateOptions, AggregateResult, BatchUpsertEndpoint, BulkPatchEndpoint, CloneEndpoint, UpsertEndpoint, SearchEndpoint, SearchOptions, SearchResult, ExportEndpoint, ImportEndpoint, VersionCompareEndpoint, VersionHistoryEndpoint, VersionReadEndpoint, VersionRollbackEndpoint, VersioningStorage, VersionHistoryEntry, AuditLogStorage, AuditLogEntry, AuditAction, AdapterBundle } from 'hono-crud/internal';
1
+ import { MetaInput, IncludeOptions, FilterCondition, RelationConfig, CreateEndpoint, ModelObject, InferModelRow, ReadEndpoint, UpdateEndpoint, NestedUpdateInput, NestedWriteResult, DeleteEndpoint, ListEndpoint, ListFilters, PaginatedResult, RestoreEndpoint, BatchCreateEndpoint, BatchDeleteEndpoint, BatchRestoreEndpoint, BatchUpdateEndpoint, BatchUpdateItem, SearchMode, AggregateEndpoint, AggregateOptions, AggregateResult, BatchUpsertEndpoint, BulkPatchEndpoint, CloneEndpoint, UpsertEndpoint, SearchEndpoint, SearchFieldConfig, SearchOptions, SearchResult, ExportEndpoint, ImportEndpoint, VersionCompareEndpoint, VersionHistoryEndpoint, VersionReadEndpoint, VersionRollbackEndpoint, VersioningStorage, VersionHistoryEntry, AuditLogStorage, AuditLogEntry, AuditAction, AdapterBundle } from 'hono-crud/internal';
2
2
  import { Env } from 'hono';
3
3
  import * as drizzle_orm from 'drizzle-orm';
4
4
  import { BuildColumns } from 'drizzle-orm';
@@ -43,6 +43,7 @@ interface DrizzleSql {
43
43
  */
44
44
  interface QueryBuilder<Row = unknown> extends PromiseLike<Row[]> {
45
45
  where(condition: unknown): QueryBuilder<Row>;
46
+ innerJoin(source: unknown, on: unknown): QueryBuilder<Row>;
46
47
  limit(n: number): QueryBuilder<Row>;
47
48
  offset(n: number): QueryBuilder<Row>;
48
49
  orderBy(...columns: unknown[]): QueryBuilder<Row>;
@@ -79,8 +80,9 @@ interface Database<Row = unknown> {
79
80
  * Casts a database handle to the internal {@link Database} interface for method
80
81
  * calls, parametrized over the row type `Row` that queries resolve to. This is
81
82
  * the single sanctioned boundary `as`: all Drizzle databases expose these
82
- * methods at runtime, and the row type derives from the consumer's Zod schema
83
- * (`ModelObject<M['model']>`), never from a drizzle-orm type.
83
+ * methods at runtime, and the row type is the model's stored row
84
+ * (`InferModelRow<M['model']>`: the table's `$inferSelect` matched
85
+ * structurally), never an imported drizzle-orm type.
84
86
  */
85
87
  declare function cast<Row = unknown>(instance: unknown): Database<Row>;
86
88
  /**
@@ -291,7 +293,7 @@ declare abstract class DrizzleCreateEndpoint<E extends Env = Env, M extends Meta
291
293
  * Gets a related table from the relation config.
292
294
  */
293
295
  protected getRelatedTable(relationConfig: RelationConfig): DrizzleTable | undefined;
294
- create(data: ModelObject<M['model']>, tx?: unknown): Promise<ModelObject<M['model']>>;
296
+ create(data: ModelObject<M['model']>, tx?: unknown): Promise<InferModelRow<M['model']>>;
295
297
  /**
296
298
  * Creates nested related records.
297
299
  */
@@ -317,7 +319,7 @@ declare abstract class DrizzleReadEndpoint<E extends Env = Env, M extends MetaIn
317
319
  protected getDb(): DB;
318
320
  protected getTable(): DrizzleTable;
319
321
  protected getColumn(field: string): DrizzleColumn;
320
- read(lookupValue: string, additionalFilters?: Record<string, string>, includeOptions?: IncludeOptions): Promise<ModelObject<M['model']> | null>;
322
+ read(lookupValue: string, additionalFilters?: Record<string, string>, includeOptions?: IncludeOptions): Promise<InferModelRow<M['model']> | null>;
321
323
  }
322
324
  /**
323
325
  * Drizzle Update endpoint.
@@ -350,8 +352,8 @@ declare abstract class DrizzleUpdateEndpoint<E extends Env = Env, M extends Meta
350
352
  /**
351
353
  * Finds an existing record for audit logging.
352
354
  */
353
- protected findExisting(lookupValue: string, additionalFilters?: Record<string, string>, tx?: unknown): Promise<ModelObject<M['model']> | null>;
354
- update(lookupValue: string, data: Partial<ModelObject<M['model']>>, additionalFilters?: Record<string, string>, tx?: unknown): Promise<ModelObject<M['model']> | null>;
355
+ protected findExisting(lookupValue: string, additionalFilters?: Record<string, string>, tx?: unknown): Promise<InferModelRow<M['model']> | null>;
356
+ update(lookupValue: string, data: Partial<ModelObject<M['model']>>, additionalFilters?: Record<string, string>, tx?: unknown): Promise<InferModelRow<M['model']> | null>;
355
357
  /**
356
358
  * Processes nested write operations.
357
359
  */
@@ -392,8 +394,8 @@ declare abstract class DrizzleDeleteEndpoint<E extends Env = Env, M extends Meta
392
394
  /**
393
395
  * Finds a record without deleting it (for constraint checks).
394
396
  */
395
- findForDelete(lookupValue: string, additionalFilters?: Record<string, string>, tx?: unknown): Promise<ModelObject<M['model']> | null>;
396
- delete(lookupValue: string, additionalFilters?: Record<string, string>, tx?: unknown): Promise<ModelObject<M['model']> | null>;
397
+ findForDelete(lookupValue: string, additionalFilters?: Record<string, string>, tx?: unknown): Promise<InferModelRow<M['model']> | null>;
398
+ delete(lookupValue: string, additionalFilters?: Record<string, string>, tx?: unknown): Promise<InferModelRow<M['model']> | null>;
397
399
  /**
398
400
  * Counts related records for restrict check.
399
401
  */
@@ -437,13 +439,13 @@ declare abstract class DrizzleListEndpoint<E extends Env = Env, M extends MetaIn
437
439
  * See {@link DrizzleUpsertEndpoint.dialect} for full semantics.
438
440
  */
439
441
  protected dialect: DrizzleDialect;
440
- /** Keyset cursor pagination is implemented (`WHERE cursorField > decoded`). */
442
+ /** Keyset cursor pagination is implemented (both directions, PK tie-break). */
441
443
  protected supportsCursorPagination: boolean;
442
444
  /** Gets the database instance from property or context */
443
445
  protected getDb(): DB;
444
446
  protected getTable(): DrizzleTable;
445
447
  protected getColumn(field: string): DrizzleColumn;
446
- list(filters: ListFilters): Promise<PaginatedResult<ModelObject<M['model']>>>;
448
+ list(filters: ListFilters): Promise<PaginatedResult<InferModelRow<M['model']>>>;
447
449
  }
448
450
  /**
449
451
  * Drizzle Restore endpoint for un-deleting soft-deleted records.
@@ -467,7 +469,7 @@ declare abstract class DrizzleRestoreEndpoint<E extends Env = Env, M extends Met
467
469
  protected getDb(): DB;
468
470
  protected getTable(): DrizzleTable;
469
471
  protected getColumn(field: string): DrizzleColumn;
470
- restore(lookupValue: string, additionalFilters?: Record<string, string>, tx?: unknown): Promise<ModelObject<M['model']> | null>;
472
+ restore(lookupValue: string, additionalFilters?: Record<string, string>, tx?: unknown): Promise<InferModelRow<M['model']> | null>;
471
473
  /**
472
474
  * Override handle to wrap in transaction when useTransaction is true.
473
475
  */
@@ -486,7 +488,7 @@ declare abstract class DrizzleBatchCreateEndpoint<E extends Env = Env, M extends
486
488
  protected getTable(): DrizzleTable;
487
489
  /** Column-aware managed timestamp (Date / epoch ms / ISO string) — see `timestamps.ts`. */
488
490
  protected managedTimestampValue(field: string): unknown;
489
- batchCreate(items: Partial<ModelObject<M['model']>>[]): Promise<ModelObject<M['model']>[]>;
491
+ batchCreate(items: Partial<ModelObject<M['model']>>[]): Promise<InferModelRow<M['model']>[]>;
490
492
  }
491
493
  /**
492
494
  * Drizzle Batch Update endpoint.
@@ -504,7 +506,7 @@ declare abstract class DrizzleBatchUpdateEndpoint<E extends Env = Env, M extends
504
506
  protected managedTimestampValue(field: string): unknown;
505
507
  protected getColumn(field: string): DrizzleColumn;
506
508
  batchUpdate(items: BatchUpdateItem<ModelObject<M['model']>>[]): Promise<{
507
- updated: ModelObject<M['model']>[];
509
+ updated: InferModelRow<M['model']>[];
508
510
  notFound: string[];
509
511
  }>;
510
512
  }
@@ -524,7 +526,7 @@ declare abstract class DrizzleBatchDeleteEndpoint<E extends Env = Env, M extends
524
526
  protected managedTimestampValue(field: string): unknown;
525
527
  protected getColumn(field: string): DrizzleColumn;
526
528
  batchDelete(ids: string[]): Promise<{
527
- deleted: ModelObject<M['model']>[];
529
+ deleted: InferModelRow<M['model']>[];
528
530
  notFound: string[];
529
531
  }>;
530
532
  }
@@ -542,11 +544,137 @@ declare abstract class DrizzleBatchRestoreEndpoint<E extends Env = Env, M extend
542
544
  protected getTable(): DrizzleTable;
543
545
  protected getColumn(field: string): DrizzleColumn;
544
546
  batchRestore(ids: string[]): Promise<{
545
- restored: ModelObject<M['model']>[];
547
+ restored: InferModelRow<M['model']>[];
546
548
  notFound: string[];
547
549
  }>;
548
550
  }
549
551
 
552
+ /** Default FTS5 tokenizer: Unicode-aware, accent-insensitive (`ação` ≡ `acao`). */
553
+ declare const DEFAULT_FTS5_TOKENIZE = "unicode61 remove_diacritics 2";
554
+ /** Default FTS5 prefix indexes (fast `ab*` / `abc*` prefix queries). */
555
+ declare const DEFAULT_FTS5_PREFIX_INDEX: readonly number[];
556
+ /** Configuration accepted by {@link defineFts5Index}. */
557
+ interface Fts5IndexConfig {
558
+ /**
559
+ * The Drizzle table whose rows are indexed. It becomes the FTS5
560
+ * external-content table: the index stores only tokens, and reads row text
561
+ * (for `snippet()`) back from this table.
562
+ */
563
+ table: DrizzleTable;
564
+ /**
565
+ * Model fields to index, in FTS5 column order (Drizzle property names; the
566
+ * index uses their database column names). Text columns only.
567
+ */
568
+ columns: readonly string[];
569
+ /** FTS5 virtual table name. Defaults to `<table>_fts`. */
570
+ name?: string;
571
+ /**
572
+ * The `casing` your Drizzle database is created with (`drizzle(client, {
573
+ * casing })`). Columns declared without an explicit name are then stored
574
+ * under the converted name (`titlePt` → `title_pt`), and the generated SQL
575
+ * must use it too. Omit when columns carry explicit names or no casing is
576
+ * configured.
577
+ */
578
+ casing?: 'snake_case' | 'camelCase';
579
+ /**
580
+ * Integer column linking index rows to content rows (FTS5
581
+ * `content_rowid`). Defaults to SQLite's implicit `rowid`, which is right
582
+ * for any rowid table. Set it to a model field when the table has an
583
+ * `INTEGER PRIMARY KEY` you want to name explicitly.
584
+ */
585
+ contentRowid?: string;
586
+ /** FTS5 `tokenize` option. Defaults to {@link DEFAULT_FTS5_TOKENIZE}. */
587
+ tokenize?: string;
588
+ /**
589
+ * FTS5 `prefix` option: token-prefix lengths to index for fast prefix
590
+ * queries. Defaults to {@link DEFAULT_FTS5_PREFIX_INDEX}; `[]` disables
591
+ * prefix indexes (prefix queries still work, just slower).
592
+ */
593
+ prefixIndex?: readonly number[];
594
+ }
595
+ /** An FTS5 index definition (see {@link defineFts5Index}). */
596
+ interface Fts5Index {
597
+ /** FTS5 virtual table name. */
598
+ readonly name: string;
599
+ /** The content table (the Drizzle table passed in). */
600
+ readonly table: DrizzleTable;
601
+ /** Content table's database name. */
602
+ readonly tableName: string;
603
+ /** Indexed model fields, in FTS5 column order. */
604
+ readonly fields: readonly string[];
605
+ /** Database column names of {@link fields}, in the same order. */
606
+ readonly columnNames: readonly string[];
607
+ /** Content-rowid model field, or `undefined` for SQLite's implicit `rowid`. */
608
+ readonly contentRowid?: string;
609
+ /** Database column name of {@link contentRowid} (`'rowid'` when unset). */
610
+ readonly contentRowidColumn: string;
611
+ /**
612
+ * SQL statements that create the index, keep it in sync, and fill it from
613
+ * existing rows: `CREATE VIRTUAL TABLE`, the insert/delete/update triggers,
614
+ * and a `'rebuild'`. Idempotent (`IF NOT EXISTS`). Each entry is one
615
+ * complete statement — run them in order (a D1 batch, a wrangler/drizzle-kit
616
+ * migration file, or one `db.run(sql.raw(statement))` each).
617
+ */
618
+ migration(): string[];
619
+ /** SQL statements that drop the triggers and the virtual table. */
620
+ dropMigration(): string[];
621
+ /**
622
+ * The `'rebuild'` statement: re-reads every content row into the index.
623
+ * Run it after bulk changes that bypass the triggers, or after a `VACUUM`
624
+ * on a table without an `INTEGER PRIMARY KEY` (which may renumber rowids).
625
+ */
626
+ rebuild(): string;
627
+ }
628
+ /**
629
+ * Describes an external-content FTS5 index over a Drizzle SQLite/D1 table.
630
+ * Validation runs at definition time and throws a plain `Error` (fail fast
631
+ * at boot).
632
+ *
633
+ * @example
634
+ * ```ts
635
+ * export const gamesFts = defineFts5Index({
636
+ * table: games,
637
+ * columns: ['title', 'description'],
638
+ * });
639
+ * // migration: gamesFts.migration() → CREATE VIRTUAL TABLE + triggers
640
+ * class GameSearch extends DrizzleSearchEndpoint {
641
+ * _meta = gameMeta;
642
+ * protected override fts5 = gamesFts;
643
+ * }
644
+ * ```
645
+ */
646
+ declare function defineFts5Index(config: Fts5IndexConfig): Fts5Index;
647
+ /** Which search terms get FTS5 prefix matching (`term*`). */
648
+ type Fts5PrefixMatch = 'last' | 'all' | 'none';
649
+ /** Options for {@link buildFts5Match}. */
650
+ interface Fts5MatchOptions {
651
+ /** `any` → OR, `all` → AND, `phrase` → one phrase. */
652
+ mode: SearchMode;
653
+ /** Prefix-match policy. Defaults to `'last'` (search-as-you-type). */
654
+ prefix?: Fts5PrefixMatch;
655
+ /**
656
+ * Restrict the match to these FTS5 column names (an FTS5 column filter).
657
+ * Omit to search every indexed column.
658
+ */
659
+ columns?: readonly string[];
660
+ }
661
+ /**
662
+ * Splits user input into FTS5 terms: whitespace-separated chunks that contain
663
+ * at least one letter or digit (pure punctuation yields no FTS5 token).
664
+ */
665
+ declare function tokenizeFts5Query(query: string): string[];
666
+ /**
667
+ * Compiles user search text into a safe FTS5 query expression, or `null`
668
+ * when it contains no searchable term.
669
+ *
670
+ * Every term is emitted as a quoted FTS5 string, so FTS5 operators typed by
671
+ * the user (`AND`, `OR`, `NOT`, `NEAR`, `*`, `^`, `:`, parentheses, column
672
+ * filters) are inert text and the expression is always syntactically valid —
673
+ * malformed input can never surface as an `fts5: syntax error`. Prefix
674
+ * matching appends `*` outside the quotes.
675
+ */
676
+ declare function buildFts5Match(query: string, options: Fts5MatchOptions): string | null;
677
+
550
678
  /**
551
679
  * Drizzle Upsert endpoint.
552
680
  * Creates a record if it doesn't exist, updates it if it does.
@@ -570,9 +698,9 @@ declare abstract class DrizzleUpsertEndpoint<E extends Env = Env, M extends Meta
570
698
  /** Column-aware managed timestamp (Date / epoch ms / ISO string) — see `timestamps.ts`. */
571
699
  protected managedTimestampValue(field: string): unknown;
572
700
  protected getColumn(field: string): DrizzleColumn;
573
- findExisting(data: Partial<ModelObject<M['model']>>): Promise<ModelObject<M['model']> | null>;
574
- create(data: Partial<ModelObject<M['model']>>): Promise<ModelObject<M['model']>>;
575
- update(existing: ModelObject<M['model']>, data: Partial<ModelObject<M['model']>>): Promise<ModelObject<M['model']>>;
701
+ findExisting(data: Partial<ModelObject<M['model']>>): Promise<InferModelRow<M['model']> | null>;
702
+ create(data: Partial<ModelObject<M['model']>>): Promise<InferModelRow<M['model']>>;
703
+ update(existing: InferModelRow<M['model']>, data: Partial<ModelObject<M['model']>>): Promise<InferModelRow<M['model']>>;
576
704
  /**
577
705
  * Performs a native database upsert using ON CONFLICT DO UPDATE (PostgreSQL/SQLite)
578
706
  * or ON DUPLICATE KEY UPDATE (MySQL).
@@ -589,7 +717,7 @@ declare abstract class DrizzleUpsertEndpoint<E extends Env = Env, M extends Meta
589
717
  * rather than unified.
590
718
  */
591
719
  protected nativeUpsert(data: Partial<ModelObject<M['model']>>, _tx?: unknown): Promise<{
592
- data: ModelObject<M['model']>;
720
+ data: InferModelRow<M['model']>;
593
721
  created: boolean;
594
722
  }>;
595
723
  }
@@ -610,9 +738,9 @@ declare abstract class DrizzleBatchUpsertEndpoint<E extends Env = Env, M extends
610
738
  /** Column-aware managed timestamp (Date / epoch ms / ISO string) — see `timestamps.ts`. */
611
739
  protected managedTimestampValue(field: string): unknown;
612
740
  protected getColumn(field: string): DrizzleColumn;
613
- findExisting(data: Partial<ModelObject<M['model']>>): Promise<ModelObject<M['model']> | null>;
614
- create(data: Partial<ModelObject<M['model']>>): Promise<ModelObject<M['model']>>;
615
- update(existing: ModelObject<M['model']>, data: Partial<ModelObject<M['model']>>): Promise<ModelObject<M['model']>>;
741
+ findExisting(data: Partial<ModelObject<M['model']>>): Promise<InferModelRow<M['model']> | null>;
742
+ create(data: Partial<ModelObject<M['model']>>): Promise<InferModelRow<M['model']>>;
743
+ update(existing: InferModelRow<M['model']>, data: Partial<ModelObject<M['model']>>): Promise<InferModelRow<M['model']>>;
616
744
  /**
617
745
  * Performs a native database batch upsert using ON CONFLICT DO UPDATE (PostgreSQL/SQLite)
618
746
  * or ON DUPLICATE KEY UPDATE (MySQL).
@@ -630,7 +758,7 @@ declare abstract class DrizzleBatchUpsertEndpoint<E extends Env = Env, M extends
630
758
  */
631
759
  protected nativeBatchUpsert(items: Partial<ModelObject<M['model']>>[], _tx?: unknown): Promise<{
632
760
  items: Array<{
633
- data: ModelObject<M['model']>;
761
+ data: InferModelRow<M['model']>;
634
762
  created: boolean;
635
763
  index: number;
636
764
  }>;
@@ -670,7 +798,7 @@ declare abstract class DrizzleBulkPatchEndpoint<E extends Env = Env, M extends M
670
798
  countMatching(filters: ListFilters): Promise<number>;
671
799
  applyPatch(data: Partial<ModelObject<M['model']>>, filters: ListFilters): Promise<{
672
800
  updated: number;
673
- records?: ModelObject<M['model']>[];
801
+ records?: InferModelRow<M['model']>[];
674
802
  }>;
675
803
  }
676
804
  /**
@@ -735,7 +863,7 @@ declare abstract class DrizzleVersionRollbackEndpoint<E extends Env = Env, M ext
735
863
  field: string;
736
864
  value: string;
737
865
  }): Promise<boolean>;
738
- rollback(lookupValue: string, versionData: Record<string, unknown>, newVersion: number): Promise<ModelObject<M['model']>>;
866
+ rollback(lookupValue: string, versionData: Record<string, unknown>, newVersion: number): Promise<InferModelRow<M['model']>>;
739
867
  }
740
868
  /**
741
869
  * Drizzle Aggregate endpoint.
@@ -760,10 +888,13 @@ declare abstract class DrizzleAggregateEndpoint<E extends Env = Env, M extends M
760
888
  * Provides full-text search with relevance scoring and highlighting.
761
889
  *
762
890
  * For PostgreSQL, this can leverage native tsvector/tsquery for better performance.
763
- * For SQLite/MySQL/PostgreSQL non-vector mode, it falls back to dialect-native
764
- * substring-position search (INSTR/POSITION/LOCATE) with in-memory scoring.
891
+ * For SQLite / Cloudflare D1, set {@link DrizzleSearchEndpoint.fts5} to an
892
+ * index from `defineFts5Index()` for FTS5 full-text search ranked by bm25.
893
+ * Otherwise it falls back to dialect-native substring-position search
894
+ * (INSTR/POSITION/LOCATE) with in-memory scoring.
765
895
  *
766
896
  * Features:
897
+ * - SQLite/D1: FTS5 MATCH with bm25 ranking, prefix matching and snippets
767
898
  * - PostgreSQL: Uses to_tsvector() and plainto_tsquery() for native full-text search
768
899
  * - Fallback: dialect-native substring match with in-memory scoring
769
900
  * - Configurable field weights
@@ -816,12 +947,41 @@ declare abstract class DrizzleSearchEndpoint<E extends Env = Env, M extends Meta
816
947
  * PostgreSQL text search configuration (e.g., 'english', 'simple').
817
948
  */
818
949
  protected vectorConfig: string;
950
+ /**
951
+ * SQLite / D1 FTS5 index (from `defineFts5Index()`). When set, search runs
952
+ * as an FTS5 `MATCH` against this external-content index: rows are ranked
953
+ * by `bm25()` in SQL (weighted by the searchable fields' weights) before
954
+ * pagination, prefix matching follows {@link fts5PrefixMatch}, and
955
+ * highlights come from FTS5 `snippet()`. Requires `dialect: 'sqlite'`.
956
+ *
957
+ * Without `searchFields`/`searchableFields`, the indexed columns are the
958
+ * searchable fields. Explicitly configured searchable fields must all be
959
+ * indexed columns.
960
+ */
961
+ protected fts5?: Fts5Index;
962
+ /**
963
+ * FTS5 prefix matching: `'last'` (default) makes the last term a prefix
964
+ * (search-as-you-type: `super mar` → `super AND mar*`), `'all'` makes every
965
+ * term a prefix, `'none'` matches whole tokens only.
966
+ */
967
+ protected fts5PrefixMatch: Fts5PrefixMatch;
968
+ /** Approximate snippet length, in tokens, of FTS5 highlights (1-64). */
969
+ protected fts5SnippetTokens: number;
970
+ protected getSearchableFields(): Record<string, SearchFieldConfig>;
819
971
  protected getTable(): DrizzleTable;
820
972
  protected getColumn(field: string): DrizzleColumn;
821
973
  /**
822
974
  * Performs search on database.
823
975
  */
824
- search(options: SearchOptions, filters: ListFilters): Promise<SearchResult<ModelObject<M['model']>>>;
976
+ search(options: SearchOptions, filters: ListFilters): Promise<SearchResult<InferModelRow<M['model']>>>;
977
+ /**
978
+ * FTS5 search path (SQLite / D1). Joins the content table to the FTS5 hits
979
+ * (`rowid`, `bm25()`, `snippet()` per column), applies the same WHERE as
980
+ * List (soft-delete, filters, tenant scope), counts, and pages in SQL.
981
+ * Order: bm25 rank (best first), then the primary key; an explicit
982
+ * `order_by` (`?sort=` or `defaultSort`) takes precedence over the rank.
983
+ */
984
+ protected searchFts5(index: Fts5Index, options: SearchOptions, filters: ListFilters): Promise<SearchResult<InferModelRow<M['model']>>>;
825
985
  }
826
986
  /**
827
987
  * Drizzle Export endpoint.
@@ -840,7 +1000,7 @@ declare abstract class DrizzleExportEndpoint<E extends Env = Env, M extends Meta
840
1000
  protected getDb(): DB;
841
1001
  protected getTable(): DrizzleTable;
842
1002
  protected getColumn(field: string): DrizzleColumn;
843
- list(filters: ListFilters): Promise<PaginatedResult<ModelObject<M['model']>>>;
1003
+ list(filters: ListFilters): Promise<PaginatedResult<InferModelRow<M['model']>>>;
844
1004
  }
845
1005
  /**
846
1006
  * Drizzle Import endpoint.
@@ -858,15 +1018,15 @@ declare abstract class DrizzleImportEndpoint<E extends Env = Env, M extends Meta
858
1018
  /**
859
1019
  * Finds an existing record by upsert keys.
860
1020
  */
861
- findExisting(data: Partial<ModelObject<M['model']>>): Promise<ModelObject<M['model']> | null>;
1021
+ findExisting(data: Partial<ModelObject<M['model']>>): Promise<InferModelRow<M['model']> | null>;
862
1022
  /**
863
1023
  * Creates a new record.
864
1024
  */
865
- create(data: Partial<ModelObject<M['model']>>): Promise<ModelObject<M['model']>>;
1025
+ create(data: Partial<ModelObject<M['model']>>): Promise<InferModelRow<M['model']>>;
866
1026
  /**
867
1027
  * Updates an existing record.
868
1028
  */
869
- update(existing: ModelObject<M['model']>, data: Partial<ModelObject<M['model']>>): Promise<ModelObject<M['model']>>;
1029
+ update(existing: InferModelRow<M['model']>, data: Partial<ModelObject<M['model']>>): Promise<InferModelRow<M['model']>>;
870
1030
  }
871
1031
  /**
872
1032
  * Drizzle Clone endpoint.
@@ -897,8 +1057,8 @@ declare abstract class DrizzleCloneEndpoint<E extends Env = Env, M extends MetaI
897
1057
  protected getColumn(field: string): DrizzleColumn;
898
1058
  /** Generates the primary-key value for the cloned row. Defaults to UUIDv4. */
899
1059
  protected generateId(): string;
900
- findSource(lookupValue: string, additionalFilters?: Record<string, string>): Promise<ModelObject<M['model']> | null>;
901
- createClone(data: ModelObject<M['model']>): Promise<ModelObject<M['model']>>;
1060
+ findSource(lookupValue: string, additionalFilters?: Record<string, string>): Promise<InferModelRow<M['model']> | null>;
1061
+ createClone(data: InferModelRow<M['model']>): Promise<InferModelRow<M['model']>>;
902
1062
  }
903
1063
 
904
1064
  /**
@@ -1719,4 +1879,4 @@ declare function isDrizzleZodAvailable(): boolean;
1719
1879
  */
1720
1880
  declare const DrizzleAdapters: AdapterBundle;
1721
1881
 
1722
- export { type CountRow, type CreateDrizzleCrudOptions, DRIZZLE_DIALECTS, type Database, DrizzleAdapters, DrizzleAggregateEndpoint, DrizzleAuditLogStorage, type DrizzleAuditLogStorageOptions, DrizzleBatchCreateEndpoint, DrizzleBatchDeleteEndpoint, DrizzleBatchRestoreEndpoint, DrizzleBatchUpdateEndpoint, DrizzleBatchUpsertEndpoint, DrizzleBulkPatchEndpoint, DrizzleCloneEndpoint, type DrizzleColumn, DrizzleCreateEndpoint, type DrizzleCrudClasses, type DrizzleDatabaseConstraint, DrizzleDeleteEndpoint, type DrizzleDialect, type DrizzleEnv, DrizzleExportEndpoint, DrizzleImportEndpoint, DrizzleListEndpoint, DrizzleReadEndpoint, DrizzleRestoreEndpoint, type DrizzleSchemas, DrizzleSearchEndpoint, type DrizzleSql, type DrizzleTable, DrizzleUpdateEndpoint, DrizzleUpsertEndpoint, DrizzleVersionCompareEndpoint, DrizzleVersionHistoryEndpoint, DrizzleVersionReadEndpoint, DrizzleVersionRollbackEndpoint, DrizzleVersioningStorage, type DrizzleVersioningStorageOptions, type QueryBuilder, type SqliteAuditLogColumns, type SqliteVersionHistoryColumns, type TimestampRepresentation, batchLoadDrizzleRelations, buildWhereCondition, cast, createDrizzleCrud, createDrizzleSchemas, createInsertSchema, createSelectSchema, createUpdateSchema, getColumn, getTable, isDrizzleZodAvailable, loadDrizzleRelation, loadDrizzleRelations, readCount, resolveTimestampRepresentation, resolveTimestampValue, sqliteAuditLogTable, sqliteVersionHistoryTable, substringMatch };
1882
+ export { type CountRow, type CreateDrizzleCrudOptions, DEFAULT_FTS5_PREFIX_INDEX, DEFAULT_FTS5_TOKENIZE, DRIZZLE_DIALECTS, type Database, DrizzleAdapters, DrizzleAggregateEndpoint, DrizzleAuditLogStorage, type DrizzleAuditLogStorageOptions, DrizzleBatchCreateEndpoint, DrizzleBatchDeleteEndpoint, DrizzleBatchRestoreEndpoint, DrizzleBatchUpdateEndpoint, DrizzleBatchUpsertEndpoint, DrizzleBulkPatchEndpoint, DrizzleCloneEndpoint, type DrizzleColumn, DrizzleCreateEndpoint, type DrizzleCrudClasses, type DrizzleDatabaseConstraint, DrizzleDeleteEndpoint, type DrizzleDialect, type DrizzleEnv, DrizzleExportEndpoint, DrizzleImportEndpoint, DrizzleListEndpoint, DrizzleReadEndpoint, DrizzleRestoreEndpoint, type DrizzleSchemas, DrizzleSearchEndpoint, type DrizzleSql, type DrizzleTable, DrizzleUpdateEndpoint, DrizzleUpsertEndpoint, DrizzleVersionCompareEndpoint, DrizzleVersionHistoryEndpoint, DrizzleVersionReadEndpoint, DrizzleVersionRollbackEndpoint, DrizzleVersioningStorage, type DrizzleVersioningStorageOptions, type Fts5Index, type Fts5IndexConfig, type Fts5MatchOptions, type Fts5PrefixMatch, type QueryBuilder, type SqliteAuditLogColumns, type SqliteVersionHistoryColumns, type TimestampRepresentation, batchLoadDrizzleRelations, buildFts5Match, buildWhereCondition, cast, createDrizzleCrud, createDrizzleSchemas, createInsertSchema, createSelectSchema, createUpdateSchema, defineFts5Index, getColumn, getTable, isDrizzleZodAvailable, loadDrizzleRelation, loadDrizzleRelations, readCount, resolveTimestampRepresentation, resolveTimestampValue, sqliteAuditLogTable, sqliteVersionHistoryTable, substringMatch, tokenizeFts5Query };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import {getTableColumns,between,isNull,isNotNull,notInArray,inArray,lte,lt as lt$1,gte,gt,ne as ne$1,eq,sql,and,desc,asc,or}from'drizzle-orm';import {ConfigurationException,resolveRelationValueAsync,loadRelationsForItem,batchLoadRelations,assertNever,CreateEndpoint,getLogger,ReadEndpoint,UpdateEndpoint,DeleteEndpoint,ListEndpoint,buildIncludeOptions,buildCursorPage,buildOffsetPageInfo,RestoreEndpoint,BatchCreateEndpoint,BatchUpdateEndpoint,BatchDeleteEndpoint,BatchRestoreEndpoint,UpsertEndpoint,BatchUpsertEndpoint,BulkPatchEndpoint,VersionHistoryEndpoint,VersionReadEndpoint,VersionCompareEndpoint,VersionRollbackEndpoint,AggregateEndpoint,isFilterOperator,computeAggregations,SearchEndpoint,searchInMemory,ExportEndpoint,ImportEndpoint,CloneEndpoint,CONTEXT_KEYS,decodeCursor}from'hono-crud/internal';import {sqliteTable,index,text,integer}from'drizzle-orm/sqlite-core';import {z}from'zod';function m(i){let e=i;if(e._tx)return e._tx;if(e.db)return e.db;let t=e.context?.get?.(CONTEXT_KEYS.db);if(t)return t;throw new ConfigurationException(`Database not configured. Either:
1
+ import {getTableColumns,between,isNull,isNotNull,notInArray,inArray,lte,lt as lt$1,gte,gt as gt$1,ne as ne$1,eq,sql,getTableName,desc,asc,and,or}from'drizzle-orm';import {ConfigurationException,resolveRelationValueAsync,loadRelationsForItem,batchLoadRelations,assertNever,CreateEndpoint,getLogger,ReadEndpoint,UpdateEndpoint,DeleteEndpoint,ListEndpoint,buildIncludeOptions,buildCursorPage,buildOffsetPageInfo,RestoreEndpoint,BatchCreateEndpoint,BatchUpdateEndpoint,BatchDeleteEndpoint,BatchRestoreEndpoint,UpsertEndpoint,BatchUpsertEndpoint,BulkPatchEndpoint,VersionHistoryEndpoint,VersionReadEndpoint,VersionCompareEndpoint,VersionRollbackEndpoint,AggregateEndpoint,isFilterOperator,computeAggregations,SearchEndpoint,searchInMemory,ExportEndpoint,ImportEndpoint,CloneEndpoint,CONTEXT_KEYS,resolveCursorWindow}from'hono-crud/internal';import {toSnakeCase,toCamelCase}from'drizzle-orm/casing';import {sqliteTable,index,text,integer}from'drizzle-orm/sqlite-core';import {z as z$1}from'zod';function b(o){let e=o;if(e._tx)return e._tx;if(e.db)return e.db;let t=e.context?.get?.(CONTEXT_KEYS.db);if(t)return t;throw new ConfigurationException(`Database not configured. Either:
2
2
  1. Set db property: db = myDb;
3
3
  2. Use middleware: c.set(CONTEXT_KEYS.db, myDb);
4
- 3. Use factory: createDrizzleCrud(db, meta)`)}function q(i){return i}function ee(i,e){return m(i).transaction(async t=>{i._tx=t;try{return await e()}finally{i._tx=void 0;}})}function g(...i){return and(...i)}function ae(...i){return or(...i)}function E(i,e,t){e.enabled&&i.push(isNull(t(e.field)));}var st=["sqlite","pg","mysql"];function b(i){if(!i.model.table)throw new ConfigurationException(`Model ${i.model.tableName} does not have a table reference`);return i.model.table}function c(i,e){let t=getTableColumns(i),n=t[e];if(!n)throw new Error(`Column '${e}' not found in table. Available columns: ${Object.keys(t).join(", ")}`);return n}function we(i){return {resolveRelation:e=>e.table??null,fetchRelated:(e,t,n,r)=>{let o=[inArray(c(e,t),n)];return r?.tenantField!=null&&r.tenantValue!=null&&o.push(eq(c(e,r.tenantField),r.tenantValue)),r?.excludeDeletedField!=null&&o.push(isNull(c(e,r.excludeDeletedField))),i.select().from(e).where(o.length===1?o[0]:and(...o))}}}async function at(i,e,t,n){let r=n.table;if(!r)return e;let o=we(i),s=await resolveRelationValueAsync(e,n,r,o.fetchRelated);return {...e,[t]:s}}async function Re(i,e,t,n){return loadRelationsForItem(e,t,we(i),n)}async function j(i,e,t,n){return batchLoadRelations(e,t,we(i),n)}function te(i,e,t="sqlite"){let n=c(i,e.field);switch(e.operator){case "eq":return eq(n,e.value);case "ne":return ne$1(n,e.value);case "gt":return gt(n,e.value);case "gte":return gte(n,e.value);case "lt":return lt$1(n,e.value);case "lte":return lte(n,e.value);case "in":return inArray(n,e.value);case "nin":return notInArray(n,e.value);case "like":return A(n,String(e.value).replace(/%/g,""),t,{caseSensitive:true});case "ilike":return A(n,String(e.value).replace(/%/g,""),t);case "null":return e.value?isNull(n):isNotNull(n);case "between":{let[r,o]=e.value;return between(n,r,o)}default:return assertNever(e.operator)}}function P(i){return Number(i[0]?.count)||0}async function ne(i){let{db:e,table:t,filters:n,dialect:r,searchFields:o=[],softDeleteConfig:s,defaultPerPage:a=20,primaryKeys:l,extraConditions:u=[],cursorField:p}=i,d=[];if(s?.enabled){let y=c(t,s.field);n.options.onlyDeleted?d.push(isNotNull(y)):n.options.withDeleted||d.push(isNull(y));}for(let y of n.filters){let B=te(t,y,r);B&&d.push(B);}if(n.options.search&&o.length>0){let y=n.options.search,B=o.map(Y=>A(c(t,Y),y,r));d.push(ae(...B));}d.push(...u);let h=d.length>0?g(...d):void 0,C=await e.select({count:sql`count(*)`}).from(t).where(h),D=P(C),f=p!==void 0&&(n.options.cursor!==void 0||n.options.limit!==void 0),R=h,M=false;if(f&&n.options.cursor){let y=decodeCursor(n.options.cursor);y!==null&&(R=g(h,gt(c(t,p),y)),M=true);}let T=e.select().from(t).where(R),O=n.options.order_by;if(O){let y=n.options.order_by_direction==="desc"?desc:asc,B=[O,...l.filter(Y=>Y!==O)];T=T.orderBy(...B.map(Y=>y(c(t,Y))));}if(f){let y=n.options.limit||n.options.per_page||a;return {records:await T.limit(y+1),totalCount:D,page:0,perPage:y,cursor:{limit:y,applied:M}}}let G=n.options.page||1,k=n.options.per_page||a;return {records:await T.limit(k).offset((G-1)*k),totalCount:D,page:G,perPage:k}}async function le(i,e,t,n,r){let o=[];for(let a of r){let l=n[a];l!==void 0&&o.push(eq(t(a),l));}return o.length===0?null:(await i.select().from(e).where(g(...o)).limit(1))[0]||null}function A(i,e,t,n){if(n?.caseSensitive)switch(t){case "pg":return sql`POSITION(${e} IN ${i}) > 0`;case "mysql":return sql`LOCATE(${e}, ${i}) > 0`;default:return sql`INSTR(${i}, ${e}) > 0`}switch(t){case "pg":return sql`POSITION(LOWER(${e}) IN LOWER(${i})) > 0`;case "mysql":return sql`LOCATE(LOWER(${e}), LOWER(${i})) > 0`;default:return sql`INSTR(LOWER(${i}), LOWER(${e})) > 0`}}function lt(i){if(!i||typeof i!="object")return "date";let e=String(i.dataType??"").toLowerCase();return e==="number"?"number":e==="string"?"string":"date"}function w(i,e=new Date){switch(lt(i)){case "number":return e.getTime();case "string":return e.toISOString();default:return e}}var L=class extends CreateEndpoint{db;useTransaction=false;getDb(){return m(this)}getTable(){return b(this._meta)}managedTimestampValue(e){return w(c(this.getTable(),e))}getRelatedTable(e){return e.table}async create(e,t){let n=t??this.getDb(),r=this.getTable(),o=this.applyManagedInsertFields(e,"drizzle");return (await n.insert(r).values(o).returning())[0]}async createNested(e,t,n,r,o){let s=o??this.getDb(),a=this.getRelatedTable(n);if(!a)return getLogger().warn(`Related table not found for ${t}. Add 'table' to the relation config.`),[];let l=Array.isArray(r)?r:[r],u=[];for(let p of l){if(typeof p!="object"||p===null)continue;let d={...p,id:crypto.randomUUID(),[n.foreignKey]:e},h=await s.insert(a).values(d).returning();h[0]&&u.push(h[0]);}return u}async handle(){return this.useTransaction?ee(this,()=>super.handle()):super.handle()}},N=class extends ReadEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return c(this.getTable(),e)}async read(e,t,n){let r=this.getTable(),o=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),a=[eq(o,e)];if(t)for(let[p,d]of Object.entries(t))a.push(eq(this.getColumn(p),d));E(a,s,p=>this.getColumn(p));let l=await this.getDb().select().from(r).where(g(...a)).limit(1);return l[0]?await Re(this.getDb(),l[0],this._meta,n):null}},F=class extends UpdateEndpoint{db;useTransaction=false;getDb(){return m(this)}getTable(){return b(this._meta)}managedTimestampValue(e){return w(c(this.getTable(),e))}getColumn(e){return c(this.getTable(),e)}getRelatedTable(e){return e.table}async findExisting(e,t,n){let r=n??this.getDb(),o=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[p,d]of Object.entries(t))l.push(eq(this.getColumn(p),d));return E(l,a,p=>this.getColumn(p)),(await r.select().from(o).where(g(...l)).limit(1))[0]||null}async update(e,t,n,r){let o=r??this.getDb(),s=this.getTable(),a=this.getColumn(this.lookupField),l=this.getSoftDeleteConfig(),u=[eq(a,e)];if(n)for(let[d,h]of Object.entries(n))u.push(eq(this.getColumn(d),h));return E(u,l,d=>this.getColumn(d)),(await o.update(s).set(this.applyManagedUpdateFields(t)).where(g(...u)).returning())[0]||null}async processNestedWrites(e,t,n,r,o){let s=o??this.getDb(),a=this.getRelatedTable(n);if(!a)return getLogger().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:[]},u=c(a,n.foreignKey),p=c(a,"id");if(r.create){let d=Array.isArray(r.create)?r.create:[r.create];for(let h of d){if(typeof h!="object"||h===null)continue;let C={...h,id:crypto.randomUUID(),[n.foreignKey]:e},D=await s.insert(a).values(C).returning();D[0]&&l.created.push(D[0]);}}if(r.update)for(let d of r.update){if(!d.id||!(await s.select().from(a).where(g(eq(p,d.id),eq(u,e))).limit(1))[0])continue;let{id:C,...D}=d,f=await s.update(a).set(D).where(eq(p,C)).returning();f[0]&&l.updated.push(f[0]);}if(r.delete)for(let d of r.delete)(await s.delete(a).where(g(eq(p,d),eq(u,e))).returning())[0]&&l.deleted.push(d);if(r.connect)for(let d of r.connect)(await s.update(a).set({[n.foreignKey]:e}).where(eq(p,d)).returning())[0]&&l.connected.push(d);if(r.disconnect)for(let d of r.disconnect)(await s.update(a).set({[n.foreignKey]:null}).where(g(eq(p,d),eq(u,e))).returning())[0]&&l.disconnected.push(d);return l}async handle(){return this.useTransaction?ee(this,()=>super.handle()):super.handle()}},U=class extends DeleteEndpoint{db;useTransaction=false;getDb(){return m(this)}getTable(){return b(this._meta)}managedTimestampValue(e){return w(c(this.getTable(),e))}getColumn(e){return c(this.getTable(),e)}getRelatedTable(e){return e.table}async findForDelete(e,t,n){let r=n??this.getDb(),o=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[p,d]of Object.entries(t))l.push(eq(this.getColumn(p),d));return E(l,a,p=>this.getColumn(p)),(await r.select().from(o).where(g(...l)).limit(1))[0]||null}async delete(e,t,n){let r=n??this.getDb(),o=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,p]of Object.entries(t))l.push(eq(this.getColumn(u),p));return E(l,a,u=>this.getColumn(u)),a.enabled?(await r.update(o).set({[a.field]:this.managedTimestampValue(a.field)}).where(g(...l)).returning())[0]||null:(await r.delete(o).where(g(...l)).returning())[0]||null}async countRelated(e,t,n,r){let o=r??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=c(s,n.foreignKey),l=await o.select({count:sql`count(*)`}).from(s).where(eq(a,e));return P(l)}async deleteRelated(e,t,n,r){let o=r??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=c(s,n.foreignKey);return (await o.delete(s).where(eq(a,e)).returning()).length}async nullifyRelated(e,t,n,r){let o=r??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=c(s,n.foreignKey);return (await o.update(s).set({[n.foreignKey]:null}).where(eq(a,e)).returning()).length}async handle(){return this.useTransaction?ee(this,()=>super.handle()):super.handle()}},V=class extends ListEndpoint{db;dialect="sqlite";supportsCursorPagination=true;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return c(this.getTable(),e)}async list(e){let t=await ne({db:this.getDb(),table:this.getTable(),filters:e,dialect:this.dialect,searchFields:this.searchFields,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage,primaryKeys:this._meta.model.primaryKeys,cursorField:this.isCursorPaginationActive()?this.cursorField||"id":void 0}),n=buildIncludeOptions(e.options.include,this.getRelationScope(e.options.withDeleted));if(t.cursor){let{items:o,result_info:s}=buildCursorPage({rows:t.records,limit:t.cursor.limit,totalCount:t.totalCount,cursorField:this.cursorField||"id",cursorApplied:t.cursor.applied});return {result:await j(this.getDb(),o,this._meta,n),result_info:s}}return {result:await j(this.getDb(),t.records,this._meta,n),result_info:buildOffsetPageInfo({page:t.page,perPage:t.perPage,totalCount:t.totalCount})}}},Z=class extends RestoreEndpoint{db;useTransaction=false;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return c(this.getTable(),e)}async restore(e,t,n){let r=n??this.getDb(),o=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[p,d]of Object.entries(t))l.push(eq(this.getColumn(p),d));return l.push(isNotNull(this.getColumn(a.field))),(await r.update(o).set({[a.field]:null}).where(g(...l)).returning())[0]||null}async handle(){return this.useTransaction?ee(this,()=>super.handle()):super.handle()}};var K=class extends BatchCreateEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}managedTimestampValue(e){return w(c(this.getTable(),e))}async batchCreate(e){let t=this.getTable(),n=e.map(o=>this.applyManagedInsertFields(o,"drizzle"));return await this.getDb().insert(t).values(n).returning()}},$=class extends BatchUpdateEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}managedTimestampValue(e){return w(c(this.getTable(),e))}getColumn(e){return c(this.getTable(),e)}async batchUpdate(e){let t=this.getTable(),n=this.getColumn(this.lookupField),r=this.getSoftDeleteConfig(),o=[],s=[],a=this.getTenantScopeFilter();for(let l of e){let u=[eq(n,l.id)];E(u,r,d=>this.getColumn(d)),a&&u.push(eq(this.getColumn(a.field),a.value));let p=await this.getDb().update(t).set(this.applyManagedUpdateFields(l.data)).where(g(...u)).returning();p[0]?o.push(p[0]):s.push(l.id);}return {updated:o,notFound:s}}},Q=class extends BatchDeleteEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}managedTimestampValue(e){return w(c(this.getTable(),e))}getColumn(e){return c(this.getTable(),e)}async batchDelete(e){let t=this.getTable(),n=this.getColumn(this.lookupField),r=this.getSoftDeleteConfig(),o=[inArray(n,e)];E(o,r,d=>this.getColumn(d));let s=this.getTenantScopeFilter();s&&o.push(eq(this.getColumn(s.field),s.value));let a;r.enabled?a=await this.getDb().update(t).set({[r.field]:this.managedTimestampValue(r.field)}).where(g(...o)).returning():a=await this.getDb().delete(t).where(g(...o)).returning();let l=a,u=new Set(l.map(d=>String(d[this.lookupField]))),p=e.filter(d=>!u.has(d));return {deleted:l,notFound:p}}},W=class extends BatchRestoreEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return c(this.getTable(),e)}async batchRestore(e){let t=this.getTable(),n=this.getColumn(this.lookupField),r=this.getSoftDeleteConfig(),o=[inArray(n,e),isNotNull(this.getColumn(r.field))],s=this.getTenantScopeFilter();s&&o.push(eq(this.getColumn(s.field),s.value));let l=await this.getDb().update(t).set({[r.field]:null}).where(g(...o)).returning(),u=new Set(l.map(d=>String(d[this.lookupField]))),p=e.filter(d=>!u.has(d));return {restored:l,notFound:p}}};function Ut(i){return i.split(/\s+/).filter(e=>e.length>0)}var H=class extends UpsertEndpoint{db;dialect="sqlite";getDb(){return m(this)}getTable(){return b(this._meta)}managedTimestampValue(e){return w(c(this.getTable(),e))}getColumn(e){return c(this.getTable(),e)}async findExisting(e){return le(this.getDb(),this.getTable(),t=>this.getColumn(t),e,this.getUpsertKeys())}async create(e){let t=this.getTable(),n=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(n).returning())[0]}async update(e,t){let n=this.getTable(),r=this._meta.model.primaryKeys[0],o=e[r];return (await this.getDb().update(n).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(r),o)).returning())[0]}async nativeUpsert(e,t){let n=this.getTable(),r=this.getUpsertKeys(),o=this._meta.model.primaryKeys[0],s=this.getSoftDeleteConfig(),a=this.getTimestampsConfig(),l=this.applyManagedInsertFields(e,"drizzle"),u={};for(let[f,R]of Object.entries(e))!r.includes(f)&&f!==o&&(this.createOnlyFields?.includes(f)||(u[f]=R));a.enabled&&(u[a.updatedAt]=Date.now());let p=r.map(f=>this.getColumn(f)),d;s.enabled&&(d=isNull(this.getColumn(s.field)));let h=Object.keys(u).length>0?u:{[o]:sql`${this.getColumn(o)}`},C=this.getDb().insert(n).values(l);return this.dialect==="mysql"?{data:(await C.onDuplicateKeyUpdate({set:h}).returning())[0],created:false}:{data:(await C.onConflictDoUpdate({target:p,set:h,where:d}).returning())[0],created:false}}},J=class extends BatchUpsertEndpoint{db;dialect="sqlite";getDb(){return m(this)}getTable(){return b(this._meta)}managedTimestampValue(e){return w(c(this.getTable(),e))}getColumn(e){return c(this.getTable(),e)}async findExisting(e){return le(this.getDb(),this.getTable(),t=>this.getColumn(t),e,this.getUpsertKeys())}async create(e){let t=this.getTable(),n=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(n).returning())[0]}async update(e,t){let n=this.getTable(),r=this._meta.model.primaryKeys[0],o=e[r];return (await this.getDb().update(n).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(r),o)).returning())[0]}async nativeBatchUpsert(e,t){if(e.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let n=this.getTable(),r=this.getUpsertKeys(),o=this._meta.model.primaryKeys[0],s=this.getTimestampsConfig(),a=e.map(D=>this.applyManagedInsertFields(D,"drizzle")),l={},u=e[0];for(let D of Object.keys(u))!r.includes(D)&&D!==o&&(this.createOnlyFields?.includes(D)||(l[D]=sql`excluded.${sql.identifier(D)}`));s.enabled&&(l[s.updatedAt]=Date.now());let p=r.map(D=>this.getColumn(D)),d=Object.keys(l).length>0?l:{[o]:sql`${this.getColumn(o)}`},h=this.getDb().insert(n).values(a),C=await(this.dialect==="mysql"?h.onDuplicateKeyUpdate({set:d}):h.onConflictDoUpdate({target:p,set:d})).returning();return {items:C.map((D,f)=>({data:D,created:false,index:f})),createdCount:0,updatedCount:C.length,totalCount:C.length}}},ce=class extends BulkPatchEndpoint{db;dialect="sqlite";getDb(){return m(this)}getTable(){return b(this._meta)}managedTimestampValue(e){return w(c(this.getTable(),e))}getColumn(e){return c(this.getTable(),e)}buildConditions(e){let t=this.getTable(),n=[];for(let o of e.filters){let s=te(t,o,this.dialect);s&&n.push(s);}let r=this.getSoftDeleteConfig();return E(n,r,o=>this.getColumn(o)),n}async countMatching(e){let t=this.buildConditions(e),n=await this.getDb().select({count:sql`count(*)`}).from(this.getTable()).where(g(...t));return P(n)}async applyPatch(e,t){let n=this.buildConditions(t),r=await this.getDb().update(this.getTable()).set(this.applyManagedUpdateFields(e)).where(g(...n)).returning();return {updated:r.length,records:r}}};async function fe(i,e,t,n,r){let o=r?g(eq(t,n),eq(c(e,r.field),r.value)):eq(t,n),s=await i.select({count:sql`count(*)`}).from(e).where(o);return P(s)>0}var ue=class extends VersionHistoryEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return c(this.getTable(),e)}async recordExists(e,t){return fe(this.getDb(),this.getTable(),this.getColumn("id"),e,t)}},pe=class extends VersionReadEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return c(this.getTable(),e)}async recordExists(e,t){return fe(this.getDb(),this.getTable(),this.getColumn("id"),e,t)}},ge=class extends VersionCompareEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return c(this.getTable(),e)}async recordExists(e,t){return fe(this.getDb(),this.getTable(),this.getColumn("id"),e,t)}},me=class extends VersionRollbackEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return c(this.getTable(),e)}async recordExists(e,t){return fe(this.getDb(),this.getTable(),this.getColumn("id"),e,t)}async rollback(e,t,n){let r=this.getTable(),o=this.getVersioningConfig().field;return (await this.getDb().update(r).set({...t,[o]:n}).where(eq(this.getColumn("id"),e)).returning())[0]}},be=class extends AggregateEndpoint{db;dialect="sqlite";getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return c(this.getTable(),e)}async aggregate(e){let t=this.getTable(),n=[],r=this.getSoftDeleteConfig();if(r.enabled){let{query:a}=await this.getValidatedData();a?.withDeleted===true||a?.withDeleted==="true"||E(n,r,u=>this.getColumn(u));}if(e.filters)for(let[a,l]of Object.entries(e.filters))if(typeof l=="object"&&l!==null)for(let[u,p]of Object.entries(l)){if(!isFilterOperator(u)){n.push(sql`1 = 0`);continue}let d=te(t,{field:a,operator:u,value:p},this.dialect);d&&n.push(d);}else n.push(eq(this.getColumn(a),l));let o=n.length>0?g(...n):void 0,s=await this.getDb().select().from(t).where(o);return computeAggregations(s,e)}},X=class extends SearchEndpoint{db;dialect="sqlite";getDb(){return m(this)}useNativeSearch=false;vectorColumn;vectorConfig="english";getTable(){return b(this._meta)}getColumn(e){return c(this.getTable(),e)}async search(e,t){let n=this.getTable(),r=[],o=this.getSearchableFields(),s=e.fields||Object.keys(o);if(this.useNativeSearch&&this.vectorColumn){let R=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(" | ")})`;r.push(sql`${R} @@ ${M}`);}else {let R=(M,T)=>{try{let O=this.getColumn(M);return A(sql`CAST(${O} AS TEXT)`,T,this.dialect)}catch{return}};if(e.mode==="all"){let M=Ut(e.query);if(M.length>0){let T=[];for(let O of M){let G=s.map(k=>R(k,O)).filter(k=>k!==void 0);G.length>0&&T.push(ae(...G));}T.length>0&&r.push(g(...T));}}else {let M=s.map(T=>R(T,e.query)).filter(T=>T!==void 0);M.length>0&&r.push(ae(...M));}}let a=await ne({db:this.getDb(),table:n,filters:t,dialect:this.dialect,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage,primaryKeys:this._meta.model.primaryKeys,extraConditions:r}),l=a.records,u=a.totalCount,p=e.mode==="all"?{...e,mode:"any"}:e,d=searchInMemory(l,p,o),h=buildIncludeOptions(t.options.include,this.getRelationScope(t.options.withDeleted)),C=d.map(R=>R.item),D=await j(this.getDb(),C,this._meta,h);return {items:d.map((R,M)=>({...R,item:D[M]})),totalCount:u}}},he=class extends ExportEndpoint{db;dialect="sqlite";getDb(){return m(this)}getTable(){return b(this._meta)}getColumn(e){return c(this.getTable(),e)}async list(e){let t=await ne({db:this.getDb(),table:this.getTable(),filters:e,dialect:this.dialect,searchFields:this.searchFields,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage,primaryKeys:this._meta.model.primaryKeys}),n=buildIncludeOptions(e.options.include,this.getRelationScope(e.options.withDeleted));return {result:await j(this.getDb(),t.records,this._meta,n),result_info:buildOffsetPageInfo({page:t.page,perPage:t.perPage,totalCount:t.totalCount})}}},ze=class extends ImportEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}managedTimestampValue(e){return w(c(this.getTable(),e))}getColumn(e){return c(this.getTable(),e)}async findExisting(e){return le(this.getDb(),this.getTable(),t=>this.getColumn(t),e,this.getUpsertKeys())}async create(e){let t=this.getTable(),n=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(n).returning())[0]}async update(e,t){let n=this.getTable(),r=this._meta.model.primaryKeys[0],o=e[r];return (await this.getDb().update(n).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(r),o)).returning())[0]}},De=class extends CloneEndpoint{db;getDb(){return m(this)}getTable(){return b(this._meta)}managedTimestampValue(e){return w(c(this.getTable(),e))}getColumn(e){return c(this.getTable(),e)}generateId(){return crypto.randomUUID()}async findSource(e,t){let n=this.getTable(),r=this.getColumn(this.lookupField),o=this.getSoftDeleteConfig(),s=[eq(r,e)];if(t)for(let[l,u]of Object.entries(t))s.push(eq(this.getColumn(l),u));E(s,o,l=>this.getColumn(l));let a=await this.getDb().select().from(n).where(g(...s)).limit(1);return a[0]?a[0]:null}async createClone(e){let t=this.getTable(),n=this.applyManagedInsertFields(e,"drizzle",()=>this.generateId());return (await this.getDb().insert(t).values(n).returning())[0]}};function nr(i,e,t){let n=t?.dialect??"sqlite";return {Create:class extends L{_meta=e;db=i},Read:class extends N{_meta=e;db=i},Update:class extends F{_meta=e;db=i},Delete:class extends U{_meta=e;db=i},List:class extends V{_meta=e;db=i;dialect=n},Restore:class extends Z{_meta=e;db=i},Upsert:class extends H{_meta=e;db=i;dialect=n},Search:class extends X{_meta=e;db=i;dialect=n},BatchCreate:class extends K{_meta=e;db=i},BatchUpdate:class extends ${_meta=e;db=i},BatchDelete:class extends Q{_meta=e;db=i},BatchRestore:class extends W{_meta=e;db=i},BatchUpsert:class extends J{_meta=e;db=i;dialect=n}}}var Ae=class{db;table;constructor(e){this.db=e.db,this.table=e.table;}col(e){return c(this.table,e)}recordScope(e,t){return and(eq(this.col("resourceTable"),e),eq(this.col("recordId"),String(t)))}toEntry(e){return {id:e.id,recordId:e.recordId,version:e.version,data:JSON.parse(e.data),createdAt:new Date(e.createdAt),...e.changedBy!=null?{changedBy:e.changedBy}:{},...e.changeReason!=null?{changeReason:e.changeReason}:{},...e.changes!=null?{changes:JSON.parse(e.changes)}:{}}}async store(e,t){let n=t.createdAt instanceof Date?t.createdAt:new Date(t.createdAt);await this.db.insert(this.table).values({id:t.id,resourceTable:e,recordId:String(t.recordId),version:t.version,data:JSON.stringify(t.data),createdAt:n.getTime(),changedBy:t.changedBy??null,changeReason:t.changeReason??null,changes:t.changes?JSON.stringify(t.changes):null});}async getByRecordId(e,t,n){let r=this.db.select().from(this.table).where(this.recordScope(e,t)).orderBy(desc(this.col("version")));return (n?.limit!=null||n?.offset!=null)&&(r=r.limit(n?.limit??Number.MAX_SAFE_INTEGER)),n?.offset!=null&&(r=r.offset(n.offset)),(await r).map(s=>this.toEntry(s))}async getVersion(e,t,n){let r=await this.db.select().from(this.table).where(and(this.recordScope(e,t),eq(this.col("version"),n))).limit(1);return r.length>0?this.toEntry(r[0]):null}async getLatestVersion(e,t){let n=await this.db.select().from(this.table).where(this.recordScope(e,t)).orderBy(desc(this.col("version"))).limit(1);return n.length>0?n[0].version:0}async pruneVersions(e,t,n){if(n<=0)return this.deleteAllVersions(e,t);let r=await this.getByRecordId(e,t);if(r.length<=n)return 0;let o=r[n-1].version;return (await this.db.delete(this.table).where(and(this.recordScope(e,t),lt$1(this.col("version"),o))).returning()).length}async deleteAllVersions(e,t){return (await this.db.delete(this.table).where(this.recordScope(e,t)).returning()).length}};function $t(){return {id:text("id").primaryKey(),resourceTable:text("resource_table").notNull(),recordId:text("record_id").notNull(),version:integer("version").notNull(),data:text("data").notNull(),createdAt:integer("created_at").notNull(),changedBy:text("changed_by"),changeReason:text("change_reason"),changes:text("changes")}}function yr(i="version_history",e){return sqliteTable(i,$t(),t=>[index(`${i}_record_version_idx`).on(t.resourceTable,t.recordId,t.version),...e?.(t)??[]])}var Le=class{db;table;constructor(e){this.db=e.db,this.table=e.table;}col(e){return c(this.table,e)}toEntry(e){return {id:e.id,timestamp:new Date(e.timestamp),action:e.action,tableName:e.tableName,recordId:e.recordId,...e.userId!=null?{userId:e.userId}:{},...e.record!=null?{record:JSON.parse(e.record)}:{},...e.previousRecord!=null?{previousRecord:JSON.parse(e.previousRecord)}:{},...e.changes!=null?{changes:JSON.parse(e.changes)}:{},...e.metadata!=null?{metadata:JSON.parse(e.metadata)}:{}}}async store(e){let t=e.timestamp instanceof Date?e.timestamp:new Date(e.timestamp);await this.db.insert(this.table).values({id:e.id,tableName:e.tableName,recordId:String(e.recordId),action:e.action,timestamp:t.getTime(),userId:e.userId??null,record:e.record!==void 0?JSON.stringify(e.record):null,previousRecord:e.previousRecord!==void 0?JSON.stringify(e.previousRecord):null,changes:e.changes!==void 0?JSON.stringify(e.changes):null,metadata:e.metadata!==void 0?JSON.stringify(e.metadata):null});}async getByRecordId(e,t,n){let r=this.db.select().from(this.table).where(g(eq(this.col("tableName"),e),eq(this.col("recordId"),String(t)))).orderBy(asc(this.col("timestamp")),asc(this.col("id"))),o=n?.offset||0,s=n?.limit||0;return s>0?(r=r.limit(s),o>0&&(r=r.offset(o))):o>0&&(r=r.limit(Number.MAX_SAFE_INTEGER),r=r.offset(o)),(await r).map(l=>this.toEntry(l))}async getAll(e){let t=[];e?.tableName&&t.push(eq(this.col("tableName"),e.tableName)),e?.action&&t.push(eq(this.col("action"),e.action)),e?.userId&&t.push(eq(this.col("userId"),e.userId)),e?.startDate&&t.push(gte(this.col("timestamp"),e.startDate.getTime())),e?.endDate&&t.push(lte(this.col("timestamp"),e.endDate.getTime()));let n=t.length>0?g(...t):void 0,r=this.db.select().from(this.table).where(n).orderBy(asc(this.col("timestamp")),asc(this.col("id"))),o=e?.offset||0,s=e?.limit||0;return s>0?(r=r.limit(s),o>0&&(r=r.offset(o))):o>0&&(r=r.limit(Number.MAX_SAFE_INTEGER),r=r.offset(o)),(await r).map(l=>this.toEntry(l))}};function Xt(){return {id:text("id").primaryKey(),tableName:text("table_name").notNull(),recordId:text("record_id").notNull(),action:text("action").notNull(),timestamp:integer("timestamp").notNull(),userId:text("user_id"),record:text("record"),previousRecord:text("previous_record"),changes:text("changes"),metadata:text("metadata")}}function Rr(i="audit_logs",e){return sqliteTable(i,Xt(),t=>[index(`${i}_record_idx`).on(t.tableName,t.recordId),index(`${i}_timestamp_idx`).on(t.timestamp),...e?.(t)??[]])}var ie=null,Ne=false,Ce=null;async function Me(){if(Ne){if(Ce)throw Ce;if(ie)return ie}Ne=true;try{return ie=await import('drizzle-zod'),ie}catch{throw Ce=new Error("drizzle-zod is not installed. Please install it: npm install drizzle-zod"),Ce}}async function Gt(i,e){return (await Me()).createSelectSchema(i,e)}async function Yt(i,e){return (await Me()).createInsertSchema(i,e)}async function en(i,e){let t=await Me();return t.createUpdateSchema?t.createUpdateSchema(i,e):t.createInsertSchema(i,e).partial()}async function tn(i,e){let t=await Me(),n=e?.coerceDates!==false,r=n?sn(i):new Set,o=t.createSelectSchema(i,e?.selectRefine),s=t.createInsertSchema(i,e?.insertRefine),a;return t.createUpdateSchema?a=t.createUpdateSchema(i,e?.updateRefine):a=t.createInsertSchema(i,e?.updateRefine).partial(),n&&r.size>0&&(s=Fe(s,r),a=Fe(a,r)),{select:o,insert:s,update:a}}function nn(){return ie!==null}var rn=z.preprocess(i=>{if(i instanceof Date)return i;if(typeof i=="string"){let e=new Date(i);if(!isNaN(e.getTime()))return e}return i},z.date()),on=z.preprocess(i=>{if(i==null)return null;if(i instanceof Date)return i;if(typeof i=="string"){let e=new Date(i);if(!isNaN(e.getTime()))return e}return i},z.date().nullable());function sn(i){let e=new Set,t=i;for(let[n,r]of Object.entries(t)){if(n==="_"||n==="$inferInsert"||n==="$inferSelect")continue;let o=r;if(!o||typeof o!="object")continue;let s=String(o.dataType??"").toLowerCase(),a=String(o.columnType??"").toLowerCase(),l=o.config,u=String(l?.dataType??"").toLowerCase();(s.includes("timestamp")||s.includes("date")||s.includes("datetime")||a.includes("pgtimestamp")||a.includes("pgdate")||a.includes("mysqltimestamp")||a.includes("mysqldate")||a.includes("sqlitetimestamp")||u.includes("timestamp")||u.includes("date"))&&e.add(n);}return e}function Fe(i,e){if(e.size===0)return i;let t=i.shape,n={};for(let[r,o]of Object.entries(t))if(e.has(r)){let s=o.isOptional?.()??false,a=o.isNullable?.()??false,l=rn;(a||s)&&(l=on),s&&(l=l.optional()),n[r]=l;}else n[r]=o;return z.object(n)}var Br={CreateEndpoint:L,ListEndpoint:V,ReadEndpoint:N,UpdateEndpoint:F,DeleteEndpoint:U,RestoreEndpoint:Z,BatchCreateEndpoint:K,BatchUpdateEndpoint:$,BatchDeleteEndpoint:Q,BatchRestoreEndpoint:W,BatchUpsertEndpoint:J,SearchEndpoint:X,AggregateEndpoint:be,ExportEndpoint:he,ImportEndpoint:ze,UpsertEndpoint:H,CloneEndpoint:De,BulkPatchEndpoint:ce,VersionHistoryEndpoint:ue,VersionReadEndpoint:pe,VersionCompareEndpoint:ge,VersionRollbackEndpoint:me};export{st as DRIZZLE_DIALECTS,Br as DrizzleAdapters,be as DrizzleAggregateEndpoint,Le as DrizzleAuditLogStorage,K as DrizzleBatchCreateEndpoint,Q as DrizzleBatchDeleteEndpoint,W as DrizzleBatchRestoreEndpoint,$ as DrizzleBatchUpdateEndpoint,J as DrizzleBatchUpsertEndpoint,ce as DrizzleBulkPatchEndpoint,De as DrizzleCloneEndpoint,L as DrizzleCreateEndpoint,U as DrizzleDeleteEndpoint,he as DrizzleExportEndpoint,ze as DrizzleImportEndpoint,V as DrizzleListEndpoint,N as DrizzleReadEndpoint,Z as DrizzleRestoreEndpoint,X as DrizzleSearchEndpoint,F as DrizzleUpdateEndpoint,H as DrizzleUpsertEndpoint,ge as DrizzleVersionCompareEndpoint,ue as DrizzleVersionHistoryEndpoint,pe as DrizzleVersionReadEndpoint,me as DrizzleVersionRollbackEndpoint,Ae as DrizzleVersioningStorage,j as batchLoadDrizzleRelations,te as buildWhereCondition,q as cast,nr as createDrizzleCrud,tn as createDrizzleSchemas,Yt as createInsertSchema,Gt as createSelectSchema,en as createUpdateSchema,c as getColumn,b as getTable,nn as isDrizzleZodAvailable,at as loadDrizzleRelation,Re as loadDrizzleRelations,P as readCount,lt as resolveTimestampRepresentation,w as resolveTimestampValue,Rr as sqliteAuditLogTable,yr as sqliteVersionHistoryTable,A as substringMatch};
4
+ 3. Use factory: createDrizzleCrud(db, meta)`)}function j(o){return o}function ne(o,e){return b(o).transaction(async t=>{o._tx=t;try{return await e()}finally{o._tx=void 0;}})}function f(...o){return and(...o)}function re(...o){return or(...o)}function k(o,e,t){e.enabled&&o.push(isNull(t(e.field)));}var Ot=["sqlite","pg","mysql"];function z(o){if(!o.model.table)throw new ConfigurationException(`Model ${o.model.tableName} does not have a table reference`);return o.model.table}function p(o,e){let t=getTableColumns(o),n=t[e];if(!n)throw new Error(`Column '${e}' not found in table. Available columns: ${Object.keys(t).join(", ")}`);return n}function _e(o){return {resolveRelation:e=>e.table??null,fetchRelated:(e,t,n,r)=>{let i=[inArray(p(e,t),n)];return r?.tenantField!=null&&r.tenantValue!=null&&i.push(eq(p(e,r.tenantField),r.tenantValue)),r?.excludeDeletedField!=null&&i.push(isNull(p(e,r.excludeDeletedField))),o.select().from(e).where(i.length===1?i[0]:and(...i))}}}async function At(o,e,t,n){let r=n.table;if(!r)return e;let i=_e(o),s=await resolveRelationValueAsync(e,n,r,i.fetchRelated);return {...e,[t]:s}}async function Pe(o,e,t,n){return loadRelationsForItem(e,t,_e(o),n)}async function O(o,e,t,n){return batchLoadRelations(e,t,_e(o),n)}function oe(o,e,t="sqlite"){let n=p(o,e.field);switch(e.operator){case "eq":return eq(n,e.value);case "ne":return ne$1(n,e.value);case "gt":return gt$1(n,e.value);case "gte":return gte(n,e.value);case "lt":return lt$1(n,e.value);case "lte":return lte(n,e.value);case "in":return inArray(n,e.value);case "nin":return notInArray(n,e.value);case "like":return L(n,String(e.value).replace(/%/g,""),t,{caseSensitive:true});case "ilike":return L(n,String(e.value).replace(/%/g,""),t);case "null":return e.value?isNull(n):isNotNull(n);case "between":{let[r,i]=e.value;return between(n,r,i)}default:return assertNever(e.operator)}}function A(o){return Number(o[0]?.count)||0}function Nt(o,e,t){let n=t.direction==="next"?gt$1:lt$1,r=[];for(let i=0;i<t.values.length;i++){let s=[];for(let a=0;a<i;a++)s.push(eq(p(o,e[a]),t.values[a]));s.push(n(p(o,e[i]),t.values[i])),r.push(s.length===1?s[0]:f(...s));}return r.length===1?r[0]:re(...r)}function Fe(o){let{table:e,filters:t,dialect:n,searchFields:r=[],softDeleteConfig:i,extraConditions:s=[]}=o,a=[];if(i?.enabled){let l=p(e,i.field);t.options.onlyDeleted?a.push(isNotNull(l)):t.options.withDeleted||a.push(isNull(l));}for(let l of t.filters){let d=oe(e,l,n);d&&a.push(d);}if(t.options.search&&r.length>0){let l=t.options.search,d=r.map(u=>L(p(e,u),l,n));a.push(re(...d));}return a.push(...s),a.length>0?f(...a):void 0}async function ie(o){let{db:e,table:t,filters:n,dialect:r,searchFields:i=[],softDeleteConfig:s,defaultPerPage:a=20,primaryKeys:l,extraConditions:d=[],cursorField:u}=o,c=Fe({table:t,filters:n,dialect:r,searchFields:i,softDeleteConfig:s,extraConditions:d}),g=await e.select({count:sql`count(*)`}).from(t).where(c),m=A(g);if(u!==void 0&&(n.options.cursor!==void 0||n.options.limit!==void 0)){let w=resolveCursorWindow({cursor:n.options.cursor,limit:n.options.limit,perPage:n.options.per_page,defaultPerPage:a,cursorField:u,primaryKeys:l}),B=w.cursor===null?c:f(c,Nt(t,w.keyFields,w.cursor)),x=w.direction==="prev"?desc:asc;return {records:await e.select().from(t).where(B).orderBy(...w.keyFields.map(ce=>x(p(t,ce)))).limit(w.limit+1),totalCount:m,page:0,perPage:w.limit,cursor:{limit:w.limit,applied:w.cursor!==null,direction:w.direction}}}let h=e.select().from(t).where(c),y=n.options.order_by;if(y){let w=n.options.order_by_direction==="desc"?desc:asc,B=[y,...l.filter(x=>x!==y)];h=h.orderBy(...B.map(x=>w(p(t,x))));}let R=n.options.page||1,T=n.options.per_page||a;return {records:await h.limit(T).offset((R-1)*T),totalCount:m,page:R,perPage:T}}async function ge(o,e,t,n,r){let i=[];for(let a of r){let l=n[a];l!==void 0&&i.push(eq(t(a),l));}return i.length===0?null:(await o.select().from(e).where(f(...i)).limit(1))[0]||null}function L(o,e,t,n){if(n?.caseSensitive)switch(t){case "pg":return sql`POSITION(${e} IN ${o}) > 0`;case "mysql":return sql`LOCATE(${e}, ${o}) > 0`;default:return sql`INSTR(${o}, ${e}) > 0`}switch(t){case "pg":return sql`POSITION(LOWER(${e}) IN LOWER(${o})) > 0`;case "mysql":return sql`LOCATE(LOWER(${e}), LOWER(${o})) > 0`;default:return sql`INSTR(LOWER(${o}), LOWER(${e})) > 0`}}function $t(o){if(!o||typeof o!="object")return "date";let e=String(o.dataType??"").toLowerCase();return e==="number"?"number":e==="string"?"string":"date"}function S(o,e=new Date){switch($t(o)){case "number":return e.getTime();case "string":return e.toISOString();default:return e}}var U=class extends CreateEndpoint{db;useTransaction=false;getDb(){return b(this)}getTable(){return z(this._meta)}managedTimestampValue(e){return S(p(this.getTable(),e))}getRelatedTable(e){return e.table}async create(e,t){let n=t??this.getDb(),r=this.getTable(),i=this.applyManagedInsertFields(e,"drizzle");return (await n.insert(r).values(i).returning())[0]}async createNested(e,t,n,r,i){let s=i??this.getDb(),a=this.getRelatedTable(n);if(!a)return getLogger().warn(`Related table not found for ${t}. Add 'table' to the relation config.`),[];let l=Array.isArray(r)?r:[r],d=[];for(let u of l){if(typeof u!="object"||u===null)continue;let c={...u,id:crypto.randomUUID(),[n.foreignKey]:e},g=await s.insert(a).values(c).returning();g[0]&&d.push(g[0]);}return d}async handle(){return this.useTransaction?ne(this,()=>super.handle()):super.handle()}},V=class extends ReadEndpoint{db;getDb(){return b(this)}getTable(){return z(this._meta)}getColumn(e){return p(this.getTable(),e)}async read(e,t,n){let r=this.getTable(),i=this.getColumn(this.lookupField),s=this.getSoftDeleteConfig(),a=[eq(i,e)];if(t)for(let[u,c]of Object.entries(t))a.push(eq(this.getColumn(u),c));k(a,s,u=>this.getColumn(u));let l=await this.getDb().select().from(r).where(f(...a)).limit(1);return l[0]?await Pe(this.getDb(),l[0],this._meta,n):null}},Z=class extends UpdateEndpoint{db;useTransaction=false;getDb(){return b(this)}getTable(){return z(this._meta)}managedTimestampValue(e){return S(p(this.getTable(),e))}getColumn(e){return p(this.getTable(),e)}getRelatedTable(e){return e.table}async findExisting(e,t,n){let r=n??this.getDb(),i=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return k(l,a,u=>this.getColumn(u)),(await r.select().from(i).where(f(...l)).limit(1))[0]||null}async update(e,t,n,r){let i=r??this.getDb(),s=this.getTable(),a=this.getColumn(this.lookupField),l=this.getSoftDeleteConfig(),d=[eq(a,e)];if(n)for(let[c,g]of Object.entries(n))d.push(eq(this.getColumn(c),g));return k(d,l,c=>this.getColumn(c)),(await i.update(s).set(this.applyManagedUpdateFields(t)).where(f(...d)).returning())[0]||null}async processNestedWrites(e,t,n,r,i){let s=i??this.getDb(),a=this.getRelatedTable(n);if(!a)return getLogger().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=p(a,n.foreignKey),u=p(a,"id");if(r.create){let c=Array.isArray(r.create)?r.create:[r.create];for(let g of c){if(typeof g!="object"||g===null)continue;let m={...g,id:crypto.randomUUID(),[n.foreignKey]:e},h=await s.insert(a).values(m).returning();h[0]&&l.created.push(h[0]);}}if(r.update)for(let c of r.update){if(!c.id||!(await s.select().from(a).where(f(eq(u,c.id),eq(d,e))).limit(1))[0])continue;let{id:m,...h}=c,y=await s.update(a).set(h).where(eq(u,m)).returning();y[0]&&l.updated.push(y[0]);}if(r.delete)for(let c of r.delete)(await s.delete(a).where(f(eq(u,c),eq(d,e))).returning())[0]&&l.deleted.push(c);if(r.connect)for(let c of r.connect)(await s.update(a).set({[n.foreignKey]:e}).where(eq(u,c)).returning())[0]&&l.connected.push(c);if(r.disconnect)for(let c of r.disconnect)(await s.update(a).set({[n.foreignKey]:null}).where(f(eq(u,c),eq(d,e))).returning())[0]&&l.disconnected.push(c);return l}async handle(){return this.useTransaction?ne(this,()=>super.handle()):super.handle()}},K=class extends DeleteEndpoint{db;useTransaction=false;getDb(){return b(this)}getTable(){return z(this._meta)}managedTimestampValue(e){return S(p(this.getTable(),e))}getColumn(e){return p(this.getTable(),e)}getRelatedTable(e){return e.table}async findForDelete(e,t,n){let r=n??this.getDb(),i=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[u,c]of Object.entries(t))l.push(eq(this.getColumn(u),c));return k(l,a,u=>this.getColumn(u)),(await r.select().from(i).where(f(...l)).limit(1))[0]||null}async delete(e,t,n){let r=n??this.getDb(),i=this.getTable(),s=this.getColumn(this.lookupField),a=this.getSoftDeleteConfig(),l=[eq(s,e)];if(t)for(let[d,u]of Object.entries(t))l.push(eq(this.getColumn(d),u));return k(l,a,d=>this.getColumn(d)),a.enabled?(await r.update(i).set({[a.field]:this.managedTimestampValue(a.field)}).where(f(...l)).returning())[0]||null:(await r.delete(i).where(f(...l)).returning())[0]||null}async countRelated(e,t,n,r){let i=r??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=p(s,n.foreignKey),l=await i.select({count:sql`count(*)`}).from(s).where(eq(a,e));return A(l)}async deleteRelated(e,t,n,r){let i=r??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=p(s,n.foreignKey);return (await i.delete(s).where(eq(a,e)).returning()).length}async nullifyRelated(e,t,n,r){let i=r??this.getDb(),s=this.getRelatedTable(n);if(!s)return 0;let a=p(s,n.foreignKey);return (await i.update(s).set({[n.foreignKey]:null}).where(eq(a,e)).returning()).length}async handle(){return this.useTransaction?ne(this,()=>super.handle()):super.handle()}},Q=class extends ListEndpoint{db;dialect="sqlite";supportsCursorPagination=true;getDb(){return b(this)}getTable(){return z(this._meta)}getColumn(e){return p(this.getTable(),e)}async list(e){let t=await ie({db:this.getDb(),table:this.getTable(),filters:e,dialect:this.dialect,searchFields:this.searchFields,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage,primaryKeys:this._meta.model.primaryKeys,cursorField:this.isCursorPaginationActive()?this.cursorField||"id":void 0}),n=buildIncludeOptions(e.options.include,this.getRelationScope(e.options.withDeleted));if(t.cursor){let{items:i,result_info:s}=buildCursorPage({rows:t.records,limit:t.cursor.limit,totalCount:t.totalCount,cursorField:this.cursorField||"id",primaryKeys:this._meta.model.primaryKeys,direction:t.cursor.direction,cursorApplied:t.cursor.applied});return {result:await O(this.getDb(),i,this._meta,n),result_info:s}}return {result:await O(this.getDb(),t.records,this._meta,n),result_info:buildOffsetPageInfo({page:t.page,perPage:t.perPage,totalCount:t.totalCount})}}},W=class extends RestoreEndpoint{db;useTransaction=false;getDb(){return b(this)}getTable(){return z(this._meta)}getColumn(e){return p(this.getTable(),e)}async restore(e,t,n){let r=n??this.getDb(),i=this.getTable(),s=this.getColumn(this.lookupField),a=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(a.field))),(await r.update(i).set({[a.field]:null}).where(f(...l)).returning())[0]||null}async handle(){return this.useTransaction?ne(this,()=>super.handle()):super.handle()}};var H=class extends BatchCreateEndpoint{db;getDb(){return b(this)}getTable(){return z(this._meta)}managedTimestampValue(e){return S(p(this.getTable(),e))}async batchCreate(e){let t=this.getTable(),n=e.map(i=>this.applyManagedInsertFields(i,"drizzle"));return await this.getDb().insert(t).values(n).returning()}},G=class extends BatchUpdateEndpoint{db;getDb(){return b(this)}getTable(){return z(this._meta)}managedTimestampValue(e){return S(p(this.getTable(),e))}getColumn(e){return p(this.getTable(),e)}async batchUpdate(e){let t=this.getTable(),n=this.getColumn(this.lookupField),r=this.getSoftDeleteConfig(),i=[],s=[],a=this.getTenantScopeFilter();for(let l of e){let d=[eq(n,l.id)];k(d,r,c=>this.getColumn(c)),a&&d.push(eq(this.getColumn(a.field),a.value));let u=await this.getDb().update(t).set(this.applyManagedUpdateFields(l.data)).where(f(...d)).returning();u[0]?i.push(u[0]):s.push(l.id);}return {updated:i,notFound:s}}},X=class extends BatchDeleteEndpoint{db;getDb(){return b(this)}getTable(){return z(this._meta)}managedTimestampValue(e){return S(p(this.getTable(),e))}getColumn(e){return p(this.getTable(),e)}async batchDelete(e){let t=this.getTable(),n=this.getColumn(this.lookupField),r=this.getSoftDeleteConfig(),i=[inArray(n,e)];k(i,r,c=>this.getColumn(c));let s=this.getTenantScopeFilter();s&&i.push(eq(this.getColumn(s.field),s.value));let a;r.enabled?a=await this.getDb().update(t).set({[r.field]:this.managedTimestampValue(r.field)}).where(f(...i)).returning():a=await this.getDb().delete(t).where(f(...i)).returning();let l=a,d=new Set(l.map(c=>String(c[this.lookupField]))),u=e.filter(c=>!d.has(c));return {deleted:l,notFound:u}}},J=class extends BatchRestoreEndpoint{db;getDb(){return b(this)}getTable(){return z(this._meta)}getColumn(e){return p(this.getTable(),e)}async batchRestore(e){let t=this.getTable(),n=this.getColumn(this.lookupField),r=this.getSoftDeleteConfig(),i=[inArray(n,e),isNotNull(this.getColumn(r.field))],s=this.getTenantScopeFilter();s&&i.push(eq(this.getColumn(s.field),s.value));let l=await this.getDb().update(t).set({[r.field]:null}).where(f(...i)).returning(),d=new Set(l.map(c=>String(c[this.lookupField]))),u=e.filter(c=>!d.has(c));return {restored:l,notFound:u}}};var ot="unicode61 remove_diacritics 2",it=[2,3];function se(o){return `"${o.replace(/"/g,'""')}"`}function he(o){return `'${o.replace(/'/g,"''")}'`}function rt(o,e,t){let n=getTableColumns(o),r=n[e];if(!r||typeof r.name!="string")throw new Error(`defineFts5Index: column '${e}' not found in table. Available columns: ${Object.keys(n).join(", ")}`);return r.keyAsName===true&&t==="snake_case"?toSnakeCase(r.name):r.keyAsName===true&&t==="camelCase"?toCamelCase(r.name):r.name}function an(o){let{table:e,columns:t}=o;if(t.length===0)throw new Error("defineFts5Index: `columns` must list at least one field");if(new Set(t).size!==t.length)throw new Error("defineFts5Index: `columns` contains duplicates");let n=o.prefixIndex??it;for(let I of n)if(!Number.isInteger(I)||I<1||I>99)throw new Error(`defineFts5Index: invalid prefixIndex length ${I} (1-99)`);let r=getTableName(e),i=o.name??`${r}_fts`,s=t.map(I=>rt(e,I,o.casing)),a=o.contentRowid===void 0?"rowid":rt(e,o.contentRowid,o.casing),l=o.tokenize??ot,d=se(i),u=se(r),c=o.contentRowid===void 0?"rowid":se(a),g=s.map(se),m=g.join(", "),h=g.map(I=>`new.${I}`).join(", "),y=g.map(I=>`old.${I}`).join(", "),R=I=>se(`${i}_${I}`),T=`INSERT INTO ${d}(${d}, rowid, ${m}) VALUES('delete', old.${c}, ${y});`,E=`INSERT INTO ${d}(rowid, ${m}) VALUES (new.${c}, ${h});`,w=[...g,...o.contentRowid===void 0?[]:[c]].join(", "),B=[`content=${he(r)}`,`content_rowid=${he(a)}`,`tokenize=${he(l)}`,...n.length>0?[`prefix=${he(n.join(" "))}`]:[]],x=`INSERT INTO ${d}(${d}) VALUES('rebuild')`;return {name:i,table:e,tableName:r,fields:[...t],columnNames:s,contentRowid:o.contentRowid,contentRowidColumn:a,migration:()=>[`CREATE VIRTUAL TABLE IF NOT EXISTS ${d} USING fts5(${m}, ${B.join(", ")})`,`CREATE TRIGGER IF NOT EXISTS ${R("ai")} AFTER INSERT ON ${u} BEGIN ${E} END`,`CREATE TRIGGER IF NOT EXISTS ${R("ad")} AFTER DELETE ON ${u} BEGIN ${T} END`,`CREATE TRIGGER IF NOT EXISTS ${R("au")} AFTER UPDATE OF ${w} ON ${u} BEGIN ${T} ${E} END`,x],dropMigration:()=>[`DROP TRIGGER IF EXISTS ${R("ai")}`,`DROP TRIGGER IF EXISTS ${R("ad")}`,`DROP TRIGGER IF EXISTS ${R("au")}`,`DROP TABLE IF EXISTS ${d}`],rebuild:()=>x}}function Oe(o){return `"${o.replace(/"/g,'""')}"`}function st(o){return o.split(/\s+/).map(e=>e.trim()).filter(e=>/[\p{L}\p{N}]/u.test(e))}function Ne(o,e){let t=st(o);if(t.length===0)return null;let n=e.prefix??"last",r=(s,a)=>n==="all"||n==="last"&&s===a-1?"*":"",i;if(e.mode==="phrase")i=`${Oe(t.join(" "))}${r(0,1)}`;else {let s=e.mode==="all"?" AND ":" OR ";i=t.map((a,l)=>`${Oe(a)}${r(l,t.length)}`).join(s);}return e.columns&&e.columns.length>0?`{${e.columns.map(Oe).join(" ")}} : (${i})`:i}var be="__fts5_rank",ze="__fts5_snippet_",ln="fts5_hits",Ae="",at="";function lt(o,e,t,n){let r=sql.identifier(o.name),i=sql.identifier(ln),s=sql.join(t.map(g=>sql.raw(String(g))),sql.raw(", ")),a=o.columnNames.map((g,m)=>sql`snippet(${r}, ${sql.raw(String(m))}, ${Ae}, ${at}, ${"\u2026"}, ${sql.raw(String(n))}) AS ${sql.identifier(`s${m}`)}`),l=sql`(SELECT ${r}.rowid AS ${sql.identifier("fts_rowid")}, bm25(${r}, ${s}) AS ${sql.identifier("fts_rank")}, ${sql.join(a,sql.raw(", "))} FROM ${r} WHERE ${r} MATCH ${e}) AS ${i}`,d=o.contentRowid===void 0?sql`${sql.identifier(o.tableName)}.rowid`:sql`${sql.identifier(o.tableName)}.${sql.identifier(o.contentRowidColumn)}`,u=sql`${i}.${sql.identifier("fts_rank")}`,c={[be]:u};return o.columnNames.forEach((g,m)=>{c[`${ze}${m}`]=sql`${i}.${sql.identifier(`s${m}`)}`;}),{source:l,on:sql`${i}.${sql.identifier("fts_rowid")} = ${d}`,rank:u,selection:c}}function dt(o){let e=Math.max(0,-o);return e/(1+e)}function ct(o){let e=Math.min(Math.max(o,0),.999999);return -(e/(1-e))}function dn(o){return o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function ut(o,e){return typeof o!="string"||!o.includes(Ae)?null:dn(o).split(Ae).join(`<${e}>`).split(at).join(`</${e}>`)}function vn(o){return o.split(/\s+/).filter(e=>e.length>0)}var Y=class extends UpsertEndpoint{db;dialect="sqlite";getDb(){return b(this)}getTable(){return z(this._meta)}managedTimestampValue(e){return S(p(this.getTable(),e))}getColumn(e){return p(this.getTable(),e)}async findExisting(e){return ge(this.getDb(),this.getTable(),t=>this.getColumn(t),e,this.getUpsertKeys())}async create(e){let t=this.getTable(),n=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(n).returning())[0]}async update(e,t){let n=this.getTable(),r=this._meta.model.primaryKeys[0],i=e[r];return (await this.getDb().update(n).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(r),i)).returning())[0]}async nativeUpsert(e,t){let n=this.getTable(),r=this.getUpsertKeys(),i=this._meta.model.primaryKeys[0],s=this.getSoftDeleteConfig(),a=this.getTimestampsConfig(),l=this.applyManagedInsertFields(e,"drizzle"),d={};for(let[y,R]of Object.entries(e))!r.includes(y)&&y!==i&&(this.createOnlyFields?.includes(y)||(d[y]=R));a.enabled&&(d[a.updatedAt]=Date.now());let u=r.map(y=>this.getColumn(y)),c;s.enabled&&(c=isNull(this.getColumn(s.field)));let g=Object.keys(d).length>0?d:{[i]:sql`${this.getColumn(i)}`},m=this.getDb().insert(n).values(l);return this.dialect==="mysql"?{data:(await m.onDuplicateKeyUpdate({set:g}).returning())[0],created:false}:{data:(await m.onConflictDoUpdate({target:u,set:g,where:c}).returning())[0],created:false}}},ee=class extends BatchUpsertEndpoint{db;dialect="sqlite";getDb(){return b(this)}getTable(){return z(this._meta)}managedTimestampValue(e){return S(p(this.getTable(),e))}getColumn(e){return p(this.getTable(),e)}async findExisting(e){return ge(this.getDb(),this.getTable(),t=>this.getColumn(t),e,this.getUpsertKeys())}async create(e){let t=this.getTable(),n=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(n).returning())[0]}async update(e,t){let n=this.getTable(),r=this._meta.model.primaryKeys[0],i=e[r];return (await this.getDb().update(n).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(r),i)).returning())[0]}async nativeBatchUpsert(e,t){if(e.length===0)return {items:[],createdCount:0,updatedCount:0,totalCount:0};let n=this.getTable(),r=this.getUpsertKeys(),i=this._meta.model.primaryKeys[0],s=this.getTimestampsConfig(),a=e.map(h=>this.applyManagedInsertFields(h,"drizzle")),l={},d=e[0];for(let h of Object.keys(d))!r.includes(h)&&h!==i&&(this.createOnlyFields?.includes(h)||(l[h]=sql`excluded.${sql.identifier(h)}`));s.enabled&&(l[s.updatedAt]=Date.now());let u=r.map(h=>this.getColumn(h)),c=Object.keys(l).length>0?l:{[i]:sql`${this.getColumn(i)}`},g=this.getDb().insert(n).values(a),m=await(this.dialect==="mysql"?g.onDuplicateKeyUpdate({set:c}):g.onConflictDoUpdate({target:u,set:c})).returning();return {items:m.map((h,y)=>({data:h,created:false,index:y})),createdCount:0,updatedCount:m.length,totalCount:m.length}}},ye=class extends BulkPatchEndpoint{db;dialect="sqlite";getDb(){return b(this)}getTable(){return z(this._meta)}managedTimestampValue(e){return S(p(this.getTable(),e))}getColumn(e){return p(this.getTable(),e)}buildConditions(e){let t=this.getTable(),n=[];for(let i of e.filters){let s=oe(t,i,this.dialect);s&&n.push(s);}let r=this.getSoftDeleteConfig();return k(n,r,i=>this.getColumn(i)),n}async countMatching(e){let t=this.buildConditions(e),n=await this.getDb().select({count:sql`count(*)`}).from(this.getTable()).where(f(...t));return A(n)}async applyPatch(e,t){let n=this.buildConditions(t),r=await this.getDb().update(this.getTable()).set(this.applyManagedUpdateFields(e)).where(f(...n)).returning();return {updated:r.length,records:r}}};async function Se(o,e,t,n,r){let i=r?f(eq(t,n),eq(p(e,r.field),r.value)):eq(t,n),s=await o.select({count:sql`count(*)`}).from(e).where(i);return A(s)>0}var we=class extends VersionHistoryEndpoint{db;getDb(){return b(this)}getTable(){return z(this._meta)}getColumn(e){return p(this.getTable(),e)}async recordExists(e,t){return Se(this.getDb(),this.getTable(),this.getColumn("id"),e,t)}},Ce=class extends VersionReadEndpoint{db;getDb(){return b(this)}getTable(){return z(this._meta)}getColumn(e){return p(this.getTable(),e)}async recordExists(e,t){return Se(this.getDb(),this.getTable(),this.getColumn("id"),e,t)}},Re=class extends VersionCompareEndpoint{db;getDb(){return b(this)}getTable(){return z(this._meta)}getColumn(e){return p(this.getTable(),e)}async recordExists(e,t){return Se(this.getDb(),this.getTable(),this.getColumn("id"),e,t)}},Te=class extends VersionRollbackEndpoint{db;getDb(){return b(this)}getTable(){return z(this._meta)}getColumn(e){return p(this.getTable(),e)}async recordExists(e,t){return Se(this.getDb(),this.getTable(),this.getColumn("id"),e,t)}async rollback(e,t,n){let r=this.getTable(),i=this.getVersioningConfig().field;return (await this.getDb().update(r).set({...t,[i]:n}).where(eq(this.getColumn("id"),e)).returning())[0]}},Me=class extends AggregateEndpoint{db;dialect="sqlite";getDb(){return b(this)}getTable(){return z(this._meta)}getColumn(e){return p(this.getTable(),e)}async aggregate(e){let t=this.getTable(),n=[],r=this.getSoftDeleteConfig();if(r.enabled){let{query:a}=await this.getValidatedData();a?.withDeleted===true||a?.withDeleted==="true"||k(n,r,d=>this.getColumn(d));}if(e.filters)for(let[a,l]of Object.entries(e.filters))if(typeof l=="object"&&l!==null)for(let[d,u]of Object.entries(l)){if(!isFilterOperator(d)){n.push(sql`1 = 0`);continue}let c=oe(t,{field:a,operator:d,value:u},this.dialect);c&&n.push(c);}else n.push(eq(this.getColumn(a),l));let i=n.length>0?f(...n):void 0,s=await this.getDb().select().from(t).where(i);return computeAggregations(s,e)}},te=class extends SearchEndpoint{db;dialect="sqlite";getDb(){return b(this)}useNativeSearch=false;vectorColumn;vectorConfig="english";fts5;fts5PrefixMatch="last";fts5SnippetTokens=24;getSearchableFields(){let e=Object.keys(this.searchableFields).length>0||this.searchFields.length>0;return this.fts5&&!e?Object.fromEntries(this.fts5.fields.map(t=>[t,{weight:this.fieldWeights[t]??1}])):super.getSearchableFields()}getTable(){return z(this._meta)}getColumn(e){return p(this.getTable(),e)}async search(e,t){if(this.fts5)return this.searchFts5(this.fts5,e,t);let n=this.getTable(),r=[],i=this.getSearchableFields(),s=e.fields||Object.keys(i);if(this.useNativeSearch&&this.vectorColumn){let R=this.getColumn(this.vectorColumn),T=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(" | ")})`;r.push(sql`${R} @@ ${T}`);}else {let R=(T,E)=>{try{let w=this.getColumn(T);return L(sql`CAST(${w} AS TEXT)`,E,this.dialect)}catch{return}};if(e.mode==="all"){let T=vn(e.query);if(T.length>0){let E=[];for(let w of T){let B=s.map(x=>R(x,w)).filter(x=>x!==void 0);B.length>0&&E.push(re(...B));}E.length>0&&r.push(f(...E));}}else {let T=s.map(E=>R(E,e.query)).filter(E=>E!==void 0);T.length>0&&r.push(re(...T));}}let a=await ie({db:this.getDb(),table:n,filters:t,dialect:this.dialect,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage,primaryKeys:this._meta.model.primaryKeys,extraConditions:r}),l=a.records,d=a.totalCount,u=e.mode==="all"?{...e,mode:"any"}:e,c=searchInMemory(l,u,i),g=buildIncludeOptions(t.options.include,this.getRelationScope(t.options.withDeleted)),m=c.map(R=>R.item),h=await O(this.getDb(),m,this._meta,g);return {items:c.map((R,T)=>({...R,item:h[T]})),totalCount:d}}async searchFts5(e,t,n){if(this.dialect!=="sqlite")throw new ConfigurationException(`fts5 search requires dialect 'sqlite' (SQLite / Cloudflare D1), got '${this.dialect}'.`);let r=this.getTable(),i=getTableName(r);if(i!==e.tableName)throw new ConfigurationException(`fts5 index '${e.name}' indexes table '${e.tableName}', but this endpoint's model table is '${i}'.`);let s=this.getSearchableFields(),a=Object.keys(s).filter(M=>!e.fields.includes(M));if(a.length>0)throw new ConfigurationException(`Searchable fields [${a.join(", ")}] are not columns of fts5 index '${e.name}' (indexed: ${e.fields.join(", ")}).`);let l=(t.fields??Object.keys(s)).filter(M=>e.fields.includes(M)),d=l.length>0&&l.length<e.fields.length,u=Ne(t.query,{mode:t.mode,prefix:this.fts5PrefixMatch,columns:d?l.map(M=>e.columnNames[e.fields.indexOf(M)]):void 0});if(u===null||l.length===0)return {items:[],totalCount:0};let c=e.fields.map(M=>{let N=s[M]?.weight??1;return Number.isFinite(N)?N:1}),g=Math.min(64,Math.max(1,Math.trunc(this.fts5SnippetTokens))),m=lt(e,u,c,g),h=Fe({table:r,filters:n,dialect:this.dialect,softDeleteConfig:this.getSoftDeleteConfig(),extraConditions:t.minScore>0?[sql`${m.rank} <= ${ct(t.minScore)}`]:[]}),y=this.getDb(),R=await y.select({count:sql`count(*)`}).from(r).innerJoin(m.source,m.on).where(h),T=A(R),E=this._meta.model.primaryKeys,w=n.options.order_by,B=n.options.order_by_direction==="desc"?desc:asc,x=w?[B(this.getColumn(w)),asc(m.rank)]:[asc(m.rank)];for(let M of E)M!==w&&x.push((w?B:asc)(this.getColumn(M)));let I=n.options.page||1,ce=n.options.per_page||this.defaultPerPage,Ue=(await y.select({...getTableColumns(r),...m.selection}).from(r).innerJoin(m.source,m.on).where(h).orderBy(...x).limit(ce).offset((I-1)*ce)).map(M=>{let N={},Ve=[];for(let[F,ue]of Object.entries(M))if(F!==be){if(F.startsWith(ze)){Ve[Number(F.slice(ze.length))]=ue;continue}N[F]=ue;}let Ze={},Ke=[];return e.fields.forEach((F,ue)=>{if(!l.includes(F))return;let Qe=ut(Ve[ue],this.highlightTag);Qe!==null&&(Ke.push(F),Ze[F]=[Qe]);}),{item:N,score:dt(Number(M[be])),matchedFields:Ke,...t.highlight?{highlights:Ze}:{}}}),Dt=buildIncludeOptions(n.options.include,this.getRelationScope(n.options.withDeleted)),yt=await O(y,Ue.map(M=>M.item),this._meta,Dt);return {items:Ue.map((M,N)=>({...M,item:yt[N]})),totalCount:T}}},Ee=class extends ExportEndpoint{db;dialect="sqlite";getDb(){return b(this)}getTable(){return z(this._meta)}getColumn(e){return p(this.getTable(),e)}async list(e){let t=await ie({db:this.getDb(),table:this.getTable(),filters:e,dialect:this.dialect,searchFields:this.searchFields,softDeleteConfig:this.getSoftDeleteConfig(),defaultPerPage:this.defaultPerPage,primaryKeys:this._meta.model.primaryKeys}),n=buildIncludeOptions(e.options.include,this.getRelationScope(e.options.withDeleted));return {result:await O(this.getDb(),t.records,this._meta,n),result_info:buildOffsetPageInfo({page:t.page,perPage:t.perPage,totalCount:t.totalCount})}}},xe=class extends ImportEndpoint{db;getDb(){return b(this)}getTable(){return z(this._meta)}managedTimestampValue(e){return S(p(this.getTable(),e))}getColumn(e){return p(this.getTable(),e)}async findExisting(e){return ge(this.getDb(),this.getTable(),t=>this.getColumn(t),e,this.getUpsertKeys())}async create(e){let t=this.getTable(),n=this.applyManagedInsertFields(e,"drizzle");return (await this.getDb().insert(t).values(n).returning())[0]}async update(e,t){let n=this.getTable(),r=this._meta.model.primaryKeys[0],i=e[r];return (await this.getDb().update(n).set(this.applyManagedUpdateFields(t)).where(eq(this.getColumn(r),i)).returning())[0]}},Ie=class extends CloneEndpoint{db;getDb(){return b(this)}getTable(){return z(this._meta)}managedTimestampValue(e){return S(p(this.getTable(),e))}getColumn(e){return p(this.getTable(),e)}generateId(){return crypto.randomUUID()}async findSource(e,t){let n=this.getTable(),r=this.getColumn(this.lookupField),i=this.getSoftDeleteConfig(),s=[eq(r,e)];if(t)for(let[l,d]of Object.entries(t))s.push(eq(this.getColumn(l),d));k(s,i,l=>this.getColumn(l));let a=await this.getDb().select().from(n).where(f(...s)).limit(1);return a[0]?a[0]:null}async createClone(e){let t=this.getTable(),n=this.applyManagedInsertFields(e,"drizzle",()=>this.generateId());return (await this.getDb().insert(t).values(n).returning())[0]}};function Wr(o,e,t){let n=t?.dialect??"sqlite";return {Create:class extends U{_meta=e;db=o},Read:class extends V{_meta=e;db=o},Update:class extends Z{_meta=e;db=o},Delete:class extends K{_meta=e;db=o},List:class extends Q{_meta=e;db=o;dialect=n},Restore:class extends W{_meta=e;db=o},Upsert:class extends Y{_meta=e;db=o;dialect=n},Search:class extends te{_meta=e;db=o;dialect=n},BatchCreate:class extends H{_meta=e;db=o},BatchUpdate:class extends G{_meta=e;db=o},BatchDelete:class extends X{_meta=e;db=o},BatchRestore:class extends J{_meta=e;db=o},BatchUpsert:class extends ee{_meta=e;db=o;dialect=n}}}var gt=class{db;table;constructor(e){this.db=e.db,this.table=e.table;}col(e){return p(this.table,e)}recordScope(e,t){return and(eq(this.col("resourceTable"),e),eq(this.col("recordId"),String(t)))}toEntry(e){return {id:e.id,recordId:e.recordId,version:e.version,data:JSON.parse(e.data),createdAt:new Date(e.createdAt),...e.changedBy!=null?{changedBy:e.changedBy}:{},...e.changeReason!=null?{changeReason:e.changeReason}:{},...e.changes!=null?{changes:JSON.parse(e.changes)}:{}}}async store(e,t){let n=t.createdAt instanceof Date?t.createdAt:new Date(t.createdAt);await this.db.insert(this.table).values({id:t.id,resourceTable:e,recordId:String(t.recordId),version:t.version,data:JSON.stringify(t.data),createdAt:n.getTime(),changedBy:t.changedBy??null,changeReason:t.changeReason??null,changes:t.changes?JSON.stringify(t.changes):null});}async getByRecordId(e,t,n){let r=this.db.select().from(this.table).where(this.recordScope(e,t)).orderBy(desc(this.col("version")));return (n?.limit!=null||n?.offset!=null)&&(r=r.limit(n?.limit??Number.MAX_SAFE_INTEGER)),n?.offset!=null&&(r=r.offset(n.offset)),(await r).map(s=>this.toEntry(s))}async getVersion(e,t,n){let r=await this.db.select().from(this.table).where(and(this.recordScope(e,t),eq(this.col("version"),n))).limit(1);return r.length>0?this.toEntry(r[0]):null}async getLatestVersion(e,t){let n=await this.db.select().from(this.table).where(this.recordScope(e,t)).orderBy(desc(this.col("version"))).limit(1);return n.length>0?n[0].version:0}async pruneVersions(e,t,n){if(n<=0)return this.deleteAllVersions(e,t);let r=await this.getByRecordId(e,t);if(r.length<=n)return 0;let i=r[n-1].version;return (await this.db.delete(this.table).where(and(this.recordScope(e,t),lt$1(this.col("version"),i))).returning()).length}async deleteAllVersions(e,t){return (await this.db.delete(this.table).where(this.recordScope(e,t)).returning()).length}};function Pn(){return {id:text("id").primaryKey(),resourceTable:text("resource_table").notNull(),recordId:text("record_id").notNull(),version:integer("version").notNull(),data:text("data").notNull(),createdAt:integer("created_at").notNull(),changedBy:text("changed_by"),changeReason:text("change_reason"),changes:text("changes")}}function mo(o="version_history",e){return sqliteTable(o,Pn(),t=>[index(`${o}_record_version_idx`).on(t.resourceTable,t.recordId,t.version),...e?.(t)??[]])}var ht=class{db;table;constructor(e){this.db=e.db,this.table=e.table;}col(e){return p(this.table,e)}toEntry(e){return {id:e.id,timestamp:new Date(e.timestamp),action:e.action,tableName:e.tableName,recordId:e.recordId,...e.userId!=null?{userId:e.userId}:{},...e.record!=null?{record:JSON.parse(e.record)}:{},...e.previousRecord!=null?{previousRecord:JSON.parse(e.previousRecord)}:{},...e.changes!=null?{changes:JSON.parse(e.changes)}:{},...e.metadata!=null?{metadata:JSON.parse(e.metadata)}:{}}}async store(e){let t=e.timestamp instanceof Date?e.timestamp:new Date(e.timestamp);await this.db.insert(this.table).values({id:e.id,tableName:e.tableName,recordId:String(e.recordId),action:e.action,timestamp:t.getTime(),userId:e.userId??null,record:e.record!==void 0?JSON.stringify(e.record):null,previousRecord:e.previousRecord!==void 0?JSON.stringify(e.previousRecord):null,changes:e.changes!==void 0?JSON.stringify(e.changes):null,metadata:e.metadata!==void 0?JSON.stringify(e.metadata):null});}async getByRecordId(e,t,n){let r=this.db.select().from(this.table).where(f(eq(this.col("tableName"),e),eq(this.col("recordId"),String(t)))).orderBy(asc(this.col("timestamp")),asc(this.col("id"))),i=n?.offset||0,s=n?.limit||0;return s>0?(r=r.limit(s),i>0&&(r=r.offset(i))):i>0&&(r=r.limit(Number.MAX_SAFE_INTEGER),r=r.offset(i)),(await r).map(l=>this.toEntry(l))}async getAll(e){let t=[];e?.tableName&&t.push(eq(this.col("tableName"),e.tableName)),e?.action&&t.push(eq(this.col("action"),e.action)),e?.userId&&t.push(eq(this.col("userId"),e.userId)),e?.startDate&&t.push(gte(this.col("timestamp"),e.startDate.getTime())),e?.endDate&&t.push(lte(this.col("timestamp"),e.endDate.getTime()));let n=t.length>0?f(...t):void 0,r=this.db.select().from(this.table).where(n).orderBy(asc(this.col("timestamp")),asc(this.col("id"))),i=e?.offset||0,s=e?.limit||0;return s>0?(r=r.limit(s),i>0&&(r=r.offset(i))):i>0&&(r=r.limit(Number.MAX_SAFE_INTEGER),r=r.offset(i)),(await r).map(l=>this.toEntry(l))}};function $n(){return {id:text("id").primaryKey(),tableName:text("table_name").notNull(),recordId:text("record_id").notNull(),action:text("action").notNull(),timestamp:integer("timestamp").notNull(),userId:text("user_id"),record:text("record"),previousRecord:text("previous_record"),changes:text("changes"),metadata:text("metadata")}}function zo(o="audit_logs",e){return sqliteTable(o,$n(),t=>[index(`${o}_record_idx`).on(t.tableName,t.recordId),index(`${o}_timestamp_idx`).on(t.timestamp),...e?.(t)??[]])}var le=null,bt=false,ke=null;async function Be(){if(bt){if(ke)throw ke;if(le)return le}bt=true;try{return le=await import('drizzle-zod'),le}catch{throw ke=new Error("drizzle-zod is not installed. Please install it: npm install drizzle-zod"),ke}}async function qn(o,e){return (await Be()).createSelectSchema(o,e)}async function Ln(o,e){return (await Be()).createInsertSchema(o,e)}async function jn(o,e){let t=await Be();return t.createUpdateSchema?t.createUpdateSchema(o,e):t.createInsertSchema(o,e).partial()}async function Un(o,e){let t=await Be(),n=e?.coerceDates!==false,r=n?Qn(o):new Set,i=t.createSelectSchema(o,e?.selectRefine),s=t.createInsertSchema(o,e?.insertRefine),a;return t.createUpdateSchema?a=t.createUpdateSchema(o,e?.updateRefine):a=t.createInsertSchema(o,e?.updateRefine).partial(),n&&r.size>0&&(s=zt(s,r),a=zt(a,r)),{select:i,insert:s,update:a}}function Vn(){return le!==null}var Zn=z$1.preprocess(o=>{if(o instanceof Date)return o;if(typeof o=="string"){let e=new Date(o);if(!isNaN(e.getTime()))return e}return o},z$1.date()),Kn=z$1.preprocess(o=>{if(o==null)return null;if(o instanceof Date)return o;if(typeof o=="string"){let e=new Date(o);if(!isNaN(e.getTime()))return e}return o},z$1.date().nullable());function Qn(o){let e=new Set,t=o;for(let[n,r]of Object.entries(t)){if(n==="_"||n==="$inferInsert"||n==="$inferSelect")continue;let i=r;if(!i||typeof i!="object")continue;let s=String(i.dataType??"").toLowerCase(),a=String(i.columnType??"").toLowerCase(),l=i.config,d=String(l?.dataType??"").toLowerCase();(s.includes("timestamp")||s.includes("date")||s.includes("datetime")||a.includes("pgtimestamp")||a.includes("pgdate")||a.includes("mysqltimestamp")||a.includes("mysqldate")||a.includes("sqlitetimestamp")||d.includes("timestamp")||d.includes("date"))&&e.add(n);}return e}function zt(o,e){if(e.size===0)return o;let t=o.shape,n={};for(let[r,i]of Object.entries(t))if(e.has(r)){let s=i.isOptional?.()??false,a=i.isNullable?.()??false,l=Zn;(a||s)&&(l=Kn),s&&(l=l.optional()),n[r]=l;}else n[r]=i;return z$1.object(n)}var Mo={CreateEndpoint:U,ListEndpoint:Q,ReadEndpoint:V,UpdateEndpoint:Z,DeleteEndpoint:K,RestoreEndpoint:W,BatchCreateEndpoint:H,BatchUpdateEndpoint:G,BatchDeleteEndpoint:X,BatchRestoreEndpoint:J,BatchUpsertEndpoint:ee,SearchEndpoint:te,AggregateEndpoint:Me,ExportEndpoint:Ee,ImportEndpoint:xe,UpsertEndpoint:Y,CloneEndpoint:Ie,BulkPatchEndpoint:ye,VersionHistoryEndpoint:we,VersionReadEndpoint:Ce,VersionCompareEndpoint:Re,VersionRollbackEndpoint:Te};export{it as DEFAULT_FTS5_PREFIX_INDEX,ot as DEFAULT_FTS5_TOKENIZE,Ot as DRIZZLE_DIALECTS,Mo as DrizzleAdapters,Me as DrizzleAggregateEndpoint,ht as DrizzleAuditLogStorage,H as DrizzleBatchCreateEndpoint,X as DrizzleBatchDeleteEndpoint,J as DrizzleBatchRestoreEndpoint,G as DrizzleBatchUpdateEndpoint,ee as DrizzleBatchUpsertEndpoint,ye as DrizzleBulkPatchEndpoint,Ie as DrizzleCloneEndpoint,U as DrizzleCreateEndpoint,K as DrizzleDeleteEndpoint,Ee as DrizzleExportEndpoint,xe as DrizzleImportEndpoint,Q as DrizzleListEndpoint,V as DrizzleReadEndpoint,W as DrizzleRestoreEndpoint,te as DrizzleSearchEndpoint,Z as DrizzleUpdateEndpoint,Y as DrizzleUpsertEndpoint,Re as DrizzleVersionCompareEndpoint,we as DrizzleVersionHistoryEndpoint,Ce as DrizzleVersionReadEndpoint,Te as DrizzleVersionRollbackEndpoint,gt as DrizzleVersioningStorage,O as batchLoadDrizzleRelations,Ne as buildFts5Match,oe as buildWhereCondition,j as cast,Wr as createDrizzleCrud,Un as createDrizzleSchemas,Ln as createInsertSchema,qn as createSelectSchema,jn as createUpdateSchema,an as defineFts5Index,p as getColumn,z as getTable,Vn as isDrizzleZodAvailable,At as loadDrizzleRelation,Pe as loadDrizzleRelations,A as readCount,$t as resolveTimestampRepresentation,S as resolveTimestampValue,zo as sqliteAuditLogTable,mo as sqliteVersionHistoryTable,L as substringMatch,st as tokenizeFts5Query};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hono-crud/drizzle",
3
- "version": "0.1.24",
3
+ "version": "0.1.25",
4
4
  "description": "Drizzle ORM CRUD adapter for hono-crud",
5
5
  "author": "Kauan Guesser <contato@kauan.net>",
6
6
  "license": "MIT",
@@ -47,7 +47,7 @@
47
47
  "drizzle-zod": ">=0.8.0",
48
48
  "hono": ">=4.11.7 <5",
49
49
  "zod": ">=4.0.0",
50
- "hono-crud": "^0.13.30"
50
+ "hono-crud": "^0.13.31"
51
51
  },
52
52
  "devDependencies": {
53
53
  "drizzle-orm": "^0.45.1",
@@ -56,7 +56,7 @@
56
56
  "tsup": "^8.4.0",
57
57
  "typescript": "^5.8.3",
58
58
  "zod": "^4.3.5",
59
- "hono-crud": "0.13.30"
59
+ "hono-crud": "0.13.31"
60
60
  },
61
61
  "peerDependenciesMeta": {
62
62
  "drizzle-zod": {