@uiid/bertrand 0.10.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/bertrand.js +118 -4474
  2. package/dist/run-screen.js +262 -47936
  3. package/package.json +1 -1
package/dist/bertrand.js CHANGED
@@ -101,4292 +101,6 @@ var init_router = __esm(() => {
101
101
  aliases = new Map;
102
102
  });
103
103
 
104
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/entity.js
105
- function is(value, type) {
106
- if (!value || typeof value !== "object") {
107
- return false;
108
- }
109
- if (value instanceof type) {
110
- return true;
111
- }
112
- if (!Object.prototype.hasOwnProperty.call(type, entityKind)) {
113
- throw new Error(`Class "${type.name ?? "<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);
114
- }
115
- let cls = Object.getPrototypeOf(value).constructor;
116
- if (cls) {
117
- while (cls) {
118
- if (entityKind in cls && cls[entityKind] === type[entityKind]) {
119
- return true;
120
- }
121
- cls = Object.getPrototypeOf(cls);
122
- }
123
- }
124
- return false;
125
- }
126
- var entityKind, hasOwnEntityKind;
127
- var init_entity = __esm(() => {
128
- entityKind = Symbol.for("drizzle:entityKind");
129
- hasOwnEntityKind = Symbol.for("drizzle:hasOwnEntityKind");
130
- });
131
-
132
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/column.js
133
- var Column;
134
- var init_column = __esm(() => {
135
- init_entity();
136
- Column = class Column {
137
- constructor(table, config) {
138
- this.table = table;
139
- this.config = config;
140
- this.name = config.name;
141
- this.keyAsName = config.keyAsName;
142
- this.notNull = config.notNull;
143
- this.default = config.default;
144
- this.defaultFn = config.defaultFn;
145
- this.onUpdateFn = config.onUpdateFn;
146
- this.hasDefault = config.hasDefault;
147
- this.primary = config.primaryKey;
148
- this.isUnique = config.isUnique;
149
- this.uniqueName = config.uniqueName;
150
- this.uniqueType = config.uniqueType;
151
- this.dataType = config.dataType;
152
- this.columnType = config.columnType;
153
- this.generated = config.generated;
154
- this.generatedIdentity = config.generatedIdentity;
155
- }
156
- static [entityKind] = "Column";
157
- name;
158
- keyAsName;
159
- primary;
160
- notNull;
161
- default;
162
- defaultFn;
163
- onUpdateFn;
164
- hasDefault;
165
- isUnique;
166
- uniqueName;
167
- uniqueType;
168
- dataType;
169
- columnType;
170
- enumValues = undefined;
171
- generated = undefined;
172
- generatedIdentity = undefined;
173
- config;
174
- mapFromDriverValue(value) {
175
- return value;
176
- }
177
- mapToDriverValue(value) {
178
- return value;
179
- }
180
- shouldDisableInsert() {
181
- return this.config.generated !== undefined && this.config.generated.type !== "byDefault";
182
- }
183
- };
184
- });
185
-
186
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/column-builder.js
187
- var ColumnBuilder;
188
- var init_column_builder = __esm(() => {
189
- init_entity();
190
- ColumnBuilder = class ColumnBuilder {
191
- static [entityKind] = "ColumnBuilder";
192
- config;
193
- constructor(name, dataType, columnType) {
194
- this.config = {
195
- name,
196
- keyAsName: name === "",
197
- notNull: false,
198
- default: undefined,
199
- hasDefault: false,
200
- primaryKey: false,
201
- isUnique: false,
202
- uniqueName: undefined,
203
- uniqueType: undefined,
204
- dataType,
205
- columnType,
206
- generated: undefined
207
- };
208
- }
209
- $type() {
210
- return this;
211
- }
212
- notNull() {
213
- this.config.notNull = true;
214
- return this;
215
- }
216
- default(value) {
217
- this.config.default = value;
218
- this.config.hasDefault = true;
219
- return this;
220
- }
221
- $defaultFn(fn) {
222
- this.config.defaultFn = fn;
223
- this.config.hasDefault = true;
224
- return this;
225
- }
226
- $default = this.$defaultFn;
227
- $onUpdateFn(fn) {
228
- this.config.onUpdateFn = fn;
229
- this.config.hasDefault = true;
230
- return this;
231
- }
232
- $onUpdate = this.$onUpdateFn;
233
- primaryKey() {
234
- this.config.primaryKey = true;
235
- this.config.notNull = true;
236
- return this;
237
- }
238
- setName(name) {
239
- if (this.config.name !== "")
240
- return;
241
- this.config.name = name;
242
- }
243
- };
244
- });
245
-
246
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/table.utils.js
247
- var TableName;
248
- var init_table_utils = __esm(() => {
249
- TableName = Symbol.for("drizzle:Name");
250
- });
251
-
252
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/tracing-utils.js
253
- function iife(fn, ...args) {
254
- return fn(...args);
255
- }
256
- var init_tracing_utils = () => {};
257
-
258
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/pg-core/unique-constraint.js
259
- function uniqueKeyName(table, columns) {
260
- return `${table[TableName]}_${columns.join("_")}_unique`;
261
- }
262
- var init_unique_constraint = __esm(() => {
263
- init_table_utils();
264
- });
265
-
266
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/pg-core/columns/common.js
267
- var PgColumn, ExtraConfigColumn;
268
- var init_common = __esm(() => {
269
- init_column();
270
- init_entity();
271
- init_unique_constraint();
272
- PgColumn = class PgColumn extends Column {
273
- constructor(table, config) {
274
- if (!config.uniqueName) {
275
- config.uniqueName = uniqueKeyName(table, [config.name]);
276
- }
277
- super(table, config);
278
- this.table = table;
279
- }
280
- static [entityKind] = "PgColumn";
281
- };
282
- ExtraConfigColumn = class ExtraConfigColumn extends PgColumn {
283
- static [entityKind] = "ExtraConfigColumn";
284
- getSQLType() {
285
- return this.getSQLType();
286
- }
287
- indexConfig = {
288
- order: this.config.order ?? "asc",
289
- nulls: this.config.nulls ?? "last",
290
- opClass: this.config.opClass
291
- };
292
- defaultConfig = {
293
- order: "asc",
294
- nulls: "last",
295
- opClass: undefined
296
- };
297
- asc() {
298
- this.indexConfig.order = "asc";
299
- return this;
300
- }
301
- desc() {
302
- this.indexConfig.order = "desc";
303
- return this;
304
- }
305
- nullsFirst() {
306
- this.indexConfig.nulls = "first";
307
- return this;
308
- }
309
- nullsLast() {
310
- this.indexConfig.nulls = "last";
311
- return this;
312
- }
313
- op(opClass) {
314
- this.indexConfig.opClass = opClass;
315
- return this;
316
- }
317
- };
318
- });
319
-
320
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/pg-core/columns/enum.js
321
- function isPgEnum(obj) {
322
- return !!obj && typeof obj === "function" && isPgEnumSym in obj && obj[isPgEnumSym] === true;
323
- }
324
- var PgEnumObjectColumn, isPgEnumSym, PgEnumColumn;
325
- var init_enum = __esm(() => {
326
- init_entity();
327
- init_common();
328
- PgEnumObjectColumn = class PgEnumObjectColumn extends PgColumn {
329
- static [entityKind] = "PgEnumObjectColumn";
330
- enum;
331
- enumValues = this.config.enum.enumValues;
332
- constructor(table, config) {
333
- super(table, config);
334
- this.enum = config.enum;
335
- }
336
- getSQLType() {
337
- return this.enum.enumName;
338
- }
339
- };
340
- isPgEnumSym = Symbol.for("drizzle:isPgEnum");
341
- PgEnumColumn = class PgEnumColumn extends PgColumn {
342
- static [entityKind] = "PgEnumColumn";
343
- enum = this.config.enum;
344
- enumValues = this.config.enum.enumValues;
345
- constructor(table, config) {
346
- super(table, config);
347
- this.enum = config.enum;
348
- }
349
- getSQLType() {
350
- return this.enum.enumName;
351
- }
352
- };
353
- });
354
-
355
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/subquery.js
356
- var Subquery, WithSubquery;
357
- var init_subquery = __esm(() => {
358
- init_entity();
359
- Subquery = class Subquery {
360
- static [entityKind] = "Subquery";
361
- constructor(sql, fields, alias2, isWith = false, usedTables = []) {
362
- this._ = {
363
- brand: "Subquery",
364
- sql,
365
- selectedFields: fields,
366
- alias: alias2,
367
- isWith,
368
- usedTables
369
- };
370
- }
371
- };
372
- WithSubquery = class WithSubquery extends Subquery {
373
- static [entityKind] = "WithSubquery";
374
- };
375
- });
376
-
377
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/version.js
378
- var version = "0.44.7";
379
- var init_version = () => {};
380
-
381
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/tracing.js
382
- var otel, rawTracer, tracer;
383
- var init_tracing = __esm(() => {
384
- init_tracing_utils();
385
- init_version();
386
- tracer = {
387
- startActiveSpan(name, fn) {
388
- if (!otel) {
389
- return fn();
390
- }
391
- if (!rawTracer) {
392
- rawTracer = otel.trace.getTracer("drizzle-orm", version);
393
- }
394
- return iife((otel2, rawTracer2) => rawTracer2.startActiveSpan(name, (span) => {
395
- try {
396
- return fn(span);
397
- } catch (e) {
398
- span.setStatus({
399
- code: otel2.SpanStatusCode.ERROR,
400
- message: e instanceof Error ? e.message : "Unknown error"
401
- });
402
- throw e;
403
- } finally {
404
- span.end();
405
- }
406
- }), otel, rawTracer);
407
- }
408
- };
409
- });
410
-
411
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/view-common.js
412
- var ViewBaseConfig;
413
- var init_view_common = __esm(() => {
414
- ViewBaseConfig = Symbol.for("drizzle:ViewBaseConfig");
415
- });
416
-
417
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/table.js
418
- function getTableName(table) {
419
- return table[TableName];
420
- }
421
- function getTableUniqueName(table) {
422
- return `${table[Schema] ?? "public"}.${table[TableName]}`;
423
- }
424
- var Schema, Columns, ExtraConfigColumns, OriginalName, BaseName, IsAlias, ExtraConfigBuilder, IsDrizzleTable, Table;
425
- var init_table = __esm(() => {
426
- init_entity();
427
- init_table_utils();
428
- Schema = Symbol.for("drizzle:Schema");
429
- Columns = Symbol.for("drizzle:Columns");
430
- ExtraConfigColumns = Symbol.for("drizzle:ExtraConfigColumns");
431
- OriginalName = Symbol.for("drizzle:OriginalName");
432
- BaseName = Symbol.for("drizzle:BaseName");
433
- IsAlias = Symbol.for("drizzle:IsAlias");
434
- ExtraConfigBuilder = Symbol.for("drizzle:ExtraConfigBuilder");
435
- IsDrizzleTable = Symbol.for("drizzle:IsDrizzleTable");
436
- Table = class Table {
437
- static [entityKind] = "Table";
438
- static Symbol = {
439
- Name: TableName,
440
- Schema,
441
- OriginalName,
442
- Columns,
443
- ExtraConfigColumns,
444
- BaseName,
445
- IsAlias,
446
- ExtraConfigBuilder
447
- };
448
- [TableName];
449
- [OriginalName];
450
- [Schema];
451
- [Columns];
452
- [ExtraConfigColumns];
453
- [BaseName];
454
- [IsAlias] = false;
455
- [IsDrizzleTable] = true;
456
- [ExtraConfigBuilder] = undefined;
457
- constructor(name, schema, baseName) {
458
- this[TableName] = this[OriginalName] = name;
459
- this[Schema] = schema;
460
- this[BaseName] = baseName;
461
- }
462
- };
463
- });
464
-
465
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sql/sql.js
466
- function isSQLWrapper(value) {
467
- return value !== null && value !== undefined && typeof value.getSQL === "function";
468
- }
469
- function mergeQueries(queries) {
470
- const result = { sql: "", params: [] };
471
- for (const query of queries) {
472
- result.sql += query.sql;
473
- result.params.push(...query.params);
474
- if (query.typings?.length) {
475
- if (!result.typings) {
476
- result.typings = [];
477
- }
478
- result.typings.push(...query.typings);
479
- }
480
- }
481
- return result;
482
- }
483
- function isDriverValueEncoder(value) {
484
- return typeof value === "object" && value !== null && "mapToDriverValue" in value && typeof value.mapToDriverValue === "function";
485
- }
486
- function sql(strings, ...params) {
487
- const queryChunks = [];
488
- if (params.length > 0 || strings.length > 0 && strings[0] !== "") {
489
- queryChunks.push(new StringChunk(strings[0]));
490
- }
491
- for (const [paramIndex, param2] of params.entries()) {
492
- queryChunks.push(param2, new StringChunk(strings[paramIndex + 1]));
493
- }
494
- return new SQL(queryChunks);
495
- }
496
- function fillPlaceholders(params, values) {
497
- return params.map((p) => {
498
- if (is(p, Placeholder)) {
499
- if (!(p.name in values)) {
500
- throw new Error(`No value for placeholder "${p.name}" was provided`);
501
- }
502
- return values[p.name];
503
- }
504
- if (is(p, Param) && is(p.value, Placeholder)) {
505
- if (!(p.value.name in values)) {
506
- throw new Error(`No value for placeholder "${p.value.name}" was provided`);
507
- }
508
- return p.encoder.mapToDriverValue(values[p.value.name]);
509
- }
510
- return p;
511
- });
512
- }
513
- var StringChunk, SQL, Name, noopDecoder, noopEncoder, noopMapper, Param, Placeholder, IsDrizzleView, View;
514
- var init_sql = __esm(() => {
515
- init_entity();
516
- init_enum();
517
- init_subquery();
518
- init_tracing();
519
- init_view_common();
520
- init_column();
521
- init_table();
522
- StringChunk = class StringChunk {
523
- static [entityKind] = "StringChunk";
524
- value;
525
- constructor(value) {
526
- this.value = Array.isArray(value) ? value : [value];
527
- }
528
- getSQL() {
529
- return new SQL([this]);
530
- }
531
- };
532
- SQL = class SQL {
533
- constructor(queryChunks) {
534
- this.queryChunks = queryChunks;
535
- for (const chunk of queryChunks) {
536
- if (is(chunk, Table)) {
537
- const schemaName = chunk[Table.Symbol.Schema];
538
- this.usedTables.push(schemaName === undefined ? chunk[Table.Symbol.Name] : schemaName + "." + chunk[Table.Symbol.Name]);
539
- }
540
- }
541
- }
542
- static [entityKind] = "SQL";
543
- decoder = noopDecoder;
544
- shouldInlineParams = false;
545
- usedTables = [];
546
- append(query) {
547
- this.queryChunks.push(...query.queryChunks);
548
- return this;
549
- }
550
- toQuery(config) {
551
- return tracer.startActiveSpan("drizzle.buildSQL", (span) => {
552
- const query = this.buildQueryFromSourceParams(this.queryChunks, config);
553
- span?.setAttributes({
554
- "drizzle.query.text": query.sql,
555
- "drizzle.query.params": JSON.stringify(query.params)
556
- });
557
- return query;
558
- });
559
- }
560
- buildQueryFromSourceParams(chunks, _config) {
561
- const config = Object.assign({}, _config, {
562
- inlineParams: _config.inlineParams || this.shouldInlineParams,
563
- paramStartIndex: _config.paramStartIndex || { value: 0 }
564
- });
565
- const {
566
- casing,
567
- escapeName,
568
- escapeParam,
569
- prepareTyping,
570
- inlineParams,
571
- paramStartIndex
572
- } = config;
573
- return mergeQueries(chunks.map((chunk) => {
574
- if (is(chunk, StringChunk)) {
575
- return { sql: chunk.value.join(""), params: [] };
576
- }
577
- if (is(chunk, Name)) {
578
- return { sql: escapeName(chunk.value), params: [] };
579
- }
580
- if (chunk === undefined) {
581
- return { sql: "", params: [] };
582
- }
583
- if (Array.isArray(chunk)) {
584
- const result = [new StringChunk("(")];
585
- for (const [i, p] of chunk.entries()) {
586
- result.push(p);
587
- if (i < chunk.length - 1) {
588
- result.push(new StringChunk(", "));
589
- }
590
- }
591
- result.push(new StringChunk(")"));
592
- return this.buildQueryFromSourceParams(result, config);
593
- }
594
- if (is(chunk, SQL)) {
595
- return this.buildQueryFromSourceParams(chunk.queryChunks, {
596
- ...config,
597
- inlineParams: inlineParams || chunk.shouldInlineParams
598
- });
599
- }
600
- if (is(chunk, Table)) {
601
- const schemaName = chunk[Table.Symbol.Schema];
602
- const tableName = chunk[Table.Symbol.Name];
603
- return {
604
- sql: schemaName === undefined || chunk[IsAlias] ? escapeName(tableName) : escapeName(schemaName) + "." + escapeName(tableName),
605
- params: []
606
- };
607
- }
608
- if (is(chunk, Column)) {
609
- const columnName = casing.getColumnCasing(chunk);
610
- if (_config.invokeSource === "indexes") {
611
- return { sql: escapeName(columnName), params: [] };
612
- }
613
- const schemaName = chunk.table[Table.Symbol.Schema];
614
- return {
615
- sql: chunk.table[IsAlias] || schemaName === undefined ? escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName) : escapeName(schemaName) + "." + escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName),
616
- params: []
617
- };
618
- }
619
- if (is(chunk, View)) {
620
- const schemaName = chunk[ViewBaseConfig].schema;
621
- const viewName = chunk[ViewBaseConfig].name;
622
- return {
623
- sql: schemaName === undefined || chunk[ViewBaseConfig].isAlias ? escapeName(viewName) : escapeName(schemaName) + "." + escapeName(viewName),
624
- params: []
625
- };
626
- }
627
- if (is(chunk, Param)) {
628
- if (is(chunk.value, Placeholder)) {
629
- return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
630
- }
631
- const mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value);
632
- if (is(mappedValue, SQL)) {
633
- return this.buildQueryFromSourceParams([mappedValue], config);
634
- }
635
- if (inlineParams) {
636
- return { sql: this.mapInlineParam(mappedValue, config), params: [] };
637
- }
638
- let typings = ["none"];
639
- if (prepareTyping) {
640
- typings = [prepareTyping(chunk.encoder)];
641
- }
642
- return { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings };
643
- }
644
- if (is(chunk, Placeholder)) {
645
- return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
646
- }
647
- if (is(chunk, SQL.Aliased) && chunk.fieldAlias !== undefined) {
648
- return { sql: escapeName(chunk.fieldAlias), params: [] };
649
- }
650
- if (is(chunk, Subquery)) {
651
- if (chunk._.isWith) {
652
- return { sql: escapeName(chunk._.alias), params: [] };
653
- }
654
- return this.buildQueryFromSourceParams([
655
- new StringChunk("("),
656
- chunk._.sql,
657
- new StringChunk(") "),
658
- new Name(chunk._.alias)
659
- ], config);
660
- }
661
- if (isPgEnum(chunk)) {
662
- if (chunk.schema) {
663
- return { sql: escapeName(chunk.schema) + "." + escapeName(chunk.enumName), params: [] };
664
- }
665
- return { sql: escapeName(chunk.enumName), params: [] };
666
- }
667
- if (isSQLWrapper(chunk)) {
668
- if (chunk.shouldOmitSQLParens?.()) {
669
- return this.buildQueryFromSourceParams([chunk.getSQL()], config);
670
- }
671
- return this.buildQueryFromSourceParams([
672
- new StringChunk("("),
673
- chunk.getSQL(),
674
- new StringChunk(")")
675
- ], config);
676
- }
677
- if (inlineParams) {
678
- return { sql: this.mapInlineParam(chunk, config), params: [] };
679
- }
680
- return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
681
- }));
682
- }
683
- mapInlineParam(chunk, { escapeString }) {
684
- if (chunk === null) {
685
- return "null";
686
- }
687
- if (typeof chunk === "number" || typeof chunk === "boolean") {
688
- return chunk.toString();
689
- }
690
- if (typeof chunk === "string") {
691
- return escapeString(chunk);
692
- }
693
- if (typeof chunk === "object") {
694
- const mappedValueAsString = chunk.toString();
695
- if (mappedValueAsString === "[object Object]") {
696
- return escapeString(JSON.stringify(chunk));
697
- }
698
- return escapeString(mappedValueAsString);
699
- }
700
- throw new Error("Unexpected param value: " + chunk);
701
- }
702
- getSQL() {
703
- return this;
704
- }
705
- as(alias2) {
706
- if (alias2 === undefined) {
707
- return this;
708
- }
709
- return new SQL.Aliased(this, alias2);
710
- }
711
- mapWith(decoder) {
712
- this.decoder = typeof decoder === "function" ? { mapFromDriverValue: decoder } : decoder;
713
- return this;
714
- }
715
- inlineParams() {
716
- this.shouldInlineParams = true;
717
- return this;
718
- }
719
- if(condition) {
720
- return condition ? this : undefined;
721
- }
722
- };
723
- Name = class Name {
724
- constructor(value) {
725
- this.value = value;
726
- }
727
- static [entityKind] = "Name";
728
- brand;
729
- getSQL() {
730
- return new SQL([this]);
731
- }
732
- };
733
- noopDecoder = {
734
- mapFromDriverValue: (value) => value
735
- };
736
- noopEncoder = {
737
- mapToDriverValue: (value) => value
738
- };
739
- noopMapper = {
740
- ...noopDecoder,
741
- ...noopEncoder
742
- };
743
- Param = class Param {
744
- constructor(value, encoder = noopEncoder) {
745
- this.value = value;
746
- this.encoder = encoder;
747
- }
748
- static [entityKind] = "Param";
749
- brand;
750
- getSQL() {
751
- return new SQL([this]);
752
- }
753
- };
754
- ((sql2) => {
755
- function empty() {
756
- return new SQL([]);
757
- }
758
- sql2.empty = empty;
759
- function fromList(list) {
760
- return new SQL(list);
761
- }
762
- sql2.fromList = fromList;
763
- function raw(str) {
764
- return new SQL([new StringChunk(str)]);
765
- }
766
- sql2.raw = raw;
767
- function join2(chunks, separator) {
768
- const result = [];
769
- for (const [i, chunk] of chunks.entries()) {
770
- if (i > 0 && separator !== undefined) {
771
- result.push(separator);
772
- }
773
- result.push(chunk);
774
- }
775
- return new SQL(result);
776
- }
777
- sql2.join = join2;
778
- function identifier(value) {
779
- return new Name(value);
780
- }
781
- sql2.identifier = identifier;
782
- function placeholder2(name2) {
783
- return new Placeholder(name2);
784
- }
785
- sql2.placeholder = placeholder2;
786
- function param2(value, encoder) {
787
- return new Param(value, encoder);
788
- }
789
- sql2.param = param2;
790
- })(sql || (sql = {}));
791
- ((SQL2) => {
792
-
793
- class Aliased {
794
- constructor(sql2, fieldAlias) {
795
- this.sql = sql2;
796
- this.fieldAlias = fieldAlias;
797
- }
798
- static [entityKind] = "SQL.Aliased";
799
- isSelectionField = false;
800
- getSQL() {
801
- return this.sql;
802
- }
803
- clone() {
804
- return new Aliased(this.sql, this.fieldAlias);
805
- }
806
- }
807
- SQL2.Aliased = Aliased;
808
- })(SQL || (SQL = {}));
809
- Placeholder = class Placeholder {
810
- constructor(name2) {
811
- this.name = name2;
812
- }
813
- static [entityKind] = "Placeholder";
814
- getSQL() {
815
- return new SQL([this]);
816
- }
817
- };
818
- IsDrizzleView = Symbol.for("drizzle:IsDrizzleView");
819
- View = class View {
820
- static [entityKind] = "View";
821
- [ViewBaseConfig];
822
- [IsDrizzleView] = true;
823
- constructor({ name: name2, schema, selectedFields, query }) {
824
- this[ViewBaseConfig] = {
825
- name: name2,
826
- originalName: name2,
827
- schema,
828
- selectedFields,
829
- query,
830
- isExisting: !query,
831
- isAlias: false
832
- };
833
- }
834
- getSQL() {
835
- return new SQL([this]);
836
- }
837
- };
838
- Column.prototype.getSQL = function() {
839
- return new SQL([this]);
840
- };
841
- Table.prototype.getSQL = function() {
842
- return new SQL([this]);
843
- };
844
- Subquery.prototype.getSQL = function() {
845
- return new SQL([this]);
846
- };
847
- });
848
-
849
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/alias.js
850
- function aliasedTable(table, tableAlias) {
851
- return new Proxy(table, new TableAliasProxyHandler(tableAlias, false));
852
- }
853
- function aliasedTableColumn(column, tableAlias) {
854
- return new Proxy(column, new ColumnAliasProxyHandler(new Proxy(column.table, new TableAliasProxyHandler(tableAlias, false))));
855
- }
856
- function mapColumnsInAliasedSQLToAlias(query, alias2) {
857
- return new SQL.Aliased(mapColumnsInSQLToAlias(query.sql, alias2), query.fieldAlias);
858
- }
859
- function mapColumnsInSQLToAlias(query, alias2) {
860
- return sql.join(query.queryChunks.map((c) => {
861
- if (is(c, Column)) {
862
- return aliasedTableColumn(c, alias2);
863
- }
864
- if (is(c, SQL)) {
865
- return mapColumnsInSQLToAlias(c, alias2);
866
- }
867
- if (is(c, SQL.Aliased)) {
868
- return mapColumnsInAliasedSQLToAlias(c, alias2);
869
- }
870
- return c;
871
- }));
872
- }
873
- var ColumnAliasProxyHandler, TableAliasProxyHandler;
874
- var init_alias = __esm(() => {
875
- init_column();
876
- init_entity();
877
- init_sql();
878
- init_table();
879
- init_view_common();
880
- ColumnAliasProxyHandler = class ColumnAliasProxyHandler {
881
- constructor(table) {
882
- this.table = table;
883
- }
884
- static [entityKind] = "ColumnAliasProxyHandler";
885
- get(columnObj, prop) {
886
- if (prop === "table") {
887
- return this.table;
888
- }
889
- return columnObj[prop];
890
- }
891
- };
892
- TableAliasProxyHandler = class TableAliasProxyHandler {
893
- constructor(alias2, replaceOriginalName) {
894
- this.alias = alias2;
895
- this.replaceOriginalName = replaceOriginalName;
896
- }
897
- static [entityKind] = "TableAliasProxyHandler";
898
- get(target, prop) {
899
- if (prop === Table.Symbol.IsAlias) {
900
- return true;
901
- }
902
- if (prop === Table.Symbol.Name) {
903
- return this.alias;
904
- }
905
- if (this.replaceOriginalName && prop === Table.Symbol.OriginalName) {
906
- return this.alias;
907
- }
908
- if (prop === ViewBaseConfig) {
909
- return {
910
- ...target[ViewBaseConfig],
911
- name: this.alias,
912
- isAlias: true
913
- };
914
- }
915
- if (prop === Table.Symbol.Columns) {
916
- const columns = target[Table.Symbol.Columns];
917
- if (!columns) {
918
- return columns;
919
- }
920
- const proxiedColumns = {};
921
- Object.keys(columns).map((key) => {
922
- proxiedColumns[key] = new Proxy(columns[key], new ColumnAliasProxyHandler(new Proxy(target, this)));
923
- });
924
- return proxiedColumns;
925
- }
926
- const value = target[prop];
927
- if (is(value, Column)) {
928
- return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(target, this)));
929
- }
930
- return value;
931
- }
932
- };
933
- });
934
-
935
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/errors.js
936
- var DrizzleError, DrizzleQueryError, TransactionRollbackError;
937
- var init_errors = __esm(() => {
938
- init_entity();
939
- DrizzleError = class DrizzleError extends Error {
940
- static [entityKind] = "DrizzleError";
941
- constructor({ message, cause }) {
942
- super(message);
943
- this.name = "DrizzleError";
944
- this.cause = cause;
945
- }
946
- };
947
- DrizzleQueryError = class DrizzleQueryError extends Error {
948
- constructor(query, params, cause) {
949
- super(`Failed query: ${query}
950
- params: ${params}`);
951
- this.query = query;
952
- this.params = params;
953
- this.cause = cause;
954
- Error.captureStackTrace(this, DrizzleQueryError);
955
- if (cause)
956
- this.cause = cause;
957
- }
958
- };
959
- TransactionRollbackError = class TransactionRollbackError extends DrizzleError {
960
- static [entityKind] = "TransactionRollbackError";
961
- constructor() {
962
- super({ message: "Rollback" });
963
- }
964
- };
965
- });
966
-
967
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/logger.js
968
- var ConsoleLogWriter, DefaultLogger, NoopLogger;
969
- var init_logger = __esm(() => {
970
- init_entity();
971
- ConsoleLogWriter = class ConsoleLogWriter {
972
- static [entityKind] = "ConsoleLogWriter";
973
- write(message) {
974
- console.log(message);
975
- }
976
- };
977
- DefaultLogger = class DefaultLogger {
978
- static [entityKind] = "DefaultLogger";
979
- writer;
980
- constructor(config) {
981
- this.writer = config?.writer ?? new ConsoleLogWriter;
982
- }
983
- logQuery(query, params) {
984
- const stringifiedParams = params.map((p) => {
985
- try {
986
- return JSON.stringify(p);
987
- } catch {
988
- return String(p);
989
- }
990
- });
991
- const paramsStr = stringifiedParams.length ? ` -- params: [${stringifiedParams.join(", ")}]` : "";
992
- this.writer.write(`Query: ${query}${paramsStr}`);
993
- }
994
- };
995
- NoopLogger = class NoopLogger {
996
- static [entityKind] = "NoopLogger";
997
- logQuery() {}
998
- };
999
- });
1000
-
1001
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/query-promise.js
1002
- var QueryPromise;
1003
- var init_query_promise = __esm(() => {
1004
- init_entity();
1005
- QueryPromise = class QueryPromise {
1006
- static [entityKind] = "QueryPromise";
1007
- [Symbol.toStringTag] = "QueryPromise";
1008
- catch(onRejected) {
1009
- return this.then(undefined, onRejected);
1010
- }
1011
- finally(onFinally) {
1012
- return this.then((value) => {
1013
- onFinally?.();
1014
- return value;
1015
- }, (reason) => {
1016
- onFinally?.();
1017
- throw reason;
1018
- });
1019
- }
1020
- then(onFulfilled, onRejected) {
1021
- return this.execute().then(onFulfilled, onRejected);
1022
- }
1023
- };
1024
- });
1025
-
1026
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/utils.js
1027
- function mapResultRow(columns, row, joinsNotNullableMap) {
1028
- const nullifyMap = {};
1029
- const result = columns.reduce((result2, { path, field }, columnIndex) => {
1030
- let decoder;
1031
- if (is(field, Column)) {
1032
- decoder = field;
1033
- } else if (is(field, SQL)) {
1034
- decoder = field.decoder;
1035
- } else {
1036
- decoder = field.sql.decoder;
1037
- }
1038
- let node = result2;
1039
- for (const [pathChunkIndex, pathChunk] of path.entries()) {
1040
- if (pathChunkIndex < path.length - 1) {
1041
- if (!(pathChunk in node)) {
1042
- node[pathChunk] = {};
1043
- }
1044
- node = node[pathChunk];
1045
- } else {
1046
- const rawValue = row[columnIndex];
1047
- const value = node[pathChunk] = rawValue === null ? null : decoder.mapFromDriverValue(rawValue);
1048
- if (joinsNotNullableMap && is(field, Column) && path.length === 2) {
1049
- const objectName = path[0];
1050
- if (!(objectName in nullifyMap)) {
1051
- nullifyMap[objectName] = value === null ? getTableName(field.table) : false;
1052
- } else if (typeof nullifyMap[objectName] === "string" && nullifyMap[objectName] !== getTableName(field.table)) {
1053
- nullifyMap[objectName] = false;
1054
- }
1055
- }
1056
- }
1057
- }
1058
- return result2;
1059
- }, {});
1060
- if (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) {
1061
- for (const [objectName, tableName] of Object.entries(nullifyMap)) {
1062
- if (typeof tableName === "string" && !joinsNotNullableMap[tableName]) {
1063
- result[objectName] = null;
1064
- }
1065
- }
1066
- }
1067
- return result;
1068
- }
1069
- function orderSelectedFields(fields, pathPrefix) {
1070
- return Object.entries(fields).reduce((result, [name, field]) => {
1071
- if (typeof name !== "string") {
1072
- return result;
1073
- }
1074
- const newPath = pathPrefix ? [...pathPrefix, name] : [name];
1075
- if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased)) {
1076
- result.push({ path: newPath, field });
1077
- } else if (is(field, Table)) {
1078
- result.push(...orderSelectedFields(field[Table.Symbol.Columns], newPath));
1079
- } else {
1080
- result.push(...orderSelectedFields(field, newPath));
1081
- }
1082
- return result;
1083
- }, []);
1084
- }
1085
- function haveSameKeys(left, right) {
1086
- const leftKeys = Object.keys(left);
1087
- const rightKeys = Object.keys(right);
1088
- if (leftKeys.length !== rightKeys.length) {
1089
- return false;
1090
- }
1091
- for (const [index, key] of leftKeys.entries()) {
1092
- if (key !== rightKeys[index]) {
1093
- return false;
1094
- }
1095
- }
1096
- return true;
1097
- }
1098
- function mapUpdateSet(table, values) {
1099
- const entries = Object.entries(values).filter(([, value]) => value !== undefined).map(([key, value]) => {
1100
- if (is(value, SQL) || is(value, Column)) {
1101
- return [key, value];
1102
- } else {
1103
- return [key, new Param(value, table[Table.Symbol.Columns][key])];
1104
- }
1105
- });
1106
- if (entries.length === 0) {
1107
- throw new Error("No values to set");
1108
- }
1109
- return Object.fromEntries(entries);
1110
- }
1111
- function applyMixins(baseClass, extendedClasses) {
1112
- for (const extendedClass of extendedClasses) {
1113
- for (const name of Object.getOwnPropertyNames(extendedClass.prototype)) {
1114
- if (name === "constructor")
1115
- continue;
1116
- Object.defineProperty(baseClass.prototype, name, Object.getOwnPropertyDescriptor(extendedClass.prototype, name) || /* @__PURE__ */ Object.create(null));
1117
- }
1118
- }
1119
- }
1120
- function getTableColumns(table) {
1121
- return table[Table.Symbol.Columns];
1122
- }
1123
- function getTableLikeName(table) {
1124
- return is(table, Subquery) ? table._.alias : is(table, View) ? table[ViewBaseConfig].name : is(table, SQL) ? undefined : table[Table.Symbol.IsAlias] ? table[Table.Symbol.Name] : table[Table.Symbol.BaseName];
1125
- }
1126
- function getColumnNameAndConfig(a, b) {
1127
- return {
1128
- name: typeof a === "string" && a.length > 0 ? a : "",
1129
- config: typeof a === "object" ? a : b
1130
- };
1131
- }
1132
- function isConfig(data) {
1133
- if (typeof data !== "object" || data === null)
1134
- return false;
1135
- if (data.constructor.name !== "Object")
1136
- return false;
1137
- if ("logger" in data) {
1138
- const type = typeof data["logger"];
1139
- if (type !== "boolean" && (type !== "object" || typeof data["logger"]["logQuery"] !== "function") && type !== "undefined")
1140
- return false;
1141
- return true;
1142
- }
1143
- if ("schema" in data) {
1144
- const type = typeof data["schema"];
1145
- if (type !== "object" && type !== "undefined")
1146
- return false;
1147
- return true;
1148
- }
1149
- if ("casing" in data) {
1150
- const type = typeof data["casing"];
1151
- if (type !== "string" && type !== "undefined")
1152
- return false;
1153
- return true;
1154
- }
1155
- if ("mode" in data) {
1156
- if (data["mode"] !== "default" || data["mode"] !== "planetscale" || data["mode"] !== undefined)
1157
- return false;
1158
- return true;
1159
- }
1160
- if ("connection" in data) {
1161
- const type = typeof data["connection"];
1162
- if (type !== "string" && type !== "object" && type !== "undefined")
1163
- return false;
1164
- return true;
1165
- }
1166
- if ("client" in data) {
1167
- const type = typeof data["client"];
1168
- if (type !== "object" && type !== "function" && type !== "undefined")
1169
- return false;
1170
- return true;
1171
- }
1172
- if (Object.keys(data).length === 0)
1173
- return true;
1174
- return false;
1175
- }
1176
- var textDecoder;
1177
- var init_utils = __esm(() => {
1178
- init_column();
1179
- init_entity();
1180
- init_sql();
1181
- init_subquery();
1182
- init_table();
1183
- init_view_common();
1184
- textDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder;
1185
- });
1186
-
1187
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/pg-core/table.js
1188
- var InlineForeignKeys, EnableRLS, PgTable;
1189
- var init_table2 = __esm(() => {
1190
- init_entity();
1191
- init_table();
1192
- InlineForeignKeys = Symbol.for("drizzle:PgInlineForeignKeys");
1193
- EnableRLS = Symbol.for("drizzle:EnableRLS");
1194
- PgTable = class PgTable extends Table {
1195
- static [entityKind] = "PgTable";
1196
- static Symbol = Object.assign({}, Table.Symbol, {
1197
- InlineForeignKeys,
1198
- EnableRLS
1199
- });
1200
- [InlineForeignKeys] = [];
1201
- [EnableRLS] = false;
1202
- [Table.Symbol.ExtraConfigBuilder] = undefined;
1203
- [Table.Symbol.ExtraConfigColumns] = {};
1204
- };
1205
- });
1206
-
1207
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/pg-core/primary-keys.js
1208
- var PrimaryKeyBuilder, PrimaryKey;
1209
- var init_primary_keys = __esm(() => {
1210
- init_entity();
1211
- init_table2();
1212
- PrimaryKeyBuilder = class PrimaryKeyBuilder {
1213
- static [entityKind] = "PgPrimaryKeyBuilder";
1214
- columns;
1215
- name;
1216
- constructor(columns, name) {
1217
- this.columns = columns;
1218
- this.name = name;
1219
- }
1220
- build(table) {
1221
- return new PrimaryKey(table, this.columns, this.name);
1222
- }
1223
- };
1224
- PrimaryKey = class PrimaryKey {
1225
- constructor(table, columns, name) {
1226
- this.table = table;
1227
- this.columns = columns;
1228
- this.name = name;
1229
- }
1230
- static [entityKind] = "PgPrimaryKey";
1231
- columns;
1232
- name;
1233
- getName() {
1234
- return this.name ?? `${this.table[PgTable.Symbol.Name]}_${this.columns.map((column) => column.name).join("_")}_pk`;
1235
- }
1236
- };
1237
- });
1238
-
1239
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sql/expressions/conditions.js
1240
- function bindIfParam(value, column) {
1241
- if (isDriverValueEncoder(column) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) {
1242
- return new Param(value, column);
1243
- }
1244
- return value;
1245
- }
1246
- function and(...unfilteredConditions) {
1247
- const conditions = unfilteredConditions.filter((c) => c !== undefined);
1248
- if (conditions.length === 0) {
1249
- return;
1250
- }
1251
- if (conditions.length === 1) {
1252
- return new SQL(conditions);
1253
- }
1254
- return new SQL([
1255
- new StringChunk("("),
1256
- sql.join(conditions, new StringChunk(" and ")),
1257
- new StringChunk(")")
1258
- ]);
1259
- }
1260
- function or(...unfilteredConditions) {
1261
- const conditions = unfilteredConditions.filter((c) => c !== undefined);
1262
- if (conditions.length === 0) {
1263
- return;
1264
- }
1265
- if (conditions.length === 1) {
1266
- return new SQL(conditions);
1267
- }
1268
- return new SQL([
1269
- new StringChunk("("),
1270
- sql.join(conditions, new StringChunk(" or ")),
1271
- new StringChunk(")")
1272
- ]);
1273
- }
1274
- function not(condition) {
1275
- return sql`not ${condition}`;
1276
- }
1277
- function inArray(column, values) {
1278
- if (Array.isArray(values)) {
1279
- if (values.length === 0) {
1280
- return sql`false`;
1281
- }
1282
- return sql`${column} in ${values.map((v) => bindIfParam(v, column))}`;
1283
- }
1284
- return sql`${column} in ${bindIfParam(values, column)}`;
1285
- }
1286
- function notInArray(column, values) {
1287
- if (Array.isArray(values)) {
1288
- if (values.length === 0) {
1289
- return sql`true`;
1290
- }
1291
- return sql`${column} not in ${values.map((v) => bindIfParam(v, column))}`;
1292
- }
1293
- return sql`${column} not in ${bindIfParam(values, column)}`;
1294
- }
1295
- function isNull(value) {
1296
- return sql`${value} is null`;
1297
- }
1298
- function isNotNull(value) {
1299
- return sql`${value} is not null`;
1300
- }
1301
- function exists(subquery) {
1302
- return sql`exists ${subquery}`;
1303
- }
1304
- function notExists(subquery) {
1305
- return sql`not exists ${subquery}`;
1306
- }
1307
- function between(column, min, max) {
1308
- return sql`${column} between ${bindIfParam(min, column)} and ${bindIfParam(max, column)}`;
1309
- }
1310
- function notBetween(column, min, max) {
1311
- return sql`${column} not between ${bindIfParam(min, column)} and ${bindIfParam(max, column)}`;
1312
- }
1313
- function like(column, value) {
1314
- return sql`${column} like ${value}`;
1315
- }
1316
- function notLike(column, value) {
1317
- return sql`${column} not like ${value}`;
1318
- }
1319
- function ilike(column, value) {
1320
- return sql`${column} ilike ${value}`;
1321
- }
1322
- function notIlike(column, value) {
1323
- return sql`${column} not ilike ${value}`;
1324
- }
1325
- var eq = (left, right) => {
1326
- return sql`${left} = ${bindIfParam(right, left)}`;
1327
- }, ne = (left, right) => {
1328
- return sql`${left} <> ${bindIfParam(right, left)}`;
1329
- }, gt = (left, right) => {
1330
- return sql`${left} > ${bindIfParam(right, left)}`;
1331
- }, gte = (left, right) => {
1332
- return sql`${left} >= ${bindIfParam(right, left)}`;
1333
- }, lt = (left, right) => {
1334
- return sql`${left} < ${bindIfParam(right, left)}`;
1335
- }, lte = (left, right) => {
1336
- return sql`${left} <= ${bindIfParam(right, left)}`;
1337
- };
1338
- var init_conditions = __esm(() => {
1339
- init_column();
1340
- init_entity();
1341
- init_table();
1342
- init_sql();
1343
- });
1344
-
1345
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sql/expressions/select.js
1346
- function asc(column) {
1347
- return sql`${column} asc`;
1348
- }
1349
- function desc(column) {
1350
- return sql`${column} desc`;
1351
- }
1352
- var init_select = __esm(() => {
1353
- init_sql();
1354
- });
1355
-
1356
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sql/expressions/index.js
1357
- var init_expressions = __esm(() => {
1358
- init_conditions();
1359
- init_select();
1360
- });
1361
-
1362
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/relations.js
1363
- function getOperators() {
1364
- return {
1365
- and,
1366
- between,
1367
- eq,
1368
- exists,
1369
- gt,
1370
- gte,
1371
- ilike,
1372
- inArray,
1373
- isNull,
1374
- isNotNull,
1375
- like,
1376
- lt,
1377
- lte,
1378
- ne,
1379
- not,
1380
- notBetween,
1381
- notExists,
1382
- notLike,
1383
- notIlike,
1384
- notInArray,
1385
- or,
1386
- sql
1387
- };
1388
- }
1389
- function getOrderByOperators() {
1390
- return {
1391
- sql,
1392
- asc,
1393
- desc
1394
- };
1395
- }
1396
- function extractTablesRelationalConfig(schema, configHelpers) {
1397
- if (Object.keys(schema).length === 1 && "default" in schema && !is(schema["default"], Table)) {
1398
- schema = schema["default"];
1399
- }
1400
- const tableNamesMap = {};
1401
- const relationsBuffer = {};
1402
- const tablesConfig = {};
1403
- for (const [key, value] of Object.entries(schema)) {
1404
- if (is(value, Table)) {
1405
- const dbName = getTableUniqueName(value);
1406
- const bufferedRelations = relationsBuffer[dbName];
1407
- tableNamesMap[dbName] = key;
1408
- tablesConfig[key] = {
1409
- tsName: key,
1410
- dbName: value[Table.Symbol.Name],
1411
- schema: value[Table.Symbol.Schema],
1412
- columns: value[Table.Symbol.Columns],
1413
- relations: bufferedRelations?.relations ?? {},
1414
- primaryKey: bufferedRelations?.primaryKey ?? []
1415
- };
1416
- for (const column of Object.values(value[Table.Symbol.Columns])) {
1417
- if (column.primary) {
1418
- tablesConfig[key].primaryKey.push(column);
1419
- }
1420
- }
1421
- const extraConfig = value[Table.Symbol.ExtraConfigBuilder]?.(value[Table.Symbol.ExtraConfigColumns]);
1422
- if (extraConfig) {
1423
- for (const configEntry of Object.values(extraConfig)) {
1424
- if (is(configEntry, PrimaryKeyBuilder)) {
1425
- tablesConfig[key].primaryKey.push(...configEntry.columns);
1426
- }
1427
- }
1428
- }
1429
- } else if (is(value, Relations)) {
1430
- const dbName = getTableUniqueName(value.table);
1431
- const tableName = tableNamesMap[dbName];
1432
- const relations2 = value.config(configHelpers(value.table));
1433
- let primaryKey;
1434
- for (const [relationName, relation] of Object.entries(relations2)) {
1435
- if (tableName) {
1436
- const tableConfig = tablesConfig[tableName];
1437
- tableConfig.relations[relationName] = relation;
1438
- if (primaryKey) {
1439
- tableConfig.primaryKey.push(...primaryKey);
1440
- }
1441
- } else {
1442
- if (!(dbName in relationsBuffer)) {
1443
- relationsBuffer[dbName] = {
1444
- relations: {},
1445
- primaryKey
1446
- };
1447
- }
1448
- relationsBuffer[dbName].relations[relationName] = relation;
1449
- }
1450
- }
1451
- }
1452
- }
1453
- return { tables: tablesConfig, tableNamesMap };
1454
- }
1455
- function createOne(sourceTable) {
1456
- return function one(table, config) {
1457
- return new One(sourceTable, table, config, config?.fields.reduce((res, f) => res && f.notNull, true) ?? false);
1458
- };
1459
- }
1460
- function createMany(sourceTable) {
1461
- return function many(referencedTable, config) {
1462
- return new Many(sourceTable, referencedTable, config);
1463
- };
1464
- }
1465
- function normalizeRelation(schema, tableNamesMap, relation) {
1466
- if (is(relation, One) && relation.config) {
1467
- return {
1468
- fields: relation.config.fields,
1469
- references: relation.config.references
1470
- };
1471
- }
1472
- const referencedTableTsName = tableNamesMap[getTableUniqueName(relation.referencedTable)];
1473
- if (!referencedTableTsName) {
1474
- throw new Error(`Table "${relation.referencedTable[Table.Symbol.Name]}" not found in schema`);
1475
- }
1476
- const referencedTableConfig = schema[referencedTableTsName];
1477
- if (!referencedTableConfig) {
1478
- throw new Error(`Table "${referencedTableTsName}" not found in schema`);
1479
- }
1480
- const sourceTable = relation.sourceTable;
1481
- const sourceTableTsName = tableNamesMap[getTableUniqueName(sourceTable)];
1482
- if (!sourceTableTsName) {
1483
- throw new Error(`Table "${sourceTable[Table.Symbol.Name]}" not found in schema`);
1484
- }
1485
- const reverseRelations = [];
1486
- for (const referencedTableRelation of Object.values(referencedTableConfig.relations)) {
1487
- if (relation.relationName && relation !== referencedTableRelation && referencedTableRelation.relationName === relation.relationName || !relation.relationName && referencedTableRelation.referencedTable === relation.sourceTable) {
1488
- reverseRelations.push(referencedTableRelation);
1489
- }
1490
- }
1491
- if (reverseRelations.length > 1) {
1492
- throw relation.relationName ? new Error(`There are multiple relations with name "${relation.relationName}" in table "${referencedTableTsName}"`) : new Error(`There are multiple relations between "${referencedTableTsName}" and "${relation.sourceTable[Table.Symbol.Name]}". Please specify relation name`);
1493
- }
1494
- if (reverseRelations[0] && is(reverseRelations[0], One) && reverseRelations[0].config) {
1495
- return {
1496
- fields: reverseRelations[0].config.references,
1497
- references: reverseRelations[0].config.fields
1498
- };
1499
- }
1500
- throw new Error(`There is not enough information to infer relation "${sourceTableTsName}.${relation.fieldName}"`);
1501
- }
1502
- function createTableRelationsHelpers(sourceTable) {
1503
- return {
1504
- one: createOne(sourceTable),
1505
- many: createMany(sourceTable)
1506
- };
1507
- }
1508
- function mapRelationalRow(tablesConfig, tableConfig, row, buildQueryResultSelection, mapColumnValue = (value) => value) {
1509
- const result = {};
1510
- for (const [
1511
- selectionItemIndex,
1512
- selectionItem
1513
- ] of buildQueryResultSelection.entries()) {
1514
- if (selectionItem.isJson) {
1515
- const relation = tableConfig.relations[selectionItem.tsKey];
1516
- const rawSubRows = row[selectionItemIndex];
1517
- const subRows = typeof rawSubRows === "string" ? JSON.parse(rawSubRows) : rawSubRows;
1518
- result[selectionItem.tsKey] = is(relation, One) ? subRows && mapRelationalRow(tablesConfig, tablesConfig[selectionItem.relationTableTsKey], subRows, selectionItem.selection, mapColumnValue) : subRows.map((subRow) => mapRelationalRow(tablesConfig, tablesConfig[selectionItem.relationTableTsKey], subRow, selectionItem.selection, mapColumnValue));
1519
- } else {
1520
- const value = mapColumnValue(row[selectionItemIndex]);
1521
- const field = selectionItem.field;
1522
- let decoder;
1523
- if (is(field, Column)) {
1524
- decoder = field;
1525
- } else if (is(field, SQL)) {
1526
- decoder = field.decoder;
1527
- } else {
1528
- decoder = field.sql.decoder;
1529
- }
1530
- result[selectionItem.tsKey] = value === null ? null : decoder.mapFromDriverValue(value);
1531
- }
1532
- }
1533
- return result;
1534
- }
1535
- var Relation, Relations, One, Many;
1536
- var init_relations = __esm(() => {
1537
- init_table();
1538
- init_column();
1539
- init_entity();
1540
- init_primary_keys();
1541
- init_expressions();
1542
- init_sql();
1543
- Relation = class Relation {
1544
- constructor(sourceTable, referencedTable, relationName) {
1545
- this.sourceTable = sourceTable;
1546
- this.referencedTable = referencedTable;
1547
- this.relationName = relationName;
1548
- this.referencedTableName = referencedTable[Table.Symbol.Name];
1549
- }
1550
- static [entityKind] = "Relation";
1551
- referencedTableName;
1552
- fieldName;
1553
- };
1554
- Relations = class Relations {
1555
- constructor(table, config) {
1556
- this.table = table;
1557
- this.config = config;
1558
- }
1559
- static [entityKind] = "Relations";
1560
- };
1561
- One = class One extends Relation {
1562
- constructor(sourceTable, referencedTable, config, isNullable) {
1563
- super(sourceTable, referencedTable, config?.relationName);
1564
- this.config = config;
1565
- this.isNullable = isNullable;
1566
- }
1567
- static [entityKind] = "One";
1568
- withFieldName(fieldName) {
1569
- const relation = new One(this.sourceTable, this.referencedTable, this.config, this.isNullable);
1570
- relation.fieldName = fieldName;
1571
- return relation;
1572
- }
1573
- };
1574
- Many = class Many extends Relation {
1575
- constructor(sourceTable, referencedTable, config) {
1576
- super(sourceTable, referencedTable, config?.relationName);
1577
- this.config = config;
1578
- }
1579
- static [entityKind] = "Many";
1580
- withFieldName(fieldName) {
1581
- const relation = new Many(this.sourceTable, this.referencedTable, this.config);
1582
- relation.fieldName = fieldName;
1583
- return relation;
1584
- }
1585
- };
1586
- });
1587
-
1588
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sql/functions/aggregate.js
1589
- var init_aggregate = () => {};
1590
-
1591
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sql/functions/vector.js
1592
- var init_vector = () => {};
1593
-
1594
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sql/functions/index.js
1595
- var init_functions = __esm(() => {
1596
- init_aggregate();
1597
- init_vector();
1598
- });
1599
-
1600
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sql/index.js
1601
- var init_sql2 = __esm(() => {
1602
- init_expressions();
1603
- init_functions();
1604
- init_sql();
1605
- });
1606
-
1607
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/index.js
1608
- var init_drizzle_orm = __esm(() => {
1609
- init_alias();
1610
- init_column_builder();
1611
- init_column();
1612
- init_entity();
1613
- init_errors();
1614
- init_logger();
1615
- init_query_promise();
1616
- init_relations();
1617
- init_sql2();
1618
- init_subquery();
1619
- init_table();
1620
- init_utils();
1621
- init_view_common();
1622
- });
1623
-
1624
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/selection-proxy.js
1625
- var SelectionProxyHandler;
1626
- var init_selection_proxy = __esm(() => {
1627
- init_alias();
1628
- init_column();
1629
- init_entity();
1630
- init_sql();
1631
- init_subquery();
1632
- init_view_common();
1633
- SelectionProxyHandler = class SelectionProxyHandler {
1634
- static [entityKind] = "SelectionProxyHandler";
1635
- config;
1636
- constructor(config) {
1637
- this.config = { ...config };
1638
- }
1639
- get(subquery2, prop) {
1640
- if (prop === "_") {
1641
- return {
1642
- ...subquery2["_"],
1643
- selectedFields: new Proxy(subquery2._.selectedFields, this)
1644
- };
1645
- }
1646
- if (prop === ViewBaseConfig) {
1647
- return {
1648
- ...subquery2[ViewBaseConfig],
1649
- selectedFields: new Proxy(subquery2[ViewBaseConfig].selectedFields, this)
1650
- };
1651
- }
1652
- if (typeof prop === "symbol") {
1653
- return subquery2[prop];
1654
- }
1655
- const columns = is(subquery2, Subquery) ? subquery2._.selectedFields : is(subquery2, View) ? subquery2[ViewBaseConfig].selectedFields : subquery2;
1656
- const value = columns[prop];
1657
- if (is(value, SQL.Aliased)) {
1658
- if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) {
1659
- return value.sql;
1660
- }
1661
- const newValue = value.clone();
1662
- newValue.isSelectionField = true;
1663
- return newValue;
1664
- }
1665
- if (is(value, SQL)) {
1666
- if (this.config.sqlBehavior === "sql") {
1667
- return value;
1668
- }
1669
- throw new Error(`You tried to reference "${prop}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`);
1670
- }
1671
- if (is(value, Column)) {
1672
- if (this.config.alias) {
1673
- return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(value.table, new TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false))));
1674
- }
1675
- return value;
1676
- }
1677
- if (typeof value !== "object" || value === null) {
1678
- return value;
1679
- }
1680
- return new Proxy(value, new SelectionProxyHandler(this.config));
1681
- }
1682
- };
1683
- });
1684
-
1685
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/foreign-keys.js
1686
- var ForeignKeyBuilder, ForeignKey;
1687
- var init_foreign_keys = __esm(() => {
1688
- init_entity();
1689
- init_table_utils();
1690
- ForeignKeyBuilder = class ForeignKeyBuilder {
1691
- static [entityKind] = "SQLiteForeignKeyBuilder";
1692
- reference;
1693
- _onUpdate;
1694
- _onDelete;
1695
- constructor(config, actions) {
1696
- this.reference = () => {
1697
- const { name, columns, foreignColumns } = config();
1698
- return { name, columns, foreignTable: foreignColumns[0].table, foreignColumns };
1699
- };
1700
- if (actions) {
1701
- this._onUpdate = actions.onUpdate;
1702
- this._onDelete = actions.onDelete;
1703
- }
1704
- }
1705
- onUpdate(action) {
1706
- this._onUpdate = action;
1707
- return this;
1708
- }
1709
- onDelete(action) {
1710
- this._onDelete = action;
1711
- return this;
1712
- }
1713
- build(table2) {
1714
- return new ForeignKey(table2, this);
1715
- }
1716
- };
1717
- ForeignKey = class ForeignKey {
1718
- constructor(table2, builder) {
1719
- this.table = table2;
1720
- this.reference = builder.reference;
1721
- this.onUpdate = builder._onUpdate;
1722
- this.onDelete = builder._onDelete;
1723
- }
1724
- static [entityKind] = "SQLiteForeignKey";
1725
- reference;
1726
- onUpdate;
1727
- onDelete;
1728
- getName() {
1729
- const { name, columns, foreignColumns } = this.reference();
1730
- const columnNames = columns.map((column2) => column2.name);
1731
- const foreignColumnNames = foreignColumns.map((column2) => column2.name);
1732
- const chunks = [
1733
- this.table[TableName],
1734
- ...columnNames,
1735
- foreignColumns[0].table[TableName],
1736
- ...foreignColumnNames
1737
- ];
1738
- return name ?? `${chunks.join("_")}_fk`;
1739
- }
1740
- };
1741
- });
1742
-
1743
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/unique-constraint.js
1744
- function uniqueKeyName2(table2, columns) {
1745
- return `${table2[TableName]}_${columns.join("_")}_unique`;
1746
- }
1747
- var init_unique_constraint2 = __esm(() => {
1748
- init_table_utils();
1749
- });
1750
-
1751
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/columns/common.js
1752
- var SQLiteColumnBuilder, SQLiteColumn;
1753
- var init_common2 = __esm(() => {
1754
- init_column_builder();
1755
- init_column();
1756
- init_entity();
1757
- init_foreign_keys();
1758
- init_unique_constraint2();
1759
- SQLiteColumnBuilder = class SQLiteColumnBuilder extends ColumnBuilder {
1760
- static [entityKind] = "SQLiteColumnBuilder";
1761
- foreignKeyConfigs = [];
1762
- references(ref, actions = {}) {
1763
- this.foreignKeyConfigs.push({ ref, actions });
1764
- return this;
1765
- }
1766
- unique(name) {
1767
- this.config.isUnique = true;
1768
- this.config.uniqueName = name;
1769
- return this;
1770
- }
1771
- generatedAlwaysAs(as, config) {
1772
- this.config.generated = {
1773
- as,
1774
- type: "always",
1775
- mode: config?.mode ?? "virtual"
1776
- };
1777
- return this;
1778
- }
1779
- buildForeignKeys(column2, table2) {
1780
- return this.foreignKeyConfigs.map(({ ref, actions }) => {
1781
- return ((ref2, actions2) => {
1782
- const builder = new ForeignKeyBuilder(() => {
1783
- const foreignColumn = ref2();
1784
- return { columns: [column2], foreignColumns: [foreignColumn] };
1785
- });
1786
- if (actions2.onUpdate) {
1787
- builder.onUpdate(actions2.onUpdate);
1788
- }
1789
- if (actions2.onDelete) {
1790
- builder.onDelete(actions2.onDelete);
1791
- }
1792
- return builder.build(table2);
1793
- })(ref, actions);
1794
- });
1795
- }
1796
- };
1797
- SQLiteColumn = class SQLiteColumn extends Column {
1798
- constructor(table2, config) {
1799
- if (!config.uniqueName) {
1800
- config.uniqueName = uniqueKeyName2(table2, [config.name]);
1801
- }
1802
- super(table2, config);
1803
- this.table = table2;
1804
- }
1805
- static [entityKind] = "SQLiteColumn";
1806
- };
1807
- });
1808
-
1809
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/columns/blob.js
1810
- function blob(a, b) {
1811
- const { name, config } = getColumnNameAndConfig(a, b);
1812
- if (config?.mode === "json") {
1813
- return new SQLiteBlobJsonBuilder(name);
1814
- }
1815
- if (config?.mode === "bigint") {
1816
- return new SQLiteBigIntBuilder(name);
1817
- }
1818
- return new SQLiteBlobBufferBuilder(name);
1819
- }
1820
- var SQLiteBigIntBuilder, SQLiteBigInt, SQLiteBlobJsonBuilder, SQLiteBlobJson, SQLiteBlobBufferBuilder, SQLiteBlobBuffer;
1821
- var init_blob = __esm(() => {
1822
- init_entity();
1823
- init_utils();
1824
- init_common2();
1825
- SQLiteBigIntBuilder = class SQLiteBigIntBuilder extends SQLiteColumnBuilder {
1826
- static [entityKind] = "SQLiteBigIntBuilder";
1827
- constructor(name) {
1828
- super(name, "bigint", "SQLiteBigInt");
1829
- }
1830
- build(table2) {
1831
- return new SQLiteBigInt(table2, this.config);
1832
- }
1833
- };
1834
- SQLiteBigInt = class SQLiteBigInt extends SQLiteColumn {
1835
- static [entityKind] = "SQLiteBigInt";
1836
- getSQLType() {
1837
- return "blob";
1838
- }
1839
- mapFromDriverValue(value) {
1840
- if (typeof Buffer !== "undefined" && Buffer.from) {
1841
- const buf = Buffer.isBuffer(value) ? value : value instanceof ArrayBuffer ? Buffer.from(value) : value.buffer ? Buffer.from(value.buffer, value.byteOffset, value.byteLength) : Buffer.from(value);
1842
- return BigInt(buf.toString("utf8"));
1843
- }
1844
- return BigInt(textDecoder.decode(value));
1845
- }
1846
- mapToDriverValue(value) {
1847
- return Buffer.from(value.toString());
1848
- }
1849
- };
1850
- SQLiteBlobJsonBuilder = class SQLiteBlobJsonBuilder extends SQLiteColumnBuilder {
1851
- static [entityKind] = "SQLiteBlobJsonBuilder";
1852
- constructor(name) {
1853
- super(name, "json", "SQLiteBlobJson");
1854
- }
1855
- build(table2) {
1856
- return new SQLiteBlobJson(table2, this.config);
1857
- }
1858
- };
1859
- SQLiteBlobJson = class SQLiteBlobJson extends SQLiteColumn {
1860
- static [entityKind] = "SQLiteBlobJson";
1861
- getSQLType() {
1862
- return "blob";
1863
- }
1864
- mapFromDriverValue(value) {
1865
- if (typeof Buffer !== "undefined" && Buffer.from) {
1866
- const buf = Buffer.isBuffer(value) ? value : value instanceof ArrayBuffer ? Buffer.from(value) : value.buffer ? Buffer.from(value.buffer, value.byteOffset, value.byteLength) : Buffer.from(value);
1867
- return JSON.parse(buf.toString("utf8"));
1868
- }
1869
- return JSON.parse(textDecoder.decode(value));
1870
- }
1871
- mapToDriverValue(value) {
1872
- return Buffer.from(JSON.stringify(value));
1873
- }
1874
- };
1875
- SQLiteBlobBufferBuilder = class SQLiteBlobBufferBuilder extends SQLiteColumnBuilder {
1876
- static [entityKind] = "SQLiteBlobBufferBuilder";
1877
- constructor(name) {
1878
- super(name, "buffer", "SQLiteBlobBuffer");
1879
- }
1880
- build(table2) {
1881
- return new SQLiteBlobBuffer(table2, this.config);
1882
- }
1883
- };
1884
- SQLiteBlobBuffer = class SQLiteBlobBuffer extends SQLiteColumn {
1885
- static [entityKind] = "SQLiteBlobBuffer";
1886
- mapFromDriverValue(value) {
1887
- if (Buffer.isBuffer(value)) {
1888
- return value;
1889
- }
1890
- return Buffer.from(value);
1891
- }
1892
- getSQLType() {
1893
- return "blob";
1894
- }
1895
- };
1896
- });
1897
-
1898
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/columns/custom.js
1899
- function customType(customTypeParams) {
1900
- return (a, b) => {
1901
- const { name, config } = getColumnNameAndConfig(a, b);
1902
- return new SQLiteCustomColumnBuilder(name, config, customTypeParams);
1903
- };
1904
- }
1905
- var SQLiteCustomColumnBuilder, SQLiteCustomColumn;
1906
- var init_custom = __esm(() => {
1907
- init_entity();
1908
- init_utils();
1909
- init_common2();
1910
- SQLiteCustomColumnBuilder = class SQLiteCustomColumnBuilder extends SQLiteColumnBuilder {
1911
- static [entityKind] = "SQLiteCustomColumnBuilder";
1912
- constructor(name, fieldConfig, customTypeParams) {
1913
- super(name, "custom", "SQLiteCustomColumn");
1914
- this.config.fieldConfig = fieldConfig;
1915
- this.config.customTypeParams = customTypeParams;
1916
- }
1917
- build(table2) {
1918
- return new SQLiteCustomColumn(table2, this.config);
1919
- }
1920
- };
1921
- SQLiteCustomColumn = class SQLiteCustomColumn extends SQLiteColumn {
1922
- static [entityKind] = "SQLiteCustomColumn";
1923
- sqlName;
1924
- mapTo;
1925
- mapFrom;
1926
- constructor(table2, config) {
1927
- super(table2, config);
1928
- this.sqlName = config.customTypeParams.dataType(config.fieldConfig);
1929
- this.mapTo = config.customTypeParams.toDriver;
1930
- this.mapFrom = config.customTypeParams.fromDriver;
1931
- }
1932
- getSQLType() {
1933
- return this.sqlName;
1934
- }
1935
- mapFromDriverValue(value) {
1936
- return typeof this.mapFrom === "function" ? this.mapFrom(value) : value;
1937
- }
1938
- mapToDriverValue(value) {
1939
- return typeof this.mapTo === "function" ? this.mapTo(value) : value;
1940
- }
1941
- };
1942
- });
1943
-
1944
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/columns/integer.js
1945
- function integer(a, b) {
1946
- const { name, config } = getColumnNameAndConfig(a, b);
1947
- if (config?.mode === "timestamp" || config?.mode === "timestamp_ms") {
1948
- return new SQLiteTimestampBuilder(name, config.mode);
1949
- }
1950
- if (config?.mode === "boolean") {
1951
- return new SQLiteBooleanBuilder(name, config.mode);
1952
- }
1953
- return new SQLiteIntegerBuilder(name);
1954
- }
1955
- var SQLiteBaseIntegerBuilder, SQLiteBaseInteger, SQLiteIntegerBuilder, SQLiteInteger, SQLiteTimestampBuilder, SQLiteTimestamp, SQLiteBooleanBuilder, SQLiteBoolean;
1956
- var init_integer = __esm(() => {
1957
- init_entity();
1958
- init_sql();
1959
- init_utils();
1960
- init_common2();
1961
- SQLiteBaseIntegerBuilder = class SQLiteBaseIntegerBuilder extends SQLiteColumnBuilder {
1962
- static [entityKind] = "SQLiteBaseIntegerBuilder";
1963
- constructor(name, dataType, columnType) {
1964
- super(name, dataType, columnType);
1965
- this.config.autoIncrement = false;
1966
- }
1967
- primaryKey(config) {
1968
- if (config?.autoIncrement) {
1969
- this.config.autoIncrement = true;
1970
- }
1971
- this.config.hasDefault = true;
1972
- return super.primaryKey();
1973
- }
1974
- };
1975
- SQLiteBaseInteger = class SQLiteBaseInteger extends SQLiteColumn {
1976
- static [entityKind] = "SQLiteBaseInteger";
1977
- autoIncrement = this.config.autoIncrement;
1978
- getSQLType() {
1979
- return "integer";
1980
- }
1981
- };
1982
- SQLiteIntegerBuilder = class SQLiteIntegerBuilder extends SQLiteBaseIntegerBuilder {
1983
- static [entityKind] = "SQLiteIntegerBuilder";
1984
- constructor(name) {
1985
- super(name, "number", "SQLiteInteger");
1986
- }
1987
- build(table2) {
1988
- return new SQLiteInteger(table2, this.config);
1989
- }
1990
- };
1991
- SQLiteInteger = class SQLiteInteger extends SQLiteBaseInteger {
1992
- static [entityKind] = "SQLiteInteger";
1993
- };
1994
- SQLiteTimestampBuilder = class SQLiteTimestampBuilder extends SQLiteBaseIntegerBuilder {
1995
- static [entityKind] = "SQLiteTimestampBuilder";
1996
- constructor(name, mode) {
1997
- super(name, "date", "SQLiteTimestamp");
1998
- this.config.mode = mode;
1999
- }
2000
- defaultNow() {
2001
- return this.default(sql`(cast((julianday('now') - 2440587.5)*86400000 as integer))`);
2002
- }
2003
- build(table2) {
2004
- return new SQLiteTimestamp(table2, this.config);
2005
- }
2006
- };
2007
- SQLiteTimestamp = class SQLiteTimestamp extends SQLiteBaseInteger {
2008
- static [entityKind] = "SQLiteTimestamp";
2009
- mode = this.config.mode;
2010
- mapFromDriverValue(value) {
2011
- if (this.config.mode === "timestamp") {
2012
- return new Date(value * 1000);
2013
- }
2014
- return new Date(value);
2015
- }
2016
- mapToDriverValue(value) {
2017
- const unix = value.getTime();
2018
- if (this.config.mode === "timestamp") {
2019
- return Math.floor(unix / 1000);
2020
- }
2021
- return unix;
2022
- }
2023
- };
2024
- SQLiteBooleanBuilder = class SQLiteBooleanBuilder extends SQLiteBaseIntegerBuilder {
2025
- static [entityKind] = "SQLiteBooleanBuilder";
2026
- constructor(name, mode) {
2027
- super(name, "boolean", "SQLiteBoolean");
2028
- this.config.mode = mode;
2029
- }
2030
- build(table2) {
2031
- return new SQLiteBoolean(table2, this.config);
2032
- }
2033
- };
2034
- SQLiteBoolean = class SQLiteBoolean extends SQLiteBaseInteger {
2035
- static [entityKind] = "SQLiteBoolean";
2036
- mode = this.config.mode;
2037
- mapFromDriverValue(value) {
2038
- return Number(value) === 1;
2039
- }
2040
- mapToDriverValue(value) {
2041
- return value ? 1 : 0;
2042
- }
2043
- };
2044
- });
2045
-
2046
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/columns/numeric.js
2047
- function numeric(a, b) {
2048
- const { name, config } = getColumnNameAndConfig(a, b);
2049
- const mode = config?.mode;
2050
- return mode === "number" ? new SQLiteNumericNumberBuilder(name) : mode === "bigint" ? new SQLiteNumericBigIntBuilder(name) : new SQLiteNumericBuilder(name);
2051
- }
2052
- var SQLiteNumericBuilder, SQLiteNumeric, SQLiteNumericNumberBuilder, SQLiteNumericNumber, SQLiteNumericBigIntBuilder, SQLiteNumericBigInt;
2053
- var init_numeric = __esm(() => {
2054
- init_entity();
2055
- init_utils();
2056
- init_common2();
2057
- SQLiteNumericBuilder = class SQLiteNumericBuilder extends SQLiteColumnBuilder {
2058
- static [entityKind] = "SQLiteNumericBuilder";
2059
- constructor(name) {
2060
- super(name, "string", "SQLiteNumeric");
2061
- }
2062
- build(table2) {
2063
- return new SQLiteNumeric(table2, this.config);
2064
- }
2065
- };
2066
- SQLiteNumeric = class SQLiteNumeric extends SQLiteColumn {
2067
- static [entityKind] = "SQLiteNumeric";
2068
- mapFromDriverValue(value) {
2069
- if (typeof value === "string")
2070
- return value;
2071
- return String(value);
2072
- }
2073
- getSQLType() {
2074
- return "numeric";
2075
- }
2076
- };
2077
- SQLiteNumericNumberBuilder = class SQLiteNumericNumberBuilder extends SQLiteColumnBuilder {
2078
- static [entityKind] = "SQLiteNumericNumberBuilder";
2079
- constructor(name) {
2080
- super(name, "number", "SQLiteNumericNumber");
2081
- }
2082
- build(table2) {
2083
- return new SQLiteNumericNumber(table2, this.config);
2084
- }
2085
- };
2086
- SQLiteNumericNumber = class SQLiteNumericNumber extends SQLiteColumn {
2087
- static [entityKind] = "SQLiteNumericNumber";
2088
- mapFromDriverValue(value) {
2089
- if (typeof value === "number")
2090
- return value;
2091
- return Number(value);
2092
- }
2093
- mapToDriverValue = String;
2094
- getSQLType() {
2095
- return "numeric";
2096
- }
2097
- };
2098
- SQLiteNumericBigIntBuilder = class SQLiteNumericBigIntBuilder extends SQLiteColumnBuilder {
2099
- static [entityKind] = "SQLiteNumericBigIntBuilder";
2100
- constructor(name) {
2101
- super(name, "bigint", "SQLiteNumericBigInt");
2102
- }
2103
- build(table2) {
2104
- return new SQLiteNumericBigInt(table2, this.config);
2105
- }
2106
- };
2107
- SQLiteNumericBigInt = class SQLiteNumericBigInt extends SQLiteColumn {
2108
- static [entityKind] = "SQLiteNumericBigInt";
2109
- mapFromDriverValue = BigInt;
2110
- mapToDriverValue = String;
2111
- getSQLType() {
2112
- return "numeric";
2113
- }
2114
- };
2115
- });
2116
-
2117
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/columns/real.js
2118
- function real(name) {
2119
- return new SQLiteRealBuilder(name ?? "");
2120
- }
2121
- var SQLiteRealBuilder, SQLiteReal;
2122
- var init_real = __esm(() => {
2123
- init_entity();
2124
- init_common2();
2125
- SQLiteRealBuilder = class SQLiteRealBuilder extends SQLiteColumnBuilder {
2126
- static [entityKind] = "SQLiteRealBuilder";
2127
- constructor(name) {
2128
- super(name, "number", "SQLiteReal");
2129
- }
2130
- build(table2) {
2131
- return new SQLiteReal(table2, this.config);
2132
- }
2133
- };
2134
- SQLiteReal = class SQLiteReal extends SQLiteColumn {
2135
- static [entityKind] = "SQLiteReal";
2136
- getSQLType() {
2137
- return "real";
2138
- }
2139
- };
2140
- });
2141
-
2142
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/columns/text.js
2143
- function text(a, b = {}) {
2144
- const { name, config } = getColumnNameAndConfig(a, b);
2145
- if (config.mode === "json") {
2146
- return new SQLiteTextJsonBuilder(name);
2147
- }
2148
- return new SQLiteTextBuilder(name, config);
2149
- }
2150
- var SQLiteTextBuilder, SQLiteText, SQLiteTextJsonBuilder, SQLiteTextJson;
2151
- var init_text = __esm(() => {
2152
- init_entity();
2153
- init_utils();
2154
- init_common2();
2155
- SQLiteTextBuilder = class SQLiteTextBuilder extends SQLiteColumnBuilder {
2156
- static [entityKind] = "SQLiteTextBuilder";
2157
- constructor(name, config) {
2158
- super(name, "string", "SQLiteText");
2159
- this.config.enumValues = config.enum;
2160
- this.config.length = config.length;
2161
- }
2162
- build(table2) {
2163
- return new SQLiteText(table2, this.config);
2164
- }
2165
- };
2166
- SQLiteText = class SQLiteText extends SQLiteColumn {
2167
- static [entityKind] = "SQLiteText";
2168
- enumValues = this.config.enumValues;
2169
- length = this.config.length;
2170
- constructor(table2, config) {
2171
- super(table2, config);
2172
- }
2173
- getSQLType() {
2174
- return `text${this.config.length ? `(${this.config.length})` : ""}`;
2175
- }
2176
- };
2177
- SQLiteTextJsonBuilder = class SQLiteTextJsonBuilder extends SQLiteColumnBuilder {
2178
- static [entityKind] = "SQLiteTextJsonBuilder";
2179
- constructor(name) {
2180
- super(name, "json", "SQLiteTextJson");
2181
- }
2182
- build(table2) {
2183
- return new SQLiteTextJson(table2, this.config);
2184
- }
2185
- };
2186
- SQLiteTextJson = class SQLiteTextJson extends SQLiteColumn {
2187
- static [entityKind] = "SQLiteTextJson";
2188
- getSQLType() {
2189
- return "text";
2190
- }
2191
- mapFromDriverValue(value) {
2192
- return JSON.parse(value);
2193
- }
2194
- mapToDriverValue(value) {
2195
- return JSON.stringify(value);
2196
- }
2197
- };
2198
- });
2199
-
2200
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/columns/all.js
2201
- function getSQLiteColumnBuilders() {
2202
- return {
2203
- blob,
2204
- customType,
2205
- integer,
2206
- numeric,
2207
- real,
2208
- text
2209
- };
2210
- }
2211
- var init_all = __esm(() => {
2212
- init_blob();
2213
- init_custom();
2214
- init_integer();
2215
- init_numeric();
2216
- init_real();
2217
- init_text();
2218
- });
2219
-
2220
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/table.js
2221
- function sqliteTableBase(name, columns, extraConfig, schema, baseName = name) {
2222
- const rawTable = new SQLiteTable(name, schema, baseName);
2223
- const parsedColumns = typeof columns === "function" ? columns(getSQLiteColumnBuilders()) : columns;
2224
- const builtColumns = Object.fromEntries(Object.entries(parsedColumns).map(([name2, colBuilderBase]) => {
2225
- const colBuilder = colBuilderBase;
2226
- colBuilder.setName(name2);
2227
- const column2 = colBuilder.build(rawTable);
2228
- rawTable[InlineForeignKeys2].push(...colBuilder.buildForeignKeys(column2, rawTable));
2229
- return [name2, column2];
2230
- }));
2231
- const table2 = Object.assign(rawTable, builtColumns);
2232
- table2[Table.Symbol.Columns] = builtColumns;
2233
- table2[Table.Symbol.ExtraConfigColumns] = builtColumns;
2234
- if (extraConfig) {
2235
- table2[SQLiteTable.Symbol.ExtraConfigBuilder] = extraConfig;
2236
- }
2237
- return table2;
2238
- }
2239
- var InlineForeignKeys2, SQLiteTable, sqliteTable = (name, columns, extraConfig) => {
2240
- return sqliteTableBase(name, columns, extraConfig);
2241
- };
2242
- var init_table3 = __esm(() => {
2243
- init_entity();
2244
- init_table();
2245
- init_all();
2246
- InlineForeignKeys2 = Symbol.for("drizzle:SQLiteInlineForeignKeys");
2247
- SQLiteTable = class SQLiteTable extends Table {
2248
- static [entityKind] = "SQLiteTable";
2249
- static Symbol = Object.assign({}, Table.Symbol, {
2250
- InlineForeignKeys: InlineForeignKeys2
2251
- });
2252
- [Table.Symbol.Columns];
2253
- [InlineForeignKeys2] = [];
2254
- [Table.Symbol.ExtraConfigBuilder] = undefined;
2255
- };
2256
- });
2257
-
2258
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/checks.js
2259
- var init_checks = () => {};
2260
-
2261
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/indexes.js
2262
- function index(name) {
2263
- return new IndexBuilderOn(name, false);
2264
- }
2265
- function uniqueIndex(name) {
2266
- return new IndexBuilderOn(name, true);
2267
- }
2268
- var IndexBuilderOn, IndexBuilder, Index;
2269
- var init_indexes = __esm(() => {
2270
- init_entity();
2271
- IndexBuilderOn = class IndexBuilderOn {
2272
- constructor(name, unique) {
2273
- this.name = name;
2274
- this.unique = unique;
2275
- }
2276
- static [entityKind] = "SQLiteIndexBuilderOn";
2277
- on(...columns) {
2278
- return new IndexBuilder(this.name, columns, this.unique);
2279
- }
2280
- };
2281
- IndexBuilder = class IndexBuilder {
2282
- static [entityKind] = "SQLiteIndexBuilder";
2283
- config;
2284
- constructor(name, columns, unique) {
2285
- this.config = {
2286
- name,
2287
- columns,
2288
- unique,
2289
- where: undefined
2290
- };
2291
- }
2292
- where(condition) {
2293
- this.config.where = condition;
2294
- return this;
2295
- }
2296
- build(table2) {
2297
- return new Index(this.config, table2);
2298
- }
2299
- };
2300
- Index = class Index {
2301
- static [entityKind] = "SQLiteIndex";
2302
- config;
2303
- constructor(config, table2) {
2304
- this.config = { ...config, table: table2 };
2305
- }
2306
- };
2307
- });
2308
-
2309
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/primary-keys.js
2310
- var init_primary_keys2 = () => {};
2311
-
2312
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/utils.js
2313
- function extractUsedTable(table2) {
2314
- if (is(table2, SQLiteTable)) {
2315
- return [`${table2[Table.Symbol.BaseName]}`];
2316
- }
2317
- if (is(table2, Subquery)) {
2318
- return table2._.usedTables ?? [];
2319
- }
2320
- if (is(table2, SQL)) {
2321
- return table2.usedTables ?? [];
2322
- }
2323
- return [];
2324
- }
2325
- var init_utils2 = __esm(() => {
2326
- init_entity();
2327
- init_sql();
2328
- init_subquery();
2329
- init_table();
2330
- init_table3();
2331
- });
2332
-
2333
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/query-builders/delete.js
2334
- var SQLiteDeleteBase;
2335
- var init_delete = __esm(() => {
2336
- init_entity();
2337
- init_query_promise();
2338
- init_selection_proxy();
2339
- init_table3();
2340
- init_table();
2341
- init_utils();
2342
- init_utils2();
2343
- SQLiteDeleteBase = class SQLiteDeleteBase extends QueryPromise {
2344
- constructor(table2, session, dialect, withList) {
2345
- super();
2346
- this.table = table2;
2347
- this.session = session;
2348
- this.dialect = dialect;
2349
- this.config = { table: table2, withList };
2350
- }
2351
- static [entityKind] = "SQLiteDelete";
2352
- config;
2353
- where(where) {
2354
- this.config.where = where;
2355
- return this;
2356
- }
2357
- orderBy(...columns) {
2358
- if (typeof columns[0] === "function") {
2359
- const orderBy = columns[0](new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })));
2360
- const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
2361
- this.config.orderBy = orderByArray;
2362
- } else {
2363
- const orderByArray = columns;
2364
- this.config.orderBy = orderByArray;
2365
- }
2366
- return this;
2367
- }
2368
- limit(limit) {
2369
- this.config.limit = limit;
2370
- return this;
2371
- }
2372
- returning(fields = this.table[SQLiteTable.Symbol.Columns]) {
2373
- this.config.returning = orderSelectedFields(fields);
2374
- return this;
2375
- }
2376
- getSQL() {
2377
- return this.dialect.buildDeleteQuery(this.config);
2378
- }
2379
- toSQL() {
2380
- const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
2381
- return rest;
2382
- }
2383
- _prepare(isOneTimeQuery = true) {
2384
- return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](this.dialect.sqlToQuery(this.getSQL()), this.config.returning, this.config.returning ? "all" : "run", true, undefined, {
2385
- type: "delete",
2386
- tables: extractUsedTable(this.config.table)
2387
- });
2388
- }
2389
- prepare() {
2390
- return this._prepare(false);
2391
- }
2392
- run = (placeholderValues) => {
2393
- return this._prepare().run(placeholderValues);
2394
- };
2395
- all = (placeholderValues) => {
2396
- return this._prepare().all(placeholderValues);
2397
- };
2398
- get = (placeholderValues) => {
2399
- return this._prepare().get(placeholderValues);
2400
- };
2401
- values = (placeholderValues) => {
2402
- return this._prepare().values(placeholderValues);
2403
- };
2404
- async execute(placeholderValues) {
2405
- return this._prepare().execute(placeholderValues);
2406
- }
2407
- $dynamic() {
2408
- return this;
2409
- }
2410
- };
2411
- });
2412
-
2413
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/casing.js
2414
- function toSnakeCase(input) {
2415
- const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? [];
2416
- return words.map((word) => word.toLowerCase()).join("_");
2417
- }
2418
- function toCamelCase(input) {
2419
- const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? [];
2420
- return words.reduce((acc, word, i) => {
2421
- const formattedWord = i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`;
2422
- return acc + formattedWord;
2423
- }, "");
2424
- }
2425
- function noopCase(input) {
2426
- return input;
2427
- }
2428
- var CasingCache;
2429
- var init_casing = __esm(() => {
2430
- init_entity();
2431
- init_table();
2432
- CasingCache = class CasingCache {
2433
- static [entityKind] = "CasingCache";
2434
- cache = {};
2435
- cachedTables = {};
2436
- convert;
2437
- constructor(casing) {
2438
- this.convert = casing === "snake_case" ? toSnakeCase : casing === "camelCase" ? toCamelCase : noopCase;
2439
- }
2440
- getColumnCasing(column2) {
2441
- if (!column2.keyAsName)
2442
- return column2.name;
2443
- const schema = column2.table[Table.Symbol.Schema] ?? "public";
2444
- const tableName = column2.table[Table.Symbol.OriginalName];
2445
- const key = `${schema}.${tableName}.${column2.name}`;
2446
- if (!this.cache[key]) {
2447
- this.cacheTable(column2.table);
2448
- }
2449
- return this.cache[key];
2450
- }
2451
- cacheTable(table2) {
2452
- const schema = table2[Table.Symbol.Schema] ?? "public";
2453
- const tableName = table2[Table.Symbol.OriginalName];
2454
- const tableKey = `${schema}.${tableName}`;
2455
- if (!this.cachedTables[tableKey]) {
2456
- for (const column2 of Object.values(table2[Table.Symbol.Columns])) {
2457
- const columnKey = `${tableKey}.${column2.name}`;
2458
- this.cache[columnKey] = this.convert(column2.name);
2459
- }
2460
- this.cachedTables[tableKey] = true;
2461
- }
2462
- }
2463
- clearCache() {
2464
- this.cache = {};
2465
- this.cachedTables = {};
2466
- }
2467
- };
2468
- });
2469
-
2470
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/columns/index.js
2471
- var init_columns = __esm(() => {
2472
- init_blob();
2473
- init_common2();
2474
- init_custom();
2475
- init_integer();
2476
- init_numeric();
2477
- init_real();
2478
- init_text();
2479
- });
2480
-
2481
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/view-base.js
2482
- var SQLiteViewBase;
2483
- var init_view_base = __esm(() => {
2484
- init_entity();
2485
- init_sql();
2486
- SQLiteViewBase = class SQLiteViewBase extends View {
2487
- static [entityKind] = "SQLiteViewBase";
2488
- };
2489
- });
2490
-
2491
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/dialect.js
2492
- var SQLiteDialect, SQLiteSyncDialect;
2493
- var init_dialect = __esm(() => {
2494
- init_alias();
2495
- init_casing();
2496
- init_column();
2497
- init_entity();
2498
- init_errors();
2499
- init_relations();
2500
- init_sql2();
2501
- init_sql();
2502
- init_columns();
2503
- init_table3();
2504
- init_subquery();
2505
- init_table();
2506
- init_utils();
2507
- init_view_common();
2508
- init_view_base();
2509
- SQLiteDialect = class SQLiteDialect {
2510
- static [entityKind] = "SQLiteDialect";
2511
- casing;
2512
- constructor(config) {
2513
- this.casing = new CasingCache(config?.casing);
2514
- }
2515
- escapeName(name) {
2516
- return `"${name}"`;
2517
- }
2518
- escapeParam(_num) {
2519
- return "?";
2520
- }
2521
- escapeString(str) {
2522
- return `'${str.replace(/'/g, "''")}'`;
2523
- }
2524
- buildWithCTE(queries) {
2525
- if (!queries?.length)
2526
- return;
2527
- const withSqlChunks = [sql`with `];
2528
- for (const [i, w] of queries.entries()) {
2529
- withSqlChunks.push(sql`${sql.identifier(w._.alias)} as (${w._.sql})`);
2530
- if (i < queries.length - 1) {
2531
- withSqlChunks.push(sql`, `);
2532
- }
2533
- }
2534
- withSqlChunks.push(sql` `);
2535
- return sql.join(withSqlChunks);
2536
- }
2537
- buildDeleteQuery({ table: table2, where, returning, withList, limit, orderBy }) {
2538
- const withSql = this.buildWithCTE(withList);
2539
- const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : undefined;
2540
- const whereSql = where ? sql` where ${where}` : undefined;
2541
- const orderBySql = this.buildOrderBy(orderBy);
2542
- const limitSql = this.buildLimit(limit);
2543
- return sql`${withSql}delete from ${table2}${whereSql}${returningSql}${orderBySql}${limitSql}`;
2544
- }
2545
- buildUpdateSet(table2, set) {
2546
- const tableColumns = table2[Table.Symbol.Columns];
2547
- const columnNames = Object.keys(tableColumns).filter((colName) => set[colName] !== undefined || tableColumns[colName]?.onUpdateFn !== undefined);
2548
- const setSize = columnNames.length;
2549
- return sql.join(columnNames.flatMap((colName, i) => {
2550
- const col = tableColumns[colName];
2551
- const value = set[colName] ?? sql.param(col.onUpdateFn(), col);
2552
- const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`;
2553
- if (i < setSize - 1) {
2554
- return [res, sql.raw(", ")];
2555
- }
2556
- return [res];
2557
- }));
2558
- }
2559
- buildUpdateQuery({ table: table2, set, where, returning, withList, joins, from, limit, orderBy }) {
2560
- const withSql = this.buildWithCTE(withList);
2561
- const setSql = this.buildUpdateSet(table2, set);
2562
- const fromSql = from && sql.join([sql.raw(" from "), this.buildFromTable(from)]);
2563
- const joinsSql = this.buildJoins(joins);
2564
- const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : undefined;
2565
- const whereSql = where ? sql` where ${where}` : undefined;
2566
- const orderBySql = this.buildOrderBy(orderBy);
2567
- const limitSql = this.buildLimit(limit);
2568
- return sql`${withSql}update ${table2} set ${setSql}${fromSql}${joinsSql}${whereSql}${returningSql}${orderBySql}${limitSql}`;
2569
- }
2570
- buildSelection(fields, { isSingleTable = false } = {}) {
2571
- const columnsLen = fields.length;
2572
- const chunks = fields.flatMap(({ field }, i) => {
2573
- const chunk = [];
2574
- if (is(field, SQL.Aliased) && field.isSelectionField) {
2575
- chunk.push(sql.identifier(field.fieldAlias));
2576
- } else if (is(field, SQL.Aliased) || is(field, SQL)) {
2577
- const query = is(field, SQL.Aliased) ? field.sql : field;
2578
- if (isSingleTable) {
2579
- chunk.push(new SQL(query.queryChunks.map((c) => {
2580
- if (is(c, Column)) {
2581
- return sql.identifier(this.casing.getColumnCasing(c));
2582
- }
2583
- return c;
2584
- })));
2585
- } else {
2586
- chunk.push(query);
2587
- }
2588
- if (is(field, SQL.Aliased)) {
2589
- chunk.push(sql` as ${sql.identifier(field.fieldAlias)}`);
2590
- }
2591
- } else if (is(field, Column)) {
2592
- const tableName = field.table[Table.Symbol.Name];
2593
- if (field.columnType === "SQLiteNumericBigInt") {
2594
- if (isSingleTable) {
2595
- chunk.push(sql`cast(${sql.identifier(this.casing.getColumnCasing(field))} as text)`);
2596
- } else {
2597
- chunk.push(sql`cast(${sql.identifier(tableName)}.${sql.identifier(this.casing.getColumnCasing(field))} as text)`);
2598
- }
2599
- } else {
2600
- if (isSingleTable) {
2601
- chunk.push(sql.identifier(this.casing.getColumnCasing(field)));
2602
- } else {
2603
- chunk.push(sql`${sql.identifier(tableName)}.${sql.identifier(this.casing.getColumnCasing(field))}`);
2604
- }
2605
- }
2606
- }
2607
- if (i < columnsLen - 1) {
2608
- chunk.push(sql`, `);
2609
- }
2610
- return chunk;
2611
- });
2612
- return sql.join(chunks);
2613
- }
2614
- buildJoins(joins) {
2615
- if (!joins || joins.length === 0) {
2616
- return;
2617
- }
2618
- const joinsArray = [];
2619
- if (joins) {
2620
- for (const [index2, joinMeta] of joins.entries()) {
2621
- if (index2 === 0) {
2622
- joinsArray.push(sql` `);
2623
- }
2624
- const table2 = joinMeta.table;
2625
- const onSql = joinMeta.on ? sql` on ${joinMeta.on}` : undefined;
2626
- if (is(table2, SQLiteTable)) {
2627
- const tableName = table2[SQLiteTable.Symbol.Name];
2628
- const tableSchema = table2[SQLiteTable.Symbol.Schema];
2629
- const origTableName = table2[SQLiteTable.Symbol.OriginalName];
2630
- const alias3 = tableName === origTableName ? undefined : joinMeta.alias;
2631
- joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : undefined}${sql.identifier(origTableName)}${alias3 && sql` ${sql.identifier(alias3)}`}${onSql}`);
2632
- } else {
2633
- joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join ${table2}${onSql}`);
2634
- }
2635
- if (index2 < joins.length - 1) {
2636
- joinsArray.push(sql` `);
2637
- }
2638
- }
2639
- }
2640
- return sql.join(joinsArray);
2641
- }
2642
- buildLimit(limit) {
2643
- return typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : undefined;
2644
- }
2645
- buildOrderBy(orderBy) {
2646
- const orderByList = [];
2647
- if (orderBy) {
2648
- for (const [index2, orderByValue] of orderBy.entries()) {
2649
- orderByList.push(orderByValue);
2650
- if (index2 < orderBy.length - 1) {
2651
- orderByList.push(sql`, `);
2652
- }
2653
- }
2654
- }
2655
- return orderByList.length > 0 ? sql` order by ${sql.join(orderByList)}` : undefined;
2656
- }
2657
- buildFromTable(table2) {
2658
- if (is(table2, Table) && table2[Table.Symbol.IsAlias]) {
2659
- return sql`${sql`${sql.identifier(table2[Table.Symbol.Schema] ?? "")}.`.if(table2[Table.Symbol.Schema])}${sql.identifier(table2[Table.Symbol.OriginalName])} ${sql.identifier(table2[Table.Symbol.Name])}`;
2660
- }
2661
- return table2;
2662
- }
2663
- buildSelectQuery({
2664
- withList,
2665
- fields,
2666
- fieldsFlat,
2667
- where,
2668
- having,
2669
- table: table2,
2670
- joins,
2671
- orderBy,
2672
- groupBy,
2673
- limit,
2674
- offset,
2675
- distinct,
2676
- setOperators
2677
- }) {
2678
- const fieldsList = fieldsFlat ?? orderSelectedFields(fields);
2679
- for (const f of fieldsList) {
2680
- if (is(f.field, Column) && getTableName(f.field.table) !== (is(table2, Subquery) ? table2._.alias : is(table2, SQLiteViewBase) ? table2[ViewBaseConfig].name : is(table2, SQL) ? undefined : getTableName(table2)) && !((table22) => joins?.some(({ alias: alias3 }) => alias3 === (table22[Table.Symbol.IsAlias] ? getTableName(table22) : table22[Table.Symbol.BaseName])))(f.field.table)) {
2681
- const tableName = getTableName(f.field.table);
2682
- throw new Error(`Your "${f.path.join("->")}" field references a column "${tableName}"."${f.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?`);
2683
- }
2684
- }
2685
- const isSingleTable = !joins || joins.length === 0;
2686
- const withSql = this.buildWithCTE(withList);
2687
- const distinctSql = distinct ? sql` distinct` : undefined;
2688
- const selection = this.buildSelection(fieldsList, { isSingleTable });
2689
- const tableSql = this.buildFromTable(table2);
2690
- const joinsSql = this.buildJoins(joins);
2691
- const whereSql = where ? sql` where ${where}` : undefined;
2692
- const havingSql = having ? sql` having ${having}` : undefined;
2693
- const groupByList = [];
2694
- if (groupBy) {
2695
- for (const [index2, groupByValue] of groupBy.entries()) {
2696
- groupByList.push(groupByValue);
2697
- if (index2 < groupBy.length - 1) {
2698
- groupByList.push(sql`, `);
2699
- }
2700
- }
2701
- }
2702
- const groupBySql = groupByList.length > 0 ? sql` group by ${sql.join(groupByList)}` : undefined;
2703
- const orderBySql = this.buildOrderBy(orderBy);
2704
- const limitSql = this.buildLimit(limit);
2705
- const offsetSql = offset ? sql` offset ${offset}` : undefined;
2706
- const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}`;
2707
- if (setOperators.length > 0) {
2708
- return this.buildSetOperations(finalQuery, setOperators);
2709
- }
2710
- return finalQuery;
2711
- }
2712
- buildSetOperations(leftSelect, setOperators) {
2713
- const [setOperator, ...rest] = setOperators;
2714
- if (!setOperator) {
2715
- throw new Error("Cannot pass undefined values to any set operator");
2716
- }
2717
- if (rest.length === 0) {
2718
- return this.buildSetOperationQuery({ leftSelect, setOperator });
2719
- }
2720
- return this.buildSetOperations(this.buildSetOperationQuery({ leftSelect, setOperator }), rest);
2721
- }
2722
- buildSetOperationQuery({
2723
- leftSelect,
2724
- setOperator: { type, isAll, rightSelect, limit, orderBy, offset }
2725
- }) {
2726
- const leftChunk = sql`${leftSelect.getSQL()} `;
2727
- const rightChunk = sql`${rightSelect.getSQL()}`;
2728
- let orderBySql;
2729
- if (orderBy && orderBy.length > 0) {
2730
- const orderByValues = [];
2731
- for (const singleOrderBy of orderBy) {
2732
- if (is(singleOrderBy, SQLiteColumn)) {
2733
- orderByValues.push(sql.identifier(singleOrderBy.name));
2734
- } else if (is(singleOrderBy, SQL)) {
2735
- for (let i = 0;i < singleOrderBy.queryChunks.length; i++) {
2736
- const chunk = singleOrderBy.queryChunks[i];
2737
- if (is(chunk, SQLiteColumn)) {
2738
- singleOrderBy.queryChunks[i] = sql.identifier(this.casing.getColumnCasing(chunk));
2739
- }
2740
- }
2741
- orderByValues.push(sql`${singleOrderBy}`);
2742
- } else {
2743
- orderByValues.push(sql`${singleOrderBy}`);
2744
- }
2745
- }
2746
- orderBySql = sql` order by ${sql.join(orderByValues, sql`, `)}`;
2747
- }
2748
- const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : undefined;
2749
- const operatorChunk = sql.raw(`${type} ${isAll ? "all " : ""}`);
2750
- const offsetSql = offset ? sql` offset ${offset}` : undefined;
2751
- return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;
2752
- }
2753
- buildInsertQuery({ table: table2, values: valuesOrSelect, onConflict, returning, withList, select: select2 }) {
2754
- const valuesSqlList = [];
2755
- const columns = table2[Table.Symbol.Columns];
2756
- const colEntries = Object.entries(columns).filter(([_, col]) => !col.shouldDisableInsert());
2757
- const insertOrder = colEntries.map(([, column2]) => sql.identifier(this.casing.getColumnCasing(column2)));
2758
- if (select2) {
2759
- const select22 = valuesOrSelect;
2760
- if (is(select22, SQL)) {
2761
- valuesSqlList.push(select22);
2762
- } else {
2763
- valuesSqlList.push(select22.getSQL());
2764
- }
2765
- } else {
2766
- const values = valuesOrSelect;
2767
- valuesSqlList.push(sql.raw("values "));
2768
- for (const [valueIndex, value] of values.entries()) {
2769
- const valueList = [];
2770
- for (const [fieldName, col] of colEntries) {
2771
- const colValue = value[fieldName];
2772
- if (colValue === undefined || is(colValue, Param) && colValue.value === undefined) {
2773
- let defaultValue;
2774
- if (col.default !== null && col.default !== undefined) {
2775
- defaultValue = is(col.default, SQL) ? col.default : sql.param(col.default, col);
2776
- } else if (col.defaultFn !== undefined) {
2777
- const defaultFnResult = col.defaultFn();
2778
- defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);
2779
- } else if (!col.default && col.onUpdateFn !== undefined) {
2780
- const onUpdateFnResult = col.onUpdateFn();
2781
- defaultValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);
2782
- } else {
2783
- defaultValue = sql`null`;
2784
- }
2785
- valueList.push(defaultValue);
2786
- } else {
2787
- valueList.push(colValue);
2788
- }
2789
- }
2790
- valuesSqlList.push(valueList);
2791
- if (valueIndex < values.length - 1) {
2792
- valuesSqlList.push(sql`, `);
2793
- }
2794
- }
2795
- }
2796
- const withSql = this.buildWithCTE(withList);
2797
- const valuesSql = sql.join(valuesSqlList);
2798
- const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : undefined;
2799
- const onConflictSql = onConflict?.length ? sql.join(onConflict) : undefined;
2800
- return sql`${withSql}insert into ${table2} ${insertOrder} ${valuesSql}${onConflictSql}${returningSql}`;
2801
- }
2802
- sqlToQuery(sql22, invokeSource) {
2803
- return sql22.toQuery({
2804
- casing: this.casing,
2805
- escapeName: this.escapeName,
2806
- escapeParam: this.escapeParam,
2807
- escapeString: this.escapeString,
2808
- invokeSource
2809
- });
2810
- }
2811
- buildRelationalQuery({
2812
- fullSchema,
2813
- schema,
2814
- tableNamesMap,
2815
- table: table2,
2816
- tableConfig,
2817
- queryConfig: config,
2818
- tableAlias,
2819
- nestedQueryRelation,
2820
- joinOn
2821
- }) {
2822
- let selection = [];
2823
- let limit, offset, orderBy = [], where;
2824
- const joins = [];
2825
- if (config === true) {
2826
- const selectionEntries = Object.entries(tableConfig.columns);
2827
- selection = selectionEntries.map(([key, value]) => ({
2828
- dbKey: value.name,
2829
- tsKey: key,
2830
- field: aliasedTableColumn(value, tableAlias),
2831
- relationTableTsKey: undefined,
2832
- isJson: false,
2833
- selection: []
2834
- }));
2835
- } else {
2836
- const aliasedColumns = Object.fromEntries(Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]));
2837
- if (config.where) {
2838
- const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, getOperators()) : config.where;
2839
- where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
2840
- }
2841
- const fieldsSelection = [];
2842
- let selectedColumns = [];
2843
- if (config.columns) {
2844
- let isIncludeMode = false;
2845
- for (const [field, value] of Object.entries(config.columns)) {
2846
- if (value === undefined) {
2847
- continue;
2848
- }
2849
- if (field in tableConfig.columns) {
2850
- if (!isIncludeMode && value === true) {
2851
- isIncludeMode = true;
2852
- }
2853
- selectedColumns.push(field);
2854
- }
2855
- }
2856
- if (selectedColumns.length > 0) {
2857
- selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
2858
- }
2859
- } else {
2860
- selectedColumns = Object.keys(tableConfig.columns);
2861
- }
2862
- for (const field of selectedColumns) {
2863
- const column2 = tableConfig.columns[field];
2864
- fieldsSelection.push({ tsKey: field, value: column2 });
2865
- }
2866
- let selectedRelations = [];
2867
- if (config.with) {
2868
- selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] }));
2869
- }
2870
- let extras;
2871
- if (config.extras) {
2872
- extras = typeof config.extras === "function" ? config.extras(aliasedColumns, { sql }) : config.extras;
2873
- for (const [tsKey, value] of Object.entries(extras)) {
2874
- fieldsSelection.push({
2875
- tsKey,
2876
- value: mapColumnsInAliasedSQLToAlias(value, tableAlias)
2877
- });
2878
- }
2879
- }
2880
- for (const { tsKey, value } of fieldsSelection) {
2881
- selection.push({
2882
- dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name,
2883
- tsKey,
2884
- field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value,
2885
- relationTableTsKey: undefined,
2886
- isJson: false,
2887
- selection: []
2888
- });
2889
- }
2890
- let orderByOrig = typeof config.orderBy === "function" ? config.orderBy(aliasedColumns, getOrderByOperators()) : config.orderBy ?? [];
2891
- if (!Array.isArray(orderByOrig)) {
2892
- orderByOrig = [orderByOrig];
2893
- }
2894
- orderBy = orderByOrig.map((orderByValue) => {
2895
- if (is(orderByValue, Column)) {
2896
- return aliasedTableColumn(orderByValue, tableAlias);
2897
- }
2898
- return mapColumnsInSQLToAlias(orderByValue, tableAlias);
2899
- });
2900
- limit = config.limit;
2901
- offset = config.offset;
2902
- for (const {
2903
- tsKey: selectedRelationTsKey,
2904
- queryConfig: selectedRelationConfigValue,
2905
- relation
2906
- } of selectedRelations) {
2907
- const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
2908
- const relationTableName = getTableUniqueName(relation.referencedTable);
2909
- const relationTableTsName = tableNamesMap[relationTableName];
2910
- const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
2911
- const joinOn2 = and(...normalizedRelation.fields.map((field2, i) => eq(aliasedTableColumn(normalizedRelation.references[i], relationTableAlias), aliasedTableColumn(field2, tableAlias))));
2912
- const builtRelation = this.buildRelationalQuery({
2913
- fullSchema,
2914
- schema,
2915
- tableNamesMap,
2916
- table: fullSchema[relationTableTsName],
2917
- tableConfig: schema[relationTableTsName],
2918
- queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue,
2919
- tableAlias: relationTableAlias,
2920
- joinOn: joinOn2,
2921
- nestedQueryRelation: relation
2922
- });
2923
- const field = sql`(${builtRelation.sql})`.as(selectedRelationTsKey);
2924
- selection.push({
2925
- dbKey: selectedRelationTsKey,
2926
- tsKey: selectedRelationTsKey,
2927
- field,
2928
- relationTableTsKey: relationTableTsName,
2929
- isJson: true,
2930
- selection: builtRelation.selection
2931
- });
2932
- }
2933
- }
2934
- if (selection.length === 0) {
2935
- throw new DrizzleError({
2936
- message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`
2937
- });
2938
- }
2939
- let result;
2940
- where = and(joinOn, where);
2941
- if (nestedQueryRelation) {
2942
- let field = sql`json_array(${sql.join(selection.map(({ field: field2 }) => is(field2, SQLiteColumn) ? sql.identifier(this.casing.getColumnCasing(field2)) : is(field2, SQL.Aliased) ? field2.sql : field2), sql`, `)})`;
2943
- if (is(nestedQueryRelation, Many)) {
2944
- field = sql`coalesce(json_group_array(${field}), json_array())`;
2945
- }
2946
- const nestedSelection = [{
2947
- dbKey: "data",
2948
- tsKey: "data",
2949
- field: field.as("data"),
2950
- isJson: true,
2951
- relationTableTsKey: tableConfig.tsName,
2952
- selection
2953
- }];
2954
- const needsSubquery = limit !== undefined || offset !== undefined || orderBy.length > 0;
2955
- if (needsSubquery) {
2956
- result = this.buildSelectQuery({
2957
- table: aliasedTable(table2, tableAlias),
2958
- fields: {},
2959
- fieldsFlat: [
2960
- {
2961
- path: [],
2962
- field: sql.raw("*")
2963
- }
2964
- ],
2965
- where,
2966
- limit,
2967
- offset,
2968
- orderBy,
2969
- setOperators: []
2970
- });
2971
- where = undefined;
2972
- limit = undefined;
2973
- offset = undefined;
2974
- orderBy = undefined;
2975
- } else {
2976
- result = aliasedTable(table2, tableAlias);
2977
- }
2978
- result = this.buildSelectQuery({
2979
- table: is(result, SQLiteTable) ? result : new Subquery(result, {}, tableAlias),
2980
- fields: {},
2981
- fieldsFlat: nestedSelection.map(({ field: field2 }) => ({
2982
- path: [],
2983
- field: is(field2, Column) ? aliasedTableColumn(field2, tableAlias) : field2
2984
- })),
2985
- joins,
2986
- where,
2987
- limit,
2988
- offset,
2989
- orderBy,
2990
- setOperators: []
2991
- });
2992
- } else {
2993
- result = this.buildSelectQuery({
2994
- table: aliasedTable(table2, tableAlias),
2995
- fields: {},
2996
- fieldsFlat: selection.map(({ field }) => ({
2997
- path: [],
2998
- field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field
2999
- })),
3000
- joins,
3001
- where,
3002
- limit,
3003
- offset,
3004
- orderBy,
3005
- setOperators: []
3006
- });
3007
- }
3008
- return {
3009
- tableTsKey: tableConfig.tsName,
3010
- sql: result,
3011
- selection
3012
- };
3013
- }
3014
- };
3015
- SQLiteSyncDialect = class SQLiteSyncDialect extends SQLiteDialect {
3016
- static [entityKind] = "SQLiteSyncDialect";
3017
- migrate(migrations, session, config) {
3018
- const migrationsTable = config === undefined ? "__drizzle_migrations" : typeof config === "string" ? "__drizzle_migrations" : config.migrationsTable ?? "__drizzle_migrations";
3019
- const migrationTableCreate = sql`
3020
- CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsTable)} (
3021
- id SERIAL PRIMARY KEY,
3022
- hash text NOT NULL,
3023
- created_at numeric
3024
- )
3025
- `;
3026
- session.run(migrationTableCreate);
3027
- const dbMigrations = session.values(sql`SELECT id, hash, created_at FROM ${sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1`);
3028
- const lastDbMigration = dbMigrations[0] ?? undefined;
3029
- session.run(sql`BEGIN`);
3030
- try {
3031
- for (const migration of migrations) {
3032
- if (!lastDbMigration || Number(lastDbMigration[2]) < migration.folderMillis) {
3033
- for (const stmt of migration.sql) {
3034
- session.run(sql.raw(stmt));
3035
- }
3036
- session.run(sql`INSERT INTO ${sql.identifier(migrationsTable)} ("hash", "created_at") VALUES(${migration.hash}, ${migration.folderMillis})`);
3037
- }
3038
- }
3039
- session.run(sql`COMMIT`);
3040
- } catch (e) {
3041
- session.run(sql`ROLLBACK`);
3042
- throw e;
3043
- }
3044
- }
3045
- };
3046
- });
3047
-
3048
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/query-builders/query-builder.js
3049
- var TypedQueryBuilder;
3050
- var init_query_builder = __esm(() => {
3051
- init_entity();
3052
- TypedQueryBuilder = class TypedQueryBuilder {
3053
- static [entityKind] = "TypedQueryBuilder";
3054
- getSelectedFields() {
3055
- return this._.selectedFields;
3056
- }
3057
- };
3058
- });
3059
-
3060
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/query-builders/select.js
3061
- function createSetOperator(type, isAll) {
3062
- return (leftSelect, rightSelect, ...restSelects) => {
3063
- const setOperators = [rightSelect, ...restSelects].map((select2) => ({
3064
- type,
3065
- isAll,
3066
- rightSelect: select2
3067
- }));
3068
- for (const setOperator of setOperators) {
3069
- if (!haveSameKeys(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) {
3070
- throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");
3071
- }
3072
- }
3073
- return leftSelect.addSetOperators(setOperators);
3074
- };
3075
- }
3076
- var SQLiteSelectBuilder, SQLiteSelectQueryBuilderBase, SQLiteSelectBase, getSQLiteSetOperators = () => ({
3077
- union,
3078
- unionAll,
3079
- intersect,
3080
- except
3081
- }), union, unionAll, intersect, except;
3082
- var init_select2 = __esm(() => {
3083
- init_entity();
3084
- init_query_builder();
3085
- init_query_promise();
3086
- init_selection_proxy();
3087
- init_sql();
3088
- init_subquery();
3089
- init_table();
3090
- init_utils();
3091
- init_view_common();
3092
- init_utils2();
3093
- init_view_base();
3094
- SQLiteSelectBuilder = class SQLiteSelectBuilder {
3095
- static [entityKind] = "SQLiteSelectBuilder";
3096
- fields;
3097
- session;
3098
- dialect;
3099
- withList;
3100
- distinct;
3101
- constructor(config) {
3102
- this.fields = config.fields;
3103
- this.session = config.session;
3104
- this.dialect = config.dialect;
3105
- this.withList = config.withList;
3106
- this.distinct = config.distinct;
3107
- }
3108
- from(source) {
3109
- const isPartialSelect = !!this.fields;
3110
- let fields;
3111
- if (this.fields) {
3112
- fields = this.fields;
3113
- } else if (is(source, Subquery)) {
3114
- fields = Object.fromEntries(Object.keys(source._.selectedFields).map((key) => [key, source[key]]));
3115
- } else if (is(source, SQLiteViewBase)) {
3116
- fields = source[ViewBaseConfig].selectedFields;
3117
- } else if (is(source, SQL)) {
3118
- fields = {};
3119
- } else {
3120
- fields = getTableColumns(source);
3121
- }
3122
- return new SQLiteSelectBase({
3123
- table: source,
3124
- fields,
3125
- isPartialSelect,
3126
- session: this.session,
3127
- dialect: this.dialect,
3128
- withList: this.withList,
3129
- distinct: this.distinct
3130
- });
3131
- }
3132
- };
3133
- SQLiteSelectQueryBuilderBase = class SQLiteSelectQueryBuilderBase extends TypedQueryBuilder {
3134
- static [entityKind] = "SQLiteSelectQueryBuilder";
3135
- _;
3136
- config;
3137
- joinsNotNullableMap;
3138
- tableName;
3139
- isPartialSelect;
3140
- session;
3141
- dialect;
3142
- cacheConfig = undefined;
3143
- usedTables = /* @__PURE__ */ new Set;
3144
- constructor({ table: table2, fields, isPartialSelect, session, dialect, withList, distinct }) {
3145
- super();
3146
- this.config = {
3147
- withList,
3148
- table: table2,
3149
- fields: { ...fields },
3150
- distinct,
3151
- setOperators: []
3152
- };
3153
- this.isPartialSelect = isPartialSelect;
3154
- this.session = session;
3155
- this.dialect = dialect;
3156
- this._ = {
3157
- selectedFields: fields,
3158
- config: this.config
3159
- };
3160
- this.tableName = getTableLikeName(table2);
3161
- this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
3162
- for (const item of extractUsedTable(table2))
3163
- this.usedTables.add(item);
3164
- }
3165
- getUsedTables() {
3166
- return [...this.usedTables];
3167
- }
3168
- createJoin(joinType) {
3169
- return (table2, on) => {
3170
- const baseTableName = this.tableName;
3171
- const tableName = getTableLikeName(table2);
3172
- for (const item of extractUsedTable(table2))
3173
- this.usedTables.add(item);
3174
- if (typeof tableName === "string" && this.config.joins?.some((join2) => join2.alias === tableName)) {
3175
- throw new Error(`Alias "${tableName}" is already used in this query`);
3176
- }
3177
- if (!this.isPartialSelect) {
3178
- if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") {
3179
- this.config.fields = {
3180
- [baseTableName]: this.config.fields
3181
- };
3182
- }
3183
- if (typeof tableName === "string" && !is(table2, SQL)) {
3184
- const selection = is(table2, Subquery) ? table2._.selectedFields : is(table2, View) ? table2[ViewBaseConfig].selectedFields : table2[Table.Symbol.Columns];
3185
- this.config.fields[tableName] = selection;
3186
- }
3187
- }
3188
- if (typeof on === "function") {
3189
- on = on(new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })));
3190
- }
3191
- if (!this.config.joins) {
3192
- this.config.joins = [];
3193
- }
3194
- this.config.joins.push({ on, table: table2, joinType, alias: tableName });
3195
- if (typeof tableName === "string") {
3196
- switch (joinType) {
3197
- case "left": {
3198
- this.joinsNotNullableMap[tableName] = false;
3199
- break;
3200
- }
3201
- case "right": {
3202
- this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));
3203
- this.joinsNotNullableMap[tableName] = true;
3204
- break;
3205
- }
3206
- case "cross":
3207
- case "inner": {
3208
- this.joinsNotNullableMap[tableName] = true;
3209
- break;
3210
- }
3211
- case "full": {
3212
- this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));
3213
- this.joinsNotNullableMap[tableName] = false;
3214
- break;
3215
- }
3216
- }
3217
- }
3218
- return this;
3219
- };
3220
- }
3221
- leftJoin = this.createJoin("left");
3222
- rightJoin = this.createJoin("right");
3223
- innerJoin = this.createJoin("inner");
3224
- fullJoin = this.createJoin("full");
3225
- crossJoin = this.createJoin("cross");
3226
- createSetOperator(type, isAll) {
3227
- return (rightSelection) => {
3228
- const rightSelect = typeof rightSelection === "function" ? rightSelection(getSQLiteSetOperators()) : rightSelection;
3229
- if (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) {
3230
- throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");
3231
- }
3232
- this.config.setOperators.push({ type, isAll, rightSelect });
3233
- return this;
3234
- };
3235
- }
3236
- union = this.createSetOperator("union", false);
3237
- unionAll = this.createSetOperator("union", true);
3238
- intersect = this.createSetOperator("intersect", false);
3239
- except = this.createSetOperator("except", false);
3240
- addSetOperators(setOperators) {
3241
- this.config.setOperators.push(...setOperators);
3242
- return this;
3243
- }
3244
- where(where) {
3245
- if (typeof where === "function") {
3246
- where = where(new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })));
3247
- }
3248
- this.config.where = where;
3249
- return this;
3250
- }
3251
- having(having) {
3252
- if (typeof having === "function") {
3253
- having = having(new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })));
3254
- }
3255
- this.config.having = having;
3256
- return this;
3257
- }
3258
- groupBy(...columns) {
3259
- if (typeof columns[0] === "function") {
3260
- const groupBy = columns[0](new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })));
3261
- this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];
3262
- } else {
3263
- this.config.groupBy = columns;
3264
- }
3265
- return this;
3266
- }
3267
- orderBy(...columns) {
3268
- if (typeof columns[0] === "function") {
3269
- const orderBy = columns[0](new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })));
3270
- const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
3271
- if (this.config.setOperators.length > 0) {
3272
- this.config.setOperators.at(-1).orderBy = orderByArray;
3273
- } else {
3274
- this.config.orderBy = orderByArray;
3275
- }
3276
- } else {
3277
- const orderByArray = columns;
3278
- if (this.config.setOperators.length > 0) {
3279
- this.config.setOperators.at(-1).orderBy = orderByArray;
3280
- } else {
3281
- this.config.orderBy = orderByArray;
3282
- }
3283
- }
3284
- return this;
3285
- }
3286
- limit(limit) {
3287
- if (this.config.setOperators.length > 0) {
3288
- this.config.setOperators.at(-1).limit = limit;
3289
- } else {
3290
- this.config.limit = limit;
3291
- }
3292
- return this;
3293
- }
3294
- offset(offset) {
3295
- if (this.config.setOperators.length > 0) {
3296
- this.config.setOperators.at(-1).offset = offset;
3297
- } else {
3298
- this.config.offset = offset;
3299
- }
3300
- return this;
3301
- }
3302
- getSQL() {
3303
- return this.dialect.buildSelectQuery(this.config);
3304
- }
3305
- toSQL() {
3306
- const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
3307
- return rest;
3308
- }
3309
- as(alias3) {
3310
- const usedTables = [];
3311
- usedTables.push(...extractUsedTable(this.config.table));
3312
- if (this.config.joins) {
3313
- for (const it of this.config.joins)
3314
- usedTables.push(...extractUsedTable(it.table));
3315
- }
3316
- return new Proxy(new Subquery(this.getSQL(), this.config.fields, alias3, false, [...new Set(usedTables)]), new SelectionProxyHandler({ alias: alias3, sqlAliasedBehavior: "alias", sqlBehavior: "error" }));
3317
- }
3318
- getSelectedFields() {
3319
- return new Proxy(this.config.fields, new SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" }));
3320
- }
3321
- $dynamic() {
3322
- return this;
3323
- }
3324
- };
3325
- SQLiteSelectBase = class SQLiteSelectBase extends SQLiteSelectQueryBuilderBase {
3326
- static [entityKind] = "SQLiteSelect";
3327
- _prepare(isOneTimeQuery = true) {
3328
- if (!this.session) {
3329
- throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");
3330
- }
3331
- const fieldsList = orderSelectedFields(this.config.fields);
3332
- const query = this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](this.dialect.sqlToQuery(this.getSQL()), fieldsList, "all", true, undefined, {
3333
- type: "select",
3334
- tables: [...this.usedTables]
3335
- }, this.cacheConfig);
3336
- query.joinsNotNullableMap = this.joinsNotNullableMap;
3337
- return query;
3338
- }
3339
- $withCache(config) {
3340
- this.cacheConfig = config === undefined ? { config: {}, enable: true, autoInvalidate: true } : config === false ? { enable: false } : { enable: true, autoInvalidate: true, ...config };
3341
- return this;
3342
- }
3343
- prepare() {
3344
- return this._prepare(false);
3345
- }
3346
- run = (placeholderValues) => {
3347
- return this._prepare().run(placeholderValues);
3348
- };
3349
- all = (placeholderValues) => {
3350
- return this._prepare().all(placeholderValues);
3351
- };
3352
- get = (placeholderValues) => {
3353
- return this._prepare().get(placeholderValues);
3354
- };
3355
- values = (placeholderValues) => {
3356
- return this._prepare().values(placeholderValues);
3357
- };
3358
- async execute() {
3359
- return this.all();
3360
- }
3361
- };
3362
- applyMixins(SQLiteSelectBase, [QueryPromise]);
3363
- union = createSetOperator("union", false);
3364
- unionAll = createSetOperator("union", true);
3365
- intersect = createSetOperator("intersect", false);
3366
- except = createSetOperator("except", false);
3367
- });
3368
-
3369
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/query-builders/query-builder.js
3370
- var QueryBuilder;
3371
- var init_query_builder2 = __esm(() => {
3372
- init_entity();
3373
- init_selection_proxy();
3374
- init_dialect();
3375
- init_subquery();
3376
- init_select2();
3377
- QueryBuilder = class QueryBuilder {
3378
- static [entityKind] = "SQLiteQueryBuilder";
3379
- dialect;
3380
- dialectConfig;
3381
- constructor(dialect) {
3382
- this.dialect = is(dialect, SQLiteDialect) ? dialect : undefined;
3383
- this.dialectConfig = is(dialect, SQLiteDialect) ? undefined : dialect;
3384
- }
3385
- $with = (alias3, selection) => {
3386
- const queryBuilder = this;
3387
- const as = (qb) => {
3388
- if (typeof qb === "function") {
3389
- qb = qb(queryBuilder);
3390
- }
3391
- return new Proxy(new WithSubquery(qb.getSQL(), selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}), alias3, true), new SelectionProxyHandler({ alias: alias3, sqlAliasedBehavior: "alias", sqlBehavior: "error" }));
3392
- };
3393
- return { as };
3394
- };
3395
- with(...queries) {
3396
- const self = this;
3397
- function select2(fields) {
3398
- return new SQLiteSelectBuilder({
3399
- fields: fields ?? undefined,
3400
- session: undefined,
3401
- dialect: self.getDialect(),
3402
- withList: queries
3403
- });
3404
- }
3405
- function selectDistinct(fields) {
3406
- return new SQLiteSelectBuilder({
3407
- fields: fields ?? undefined,
3408
- session: undefined,
3409
- dialect: self.getDialect(),
3410
- withList: queries,
3411
- distinct: true
3412
- });
3413
- }
3414
- return { select: select2, selectDistinct };
3415
- }
3416
- select(fields) {
3417
- return new SQLiteSelectBuilder({ fields: fields ?? undefined, session: undefined, dialect: this.getDialect() });
3418
- }
3419
- selectDistinct(fields) {
3420
- return new SQLiteSelectBuilder({
3421
- fields: fields ?? undefined,
3422
- session: undefined,
3423
- dialect: this.getDialect(),
3424
- distinct: true
3425
- });
3426
- }
3427
- getDialect() {
3428
- if (!this.dialect) {
3429
- this.dialect = new SQLiteSyncDialect(this.dialectConfig);
3430
- }
3431
- return this.dialect;
3432
- }
3433
- };
3434
- });
3435
-
3436
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/query-builders/insert.js
3437
- var SQLiteInsertBuilder, SQLiteInsertBase;
3438
- var init_insert = __esm(() => {
3439
- init_entity();
3440
- init_query_promise();
3441
- init_sql();
3442
- init_table3();
3443
- init_table();
3444
- init_utils();
3445
- init_utils2();
3446
- init_query_builder2();
3447
- SQLiteInsertBuilder = class SQLiteInsertBuilder {
3448
- constructor(table2, session, dialect, withList) {
3449
- this.table = table2;
3450
- this.session = session;
3451
- this.dialect = dialect;
3452
- this.withList = withList;
3453
- }
3454
- static [entityKind] = "SQLiteInsertBuilder";
3455
- values(values) {
3456
- values = Array.isArray(values) ? values : [values];
3457
- if (values.length === 0) {
3458
- throw new Error("values() must be called with at least one value");
3459
- }
3460
- const mappedValues = values.map((entry) => {
3461
- const result = {};
3462
- const cols = this.table[Table.Symbol.Columns];
3463
- for (const colKey of Object.keys(entry)) {
3464
- const colValue = entry[colKey];
3465
- result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
3466
- }
3467
- return result;
3468
- });
3469
- return new SQLiteInsertBase(this.table, mappedValues, this.session, this.dialect, this.withList);
3470
- }
3471
- select(selectQuery) {
3472
- const select2 = typeof selectQuery === "function" ? selectQuery(new QueryBuilder) : selectQuery;
3473
- if (!is(select2, SQL) && !haveSameKeys(this.table[Columns], select2._.selectedFields)) {
3474
- throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");
3475
- }
3476
- return new SQLiteInsertBase(this.table, select2, this.session, this.dialect, this.withList, true);
3477
- }
3478
- };
3479
- SQLiteInsertBase = class SQLiteInsertBase extends QueryPromise {
3480
- constructor(table2, values, session, dialect, withList, select2) {
3481
- super();
3482
- this.session = session;
3483
- this.dialect = dialect;
3484
- this.config = { table: table2, values, withList, select: select2 };
3485
- }
3486
- static [entityKind] = "SQLiteInsert";
3487
- config;
3488
- returning(fields = this.config.table[SQLiteTable.Symbol.Columns]) {
3489
- this.config.returning = orderSelectedFields(fields);
3490
- return this;
3491
- }
3492
- onConflictDoNothing(config = {}) {
3493
- if (!this.config.onConflict)
3494
- this.config.onConflict = [];
3495
- if (config.target === undefined) {
3496
- this.config.onConflict.push(sql` on conflict do nothing`);
3497
- } else {
3498
- const targetSql = Array.isArray(config.target) ? sql`${config.target}` : sql`${[config.target]}`;
3499
- const whereSql = config.where ? sql` where ${config.where}` : sql``;
3500
- this.config.onConflict.push(sql` on conflict ${targetSql} do nothing${whereSql}`);
3501
- }
3502
- return this;
3503
- }
3504
- onConflictDoUpdate(config) {
3505
- if (config.where && (config.targetWhere || config.setWhere)) {
3506
- throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');
3507
- }
3508
- if (!this.config.onConflict)
3509
- this.config.onConflict = [];
3510
- const whereSql = config.where ? sql` where ${config.where}` : undefined;
3511
- const targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : undefined;
3512
- const setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : undefined;
3513
- const targetSql = Array.isArray(config.target) ? sql`${config.target}` : sql`${[config.target]}`;
3514
- const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
3515
- this.config.onConflict.push(sql` on conflict ${targetSql}${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`);
3516
- return this;
3517
- }
3518
- getSQL() {
3519
- return this.dialect.buildInsertQuery(this.config);
3520
- }
3521
- toSQL() {
3522
- const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
3523
- return rest;
3524
- }
3525
- _prepare(isOneTimeQuery = true) {
3526
- return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](this.dialect.sqlToQuery(this.getSQL()), this.config.returning, this.config.returning ? "all" : "run", true, undefined, {
3527
- type: "insert",
3528
- tables: extractUsedTable(this.config.table)
3529
- });
3530
- }
3531
- prepare() {
3532
- return this._prepare(false);
3533
- }
3534
- run = (placeholderValues) => {
3535
- return this._prepare().run(placeholderValues);
3536
- };
3537
- all = (placeholderValues) => {
3538
- return this._prepare().all(placeholderValues);
3539
- };
3540
- get = (placeholderValues) => {
3541
- return this._prepare().get(placeholderValues);
3542
- };
3543
- values = (placeholderValues) => {
3544
- return this._prepare().values(placeholderValues);
3545
- };
3546
- async execute() {
3547
- return this.config.returning ? this.all() : this.run();
3548
- }
3549
- $dynamic() {
3550
- return this;
3551
- }
3552
- };
3553
- });
3554
-
3555
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/query-builders/update.js
3556
- var SQLiteUpdateBuilder, SQLiteUpdateBase;
3557
- var init_update = __esm(() => {
3558
- init_entity();
3559
- init_query_promise();
3560
- init_selection_proxy();
3561
- init_table3();
3562
- init_subquery();
3563
- init_table();
3564
- init_utils();
3565
- init_view_common();
3566
- init_utils2();
3567
- init_view_base();
3568
- SQLiteUpdateBuilder = class SQLiteUpdateBuilder {
3569
- constructor(table2, session, dialect, withList) {
3570
- this.table = table2;
3571
- this.session = session;
3572
- this.dialect = dialect;
3573
- this.withList = withList;
3574
- }
3575
- static [entityKind] = "SQLiteUpdateBuilder";
3576
- set(values) {
3577
- return new SQLiteUpdateBase(this.table, mapUpdateSet(this.table, values), this.session, this.dialect, this.withList);
3578
- }
3579
- };
3580
- SQLiteUpdateBase = class SQLiteUpdateBase extends QueryPromise {
3581
- constructor(table2, set, session, dialect, withList) {
3582
- super();
3583
- this.session = session;
3584
- this.dialect = dialect;
3585
- this.config = { set, table: table2, withList, joins: [] };
3586
- }
3587
- static [entityKind] = "SQLiteUpdate";
3588
- config;
3589
- from(source) {
3590
- this.config.from = source;
3591
- return this;
3592
- }
3593
- createJoin(joinType) {
3594
- return (table2, on) => {
3595
- const tableName = getTableLikeName(table2);
3596
- if (typeof tableName === "string" && this.config.joins.some((join2) => join2.alias === tableName)) {
3597
- throw new Error(`Alias "${tableName}" is already used in this query`);
3598
- }
3599
- if (typeof on === "function") {
3600
- const from = this.config.from ? is(table2, SQLiteTable) ? table2[Table.Symbol.Columns] : is(table2, Subquery) ? table2._.selectedFields : is(table2, SQLiteViewBase) ? table2[ViewBaseConfig].selectedFields : undefined : undefined;
3601
- on = on(new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })), from && new Proxy(from, new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })));
3602
- }
3603
- this.config.joins.push({ on, table: table2, joinType, alias: tableName });
3604
- return this;
3605
- };
3606
- }
3607
- leftJoin = this.createJoin("left");
3608
- rightJoin = this.createJoin("right");
3609
- innerJoin = this.createJoin("inner");
3610
- fullJoin = this.createJoin("full");
3611
- where(where) {
3612
- this.config.where = where;
3613
- return this;
3614
- }
3615
- orderBy(...columns) {
3616
- if (typeof columns[0] === "function") {
3617
- const orderBy = columns[0](new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })));
3618
- const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
3619
- this.config.orderBy = orderByArray;
3620
- } else {
3621
- const orderByArray = columns;
3622
- this.config.orderBy = orderByArray;
3623
- }
3624
- return this;
3625
- }
3626
- limit(limit) {
3627
- this.config.limit = limit;
3628
- return this;
3629
- }
3630
- returning(fields = this.config.table[SQLiteTable.Symbol.Columns]) {
3631
- this.config.returning = orderSelectedFields(fields);
3632
- return this;
3633
- }
3634
- getSQL() {
3635
- return this.dialect.buildUpdateQuery(this.config);
3636
- }
3637
- toSQL() {
3638
- const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
3639
- return rest;
3640
- }
3641
- _prepare(isOneTimeQuery = true) {
3642
- return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](this.dialect.sqlToQuery(this.getSQL()), this.config.returning, this.config.returning ? "all" : "run", true, undefined, {
3643
- type: "insert",
3644
- tables: extractUsedTable(this.config.table)
3645
- });
3646
- }
3647
- prepare() {
3648
- return this._prepare(false);
3649
- }
3650
- run = (placeholderValues) => {
3651
- return this._prepare().run(placeholderValues);
3652
- };
3653
- all = (placeholderValues) => {
3654
- return this._prepare().all(placeholderValues);
3655
- };
3656
- get = (placeholderValues) => {
3657
- return this._prepare().get(placeholderValues);
3658
- };
3659
- values = (placeholderValues) => {
3660
- return this._prepare().values(placeholderValues);
3661
- };
3662
- async execute() {
3663
- return this.config.returning ? this.all() : this.run();
3664
- }
3665
- $dynamic() {
3666
- return this;
3667
- }
3668
- };
3669
- });
3670
-
3671
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/query-builders/index.js
3672
- var init_query_builders = __esm(() => {
3673
- init_delete();
3674
- init_insert();
3675
- init_query_builder2();
3676
- init_select2();
3677
- init_update();
3678
- });
3679
-
3680
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/query-builders/count.js
3681
- var SQLiteCountBuilder;
3682
- var init_count = __esm(() => {
3683
- init_entity();
3684
- init_sql();
3685
- SQLiteCountBuilder = class SQLiteCountBuilder extends SQL {
3686
- constructor(params) {
3687
- super(SQLiteCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
3688
- this.params = params;
3689
- this.session = params.session;
3690
- this.sql = SQLiteCountBuilder.buildCount(params.source, params.filters);
3691
- }
3692
- sql;
3693
- static [entityKind] = "SQLiteCountBuilderAsync";
3694
- [Symbol.toStringTag] = "SQLiteCountBuilderAsync";
3695
- session;
3696
- static buildEmbeddedCount(source, filters) {
3697
- return sql`(select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters})`;
3698
- }
3699
- static buildCount(source, filters) {
3700
- return sql`select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters}`;
3701
- }
3702
- then(onfulfilled, onrejected) {
3703
- return Promise.resolve(this.session.count(this.sql)).then(onfulfilled, onrejected);
3704
- }
3705
- catch(onRejected) {
3706
- return this.then(undefined, onRejected);
3707
- }
3708
- finally(onFinally) {
3709
- return this.then((value) => {
3710
- onFinally?.();
3711
- return value;
3712
- }, (reason) => {
3713
- onFinally?.();
3714
- throw reason;
3715
- });
3716
- }
3717
- };
3718
- });
3719
-
3720
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/query-builders/query.js
3721
- var RelationalQueryBuilder, SQLiteRelationalQuery, SQLiteSyncRelationalQuery;
3722
- var init_query = __esm(() => {
3723
- init_entity();
3724
- init_query_promise();
3725
- init_relations();
3726
- RelationalQueryBuilder = class RelationalQueryBuilder {
3727
- constructor(mode, fullSchema, schema, tableNamesMap, table2, tableConfig, dialect, session) {
3728
- this.mode = mode;
3729
- this.fullSchema = fullSchema;
3730
- this.schema = schema;
3731
- this.tableNamesMap = tableNamesMap;
3732
- this.table = table2;
3733
- this.tableConfig = tableConfig;
3734
- this.dialect = dialect;
3735
- this.session = session;
3736
- }
3737
- static [entityKind] = "SQLiteAsyncRelationalQueryBuilder";
3738
- findMany(config) {
3739
- return this.mode === "sync" ? new SQLiteSyncRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? config : {}, "many") : new SQLiteRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? config : {}, "many");
3740
- }
3741
- findFirst(config) {
3742
- return this.mode === "sync" ? new SQLiteSyncRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? { ...config, limit: 1 } : { limit: 1 }, "first") : new SQLiteRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? { ...config, limit: 1 } : { limit: 1 }, "first");
3743
- }
3744
- };
3745
- SQLiteRelationalQuery = class SQLiteRelationalQuery extends QueryPromise {
3746
- constructor(fullSchema, schema, tableNamesMap, table2, tableConfig, dialect, session, config, mode) {
3747
- super();
3748
- this.fullSchema = fullSchema;
3749
- this.schema = schema;
3750
- this.tableNamesMap = tableNamesMap;
3751
- this.table = table2;
3752
- this.tableConfig = tableConfig;
3753
- this.dialect = dialect;
3754
- this.session = session;
3755
- this.config = config;
3756
- this.mode = mode;
3757
- }
3758
- static [entityKind] = "SQLiteAsyncRelationalQuery";
3759
- mode;
3760
- getSQL() {
3761
- return this.dialect.buildRelationalQuery({
3762
- fullSchema: this.fullSchema,
3763
- schema: this.schema,
3764
- tableNamesMap: this.tableNamesMap,
3765
- table: this.table,
3766
- tableConfig: this.tableConfig,
3767
- queryConfig: this.config,
3768
- tableAlias: this.tableConfig.tsName
3769
- }).sql;
3770
- }
3771
- _prepare(isOneTimeQuery = false) {
3772
- const { query, builtQuery } = this._toSQL();
3773
- return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](builtQuery, undefined, this.mode === "first" ? "get" : "all", true, (rawRows, mapColumnValue) => {
3774
- const rows = rawRows.map((row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue));
3775
- if (this.mode === "first") {
3776
- return rows[0];
3777
- }
3778
- return rows;
3779
- });
3780
- }
3781
- prepare() {
3782
- return this._prepare(false);
3783
- }
3784
- _toSQL() {
3785
- const query = this.dialect.buildRelationalQuery({
3786
- fullSchema: this.fullSchema,
3787
- schema: this.schema,
3788
- tableNamesMap: this.tableNamesMap,
3789
- table: this.table,
3790
- tableConfig: this.tableConfig,
3791
- queryConfig: this.config,
3792
- tableAlias: this.tableConfig.tsName
3793
- });
3794
- const builtQuery = this.dialect.sqlToQuery(query.sql);
3795
- return { query, builtQuery };
3796
- }
3797
- toSQL() {
3798
- return this._toSQL().builtQuery;
3799
- }
3800
- executeRaw() {
3801
- if (this.mode === "first") {
3802
- return this._prepare(false).get();
3803
- }
3804
- return this._prepare(false).all();
3805
- }
3806
- async execute() {
3807
- return this.executeRaw();
3808
- }
3809
- };
3810
- SQLiteSyncRelationalQuery = class SQLiteSyncRelationalQuery extends SQLiteRelationalQuery {
3811
- static [entityKind] = "SQLiteSyncRelationalQuery";
3812
- sync() {
3813
- return this.executeRaw();
3814
- }
3815
- };
3816
- });
3817
-
3818
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/query-builders/raw.js
3819
- var SQLiteRaw;
3820
- var init_raw = __esm(() => {
3821
- init_entity();
3822
- init_query_promise();
3823
- SQLiteRaw = class SQLiteRaw extends QueryPromise {
3824
- constructor(execute, getSQL, action, dialect, mapBatchResult) {
3825
- super();
3826
- this.execute = execute;
3827
- this.getSQL = getSQL;
3828
- this.dialect = dialect;
3829
- this.mapBatchResult = mapBatchResult;
3830
- this.config = { action };
3831
- }
3832
- static [entityKind] = "SQLiteRaw";
3833
- config;
3834
- getQuery() {
3835
- return { ...this.dialect.sqlToQuery(this.getSQL()), method: this.config.action };
3836
- }
3837
- mapResult(result, isFromBatch) {
3838
- return isFromBatch ? this.mapBatchResult(result) : result;
3839
- }
3840
- _prepare() {
3841
- return this;
3842
- }
3843
- isResponseInArrayMode() {
3844
- return false;
3845
- }
3846
- };
3847
- });
3848
-
3849
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/db.js
3850
- var BaseSQLiteDatabase;
3851
- var init_db = __esm(() => {
3852
- init_entity();
3853
- init_selection_proxy();
3854
- init_sql();
3855
- init_query_builders();
3856
- init_subquery();
3857
- init_count();
3858
- init_query();
3859
- init_raw();
3860
- BaseSQLiteDatabase = class BaseSQLiteDatabase {
3861
- constructor(resultKind, dialect, session, schema) {
3862
- this.resultKind = resultKind;
3863
- this.dialect = dialect;
3864
- this.session = session;
3865
- this._ = schema ? {
3866
- schema: schema.schema,
3867
- fullSchema: schema.fullSchema,
3868
- tableNamesMap: schema.tableNamesMap
3869
- } : {
3870
- schema: undefined,
3871
- fullSchema: {},
3872
- tableNamesMap: {}
3873
- };
3874
- this.query = {};
3875
- const query = this.query;
3876
- if (this._.schema) {
3877
- for (const [tableName, columns] of Object.entries(this._.schema)) {
3878
- query[tableName] = new RelationalQueryBuilder(resultKind, schema.fullSchema, this._.schema, this._.tableNamesMap, schema.fullSchema[tableName], columns, dialect, session);
3879
- }
3880
- }
3881
- this.$cache = { invalidate: async (_params) => {} };
3882
- }
3883
- static [entityKind] = "BaseSQLiteDatabase";
3884
- query;
3885
- $with = (alias3, selection) => {
3886
- const self = this;
3887
- const as = (qb) => {
3888
- if (typeof qb === "function") {
3889
- qb = qb(new QueryBuilder(self.dialect));
3890
- }
3891
- return new Proxy(new WithSubquery(qb.getSQL(), selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}), alias3, true), new SelectionProxyHandler({ alias: alias3, sqlAliasedBehavior: "alias", sqlBehavior: "error" }));
3892
- };
3893
- return { as };
3894
- };
3895
- $count(source, filters) {
3896
- return new SQLiteCountBuilder({ source, filters, session: this.session });
3897
- }
3898
- with(...queries) {
3899
- const self = this;
3900
- function select3(fields) {
3901
- return new SQLiteSelectBuilder({
3902
- fields: fields ?? undefined,
3903
- session: self.session,
3904
- dialect: self.dialect,
3905
- withList: queries
3906
- });
3907
- }
3908
- function selectDistinct(fields) {
3909
- return new SQLiteSelectBuilder({
3910
- fields: fields ?? undefined,
3911
- session: self.session,
3912
- dialect: self.dialect,
3913
- withList: queries,
3914
- distinct: true
3915
- });
3916
- }
3917
- function update2(table2) {
3918
- return new SQLiteUpdateBuilder(table2, self.session, self.dialect, queries);
3919
- }
3920
- function insert2(into) {
3921
- return new SQLiteInsertBuilder(into, self.session, self.dialect, queries);
3922
- }
3923
- function delete_(from) {
3924
- return new SQLiteDeleteBase(from, self.session, self.dialect, queries);
3925
- }
3926
- return { select: select3, selectDistinct, update: update2, insert: insert2, delete: delete_ };
3927
- }
3928
- select(fields) {
3929
- return new SQLiteSelectBuilder({ fields: fields ?? undefined, session: this.session, dialect: this.dialect });
3930
- }
3931
- selectDistinct(fields) {
3932
- return new SQLiteSelectBuilder({
3933
- fields: fields ?? undefined,
3934
- session: this.session,
3935
- dialect: this.dialect,
3936
- distinct: true
3937
- });
3938
- }
3939
- update(table2) {
3940
- return new SQLiteUpdateBuilder(table2, this.session, this.dialect);
3941
- }
3942
- $cache;
3943
- insert(into) {
3944
- return new SQLiteInsertBuilder(into, this.session, this.dialect);
3945
- }
3946
- delete(from) {
3947
- return new SQLiteDeleteBase(from, this.session, this.dialect);
3948
- }
3949
- run(query) {
3950
- const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
3951
- if (this.resultKind === "async") {
3952
- return new SQLiteRaw(async () => this.session.run(sequel), () => sequel, "run", this.dialect, this.session.extractRawRunValueFromBatchResult.bind(this.session));
3953
- }
3954
- return this.session.run(sequel);
3955
- }
3956
- all(query) {
3957
- const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
3958
- if (this.resultKind === "async") {
3959
- return new SQLiteRaw(async () => this.session.all(sequel), () => sequel, "all", this.dialect, this.session.extractRawAllValueFromBatchResult.bind(this.session));
3960
- }
3961
- return this.session.all(sequel);
3962
- }
3963
- get(query) {
3964
- const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
3965
- if (this.resultKind === "async") {
3966
- return new SQLiteRaw(async () => this.session.get(sequel), () => sequel, "get", this.dialect, this.session.extractRawGetValueFromBatchResult.bind(this.session));
3967
- }
3968
- return this.session.get(sequel);
3969
- }
3970
- values(query) {
3971
- const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
3972
- if (this.resultKind === "async") {
3973
- return new SQLiteRaw(async () => this.session.values(sequel), () => sequel, "values", this.dialect, this.session.extractRawValuesValueFromBatchResult.bind(this.session));
3974
- }
3975
- return this.session.values(sequel);
3976
- }
3977
- transaction(transaction, config) {
3978
- return this.session.transaction(transaction, config);
3979
- }
3980
- };
3981
- });
3982
-
3983
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/alias.js
3984
- var init_alias2 = () => {};
3985
-
3986
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/cache/core/cache.js
3987
- async function hashQuery(sql4, params) {
3988
- const dataToHash = `${sql4}-${JSON.stringify(params)}`;
3989
- const encoder = new TextEncoder;
3990
- const data = encoder.encode(dataToHash);
3991
- const hashBuffer = await crypto.subtle.digest("SHA-256", data);
3992
- const hashArray = [...new Uint8Array(hashBuffer)];
3993
- const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
3994
- return hashHex;
3995
- }
3996
- var Cache, NoopCache;
3997
- var init_cache = __esm(() => {
3998
- init_entity();
3999
- Cache = class Cache {
4000
- static [entityKind] = "Cache";
4001
- };
4002
- NoopCache = class NoopCache extends Cache {
4003
- strategy() {
4004
- return "all";
4005
- }
4006
- static [entityKind] = "NoopCache";
4007
- async get(_key) {
4008
- return;
4009
- }
4010
- async put(_hashedQuery, _response, _tables, _config) {}
4011
- async onMutate(_params) {}
4012
- };
4013
- });
4014
-
4015
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/session.js
4016
- var ExecuteResultSync, SQLitePreparedQuery, SQLiteSession, SQLiteTransaction;
4017
- var init_session = __esm(() => {
4018
- init_cache();
4019
- init_entity();
4020
- init_errors();
4021
- init_query_promise();
4022
- init_db();
4023
- ExecuteResultSync = class ExecuteResultSync extends QueryPromise {
4024
- constructor(resultCb) {
4025
- super();
4026
- this.resultCb = resultCb;
4027
- }
4028
- static [entityKind] = "ExecuteResultSync";
4029
- async execute() {
4030
- return this.resultCb();
4031
- }
4032
- sync() {
4033
- return this.resultCb();
4034
- }
4035
- };
4036
- SQLitePreparedQuery = class SQLitePreparedQuery {
4037
- constructor(mode, executeMethod, query, cache, queryMetadata, cacheConfig) {
4038
- this.mode = mode;
4039
- this.executeMethod = executeMethod;
4040
- this.query = query;
4041
- this.cache = cache;
4042
- this.queryMetadata = queryMetadata;
4043
- this.cacheConfig = cacheConfig;
4044
- if (cache && cache.strategy() === "all" && cacheConfig === undefined) {
4045
- this.cacheConfig = { enable: true, autoInvalidate: true };
4046
- }
4047
- if (!this.cacheConfig?.enable) {
4048
- this.cacheConfig = undefined;
4049
- }
4050
- }
4051
- static [entityKind] = "PreparedQuery";
4052
- joinsNotNullableMap;
4053
- async queryWithCache(queryString, params, query) {
4054
- if (this.cache === undefined || is(this.cache, NoopCache) || this.queryMetadata === undefined) {
4055
- try {
4056
- return await query();
4057
- } catch (e) {
4058
- throw new DrizzleQueryError(queryString, params, e);
4059
- }
4060
- }
4061
- if (this.cacheConfig && !this.cacheConfig.enable) {
4062
- try {
4063
- return await query();
4064
- } catch (e) {
4065
- throw new DrizzleQueryError(queryString, params, e);
4066
- }
4067
- }
4068
- if ((this.queryMetadata.type === "insert" || this.queryMetadata.type === "update" || this.queryMetadata.type === "delete") && this.queryMetadata.tables.length > 0) {
4069
- try {
4070
- const [res] = await Promise.all([
4071
- query(),
4072
- this.cache.onMutate({ tables: this.queryMetadata.tables })
4073
- ]);
4074
- return res;
4075
- } catch (e) {
4076
- throw new DrizzleQueryError(queryString, params, e);
4077
- }
4078
- }
4079
- if (!this.cacheConfig) {
4080
- try {
4081
- return await query();
4082
- } catch (e) {
4083
- throw new DrizzleQueryError(queryString, params, e);
4084
- }
4085
- }
4086
- if (this.queryMetadata.type === "select") {
4087
- const fromCache = await this.cache.get(this.cacheConfig.tag ?? await hashQuery(queryString, params), this.queryMetadata.tables, this.cacheConfig.tag !== undefined, this.cacheConfig.autoInvalidate);
4088
- if (fromCache === undefined) {
4089
- let result;
4090
- try {
4091
- result = await query();
4092
- } catch (e) {
4093
- throw new DrizzleQueryError(queryString, params, e);
4094
- }
4095
- await this.cache.put(this.cacheConfig.tag ?? await hashQuery(queryString, params), result, this.cacheConfig.autoInvalidate ? this.queryMetadata.tables : [], this.cacheConfig.tag !== undefined, this.cacheConfig.config);
4096
- return result;
4097
- }
4098
- return fromCache;
4099
- }
4100
- try {
4101
- return await query();
4102
- } catch (e) {
4103
- throw new DrizzleQueryError(queryString, params, e);
4104
- }
4105
- }
4106
- getQuery() {
4107
- return this.query;
4108
- }
4109
- mapRunResult(result, _isFromBatch) {
4110
- return result;
4111
- }
4112
- mapAllResult(_result, _isFromBatch) {
4113
- throw new Error("Not implemented");
4114
- }
4115
- mapGetResult(_result, _isFromBatch) {
4116
- throw new Error("Not implemented");
4117
- }
4118
- execute(placeholderValues) {
4119
- if (this.mode === "async") {
4120
- return this[this.executeMethod](placeholderValues);
4121
- }
4122
- return new ExecuteResultSync(() => this[this.executeMethod](placeholderValues));
4123
- }
4124
- mapResult(response, isFromBatch) {
4125
- switch (this.executeMethod) {
4126
- case "run": {
4127
- return this.mapRunResult(response, isFromBatch);
4128
- }
4129
- case "all": {
4130
- return this.mapAllResult(response, isFromBatch);
4131
- }
4132
- case "get": {
4133
- return this.mapGetResult(response, isFromBatch);
4134
- }
4135
- }
4136
- }
4137
- };
4138
- SQLiteSession = class SQLiteSession {
4139
- constructor(dialect) {
4140
- this.dialect = dialect;
4141
- }
4142
- static [entityKind] = "SQLiteSession";
4143
- prepareOneTimeQuery(query, fields, executeMethod, isResponseInArrayMode, customResultMapper, queryMetadata, cacheConfig) {
4144
- return this.prepareQuery(query, fields, executeMethod, isResponseInArrayMode, customResultMapper, queryMetadata, cacheConfig);
4145
- }
4146
- run(query) {
4147
- const staticQuery = this.dialect.sqlToQuery(query);
4148
- try {
4149
- return this.prepareOneTimeQuery(staticQuery, undefined, "run", false).run();
4150
- } catch (err) {
4151
- throw new DrizzleError({ cause: err, message: `Failed to run the query '${staticQuery.sql}'` });
4152
- }
4153
- }
4154
- extractRawRunValueFromBatchResult(result) {
4155
- return result;
4156
- }
4157
- all(query) {
4158
- return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), undefined, "run", false).all();
4159
- }
4160
- extractRawAllValueFromBatchResult(_result) {
4161
- throw new Error("Not implemented");
4162
- }
4163
- get(query) {
4164
- return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), undefined, "run", false).get();
4165
- }
4166
- extractRawGetValueFromBatchResult(_result) {
4167
- throw new Error("Not implemented");
4168
- }
4169
- values(query) {
4170
- return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), undefined, "run", false).values();
4171
- }
4172
- async count(sql4) {
4173
- const result = await this.values(sql4);
4174
- return result[0][0];
4175
- }
4176
- extractRawValuesValueFromBatchResult(_result) {
4177
- throw new Error("Not implemented");
4178
- }
4179
- };
4180
- SQLiteTransaction = class SQLiteTransaction extends BaseSQLiteDatabase {
4181
- constructor(resultType, dialect, session, schema, nestedIndex = 0) {
4182
- super(resultType, dialect, session, schema);
4183
- this.schema = schema;
4184
- this.nestedIndex = nestedIndex;
4185
- }
4186
- static [entityKind] = "SQLiteTransaction";
4187
- rollback() {
4188
- throw new TransactionRollbackError;
4189
- }
4190
- };
4191
- });
4192
-
4193
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/view.js
4194
- var init_view = () => {};
4195
-
4196
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/sqlite-core/index.js
4197
- var init_sqlite_core = __esm(() => {
4198
- init_alias2();
4199
- init_checks();
4200
- init_columns();
4201
- init_db();
4202
- init_dialect();
4203
- init_foreign_keys();
4204
- init_indexes();
4205
- init_primary_keys2();
4206
- init_query_builders();
4207
- init_session();
4208
- init_table3();
4209
- init_unique_constraint2();
4210
- init_utils2();
4211
- init_view();
4212
- });
4213
-
4214
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/bun-sqlite/session.js
4215
- var SQLiteBunSession, SQLiteBunTransaction, PreparedQuery;
4216
- var init_session2 = __esm(() => {
4217
- init_entity();
4218
- init_logger();
4219
- init_sql();
4220
- init_sqlite_core();
4221
- init_session();
4222
- init_utils();
4223
- SQLiteBunSession = class SQLiteBunSession extends SQLiteSession {
4224
- constructor(client, dialect2, schema, options = {}) {
4225
- super(dialect2);
4226
- this.client = client;
4227
- this.schema = schema;
4228
- this.logger = options.logger ?? new NoopLogger;
4229
- }
4230
- static [entityKind] = "SQLiteBunSession";
4231
- logger;
4232
- exec(query) {
4233
- this.client.exec(query);
4234
- }
4235
- prepareQuery(query, fields, executeMethod, isResponseInArrayMode, customResultMapper) {
4236
- const stmt = this.client.prepare(query.sql);
4237
- return new PreparedQuery(stmt, query, this.logger, fields, executeMethod, isResponseInArrayMode, customResultMapper);
4238
- }
4239
- transaction(transaction, config = {}) {
4240
- const tx = new SQLiteBunTransaction("sync", this.dialect, this, this.schema);
4241
- let result;
4242
- const nativeTx = this.client.transaction(() => {
4243
- result = transaction(tx);
4244
- });
4245
- nativeTx[config.behavior ?? "deferred"]();
4246
- return result;
4247
- }
4248
- };
4249
- SQLiteBunTransaction = class SQLiteBunTransaction extends SQLiteTransaction {
4250
- static [entityKind] = "SQLiteBunTransaction";
4251
- transaction(transaction) {
4252
- const savepointName = `sp${this.nestedIndex}`;
4253
- const tx = new SQLiteBunTransaction("sync", this.dialect, this.session, this.schema, this.nestedIndex + 1);
4254
- this.session.run(sql.raw(`savepoint ${savepointName}`));
4255
- try {
4256
- const result = transaction(tx);
4257
- this.session.run(sql.raw(`release savepoint ${savepointName}`));
4258
- return result;
4259
- } catch (err) {
4260
- this.session.run(sql.raw(`rollback to savepoint ${savepointName}`));
4261
- throw err;
4262
- }
4263
- }
4264
- };
4265
- PreparedQuery = class PreparedQuery extends SQLitePreparedQuery {
4266
- constructor(stmt, query, logger2, fields, executeMethod, _isResponseInArrayMode, customResultMapper) {
4267
- super("sync", executeMethod, query);
4268
- this.stmt = stmt;
4269
- this.logger = logger2;
4270
- this.fields = fields;
4271
- this._isResponseInArrayMode = _isResponseInArrayMode;
4272
- this.customResultMapper = customResultMapper;
4273
- }
4274
- static [entityKind] = "SQLiteBunPreparedQuery";
4275
- run(placeholderValues) {
4276
- const params = fillPlaceholders(this.query.params, placeholderValues ?? {});
4277
- this.logger.logQuery(this.query.sql, params);
4278
- return this.stmt.run(...params);
4279
- }
4280
- all(placeholderValues) {
4281
- const { fields, query, logger: logger2, joinsNotNullableMap, stmt, customResultMapper } = this;
4282
- if (!fields && !customResultMapper) {
4283
- const params = fillPlaceholders(query.params, placeholderValues ?? {});
4284
- logger2.logQuery(query.sql, params);
4285
- return stmt.all(...params);
4286
- }
4287
- const rows = this.values(placeholderValues);
4288
- if (customResultMapper) {
4289
- return customResultMapper(rows);
4290
- }
4291
- return rows.map((row) => mapResultRow(fields, row, joinsNotNullableMap));
4292
- }
4293
- get(placeholderValues) {
4294
- const params = fillPlaceholders(this.query.params, placeholderValues ?? {});
4295
- this.logger.logQuery(this.query.sql, params);
4296
- const row = this.stmt.values(...params)[0];
4297
- if (!row) {
4298
- return;
4299
- }
4300
- const { fields, joinsNotNullableMap, customResultMapper } = this;
4301
- if (!fields && !customResultMapper) {
4302
- return row;
4303
- }
4304
- if (customResultMapper) {
4305
- return customResultMapper([row]);
4306
- }
4307
- return mapResultRow(fields, row, joinsNotNullableMap);
4308
- }
4309
- values(placeholderValues) {
4310
- const params = fillPlaceholders(this.query.params, placeholderValues ?? {});
4311
- this.logger.logQuery(this.query.sql, params);
4312
- return this.stmt.values(...params);
4313
- }
4314
- isResponseInArrayMode() {
4315
- return this._isResponseInArrayMode;
4316
- }
4317
- };
4318
- });
4319
-
4320
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/bun-sqlite/driver.js
4321
- import { Database } from "bun:sqlite";
4322
- function construct(client, config = {}) {
4323
- const dialect2 = new SQLiteSyncDialect({ casing: config.casing });
4324
- let logger2;
4325
- if (config.logger === true) {
4326
- logger2 = new DefaultLogger;
4327
- } else if (config.logger !== false) {
4328
- logger2 = config.logger;
4329
- }
4330
- let schema;
4331
- if (config.schema) {
4332
- const tablesConfig = extractTablesRelationalConfig(config.schema, createTableRelationsHelpers);
4333
- schema = {
4334
- fullSchema: config.schema,
4335
- schema: tablesConfig.tables,
4336
- tableNamesMap: tablesConfig.tableNamesMap
4337
- };
4338
- }
4339
- const session2 = new SQLiteBunSession(client, dialect2, schema, { logger: logger2 });
4340
- const db2 = new BunSQLiteDatabase("sync", dialect2, session2, schema);
4341
- db2.$client = client;
4342
- return db2;
4343
- }
4344
- function drizzle(...params) {
4345
- if (params[0] === undefined || typeof params[0] === "string") {
4346
- const instance = params[0] === undefined ? new Database : new Database(params[0]);
4347
- return construct(instance, params[1]);
4348
- }
4349
- if (isConfig(params[0])) {
4350
- const { connection, client, ...drizzleConfig } = params[0];
4351
- if (client)
4352
- return construct(client, drizzleConfig);
4353
- if (typeof connection === "object") {
4354
- const { source, ...opts } = connection;
4355
- const options = Object.values(opts).filter((v) => v !== undefined).length ? opts : undefined;
4356
- const instance2 = new Database(source, options);
4357
- return construct(instance2, drizzleConfig);
4358
- }
4359
- const instance = new Database(connection);
4360
- return construct(instance, drizzleConfig);
4361
- }
4362
- return construct(params[0], params[1]);
4363
- }
4364
- var BunSQLiteDatabase;
4365
- var init_driver = __esm(() => {
4366
- init_entity();
4367
- init_logger();
4368
- init_relations();
4369
- init_db();
4370
- init_dialect();
4371
- init_utils();
4372
- init_session2();
4373
- BunSQLiteDatabase = class BunSQLiteDatabase extends BaseSQLiteDatabase {
4374
- static [entityKind] = "BunSQLiteDatabase";
4375
- };
4376
- ((drizzle2) => {
4377
- function mock(config) {
4378
- return construct({}, config);
4379
- }
4380
- drizzle2.mock = mock;
4381
- })(drizzle || (drizzle = {}));
4382
- });
4383
-
4384
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/bun-sqlite/index.js
4385
- var init_bun_sqlite = __esm(() => {
4386
- init_driver();
4387
- init_session2();
4388
- });
4389
-
4390
104
  // src/db/schema.ts
4391
105
  var exports_schema = {};
4392
106
  __export(exports_schema, {
@@ -4399,10 +113,10 @@ __export(exports_schema, {
4399
113
  events: () => events,
4400
114
  conversations: () => conversations
4401
115
  });
116
+ import { sqliteTable, text, integer, index, uniqueIndex } from "drizzle-orm/sqlite-core";
117
+ import { sql } from "drizzle-orm";
4402
118
  var groups, labels, sessions, sessionLabels, conversations, events, worktreeAssociations, sessionStats;
4403
119
  var init_schema = __esm(() => {
4404
- init_sqlite_core();
4405
- init_drizzle_orm();
4406
120
  groups = sqliteTable("groups", {
4407
121
  id: text("id").primaryKey(),
4408
122
  parentId: text("parent_id").references(() => groups.id, {
@@ -4503,14 +217,15 @@ var init_schema = __esm(() => {
4503
217
  });
4504
218
 
4505
219
  // src/db/client.ts
4506
- import { Database as Database2 } from "bun:sqlite";
220
+ import { Database } from "bun:sqlite";
221
+ import { drizzle } from "drizzle-orm/bun-sqlite";
4507
222
  import { mkdirSync } from "fs";
4508
223
  import { dirname } from "path";
4509
224
  function getDb() {
4510
225
  if (_db)
4511
226
  return _db;
4512
227
  mkdirSync(dirname(paths.db), { recursive: true });
4513
- const sqlite = new Database2(paths.db);
228
+ const sqlite = new Database(paths.db);
4514
229
  sqlite.exec("PRAGMA journal_mode = WAL");
4515
230
  sqlite.exec("PRAGMA foreign_keys = ON");
4516
231
  sqlite.exec("PRAGMA synchronous = NORMAL");
@@ -4521,51 +236,23 @@ function getDb() {
4521
236
  }
4522
237
  var _db = null;
4523
238
  var init_client = __esm(() => {
4524
- init_bun_sqlite();
4525
239
  init_paths();
4526
240
  init_schema();
4527
241
  });
4528
242
 
4529
- // node_modules/.pnpm/nanoid@5.1.7/node_modules/nanoid/url-alphabet/index.js
4530
- var urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
4531
-
4532
- // node_modules/.pnpm/nanoid@5.1.7/node_modules/nanoid/index.js
4533
- import { webcrypto as crypto2 } from "crypto";
4534
- function fillPool(bytes) {
4535
- if (!pool || pool.length < bytes) {
4536
- pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER);
4537
- crypto2.getRandomValues(pool);
4538
- poolOffset = 0;
4539
- } else if (poolOffset + bytes > pool.length) {
4540
- crypto2.getRandomValues(pool);
4541
- poolOffset = 0;
4542
- }
4543
- poolOffset += bytes;
4544
- }
4545
- function nanoid(size = 21) {
4546
- fillPool(size |= 0);
4547
- let id = "";
4548
- for (let i = poolOffset - size;i < poolOffset; i++) {
4549
- id += urlAlphabet[pool[i] & 63];
4550
- }
4551
- return id;
4552
- }
4553
- var POOL_SIZE_MULTIPLIER = 128, pool, poolOffset;
4554
- var init_nanoid = () => {};
4555
-
4556
243
  // src/lib/id.ts
244
+ import { nanoid } from "nanoid";
4557
245
  function createId(size = 12) {
4558
246
  return nanoid(size);
4559
247
  }
4560
- var init_id = __esm(() => {
4561
- init_nanoid();
4562
- });
248
+ var init_id = () => {};
4563
249
 
4564
250
  // src/db/queries/sessions.ts
251
+ import { eq, and, inArray, sql as sql2 } from "drizzle-orm";
4565
252
  function createSession(opts) {
4566
- const db2 = getDb();
253
+ const db = getDb();
4567
254
  const id = createId();
4568
- return db2.insert(sessions).values({ id, ...opts }).returning().get();
255
+ return db.insert(sessions).values({ id, ...opts }).returning().get();
4569
256
  }
4570
257
  function getSession(id) {
4571
258
  return getDb().select().from(sessions).where(eq(sessions.id, id)).get();
@@ -4580,8 +267,8 @@ function getActiveSessions() {
4580
267
  return getDb().select({ session: sessions, groupPath: groups.path }).from(sessions).innerJoin(groups, eq(sessions.groupId, groups.id)).where(inArray(sessions.status, ["active", "waiting"])).all();
4581
268
  }
4582
269
  function getAllSessions(opts) {
4583
- const db2 = getDb();
4584
- const query = db2.select({ session: sessions, groupPath: groups.path }).from(sessions).innerJoin(groups, eq(sessions.groupId, groups.id));
270
+ const db = getDb();
271
+ const query = db.select({ session: sessions, groupPath: groups.path }).from(sessions).innerJoin(groups, eq(sessions.groupId, groups.id));
4585
272
  if (opts?.excludeArchived) {
4586
273
  return query.where(inArray(sessions.status, [
4587
274
  "active",
@@ -4592,16 +279,15 @@ function getAllSessions(opts) {
4592
279
  return query.all();
4593
280
  }
4594
281
  function updateSessionStatus(id, status) {
4595
- return getDb().update(sessions).set({ status, updatedAt: sql`(datetime('now'))` }).where(eq(sessions.id, id)).returning().get();
282
+ return getDb().update(sessions).set({ status, updatedAt: sql2`(datetime('now'))` }).where(eq(sessions.id, id)).returning().get();
4596
283
  }
4597
284
  function updateSession(id, data) {
4598
- return getDb().update(sessions).set({ ...data, updatedAt: sql`(datetime('now'))` }).where(eq(sessions.id, id)).returning().get();
285
+ return getDb().update(sessions).set({ ...data, updatedAt: sql2`(datetime('now'))` }).where(eq(sessions.id, id)).returning().get();
4599
286
  }
4600
287
  function deleteSession(id) {
4601
288
  return getDb().delete(sessions).where(eq(sessions.id, id)).run();
4602
289
  }
4603
290
  var init_sessions = __esm(() => {
4604
- init_drizzle_orm();
4605
291
  init_client();
4606
292
  init_schema();
4607
293
  init_id();
@@ -4656,6 +342,7 @@ function normalizeAnsweredMeta(meta) {
4656
342
  }
4657
343
 
4658
344
  // src/db/queries/events.ts
345
+ import { eq as eq2, and as and2, desc } from "drizzle-orm";
4659
346
  function insertEvent(opts) {
4660
347
  return getDb().insert(events).values({
4661
348
  sessionId: opts.sessionId,
@@ -4666,35 +353,34 @@ function insertEvent(opts) {
4666
353
  }).returning().get();
4667
354
  }
4668
355
  function getEventsBySession(sessionId) {
4669
- return getDb().select().from(events).where(eq(events.sessionId, sessionId)).orderBy(events.createdAt, events.id).all();
356
+ return getDb().select().from(events).where(eq2(events.sessionId, sessionId)).orderBy(events.createdAt, events.id).all();
4670
357
  }
4671
358
  function getEventsByType(sessionId, eventType) {
4672
- return getDb().select().from(events).where(and(eq(events.sessionId, sessionId), eq(events.event, eventType))).orderBy(events.createdAt).all();
359
+ return getDb().select().from(events).where(and2(eq2(events.sessionId, sessionId), eq2(events.event, eventType))).orderBy(events.createdAt).all();
4673
360
  }
4674
361
  var init_events = __esm(() => {
4675
- init_drizzle_orm();
4676
362
  init_client();
4677
363
  init_schema();
4678
364
  });
4679
365
 
4680
366
  // src/db/queries/conversations.ts
367
+ import { eq as eq3, and as and3, desc as desc2, sql as sql3 } from "drizzle-orm";
4681
368
  function createConversation(opts) {
4682
369
  return getDb().insert(conversations).values(opts).returning().get();
4683
370
  }
4684
371
  function getConversation(id) {
4685
- return getDb().select().from(conversations).where(eq(conversations.id, id)).get();
372
+ return getDb().select().from(conversations).where(eq3(conversations.id, id)).get();
4686
373
  }
4687
374
  function getConversationsBySession(sessionId) {
4688
- return getDb().select().from(conversations).where(and(eq(conversations.sessionId, sessionId), eq(conversations.discarded, false))).orderBy(desc(conversations.startedAt)).all();
375
+ return getDb().select().from(conversations).where(and3(eq3(conversations.sessionId, sessionId), eq3(conversations.discarded, false))).orderBy(desc2(conversations.startedAt)).all();
4689
376
  }
4690
377
  function endConversation(id) {
4691
- return getDb().update(conversations).set({ endedAt: sql`(datetime('now'))` }).where(eq(conversations.id, id)).returning().get();
378
+ return getDb().update(conversations).set({ endedAt: sql3`(datetime('now'))` }).where(eq3(conversations.id, id)).returning().get();
4692
379
  }
4693
380
  function updateLastQuestion(id, question) {
4694
- return getDb().update(conversations).set({ lastQuestion: question }).where(eq(conversations.id, id)).returning().get();
381
+ return getDb().update(conversations).set({ lastQuestion: question }).where(eq3(conversations.id, id)).returning().get();
4695
382
  }
4696
383
  var init_conversations = __esm(() => {
4697
- init_drizzle_orm();
4698
384
  init_client();
4699
385
  init_schema();
4700
386
  });
@@ -4702,7 +388,7 @@ var init_conversations = __esm(() => {
4702
388
  // src/cli/commands/update.ts
4703
389
  var exports_update = {};
4704
390
  var EVENT_STATUS_MAP;
4705
- var init_update2 = __esm(() => {
391
+ var init_update = __esm(() => {
4706
392
  init_router();
4707
393
  init_sessions();
4708
394
  init_events();
@@ -4741,13 +427,13 @@ var init_update2 = __esm(() => {
4741
427
  console.error("Usage: bertrand update --session-id <id> --event <type> [--meta <json>]");
4742
428
  process.exit(1);
4743
429
  }
4744
- const session3 = getSession(sessionId);
4745
- if (!session3) {
430
+ const session = getSession(sessionId);
431
+ if (!session) {
4746
432
  console.error(`Session not found: ${sessionId}`);
4747
433
  process.exit(1);
4748
434
  }
4749
435
  const newStatus = EVENT_STATUS_MAP[event];
4750
- if (newStatus && newStatus === session3.status) {
436
+ if (newStatus && newStatus === session.status) {
4751
437
  return;
4752
438
  }
4753
439
  let meta;
@@ -4791,8 +477,8 @@ function getContextWindowSize(model) {
4791
477
  function getLatestAssistantTurn(filePath) {
4792
478
  if (!existsSync2(filePath))
4793
479
  return null;
4794
- const text3 = readFileSync(filePath, "utf-8");
4795
- const lines = text3.split(`
480
+ const text2 = readFileSync(filePath, "utf-8");
481
+ const lines = text2.split(`
4796
482
  `);
4797
483
  const assistantEntries = [];
4798
484
  for (let i = lines.length - 1;i >= 0; i--) {
@@ -4851,8 +537,8 @@ function getLatestAssistantTurn(filePath) {
4851
537
  function getContextSnapshot(filePath) {
4852
538
  if (!existsSync2(filePath))
4853
539
  return null;
4854
- const text3 = readFileSync(filePath, "utf-8");
4855
- const lines = text3.split(`
540
+ const text2 = readFileSync(filePath, "utf-8");
541
+ const lines = text2.split(`
4856
542
  `);
4857
543
  for (let i = lines.length - 1;i >= 0; i--) {
4858
544
  const line = lines[i];
@@ -4929,8 +615,8 @@ var init_snapshot = __esm(() => {
4929
615
  console.error("Usage: bertrand snapshot --session-id <id> --transcript-path <path> [--conversation-id <id>]");
4930
616
  process.exit(1);
4931
617
  }
4932
- const session3 = getSession(sessionId);
4933
- if (!session3) {
618
+ const session = getSession(sessionId);
619
+ if (!session) {
4934
620
  console.error(`Session not found: ${sessionId}`);
4935
621
  process.exit(1);
4936
622
  }
@@ -4958,8 +644,8 @@ var init_snapshot = __esm(() => {
4958
644
 
4959
645
  // src/cli/commands/assistant-message.ts
4960
646
  var exports_assistant_message = {};
4961
- function summarize(text3) {
4962
- const firstLine = text3.split(`
647
+ function summarize(text2) {
648
+ const firstLine = text2.split(`
4963
649
  `).find((l) => l.trim()) ?? "";
4964
650
  const trimmed = firstLine.trim();
4965
651
  return trimmed.length > 80 ? `${trimmed.slice(0, 77)}...` : trimmed;
@@ -4992,8 +678,8 @@ var init_assistant_message = __esm(() => {
4992
678
  console.error("Usage: bertrand assistant-message --session-id <id> --transcript-path <path> [--conversation-id <id>]");
4993
679
  process.exit(1);
4994
680
  }
4995
- const session3 = getSession(sessionId);
4996
- if (!session3) {
681
+ const session = getSession(sessionId);
682
+ if (!session) {
4997
683
  console.error(`Session not found: ${sessionId}`);
4998
684
  process.exit(1);
4999
685
  }
@@ -5134,21 +820,21 @@ var init_notify = __esm(() => {
5134
820
  });
5135
821
 
5136
822
  // src/db/queries/stats.ts
823
+ import { eq as eq4, sql as sql4 } from "drizzle-orm";
5137
824
  function getSessionStats(sessionId) {
5138
- return getDb().select().from(sessionStats).where(eq(sessionStats.sessionId, sessionId)).get();
825
+ return getDb().select().from(sessionStats).where(eq4(sessionStats.sessionId, sessionId)).get();
5139
826
  }
5140
827
  function upsertSessionStats(sessionId, data) {
5141
828
  return getDb().insert(sessionStats).values({
5142
829
  sessionId,
5143
830
  ...data,
5144
- updatedAt: sql`(datetime('now'))`
831
+ updatedAt: sql4`(datetime('now'))`
5145
832
  }).onConflictDoUpdate({
5146
833
  target: sessionStats.sessionId,
5147
- set: { ...data, updatedAt: sql`(datetime('now'))` }
834
+ set: { ...data, updatedAt: sql4`(datetime('now'))` }
5148
835
  }).returning().get();
5149
836
  }
5150
837
  var init_stats = __esm(() => {
5151
- init_drizzle_orm();
5152
838
  init_client();
5153
839
  init_schema();
5154
840
  });
@@ -5311,6 +997,7 @@ var init_timing = __esm(() => {
5311
997
  });
5312
998
 
5313
999
  // src/lib/engagement_stats.ts
1000
+ import { eq as eq5, sql as sql5 } from "drizzle-orm";
5314
1001
  function aggregateToolUsage(sessionId) {
5315
1002
  const counts = {};
5316
1003
  const applied = getEventsByType(sessionId, "tool.applied");
@@ -5369,9 +1056,9 @@ function permissionDenialCount(sessionId) {
5369
1056
  }
5370
1057
  function discardRate(sessionId) {
5371
1058
  const row = getDb().select({
5372
- total: sql`count(*)`,
5373
- discarded: sql`sum(case when ${conversations.discarded} then 1 else 0 end)`
5374
- }).from(conversations).where(eq(conversations.sessionId, sessionId)).get();
1059
+ total: sql5`count(*)`,
1060
+ discarded: sql5`sum(case when ${conversations.discarded} then 1 else 0 end)`
1061
+ }).from(conversations).where(eq5(conversations.sessionId, sessionId)).get();
5375
1062
  return {
5376
1063
  total: row?.total ?? 0,
5377
1064
  discarded: row?.discarded ?? 0
@@ -5386,7 +1073,6 @@ function computeEngagementStats(sessionId) {
5386
1073
  };
5387
1074
  }
5388
1075
  var init_engagement_stats = __esm(() => {
5389
- init_drizzle_orm();
5390
1076
  init_client();
5391
1077
  init_schema();
5392
1078
  init_events();
@@ -5454,10 +1140,10 @@ var init_server = __esm(() => {
5454
1140
  return getEventsBySession(sessionId);
5455
1141
  }],
5456
1142
  [/^\/api\/stats\/(?<sessionId>[^/]+)$/, ({ sessionId }) => {
5457
- const session3 = getSession(sessionId);
5458
- if (!session3)
1143
+ const session = getSession(sessionId);
1144
+ if (!session)
5459
1145
  return null;
5460
- const isLive = session3.status === "active" || session3.status === "waiting";
1146
+ const isLive = session.status === "active" || session.status === "waiting";
5461
1147
  if (isLive) {
5462
1148
  return { sessionId, ...computeSessionStats(sessionId), updatedAt: new Date().toISOString() };
5463
1149
  }
@@ -5484,25 +1170,26 @@ var init_serve = __esm(() => {
5484
1170
  });
5485
1171
 
5486
1172
  // src/db/queries/groups.ts
1173
+ import { eq as eq6, like, or, isNull } from "drizzle-orm";
5487
1174
  function createGroup(opts) {
5488
- const db2 = getDb();
1175
+ const db = getDb();
5489
1176
  const id = createId();
5490
1177
  let path = opts.slug;
5491
1178
  let depth = 0;
5492
1179
  if (opts.parentId) {
5493
- const parent = db2.select().from(groups).where(eq(groups.id, opts.parentId)).get();
1180
+ const parent = db.select().from(groups).where(eq6(groups.id, opts.parentId)).get();
5494
1181
  if (!parent)
5495
1182
  throw new Error(`Parent group ${opts.parentId} not found`);
5496
1183
  path = `${parent.path}/${opts.slug}`;
5497
1184
  depth = parent.depth + 1;
5498
1185
  }
5499
- return db2.insert(groups).values({ id, slug: opts.slug, name: opts.name, parentId: opts.parentId, path, depth }).returning().get();
1186
+ return db.insert(groups).values({ id, slug: opts.slug, name: opts.name, parentId: opts.parentId, path, depth }).returning().get();
5500
1187
  }
5501
1188
  function getGroup(id) {
5502
- return getDb().select().from(groups).where(eq(groups.id, id)).get();
1189
+ return getDb().select().from(groups).where(eq6(groups.id, id)).get();
5503
1190
  }
5504
1191
  function getGroupByPath(path) {
5505
- return getDb().select().from(groups).where(eq(groups.path, path)).get();
1192
+ return getDb().select().from(groups).where(eq6(groups.path, path)).get();
5506
1193
  }
5507
1194
  function getOrCreateGroupPath(path) {
5508
1195
  const existing = getGroupByPath(path);
@@ -5524,7 +1211,6 @@ function getOrCreateGroupPath(path) {
5524
1211
  return parentId;
5525
1212
  }
5526
1213
  var init_groups = __esm(() => {
5527
- init_drizzle_orm();
5528
1214
  init_client();
5529
1215
  init_schema();
5530
1216
  init_id();
@@ -5589,10 +1275,10 @@ function formatAgo(isoOrDate) {
5589
1275
  return `${Math.floor(ms / DAY)}d ago`;
5590
1276
  return date.toLocaleDateString("en-US", { month: "short", day: "numeric" });
5591
1277
  }
5592
- function truncate(text3, maxLen) {
5593
- if (text3.length <= maxLen)
5594
- return text3;
5595
- return text3.slice(0, maxLen - 1) + "\u2026";
1278
+ function truncate(text2, maxLen) {
1279
+ if (text2.length <= maxLen)
1280
+ return text2;
1281
+ return text2.slice(0, maxLen - 1) + "\u2026";
5596
1282
  }
5597
1283
  function formatTime(iso, includeDate = false) {
5598
1284
  const date = new Date(iso);
@@ -5694,7 +1380,7 @@ async function launch(opts) {
5694
1380
  }
5695
1381
  }
5696
1382
  const groupId = getOrCreateGroupPath(opts.groupPath);
5697
- const session3 = createSession({
1383
+ const session = createSession({
5698
1384
  groupId,
5699
1385
  slug: opts.slug,
5700
1386
  name: opts.name ?? opts.slug
@@ -5702,58 +1388,58 @@ async function launch(opts) {
5702
1388
  const claudeId = randomUUID();
5703
1389
  const conversation = createConversation({
5704
1390
  id: claudeId,
5705
- sessionId: session3.id
1391
+ sessionId: session.id
5706
1392
  });
5707
- updateSession(session3.id, { status: "active", pid: process.pid });
1393
+ updateSession(session.id, { status: "active", pid: process.pid });
5708
1394
  insertEvent({
5709
- sessionId: session3.id,
1395
+ sessionId: session.id,
5710
1396
  conversationId: claudeId,
5711
1397
  event: "session.started"
5712
1398
  });
5713
1399
  insertEvent({
5714
- sessionId: session3.id,
1400
+ sessionId: session.id,
5715
1401
  conversationId: claudeId,
5716
1402
  event: "claude.started",
5717
1403
  meta: { claude_id: claudeId }
5718
1404
  });
5719
1405
  const sessionName = `${opts.groupPath}/${opts.slug}`;
5720
- const siblingContext = buildSiblingContext(groupId, session3.id);
1406
+ const siblingContext = buildSiblingContext(groupId, session.id);
5721
1407
  const contract = buildContract(sessionName, siblingContext);
5722
1408
  const exitCode = await launchClaude({
5723
- sessionId: session3.id,
1409
+ sessionId: session.id,
5724
1410
  claudeId,
5725
1411
  sessionName,
5726
1412
  sessionSlug: opts.slug,
5727
1413
  contract
5728
1414
  });
5729
- finalizeSession(session3.id, claudeId, exitCode);
5730
- return session3.id;
1415
+ finalizeSession(session.id, claudeId, exitCode);
1416
+ return session.id;
5731
1417
  }
5732
1418
  async function resume(opts) {
5733
- const session3 = getSession(opts.sessionId);
5734
- if (!session3)
1419
+ const session = getSession(opts.sessionId);
1420
+ if (!session)
5735
1421
  throw new Error(`Session not found: ${opts.sessionId}`);
5736
- const group = getGroup(session3.groupId);
5737
- const sessionName = group ? `${group.path}/${session3.slug}` : session3.name;
5738
- updateSession(session3.id, { status: "active", pid: process.pid });
1422
+ const group = getGroup(session.groupId);
1423
+ const sessionName = group ? `${group.path}/${session.slug}` : session.name;
1424
+ updateSession(session.id, { status: "active", pid: process.pid });
5739
1425
  insertEvent({
5740
- sessionId: session3.id,
1426
+ sessionId: session.id,
5741
1427
  conversationId: opts.conversationId,
5742
1428
  event: "session.resumed",
5743
1429
  meta: { claude_id: opts.conversationId }
5744
1430
  });
5745
- const siblingContext = buildSiblingContext(session3.groupId, session3.id);
1431
+ const siblingContext = buildSiblingContext(session.groupId, session.id);
5746
1432
  const contract = buildContract(sessionName, siblingContext);
5747
1433
  const exitCode = await launchClaude({
5748
- sessionId: session3.id,
1434
+ sessionId: session.id,
5749
1435
  claudeId: opts.conversationId,
5750
1436
  sessionName,
5751
- sessionSlug: session3.slug,
1437
+ sessionSlug: session.slug,
5752
1438
  contract,
5753
1439
  resume: true
5754
1440
  });
5755
- finalizeSession(session3.id, opts.conversationId, exitCode);
5756
- return session3.id;
1441
+ finalizeSession(session.id, opts.conversationId, exitCode);
1442
+ return session.id;
5757
1443
  }
5758
1444
  function finalizeSession(sessionId, conversationId, exitCode) {
5759
1445
  if (!getSession(sessionId))
@@ -5780,7 +1466,7 @@ function finalizeSession(sessionId, conversationId, exitCode) {
5780
1466
  });
5781
1467
  computeAndPersist(sessionId);
5782
1468
  }
5783
- var init_session3 = __esm(() => {
1469
+ var init_session = __esm(() => {
5784
1470
  init_sessions();
5785
1471
  init_conversations();
5786
1472
  init_events();
@@ -5894,7 +1580,7 @@ var SCREEN_ENTRY;
5894
1580
  var init_app = __esm(() => {
5895
1581
  init_sessions();
5896
1582
  init_conversations();
5897
- init_session3();
1583
+ init_session();
5898
1584
  SCREEN_ENTRY = (() => {
5899
1585
  const built = join3(import.meta.dir, "run-screen.js");
5900
1586
  return existsSync3(built) ? built : join3(import.meta.dir, "run-screen.tsx");
@@ -5933,17 +1619,17 @@ function isProcessAlive(pid) {
5933
1619
  function recoverStaleSessions() {
5934
1620
  const active = getActiveSessions();
5935
1621
  let recovered = 0;
5936
- for (const { session: session3 } of active) {
5937
- if (session3.pid && !isProcessAlive(session3.pid)) {
5938
- updateSession(session3.id, {
1622
+ for (const { session } of active) {
1623
+ if (session.pid && !isProcessAlive(session.pid)) {
1624
+ updateSession(session.id, {
5939
1625
  status: "paused",
5940
1626
  pid: null
5941
1627
  });
5942
1628
  insertEvent({
5943
- sessionId: session3.id,
1629
+ sessionId: session.id,
5944
1630
  event: "session.paused",
5945
1631
  summary: "Recovered from stale state (process not found)",
5946
- meta: { stale_pid: session3.pid }
1632
+ meta: { stale_pid: session.pid }
5947
1633
  });
5948
1634
  recovered++;
5949
1635
  }
@@ -5960,7 +1646,7 @@ var exports_launch = {};
5960
1646
  var init_launch = __esm(() => {
5961
1647
  init_router();
5962
1648
  init_app();
5963
- init_session3();
1649
+ init_session();
5964
1650
  init_recovery();
5965
1651
  register("launch", async (args) => {
5966
1652
  recoverStaleSessions();
@@ -5975,65 +1661,23 @@ var init_launch = __esm(() => {
5975
1661
  });
5976
1662
  });
5977
1663
 
5978
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/migrator.js
5979
- import crypto3 from "crypto";
5980
- import fs from "fs";
5981
- function readMigrationFiles(config) {
5982
- const migrationFolderTo = config.migrationsFolder;
5983
- const migrationQueries = [];
5984
- const journalPath = `${migrationFolderTo}/meta/_journal.json`;
5985
- if (!fs.existsSync(journalPath)) {
5986
- throw new Error(`Can't find meta/_journal.json file`);
5987
- }
5988
- const journalAsString = fs.readFileSync(`${migrationFolderTo}/meta/_journal.json`).toString();
5989
- const journal = JSON.parse(journalAsString);
5990
- for (const journalEntry of journal.entries) {
5991
- const migrationPath = `${migrationFolderTo}/${journalEntry.tag}.sql`;
5992
- try {
5993
- const query = fs.readFileSync(`${migrationFolderTo}/${journalEntry.tag}.sql`).toString();
5994
- const result = query.split("--> statement-breakpoint").map((it) => {
5995
- return it;
5996
- });
5997
- migrationQueries.push({
5998
- sql: result,
5999
- bps: journalEntry.breakpoints,
6000
- folderMillis: journalEntry.when,
6001
- hash: crypto3.createHash("sha256").update(query).digest("hex")
6002
- });
6003
- } catch {
6004
- throw new Error(`No file ${migrationPath} found in ${migrationFolderTo} folder`);
6005
- }
6006
- }
6007
- return migrationQueries;
6008
- }
6009
- var init_migrator = () => {};
6010
-
6011
- // node_modules/.pnpm/drizzle-orm@0.44.7_bun-types@1.3.11/node_modules/drizzle-orm/bun-sqlite/migrator.js
6012
- function migrate(db2, config) {
6013
- const migrations = readMigrationFiles(config);
6014
- db2.dialect.migrate(migrations, db2.session, config);
6015
- }
6016
- var init_migrator2 = __esm(() => {
6017
- init_migrator();
6018
- });
6019
-
6020
1664
  // src/db/migrate.ts
6021
- import { Database as Database3 } from "bun:sqlite";
1665
+ import { Database as Database2 } from "bun:sqlite";
1666
+ import { drizzle as drizzle2 } from "drizzle-orm/bun-sqlite";
1667
+ import { migrate } from "drizzle-orm/bun-sqlite/migrator";
6022
1668
  import { mkdirSync as mkdirSync2 } from "fs";
6023
1669
  import { dirname as dirname2 } from "path";
6024
1670
  function runMigrations() {
6025
1671
  mkdirSync2(dirname2(paths.db), { recursive: true });
6026
- const sqlite = new Database3(paths.db);
1672
+ const sqlite = new Database2(paths.db);
6027
1673
  sqlite.exec("PRAGMA journal_mode = WAL");
6028
1674
  sqlite.exec("PRAGMA foreign_keys = ON");
6029
- const db2 = drizzle(sqlite);
6030
- migrate(db2, { migrationsFolder: MIGRATIONS_FOLDER });
1675
+ const db = drizzle2(sqlite);
1676
+ migrate(db, { migrationsFolder: MIGRATIONS_FOLDER });
6031
1677
  sqlite.close();
6032
1678
  }
6033
1679
  var MIGRATIONS_FOLDER;
6034
1680
  var init_migrate = __esm(() => {
6035
- init_bun_sqlite();
6036
- init_migrator2();
6037
1681
  init_paths();
6038
1682
  MIGRATIONS_FOLDER = import.meta.dir + "/migrations";
6039
1683
  if (false) {}
@@ -6837,11 +2481,11 @@ var init_compact = __esm(() => {
6837
2481
 
6838
2482
  // src/cli/commands/log.ts
6839
2483
  var exports_log = {};
6840
- function ansi(code, text3) {
6841
- return `\x1B[${code}m${text3}${RESET}`;
2484
+ function ansi(code, text2) {
2485
+ return `\x1B[${code}m${text2}${RESET}`;
6842
2486
  }
6843
- function ansi256(code, text3) {
6844
- return `\x1B[38;5;${code}m${text3}${RESET}`;
2487
+ function ansi256(code, text2) {
2488
+ return `\x1B[38;5;${code}m${text2}${RESET}`;
6845
2489
  }
6846
2490
  function showAllSessions() {
6847
2491
  const rows = getAllSessions().sort((a, b) => new Date(b.session.updatedAt).getTime() - new Date(a.session.updatedAt).getTime());
@@ -7029,12 +2673,12 @@ var init_log = __esm(() => {
7029
2673
  console.error(`Group not found: ${groupPath}`);
7030
2674
  process.exit(1);
7031
2675
  }
7032
- const session3 = getSessionByGroupSlug(group.id, slug);
7033
- if (!session3) {
2676
+ const session = getSessionByGroupSlug(group.id, slug);
2677
+ if (!session) {
7034
2678
  console.error(`Session not found: ${target}`);
7035
2679
  process.exit(1);
7036
2680
  }
7037
- showSessionLog(session3.id, `${groupPath}/${slug}`, isJson);
2681
+ showSessionLog(session.id, `${groupPath}/${slug}`, isJson);
7038
2682
  });
7039
2683
  });
7040
2684
 
@@ -7191,12 +2835,12 @@ var init_stats2 = __esm(() => {
7191
2835
  console.error(`Group not found: ${groupPath}`);
7192
2836
  process.exit(1);
7193
2837
  }
7194
- const session3 = getSessionByGroupSlug(group.id, slug);
7195
- if (!session3) {
2838
+ const session = getSessionByGroupSlug(group.id, slug);
2839
+ if (!session) {
7196
2840
  console.error(`Session not found: ${target}`);
7197
2841
  process.exit(1);
7198
2842
  }
7199
- const m = getMetrics(session3.id, `${groupPath}/${slug}`, session3.status);
2843
+ const m = getMetrics(session.id, `${groupPath}/${slug}`, session.status);
7200
2844
  renderSession(m, isJson);
7201
2845
  });
7202
2846
  });
@@ -7211,9 +2855,9 @@ var init_backfill_stats = __esm(() => {
7211
2855
  const includeArchived = args.includes("--include-archived");
7212
2856
  const rows = getAllSessions({ excludeArchived: !includeArchived });
7213
2857
  console.log(`Backfilling stats for ${rows.length} session(s)${includeArchived ? "" : " (excluding archived)"}...`);
7214
- for (const { session: session3, groupPath } of rows) {
7215
- computeAndPersist(session3.id);
7216
- console.log(` \u2713 ${groupPath}/${session3.slug}`);
2858
+ for (const { session, groupPath } of rows) {
2859
+ computeAndPersist(session.id);
2860
+ console.log(` \u2713 ${groupPath}/${session.slug}`);
7217
2861
  }
7218
2862
  console.log("Done.");
7219
2863
  });
@@ -7228,12 +2872,12 @@ function resolveSession(name) {
7228
2872
  console.error(`Group not found: ${groupPath}`);
7229
2873
  process.exit(1);
7230
2874
  }
7231
- const session3 = getSessionByGroupSlug(group.id, slug);
7232
- if (!session3) {
2875
+ const session = getSessionByGroupSlug(group.id, slug);
2876
+ if (!session) {
7233
2877
  console.error(`Session not found: ${name}`);
7234
2878
  process.exit(1);
7235
2879
  }
7236
- return { session: session3, groupPath };
2880
+ return { session, groupPath };
7237
2881
  }
7238
2882
  var ACTIVE_STATUSES2;
7239
2883
  var init_archive = __esm(() => {
@@ -7269,26 +2913,26 @@ Archived ${archived} session${archived === 1 ? "" : "s"}.`);
7269
2913
  console.error(" bertrand archive --all-paused");
7270
2914
  process.exit(1);
7271
2915
  }
7272
- const { session: session3, groupPath } = resolveSession(sessionName);
7273
- const fullName = `${groupPath}/${session3.slug}`;
2916
+ const { session, groupPath } = resolveSession(sessionName);
2917
+ const fullName = `${groupPath}/${session.slug}`;
7274
2918
  if (isUndo) {
7275
- if (session3.status !== "archived") {
7276
- console.error(`${fullName} is not archived (status: ${session3.status})`);
2919
+ if (session.status !== "archived") {
2920
+ console.error(`${fullName} is not archived (status: ${session.status})`);
7277
2921
  process.exit(1);
7278
2922
  }
7279
- updateSessionStatus(session3.id, "paused");
2923
+ updateSessionStatus(session.id, "paused");
7280
2924
  console.log(`Unarchived ${fullName}`);
7281
2925
  return;
7282
2926
  }
7283
- if (ACTIVE_STATUSES2.includes(session3.status)) {
7284
- console.error(`Cannot archive active session ${fullName} (status: ${session3.status})`);
2927
+ if (ACTIVE_STATUSES2.includes(session.status)) {
2928
+ console.error(`Cannot archive active session ${fullName} (status: ${session.status})`);
7285
2929
  process.exit(1);
7286
2930
  }
7287
- if (session3.status === "archived") {
2931
+ if (session.status === "archived") {
7288
2932
  console.error(`${fullName} is already archived`);
7289
2933
  process.exit(1);
7290
2934
  }
7291
- updateSessionStatus(session3.id, "archived");
2935
+ updateSessionStatus(session.id, "archived");
7292
2936
  console.log(`Archived ${fullName}`);
7293
2937
  });
7294
2938
  });
@@ -7297,7 +2941,7 @@ Archived ${archived} session${archived === 1 ? "" : "s"}.`);
7297
2941
  init_router();
7298
2942
  var command = process.argv[2];
7299
2943
  var hotPath = {
7300
- update: () => Promise.resolve().then(() => (init_update2(), exports_update)),
2944
+ update: () => Promise.resolve().then(() => (init_update(), exports_update)),
7301
2945
  snapshot: () => Promise.resolve().then(() => (init_snapshot(), exports_snapshot)),
7302
2946
  "assistant-message": () => Promise.resolve().then(() => (init_assistant_message(), exports_assistant_message)),
7303
2947
  badge: () => Promise.resolve().then(() => (init_badge(), exports_badge)),
@@ -7315,7 +2959,7 @@ if (command && command in hotPath) {
7315
2959
  Promise.resolve().then(() => (init_stats2(), exports_stats)),
7316
2960
  Promise.resolve().then(() => (init_backfill_stats(), exports_backfill_stats)),
7317
2961
  Promise.resolve().then(() => (init_archive(), exports_archive)),
7318
- Promise.resolve().then(() => (init_update2(), exports_update)),
2962
+ Promise.resolve().then(() => (init_update(), exports_update)),
7319
2963
  Promise.resolve().then(() => (init_snapshot(), exports_snapshot)),
7320
2964
  Promise.resolve().then(() => (init_assistant_message(), exports_assistant_message)),
7321
2965
  Promise.resolve().then(() => (init_serve(), exports_serve)),