@shipeasy/openapi 1.0.0

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.
@@ -0,0 +1,2813 @@
1
+ // src/resources/killswitches.ts
2
+ import { z as z3 } from "zod";
3
+
4
+ // ../core/src/schemas/killswitches.ts
5
+ import { z as z2 } from "zod";
6
+
7
+ // ../core/src/schemas/configs.ts
8
+ import { z } from "zod";
9
+
10
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/entity.js
11
+ var entityKind = /* @__PURE__ */ Symbol.for("drizzle:entityKind");
12
+ function is(value, type) {
13
+ if (!value || typeof value !== "object") {
14
+ return false;
15
+ }
16
+ if (value instanceof type) {
17
+ return true;
18
+ }
19
+ if (!Object.prototype.hasOwnProperty.call(type, entityKind)) {
20
+ throw new Error(
21
+ `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.`
22
+ );
23
+ }
24
+ let cls = Object.getPrototypeOf(value).constructor;
25
+ if (cls) {
26
+ while (cls) {
27
+ if (entityKind in cls && cls[entityKind] === type[entityKind]) {
28
+ return true;
29
+ }
30
+ cls = Object.getPrototypeOf(cls);
31
+ }
32
+ }
33
+ return false;
34
+ }
35
+
36
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/column.js
37
+ var Column = class {
38
+ constructor(table, config) {
39
+ this.table = table;
40
+ this.config = config;
41
+ this.name = config.name;
42
+ this.keyAsName = config.keyAsName;
43
+ this.notNull = config.notNull;
44
+ this.default = config.default;
45
+ this.defaultFn = config.defaultFn;
46
+ this.onUpdateFn = config.onUpdateFn;
47
+ this.hasDefault = config.hasDefault;
48
+ this.primary = config.primaryKey;
49
+ this.isUnique = config.isUnique;
50
+ this.uniqueName = config.uniqueName;
51
+ this.uniqueType = config.uniqueType;
52
+ this.dataType = config.dataType;
53
+ this.columnType = config.columnType;
54
+ this.generated = config.generated;
55
+ this.generatedIdentity = config.generatedIdentity;
56
+ }
57
+ static [entityKind] = "Column";
58
+ name;
59
+ keyAsName;
60
+ primary;
61
+ notNull;
62
+ default;
63
+ defaultFn;
64
+ onUpdateFn;
65
+ hasDefault;
66
+ isUnique;
67
+ uniqueName;
68
+ uniqueType;
69
+ dataType;
70
+ columnType;
71
+ enumValues = void 0;
72
+ generated = void 0;
73
+ generatedIdentity = void 0;
74
+ config;
75
+ mapFromDriverValue(value) {
76
+ return value;
77
+ }
78
+ mapToDriverValue(value) {
79
+ return value;
80
+ }
81
+ // ** @internal */
82
+ shouldDisableInsert() {
83
+ return this.config.generated !== void 0 && this.config.generated.type !== "byDefault";
84
+ }
85
+ };
86
+
87
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/column-builder.js
88
+ var ColumnBuilder = class {
89
+ static [entityKind] = "ColumnBuilder";
90
+ config;
91
+ constructor(name, dataType, columnType) {
92
+ this.config = {
93
+ name,
94
+ keyAsName: name === "",
95
+ notNull: false,
96
+ default: void 0,
97
+ hasDefault: false,
98
+ primaryKey: false,
99
+ isUnique: false,
100
+ uniqueName: void 0,
101
+ uniqueType: void 0,
102
+ dataType,
103
+ columnType,
104
+ generated: void 0
105
+ };
106
+ }
107
+ /**
108
+ * Changes the data type of the column. Commonly used with `json` columns. Also, useful for branded types.
109
+ *
110
+ * @example
111
+ * ```ts
112
+ * const users = pgTable('users', {
113
+ * id: integer('id').$type<UserId>().primaryKey(),
114
+ * details: json('details').$type<UserDetails>().notNull(),
115
+ * });
116
+ * ```
117
+ */
118
+ $type() {
119
+ return this;
120
+ }
121
+ /**
122
+ * Adds a `not null` clause to the column definition.
123
+ *
124
+ * Affects the `select` model of the table - columns *without* `not null` will be nullable on select.
125
+ */
126
+ notNull() {
127
+ this.config.notNull = true;
128
+ return this;
129
+ }
130
+ /**
131
+ * Adds a `default <value>` clause to the column definition.
132
+ *
133
+ * Affects the `insert` model of the table - columns *with* `default` are optional on insert.
134
+ *
135
+ * If you need to set a dynamic default value, use {@link $defaultFn} instead.
136
+ */
137
+ default(value) {
138
+ this.config.default = value;
139
+ this.config.hasDefault = true;
140
+ return this;
141
+ }
142
+ /**
143
+ * Adds a dynamic default value to the column.
144
+ * The function will be called when the row is inserted, and the returned value will be used as the column value.
145
+ *
146
+ * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.
147
+ */
148
+ $defaultFn(fn) {
149
+ this.config.defaultFn = fn;
150
+ this.config.hasDefault = true;
151
+ return this;
152
+ }
153
+ /**
154
+ * Alias for {@link $defaultFn}.
155
+ */
156
+ $default = this.$defaultFn;
157
+ /**
158
+ * Adds a dynamic update value to the column.
159
+ * The function will be called when the row is updated, and the returned value will be used as the column value if none is provided.
160
+ * If no `default` (or `$defaultFn`) value is provided, the function will be called when the row is inserted as well, and the returned value will be used as the column value.
161
+ *
162
+ * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.
163
+ */
164
+ $onUpdateFn(fn) {
165
+ this.config.onUpdateFn = fn;
166
+ this.config.hasDefault = true;
167
+ return this;
168
+ }
169
+ /**
170
+ * Alias for {@link $onUpdateFn}.
171
+ */
172
+ $onUpdate = this.$onUpdateFn;
173
+ /**
174
+ * Adds a `primary key` clause to the column definition. This implicitly makes the column `not null`.
175
+ *
176
+ * In SQLite, `integer primary key` implicitly makes the column auto-incrementing.
177
+ */
178
+ primaryKey() {
179
+ this.config.primaryKey = true;
180
+ this.config.notNull = true;
181
+ return this;
182
+ }
183
+ /** @internal Sets the name of the column to the key within the table definition if a name was not given. */
184
+ setName(name) {
185
+ if (this.config.name !== "")
186
+ return;
187
+ this.config.name = name;
188
+ }
189
+ };
190
+
191
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/table.utils.js
192
+ var TableName = /* @__PURE__ */ Symbol.for("drizzle:Name");
193
+
194
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/pg-core/foreign-keys.js
195
+ var ForeignKeyBuilder = class {
196
+ static [entityKind] = "PgForeignKeyBuilder";
197
+ /** @internal */
198
+ reference;
199
+ /** @internal */
200
+ _onUpdate = "no action";
201
+ /** @internal */
202
+ _onDelete = "no action";
203
+ constructor(config, actions) {
204
+ this.reference = () => {
205
+ const { name, columns, foreignColumns } = config();
206
+ return { name, columns, foreignTable: foreignColumns[0].table, foreignColumns };
207
+ };
208
+ if (actions) {
209
+ this._onUpdate = actions.onUpdate;
210
+ this._onDelete = actions.onDelete;
211
+ }
212
+ }
213
+ onUpdate(action) {
214
+ this._onUpdate = action === void 0 ? "no action" : action;
215
+ return this;
216
+ }
217
+ onDelete(action) {
218
+ this._onDelete = action === void 0 ? "no action" : action;
219
+ return this;
220
+ }
221
+ /** @internal */
222
+ build(table) {
223
+ return new ForeignKey(table, this);
224
+ }
225
+ };
226
+ var ForeignKey = class {
227
+ constructor(table, builder) {
228
+ this.table = table;
229
+ this.reference = builder.reference;
230
+ this.onUpdate = builder._onUpdate;
231
+ this.onDelete = builder._onDelete;
232
+ }
233
+ static [entityKind] = "PgForeignKey";
234
+ reference;
235
+ onUpdate;
236
+ onDelete;
237
+ getName() {
238
+ const { name, columns, foreignColumns } = this.reference();
239
+ const columnNames = columns.map((column) => column.name);
240
+ const foreignColumnNames = foreignColumns.map((column) => column.name);
241
+ const chunks = [
242
+ this.table[TableName],
243
+ ...columnNames,
244
+ foreignColumns[0].table[TableName],
245
+ ...foreignColumnNames
246
+ ];
247
+ return name ?? `${chunks.join("_")}_fk`;
248
+ }
249
+ };
250
+
251
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/tracing-utils.js
252
+ function iife(fn, ...args) {
253
+ return fn(...args);
254
+ }
255
+
256
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/pg-core/unique-constraint.js
257
+ function uniqueKeyName(table, columns) {
258
+ return `${table[TableName]}_${columns.join("_")}_unique`;
259
+ }
260
+ var UniqueConstraintBuilder = class {
261
+ constructor(columns, name) {
262
+ this.name = name;
263
+ this.columns = columns;
264
+ }
265
+ static [entityKind] = "PgUniqueConstraintBuilder";
266
+ /** @internal */
267
+ columns;
268
+ /** @internal */
269
+ nullsNotDistinctConfig = false;
270
+ nullsNotDistinct() {
271
+ this.nullsNotDistinctConfig = true;
272
+ return this;
273
+ }
274
+ /** @internal */
275
+ build(table) {
276
+ return new UniqueConstraint(table, this.columns, this.nullsNotDistinctConfig, this.name);
277
+ }
278
+ };
279
+ var UniqueOnConstraintBuilder = class {
280
+ static [entityKind] = "PgUniqueOnConstraintBuilder";
281
+ /** @internal */
282
+ name;
283
+ constructor(name) {
284
+ this.name = name;
285
+ }
286
+ on(...columns) {
287
+ return new UniqueConstraintBuilder(columns, this.name);
288
+ }
289
+ };
290
+ var UniqueConstraint = class {
291
+ constructor(table, columns, nullsNotDistinct, name) {
292
+ this.table = table;
293
+ this.columns = columns;
294
+ this.name = name ?? uniqueKeyName(this.table, this.columns.map((column) => column.name));
295
+ this.nullsNotDistinct = nullsNotDistinct;
296
+ }
297
+ static [entityKind] = "PgUniqueConstraint";
298
+ columns;
299
+ name;
300
+ nullsNotDistinct = false;
301
+ getName() {
302
+ return this.name;
303
+ }
304
+ };
305
+
306
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/pg-core/utils/array.js
307
+ function parsePgArrayValue(arrayString, startFrom, inQuotes) {
308
+ for (let i = startFrom; i < arrayString.length; i++) {
309
+ const char = arrayString[i];
310
+ if (char === "\\") {
311
+ i++;
312
+ continue;
313
+ }
314
+ if (char === '"') {
315
+ return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i + 1];
316
+ }
317
+ if (inQuotes) {
318
+ continue;
319
+ }
320
+ if (char === "," || char === "}") {
321
+ return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i];
322
+ }
323
+ }
324
+ return [arrayString.slice(startFrom).replace(/\\/g, ""), arrayString.length];
325
+ }
326
+ function parsePgNestedArray(arrayString, startFrom = 0) {
327
+ const result = [];
328
+ let i = startFrom;
329
+ let lastCharIsComma = false;
330
+ while (i < arrayString.length) {
331
+ const char = arrayString[i];
332
+ if (char === ",") {
333
+ if (lastCharIsComma || i === startFrom) {
334
+ result.push("");
335
+ }
336
+ lastCharIsComma = true;
337
+ i++;
338
+ continue;
339
+ }
340
+ lastCharIsComma = false;
341
+ if (char === "\\") {
342
+ i += 2;
343
+ continue;
344
+ }
345
+ if (char === '"') {
346
+ const [value2, startFrom2] = parsePgArrayValue(arrayString, i + 1, true);
347
+ result.push(value2);
348
+ i = startFrom2;
349
+ continue;
350
+ }
351
+ if (char === "}") {
352
+ return [result, i + 1];
353
+ }
354
+ if (char === "{") {
355
+ const [value2, startFrom2] = parsePgNestedArray(arrayString, i + 1);
356
+ result.push(value2);
357
+ i = startFrom2;
358
+ continue;
359
+ }
360
+ const [value, newStartFrom] = parsePgArrayValue(arrayString, i, false);
361
+ result.push(value);
362
+ i = newStartFrom;
363
+ }
364
+ return [result, i];
365
+ }
366
+ function parsePgArray(arrayString) {
367
+ const [result] = parsePgNestedArray(arrayString, 1);
368
+ return result;
369
+ }
370
+ function makePgArray(array) {
371
+ return `{${array.map((item) => {
372
+ if (Array.isArray(item)) {
373
+ return makePgArray(item);
374
+ }
375
+ if (typeof item === "string") {
376
+ return `"${item.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
377
+ }
378
+ return `${item}`;
379
+ }).join(",")}}`;
380
+ }
381
+
382
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/pg-core/columns/common.js
383
+ var PgColumnBuilder = class extends ColumnBuilder {
384
+ foreignKeyConfigs = [];
385
+ static [entityKind] = "PgColumnBuilder";
386
+ array(size) {
387
+ return new PgArrayBuilder(this.config.name, this, size);
388
+ }
389
+ references(ref, actions = {}) {
390
+ this.foreignKeyConfigs.push({ ref, actions });
391
+ return this;
392
+ }
393
+ unique(name, config) {
394
+ this.config.isUnique = true;
395
+ this.config.uniqueName = name;
396
+ this.config.uniqueType = config?.nulls;
397
+ return this;
398
+ }
399
+ generatedAlwaysAs(as) {
400
+ this.config.generated = {
401
+ as,
402
+ type: "always",
403
+ mode: "stored"
404
+ };
405
+ return this;
406
+ }
407
+ /** @internal */
408
+ buildForeignKeys(column, table) {
409
+ return this.foreignKeyConfigs.map(({ ref, actions }) => {
410
+ return iife(
411
+ (ref2, actions2) => {
412
+ const builder = new ForeignKeyBuilder(() => {
413
+ const foreignColumn = ref2();
414
+ return { columns: [column], foreignColumns: [foreignColumn] };
415
+ });
416
+ if (actions2.onUpdate) {
417
+ builder.onUpdate(actions2.onUpdate);
418
+ }
419
+ if (actions2.onDelete) {
420
+ builder.onDelete(actions2.onDelete);
421
+ }
422
+ return builder.build(table);
423
+ },
424
+ ref,
425
+ actions
426
+ );
427
+ });
428
+ }
429
+ /** @internal */
430
+ buildExtraConfigColumn(table) {
431
+ return new ExtraConfigColumn(table, this.config);
432
+ }
433
+ };
434
+ var PgColumn = class extends Column {
435
+ constructor(table, config) {
436
+ if (!config.uniqueName) {
437
+ config.uniqueName = uniqueKeyName(table, [config.name]);
438
+ }
439
+ super(table, config);
440
+ this.table = table;
441
+ }
442
+ static [entityKind] = "PgColumn";
443
+ };
444
+ var ExtraConfigColumn = class extends PgColumn {
445
+ static [entityKind] = "ExtraConfigColumn";
446
+ getSQLType() {
447
+ return this.getSQLType();
448
+ }
449
+ indexConfig = {
450
+ order: this.config.order ?? "asc",
451
+ nulls: this.config.nulls ?? "last",
452
+ opClass: this.config.opClass
453
+ };
454
+ defaultConfig = {
455
+ order: "asc",
456
+ nulls: "last",
457
+ opClass: void 0
458
+ };
459
+ asc() {
460
+ this.indexConfig.order = "asc";
461
+ return this;
462
+ }
463
+ desc() {
464
+ this.indexConfig.order = "desc";
465
+ return this;
466
+ }
467
+ nullsFirst() {
468
+ this.indexConfig.nulls = "first";
469
+ return this;
470
+ }
471
+ nullsLast() {
472
+ this.indexConfig.nulls = "last";
473
+ return this;
474
+ }
475
+ /**
476
+ * ### PostgreSQL documentation quote
477
+ *
478
+ * > An operator class with optional parameters can be specified for each column of an index.
479
+ * The operator class identifies the operators to be used by the index for that column.
480
+ * For example, a B-tree index on four-byte integers would use the int4_ops class;
481
+ * this operator class includes comparison functions for four-byte integers.
482
+ * In practice the default operator class for the column's data type is usually sufficient.
483
+ * The main point of having operator classes is that for some data types, there could be more than one meaningful ordering.
484
+ * For example, we might want to sort a complex-number data type either by absolute value or by real part.
485
+ * We could do this by defining two operator classes for the data type and then selecting the proper class when creating an index.
486
+ * More information about operator classes check:
487
+ *
488
+ * ### Useful links
489
+ * https://www.postgresql.org/docs/current/sql-createindex.html
490
+ *
491
+ * https://www.postgresql.org/docs/current/indexes-opclass.html
492
+ *
493
+ * https://www.postgresql.org/docs/current/xindex.html
494
+ *
495
+ * ### Additional types
496
+ * If you have the `pg_vector` extension installed in your database, you can use the
497
+ * `vector_l2_ops`, `vector_ip_ops`, `vector_cosine_ops`, `vector_l1_ops`, `bit_hamming_ops`, `bit_jaccard_ops`, `halfvec_l2_ops`, `sparsevec_l2_ops` options, which are predefined types.
498
+ *
499
+ * **You can always specify any string you want in the operator class, in case Drizzle doesn't have it natively in its types**
500
+ *
501
+ * @param opClass
502
+ * @returns
503
+ */
504
+ op(opClass) {
505
+ this.indexConfig.opClass = opClass;
506
+ return this;
507
+ }
508
+ };
509
+ var IndexedColumn = class {
510
+ static [entityKind] = "IndexedColumn";
511
+ constructor(name, keyAsName, type, indexConfig) {
512
+ this.name = name;
513
+ this.keyAsName = keyAsName;
514
+ this.type = type;
515
+ this.indexConfig = indexConfig;
516
+ }
517
+ name;
518
+ keyAsName;
519
+ type;
520
+ indexConfig;
521
+ };
522
+ var PgArrayBuilder = class extends PgColumnBuilder {
523
+ static [entityKind] = "PgArrayBuilder";
524
+ constructor(name, baseBuilder, size) {
525
+ super(name, "array", "PgArray");
526
+ this.config.baseBuilder = baseBuilder;
527
+ this.config.size = size;
528
+ }
529
+ /** @internal */
530
+ build(table) {
531
+ const baseColumn = this.config.baseBuilder.build(table);
532
+ return new PgArray(
533
+ table,
534
+ this.config,
535
+ baseColumn
536
+ );
537
+ }
538
+ };
539
+ var PgArray = class _PgArray extends PgColumn {
540
+ constructor(table, config, baseColumn, range) {
541
+ super(table, config);
542
+ this.baseColumn = baseColumn;
543
+ this.range = range;
544
+ this.size = config.size;
545
+ }
546
+ size;
547
+ static [entityKind] = "PgArray";
548
+ getSQLType() {
549
+ return `${this.baseColumn.getSQLType()}[${typeof this.size === "number" ? this.size : ""}]`;
550
+ }
551
+ mapFromDriverValue(value) {
552
+ if (typeof value === "string") {
553
+ value = parsePgArray(value);
554
+ }
555
+ return value.map((v) => this.baseColumn.mapFromDriverValue(v));
556
+ }
557
+ mapToDriverValue(value, isNestedArray = false) {
558
+ const a = value.map(
559
+ (v) => v === null ? null : is(this.baseColumn, _PgArray) ? this.baseColumn.mapToDriverValue(v, true) : this.baseColumn.mapToDriverValue(v)
560
+ );
561
+ if (isNestedArray)
562
+ return a;
563
+ return makePgArray(a);
564
+ }
565
+ };
566
+
567
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/pg-core/columns/enum.js
568
+ var isPgEnumSym = /* @__PURE__ */ Symbol.for("drizzle:isPgEnum");
569
+ function isPgEnum(obj) {
570
+ return !!obj && typeof obj === "function" && isPgEnumSym in obj && obj[isPgEnumSym] === true;
571
+ }
572
+ var PgEnumColumnBuilder = class extends PgColumnBuilder {
573
+ static [entityKind] = "PgEnumColumnBuilder";
574
+ constructor(name, enumInstance) {
575
+ super(name, "string", "PgEnumColumn");
576
+ this.config.enum = enumInstance;
577
+ }
578
+ /** @internal */
579
+ build(table) {
580
+ return new PgEnumColumn(
581
+ table,
582
+ this.config
583
+ );
584
+ }
585
+ };
586
+ var PgEnumColumn = class extends PgColumn {
587
+ static [entityKind] = "PgEnumColumn";
588
+ enum = this.config.enum;
589
+ enumValues = this.config.enum.enumValues;
590
+ constructor(table, config) {
591
+ super(table, config);
592
+ this.enum = config.enum;
593
+ }
594
+ getSQLType() {
595
+ return this.enum.enumName;
596
+ }
597
+ };
598
+
599
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/subquery.js
600
+ var Subquery = class {
601
+ static [entityKind] = "Subquery";
602
+ constructor(sql2, selection, alias, isWith = false) {
603
+ this._ = {
604
+ brand: "Subquery",
605
+ sql: sql2,
606
+ selectedFields: selection,
607
+ alias,
608
+ isWith
609
+ };
610
+ }
611
+ // getSQL(): SQL<unknown> {
612
+ // return new SQL([this]);
613
+ // }
614
+ };
615
+ var WithSubquery = class extends Subquery {
616
+ static [entityKind] = "WithSubquery";
617
+ };
618
+
619
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/version.js
620
+ var version = "0.36.4";
621
+
622
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/tracing.js
623
+ var otel;
624
+ var rawTracer;
625
+ var tracer = {
626
+ startActiveSpan(name, fn) {
627
+ if (!otel) {
628
+ return fn();
629
+ }
630
+ if (!rawTracer) {
631
+ rawTracer = otel.trace.getTracer("drizzle-orm", version);
632
+ }
633
+ return iife(
634
+ (otel2, rawTracer2) => rawTracer2.startActiveSpan(
635
+ name,
636
+ (span) => {
637
+ try {
638
+ return fn(span);
639
+ } catch (e) {
640
+ span.setStatus({
641
+ code: otel2.SpanStatusCode.ERROR,
642
+ message: e instanceof Error ? e.message : "Unknown error"
643
+ // eslint-disable-line no-instanceof/no-instanceof
644
+ });
645
+ throw e;
646
+ } finally {
647
+ span.end();
648
+ }
649
+ }
650
+ ),
651
+ otel,
652
+ rawTracer
653
+ );
654
+ }
655
+ };
656
+
657
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/view-common.js
658
+ var ViewBaseConfig = /* @__PURE__ */ Symbol.for("drizzle:ViewBaseConfig");
659
+
660
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/table.js
661
+ var Schema = /* @__PURE__ */ Symbol.for("drizzle:Schema");
662
+ var Columns = /* @__PURE__ */ Symbol.for("drizzle:Columns");
663
+ var ExtraConfigColumns = /* @__PURE__ */ Symbol.for("drizzle:ExtraConfigColumns");
664
+ var OriginalName = /* @__PURE__ */ Symbol.for("drizzle:OriginalName");
665
+ var BaseName = /* @__PURE__ */ Symbol.for("drizzle:BaseName");
666
+ var IsAlias = /* @__PURE__ */ Symbol.for("drizzle:IsAlias");
667
+ var ExtraConfigBuilder = /* @__PURE__ */ Symbol.for("drizzle:ExtraConfigBuilder");
668
+ var IsDrizzleTable = /* @__PURE__ */ Symbol.for("drizzle:IsDrizzleTable");
669
+ var Table = class {
670
+ static [entityKind] = "Table";
671
+ /** @internal */
672
+ static Symbol = {
673
+ Name: TableName,
674
+ Schema,
675
+ OriginalName,
676
+ Columns,
677
+ ExtraConfigColumns,
678
+ BaseName,
679
+ IsAlias,
680
+ ExtraConfigBuilder
681
+ };
682
+ /**
683
+ * @internal
684
+ * Can be changed if the table is aliased.
685
+ */
686
+ [TableName];
687
+ /**
688
+ * @internal
689
+ * Used to store the original name of the table, before any aliasing.
690
+ */
691
+ [OriginalName];
692
+ /** @internal */
693
+ [Schema];
694
+ /** @internal */
695
+ [Columns];
696
+ /** @internal */
697
+ [ExtraConfigColumns];
698
+ /**
699
+ * @internal
700
+ * Used to store the table name before the transformation via the `tableCreator` functions.
701
+ */
702
+ [BaseName];
703
+ /** @internal */
704
+ [IsAlias] = false;
705
+ /** @internal */
706
+ [IsDrizzleTable] = true;
707
+ /** @internal */
708
+ [ExtraConfigBuilder] = void 0;
709
+ constructor(name, schema, baseName) {
710
+ this[TableName] = this[OriginalName] = name;
711
+ this[Schema] = schema;
712
+ this[BaseName] = baseName;
713
+ }
714
+ };
715
+
716
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/sql/sql.js
717
+ var FakePrimitiveParam = class {
718
+ static [entityKind] = "FakePrimitiveParam";
719
+ };
720
+ function isSQLWrapper(value) {
721
+ return value !== null && value !== void 0 && typeof value.getSQL === "function";
722
+ }
723
+ function mergeQueries(queries) {
724
+ const result = { sql: "", params: [] };
725
+ for (const query of queries) {
726
+ result.sql += query.sql;
727
+ result.params.push(...query.params);
728
+ if (query.typings?.length) {
729
+ if (!result.typings) {
730
+ result.typings = [];
731
+ }
732
+ result.typings.push(...query.typings);
733
+ }
734
+ }
735
+ return result;
736
+ }
737
+ var StringChunk = class {
738
+ static [entityKind] = "StringChunk";
739
+ value;
740
+ constructor(value) {
741
+ this.value = Array.isArray(value) ? value : [value];
742
+ }
743
+ getSQL() {
744
+ return new SQL([this]);
745
+ }
746
+ };
747
+ var SQL = class _SQL {
748
+ constructor(queryChunks) {
749
+ this.queryChunks = queryChunks;
750
+ }
751
+ static [entityKind] = "SQL";
752
+ /** @internal */
753
+ decoder = noopDecoder;
754
+ shouldInlineParams = false;
755
+ append(query) {
756
+ this.queryChunks.push(...query.queryChunks);
757
+ return this;
758
+ }
759
+ toQuery(config) {
760
+ return tracer.startActiveSpan("drizzle.buildSQL", (span) => {
761
+ const query = this.buildQueryFromSourceParams(this.queryChunks, config);
762
+ span?.setAttributes({
763
+ "drizzle.query.text": query.sql,
764
+ "drizzle.query.params": JSON.stringify(query.params)
765
+ });
766
+ return query;
767
+ });
768
+ }
769
+ buildQueryFromSourceParams(chunks, _config) {
770
+ const config = Object.assign({}, _config, {
771
+ inlineParams: _config.inlineParams || this.shouldInlineParams,
772
+ paramStartIndex: _config.paramStartIndex || { value: 0 }
773
+ });
774
+ const {
775
+ casing,
776
+ escapeName,
777
+ escapeParam,
778
+ prepareTyping,
779
+ inlineParams,
780
+ paramStartIndex
781
+ } = config;
782
+ return mergeQueries(chunks.map((chunk) => {
783
+ if (is(chunk, StringChunk)) {
784
+ return { sql: chunk.value.join(""), params: [] };
785
+ }
786
+ if (is(chunk, Name)) {
787
+ return { sql: escapeName(chunk.value), params: [] };
788
+ }
789
+ if (chunk === void 0) {
790
+ return { sql: "", params: [] };
791
+ }
792
+ if (Array.isArray(chunk)) {
793
+ const result = [new StringChunk("(")];
794
+ for (const [i, p] of chunk.entries()) {
795
+ result.push(p);
796
+ if (i < chunk.length - 1) {
797
+ result.push(new StringChunk(", "));
798
+ }
799
+ }
800
+ result.push(new StringChunk(")"));
801
+ return this.buildQueryFromSourceParams(result, config);
802
+ }
803
+ if (is(chunk, _SQL)) {
804
+ return this.buildQueryFromSourceParams(chunk.queryChunks, {
805
+ ...config,
806
+ inlineParams: inlineParams || chunk.shouldInlineParams
807
+ });
808
+ }
809
+ if (is(chunk, Table)) {
810
+ const schemaName = chunk[Table.Symbol.Schema];
811
+ const tableName = chunk[Table.Symbol.Name];
812
+ return {
813
+ sql: schemaName === void 0 ? escapeName(tableName) : escapeName(schemaName) + "." + escapeName(tableName),
814
+ params: []
815
+ };
816
+ }
817
+ if (is(chunk, Column)) {
818
+ const columnName = casing.getColumnCasing(chunk);
819
+ if (_config.invokeSource === "indexes") {
820
+ return { sql: escapeName(columnName), params: [] };
821
+ }
822
+ const schemaName = chunk.table[Table.Symbol.Schema];
823
+ return {
824
+ sql: chunk.table[IsAlias] || schemaName === void 0 ? escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName) : escapeName(schemaName) + "." + escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName),
825
+ params: []
826
+ };
827
+ }
828
+ if (is(chunk, View)) {
829
+ const schemaName = chunk[ViewBaseConfig].schema;
830
+ const viewName = chunk[ViewBaseConfig].name;
831
+ return {
832
+ sql: schemaName === void 0 ? escapeName(viewName) : escapeName(schemaName) + "." + escapeName(viewName),
833
+ params: []
834
+ };
835
+ }
836
+ if (is(chunk, Param)) {
837
+ if (is(chunk.value, Placeholder)) {
838
+ return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
839
+ }
840
+ const mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value);
841
+ if (is(mappedValue, _SQL)) {
842
+ return this.buildQueryFromSourceParams([mappedValue], config);
843
+ }
844
+ if (inlineParams) {
845
+ return { sql: this.mapInlineParam(mappedValue, config), params: [] };
846
+ }
847
+ let typings = ["none"];
848
+ if (prepareTyping) {
849
+ typings = [prepareTyping(chunk.encoder)];
850
+ }
851
+ return { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings };
852
+ }
853
+ if (is(chunk, Placeholder)) {
854
+ return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
855
+ }
856
+ if (is(chunk, _SQL.Aliased) && chunk.fieldAlias !== void 0) {
857
+ return { sql: escapeName(chunk.fieldAlias), params: [] };
858
+ }
859
+ if (is(chunk, Subquery)) {
860
+ if (chunk._.isWith) {
861
+ return { sql: escapeName(chunk._.alias), params: [] };
862
+ }
863
+ return this.buildQueryFromSourceParams([
864
+ new StringChunk("("),
865
+ chunk._.sql,
866
+ new StringChunk(") "),
867
+ new Name(chunk._.alias)
868
+ ], config);
869
+ }
870
+ if (isPgEnum(chunk)) {
871
+ if (chunk.schema) {
872
+ return { sql: escapeName(chunk.schema) + "." + escapeName(chunk.enumName), params: [] };
873
+ }
874
+ return { sql: escapeName(chunk.enumName), params: [] };
875
+ }
876
+ if (isSQLWrapper(chunk)) {
877
+ if (chunk.shouldOmitSQLParens?.()) {
878
+ return this.buildQueryFromSourceParams([chunk.getSQL()], config);
879
+ }
880
+ return this.buildQueryFromSourceParams([
881
+ new StringChunk("("),
882
+ chunk.getSQL(),
883
+ new StringChunk(")")
884
+ ], config);
885
+ }
886
+ if (inlineParams) {
887
+ return { sql: this.mapInlineParam(chunk, config), params: [] };
888
+ }
889
+ return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
890
+ }));
891
+ }
892
+ mapInlineParam(chunk, { escapeString }) {
893
+ if (chunk === null) {
894
+ return "null";
895
+ }
896
+ if (typeof chunk === "number" || typeof chunk === "boolean") {
897
+ return chunk.toString();
898
+ }
899
+ if (typeof chunk === "string") {
900
+ return escapeString(chunk);
901
+ }
902
+ if (typeof chunk === "object") {
903
+ const mappedValueAsString = chunk.toString();
904
+ if (mappedValueAsString === "[object Object]") {
905
+ return escapeString(JSON.stringify(chunk));
906
+ }
907
+ return escapeString(mappedValueAsString);
908
+ }
909
+ throw new Error("Unexpected param value: " + chunk);
910
+ }
911
+ getSQL() {
912
+ return this;
913
+ }
914
+ as(alias) {
915
+ if (alias === void 0) {
916
+ return this;
917
+ }
918
+ return new _SQL.Aliased(this, alias);
919
+ }
920
+ mapWith(decoder) {
921
+ this.decoder = typeof decoder === "function" ? { mapFromDriverValue: decoder } : decoder;
922
+ return this;
923
+ }
924
+ inlineParams() {
925
+ this.shouldInlineParams = true;
926
+ return this;
927
+ }
928
+ /**
929
+ * This method is used to conditionally include a part of the query.
930
+ *
931
+ * @param condition - Condition to check
932
+ * @returns itself if the condition is `true`, otherwise `undefined`
933
+ */
934
+ if(condition) {
935
+ return condition ? this : void 0;
936
+ }
937
+ };
938
+ var Name = class {
939
+ constructor(value) {
940
+ this.value = value;
941
+ }
942
+ static [entityKind] = "Name";
943
+ brand;
944
+ getSQL() {
945
+ return new SQL([this]);
946
+ }
947
+ };
948
+ var noopDecoder = {
949
+ mapFromDriverValue: (value) => value
950
+ };
951
+ var noopEncoder = {
952
+ mapToDriverValue: (value) => value
953
+ };
954
+ var noopMapper = {
955
+ ...noopDecoder,
956
+ ...noopEncoder
957
+ };
958
+ var Param = class {
959
+ /**
960
+ * @param value - Parameter value
961
+ * @param encoder - Encoder to convert the value to a driver parameter
962
+ */
963
+ constructor(value, encoder = noopEncoder) {
964
+ this.value = value;
965
+ this.encoder = encoder;
966
+ }
967
+ static [entityKind] = "Param";
968
+ brand;
969
+ getSQL() {
970
+ return new SQL([this]);
971
+ }
972
+ };
973
+ function sql(strings, ...params) {
974
+ const queryChunks = [];
975
+ if (params.length > 0 || strings.length > 0 && strings[0] !== "") {
976
+ queryChunks.push(new StringChunk(strings[0]));
977
+ }
978
+ for (const [paramIndex, param2] of params.entries()) {
979
+ queryChunks.push(param2, new StringChunk(strings[paramIndex + 1]));
980
+ }
981
+ return new SQL(queryChunks);
982
+ }
983
+ ((sql2) => {
984
+ function empty() {
985
+ return new SQL([]);
986
+ }
987
+ sql2.empty = empty;
988
+ function fromList(list) {
989
+ return new SQL(list);
990
+ }
991
+ sql2.fromList = fromList;
992
+ function raw(str) {
993
+ return new SQL([new StringChunk(str)]);
994
+ }
995
+ sql2.raw = raw;
996
+ function join(chunks, separator) {
997
+ const result = [];
998
+ for (const [i, chunk] of chunks.entries()) {
999
+ if (i > 0 && separator !== void 0) {
1000
+ result.push(separator);
1001
+ }
1002
+ result.push(chunk);
1003
+ }
1004
+ return new SQL(result);
1005
+ }
1006
+ sql2.join = join;
1007
+ function identifier(value) {
1008
+ return new Name(value);
1009
+ }
1010
+ sql2.identifier = identifier;
1011
+ function placeholder2(name2) {
1012
+ return new Placeholder(name2);
1013
+ }
1014
+ sql2.placeholder = placeholder2;
1015
+ function param2(value, encoder) {
1016
+ return new Param(value, encoder);
1017
+ }
1018
+ sql2.param = param2;
1019
+ })(sql || (sql = {}));
1020
+ ((SQL2) => {
1021
+ class Aliased {
1022
+ constructor(sql2, fieldAlias) {
1023
+ this.sql = sql2;
1024
+ this.fieldAlias = fieldAlias;
1025
+ }
1026
+ static [entityKind] = "SQL.Aliased";
1027
+ /** @internal */
1028
+ isSelectionField = false;
1029
+ getSQL() {
1030
+ return this.sql;
1031
+ }
1032
+ /** @internal */
1033
+ clone() {
1034
+ return new Aliased(this.sql, this.fieldAlias);
1035
+ }
1036
+ }
1037
+ SQL2.Aliased = Aliased;
1038
+ })(SQL || (SQL = {}));
1039
+ var Placeholder = class {
1040
+ constructor(name2) {
1041
+ this.name = name2;
1042
+ }
1043
+ static [entityKind] = "Placeholder";
1044
+ getSQL() {
1045
+ return new SQL([this]);
1046
+ }
1047
+ };
1048
+ var View = class {
1049
+ static [entityKind] = "View";
1050
+ /** @internal */
1051
+ [ViewBaseConfig];
1052
+ constructor({ name: name2, schema, selectedFields, query }) {
1053
+ this[ViewBaseConfig] = {
1054
+ name: name2,
1055
+ originalName: name2,
1056
+ schema,
1057
+ selectedFields,
1058
+ query,
1059
+ isExisting: !query,
1060
+ isAlias: false
1061
+ };
1062
+ }
1063
+ getSQL() {
1064
+ return new SQL([this]);
1065
+ }
1066
+ };
1067
+ Column.prototype.getSQL = function() {
1068
+ return new SQL([this]);
1069
+ };
1070
+ Table.prototype.getSQL = function() {
1071
+ return new SQL([this]);
1072
+ };
1073
+ Subquery.prototype.getSQL = function() {
1074
+ return new SQL([this]);
1075
+ };
1076
+
1077
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/utils.js
1078
+ function getColumnNameAndConfig(a, b) {
1079
+ return {
1080
+ name: typeof a === "string" && a.length > 0 ? a : "",
1081
+ config: typeof a === "object" ? a : b
1082
+ };
1083
+ }
1084
+
1085
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/sqlite-core/foreign-keys.js
1086
+ var ForeignKeyBuilder2 = class {
1087
+ static [entityKind] = "SQLiteForeignKeyBuilder";
1088
+ /** @internal */
1089
+ reference;
1090
+ /** @internal */
1091
+ _onUpdate;
1092
+ /** @internal */
1093
+ _onDelete;
1094
+ constructor(config, actions) {
1095
+ this.reference = () => {
1096
+ const { name, columns, foreignColumns } = config();
1097
+ return { name, columns, foreignTable: foreignColumns[0].table, foreignColumns };
1098
+ };
1099
+ if (actions) {
1100
+ this._onUpdate = actions.onUpdate;
1101
+ this._onDelete = actions.onDelete;
1102
+ }
1103
+ }
1104
+ onUpdate(action) {
1105
+ this._onUpdate = action;
1106
+ return this;
1107
+ }
1108
+ onDelete(action) {
1109
+ this._onDelete = action;
1110
+ return this;
1111
+ }
1112
+ /** @internal */
1113
+ build(table) {
1114
+ return new ForeignKey2(table, this);
1115
+ }
1116
+ };
1117
+ var ForeignKey2 = class {
1118
+ constructor(table, builder) {
1119
+ this.table = table;
1120
+ this.reference = builder.reference;
1121
+ this.onUpdate = builder._onUpdate;
1122
+ this.onDelete = builder._onDelete;
1123
+ }
1124
+ static [entityKind] = "SQLiteForeignKey";
1125
+ reference;
1126
+ onUpdate;
1127
+ onDelete;
1128
+ getName() {
1129
+ const { name, columns, foreignColumns } = this.reference();
1130
+ const columnNames = columns.map((column) => column.name);
1131
+ const foreignColumnNames = foreignColumns.map((column) => column.name);
1132
+ const chunks = [
1133
+ this.table[TableName],
1134
+ ...columnNames,
1135
+ foreignColumns[0].table[TableName],
1136
+ ...foreignColumnNames
1137
+ ];
1138
+ return name ?? `${chunks.join("_")}_fk`;
1139
+ }
1140
+ };
1141
+
1142
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/sqlite-core/unique-constraint.js
1143
+ function uniqueKeyName2(table, columns) {
1144
+ return `${table[TableName]}_${columns.join("_")}_unique`;
1145
+ }
1146
+ var UniqueConstraintBuilder2 = class {
1147
+ constructor(columns, name) {
1148
+ this.name = name;
1149
+ this.columns = columns;
1150
+ }
1151
+ static [entityKind] = "SQLiteUniqueConstraintBuilder";
1152
+ /** @internal */
1153
+ columns;
1154
+ /** @internal */
1155
+ build(table) {
1156
+ return new UniqueConstraint2(table, this.columns, this.name);
1157
+ }
1158
+ };
1159
+ var UniqueOnConstraintBuilder2 = class {
1160
+ static [entityKind] = "SQLiteUniqueOnConstraintBuilder";
1161
+ /** @internal */
1162
+ name;
1163
+ constructor(name) {
1164
+ this.name = name;
1165
+ }
1166
+ on(...columns) {
1167
+ return new UniqueConstraintBuilder2(columns, this.name);
1168
+ }
1169
+ };
1170
+ var UniqueConstraint2 = class {
1171
+ constructor(table, columns, name) {
1172
+ this.table = table;
1173
+ this.columns = columns;
1174
+ this.name = name ?? uniqueKeyName2(this.table, this.columns.map((column) => column.name));
1175
+ }
1176
+ static [entityKind] = "SQLiteUniqueConstraint";
1177
+ columns;
1178
+ name;
1179
+ getName() {
1180
+ return this.name;
1181
+ }
1182
+ };
1183
+
1184
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/sqlite-core/columns/common.js
1185
+ var SQLiteColumnBuilder = class extends ColumnBuilder {
1186
+ static [entityKind] = "SQLiteColumnBuilder";
1187
+ foreignKeyConfigs = [];
1188
+ references(ref, actions = {}) {
1189
+ this.foreignKeyConfigs.push({ ref, actions });
1190
+ return this;
1191
+ }
1192
+ unique(name) {
1193
+ this.config.isUnique = true;
1194
+ this.config.uniqueName = name;
1195
+ return this;
1196
+ }
1197
+ generatedAlwaysAs(as, config) {
1198
+ this.config.generated = {
1199
+ as,
1200
+ type: "always",
1201
+ mode: config?.mode ?? "virtual"
1202
+ };
1203
+ return this;
1204
+ }
1205
+ /** @internal */
1206
+ buildForeignKeys(column, table) {
1207
+ return this.foreignKeyConfigs.map(({ ref, actions }) => {
1208
+ return ((ref2, actions2) => {
1209
+ const builder = new ForeignKeyBuilder2(() => {
1210
+ const foreignColumn = ref2();
1211
+ return { columns: [column], foreignColumns: [foreignColumn] };
1212
+ });
1213
+ if (actions2.onUpdate) {
1214
+ builder.onUpdate(actions2.onUpdate);
1215
+ }
1216
+ if (actions2.onDelete) {
1217
+ builder.onDelete(actions2.onDelete);
1218
+ }
1219
+ return builder.build(table);
1220
+ })(ref, actions);
1221
+ });
1222
+ }
1223
+ };
1224
+ var SQLiteColumn = class extends Column {
1225
+ constructor(table, config) {
1226
+ if (!config.uniqueName) {
1227
+ config.uniqueName = uniqueKeyName2(table, [config.name]);
1228
+ }
1229
+ super(table, config);
1230
+ this.table = table;
1231
+ }
1232
+ static [entityKind] = "SQLiteColumn";
1233
+ };
1234
+
1235
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/sqlite-core/columns/blob.js
1236
+ var SQLiteBigIntBuilder = class extends SQLiteColumnBuilder {
1237
+ static [entityKind] = "SQLiteBigIntBuilder";
1238
+ constructor(name) {
1239
+ super(name, "bigint", "SQLiteBigInt");
1240
+ }
1241
+ /** @internal */
1242
+ build(table) {
1243
+ return new SQLiteBigInt(table, this.config);
1244
+ }
1245
+ };
1246
+ var SQLiteBigInt = class extends SQLiteColumn {
1247
+ static [entityKind] = "SQLiteBigInt";
1248
+ getSQLType() {
1249
+ return "blob";
1250
+ }
1251
+ mapFromDriverValue(value) {
1252
+ return BigInt(Buffer.isBuffer(value) ? value.toString() : String.fromCodePoint(...value));
1253
+ }
1254
+ mapToDriverValue(value) {
1255
+ return Buffer.from(value.toString());
1256
+ }
1257
+ };
1258
+ var SQLiteBlobJsonBuilder = class extends SQLiteColumnBuilder {
1259
+ static [entityKind] = "SQLiteBlobJsonBuilder";
1260
+ constructor(name) {
1261
+ super(name, "json", "SQLiteBlobJson");
1262
+ }
1263
+ /** @internal */
1264
+ build(table) {
1265
+ return new SQLiteBlobJson(
1266
+ table,
1267
+ this.config
1268
+ );
1269
+ }
1270
+ };
1271
+ var SQLiteBlobJson = class extends SQLiteColumn {
1272
+ static [entityKind] = "SQLiteBlobJson";
1273
+ getSQLType() {
1274
+ return "blob";
1275
+ }
1276
+ mapFromDriverValue(value) {
1277
+ return JSON.parse(Buffer.isBuffer(value) ? value.toString() : String.fromCodePoint(...value));
1278
+ }
1279
+ mapToDriverValue(value) {
1280
+ return Buffer.from(JSON.stringify(value));
1281
+ }
1282
+ };
1283
+ var SQLiteBlobBufferBuilder = class extends SQLiteColumnBuilder {
1284
+ static [entityKind] = "SQLiteBlobBufferBuilder";
1285
+ constructor(name) {
1286
+ super(name, "buffer", "SQLiteBlobBuffer");
1287
+ }
1288
+ /** @internal */
1289
+ build(table) {
1290
+ return new SQLiteBlobBuffer(table, this.config);
1291
+ }
1292
+ };
1293
+ var SQLiteBlobBuffer = class extends SQLiteColumn {
1294
+ static [entityKind] = "SQLiteBlobBuffer";
1295
+ getSQLType() {
1296
+ return "blob";
1297
+ }
1298
+ };
1299
+ function blob(a, b) {
1300
+ const { name, config } = getColumnNameAndConfig(a, b);
1301
+ if (config?.mode === "json") {
1302
+ return new SQLiteBlobJsonBuilder(name);
1303
+ }
1304
+ if (config?.mode === "bigint") {
1305
+ return new SQLiteBigIntBuilder(name);
1306
+ }
1307
+ return new SQLiteBlobBufferBuilder(name);
1308
+ }
1309
+
1310
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/sqlite-core/columns/custom.js
1311
+ var SQLiteCustomColumnBuilder = class extends SQLiteColumnBuilder {
1312
+ static [entityKind] = "SQLiteCustomColumnBuilder";
1313
+ constructor(name, fieldConfig, customTypeParams) {
1314
+ super(name, "custom", "SQLiteCustomColumn");
1315
+ this.config.fieldConfig = fieldConfig;
1316
+ this.config.customTypeParams = customTypeParams;
1317
+ }
1318
+ /** @internal */
1319
+ build(table) {
1320
+ return new SQLiteCustomColumn(
1321
+ table,
1322
+ this.config
1323
+ );
1324
+ }
1325
+ };
1326
+ var SQLiteCustomColumn = class extends SQLiteColumn {
1327
+ static [entityKind] = "SQLiteCustomColumn";
1328
+ sqlName;
1329
+ mapTo;
1330
+ mapFrom;
1331
+ constructor(table, config) {
1332
+ super(table, config);
1333
+ this.sqlName = config.customTypeParams.dataType(config.fieldConfig);
1334
+ this.mapTo = config.customTypeParams.toDriver;
1335
+ this.mapFrom = config.customTypeParams.fromDriver;
1336
+ }
1337
+ getSQLType() {
1338
+ return this.sqlName;
1339
+ }
1340
+ mapFromDriverValue(value) {
1341
+ return typeof this.mapFrom === "function" ? this.mapFrom(value) : value;
1342
+ }
1343
+ mapToDriverValue(value) {
1344
+ return typeof this.mapTo === "function" ? this.mapTo(value) : value;
1345
+ }
1346
+ };
1347
+ function customType(customTypeParams) {
1348
+ return (a, b) => {
1349
+ const { name, config } = getColumnNameAndConfig(a, b);
1350
+ return new SQLiteCustomColumnBuilder(
1351
+ name,
1352
+ config,
1353
+ customTypeParams
1354
+ );
1355
+ };
1356
+ }
1357
+
1358
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/sqlite-core/columns/integer.js
1359
+ var SQLiteBaseIntegerBuilder = class extends SQLiteColumnBuilder {
1360
+ static [entityKind] = "SQLiteBaseIntegerBuilder";
1361
+ constructor(name, dataType, columnType) {
1362
+ super(name, dataType, columnType);
1363
+ this.config.autoIncrement = false;
1364
+ }
1365
+ primaryKey(config) {
1366
+ if (config?.autoIncrement) {
1367
+ this.config.autoIncrement = true;
1368
+ }
1369
+ this.config.hasDefault = true;
1370
+ return super.primaryKey();
1371
+ }
1372
+ };
1373
+ var SQLiteBaseInteger = class extends SQLiteColumn {
1374
+ static [entityKind] = "SQLiteBaseInteger";
1375
+ autoIncrement = this.config.autoIncrement;
1376
+ getSQLType() {
1377
+ return "integer";
1378
+ }
1379
+ };
1380
+ var SQLiteIntegerBuilder = class extends SQLiteBaseIntegerBuilder {
1381
+ static [entityKind] = "SQLiteIntegerBuilder";
1382
+ constructor(name) {
1383
+ super(name, "number", "SQLiteInteger");
1384
+ }
1385
+ build(table) {
1386
+ return new SQLiteInteger(
1387
+ table,
1388
+ this.config
1389
+ );
1390
+ }
1391
+ };
1392
+ var SQLiteInteger = class extends SQLiteBaseInteger {
1393
+ static [entityKind] = "SQLiteInteger";
1394
+ };
1395
+ var SQLiteTimestampBuilder = class extends SQLiteBaseIntegerBuilder {
1396
+ static [entityKind] = "SQLiteTimestampBuilder";
1397
+ constructor(name, mode) {
1398
+ super(name, "date", "SQLiteTimestamp");
1399
+ this.config.mode = mode;
1400
+ }
1401
+ /**
1402
+ * @deprecated Use `default()` with your own expression instead.
1403
+ *
1404
+ * Adds `DEFAULT (cast((julianday('now') - 2440587.5)*86400000 as integer))` to the column, which is the current epoch timestamp in milliseconds.
1405
+ */
1406
+ defaultNow() {
1407
+ return this.default(sql`(cast((julianday('now') - 2440587.5)*86400000 as integer))`);
1408
+ }
1409
+ build(table) {
1410
+ return new SQLiteTimestamp(
1411
+ table,
1412
+ this.config
1413
+ );
1414
+ }
1415
+ };
1416
+ var SQLiteTimestamp = class extends SQLiteBaseInteger {
1417
+ static [entityKind] = "SQLiteTimestamp";
1418
+ mode = this.config.mode;
1419
+ mapFromDriverValue(value) {
1420
+ if (this.config.mode === "timestamp") {
1421
+ return new Date(value * 1e3);
1422
+ }
1423
+ return new Date(value);
1424
+ }
1425
+ mapToDriverValue(value) {
1426
+ const unix = value.getTime();
1427
+ if (this.config.mode === "timestamp") {
1428
+ return Math.floor(unix / 1e3);
1429
+ }
1430
+ return unix;
1431
+ }
1432
+ };
1433
+ var SQLiteBooleanBuilder = class extends SQLiteBaseIntegerBuilder {
1434
+ static [entityKind] = "SQLiteBooleanBuilder";
1435
+ constructor(name, mode) {
1436
+ super(name, "boolean", "SQLiteBoolean");
1437
+ this.config.mode = mode;
1438
+ }
1439
+ build(table) {
1440
+ return new SQLiteBoolean(
1441
+ table,
1442
+ this.config
1443
+ );
1444
+ }
1445
+ };
1446
+ var SQLiteBoolean = class extends SQLiteBaseInteger {
1447
+ static [entityKind] = "SQLiteBoolean";
1448
+ mode = this.config.mode;
1449
+ mapFromDriverValue(value) {
1450
+ return Number(value) === 1;
1451
+ }
1452
+ mapToDriverValue(value) {
1453
+ return value ? 1 : 0;
1454
+ }
1455
+ };
1456
+ function integer(a, b) {
1457
+ const { name, config } = getColumnNameAndConfig(a, b);
1458
+ if (config?.mode === "timestamp" || config?.mode === "timestamp_ms") {
1459
+ return new SQLiteTimestampBuilder(name, config.mode);
1460
+ }
1461
+ if (config?.mode === "boolean") {
1462
+ return new SQLiteBooleanBuilder(name, config.mode);
1463
+ }
1464
+ return new SQLiteIntegerBuilder(name);
1465
+ }
1466
+
1467
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/sqlite-core/columns/numeric.js
1468
+ var SQLiteNumericBuilder = class extends SQLiteColumnBuilder {
1469
+ static [entityKind] = "SQLiteNumericBuilder";
1470
+ constructor(name) {
1471
+ super(name, "string", "SQLiteNumeric");
1472
+ }
1473
+ /** @internal */
1474
+ build(table) {
1475
+ return new SQLiteNumeric(
1476
+ table,
1477
+ this.config
1478
+ );
1479
+ }
1480
+ };
1481
+ var SQLiteNumeric = class extends SQLiteColumn {
1482
+ static [entityKind] = "SQLiteNumeric";
1483
+ getSQLType() {
1484
+ return "numeric";
1485
+ }
1486
+ };
1487
+ function numeric(name) {
1488
+ return new SQLiteNumericBuilder(name ?? "");
1489
+ }
1490
+
1491
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/sqlite-core/columns/real.js
1492
+ var SQLiteRealBuilder = class extends SQLiteColumnBuilder {
1493
+ static [entityKind] = "SQLiteRealBuilder";
1494
+ constructor(name) {
1495
+ super(name, "number", "SQLiteReal");
1496
+ }
1497
+ /** @internal */
1498
+ build(table) {
1499
+ return new SQLiteReal(table, this.config);
1500
+ }
1501
+ };
1502
+ var SQLiteReal = class extends SQLiteColumn {
1503
+ static [entityKind] = "SQLiteReal";
1504
+ getSQLType() {
1505
+ return "real";
1506
+ }
1507
+ };
1508
+ function real(name) {
1509
+ return new SQLiteRealBuilder(name ?? "");
1510
+ }
1511
+
1512
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/sqlite-core/columns/text.js
1513
+ var SQLiteTextBuilder = class extends SQLiteColumnBuilder {
1514
+ static [entityKind] = "SQLiteTextBuilder";
1515
+ constructor(name, config) {
1516
+ super(name, "string", "SQLiteText");
1517
+ this.config.enumValues = config.enum;
1518
+ this.config.length = config.length;
1519
+ }
1520
+ /** @internal */
1521
+ build(table) {
1522
+ return new SQLiteText(table, this.config);
1523
+ }
1524
+ };
1525
+ var SQLiteText = class extends SQLiteColumn {
1526
+ static [entityKind] = "SQLiteText";
1527
+ enumValues = this.config.enumValues;
1528
+ length = this.config.length;
1529
+ constructor(table, config) {
1530
+ super(table, config);
1531
+ }
1532
+ getSQLType() {
1533
+ return `text${this.config.length ? `(${this.config.length})` : ""}`;
1534
+ }
1535
+ };
1536
+ var SQLiteTextJsonBuilder = class extends SQLiteColumnBuilder {
1537
+ static [entityKind] = "SQLiteTextJsonBuilder";
1538
+ constructor(name) {
1539
+ super(name, "json", "SQLiteTextJson");
1540
+ }
1541
+ /** @internal */
1542
+ build(table) {
1543
+ return new SQLiteTextJson(
1544
+ table,
1545
+ this.config
1546
+ );
1547
+ }
1548
+ };
1549
+ var SQLiteTextJson = class extends SQLiteColumn {
1550
+ static [entityKind] = "SQLiteTextJson";
1551
+ getSQLType() {
1552
+ return "text";
1553
+ }
1554
+ mapFromDriverValue(value) {
1555
+ return JSON.parse(value);
1556
+ }
1557
+ mapToDriverValue(value) {
1558
+ return JSON.stringify(value);
1559
+ }
1560
+ };
1561
+ function text(a, b = {}) {
1562
+ const { name, config } = getColumnNameAndConfig(a, b);
1563
+ if (config.mode === "json") {
1564
+ return new SQLiteTextJsonBuilder(name);
1565
+ }
1566
+ return new SQLiteTextBuilder(name, config);
1567
+ }
1568
+
1569
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/sqlite-core/columns/all.js
1570
+ function getSQLiteColumnBuilders() {
1571
+ return {
1572
+ blob,
1573
+ customType,
1574
+ integer,
1575
+ numeric,
1576
+ real,
1577
+ text
1578
+ };
1579
+ }
1580
+
1581
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/sqlite-core/table.js
1582
+ var InlineForeignKeys = /* @__PURE__ */ Symbol.for("drizzle:SQLiteInlineForeignKeys");
1583
+ var SQLiteTable = class extends Table {
1584
+ static [entityKind] = "SQLiteTable";
1585
+ /** @internal */
1586
+ static Symbol = Object.assign({}, Table.Symbol, {
1587
+ InlineForeignKeys
1588
+ });
1589
+ /** @internal */
1590
+ [Table.Symbol.Columns];
1591
+ /** @internal */
1592
+ [InlineForeignKeys] = [];
1593
+ /** @internal */
1594
+ [Table.Symbol.ExtraConfigBuilder] = void 0;
1595
+ };
1596
+ function sqliteTableBase(name, columns, extraConfig, schema, baseName = name) {
1597
+ const rawTable = new SQLiteTable(name, schema, baseName);
1598
+ const parsedColumns = typeof columns === "function" ? columns(getSQLiteColumnBuilders()) : columns;
1599
+ const builtColumns = Object.fromEntries(
1600
+ Object.entries(parsedColumns).map(([name2, colBuilderBase]) => {
1601
+ const colBuilder = colBuilderBase;
1602
+ colBuilder.setName(name2);
1603
+ const column = colBuilder.build(rawTable);
1604
+ rawTable[InlineForeignKeys].push(...colBuilder.buildForeignKeys(column, rawTable));
1605
+ return [name2, column];
1606
+ })
1607
+ );
1608
+ const table = Object.assign(rawTable, builtColumns);
1609
+ table[Table.Symbol.Columns] = builtColumns;
1610
+ table[Table.Symbol.ExtraConfigColumns] = builtColumns;
1611
+ if (extraConfig) {
1612
+ table[SQLiteTable.Symbol.ExtraConfigBuilder] = extraConfig;
1613
+ }
1614
+ return table;
1615
+ }
1616
+ var sqliteTable = (name, columns, extraConfig) => {
1617
+ return sqliteTableBase(name, columns, extraConfig);
1618
+ };
1619
+
1620
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/sqlite-core/indexes.js
1621
+ var IndexBuilderOn = class {
1622
+ constructor(name, unique) {
1623
+ this.name = name;
1624
+ this.unique = unique;
1625
+ }
1626
+ static [entityKind] = "SQLiteIndexBuilderOn";
1627
+ on(...columns) {
1628
+ return new IndexBuilder(this.name, columns, this.unique);
1629
+ }
1630
+ };
1631
+ var IndexBuilder = class {
1632
+ static [entityKind] = "SQLiteIndexBuilder";
1633
+ /** @internal */
1634
+ config;
1635
+ constructor(name, columns, unique) {
1636
+ this.config = {
1637
+ name,
1638
+ columns,
1639
+ unique,
1640
+ where: void 0
1641
+ };
1642
+ }
1643
+ /**
1644
+ * Condition for partial index.
1645
+ */
1646
+ where(condition) {
1647
+ this.config.where = condition;
1648
+ return this;
1649
+ }
1650
+ /** @internal */
1651
+ build(table) {
1652
+ return new Index(this.config, table);
1653
+ }
1654
+ };
1655
+ var Index = class {
1656
+ static [entityKind] = "SQLiteIndex";
1657
+ config;
1658
+ constructor(config, table) {
1659
+ this.config = { ...config, table };
1660
+ }
1661
+ };
1662
+ function index(name) {
1663
+ return new IndexBuilderOn(name, false);
1664
+ }
1665
+ function uniqueIndex(name) {
1666
+ return new IndexBuilderOn(name, true);
1667
+ }
1668
+
1669
+ // ../../node_modules/.pnpm/drizzle-orm@0.36.4_@cloudflare+workers-types@4.20260416.2_@types+better-sqlite3@7.6.13__6bda8a68f3e10d0b03cd2031bac7989c/node_modules/drizzle-orm/sqlite-core/primary-keys.js
1670
+ function primaryKey(...config) {
1671
+ if (config[0].columns) {
1672
+ return new PrimaryKeyBuilder(config[0].columns, config[0].name);
1673
+ }
1674
+ return new PrimaryKeyBuilder(config);
1675
+ }
1676
+ var PrimaryKeyBuilder = class {
1677
+ static [entityKind] = "SQLitePrimaryKeyBuilder";
1678
+ /** @internal */
1679
+ columns;
1680
+ /** @internal */
1681
+ name;
1682
+ constructor(columns, name) {
1683
+ this.columns = columns;
1684
+ this.name = name;
1685
+ }
1686
+ /** @internal */
1687
+ build(table) {
1688
+ return new PrimaryKey(table, this.columns, this.name);
1689
+ }
1690
+ };
1691
+ var PrimaryKey = class {
1692
+ constructor(table, columns, name) {
1693
+ this.table = table;
1694
+ this.columns = columns;
1695
+ this.name = name;
1696
+ }
1697
+ static [entityKind] = "SQLitePrimaryKey";
1698
+ columns;
1699
+ name;
1700
+ getName() {
1701
+ return this.name ?? `${this.table[SQLiteTable.Symbol.Name]}_${this.columns.map((column) => column.name).join("_")}_pk`;
1702
+ }
1703
+ };
1704
+
1705
+ // ../core/src/db/schema.ts
1706
+ var projects = sqliteTable(
1707
+ "projects",
1708
+ {
1709
+ id: text("id").primaryKey(),
1710
+ name: text("name").notNull(),
1711
+ domain: text("domain"),
1712
+ ownerEmail: text("owner_email").notNull(),
1713
+ plan: text("plan", { enum: ["free", "paid"] }).notNull().default("free"),
1714
+ status: text("status", { enum: ["active", "inactive"] }).notNull().default("active"),
1715
+ // Stripe billing
1716
+ stripeCustomerId: text("stripe_customer_id").unique(),
1717
+ stripeSubscriptionId: text("stripe_subscription_id").unique(),
1718
+ stripeItemIdBase: text("stripe_item_id_base"),
1719
+ stripeItemIdExperiments: text("stripe_item_id_experiments"),
1720
+ stripeItemIdGates: text("stripe_item_id_gates"),
1721
+ stripeItemIdConfigs: text("stripe_item_id_configs"),
1722
+ subscriptionStatus: text("subscription_status", {
1723
+ enum: ["none", "trialing", "active", "past_due", "canceled", "incomplete"]
1724
+ }).notNull().default("none"),
1725
+ currentPeriodEnd: text("current_period_end"),
1726
+ trialEndsAt: text("trial_ends_at"),
1727
+ cancelAtPeriodEnd: integer("cancel_at_period_end").notNull().default(0),
1728
+ billingInterval: text("billing_interval", { enum: ["monthly", "annual"] }).notNull().default("monthly"),
1729
+ // Per-project module toggles. Control which surfaces (admin tabs, devtools
1730
+ // panels) are exposed for this project. All default to enabled so existing
1731
+ // projects keep their full feature set after the migration.
1732
+ moduleTranslations: integer("module_translations", { mode: "boolean" }).notNull().default(true),
1733
+ moduleConfigs: integer("module_configs", { mode: "boolean" }).notNull().default(true),
1734
+ moduleGates: integer("module_gates", { mode: "boolean" }).notNull().default(true),
1735
+ moduleExperiments: integer("module_experiments", { mode: "boolean" }).notNull().default(true),
1736
+ moduleFeedback: integer("module_feedback", { mode: "boolean" }).notNull().default(true),
1737
+ moduleUser: integer("module_user", { mode: "boolean" }).notNull().default(true),
1738
+ moduleEvents: integer("module_events", { mode: "boolean" }).notNull().default(true),
1739
+ createdAt: text("created_at").notNull(),
1740
+ updatedAt: text("updated_at").notNull()
1741
+ },
1742
+ (t) => ({
1743
+ // One project per (owner, domain): a single account can't accidentally
1744
+ // create two projects pointing at the same site. Multiple projects per
1745
+ // owner are still allowed across different domains, and `domain` may be
1746
+ // NULL for projects without a configured site (SQLite treats each NULL
1747
+ // as distinct under UNIQUE, so multiple no-domain projects per owner are
1748
+ // permitted).
1749
+ ownerDomainUniq: uniqueIndex("projects_owner_domain_uniq").on(t.ownerEmail, t.domain)
1750
+ })
1751
+ );
1752
+ var users = sqliteTable("users", {
1753
+ email: text("email").primaryKey(),
1754
+ termsAcceptedAt: text("terms_accepted_at"),
1755
+ termsVersion: text("terms_version"),
1756
+ onboardingCompletedAt: text("onboarding_completed_at"),
1757
+ createdAt: text("created_at").notNull(),
1758
+ updatedAt: text("updated_at").notNull()
1759
+ });
1760
+ var projectMembers = sqliteTable(
1761
+ "project_members",
1762
+ {
1763
+ id: text("id").primaryKey(),
1764
+ projectId: text("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
1765
+ email: text("email").notNull(),
1766
+ role: text("role", { enum: ["admin", "editor", "viewer"] }).notNull().default("editor"),
1767
+ status: text("status", { enum: ["active", "pending", "removed"] }).notNull().default("pending"),
1768
+ invitedByEmail: text("invited_by_email").notNull(),
1769
+ invitedAt: text("invited_at").notNull(),
1770
+ acceptedAt: text("accepted_at"),
1771
+ removedAt: text("removed_at")
1772
+ },
1773
+ (t) => ({
1774
+ projectIdx: index("project_members_project").on(t.projectId, t.status),
1775
+ projectEmailUniq: uniqueIndex("project_members_project_email").on(t.projectId, t.email)
1776
+ })
1777
+ );
1778
+ var sdkKeys = sqliteTable(
1779
+ "sdk_keys",
1780
+ {
1781
+ id: text("id").primaryKey(),
1782
+ projectId: text("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
1783
+ keyHash: text("key_hash").unique().notNull(),
1784
+ type: text("type", { enum: ["server", "client", "admin"] }).notNull(),
1785
+ scope: text("scope", { enum: ["experiments", "i18n"] }).notNull().default("experiments"),
1786
+ createdAt: text("created_at").notNull(),
1787
+ revokedAt: text("revoked_at"),
1788
+ expiresAt: text("expires_at"),
1789
+ // Email of the human who minted this key (admin keys via dashboard or
1790
+ // CLI device-flow). Used to authorize cross-project --project overrides
1791
+ // by joining against project_members. Null for older keys + for
1792
+ // service-to-service keys without a human owner.
1793
+ createdByEmail: text("created_by_email")
1794
+ },
1795
+ (t) => ({ hashIdx: index("sdk_keys_hash").on(t.keyHash) })
1796
+ );
1797
+ var cliAuthSessions = sqliteTable(
1798
+ "cli_auth_sessions",
1799
+ {
1800
+ state: text("state").primaryKey(),
1801
+ codeChallenge: text("code_challenge").notNull(),
1802
+ projectId: text("project_id").references(() => projects.id),
1803
+ tokenHash: text("token_hash"),
1804
+ status: text("status", { enum: ["pending", "complete", "expired"] }).notNull().default("pending"),
1805
+ createdAt: text("created_at").notNull(),
1806
+ expiresAt: text("expires_at").notNull(),
1807
+ completedAt: text("completed_at")
1808
+ },
1809
+ (t) => ({ expiresIdx: index("cli_auth_sessions_expires").on(t.expiresAt) })
1810
+ );
1811
+ var cliTokens = sqliteTable(
1812
+ "cli_tokens",
1813
+ {
1814
+ tokenId: text("token_id").primaryKey(),
1815
+ projectId: text("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
1816
+ userEmail: text("user_email").notNull(),
1817
+ issuedAt: text("issued_at").notNull(),
1818
+ expiresAt: text("expires_at").notNull(),
1819
+ revokedAt: text("revoked_at"),
1820
+ lastUsedAt: text("last_used_at")
1821
+ },
1822
+ (t) => ({
1823
+ projectIdx: index("cli_tokens_project").on(t.projectId),
1824
+ expiresIdx: index("cli_tokens_expires").on(t.expiresAt)
1825
+ })
1826
+ );
1827
+ var analysisFailures = sqliteTable("analysis_failures", {
1828
+ projectId: text("project_id").primaryKey().references(() => projects.id),
1829
+ failedAt: text("failed_at").notNull(),
1830
+ retryCount: integer("retry_count").notNull().default(3),
1831
+ messageBody: text("message_body"),
1832
+ resolvedAt: text("resolved_at")
1833
+ });
1834
+ var systemHealth = sqliteTable("system_health", {
1835
+ key: text("key").primaryKey(),
1836
+ lastFiredAt: text("last_fired_at").notNull(),
1837
+ projectsEnqueued: integer("projects_enqueued")
1838
+ });
1839
+ var auditLog = sqliteTable(
1840
+ "audit_log",
1841
+ {
1842
+ id: text("id").primaryKey(),
1843
+ projectId: text("project_id").notNull().references(() => projects.id),
1844
+ actorEmail: text("actor_email").notNull(),
1845
+ actorType: text("actor_type", { enum: ["user", "cli", "system"] }).notNull(),
1846
+ action: text("action").notNull(),
1847
+ resourceType: text("resource_type").notNull(),
1848
+ resourceId: text("resource_id"),
1849
+ payload: text("payload"),
1850
+ createdAt: text("created_at").notNull()
1851
+ },
1852
+ (t) => ({
1853
+ projectIdx: index("audit_log_project").on(t.projectId, t.createdAt),
1854
+ actorIdx: index("audit_log_actor").on(t.actorEmail),
1855
+ resourceIdx: index("audit_log_resource").on(t.resourceType, t.resourceId)
1856
+ })
1857
+ );
1858
+ var gates = sqliteTable(
1859
+ "gates",
1860
+ {
1861
+ id: text("id").primaryKey(),
1862
+ projectId: text("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
1863
+ name: text("name").notNull(),
1864
+ rules: text("rules", { mode: "json" }).$type().notNull(),
1865
+ rolloutPct: integer("rollout_pct").notNull().default(0),
1866
+ salt: text("salt").notNull(),
1867
+ enabled: integer("enabled").notNull().default(1),
1868
+ // Gatekeeper metadata + ordered sub-gate stack. Stack is null on rows that
1869
+ // predate the gatekeeper migration; eval falls back to rules+rolloutPct.
1870
+ title: text("title"),
1871
+ description: text("description"),
1872
+ folder: text("folder"),
1873
+ groupName: text("group_name"),
1874
+ ownerEmail: text("owner_email"),
1875
+ stack: text("stack", { mode: "json" }).$type(),
1876
+ updatedAt: text("updated_at").notNull(),
1877
+ deletedAt: text("deleted_at")
1878
+ },
1879
+ (t) => ({
1880
+ projectIdx: index("gates_project").on(t.projectId),
1881
+ projectNameUniq: uniqueIndex("gates_project_name").on(t.projectId, t.name).where(sql`deleted_at is null`)
1882
+ })
1883
+ );
1884
+ var CONFIG_ENVS = ["dev", "staging", "prod"];
1885
+ var CONFIG_KINDS = ["config", "killswitch"];
1886
+ var DEFAULT_CONFIG_SCHEMA = {
1887
+ type: "object",
1888
+ properties: {},
1889
+ additionalProperties: true
1890
+ };
1891
+ var configs = sqliteTable(
1892
+ "configs",
1893
+ {
1894
+ id: text("id").primaryKey(),
1895
+ projectId: text("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
1896
+ name: text("name").notNull(),
1897
+ description: text("description"),
1898
+ kind: text("kind", { enum: CONFIG_KINDS }).notNull().default("config"),
1899
+ schemaJson: text("schema_json", { mode: "json" }).$type().notNull().default(DEFAULT_CONFIG_SCHEMA),
1900
+ updatedAt: text("updated_at").notNull(),
1901
+ deletedAt: text("deleted_at")
1902
+ },
1903
+ (t) => ({
1904
+ uniq: uniqueIndex("configs_project_name").on(t.projectId, t.name).where(sql`deleted_at is null`)
1905
+ })
1906
+ );
1907
+ var configValues = sqliteTable(
1908
+ "config_values",
1909
+ {
1910
+ id: text("id").primaryKey(),
1911
+ projectId: text("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
1912
+ configId: text("config_id").notNull().references(() => configs.id, { onDelete: "cascade" }),
1913
+ env: text("env", { enum: CONFIG_ENVS }).notNull(),
1914
+ valueJson: text("value_json", { mode: "json" }).$type().notNull(),
1915
+ version: integer("version").notNull(),
1916
+ publishedAt: text("published_at").notNull(),
1917
+ publishedBy: text("published_by").notNull()
1918
+ },
1919
+ (t) => ({
1920
+ projectIdx: index("config_values_project").on(t.projectId),
1921
+ configEnvIdx: index("config_values_config_env").on(t.configId, t.env, t.version),
1922
+ uniq: uniqueIndex("config_values_config_env_version").on(t.configId, t.env, t.version)
1923
+ })
1924
+ );
1925
+ var configDrafts = sqliteTable(
1926
+ "config_drafts",
1927
+ {
1928
+ id: text("id").primaryKey(),
1929
+ projectId: text("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
1930
+ configId: text("config_id").notNull().references(() => configs.id, { onDelete: "cascade" }),
1931
+ env: text("env", { enum: CONFIG_ENVS }).notNull(),
1932
+ valueJson: text("value_json", { mode: "json" }).$type().notNull(),
1933
+ baseVersion: integer("base_version").notNull(),
1934
+ authorEmail: text("author_email").notNull(),
1935
+ createdAt: text("created_at").notNull(),
1936
+ updatedAt: text("updated_at").notNull()
1937
+ },
1938
+ (t) => ({
1939
+ projectIdx: index("config_drafts_project").on(t.projectId),
1940
+ uniq: uniqueIndex("config_drafts_config_env").on(t.configId, t.env)
1941
+ })
1942
+ );
1943
+ var universes = sqliteTable(
1944
+ "universes",
1945
+ {
1946
+ id: text("id").primaryKey(),
1947
+ projectId: text("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
1948
+ name: text("name").notNull(),
1949
+ unitType: text("unit_type").notNull().default("user_id"),
1950
+ holdoutRange: text("holdout_range", { mode: "json" }).$type(),
1951
+ createdAt: text("created_at").notNull(),
1952
+ deletedAt: text("deleted_at")
1953
+ },
1954
+ (t) => ({
1955
+ projectIdx: index("universes_project").on(t.projectId),
1956
+ projectUniq: uniqueIndex("universes_project_name").on(t.projectId, t.name).where(sql`deleted_at is null`)
1957
+ })
1958
+ );
1959
+ var experiments = sqliteTable(
1960
+ "experiments",
1961
+ {
1962
+ id: text("id").primaryKey(),
1963
+ projectId: text("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
1964
+ name: text("name").notNull(),
1965
+ description: text("description"),
1966
+ tag: text("tag"),
1967
+ universe: text("universe").notNull(),
1968
+ targetingGate: text("targeting_gate"),
1969
+ allocationPct: integer("allocation_pct").notNull().default(0),
1970
+ salt: text("salt").notNull(),
1971
+ params: text("params", { mode: "json" }).$type().notNull(),
1972
+ groups: text("groups", { mode: "json" }).$type().notNull(),
1973
+ status: text("status", { enum: ["draft", "running", "stopped", "archived"] }).notNull().default("draft"),
1974
+ startedAt: text("started_at"),
1975
+ stoppedAt: text("stopped_at"),
1976
+ significanceThreshold: real("significance_threshold").notNull().default(0.05),
1977
+ minRuntimeDays: integer("min_runtime_days").notNull().default(0),
1978
+ minSampleSize: integer("min_sample_size").notNull().default(100),
1979
+ cupedFrozenAt: text("cuped_frozen_at"),
1980
+ sequentialTesting: integer("sequential_testing", { mode: "boolean" }).notNull().default(false),
1981
+ hashVersion: integer("hash_version").notNull().default(1),
1982
+ updatedAt: text("updated_at").notNull()
1983
+ },
1984
+ (t) => ({
1985
+ projectIdx: index("experiments_project").on(t.projectId),
1986
+ projectUniq: uniqueIndex("experiments_project_name").on(t.projectId, t.name)
1987
+ })
1988
+ );
1989
+ var events = sqliteTable(
1990
+ "events",
1991
+ {
1992
+ id: text("id").primaryKey(),
1993
+ projectId: text("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
1994
+ name: text("name").notNull(),
1995
+ description: text("description"),
1996
+ properties: text("properties", { mode: "json" }).$type().notNull().default([]),
1997
+ pending: integer("pending").notNull().default(0),
1998
+ createdAt: text("created_at").notNull(),
1999
+ deletedAt: text("deleted_at")
2000
+ },
2001
+ (t) => ({
2002
+ projectIdx: index("events_project").on(t.projectId),
2003
+ projectUniq: uniqueIndex("events_project_name").on(t.projectId, t.name).where(sql`deleted_at is null`)
2004
+ })
2005
+ );
2006
+ var metrics = sqliteTable(
2007
+ "metrics",
2008
+ {
2009
+ id: text("id").primaryKey(),
2010
+ projectId: text("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
2011
+ name: text("name").notNull(),
2012
+ eventName: text("event_name").notNull(),
2013
+ valuePath: text("value_path"),
2014
+ aggregation: text("aggregation", {
2015
+ enum: ["count_users", "count_events", "sum", "avg", "retention_Nd"]
2016
+ }).notNull().default("count_users"),
2017
+ winsorizePct: integer("winsorize_pct").notNull().default(99),
2018
+ minDetectableEffect: real("min_detectable_effect"),
2019
+ updatedAt: text("updated_at").notNull(),
2020
+ deletedAt: text("deleted_at")
2021
+ },
2022
+ (t) => ({
2023
+ uniq: uniqueIndex("metrics_project_name").on(t.projectId, t.name).where(sql`deleted_at is null`)
2024
+ })
2025
+ );
2026
+ var experimentMetrics = sqliteTable(
2027
+ "experiment_metrics",
2028
+ {
2029
+ id: text("id").primaryKey(),
2030
+ experimentId: text("experiment_id").notNull().references(() => experiments.id, { onDelete: "cascade" }),
2031
+ metricId: text("metric_id").notNull().references(() => metrics.id, { onDelete: "cascade" }),
2032
+ role: text("role", { enum: ["goal", "guardrail", "secondary"] }).notNull(),
2033
+ createdAt: integer("created_at").notNull()
2034
+ },
2035
+ (t) => ({ uniq: uniqueIndex("exp_metrics_uniq").on(t.experimentId, t.metricId) })
2036
+ );
2037
+ var experimentResults = sqliteTable(
2038
+ "experiment_results",
2039
+ {
2040
+ projectId: text("project_id").notNull(),
2041
+ experiment: text("experiment").notNull(),
2042
+ metric: text("metric").notNull(),
2043
+ groupName: text("group_name").notNull(),
2044
+ ds: text("ds").notNull(),
2045
+ n: integer("n"),
2046
+ mean: real("mean"),
2047
+ variance: real("variance"),
2048
+ delta: real("delta"),
2049
+ deltaPct: real("delta_pct"),
2050
+ ci95Low: real("ci_95_low"),
2051
+ ci95High: real("ci_95_high"),
2052
+ ci99Low: real("ci_99_low"),
2053
+ ci99High: real("ci_99_high"),
2054
+ pValue: real("p_value"),
2055
+ expectedN: integer("expected_n"),
2056
+ srmPValue: real("srm_p_value"),
2057
+ srmDetected: integer("srm_detected").notNull().default(0),
2058
+ msprtLambda: real("msprt_lambda"),
2059
+ msprtSignificant: integer("msprt_significant"),
2060
+ isFinal: integer("is_final").notNull().default(0),
2061
+ peekWarning: integer("peek_warning").notNull().default(0)
2062
+ },
2063
+ (t) => ({
2064
+ pk: primaryKey({ columns: [t.projectId, t.experiment, t.metric, t.groupName, t.ds] }),
2065
+ dsIdx: index("experiment_results_ds").on(t.projectId, t.ds)
2066
+ })
2067
+ );
2068
+ var userMetricBaseline = sqliteTable(
2069
+ "user_metric_baseline",
2070
+ {
2071
+ projectId: text("project_id").notNull(),
2072
+ userId: text("user_id").notNull(),
2073
+ metricName: text("metric_name").notNull(),
2074
+ avgValue: real("avg_value").notNull(),
2075
+ updatedDs: text("updated_ds").notNull()
2076
+ },
2077
+ (t) => ({ pk: primaryKey({ columns: [t.projectId, t.userId, t.metricName] }) })
2078
+ );
2079
+ var userAliases = sqliteTable(
2080
+ "user_aliases",
2081
+ {
2082
+ projectId: text("project_id").notNull(),
2083
+ anonymousId: text("anonymous_id").notNull(),
2084
+ userId: text("user_id").notNull(),
2085
+ createdAt: text("created_at").notNull()
2086
+ },
2087
+ (t) => ({
2088
+ pk: primaryKey({ columns: [t.projectId, t.anonymousId] }),
2089
+ userIdx: index("user_aliases_user").on(t.projectId, t.userId)
2090
+ })
2091
+ );
2092
+ var userAttributes = sqliteTable(
2093
+ "user_attributes",
2094
+ {
2095
+ id: text("id").primaryKey(),
2096
+ projectId: text("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
2097
+ name: text("name").notNull(),
2098
+ type: text("type", { enum: ["string", "number", "boolean", "enum", "date"] }).notNull(),
2099
+ enumValues: text("enum_values", { mode: "json" }).$type(),
2100
+ required: integer("required").notNull().default(0),
2101
+ description: text("description"),
2102
+ sdkPath: text("sdk_path"),
2103
+ createdAt: text("created_at").notNull(),
2104
+ deletedAt: text("deleted_at")
2105
+ },
2106
+ (t) => ({
2107
+ projectIdx: index("user_attributes_project").on(t.projectId),
2108
+ projectUniq: uniqueIndex("user_attributes_project_name").on(t.projectId, t.name).where(sql`deleted_at is null`)
2109
+ })
2110
+ );
2111
+ var labelProfiles = sqliteTable(
2112
+ "label_profiles",
2113
+ {
2114
+ id: text("id").primaryKey(),
2115
+ projectId: text("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
2116
+ name: text("name").notNull(),
2117
+ defaultChunkId: text("default_chunk_id"),
2118
+ createdAt: text("created_at").notNull(),
2119
+ deletedAt: text("deleted_at")
2120
+ },
2121
+ (t) => ({
2122
+ projectIdx: index("label_profiles_project").on(t.projectId),
2123
+ projectNameUniq: uniqueIndex("label_profiles_project_name").on(t.projectId, t.name).where(sql`deleted_at is null`)
2124
+ })
2125
+ );
2126
+ var labelChunks = sqliteTable(
2127
+ "label_chunks",
2128
+ {
2129
+ id: text("id").primaryKey(),
2130
+ projectId: text("project_id").notNull(),
2131
+ profileId: text("profile_id").notNull().references(() => labelProfiles.id, { onDelete: "cascade" }),
2132
+ name: text("name").notNull(),
2133
+ isIndex: integer("is_index").notNull().default(0),
2134
+ publishedUrl: text("published_url"),
2135
+ publishedHash: text("published_hash"),
2136
+ publishedAt: text("published_at"),
2137
+ etag: text("etag")
2138
+ },
2139
+ (t) => ({
2140
+ projectIdx: index("label_chunks_project").on(t.projectId),
2141
+ profileNameUniq: uniqueIndex("label_chunks_profile_name").on(t.profileId, t.name)
2142
+ })
2143
+ );
2144
+ var labelKeys = sqliteTable(
2145
+ "label_keys",
2146
+ {
2147
+ id: text("id").primaryKey(),
2148
+ projectId: text("project_id").notNull(),
2149
+ profileId: text("profile_id").notNull().references(() => labelProfiles.id, { onDelete: "cascade" }),
2150
+ chunkId: text("chunk_id").notNull().references(() => labelChunks.id, { onDelete: "cascade" }),
2151
+ key: text("key").notNull(),
2152
+ value: text("value").notNull(),
2153
+ description: text("description"),
2154
+ // JSON array of variable names extracted from the value's {{var}} placeholders.
2155
+ // `null` = no variables detected; `[]` = explicitly none (normalized).
2156
+ variables: text("variables", { mode: "json" }).$type(),
2157
+ updatedAt: text("updated_at").notNull(),
2158
+ updatedBy: text("updated_by").notNull()
2159
+ },
2160
+ (t) => ({
2161
+ projectIdx: index("label_keys_project").on(t.projectId),
2162
+ chunkIdx: index("label_keys_chunk").on(t.chunkId),
2163
+ profileKeyUniq: uniqueIndex("label_keys_profile_key").on(t.profileId, t.key)
2164
+ })
2165
+ );
2166
+ var labelDrafts = sqliteTable(
2167
+ "label_drafts",
2168
+ {
2169
+ id: text("id").primaryKey(),
2170
+ projectId: text("project_id").notNull(),
2171
+ profileId: text("profile_id").notNull().references(() => labelProfiles.id, { onDelete: "cascade" }),
2172
+ name: text("name").notNull(),
2173
+ sourceProfileId: text("source_profile_id").references(() => labelProfiles.id, {
2174
+ onDelete: "set null"
2175
+ }),
2176
+ createdBy: text("created_by").notNull(),
2177
+ status: text("status", { enum: ["open", "merged", "abandoned"] }).notNull().default("open"),
2178
+ createdAt: text("created_at").notNull(),
2179
+ publishedAt: text("published_at")
2180
+ },
2181
+ (t) => ({
2182
+ projectIdx: index("label_drafts_project").on(t.projectId),
2183
+ projectNameUniq: uniqueIndex("label_drafts_project_name").on(t.projectId, t.name)
2184
+ })
2185
+ );
2186
+ var labelDraftKeys = sqliteTable(
2187
+ "label_draft_keys",
2188
+ {
2189
+ id: text("id").primaryKey(),
2190
+ projectId: text("project_id").notNull(),
2191
+ draftId: text("draft_id").notNull().references(() => labelDrafts.id, { onDelete: "cascade" }),
2192
+ key: text("key").notNull(),
2193
+ value: text("value").notNull(),
2194
+ description: text("description"),
2195
+ variables: text("variables", { mode: "json" }).$type(),
2196
+ updatedBy: text("updated_by").notNull(),
2197
+ updatedAt: text("updated_at").notNull()
2198
+ },
2199
+ (t) => ({
2200
+ draftKeyUniq: uniqueIndex("label_draft_keys_draft_key").on(t.draftId, t.key),
2201
+ projectIdx: index("label_draft_keys_project").on(t.projectId)
2202
+ })
2203
+ );
2204
+ var BUG_STATUSES = ["open", "triaged", "in_progress", "resolved", "wont_fix"];
2205
+ var BUG_PRIORITIES = ["low", "medium", "high", "critical"];
2206
+ var bugReports = sqliteTable(
2207
+ "bug_reports",
2208
+ {
2209
+ id: text("id").primaryKey(),
2210
+ projectId: text("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
2211
+ title: text("title").notNull(),
2212
+ stepsToReproduce: text("steps_to_reproduce").notNull().default(""),
2213
+ actualResult: text("actual_result").notNull().default(""),
2214
+ expectedResult: text("expected_result").notNull().default(""),
2215
+ status: text("status", { enum: BUG_STATUSES }).notNull().default("open"),
2216
+ priority: text("priority", { enum: BUG_PRIORITIES }),
2217
+ reporterEmail: text("reporter_email"),
2218
+ pageUrl: text("page_url"),
2219
+ userAgent: text("user_agent"),
2220
+ viewport: text("viewport"),
2221
+ context: text("context", { mode: "json" }).$type(),
2222
+ createdAt: text("created_at").notNull(),
2223
+ updatedAt: text("updated_at").notNull()
2224
+ },
2225
+ (t) => ({
2226
+ projectIdx: index("bug_reports_project").on(t.projectId, t.status),
2227
+ createdIdx: index("bug_reports_created").on(t.projectId, t.createdAt)
2228
+ })
2229
+ );
2230
+ var FEATURE_REQUEST_STATUSES = [
2231
+ "open",
2232
+ "considering",
2233
+ "planned",
2234
+ "shipped",
2235
+ "declined"
2236
+ ];
2237
+ var FEATURE_REQUEST_IMPORTANCES = ["nice_to_have", "important", "critical"];
2238
+ var featureRequests = sqliteTable(
2239
+ "feature_requests",
2240
+ {
2241
+ id: text("id").primaryKey(),
2242
+ projectId: text("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
2243
+ title: text("title").notNull(),
2244
+ description: text("description").notNull().default(""),
2245
+ useCase: text("use_case").notNull().default(""),
2246
+ importance: text("importance", { enum: FEATURE_REQUEST_IMPORTANCES }).notNull().default("nice_to_have"),
2247
+ status: text("status", { enum: FEATURE_REQUEST_STATUSES }).notNull().default("open"),
2248
+ reporterEmail: text("reporter_email"),
2249
+ pageUrl: text("page_url"),
2250
+ userAgent: text("user_agent"),
2251
+ context: text("context", { mode: "json" }).$type(),
2252
+ createdAt: text("created_at").notNull(),
2253
+ updatedAt: text("updated_at").notNull()
2254
+ },
2255
+ (t) => ({
2256
+ projectIdx: index("feature_requests_project").on(t.projectId, t.status),
2257
+ createdIdx: index("feature_requests_created").on(t.projectId, t.createdAt)
2258
+ })
2259
+ );
2260
+ var REPORT_KINDS = ["bug", "feature_request"];
2261
+ var ATTACHMENT_KINDS = ["screenshot", "recording", "file"];
2262
+ var reportAttachments = sqliteTable(
2263
+ "report_attachments",
2264
+ {
2265
+ id: text("id").primaryKey(),
2266
+ projectId: text("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
2267
+ reportKind: text("report_kind", { enum: REPORT_KINDS }).notNull(),
2268
+ reportId: text("report_id").notNull(),
2269
+ kind: text("kind", { enum: ATTACHMENT_KINDS }).notNull(),
2270
+ filename: text("filename").notNull(),
2271
+ mimeType: text("mime_type").notNull(),
2272
+ sizeBytes: integer("size_bytes").notNull(),
2273
+ r2Key: text("r2_key").notNull(),
2274
+ createdAt: text("created_at").notNull()
2275
+ },
2276
+ (t) => ({
2277
+ reportIdx: index("report_attachments_report").on(t.projectId, t.reportKind, t.reportId)
2278
+ })
2279
+ );
2280
+ var CONNECTOR_PROVIDERS = ["google_sheets"];
2281
+ var connectors = sqliteTable(
2282
+ "connectors",
2283
+ {
2284
+ id: text("id").primaryKey(),
2285
+ projectId: text("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
2286
+ provider: text("provider", { enum: CONNECTOR_PROVIDERS }).notNull(),
2287
+ name: text("name").notNull(),
2288
+ enabled: integer("enabled", { mode: "boolean" }).notNull().default(true),
2289
+ events: text("events", { mode: "json" }).$type().notNull(),
2290
+ config: text("config", { mode: "json" }).$type().notNull(),
2291
+ // AES-GCM encrypted JSON: { refresh_token, access_token, expires_at, scope }
2292
+ credentialsCipher: text("credentials_cipher"),
2293
+ // Display label (e.g., the OAuth account email)
2294
+ accountLabel: text("account_label"),
2295
+ createdAt: text("created_at").notNull(),
2296
+ updatedAt: text("updated_at").notNull()
2297
+ },
2298
+ (t) => ({
2299
+ projectIdx: index("connectors_project").on(t.projectId, t.provider)
2300
+ })
2301
+ );
2302
+ var i18nUsageDaily = sqliteTable(
2303
+ "i18n_usage_daily",
2304
+ {
2305
+ projectId: text("project_id").notNull(),
2306
+ sdkKeyId: text("sdk_key_id").notNull(),
2307
+ date: text("date").notNull(),
2308
+ requestCount: integer("request_count").notNull().default(0)
2309
+ },
2310
+ (t) => ({
2311
+ pk: primaryKey({ columns: [t.projectId, t.sdkKeyId, t.date] }),
2312
+ projectDateIdx: index("i18n_usage_daily_project_date").on(t.projectId, t.date)
2313
+ })
2314
+ );
2315
+ var billingEvents = sqliteTable(
2316
+ "billing_events",
2317
+ {
2318
+ // Stripe event ID — INSERT OR IGNORE makes webhook handling idempotent
2319
+ id: text("id").primaryKey(),
2320
+ projectId: text("project_id").references(() => projects.id, { onDelete: "set null" }),
2321
+ type: text("type").notNull(),
2322
+ payload: text("payload", { mode: "json" }).$type().notNull(),
2323
+ receivedAt: text("received_at").notNull()
2324
+ },
2325
+ (t) => ({
2326
+ projectIdx: index("billing_events_project").on(t.projectId)
2327
+ })
2328
+ );
2329
+
2330
+ // ../core/src/schemas/configs.ts
2331
+ var SEGMENT = /^[a-z0-9](?:[a-z0-9_-]*[a-z0-9])?$/;
2332
+ var RESERVED_FOLDER = "_default";
2333
+ var configNameSchema = z.string().max(128).refine(
2334
+ (s) => {
2335
+ const parts = s.split(".");
2336
+ if (parts.length !== 2) return false;
2337
+ return parts.every((p, i) => p === RESERVED_FOLDER && i === 0 ? true : SEGMENT.test(p));
2338
+ },
2339
+ {
2340
+ message: "Must be `folder.name` \u2014 exactly two lowercase segments separated by a dot (e.g. `pricing.tiers`)."
2341
+ }
2342
+ ).describe(
2343
+ "Stable config key in `folder.name` form (two lowercase segments separated by a dot, e.g. `pricing.tiers`). Used by SDKs as `Shipeasy.getConfig('<name>')`. Immutable after create."
2344
+ );
2345
+ var configKindSchema = z.enum(CONFIG_KINDS);
2346
+ var configEnvSchema = z.enum(CONFIG_ENVS).describe("Target environment. One of the project's configured envs (`dev`, `stage`, `prod`).");
2347
+ var jsonSchemaSchema = z.record(z.string(), z.unknown()).refine((s) => s.type === "object", { message: "Top-level schema type must be 'object'" }).describe(
2348
+ "JSON Schema (draft 2020-12) describing the shape of the config value. Top-level `type` must be `'object'`; every published value is validated against this schema."
2349
+ );
2350
+ var initialValuesSchema = z.union([z.unknown(), z.record(configEnvSchema, z.unknown())]).describe(
2351
+ "Initial config value. Either a single JSON object applied to every env, or a `{ env: value }` map seeding per-env values. Must match `schema`. Defaults to `{}` on every env when omitted."
2352
+ );
2353
+ var configCreateSchema = z.object({
2354
+ name: configNameSchema,
2355
+ description: z.string().max(512).optional().describe("Optional free-form description shown in the dashboard. Max 512 chars."),
2356
+ schema: jsonSchemaSchema,
2357
+ value: initialValuesSchema.optional()
2358
+ }).describe("Body for `POST /api/admin/configs`. `name` + `schema` required.");
2359
+ var configUpdateSchema = z.object({
2360
+ schema: jsonSchemaSchema.optional().describe(
2361
+ "Replacement schema. When supplied, the new schema is validated against every published value before it lands."
2362
+ ),
2363
+ value: z.unknown().optional().describe(
2364
+ "Flat value applied to **every** env. Publishes a new version per env. To target one env, use `PUT /{id}/drafts` then `POST /{id}/publish`."
2365
+ )
2366
+ }).describe(
2367
+ "Body for `PATCH /api/admin/configs/{id}`. Partial \u2014 only supplied fields change. `value` republishes on every env."
2368
+ );
2369
+ var configSchemaUpdateSchema = z.object({ schema: jsonSchemaSchema }).describe("Schema-only update. Does not bump value versions or rebuild KV.");
2370
+ var configDraftUpsertSchema = z.object({
2371
+ env: configEnvSchema,
2372
+ value: z.unknown().describe("Draft value to stage on `env`. Validated against the config's current schema.")
2373
+ }).describe(
2374
+ "Body for `PUT /api/admin/configs/{id}/drafts`. Stages a value for a single env without publishing."
2375
+ );
2376
+ var configPublishSchema = z.object({ env: configEnvSchema }).describe(
2377
+ "Body for `POST /api/admin/configs/{id}/publish` and `DELETE /api/admin/configs/{id}/drafts`. Names the target env."
2378
+ );
2379
+ var configEnvPublishedSchema = z.object({
2380
+ version: z.number().int().describe("Monotonically increasing version per env."),
2381
+ publishedAt: z.string().describe("ISO-8601 publish timestamp."),
2382
+ publishedBy: z.string().describe("Email/id of the actor who published this version.")
2383
+ });
2384
+ var configDraftSummarySchema = z.object({
2385
+ updatedAt: z.string().describe("ISO-8601 last-edit timestamp on the draft."),
2386
+ authorEmail: z.string().describe("Email/id of the actor who last edited the draft."),
2387
+ baseVersion: z.number().int().describe("Published version the draft was forked from.")
2388
+ });
2389
+ var configResponseSchema = z.object({
2390
+ id: z.string().describe("Stable opaque config id (`cfg_\u2026`)."),
2391
+ name: configNameSchema,
2392
+ description: z.string().nullable(),
2393
+ schema: jsonSchemaSchema,
2394
+ updatedAt: z.string().describe("ISO-8601 timestamp of last mutation."),
2395
+ envs: z.record(configEnvSchema, configEnvPublishedSchema).describe("Per-env latest published version metadata."),
2396
+ drafts: z.record(configEnvSchema, configDraftSummarySchema).describe("Per-env active drafts (if any)."),
2397
+ values: z.record(configEnvSchema, z.unknown()).optional().describe("Per-env latest published values (only returned by `GET /{id}`, not list)."),
2398
+ draftValues: z.record(configEnvSchema, z.unknown()).optional().describe("Per-env draft values (only returned by `GET /{id}`).")
2399
+ });
2400
+ var configCreateResponseSchema = z.object({
2401
+ id: z.string().describe("Newly assigned config id."),
2402
+ name: configNameSchema
2403
+ });
2404
+ var configUpdateResponseSchema = z.object({
2405
+ id: z.string().describe("Config id that was updated.")
2406
+ });
2407
+ var configDeleteResponseSchema = z.object({ ok: z.literal(true) });
2408
+ var configDraftSaveResponseSchema = z.object({
2409
+ id: z.string(),
2410
+ env: configEnvSchema,
2411
+ baseVersion: z.number().int().describe("Published version the draft is based on."),
2412
+ updatedAt: z.string()
2413
+ });
2414
+ var configDraftDiscardResponseSchema = z.object({ ok: z.literal(true) });
2415
+ var configPublishResponseSchema = z.object({
2416
+ id: z.string(),
2417
+ env: configEnvSchema,
2418
+ version: z.number().int().describe("Newly published version on `env`.")
2419
+ });
2420
+ var configActivityEntrySchema = z.object({
2421
+ id: z.string(),
2422
+ action: z.string().describe("Audit action (e.g. `config.create`, `config.publish`)."),
2423
+ actorEmail: z.string(),
2424
+ actorType: z.enum(["user", "cli", "system"]),
2425
+ payload: z.unknown().nullable(),
2426
+ createdAt: z.string().describe("ISO-8601 timestamp.")
2427
+ });
2428
+ var configActivityResponseSchema = z.array(configActivityEntrySchema).describe("Recent audit rows for one config, newest first.");
2429
+
2430
+ // ../core/src/schemas/killswitches.ts
2431
+ var switchKeySchema = z2.string().max(64).regex(/^[a-z0-9](?:[a-z0-9_-]*[a-z0-9])?$/, {
2432
+ message: "Switch keys must be lowercase, no dots."
2433
+ }).describe(
2434
+ "Single-segment switch key (lowercase letters, digits, `_`/`-`; no dots). Used as the nested switch entry inside a killswitch's `switches` map."
2435
+ );
2436
+ var killswitchValueSchema = z2.object({
2437
+ value: z2.boolean().describe(
2438
+ "Default boolean delivered when no `switches` entry matches the caller's switch key."
2439
+ ),
2440
+ switches: z2.record(switchKeySchema, z2.boolean()).optional().describe(
2441
+ "Per-switch overrides. When present, a matching key takes precedence over `value` on the client."
2442
+ )
2443
+ }).describe("Runtime killswitch payload returned to SDKs.");
2444
+ var killswitchCreateSchema = z2.object({
2445
+ name: configNameSchema.describe(
2446
+ "Stable killswitch key in `folder.name` form (two lowercase segments separated by a dot \u2014 e.g. `payments.checkout`). Immutable after create."
2447
+ ),
2448
+ description: z2.string().max(512).optional().describe("Optional free-form description shown in the dashboard. Max 512 chars."),
2449
+ value: z2.boolean().optional().describe(
2450
+ "Default value applied to every env at creation. Defaults to `false`. Use `true` to ship the killswitch pre-tripped."
2451
+ ),
2452
+ switches: z2.record(switchKeySchema, z2.boolean()).optional().describe(
2453
+ "Initial per-switch overrides applied to every env. Empty/omitted leaves the killswitch with only the flat `value`."
2454
+ )
2455
+ }).describe("Body for `POST /api/admin/killswitches`. Only `name` is required.");
2456
+ var killswitchUpdateSchema = z2.object({
2457
+ description: z2.string().max(512).nullish().describe("New description, or `null` to clear it. Max 512 chars."),
2458
+ value: z2.boolean().optional().describe(
2459
+ "Flat value applied to every env. Publishes a new version per env when set. Omit to leave values unchanged."
2460
+ ),
2461
+ switches: z2.record(switchKeySchema, z2.boolean()).optional().describe(
2462
+ "Replace the switches map wholesale on every env. To edit a single entry on a single env use `PUT /{id}/switch` instead."
2463
+ )
2464
+ }).describe(
2465
+ "Body for `PATCH /api/admin/killswitches/{id}`. Partial \u2014 only supplied fields change. `switches` replaces wholesale (no merge)."
2466
+ );
2467
+ var killswitchSwitchSetSchema = z2.object({
2468
+ env: configEnvSchema.describe("Target environment (`dev`/`stage`/`prod`)."),
2469
+ switchKey: switchKeySchema.describe("Switch key to set."),
2470
+ value: z2.boolean().describe("New boolean value for this `switchKey` on this `env`.")
2471
+ }).describe(
2472
+ "Body for `PUT /api/admin/killswitches/{id}/switch`. Sets or updates one switch entry on one env."
2473
+ );
2474
+ var killswitchSwitchUnsetSchema = z2.object({
2475
+ env: configEnvSchema.describe("Target environment."),
2476
+ switchKey: switchKeySchema.describe("Switch key to remove.")
2477
+ }).describe(
2478
+ "Body for `DELETE /api/admin/killswitches/{id}/switch`. Removes one switch entry from one env."
2479
+ );
2480
+ var killswitchEnvEntrySchema = z2.object({
2481
+ value: z2.boolean().describe("Flat boolean published for this env."),
2482
+ switches: z2.record(switchKeySchema, z2.boolean()).optional(),
2483
+ version: z2.number().int().describe("Monotonically increasing version per env."),
2484
+ publishedAt: z2.string().describe("ISO-8601 publish timestamp for this version.")
2485
+ });
2486
+ var killswitchResponseSchema = z2.object({
2487
+ id: z2.string().describe("Stable opaque killswitch id."),
2488
+ name: configNameSchema,
2489
+ description: z2.string().nullable().describe("Free-form description or `null`."),
2490
+ updatedAt: z2.string().describe("ISO-8601 timestamp of last mutation."),
2491
+ envs: z2.record(configEnvSchema, killswitchEnvEntrySchema).describe("Per-env latest value, switches, version, and publish timestamp.")
2492
+ });
2493
+ var killswitchCreateResponseSchema = z2.object({
2494
+ id: z2.string().describe("Newly assigned killswitch id."),
2495
+ name: configNameSchema
2496
+ });
2497
+ var killswitchUpdateResponseSchema = z2.object({
2498
+ id: z2.string().describe("Killswitch id that was updated.")
2499
+ });
2500
+ var killswitchDeleteResponseSchema = z2.object({ ok: z2.literal(true) });
2501
+ var killswitchSwitchSetResponseSchema = z2.object({
2502
+ id: z2.string(),
2503
+ env: configEnvSchema,
2504
+ switchKey: switchKeySchema,
2505
+ value: z2.boolean()
2506
+ });
2507
+ var killswitchSwitchUnsetResponseSchema = z2.object({
2508
+ id: z2.string(),
2509
+ env: configEnvSchema,
2510
+ switchKey: switchKeySchema,
2511
+ removed: z2.boolean().describe("`true` if the entry existed and was removed, `false` if no-op.")
2512
+ });
2513
+
2514
+ // src/transport.ts
2515
+ var ApiError = class extends Error {
2516
+ constructor(message, status) {
2517
+ super(message);
2518
+ this.status = status;
2519
+ this.name = "ApiError";
2520
+ }
2521
+ status;
2522
+ };
2523
+
2524
+ // src/resources/killswitches.ts
2525
+ var killswitchListResponseSchema = z3.object({
2526
+ data: z3.array(killswitchResponseSchema),
2527
+ next_cursor: z3.string().nullable()
2528
+ });
2529
+ var BASE = "/api/admin/killswitches";
2530
+ function killswitchesClient(t) {
2531
+ async function list(opts = {}) {
2532
+ const query = {};
2533
+ if (opts.limit !== void 0) query.limit = String(opts.limit);
2534
+ if (opts.cursor) query.cursor = opts.cursor;
2535
+ return t.request("GET", BASE, void 0, query);
2536
+ }
2537
+ async function listAll() {
2538
+ const out = [];
2539
+ let cursor;
2540
+ do {
2541
+ const page = await list({ limit: 500, cursor });
2542
+ out.push(...page.data);
2543
+ cursor = page.next_cursor ?? void 0;
2544
+ } while (cursor);
2545
+ return out;
2546
+ }
2547
+ async function resolve(idOrName) {
2548
+ try {
2549
+ return await t.request("GET", `${BASE}/${idOrName}`);
2550
+ } catch (err) {
2551
+ if (!(err instanceof ApiError) || err.status !== 404) throw err;
2552
+ }
2553
+ const all = await listAll();
2554
+ const found = all.find((k) => k.name === idOrName);
2555
+ if (!found) throw new ApiError(`Killswitch '${idOrName}' not found`, 404);
2556
+ return found;
2557
+ }
2558
+ return {
2559
+ list,
2560
+ listAll,
2561
+ resolve,
2562
+ get: (id) => t.request("GET", `${BASE}/${id}`),
2563
+ create: (input) => t.request("POST", BASE, killswitchCreateSchema.parse(input)),
2564
+ update: (id, input) => t.request("PATCH", `${BASE}/${id}`, killswitchUpdateSchema.parse(input)),
2565
+ delete: (id) => t.request("DELETE", `${BASE}/${id}`),
2566
+ setSwitch: (id, input) => t.request("PUT", `${BASE}/${id}/switch`, killswitchSwitchSetSchema.parse(input)),
2567
+ unsetSwitch: (id, input) => t.request("DELETE", `${BASE}/${id}/switch`, killswitchSwitchUnsetSchema.parse(input))
2568
+ };
2569
+ }
2570
+ var SAMPLE_KS = {
2571
+ id: "ksw_01j7w9d8h2k4m6n8p0q2r4s6t8",
2572
+ name: "payments.checkout",
2573
+ description: "Master kill for the checkout flow. Trip to fall back to the legacy provider.",
2574
+ updatedAt: "2026-05-09T18:22:11.000Z",
2575
+ envs: {
2576
+ dev: { value: false, version: 3, publishedAt: "2026-05-09T18:22:11.000Z" },
2577
+ stage: { value: false, version: 3, publishedAt: "2026-05-09T18:22:11.000Z" },
2578
+ prod: {
2579
+ value: false,
2580
+ switches: { eu_region: true },
2581
+ version: 5,
2582
+ publishedAt: "2026-05-09T18:22:11.000Z"
2583
+ }
2584
+ }
2585
+ };
2586
+ var killswitchesResource = {
2587
+ name: "killswitches",
2588
+ basePath: BASE,
2589
+ describeOne: "killswitch",
2590
+ describeMany: "killswitches",
2591
+ tag: {
2592
+ name: "Killswitches",
2593
+ description: [
2594
+ "Killswitches: per-env boolean overrides for kill-style operational toggles. Optimised for incident response \u2014 no rules, no rollout, just a flat boolean (plus optional per-key overrides) versioned per environment.",
2595
+ "",
2596
+ "**Identity.** Each killswitch is keyed by `name` in `folder.name` form (e.g. `payments.checkout`). Immutable after create.",
2597
+ "",
2598
+ "**Per-env values.** Every killswitch stores one version stream per env (`dev`, `stage`, `prod`). A `PATCH` with `value`/`switches` applies to **every** env in one shot (publishes a new version per env). To touch a single env, use `PUT /{id}/switch` and friends.",
2599
+ "",
2600
+ "**Switches map.** Optional `switches: { key: bool }` overrides the flat `value` for specific named call sites \u2014 useful for region/feature-scoped kills.",
2601
+ "",
2602
+ "**Versioning.** Each publish (create, update, set-switch, unset-switch) bumps the per-env `version` monotonically. SDKs deliver the latest published version."
2603
+ ].join("\n")
2604
+ },
2605
+ schemas: {
2606
+ create: killswitchCreateSchema,
2607
+ update: killswitchUpdateSchema,
2608
+ setSwitch: killswitchSwitchSetSchema,
2609
+ unsetSwitch: killswitchSwitchUnsetSchema
2610
+ },
2611
+ actions: [
2612
+ { name: "setSwitch", description: "Set or update one switch entry on one env" },
2613
+ { name: "unsetSwitch", description: "Remove one switch entry from one env" }
2614
+ ],
2615
+ endpoints: [
2616
+ {
2617
+ operationId: "listKillswitches",
2618
+ method: "GET",
2619
+ path: "",
2620
+ summary: "List killswitches",
2621
+ description: "Returns a single page of killswitches ordered by `updated_at desc, id desc`. Each row includes the latest published `value`/`switches`/`version` per env.",
2622
+ response: killswitchListResponseSchema,
2623
+ examples: { response: { data: [SAMPLE_KS], next_cursor: null } },
2624
+ useCase: "Snapshot every killswitch in the project \u2014 e.g. to render an incident-response runbook listing every kill and its current trip state."
2625
+ },
2626
+ {
2627
+ operationId: "getKillswitch",
2628
+ method: "GET",
2629
+ path: "/{id}",
2630
+ summary: "Get one killswitch",
2631
+ description: "Returns the killswitch metadata plus the latest published `value`/`switches`/`version` per env.",
2632
+ pathParams: { id: "Stable opaque killswitch id (`ksw_\u2026`)." },
2633
+ response: killswitchResponseSchema,
2634
+ examples: { response: SAMPLE_KS },
2635
+ useCase: "Fetch the current state of one killswitch \u2014 e.g. to verify a trip propagated before declaring an incident mitigated."
2636
+ },
2637
+ {
2638
+ operationId: "createKillswitch",
2639
+ method: "POST",
2640
+ path: "",
2641
+ summary: "Create a killswitch",
2642
+ description: [
2643
+ "Creates a new killswitch with `value` (default `false`) applied to **every** env at version 1.",
2644
+ "",
2645
+ "Returns `409` if `name` already exists in the project."
2646
+ ].join("\n"),
2647
+ successStatus: 201,
2648
+ request: killswitchCreateSchema,
2649
+ response: killswitchCreateResponseSchema,
2650
+ examples: {
2651
+ requestExamples: {
2652
+ minimal: {
2653
+ summary: "Minimal \u2014 name only, untripped",
2654
+ description: "Smallest valid body. Creates a killswitch with `value: false` on every env.",
2655
+ value: { name: "payments.checkout" }
2656
+ },
2657
+ preTripped: {
2658
+ summary: "Pre-tripped on create",
2659
+ description: "Ship the killswitch already tripped (`value: true`) \u2014 useful when provisioning a kill ahead of a deploy you want to ship with the feature off.",
2660
+ value: {
2661
+ name: "payments.checkout",
2662
+ description: "Master kill for the new checkout flow.",
2663
+ value: true
2664
+ }
2665
+ },
2666
+ withSwitches: {
2667
+ summary: "With per-region switches",
2668
+ description: "Seed a `switches` map so specific named call sites can be tripped independently of the flat `value`.",
2669
+ value: {
2670
+ name: "payments.checkout",
2671
+ value: false,
2672
+ switches: { eu_region: true, apac_region: false }
2673
+ }
2674
+ }
2675
+ },
2676
+ response: { id: "ksw_01j7w9d8h2k4m6n8p0q2r4s6t8", name: "payments.checkout" }
2677
+ },
2678
+ useCase: [
2679
+ '- **Untripped create** \u2014 `{ "name": "payments.checkout" }`. Provision the kill ahead of an incident.',
2680
+ '- **Pre-tripped** \u2014 `{ "value": true }` to ship the killswitch already engaged.',
2681
+ "- **With switches** \u2014 seed `switches` to carve out per-region/per-tenant kills from day one."
2682
+ ].join("\n")
2683
+ },
2684
+ {
2685
+ operationId: "updateKillswitch",
2686
+ method: "PATCH",
2687
+ path: "/{id}",
2688
+ summary: "Update a killswitch",
2689
+ description: [
2690
+ "Partial update applied to **every** env. Setting `value`/`switches` publishes a new version per env. Description-only patches don't bump versions.",
2691
+ "",
2692
+ "To change a single switch on a single env, use `PUT /{id}/switch` instead."
2693
+ ].join("\n"),
2694
+ pathParams: { id: "Stable opaque killswitch id." },
2695
+ request: killswitchUpdateSchema,
2696
+ response: killswitchUpdateResponseSchema,
2697
+ examples: {
2698
+ requestExamples: {
2699
+ trip: {
2700
+ summary: "Trip the killswitch on every env",
2701
+ description: "Sets `value: true` on dev/stage/prod, bumping each env's version by one.",
2702
+ value: { value: true }
2703
+ },
2704
+ untrip: {
2705
+ summary: "Untrip on every env",
2706
+ description: "Sets `value: false` on every env.",
2707
+ value: { value: false }
2708
+ },
2709
+ replaceSwitches: {
2710
+ summary: "Replace switches map",
2711
+ description: "Replaces the per-key overrides wholesale on every env. Pass `{}` to clear.",
2712
+ value: { switches: { eu_region: true, apac_region: true } }
2713
+ },
2714
+ updateDescription: {
2715
+ summary: "Description-only update",
2716
+ description: "Doesn't bump versions or trigger a republish \u2014 only metadata changes.",
2717
+ value: { description: "Master kill \u2014 owner: payments-platform" }
2718
+ }
2719
+ },
2720
+ response: { id: "ksw_01j7w9d8h2k4m6n8p0q2r4s6t8" }
2721
+ },
2722
+ useCase: [
2723
+ '- **Trip everywhere** \u2014 `{ "value": true }`. Kills the feature across dev/stage/prod in one call.',
2724
+ '- **Untrip everywhere** \u2014 `{ "value": false }`.',
2725
+ "- **Replace switches** \u2014 send the full new map; per-key edits use `PUT /{id}/switch`.",
2726
+ "- **Update description** \u2014 metadata-only patches don't bump versions."
2727
+ ].join("\n")
2728
+ },
2729
+ {
2730
+ operationId: "deleteKillswitch",
2731
+ method: "DELETE",
2732
+ path: "/{id}",
2733
+ summary: "Delete a killswitch",
2734
+ description: "Soft-deletes the killswitch and rebuilds the project's flags KV blob so SDKs stop seeing it.",
2735
+ pathParams: { id: "Stable opaque killswitch id." },
2736
+ response: killswitchDeleteResponseSchema,
2737
+ examples: { response: { ok: true } },
2738
+ useCase: "Tear down a killswitch after the feature it protected has been removed."
2739
+ },
2740
+ {
2741
+ operationId: "setKillswitchSwitch",
2742
+ method: "PUT",
2743
+ path: "/{id}/switch",
2744
+ summary: "Set one switch entry",
2745
+ description: [
2746
+ "Sets or updates a single `switchKey` on a single `env`. Publishes one new version on that env only \u2014 other envs untouched.",
2747
+ "",
2748
+ "Use this for surgical per-env, per-key flips during incident response (e.g. trip `eu_region` on prod without touching the flat `value` or other envs)."
2749
+ ].join("\n"),
2750
+ pathParams: { id: "Stable opaque killswitch id." },
2751
+ request: killswitchSwitchSetSchema,
2752
+ response: killswitchSwitchSetResponseSchema,
2753
+ examples: {
2754
+ requestExamples: {
2755
+ tripRegion: {
2756
+ summary: "Trip eu_region on prod",
2757
+ description: "Sets `switches.eu_region = true` on prod only. Other envs and the flat `value` are unchanged.",
2758
+ value: { env: "prod", switchKey: "eu_region", value: true }
2759
+ },
2760
+ untripRegion: {
2761
+ summary: "Untrip eu_region on prod",
2762
+ description: "Flip the same entry back off without removing it from the map.",
2763
+ value: { env: "prod", switchKey: "eu_region", value: false }
2764
+ }
2765
+ },
2766
+ response: {
2767
+ id: "ksw_01j7w9d8h2k4m6n8p0q2r4s6t8",
2768
+ env: "prod",
2769
+ switchKey: "eu_region",
2770
+ value: true
2771
+ }
2772
+ },
2773
+ useCase: [
2774
+ '- **Trip a region** \u2014 `{ "env": "prod", "switchKey": "eu_region", "value": true }`.',
2775
+ "- **Untrip without removing** \u2014 same payload with `value: false`. To remove the entry entirely use `DELETE /{id}/switch`."
2776
+ ].join("\n")
2777
+ },
2778
+ {
2779
+ operationId: "unsetKillswitchSwitch",
2780
+ method: "DELETE",
2781
+ path: "/{id}/switch",
2782
+ summary: "Remove one switch entry",
2783
+ description: [
2784
+ "Removes a single `switchKey` from the `switches` map on a single `env`. Publishes a new version on that env.",
2785
+ "",
2786
+ "Returns `{ removed: false }` if the entry didn't exist (idempotent no-op)."
2787
+ ].join("\n"),
2788
+ pathParams: { id: "Stable opaque killswitch id." },
2789
+ request: killswitchSwitchUnsetSchema,
2790
+ response: killswitchSwitchUnsetResponseSchema,
2791
+ examples: {
2792
+ requestExamples: {
2793
+ removeRegion: {
2794
+ summary: "Remove eu_region from prod",
2795
+ description: "Drops the `eu_region` override on prod so the flat `value` applies again.",
2796
+ value: { env: "prod", switchKey: "eu_region" }
2797
+ }
2798
+ },
2799
+ response: {
2800
+ id: "ksw_01j7w9d8h2k4m6n8p0q2r4s6t8",
2801
+ env: "prod",
2802
+ switchKey: "eu_region",
2803
+ removed: true
2804
+ }
2805
+ },
2806
+ useCase: "Clean up a per-region override after the incident is resolved so the flat `value` governs again."
2807
+ }
2808
+ ]
2809
+ };
2810
+ export {
2811
+ killswitchesClient,
2812
+ killswitchesResource
2813
+ };