@h3ravel/arquebus 0.6.16 → 0.7.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,3540 @@
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (all) => {
9
+ let target = {};
10
+ for (var name in all) __defProp(target, name, {
11
+ get: all[name],
12
+ enumerable: true
13
+ });
14
+ return target;
15
+ };
16
+ var __copyProps = (to, from, except, desc) => {
17
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
18
+ key = keys[i];
19
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
20
+ get: ((k) => from[k]).bind(null, key),
21
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
22
+ });
23
+ }
24
+ return to;
25
+ };
26
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
27
+ value: mod,
28
+ enumerable: true
29
+ }) : target, mod));
30
+
31
+ //#endregion
32
+ let radashi = require("radashi");
33
+ let dayjs_plugin_advancedFormat_js = require("dayjs/plugin/advancedFormat.js");
34
+ dayjs_plugin_advancedFormat_js = __toESM(dayjs_plugin_advancedFormat_js);
35
+ let dayjs = require("dayjs");
36
+ dayjs = __toESM(dayjs);
37
+ let collect_js = require("collect.js");
38
+ collect_js = __toESM(collect_js);
39
+ let knex = require("knex");
40
+ knex = __toESM(knex);
41
+ let path = require("path");
42
+ path = __toESM(path);
43
+ let fs = require("fs");
44
+ let __h3ravel_shared = require("@h3ravel/shared");
45
+ let pluralize = require("pluralize");
46
+ pluralize = __toESM(pluralize);
47
+
48
+ //#region src/mixin.ts
49
+ var mixin_exports = /* @__PURE__ */ __export({ compose: () => compose$1 });
50
+ /**
51
+ * Compose function that merges multiple classes and mixins
52
+ *
53
+ * @example
54
+ * const SomePlugin = <TBase extends new (...args: any[]) => TGeneric> (Base: TBase) => {
55
+ * return class extends Base {
56
+ * pluginAttribtue = 'plugin'
57
+ * pluginMethod () {
58
+ * return this.pluginAttribtue
59
+ * }
60
+ * }
61
+ * }
62
+ *
63
+ * // Base class
64
+ * class Model {
65
+ * make () {
66
+ * console.log('make')
67
+ * }
68
+ * pluginMethod (id: string) {
69
+ * }
70
+ * }
71
+ *
72
+ * class User extends compose(
73
+ * Model,
74
+ * SomePlugin,
75
+ * ) {
76
+ * relationPosts () {
77
+ * return 'hasMany Posts'
78
+ * }
79
+ * }
80
+ *
81
+ * const user = new User()
82
+ * user.make() // from Model
83
+ * user.pluginMethod() // from SomePlugin
84
+ * user.relationPosts() // from User
85
+ *
86
+ * console.log(user.pluginMethod('w')) // "plugin"
87
+ * console.log(user.pluginMethod()) // "plugin"
88
+ * console.log(user.relationPosts()) // "hasMany Posts"
89
+ *
90
+ * @param Base
91
+ * @param mixins
92
+ * @returns
93
+ */
94
+ function compose$1(Base, ...mixins) {
95
+ /**
96
+ * Apply each mixin or class in sequence
97
+ */
98
+ return mixins.reduce((acc, mixin) => {
99
+ if (typeof mixin === "function" && mixin.prototype)
100
+ /**
101
+ * If it's a class constructor, extend it
102
+ */
103
+ return class extends acc {
104
+ constructor(...args) {
105
+ super(...args);
106
+ /**
107
+ * Copy instance properties from mixin prototype
108
+ */
109
+ Object.getOwnPropertyNames(mixin.prototype).forEach((name) => {
110
+ if (name !== "constructor") Object.defineProperty(this, name, Object.getOwnPropertyDescriptor(mixin.prototype, name));
111
+ });
112
+ }
113
+ };
114
+ else if (typeof mixin === "function")
115
+ /**
116
+ * If it's a mixin function, call it with current class
117
+ */
118
+ return mixin(acc);
119
+ return acc;
120
+ }, Base);
121
+ }
122
+
123
+ //#endregion
124
+ //#region src/utils.ts
125
+ dayjs.default.extend(dayjs_plugin_advancedFormat_js.default);
126
+ const getRelationName = (relationMethod) => {
127
+ return (0, radashi.snake)(relationMethod.substring(8));
128
+ };
129
+ const getRelationMethod = (relation) => {
130
+ return (0, radashi.camel)(`relation_${relation}`);
131
+ };
132
+ const getScopeMethod = (scope) => {
133
+ return (0, radashi.camel)(`scope_${scope}`);
134
+ };
135
+ const getAttrMethod = (attr) => {
136
+ return (0, radashi.camel)(`attribute_${attr}`);
137
+ };
138
+ const getGetterMethod = (attr) => {
139
+ return (0, radashi.camel)(`get_${attr}_attribute`);
140
+ };
141
+ const getSetterMethod = (attr) => {
142
+ return (0, radashi.camel)(`set_${attr}_attribute`);
143
+ };
144
+ /**
145
+ * Tap into a model a collection instance
146
+ *
147
+ * @param instance
148
+ * @param callback
149
+ * @returns
150
+ */
151
+ const tap = (instance, callback) => {
152
+ const result = callback(instance);
153
+ return result instanceof Promise ? result.then(() => instance) : instance;
154
+ };
155
+ const { compose } = mixin_exports;
156
+ const flattenDeep = (arr) => Array.isArray(arr) ? arr.reduce((a, b) => a.concat(flattenDeep(b)), []) : [arr];
157
+ const snakeCase = (str) => (0, radashi.trim)((0, radashi.snake)(str.replace(/[^a-zA-Z0-9_-]/g, "-")), "_-");
158
+
159
+ //#endregion
160
+ //#region src/casts-attributes.ts
161
+ var CastsAttributes = class CastsAttributes {
162
+ constructor() {
163
+ if (this.constructor === CastsAttributes) throw new Error("CastsAttributes cannot be instantiated");
164
+ }
165
+ static get(_model, _key, _value, _attributes) {
166
+ throw new Error("get not implemented");
167
+ }
168
+ static set(_model, _key, _value, _attributes) {
169
+ throw new Error("set not implemented");
170
+ }
171
+ };
172
+ var casts_attributes_default = CastsAttributes;
173
+
174
+ //#endregion
175
+ //#region src/concerns/has-attributes.ts
176
+ var has_attributes_exports = /* @__PURE__ */ __export({ default: () => has_attributes_default });
177
+ const HasAttributes = (Model$1) => {
178
+ return class extends Model$1 {
179
+ static castTypeCache = {};
180
+ attributes = {};
181
+ original = {};
182
+ casts = {};
183
+ changes = {};
184
+ appends = [];
185
+ setAppends(appends) {
186
+ this.appends = appends;
187
+ return this;
188
+ }
189
+ append(...keys) {
190
+ const appends = flattenDeep(keys);
191
+ this.appends = [...this.appends, ...appends];
192
+ return this;
193
+ }
194
+ normalizeCastClassResponse(key, value) {
195
+ var _value$constructor;
196
+ return (value === null || value === void 0 || (_value$constructor = value.constructor) === null || _value$constructor === void 0 ? void 0 : _value$constructor.name) === "Object" ? value : { [key]: value };
197
+ }
198
+ syncOriginal() {
199
+ this.original = this.getAttributes();
200
+ return this;
201
+ }
202
+ syncChanges() {
203
+ this.changes = this.getDirty();
204
+ return this;
205
+ }
206
+ syncOriginalAttribute(attribute) {
207
+ this.syncOriginalAttributes(attribute);
208
+ }
209
+ syncOriginalAttributes(...attributes) {
210
+ attributes = flattenDeep(attributes);
211
+ const modelAttributes = this.getAttributes();
212
+ for (const attribute of attributes) this.original[attribute] = modelAttributes[attribute];
213
+ return this;
214
+ }
215
+ isDirty(...attributes) {
216
+ const changes = this.getDirty();
217
+ attributes = flattenDeep(attributes);
218
+ if (attributes.length === 0) return Object.keys(changes).length > 0;
219
+ for (const attribute of attributes) if (attribute in changes) return true;
220
+ return false;
221
+ }
222
+ getDirty() {
223
+ const dirty = {};
224
+ const attributes = this.getAttributes();
225
+ for (const key in attributes) {
226
+ const value = attributes[key];
227
+ if (!this.originalIsEquivalent(key)) dirty[key] = value;
228
+ }
229
+ return dirty;
230
+ }
231
+ originalIsEquivalent(key) {
232
+ if (this.original[key] === void 0) return false;
233
+ if (this.attributes[key] === this.original[key]) return true;
234
+ else return false;
235
+ }
236
+ setAttributes(attributes) {
237
+ this.attributes = { ...attributes };
238
+ }
239
+ setRawAttributes(attributes, sync = false) {
240
+ this.attributes = attributes;
241
+ if (sync) this.syncOriginal();
242
+ return this;
243
+ }
244
+ getAttributes() {
245
+ return { ...this.attributes };
246
+ }
247
+ setAttribute(key, value) {
248
+ const setterMethod = getSetterMethod(key);
249
+ if (typeof this[setterMethod] === "function") {
250
+ this[setterMethod](value);
251
+ return this;
252
+ }
253
+ const attrMethod = getAttrMethod(key);
254
+ if (typeof this[attrMethod] === "function") {
255
+ const callback = this[attrMethod]().set || ((value$1) => {
256
+ this.attributes[key] = value$1;
257
+ });
258
+ this.attributes = {
259
+ ...this.attributes,
260
+ ...this.normalizeCastClassResponse(key, callback(value, this.attributes))
261
+ };
262
+ return this;
263
+ }
264
+ const castType = this.getCasts()[key];
265
+ if (this.isCustomCast(castType) && typeof castType !== "string") value = castType.set(this, key, value, this.attributes) ?? "";
266
+ if (castType === "json") value = JSON.stringify(value);
267
+ if (castType === "collection") value = JSON.stringify(value);
268
+ if (value !== null && this.isDateAttribute(key)) value = this.fromDateTime(value);
269
+ this.attributes[key] = value;
270
+ return this;
271
+ }
272
+ getAttribute(key) {
273
+ if (!key) return;
274
+ const getterMethod = getGetterMethod(key);
275
+ if (typeof this[getterMethod] === "function") return this[getterMethod](this.attributes[key], this.attributes);
276
+ const attrMethod = getAttrMethod(key);
277
+ if (typeof this[attrMethod] === "function") return this[attrMethod]().get(this.attributes[key], this.attributes);
278
+ if (key in this.attributes) {
279
+ if (this.hasCast(key)) return this.castAttribute(key, this.attributes[key]);
280
+ if (this.getDates().includes(key)) return this.asDateTime(this.attributes[key]);
281
+ return this.attributes[key];
282
+ }
283
+ if (key in this.relations) return this.relations[key];
284
+ }
285
+ castAttribute(key, value) {
286
+ const castType = this.getCastType(key);
287
+ if (!castType) return value;
288
+ if (value === null) return value;
289
+ switch (castType) {
290
+ case "int":
291
+ case "integer": return parseInt(value);
292
+ case "real":
293
+ case "float":
294
+ case "double": return parseFloat(value);
295
+ case "decimal": return this.asDecimal(value, castType.split(":")[1]);
296
+ case "string": return String(value);
297
+ case "bool":
298
+ case "boolean": return Boolean(value);
299
+ case "object":
300
+ case "json": try {
301
+ return JSON.parse(value);
302
+ } catch {
303
+ return null;
304
+ }
305
+ case "collection": try {
306
+ return (0, collect_js.default)(JSON.parse(value));
307
+ } catch {
308
+ return (0, collect_js.default)([]);
309
+ }
310
+ case "date": return this.asDate(value);
311
+ case "datetime":
312
+ case "custom_datetime": return this.asDateTime(value);
313
+ case "timestamp": return this.asTimestamp(value);
314
+ }
315
+ if (this.isCustomCast(castType)) return castType.get(this, key, value, this.attributes);
316
+ return value;
317
+ }
318
+ attributesToData() {
319
+ let attributes = { ...this.attributes };
320
+ for (const key in attributes) {
321
+ if (this.hidden.includes(key)) attributes = (0, radashi.omit)(attributes, [key]);
322
+ if (this.visible.length > 0 && this.visible.includes(key) === false) attributes = (0, radashi.omit)(attributes, [key]);
323
+ }
324
+ for (const key of this.getDates()) {
325
+ if (attributes[key] === void 0) continue;
326
+ attributes[key] = this.serializeDate(this.asDateTime(attributes[key]));
327
+ }
328
+ const casts = this.getCasts();
329
+ for (const key in casts) {
330
+ const value = casts[key];
331
+ if (key in attributes === false) continue;
332
+ attributes[key] = this.castAttribute(key, attributes[key]);
333
+ if (key in attributes && ["date", "datetime"].includes(String(value))) attributes[key] = this.serializeDate(attributes[key]);
334
+ if (key in attributes && this.isCustomDateTimeCast(value)) attributes[key] = (0, dayjs.default)(attributes[key]).format(String(value).split(":")[1]);
335
+ }
336
+ for (const key of this.appends) attributes[key] = this.mutateAttribute(key, null);
337
+ return attributes;
338
+ }
339
+ mutateAttribute(key, value) {
340
+ if (typeof this[getGetterMethod(key)] === "function") return this[getGetterMethod(key)](value);
341
+ else if (typeof this[getAttrMethod(key)] === "function") return this[getAttrMethod(key)]().get(key, this.attributes);
342
+ else if (key in this) return this[key];
343
+ return value;
344
+ }
345
+ mutateAttributeForArray(_key, _value) {}
346
+ isDateAttribute(key) {
347
+ return this.getDates().includes(key) || this.isDateCastable(key);
348
+ }
349
+ serializeDate(date) {
350
+ return date ? (0, dayjs.default)(date).toISOString() : null;
351
+ }
352
+ getDates() {
353
+ return this.usesTimestamps() ? [this.getCreatedAtColumn(), this.getUpdatedAtColumn()] : [];
354
+ }
355
+ getCasts() {
356
+ if (this.getIncrementing()) return {
357
+ [this.getKeyName()]: this.getKeyType(),
358
+ ...this.casts
359
+ };
360
+ return this.casts;
361
+ }
362
+ getCastType(key) {
363
+ const castType = this.getCasts()[key];
364
+ let castTypeCacheKey;
365
+ if (typeof castType === "string") castTypeCacheKey = castType;
366
+ else if (new castType() instanceof casts_attributes_default) castTypeCacheKey = castType.name;
367
+ if (castTypeCacheKey && this.getConstructor().castTypeCache[castTypeCacheKey] !== void 0) return this.getConstructor().castTypeCache[castTypeCacheKey];
368
+ let convertedCastType;
369
+ if (this.isCustomDateTimeCast(castType)) convertedCastType = "custom_datetime";
370
+ else if (this.isDecimalCast(castType)) convertedCastType = "decimal";
371
+ else if (this.isCustomCast(castType)) convertedCastType = castType;
372
+ else convertedCastType = String(castType).toLocaleLowerCase().trim();
373
+ return this.getConstructor()[castTypeCacheKey] = convertedCastType;
374
+ }
375
+ hasCast(key, types = []) {
376
+ if (key in this.casts) {
377
+ types = (0, radashi.flat)(types);
378
+ return types.length > 0 ? types.includes(this.getCastType(key)) : true;
379
+ }
380
+ return false;
381
+ }
382
+ withDayjs(date) {
383
+ return (0, dayjs.default)(date);
384
+ }
385
+ isCustomCast(cast) {
386
+ return typeof cast === "function" && new cast() instanceof casts_attributes_default;
387
+ }
388
+ isCustomDateTimeCast(cast) {
389
+ if (typeof cast !== "string") return false;
390
+ return cast.startsWith("date:") || cast.startsWith("datetime:");
391
+ }
392
+ isDecimalCast(cast) {
393
+ if (typeof cast !== "string") return false;
394
+ return cast.startsWith("decimal:");
395
+ }
396
+ isDateCastable(key) {
397
+ return this.hasCast(key, ["date", "datetime"]);
398
+ }
399
+ fromDateTime(value) {
400
+ return (0, dayjs.default)(this.asDateTime(value)).format(this.getDateFormat());
401
+ }
402
+ getDateFormat() {
403
+ return this.dateFormat || "YYYY-MM-DD HH:mm:ss";
404
+ }
405
+ asDecimal(value, decimals) {
406
+ return parseFloat(value).toFixed(decimals);
407
+ }
408
+ asDateTime(value) {
409
+ if (value === null) return null;
410
+ if (value instanceof Date) return value;
411
+ if (typeof value === "number") return /* @__PURE__ */ new Date(value * 1e3);
412
+ return new Date(value);
413
+ }
414
+ asDate(value) {
415
+ return (0, dayjs.default)(this.asDateTime(value)).startOf("day").toDate();
416
+ }
417
+ };
418
+ };
419
+ var has_attributes_default = HasAttributes;
420
+
421
+ //#endregion
422
+ //#region src/errors.ts
423
+ var BaseError = class extends Error {
424
+ constructor(message, _entity) {
425
+ super(message);
426
+ Error.captureStackTrace(this, this.constructor);
427
+ this.name = this.constructor.name;
428
+ this.message = message;
429
+ }
430
+ };
431
+ var ModelNotFoundError = class extends BaseError {
432
+ model;
433
+ ids = [];
434
+ constructor() {
435
+ super("");
436
+ }
437
+ setModel(model, ids = []) {
438
+ this.model = model;
439
+ this.ids = (0, radashi.isArray)(ids) ? ids : [ids];
440
+ this.message = `No query results for model [${model}]`;
441
+ if (this.ids.length > 0) this.message += " " + this.ids.join(", ");
442
+ else this.message += ".";
443
+ return this;
444
+ }
445
+ getModel() {
446
+ return this.model;
447
+ }
448
+ getIds() {
449
+ return this.ids;
450
+ }
451
+ };
452
+ var RelationNotFoundError = class extends BaseError {};
453
+ var InvalidArgumentError = class extends BaseError {};
454
+
455
+ //#endregion
456
+ //#region src/scope.ts
457
+ var Scope = class Scope {
458
+ constructor() {
459
+ if (this.constructor === Scope) throw new Error("Scope cannot be instantiated");
460
+ }
461
+ apply(_builder, _model) {
462
+ throw new Error("apply not implemented");
463
+ }
464
+ };
465
+ var scope_default = Scope;
466
+
467
+ //#endregion
468
+ //#region src/concerns/has-global-scopes.ts
469
+ var has_global_scopes_exports = /* @__PURE__ */ __export({ default: () => has_global_scopes_default });
470
+ const HasGlobalScopes = (Model$1) => {
471
+ return class extends Model$1 {
472
+ static globalScopes;
473
+ static addGlobalScope(scope, implementation = null) {
474
+ if (typeof scope === "string" && implementation instanceof scope_default) {
475
+ this.globalScopes = (0, radashi.set)(this.globalScopes ?? {}, this.name + "." + scope, implementation);
476
+ return implementation;
477
+ } else if (scope instanceof scope_default) {
478
+ this.globalScopes = (0, radashi.set)(this.globalScopes ?? {}, this.name + "." + scope.constructor.name, scope);
479
+ return scope;
480
+ }
481
+ throw new InvalidArgumentError("Global scope must be an instance of Scope.");
482
+ }
483
+ static hasGlobalScope(scope) {
484
+ return this.getGlobalScope(scope) !== null;
485
+ }
486
+ static getGlobalScope(scope) {
487
+ if (typeof scope === "string") return (0, radashi.get)(this.globalScopes, this.name + "." + scope);
488
+ return (0, radashi.get)(this.globalScopes, this.name + "." + scope.constructor.name);
489
+ }
490
+ static getAllGlobalScopes() {
491
+ return this.globalScopes;
492
+ }
493
+ static setAllGlobalScopes(scopes) {
494
+ this.globalScopes = scopes;
495
+ }
496
+ getGlobalScopes() {
497
+ return (0, radashi.get)(this.constructor.globalScopes, this.constructor.name, {});
498
+ }
499
+ };
500
+ };
501
+ var has_global_scopes_default = HasGlobalScopes;
502
+
503
+ //#endregion
504
+ //#region src/hooks.ts
505
+ var Hooks = class {
506
+ hooks = {
507
+ creating: [],
508
+ created: [],
509
+ updating: [],
510
+ updated: [],
511
+ saving: [],
512
+ saved: [],
513
+ deleting: [],
514
+ deleted: [],
515
+ restoring: [],
516
+ restored: [],
517
+ trashed: [],
518
+ forceDeleting: [],
519
+ forceDeleted: []
520
+ };
521
+ add(hook, callback) {
522
+ this.hooks[hook].push(callback);
523
+ }
524
+ async exec(hook, data) {
525
+ const callbacks = this.hooks[hook] ?? [];
526
+ for (const callback of callbacks) await callback(...data);
527
+ return true;
528
+ }
529
+ };
530
+ var hooks_default = Hooks;
531
+
532
+ //#endregion
533
+ //#region src/concerns/has-hooks.ts
534
+ var has_hooks_exports = /* @__PURE__ */ __export({ default: () => has_hooks_default });
535
+ const HasHooks = (Model$1) => {
536
+ return class extends Model$1 {
537
+ static hooks = null;
538
+ static addHook(hook, callback) {
539
+ if (this.hooks instanceof hooks_default === false) this.hooks = new hooks_default();
540
+ this.hooks.add(hook, callback);
541
+ }
542
+ static creating(callback) {
543
+ this.addHook("creating", callback);
544
+ }
545
+ static created(callback) {
546
+ this.addHook("created", callback);
547
+ }
548
+ static updating(callback) {
549
+ this.addHook("updating", callback);
550
+ }
551
+ static updated(callback) {
552
+ this.addHook("updated", callback);
553
+ }
554
+ static saving(callback) {
555
+ this.addHook("saving", callback);
556
+ }
557
+ static saved(callback) {
558
+ this.addHook("saved", callback);
559
+ }
560
+ static deleting(callback) {
561
+ this.addHook("deleting", callback);
562
+ }
563
+ static deleted(callback) {
564
+ this.addHook("deleted", callback);
565
+ }
566
+ static restoring(callback) {
567
+ this.addHook("restoring", callback);
568
+ }
569
+ static restored(callback) {
570
+ this.addHook("restored", callback);
571
+ }
572
+ static trashed(callback) {
573
+ this.addHook("trashed", callback);
574
+ }
575
+ static forceDeleted(callback) {
576
+ this.addHook("forceDeleted", callback);
577
+ }
578
+ async execHooks(hook, options) {
579
+ if (this.constructor.hooks instanceof hooks_default === false) return;
580
+ return await this.constructor.hooks.exec(hook, [this, options]);
581
+ }
582
+ };
583
+ };
584
+ var has_hooks_default = HasHooks;
585
+
586
+ //#endregion
587
+ //#region src/collection.ts
588
+ var Collection = class Collection extends collect_js.Collection {
589
+ newConstructor(...args) {
590
+ return new (this.getConstructor())(...args);
591
+ }
592
+ getConstructor() {
593
+ return this.constructor;
594
+ }
595
+ async load(...relations) {
596
+ if (this.isNotEmpty()) {
597
+ const items = await this.first().constructor.query().with(...relations).eagerLoadRelations(this.items);
598
+ return this.newConstructor(items);
599
+ }
600
+ return this;
601
+ }
602
+ async loadAggregate(relations, column, action = null) {
603
+ if (this.isEmpty()) return this;
604
+ const models = (await this.first().newModelQuery().whereIn(this.first().getKeyName(), this.modelKeys()).select(this.first().getKeyName()).withAggregate(relations, column, action).get()).keyBy(this.first().getKeyName());
605
+ const attributes = (0, radashi.diff)(Object.keys(models.first().getAttributes()), [models.first().getKeyName()]);
606
+ this.each((model) => {
607
+ const extraAttributes = (0, radashi.pick)(models.get(model.getKey()).getAttributes(), attributes);
608
+ model.fill(extraAttributes).syncOriginalAttributes(...attributes);
609
+ });
610
+ return this;
611
+ }
612
+ loadCount(relations) {
613
+ return this.loadAggregate(relations, "*", "count");
614
+ }
615
+ loadMax(relation, column) {
616
+ return this.loadAggregate(relation, column, "max");
617
+ }
618
+ loadMin(relation, column) {
619
+ return this.loadAggregate(relation, column, "min");
620
+ }
621
+ loadSum(relation, column) {
622
+ return this.loadAggregate(relation, column, "sum");
623
+ }
624
+ loadAvg(relation, column) {
625
+ return this.loadAggregate(relation, column, "avg");
626
+ }
627
+ mapThen(callback) {
628
+ return Promise.all(this.map(callback));
629
+ }
630
+ modelKeys() {
631
+ return this.all().map((item) => item.getKey());
632
+ }
633
+ contains(key, operator, value) {
634
+ if (arguments.length > 1) return super.contains(key, value ?? operator);
635
+ if (key instanceof model_default) return super.contains((model) => {
636
+ return model.is(key);
637
+ });
638
+ return super.contains((model) => {
639
+ return model.getKey() == key;
640
+ });
641
+ }
642
+ diff(items) {
643
+ const diff = new this.constructor();
644
+ const dictionary = this.getDictionary(items);
645
+ this.items.map((item) => {
646
+ if (dictionary[item.getKey()] === void 0) diff.add(item);
647
+ });
648
+ return diff;
649
+ }
650
+ except(keys) {
651
+ const dictionary = (0, radashi.omit)(this.getDictionary(), keys);
652
+ return new this.constructor(Object.values(dictionary));
653
+ }
654
+ intersect(items) {
655
+ const intersect = new this.constructor();
656
+ if ((0, radashi.isEmpty)(items)) return intersect;
657
+ const dictionary = this.getDictionary(items);
658
+ for (const item of this.items) if (dictionary[item.getKey()] !== void 0) intersect.add(item);
659
+ return intersect;
660
+ }
661
+ unique(key, _strict = false) {
662
+ if (key) return super.unique(key);
663
+ return new this.constructor(Object.values(this.getDictionary()));
664
+ }
665
+ find(key, defaultValue = null) {
666
+ if (key instanceof model_default) key = key.getKey();
667
+ if ((0, radashi.isArray)(key)) {
668
+ if (this.isEmpty()) return new this.constructor();
669
+ return this.whereIn(this.first().getKeyName(), key);
670
+ }
671
+ (0, collect_js.collect)(this.items).first((model) => {
672
+ return model.getKey() == key;
673
+ });
674
+ return this.items.filter((model) => {
675
+ return model.getKey() == key;
676
+ })[0] || defaultValue;
677
+ }
678
+ async fresh(...args) {
679
+ if (this.isEmpty()) return new this.constructor();
680
+ const model = this.first();
681
+ const freshModels = (await model.newQuery().with(...args).whereIn(model.getKeyName(), this.modelKeys()).get()).getDictionary();
682
+ return this.filter((model$1) => {
683
+ return model$1.exists && freshModels[model$1.getKey()] !== void 0;
684
+ }).map((model$1) => {
685
+ return freshModels[model$1.getKey()];
686
+ });
687
+ }
688
+ makeVisible(attributes) {
689
+ return this.each((item) => {
690
+ item.makeVisible(attributes);
691
+ });
692
+ }
693
+ makeHidden(attributes) {
694
+ return this.each((item) => {
695
+ item.makeHidden(attributes);
696
+ });
697
+ }
698
+ append(attributes) {
699
+ return this.each((item) => {
700
+ item.append(attributes);
701
+ });
702
+ }
703
+ only(keys) {
704
+ if (keys === null) return new Collection(this.items);
705
+ const dictionary = (0, radashi.pick)(this.getDictionary(), keys);
706
+ return new this.constructor(Object.values(dictionary));
707
+ }
708
+ getDictionary(items) {
709
+ items = !items ? this.items : items;
710
+ const dictionary = {};
711
+ items.map((value) => {
712
+ dictionary[value.getKey()] = value;
713
+ });
714
+ return dictionary;
715
+ }
716
+ toQuery() {
717
+ const model = this.first();
718
+ if (!model) throw new Error("Unable to create query for empty collection.");
719
+ const modelName = model.constructor.name;
720
+ if (this.filter((model$1) => {
721
+ return !(model$1 instanceof modelName);
722
+ }).isNotEmpty()) throw new Error("Unable to create query for collection with mixed types.");
723
+ return model.newModelQuery().whereKey(this.modelKeys());
724
+ }
725
+ toData() {
726
+ return this.all().map((item) => typeof item.toData == "function" ? item.toData() : item);
727
+ }
728
+ toJSON() {
729
+ return this.toData();
730
+ }
731
+ toJson(...args) {
732
+ return JSON.stringify(this.toData(), ...args);
733
+ }
734
+ [Symbol.iterator] = () => {
735
+ const items = this.items;
736
+ const length = this.items.length;
737
+ let n = 0;
738
+ return { next() {
739
+ return n < length ? {
740
+ value: items[n++],
741
+ done: false
742
+ } : { done: true };
743
+ } };
744
+ };
745
+ };
746
+ var collection_default = Collection;
747
+
748
+ //#endregion
749
+ //#region src/relations/concerns/interacts-with-pivot-table.ts
750
+ const InteractsWithPivotTable = (Relation$1) => {
751
+ return class extends Relation$1 {
752
+ newExistingPivot(attributes = []) {
753
+ return this.newPivot(attributes, true);
754
+ }
755
+ newPivot(attributes = [], exists = false) {
756
+ return this.related.newPivot(this.parent, attributes, this.getTable(), exists, this.using).setPivotKeys(this.foreignPivotKey, this.relatedPivotKey);
757
+ }
758
+ async attach(id, attributes = {}, _touch = true) {
759
+ if (this.using) await this.attachUsingCustomClass(id, attributes);
760
+ else await this.newPivotStatement().insert(this.formatAttachRecords(this.parseIds(id), attributes));
761
+ }
762
+ async detach(ids, _touch = true) {
763
+ let results;
764
+ if (this.using && ids !== null && this.pivotWheres.length == 0 && this.pivotWhereIns.length == 0 && this.pivotWhereNulls.length == 0) results = await this.detachUsingCustomClass(ids);
765
+ else {
766
+ const query = this.newPivotQuery();
767
+ if (ids !== null) {
768
+ ids = this.parseIds(ids);
769
+ if (ids.length == 0) return 0;
770
+ query.whereIn(this.getQualifiedRelatedPivotKeyName(), ids);
771
+ }
772
+ results = await query.delete();
773
+ }
774
+ return results;
775
+ }
776
+ async sync(ids, detaching = true) {
777
+ let changes = {
778
+ attached: [],
779
+ detached: [],
780
+ updated: []
781
+ };
782
+ let records;
783
+ const results = await this.getCurrentlyAttachedPivots();
784
+ const current = results.length === 0 ? [] : results.map((result) => result.toData()).pluck(this.relatedPivotKey).all().map((i) => String(i));
785
+ const detach = (0, radashi.diff)(current, Object.keys(records = this.formatRecordsList(this.parseIds(ids))));
786
+ if (detaching && detach.length > 0) {
787
+ await this.detach(detach);
788
+ changes.detached = this.castKeys(detach);
789
+ }
790
+ changes = (0, radashi.assign)(changes, await this.attachNew(records, current, false));
791
+ return changes;
792
+ }
793
+ syncWithoutDetaching(ids) {
794
+ return this.sync(ids, false);
795
+ }
796
+ syncWithPivotValues(ids, values, detaching = true) {
797
+ return this.sync((0, collect_js.collect)(this.parseIds(ids)).mapWithKeys((id) => {
798
+ return [id, values];
799
+ }), detaching);
800
+ }
801
+ withPivot(columns) {
802
+ this.pivotColumns = this.pivotColumns.concat((0, radashi.isArray)(columns) ? columns : Array.prototype.slice.call(columns));
803
+ return this;
804
+ }
805
+ async attachNew(records, current, touch = true) {
806
+ const changes = {
807
+ attached: [],
808
+ updated: []
809
+ };
810
+ for (const id in records) {
811
+ const attributes = records[id];
812
+ if (!current.includes(id)) {
813
+ await this.attach(id, attributes, touch);
814
+ changes.attached.push(this.castKey(id));
815
+ } else if (Object.keys(attributes).length > 0 && await this.updateExistingPivot(id, attributes, touch)) changes.updated.push(this.castKey(id));
816
+ }
817
+ return changes;
818
+ }
819
+ async updateExistingPivot(id, attributes, touch = true) {
820
+ if (this.using && this.pivotWheres.length > 0 && this.pivotWhereInspivotWheres.length > 0 && this.pivotWhereNullspivotWheres.length > 0) return await this.updateExistingPivotUsingCustomClass(id, attributes, touch);
821
+ if (this.hasPivotColumn(this.updatedAt())) attributes = this.addTimestampsToAttachment(attributes, true);
822
+ return this.newPivotStatementForId(this.parseId(id)).update(this.castAttributes(attributes));
823
+ }
824
+ addTimestampsToAttachment(record, exists = false) {
825
+ let fresh = this.parent.freshTimestamp();
826
+ if (this.using) fresh = new this.using().fromDateTime(fresh);
827
+ if (!exists && this.hasPivotColumn(this.createdAt())) record[this.createdAt()] = fresh;
828
+ if (this.hasPivotColumn(this.updatedAt())) record[this.updatedAt()] = fresh;
829
+ return record;
830
+ }
831
+ async updateExistingPivotUsingCustomClass(id, attributes, _touch) {
832
+ const pivot = await this.getCurrentlyAttachedPivots().where(this.foreignPivotKey, this.parent[this.parentKey]).where(this.relatedPivotKey, this.parseId(id)).first();
833
+ const updated = pivot ? pivot.fill(attributes).isDirty() : false;
834
+ if (updated) await pivot.save();
835
+ return parseInt(updated);
836
+ }
837
+ formatRecordsList(records) {
838
+ return (0, collect_js.collect)(records).mapWithKeys((attributes, id) => {
839
+ if (!(0, radashi.isArray)(attributes)) [id, attributes] = [attributes, {}];
840
+ return [id, attributes];
841
+ }).all();
842
+ }
843
+ async getCurrentlyAttachedPivots() {
844
+ return (await this.newPivotQuery().get()).map((record) => {
845
+ return (this.using || Pivot).fromRawAttributes(this.parent, record, this.getTable(), true).setPivotKeys(this.foreignPivotKey, this.relatedPivotKey);
846
+ });
847
+ }
848
+ castKeys(keys) {
849
+ return keys.map((v) => {
850
+ return this.castKey(v);
851
+ });
852
+ }
853
+ castKey(key) {
854
+ return this.getTypeSwapValue(this.related.getKeyType(), key);
855
+ }
856
+ getTypeSwapValue(type, value) {
857
+ switch (type.toLowerCase()) {
858
+ case "int":
859
+ case "integer": return parseInt(value);
860
+ case "real":
861
+ case "float":
862
+ case "double": return parseFloat(value);
863
+ case "string": return String(value);
864
+ default: return value;
865
+ }
866
+ }
867
+ newPivotQuery() {
868
+ const query = this.newPivotStatement();
869
+ this.pivotWheres.map((args) => {
870
+ query.where(...args);
871
+ });
872
+ this.pivotWhereIns.map((args) => {
873
+ query.whereIn(...args);
874
+ });
875
+ this.pivotWhereNulls.map((args) => {
876
+ query.whereNull(...args);
877
+ });
878
+ return query.where(this.getQualifiedForeignPivotKeyName(), this.parent[this.parentKey]);
879
+ }
880
+ async detachUsingCustomClass(ids) {
881
+ let results = 0;
882
+ for (const id in this.parseIds(ids)) results += await this.newPivot({
883
+ [this.foreignPivotKey]: this.parent[this.parentKey],
884
+ [this.relatedPivotKey]: id
885
+ }, true).delete();
886
+ return results;
887
+ }
888
+ newPivotStatement() {
889
+ const builder = this.parent.newQuery();
890
+ builder.setTable(this.table);
891
+ return builder;
892
+ }
893
+ async attachUsingCustomClass(id, attributes) {
894
+ const records = this.formatAttachRecords(this.parseIds(id), attributes);
895
+ await Promise.all(records.map(async (record) => {
896
+ await this.newPivot(record, false).save();
897
+ }));
898
+ }
899
+ formatAttachRecords(ids, attributes) {
900
+ const records = [];
901
+ const hasTimestamps = this.hasPivotColumn(this.createdAt()) || this.hasPivotColumn(this.updatedAt());
902
+ for (const key in ids) {
903
+ const value = ids[key];
904
+ records.push(this.formatAttachRecord(key, value, attributes, hasTimestamps));
905
+ }
906
+ return records;
907
+ }
908
+ formatAttachRecord(key, value, attributes, hasTimestamps) {
909
+ const [id, newAttributes] = this.extractAttachIdAndAttributes(key, value, attributes);
910
+ return (0, radashi.assign)(this.baseAttachRecord(id, hasTimestamps), newAttributes);
911
+ }
912
+ baseAttachRecord(id, timed) {
913
+ let record = {};
914
+ record[this.relatedPivotKey] = id;
915
+ record[this.foreignPivotKey] = this.parent[this.parentKey];
916
+ if (timed) record = this.addTimestampsToAttachment(record);
917
+ this.pivotValues.map((value) => {
918
+ record[value.column] = value.value;
919
+ });
920
+ return record;
921
+ }
922
+ extractAttachIdAndAttributes(key, value, newAttributes) {
923
+ return (0, radashi.isArray)(value) ? [key, {
924
+ ...value,
925
+ ...newAttributes
926
+ }] : [value, newAttributes];
927
+ }
928
+ hasPivotColumn(column) {
929
+ return this.pivotColumns.includes(column);
930
+ }
931
+ parseIds(value) {
932
+ if (value instanceof Model) return [value[this.relatedKey]];
933
+ if (value instanceof collection_default) return value.pluck(this.relatedKey).all();
934
+ return (0, radashi.isArray)(value) ? value : [value];
935
+ }
936
+ };
937
+ };
938
+ var interacts_with_pivot_table_default = InteractsWithPivotTable;
939
+
940
+ //#endregion
941
+ //#region src/relations/relation.ts
942
+ var Relation = class {
943
+ query;
944
+ parent;
945
+ related;
946
+ eagerKeysWereEmpty = false;
947
+ static constraints = true;
948
+ static selfJoinCount = 0;
949
+ constructor(query, parent) {
950
+ this.query = query;
951
+ this.parent = parent;
952
+ this.related = this.query.model;
953
+ }
954
+ static extend(trait) {
955
+ for (const methodName in trait) this.prototype[methodName] = trait[methodName];
956
+ }
957
+ static noConstraints(callback) {
958
+ const previous = this.constraints;
959
+ this.constraints = false;
960
+ try {
961
+ return callback();
962
+ } finally {
963
+ this.constraints = previous;
964
+ }
965
+ }
966
+ asProxy() {
967
+ return new Proxy(this, { get: function(target, prop) {
968
+ if (typeof target[prop] !== "undefined") return target[prop];
969
+ if (typeof prop === "string") {
970
+ if (typeof target.query[prop] === "function") return (...args) => {
971
+ target.query[prop](...args);
972
+ return target.asProxy();
973
+ };
974
+ }
975
+ } });
976
+ }
977
+ getRelated() {
978
+ return this.related;
979
+ }
980
+ getKeys(models, key) {
981
+ return models.map((model) => key ? model.attributes[key] : model.getKey()).sort();
982
+ }
983
+ getRelationQuery() {
984
+ return this.query;
985
+ }
986
+ whereInEager(whereIn, key, modelKeys, query = null) {
987
+ (query || this.query)[whereIn](key, modelKeys);
988
+ if (modelKeys.length === 0) this.eagerKeysWereEmpty = true;
989
+ }
990
+ whereInMethod(model, key) {
991
+ return "whereIn";
992
+ }
993
+ getEager() {
994
+ return this.eagerKeysWereEmpty ? this.query.getModel().newCollection() : this.get();
995
+ }
996
+ async get(columns = ["*"]) {
997
+ return await this.query.get(columns);
998
+ }
999
+ async first(columns = ["*"]) {
1000
+ return await this.query.first(columns);
1001
+ }
1002
+ async paginate(...args) {
1003
+ return await this.query.paginate(...args);
1004
+ }
1005
+ async count(...args) {
1006
+ return await this.query.clearSelect().count(...args);
1007
+ }
1008
+ toSql() {
1009
+ return this.query.toSql();
1010
+ }
1011
+ addConstraints() {}
1012
+ getRelationCountHash(incrementJoinCount = true) {
1013
+ return "arquebus_reserved_" + (incrementJoinCount ? this.constructor.selfJoinCount++ : this.constructor.selfJoinCount);
1014
+ }
1015
+ getRelationExistenceQuery(query, parentQuery, columns = ["*"]) {
1016
+ return query.select(columns).whereColumn(this.getQualifiedParentKeyName(), "=", this.getExistenceCompareKey());
1017
+ }
1018
+ getRelationExistenceCountQuery(query, parentQuery) {
1019
+ const db = this.related.getConnection();
1020
+ return this.getRelationExistenceQuery(query, parentQuery, db.raw("count(*)"));
1021
+ }
1022
+ getQualifiedParentKeyName() {
1023
+ return this.parent.getQualifiedKeyName();
1024
+ }
1025
+ getExistenceCompareKey() {
1026
+ var _this$getQualifiedFor;
1027
+ return (_this$getQualifiedFor = this.getQualifiedForeignKeyName) === null || _this$getQualifiedFor === void 0 ? void 0 : _this$getQualifiedFor.call(this);
1028
+ }
1029
+ };
1030
+ var relation_default = Relation;
1031
+
1032
+ //#endregion
1033
+ //#region src/relations/belongs-to-many.ts
1034
+ var BelongsToMany = class extends compose(relation_default, interacts_with_pivot_table_default) {
1035
+ table;
1036
+ foreignPivotKey;
1037
+ relatedPivotKey;
1038
+ parentKey;
1039
+ relatedKey;
1040
+ pivotColumns = [];
1041
+ pivotValues = [];
1042
+ pivotWheres = [];
1043
+ pivotWhereIns = [];
1044
+ pivotWhereNulls = [];
1045
+ accessor = "pivot";
1046
+ using;
1047
+ pivotCreatedAt;
1048
+ pivotUpdatedAt;
1049
+ constructor(query, parent, table, foreignPivotKey, relatedPivotKey, parentKey, relatedKey) {
1050
+ super(query, parent);
1051
+ this.table = table;
1052
+ this.foreignPivotKey = foreignPivotKey;
1053
+ this.relatedPivotKey = relatedPivotKey;
1054
+ this.parentKey = parentKey;
1055
+ this.relatedKey = relatedKey;
1056
+ this.addConstraints();
1057
+ return this.asProxy();
1058
+ }
1059
+ initRelation(models, relation) {
1060
+ models.map((model) => {
1061
+ model.setRelation(relation, new collection_default([]));
1062
+ });
1063
+ return models;
1064
+ }
1065
+ addConstraints() {
1066
+ this.performJoin();
1067
+ if (this.constructor.constraints) this.addWhereConstraints();
1068
+ }
1069
+ performJoin(query = null) {
1070
+ query = query || this.query;
1071
+ query.join(this.getTable(), this.getQualifiedRelatedKeyName(), "=", this.qualifyPivotColumn(this.relatedPivotKey));
1072
+ return this;
1073
+ }
1074
+ getTable() {
1075
+ return this.table;
1076
+ }
1077
+ getQualifiedRelatedKeyName() {
1078
+ return this.related.qualifyColumn(this.relatedKey);
1079
+ }
1080
+ async getResults() {
1081
+ return this.parent[this.parentKey] !== null ? await this.get() : new collection_default([]);
1082
+ }
1083
+ addWhereConstraints() {
1084
+ this.query.where(this.getQualifiedForeignPivotKeyName(), "=", this.parent[this.parentKey]);
1085
+ return this;
1086
+ }
1087
+ async get(columns) {
1088
+ var _builder$query;
1089
+ const builder = this.query.applyScopes();
1090
+ columns = ((_builder$query = builder.query) === null || _builder$query === void 0 || (_builder$query = _builder$query._statements) === null || _builder$query === void 0 ? void 0 : _builder$query.find((item) => item.grouping == "columns")) ? [] : columns;
1091
+ let models = await builder.select(this.shouldSelect(columns)).getModels();
1092
+ this.hydratePivotRelation(models);
1093
+ if (models.length > 0) models = await builder.eagerLoadRelations(models);
1094
+ return new collection_default(models);
1095
+ }
1096
+ async first(columns = ["*"]) {
1097
+ const results = await this.take(1).get(columns);
1098
+ return results.count() > 0 ? results.first() : null;
1099
+ }
1100
+ async firstOrFail(...columns) {
1101
+ const model = await this.first(...columns);
1102
+ if (model !== null) return model;
1103
+ throw new ModelNotFoundError().setModel(this.related.constructor);
1104
+ }
1105
+ async paginate(page = 1, perPage = 15, columns = ["*"]) {
1106
+ this.query.select(this.shouldSelect(columns));
1107
+ return tap(await this.query.paginate(page, perPage), (paginator) => {
1108
+ this.hydratePivotRelation(paginator.items());
1109
+ });
1110
+ }
1111
+ async chunk(count, callback) {
1112
+ return await this.prepareQueryBuilder().chunk(count, async (results, page) => {
1113
+ this.hydratePivotRelation(results.all());
1114
+ return await callback(results, page);
1115
+ });
1116
+ }
1117
+ setUsing(model) {
1118
+ this.using = model;
1119
+ return this;
1120
+ }
1121
+ as(accessor) {
1122
+ this.accessor = accessor;
1123
+ return this;
1124
+ }
1125
+ prepareQueryBuilder() {
1126
+ return this.query.select(this.shouldSelect());
1127
+ }
1128
+ hydratePivotRelation(models) {
1129
+ models.map((model) => {
1130
+ model.setRelation(this.accessor, this.newExistingPivot(this.migratePivotAttributes(model)));
1131
+ });
1132
+ }
1133
+ migratePivotAttributes(model) {
1134
+ const values = {};
1135
+ for (const key in model.attributes) {
1136
+ const value = model.attributes[key];
1137
+ if (key.startsWith("pivot_")) {
1138
+ values[key.substring(6)] = value;
1139
+ model.attributes = (0, radashi.omit)(model.attributes, [key]);
1140
+ }
1141
+ }
1142
+ return values;
1143
+ }
1144
+ withTimestamps(createdAt = null, updatedAt = null) {
1145
+ this.pivotCreatedAt = createdAt;
1146
+ this.pivotUpdatedAt = updatedAt;
1147
+ return this.withPivot(this.createdAt(), this.updatedAt());
1148
+ }
1149
+ shouldSelect(columns = ["*"]) {
1150
+ if ((0, radashi.isEqual)(columns, ["*"])) columns = [this.related.getTable() + ".*"];
1151
+ return columns.concat(this.aliasedPivotColumns());
1152
+ }
1153
+ aliasedPivotColumns() {
1154
+ return (0, collect_js.collect)([this.foreignPivotKey, this.relatedPivotKey].concat(this.pivotColumns)).map((column) => {
1155
+ return this.qualifyPivotColumn(column) + " as pivot_" + column;
1156
+ }).unique().all();
1157
+ }
1158
+ qualifyPivotColumn(column) {
1159
+ return column.includes(".") ? column : this.getTable() + "." + column;
1160
+ }
1161
+ match(models, results, relation) {
1162
+ const dictionary = this.buildDictionary(results);
1163
+ models.map((model) => {
1164
+ const key = model.getKey();
1165
+ if (dictionary[key] !== void 0) model.setRelation(relation, dictionary[key]);
1166
+ });
1167
+ return models;
1168
+ }
1169
+ buildDictionary(results) {
1170
+ const dictionary = {};
1171
+ results.map((result) => {
1172
+ const value = result[this.accessor][this.foreignPivotKey];
1173
+ if (dictionary[value] === void 0) dictionary[value] = new collection_default([]);
1174
+ dictionary[value].push(result);
1175
+ });
1176
+ return dictionary;
1177
+ }
1178
+ addEagerConstraints(models) {
1179
+ this.query.whereIn(this.getQualifiedForeignPivotKeyName(), this.getKeys(models, this.parentKey));
1180
+ }
1181
+ getQualifiedForeignPivotKeyName() {
1182
+ return this.qualifyPivotColumn(this.foreignPivotKey);
1183
+ }
1184
+ getQualifiedRelatedPivotKeyName() {
1185
+ return this.qualifyPivotColumn(this.relatedPivotKey);
1186
+ }
1187
+ wherePivot(column, operator = null, value = null, boolean = "and") {
1188
+ this.pivotWheres.push(Array.prototype.slice.call(arguments));
1189
+ return this.where(this.qualifyPivotColumn(column), operator, value, boolean);
1190
+ }
1191
+ wherePivotBetween(column, values, boolean = "and", not = false) {
1192
+ return this.whereBetween(this.qualifyPivotColumn(column), values, boolean, not);
1193
+ }
1194
+ orWherePivotBetween(column, values) {
1195
+ return this.wherePivotBetween(column, values, "or");
1196
+ }
1197
+ wherePivotNotBetween(column, values, boolean = "and") {
1198
+ return this.wherePivotBetween(column, values, boolean, true);
1199
+ }
1200
+ orWherePivotNotBetween(column, values) {
1201
+ return this.wherePivotBetween(column, values, "or", true);
1202
+ }
1203
+ wherePivotIn(column, values, boolean = "and", not = false) {
1204
+ return this.whereIn(this.qualifyPivotColumn(column), values, boolean, not);
1205
+ }
1206
+ orWherePivot(column, operator = null, value = null) {
1207
+ return this.wherePivot(column, operator, value, "or");
1208
+ }
1209
+ orWherePivotIn(column, values) {
1210
+ return this.wherePivotIn(column, values, "or");
1211
+ }
1212
+ wherePivotNotIn(column, values, boolean = "and") {
1213
+ return this.wherePivotIn(column, values, boolean, true);
1214
+ }
1215
+ orWherePivotNotIn(column, values) {
1216
+ return this.wherePivotNotIn(column, values, "or");
1217
+ }
1218
+ wherePivotNull(column, boolean = "and", not = false) {
1219
+ return this.whereNull(this.qualifyPivotColumn(column), boolean, not);
1220
+ }
1221
+ wherePivotNotNull(column, boolean = "and") {
1222
+ return this.wherePivotNull(column, boolean, true);
1223
+ }
1224
+ orWherePivotNull(column, not = false) {
1225
+ return this.wherePivotNull(column, "or", not);
1226
+ }
1227
+ orWherePivotNotNull(column) {
1228
+ return this.orWherePivotNull(column, true);
1229
+ }
1230
+ orderByPivot(column, direction = "asc") {
1231
+ return this.orderBy(this.qualifyPivotColumn(column), direction);
1232
+ }
1233
+ createdAt() {
1234
+ return this.pivotCreatedAt || this.parent.getCreatedAtColumn();
1235
+ }
1236
+ updatedAt() {
1237
+ return this.pivotUpdatedAt || this.parent.getUpdatedAtColumn();
1238
+ }
1239
+ getExistenceCompareKey() {
1240
+ return this.getQualifiedForeignPivotKeyName();
1241
+ }
1242
+ getRelationExistenceQuery(query, parentQuery, columns = ["*"]) {
1243
+ if (parentQuery.getQuery()._single.table == query.getQuery()._single.table) return this.getRelationExistenceQueryForSelfJoin(query, parentQuery, columns);
1244
+ this.performJoin(query);
1245
+ return super.getRelationExistenceQuery(query, parentQuery, columns);
1246
+ }
1247
+ getRelationExistenceQueryForSelfJoin(query, parentQuery, columns = ["*"]) {
1248
+ const hash = this.getRelationCountHash();
1249
+ query.select(columns).from(this.related.getTable() + " as " + hash);
1250
+ this.related.setTable(hash);
1251
+ this.performJoin(query);
1252
+ return super.getRelationExistenceQuery(query, parentQuery, columns);
1253
+ }
1254
+ };
1255
+ var belongs_to_many_default = BelongsToMany;
1256
+
1257
+ //#endregion
1258
+ //#region src/paginator.ts
1259
+ var Paginator = class {
1260
+ static formatter;
1261
+ _items;
1262
+ _total;
1263
+ _perPage;
1264
+ _lastPage;
1265
+ _currentPage;
1266
+ hasMore = false;
1267
+ options = {};
1268
+ static setFormatter(formatter) {
1269
+ if (typeof formatter !== "function" && formatter !== null && formatter !== void 0) throw new Error("Paginator formatter must be a function or null");
1270
+ if (!formatter) return;
1271
+ this.formatter = formatter;
1272
+ }
1273
+ constructor(items, total, perPage, currentPage = 1, options = {}) {
1274
+ this.options = options;
1275
+ for (const key in options) this[key] = options[key];
1276
+ this._items = new collection_default([]);
1277
+ this._total = total;
1278
+ this._perPage = parseInt(String(perPage));
1279
+ this._lastPage = Math.max(Math.ceil(total / perPage), 1);
1280
+ this._currentPage = currentPage;
1281
+ this.setItems(items);
1282
+ }
1283
+ setItems(items) {
1284
+ this._items = items instanceof collection_default ? items : new collection_default(items);
1285
+ this.hasMore = this._items.count() > this._perPage;
1286
+ this._items = this._items.slice(0, this._perPage);
1287
+ }
1288
+ firstItem() {
1289
+ return this.count() > 0 ? (this._currentPage - 1) * this._perPage + 1 : null;
1290
+ }
1291
+ lastItem() {
1292
+ return this.count() > 0 ? (this.firstItem() ?? 0) + this.count() - 1 : null;
1293
+ }
1294
+ hasMorePages() {
1295
+ return this._currentPage < this._lastPage;
1296
+ }
1297
+ get(index) {
1298
+ return this._items.get(index);
1299
+ }
1300
+ count() {
1301
+ return this._items.count();
1302
+ }
1303
+ items() {
1304
+ return this._items;
1305
+ }
1306
+ map(callback) {
1307
+ return this._items.map(callback);
1308
+ }
1309
+ currentPage() {
1310
+ return this._currentPage;
1311
+ }
1312
+ onFirstPage() {
1313
+ return this._currentPage === 1;
1314
+ }
1315
+ perPage() {
1316
+ return this._perPage;
1317
+ }
1318
+ lastPage() {
1319
+ return this._lastPage;
1320
+ }
1321
+ total() {
1322
+ return this._total;
1323
+ }
1324
+ toData() {
1325
+ if (this.constructor.formatter && typeof this.constructor.formatter === "function") return this.constructor.formatter(this);
1326
+ return {
1327
+ current_page: this._currentPage,
1328
+ data: this._items.toData(),
1329
+ per_page: this._perPage,
1330
+ total: this._total,
1331
+ last_page: this._lastPage,
1332
+ count: this.count()
1333
+ };
1334
+ }
1335
+ toJSON() {
1336
+ return this.toData();
1337
+ }
1338
+ toJson(...args) {
1339
+ return JSON.stringify(this.toData(), ...args);
1340
+ }
1341
+ };
1342
+ var paginator_default = Paginator;
1343
+
1344
+ //#endregion
1345
+ //#region src/builder.ts
1346
+ const Inference$1 = class {};
1347
+ var Builder = class Builder extends Inference$1 {
1348
+ query;
1349
+ connection;
1350
+ model;
1351
+ actions;
1352
+ localMacros = {};
1353
+ eagerLoad = {};
1354
+ globalScopes = {};
1355
+ onDeleteCallback;
1356
+ constructor(query) {
1357
+ super();
1358
+ this.query = query;
1359
+ return this.asProxy();
1360
+ }
1361
+ asProxy() {
1362
+ return new Proxy(this, { get(target, prop) {
1363
+ var _target$query$connect;
1364
+ if (typeof target[prop] !== "undefined") return target[prop];
1365
+ const skipReturning = !!((_target$query$connect = target.query.connector) === null || _target$query$connect === void 0 || (_target$query$connect = _target$query$connect.client.config) === null || _target$query$connect === void 0 || (_target$query$connect = _target$query$connect.client) === null || _target$query$connect === void 0 ? void 0 : _target$query$connect.includes("mysql")) && prop === "returning";
1366
+ if ([
1367
+ "select",
1368
+ "from",
1369
+ "where",
1370
+ "orWhere",
1371
+ "whereColumn",
1372
+ "whereRaw",
1373
+ "whereNot",
1374
+ "orWhereNot",
1375
+ "whereIn",
1376
+ "orWhereIn",
1377
+ "whereNotIn",
1378
+ "orWhereNotIn",
1379
+ "whereNull",
1380
+ "orWhereNull",
1381
+ "whereNotNull",
1382
+ "orWhereNotNull",
1383
+ "whereExists",
1384
+ "orWhereExists",
1385
+ "whereNotExists",
1386
+ "orWhereNotExists",
1387
+ "whereBetween",
1388
+ "orWhereBetween",
1389
+ "whereNotBetween",
1390
+ "orWhereNotBetween",
1391
+ "whereLike",
1392
+ "orWhereLike",
1393
+ "whereILike",
1394
+ "orWhereILike",
1395
+ "whereJsonObject",
1396
+ "whereJsonPath",
1397
+ "whereJsonSupersetOf",
1398
+ "whereJsonSubsetOf",
1399
+ "join",
1400
+ "joinRaw",
1401
+ "leftJoin",
1402
+ "leftOuterJoin",
1403
+ "rightJoin",
1404
+ "rightOuterJoin",
1405
+ "crossJoin",
1406
+ "transacting",
1407
+ "groupBy",
1408
+ "groupByRaw",
1409
+ "returning",
1410
+ "having",
1411
+ "havingRaw",
1412
+ "havingBetween",
1413
+ "limit",
1414
+ "offset",
1415
+ "orderBy",
1416
+ "orderByRaw",
1417
+ "union",
1418
+ "insert",
1419
+ "forUpdate",
1420
+ "forShare",
1421
+ "distinct",
1422
+ "clearOrder",
1423
+ "clear",
1424
+ "clearSelect",
1425
+ "clearWhere",
1426
+ "clearHaving",
1427
+ "clearGroup"
1428
+ ].includes(prop) && !skipReturning) return (...args) => {
1429
+ target.query[prop](...args);
1430
+ return target.asProxy();
1431
+ };
1432
+ if ([
1433
+ "avg",
1434
+ "max",
1435
+ "min",
1436
+ "sum",
1437
+ "count"
1438
+ ].includes(prop)) return (column) => {
1439
+ const instance = target.asProxy();
1440
+ instance.applyScopes();
1441
+ column = !column && prop === "count" ? "*" : column;
1442
+ return instance.query[prop](column);
1443
+ };
1444
+ if (typeof prop === "string") {
1445
+ if (target.hasMacro(prop)) {
1446
+ const instance = target.asProxy();
1447
+ return (...args) => {
1448
+ return instance.localMacros[prop](instance, ...args);
1449
+ };
1450
+ }
1451
+ if (target.hasNamedScope(prop)) {
1452
+ const instance = target.asProxy();
1453
+ return (...args) => {
1454
+ instance.callNamedScope(prop, args);
1455
+ return instance;
1456
+ };
1457
+ }
1458
+ if (prop.startsWith("where")) {
1459
+ const column = (0, radashi.snake)(prop.substring(5));
1460
+ return (...args) => {
1461
+ target.query.where(column, ...args);
1462
+ return target.asProxy();
1463
+ };
1464
+ }
1465
+ }
1466
+ } });
1467
+ }
1468
+ orWhere(...args) {
1469
+ if (typeof args[0] === "function") {
1470
+ const callback = args[0];
1471
+ this.query.orWhere((query) => {
1472
+ this.query = query;
1473
+ callback(this);
1474
+ });
1475
+ return this;
1476
+ }
1477
+ this.query.orWhere(...args);
1478
+ return this;
1479
+ }
1480
+ async chunk(count, callback) {
1481
+ let page = 1;
1482
+ let countResults;
1483
+ do {
1484
+ this.enforceOrderBy();
1485
+ const results = await this.clone().forPage(page, count).get();
1486
+ countResults = results.count();
1487
+ if (countResults == 0) break;
1488
+ if (await callback(results, page) === false) return false;
1489
+ page++;
1490
+ } while (countResults === count);
1491
+ return true;
1492
+ }
1493
+ enforceOrderBy() {
1494
+ if (this.query._statements.filter((item) => item.grouping === "order").length === 0) this.orderBy(this.model.getQualifiedKeyName(), "asc");
1495
+ }
1496
+ clone() {
1497
+ const query = this.query.clone();
1498
+ const builder = new this.constructor(query);
1499
+ builder.connection = this.connection;
1500
+ builder.setModel(this.model);
1501
+ builder.globalScopes = { ...this.globalScopes };
1502
+ builder.localMacros = { ...this.localMacros };
1503
+ builder.eagerLoad = { ...this.eagerLoad };
1504
+ return builder;
1505
+ }
1506
+ forPage(page, perPage = 15) {
1507
+ return this.offset((page - 1) * perPage).limit(perPage);
1508
+ }
1509
+ insert(...args) {
1510
+ return this.query.insert(...args);
1511
+ }
1512
+ update(values) {
1513
+ this.applyScopes();
1514
+ return this.query.update(this.addUpdatedAtColumn(values));
1515
+ }
1516
+ increment(column, amount = 1, extra = {}) {
1517
+ this.applyScopes();
1518
+ const db = this.model.getConnection();
1519
+ return this.query.update(this.addUpdatedAtColumn({
1520
+ ...extra,
1521
+ [column]: db.raw(`${column} + ${amount}`)
1522
+ }));
1523
+ }
1524
+ decrement(column, amount = 1, extra = {}) {
1525
+ this.applyScopes();
1526
+ const db = this.model.getConnection();
1527
+ return this.query.update(this.addUpdatedAtColumn({
1528
+ ...extra,
1529
+ [column]: db.raw(`${column} - ${amount}`)
1530
+ }));
1531
+ }
1532
+ addUpdatedAtColumn(values) {
1533
+ if (!this.model.usesTimestamps() || this.model.getUpdatedAtColumn() === null) return values;
1534
+ values = (0, radashi.assign)({ [this.model.getUpdatedAtColumn()]: this.model.freshTimestampString() }, values);
1535
+ return values;
1536
+ }
1537
+ delete() {
1538
+ if (this.onDeleteCallback) return this.onDeleteCallback(this);
1539
+ return this.query.delete();
1540
+ }
1541
+ onDelete(callback) {
1542
+ this.onDeleteCallback = callback;
1543
+ }
1544
+ forceDelete() {
1545
+ return this.query.delete();
1546
+ }
1547
+ async create(attributes = {}) {
1548
+ return await tap(this.newModelInstance(attributes), async (instance) => {
1549
+ await instance.save({ client: this.query });
1550
+ });
1551
+ }
1552
+ newModelInstance(attributes = {}) {
1553
+ return this.model.newInstance(attributes).setConnection(this.model.getConnectionName());
1554
+ }
1555
+ getQuery() {
1556
+ return this.query;
1557
+ }
1558
+ getModel() {
1559
+ return this.model;
1560
+ }
1561
+ setModel(model) {
1562
+ var _this$query;
1563
+ this.model = model;
1564
+ if (typeof ((_this$query = this.query) === null || _this$query === void 0 || (_this$query = _this$query.client) === null || _this$query === void 0 ? void 0 : _this$query.table) == "function") this.query = this.query.client.table(this.model.getTable());
1565
+ else this.query = this.query.table(this.model.getTable());
1566
+ return this;
1567
+ }
1568
+ qualifyColumn(column) {
1569
+ return this.model.qualifyColumn(column);
1570
+ }
1571
+ setTable(table) {
1572
+ this.query = this.query.table(table);
1573
+ return this;
1574
+ }
1575
+ applyScopes() {
1576
+ if (!this.globalScopes) return this;
1577
+ for (const identifier in this.globalScopes) {
1578
+ const scope = this.globalScopes[identifier];
1579
+ if (scope instanceof scope_default) scope.apply(this, this.getModel());
1580
+ else scope(this);
1581
+ }
1582
+ return this;
1583
+ }
1584
+ hasNamedScope(name) {
1585
+ return this.model && this.model.hasNamedScope(name);
1586
+ }
1587
+ callNamedScope(scope, parameters) {
1588
+ return this.model.callNamedScope(scope, [this, ...parameters]);
1589
+ }
1590
+ callScope(scope, parameters = []) {
1591
+ return scope(this, ...parameters) || this;
1592
+ }
1593
+ scopes(scopes) {
1594
+ scopes.map((scopeName) => {
1595
+ const scopeMethod = getScopeMethod(scopeName);
1596
+ if (typeof this.model[scopeMethod] === "function") this.globalScopes[scopeName] = this.model[scopeMethod];
1597
+ });
1598
+ return this;
1599
+ }
1600
+ withGlobalScope(identifier, scope) {
1601
+ this.globalScopes[identifier] = scope;
1602
+ if (typeof scope.extend === "function") scope.extend(this);
1603
+ return this;
1604
+ }
1605
+ withoutGlobalScope(scope) {
1606
+ if (typeof scope !== "string") scope = scope.constructor.name;
1607
+ this.globalScopes = (0, radashi.omit)(this.globalScopes, [scope]);
1608
+ return this;
1609
+ }
1610
+ macro(name, callback) {
1611
+ this.localMacros[name] = callback;
1612
+ return this;
1613
+ }
1614
+ hasMacro(name) {
1615
+ return name in this.localMacros;
1616
+ }
1617
+ getMacro(name) {
1618
+ return this.localMacros[name];
1619
+ }
1620
+ with(...args) {
1621
+ let eagerLoads = {};
1622
+ if (typeof args[1] === "function") {
1623
+ const eagerLoad = this.parseWithRelations({ [args[0]]: args[1] });
1624
+ this.eagerLoad = (0, radashi.assign)(this.eagerLoad, eagerLoad);
1625
+ return this;
1626
+ }
1627
+ const relations = flattenDeep(args);
1628
+ if (relations.length === 0) return this;
1629
+ for (const relation of relations) {
1630
+ let eagerLoad;
1631
+ if (typeof relation === "string") eagerLoad = { [relation]: (q) => q };
1632
+ else if (typeof relation === "object") eagerLoad = relation;
1633
+ eagerLoads = (0, radashi.assign)(eagerLoads, eagerLoad);
1634
+ }
1635
+ this.eagerLoad = (0, radashi.assign)(this.eagerLoad, this.parseWithRelations(eagerLoads));
1636
+ return this;
1637
+ }
1638
+ has(relation, operator = ">=", count = 1, boolean = "and", callback = null) {
1639
+ if ((0, radashi.isString)(relation)) {
1640
+ if (relation.includes(".")) return this.hasNested(relation, operator, count, boolean, callback);
1641
+ relation = this.getRelationWithoutConstraints(getRelationMethod(relation));
1642
+ }
1643
+ const method = this.canUseExistsForExistenceCheck(operator, count) ? "getRelationExistenceQuery" : "getRelationExistenceCountQuery";
1644
+ const hasQuery = relation[method](relation.getRelated().newModelQuery(), this);
1645
+ if (callback) callback(hasQuery);
1646
+ return this.addHasWhere(hasQuery, relation, operator, count, boolean);
1647
+ }
1648
+ orHas(relation, operator = ">=", count = 1) {
1649
+ return this.has(relation, operator, count, "or");
1650
+ }
1651
+ doesntHave(relation, boolean = "and", callback = null) {
1652
+ return this.has(relation, "<", 1, boolean, callback);
1653
+ }
1654
+ orDoesntHave(relation) {
1655
+ return this.doesntHave(relation, "or");
1656
+ }
1657
+ whereHas(relation, callback = null, operator = ">=", count = 1) {
1658
+ return this.has(relation, operator, count, "and", callback);
1659
+ }
1660
+ orWhereHas(relation, callback = null, operator = ">=", count = 1) {
1661
+ return this.has(relation, operator, count, "or", callback);
1662
+ }
1663
+ whereRelation(relation, ...args) {
1664
+ const column = args.shift();
1665
+ return this.whereHas(relation, (query) => {
1666
+ if (typeof column === "function") column(query);
1667
+ else query.where(column, ...args);
1668
+ });
1669
+ }
1670
+ orWhereRelation(relation, ...args) {
1671
+ const column = args.shift();
1672
+ return this.orWhereHas(relation, function(query) {
1673
+ if (typeof column === "function") column(query);
1674
+ else query.where(column, ...args);
1675
+ });
1676
+ }
1677
+ hasNested(relations, operator = ">=", count = 1, boolean = "and", callback = null) {
1678
+ relations = relations.split(".");
1679
+ const doesntHave = operator === "<" && count === 1;
1680
+ if (doesntHave) {
1681
+ operator = ">=";
1682
+ count = 1;
1683
+ }
1684
+ const closure = (q) => {
1685
+ if (relations.length > 1) q.whereHas(relations.shift(), closure);
1686
+ else q.has(relations.shift(), operator, count, "and", callback);
1687
+ return null;
1688
+ };
1689
+ return this.has(relations.shift(), doesntHave ? "<" : ">=", 1, boolean, closure);
1690
+ }
1691
+ canUseExistsForExistenceCheck(operator, count) {
1692
+ return (operator === ">=" || operator === "<") && count === 1;
1693
+ }
1694
+ addHasWhere(hasQuery, relation, operator, count, boolean) {
1695
+ hasQuery.mergeConstraintsFrom(relation.getQuery());
1696
+ return this.canUseExistsForExistenceCheck(operator, count) ? this.addWhereExistsQuery(hasQuery.getQuery(), boolean, operator === "<" && count === 1) : this.addWhereCountQuery(hasQuery.getQuery(), operator, count, boolean);
1697
+ }
1698
+ addWhereExistsQuery(query, boolean = "and", not = false) {
1699
+ const type = not ? "NotExists" : "Exists";
1700
+ const method = boolean === "and" ? "where" + type : "orWhere" + type;
1701
+ this[method](query.connector);
1702
+ return this;
1703
+ }
1704
+ addWhereCountQuery(query, operator = ">=", count = 1, boolean = "and") {
1705
+ const db = this.model.getConnection();
1706
+ return this.where(db.raw("(" + query.toSQL().sql + ")"), operator, typeof count === "number" ? db.raw(count) : count, boolean);
1707
+ }
1708
+ withAggregate(relations, column, action = null) {
1709
+ if (relations.length === 0) return this;
1710
+ relations = flattenDeep([relations]);
1711
+ let eagerLoads = {};
1712
+ for (const relation of relations) {
1713
+ let eagerLoad;
1714
+ if (typeof relation === "string") eagerLoad = { [relation]: (q) => q };
1715
+ else if (typeof relation === "object") eagerLoad = relation;
1716
+ eagerLoads = (0, radashi.assign)(eagerLoads, eagerLoad);
1717
+ }
1718
+ relations = eagerLoads;
1719
+ const db = this.model.getConnection();
1720
+ if (this.query._statements.filter((item) => item.grouping == "columns").map((item) => item.value).flat().length === 0) this.query.select([this.query._single.table + ".*"]);
1721
+ const parses = this.parseWithRelations(relations);
1722
+ for (let name in parses) {
1723
+ const constraints = parses[name];
1724
+ const segments = name.split(" ");
1725
+ let alias, expression;
1726
+ if (segments.length === 3 && segments[1].toLocaleLowerCase() === "as") [name, alias] = [segments[0], segments[2]];
1727
+ const relation = this.getRelationWithoutConstraints(getRelationMethod(name));
1728
+ if (action) {
1729
+ const hashedColumn = this.query._single.table === relation.query.query._single.table ? `${relation.getRelationCountHash(false)}.${column}` : column;
1730
+ const wrappedColumn = column === "*" ? column : relation.getRelated().qualifyColumn(hashedColumn);
1731
+ expression = action === "exists" ? wrappedColumn : `${action}(${wrappedColumn})`;
1732
+ } else expression = column;
1733
+ const query = relation.getRelationExistenceQuery(relation.getRelated().newModelQuery(), this, db.raw(expression));
1734
+ constraints(query);
1735
+ alias = alias || (0, radashi.snake)(`${name} ${action} ${column}`.replace("/[^[:alnum:][:space:]_]/u", ""));
1736
+ if (action === "exists") this.select(db.raw(`exists(${query.toSql().sql}) as ${alias}`));
1737
+ else this.selectSub(action ? query : query.limit(1), alias);
1738
+ }
1739
+ return this;
1740
+ }
1741
+ toSql() {
1742
+ const query = this.clone();
1743
+ query.applyScopes();
1744
+ return query.query.toSQL();
1745
+ }
1746
+ mergeConstraintsFrom(_from) {
1747
+ return this;
1748
+ }
1749
+ selectSub(query, as) {
1750
+ const [querySub, bindings] = this.createSub(query);
1751
+ const db = this.model.getConnection();
1752
+ return this.select(db.raw("(" + querySub + ") as " + as, bindings));
1753
+ }
1754
+ createSub(query) {
1755
+ return this.parseSub(query);
1756
+ }
1757
+ parseSub(query) {
1758
+ if (query instanceof Builder || query instanceof relation_default) return [query.toSql().sql, query.toSql().bindings];
1759
+ else if ((0, radashi.isString)(query)) return [query, []];
1760
+ else throw new Error("A subquery must be a query builder instance, a Closure, or a string.");
1761
+ }
1762
+ prependDatabaseNameIfCrossDatabaseQuery(query) {
1763
+ if (query.query._single.table !== this.query._single.table) {
1764
+ const databaseName = query.query._single.table;
1765
+ if (!query.query._single.table.startsWith(databaseName) && !query.query._single.table.contains(".")) query.from(databaseName + "." + query.from);
1766
+ }
1767
+ return query;
1768
+ }
1769
+ getRelationWithoutConstraints(relation) {
1770
+ return relation_default.noConstraints(() => {
1771
+ return this.getModel()[relation]();
1772
+ });
1773
+ }
1774
+ withCount(...args) {
1775
+ return this.withAggregate(flattenDeep(args), "*", "count");
1776
+ }
1777
+ withMax(relation, column) {
1778
+ return this.withAggregate(relation, column, "max");
1779
+ }
1780
+ withMin(relation, column) {
1781
+ return this.withAggregate(relation, column, "min");
1782
+ }
1783
+ withAvg(relation, column) {
1784
+ return this.withAggregate(relation, column, "avg");
1785
+ }
1786
+ withSum(relation, column) {
1787
+ return this.withAggregate(relation, column, "sum");
1788
+ }
1789
+ withExists(relation) {
1790
+ return this.withAggregate(relation, "*", "exists");
1791
+ }
1792
+ parseWithRelations(relations) {
1793
+ if (relations.length === 0) return [];
1794
+ let results = {};
1795
+ const constraintsMap = this.prepareNestedWithRelationships(relations);
1796
+ for (const name in constraintsMap) {
1797
+ results = this.addNestedWiths(name, results);
1798
+ results[name] = constraintsMap[name];
1799
+ }
1800
+ return results;
1801
+ }
1802
+ addNestedWiths(name, results) {
1803
+ const progress = [];
1804
+ name.split(".").map((segment) => {
1805
+ progress.push(segment);
1806
+ const last = progress.join(".");
1807
+ if (results[last] === void 0) results[last] = () => {};
1808
+ });
1809
+ return results;
1810
+ }
1811
+ prepareNestedWithRelationships(relations, prefix = "") {
1812
+ let preparedRelationships = {};
1813
+ if (prefix !== "") prefix += ".";
1814
+ for (const key in relations) {
1815
+ const value = relations[key];
1816
+ if ((0, radashi.isString)(value) || Number.isFinite(parseInt(value))) continue;
1817
+ const [attribute, attributeSelectConstraint] = this.parseNameAndAttributeSelectionConstraint(key, value);
1818
+ preparedRelationships = Object.assign({}, preparedRelationships, { [`${prefix}${attribute}`]: attributeSelectConstraint }, this.prepareNestedWithRelationships(value, `${prefix}${attribute}`));
1819
+ relations = (0, radashi.omit)(relations, [key]);
1820
+ }
1821
+ for (const key in relations) {
1822
+ const value = relations[key];
1823
+ let attribute = key, attributeSelectConstraint = value;
1824
+ if ((0, radashi.isString)(value)) [attribute, attributeSelectConstraint] = this.parseNameAndAttributeSelectionConstraint(value);
1825
+ preparedRelationships[`${prefix}${attribute}`] = this.combineConstraints([attributeSelectConstraint, preparedRelationships[`${prefix}${attribute}`] || (() => {})]);
1826
+ }
1827
+ return preparedRelationships;
1828
+ }
1829
+ combineConstraints(constraints) {
1830
+ return (builder) => {
1831
+ constraints.map((constraint) => {
1832
+ builder = constraint(builder) || builder;
1833
+ });
1834
+ return builder;
1835
+ };
1836
+ }
1837
+ parseNameAndAttributeSelectionConstraint(name, value) {
1838
+ return name.includes(":") ? this.createSelectWithConstraint(name) : [name, value];
1839
+ }
1840
+ createSelectWithConstraint(name) {
1841
+ return [name.split(":")[0], (query) => {
1842
+ query.select(name.split(":")[1].split(",").map((column) => {
1843
+ if (column.includes(".")) return column;
1844
+ return query instanceof belongs_to_many_default ? query.related.getTable() + "." + column : column;
1845
+ }));
1846
+ }];
1847
+ }
1848
+ related(relation) {
1849
+ if (typeof this.model[getRelationMethod(relation)] !== "function") throw new RelationNotFoundError(`Model [${this.model.constructor.name}]'s relation [${relation}] doesn't exist.`);
1850
+ return this.model[getRelationMethod(relation)]();
1851
+ }
1852
+ take(...args) {
1853
+ return this.limit(...args);
1854
+ }
1855
+ skip(...args) {
1856
+ return this.offset(...args);
1857
+ }
1858
+ async first(...columns) {
1859
+ this.applyScopes();
1860
+ this.limit(1);
1861
+ let models = await this.getModels(columns);
1862
+ if (models.length > 0) models = await this.eagerLoadRelations(models);
1863
+ return models[0] || null;
1864
+ }
1865
+ async firstOrFail(...columns) {
1866
+ const data = await this.first(...columns);
1867
+ if (data === null) throw new ModelNotFoundError().setModel(this.model.constructor.name);
1868
+ return data;
1869
+ }
1870
+ async findOrFail(...args) {
1871
+ const data = await this.find(...args);
1872
+ if ((0, radashi.isArray)(args[0])) {
1873
+ if (data.count() !== args[0].length) throw new ModelNotFoundError().setModel(this.model.constructor.name, (0, radashi.diff)(args[0], data.modelKeys()));
1874
+ return data;
1875
+ }
1876
+ if (data === null) throw new ModelNotFoundError().setModel(this.model.constructor.name, args[0]);
1877
+ return data;
1878
+ }
1879
+ async findOrNew(id, columns = ["*"]) {
1880
+ const model = await this.find(id, columns);
1881
+ if (model !== null) return model;
1882
+ return this.newModelInstance();
1883
+ }
1884
+ async firstOrNew(attributes = {}, values = {}) {
1885
+ const instance = await this.where(attributes).first();
1886
+ if (instance !== null) return instance;
1887
+ return this.newModelInstance((0, radashi.assign)(attributes, values));
1888
+ }
1889
+ async firstOrCreate(attributes = {}, values = {}) {
1890
+ const instance = await this.where(attributes).first();
1891
+ if (instance !== null) return instance;
1892
+ return tap(this.newModelInstance((0, radashi.assign)(attributes, values)), async (instance$1) => {
1893
+ await instance$1.save({ client: this.query });
1894
+ });
1895
+ }
1896
+ async updateOrCreate(attributes, values = {}) {
1897
+ return await tap(await this.firstOrNew(attributes), async (instance) => {
1898
+ await instance.fill(values).save({ client: this.query });
1899
+ });
1900
+ }
1901
+ latest(column = "id") {
1902
+ if (column === null) column = this.model.getCreatedAtColumn() || "created_at";
1903
+ this.query.orderBy(column, "desc");
1904
+ return this;
1905
+ }
1906
+ oldest(column = "id") {
1907
+ if (column === null) column = this.model.getCreatedAtColumn() || "created_at";
1908
+ this.query.orderBy(column, "asc");
1909
+ return this;
1910
+ }
1911
+ async find(id, columns) {
1912
+ if ((0, radashi.isArray)(id) || id instanceof collection_default) return await this.findMany(id, columns);
1913
+ return await this.where(this.model.getKeyName(), id).first(columns);
1914
+ }
1915
+ async findMany(ids, columns = ["*"]) {
1916
+ if (ids instanceof collection_default) ids = ids.modelKeys();
1917
+ ids = (0, radashi.isArray)(ids) ? ids : [ids];
1918
+ if (ids.length === 0) return new collection_default([]);
1919
+ return await this.whereIn(this.model.getKeyName(), ids).get(columns);
1920
+ }
1921
+ async pluck(column) {
1922
+ return new collection_default(await this.query.pluck(column));
1923
+ }
1924
+ async destroy(ids) {
1925
+ if (ids instanceof collection_default) ids = ids.modelKeys();
1926
+ if (ids instanceof collect_js.Collection) ids = ids.all();
1927
+ ids = (0, radashi.isArray)(ids) ? ids : Array.prototype.slice.call(ids);
1928
+ if (ids.length === 0) return 0;
1929
+ const key = this.model.newInstance().getKeyName();
1930
+ let count = 0;
1931
+ const models = await this.model.newModelQuery().whereIn(key, ids).get();
1932
+ for (const model of models) if (await model.delete()) count++;
1933
+ return count;
1934
+ }
1935
+ async get(columns = ["*"]) {
1936
+ this.applyScopes();
1937
+ let models = await this.getModels(columns);
1938
+ if (models.length > 0) models = await this.eagerLoadRelations(models);
1939
+ return new collection_default(models);
1940
+ }
1941
+ async all(columns = ["*"]) {
1942
+ return await this.model.newModelQuery().get(columns);
1943
+ }
1944
+ async paginate(page = 1, perPage = 10) {
1945
+ var _this;
1946
+ page = page || 1;
1947
+ perPage = perPage || ((_this = this) === null || _this === void 0 || (_this = _this.model) === null || _this === void 0 ? void 0 : _this.perPage) || 15;
1948
+ this.applyScopes();
1949
+ const total = await this.query.clone().clearOrder().clearSelect().count(this.primaryKey);
1950
+ let results = [];
1951
+ if (total > 0) {
1952
+ const skip = (page - 1) * (perPage ?? 10);
1953
+ this.take(perPage).skip(skip);
1954
+ results = await this.getModels();
1955
+ if (results.length > 0) results = await this.eagerLoadRelations(results);
1956
+ } else results = [];
1957
+ return new paginator_default(results, parseInt(total), perPage, page);
1958
+ }
1959
+ async getModels(...columns) {
1960
+ columns = (0, radashi.flat)(columns);
1961
+ if (columns.length > 0) {
1962
+ if (this.query._statements.filter((item) => item.grouping == "columns").length == 0 && columns[0] !== "*") this.query.select(...columns);
1963
+ }
1964
+ return this.hydrate(await this.query.get()).all();
1965
+ }
1966
+ getRelation(name) {
1967
+ if (typeof this.model[getRelationMethod(name)] !== "function") throw new RelationNotFoundError(`Model [${this.model.constructor.name}]'s relation [${name}] doesn't exist.`);
1968
+ const relation = relation_default.noConstraints(() => this.model.newInstance(this.model.attributes)[getRelationMethod(name)]());
1969
+ const nested = this.relationsNestedUnder(name);
1970
+ if (Object.keys(nested).length > 0) relation.query.with(nested);
1971
+ return relation.asProxy();
1972
+ }
1973
+ relationsNestedUnder(relation) {
1974
+ const nested = {};
1975
+ for (const name in this.eagerLoad) {
1976
+ const constraints = this.eagerLoad[name];
1977
+ if (this.isNestedUnder(relation, name)) nested[name.substring((relation + ".").length)] = constraints;
1978
+ }
1979
+ return nested;
1980
+ }
1981
+ isNestedUnder(relation, name) {
1982
+ return name.includes(".") && name.startsWith(relation + ".");
1983
+ }
1984
+ async eagerLoadRelation(models, name, constraints) {
1985
+ const relation = this.getRelation(name);
1986
+ relation.addEagerConstraints(models);
1987
+ constraints(relation);
1988
+ return relation.match(relation.initRelation(models, name), await relation.get(), name);
1989
+ }
1990
+ async eagerLoadRelations(models) {
1991
+ for (const name in this.eagerLoad) {
1992
+ const constraints = this.eagerLoad[name];
1993
+ if (!name.includes(".")) models = await this.eagerLoadRelation(models, name, constraints);
1994
+ }
1995
+ return models;
1996
+ }
1997
+ hydrate(items) {
1998
+ return new collection_default(items.map((item) => {
1999
+ if (!this.model) return item;
2000
+ return this.model.newFromBuilder(item);
2001
+ }));
2002
+ }
2003
+ };
2004
+ var builder_default = Builder;
2005
+
2006
+ //#endregion
2007
+ //#region src/relations/has-one-or-many.ts
2008
+ const HasOneOrMany = (Relation$1) => {
2009
+ return class extends Relation$1 {
2010
+ getRelationValue(dictionary, key, type) {
2011
+ const value = dictionary[key];
2012
+ return type === "one" ? value[0] : new collection_default(value);
2013
+ }
2014
+ matchOneOrMany(models, results, relation, type) {
2015
+ const dictionary = this.buildDictionary(results);
2016
+ models.map((model) => {
2017
+ const key = model.attributes[this.localKey];
2018
+ if (dictionary[key] !== void 0) model.setRelation(relation, this.getRelationValue(dictionary, key, type));
2019
+ });
2020
+ return models;
2021
+ }
2022
+ buildDictionary(results) {
2023
+ const foreign = this.getForeignKeyName();
2024
+ return (0, collect_js.default)(results).mapToDictionary((result) => [result[foreign], result]).all();
2025
+ }
2026
+ async save(model) {
2027
+ this.setForeignAttributesForCreate(model);
2028
+ return await model.save() ? model : false;
2029
+ }
2030
+ async saveMany(models) {
2031
+ await Promise.all(models.map(async (model) => {
2032
+ await this.save(model);
2033
+ }));
2034
+ return models instanceof collection_default ? models : new collection_default(models);
2035
+ }
2036
+ async create(attributes = {}) {
2037
+ return await tap(this.related.constructor.init(attributes), async (instance) => {
2038
+ this.setForeignAttributesForCreate(instance);
2039
+ await instance.save();
2040
+ });
2041
+ }
2042
+ async createMany(records) {
2043
+ const instances = await Promise.all(records.map(async (record) => {
2044
+ return await this.create(record);
2045
+ }));
2046
+ return instances instanceof collection_default ? instances : new collection_default(instances);
2047
+ }
2048
+ setForeignAttributesForCreate(model) {
2049
+ model[this.getForeignKeyName()] = this.getParentKey();
2050
+ }
2051
+ getForeignKeyName() {
2052
+ const segments = this.getQualifiedForeignKeyName().split(".");
2053
+ return segments[segments.length - 1];
2054
+ }
2055
+ getParentKey() {
2056
+ return this.parent.attributes[this.localKey];
2057
+ }
2058
+ getQualifiedForeignKeyName() {
2059
+ return this.foreignKey;
2060
+ }
2061
+ getExistenceCompareKey() {
2062
+ return this.getQualifiedForeignKeyName();
2063
+ }
2064
+ addConstraints() {
2065
+ if (this.constructor.constraints) {
2066
+ const query = this.getRelationQuery();
2067
+ query.where(this.foreignKey, "=", this.getParentKey());
2068
+ query.whereNotNull(this.foreignKey);
2069
+ }
2070
+ }
2071
+ };
2072
+ };
2073
+ var has_one_or_many_default = HasOneOrMany;
2074
+
2075
+ //#endregion
2076
+ //#region src/relations/has-many.ts
2077
+ var HasMany = class extends compose(relation_default, has_one_or_many_default) {
2078
+ foreignKey;
2079
+ localKey;
2080
+ constructor(query, parent, foreignKey, localKey) {
2081
+ super(query, parent);
2082
+ this.foreignKey = foreignKey;
2083
+ this.localKey = localKey;
2084
+ this.addConstraints();
2085
+ return this.asProxy();
2086
+ }
2087
+ initRelation(models, relation) {
2088
+ models.map((model) => {
2089
+ model.setRelation(relation, new collection_default([]));
2090
+ });
2091
+ return models;
2092
+ }
2093
+ async getResults() {
2094
+ return this.getParentKey() !== null ? await this.query.get() : new collection_default([]);
2095
+ }
2096
+ getForeignKeyName() {
2097
+ var _this$foreignKey;
2098
+ const segments = (_this$foreignKey = this.foreignKey) === null || _this$foreignKey === void 0 ? void 0 : _this$foreignKey.split(".");
2099
+ return segments === null || segments === void 0 ? void 0 : segments.pop();
2100
+ }
2101
+ buildDictionary(results) {
2102
+ const foreign = this.getForeignKeyName();
2103
+ return (0, collect_js.collect)(results).mapToDictionary((result) => [result[foreign], result]).all();
2104
+ }
2105
+ match(models, results, relation) {
2106
+ return this.matchOneOrMany(models, results, relation, "many");
2107
+ }
2108
+ addEagerConstraints(models) {
2109
+ this.query.whereIn(this.foreignKey, this.getKeys(models, this.localKey));
2110
+ }
2111
+ };
2112
+ var has_many_default = HasMany;
2113
+
2114
+ //#endregion
2115
+ //#region src/relations/concerns/supports-default-models.ts
2116
+ const SupportsDefaultModels = (Relation$1) => {
2117
+ return class extends Relation$1 {
2118
+ _withDefault;
2119
+ withDefault(callback = true) {
2120
+ this._withDefault = callback;
2121
+ return this;
2122
+ }
2123
+ getDefaultFor(parent) {
2124
+ if (!this._withDefault) return null;
2125
+ const instance = this.newRelatedInstanceFor(parent);
2126
+ if (typeof this._withDefault === "function") return this._withDefault(instance, parent) || instance;
2127
+ if (typeof this._withDefault === "object") for (const key in this._withDefault) instance.setAttribute(key, this._withDefault[key]);
2128
+ return instance;
2129
+ }
2130
+ };
2131
+ };
2132
+ var supports_default_models_default = SupportsDefaultModels;
2133
+
2134
+ //#endregion
2135
+ //#region src/relations/has-one.ts
2136
+ var HasOne = class extends compose(relation_default, has_one_or_many_default, supports_default_models_default) {
2137
+ foreignKey;
2138
+ localKey;
2139
+ constructor(query, parent, foreignKey, localKey) {
2140
+ super(query, parent);
2141
+ this.foreignKey = foreignKey;
2142
+ this.localKey = localKey;
2143
+ this.addConstraints();
2144
+ return this.asProxy();
2145
+ }
2146
+ initRelation(models, relation) {
2147
+ models.map((model) => {
2148
+ model.setRelation(relation, this.getDefaultFor(model));
2149
+ });
2150
+ return models;
2151
+ }
2152
+ matchOne(models, results, relation) {
2153
+ return this.matchOneOrMany(models, results, relation, "one");
2154
+ }
2155
+ getForeignKeyName() {
2156
+ var _this$foreignKey;
2157
+ const segments = (_this$foreignKey = this.foreignKey) === null || _this$foreignKey === void 0 ? void 0 : _this$foreignKey.split(".");
2158
+ return segments === null || segments === void 0 ? void 0 : segments.pop();
2159
+ }
2160
+ async getResults() {
2161
+ if (this.getParentKey() === null) return this.getDefaultFor(this.parent);
2162
+ return await this.query.first() || this.getDefaultFor(this.parent);
2163
+ }
2164
+ match(models, results, relation) {
2165
+ return this.matchOneOrMany(models, results, relation, "one");
2166
+ }
2167
+ addEagerConstraints(models) {
2168
+ this.query.whereIn(this.foreignKey, this.getKeys(models, this.localKey));
2169
+ }
2170
+ newRelatedInstanceFor(parent) {
2171
+ return this.related.newInstance().setAttribute(this.getForeignKeyName(), parent[this.localKey]);
2172
+ }
2173
+ };
2174
+ var has_one_default = HasOne;
2175
+
2176
+ //#endregion
2177
+ //#region src/concerns/has-timestamps.ts
2178
+ var has_timestamps_exports = /* @__PURE__ */ __export({ default: () => has_timestamps_default });
2179
+ const HasTimestamps = (Model$1) => {
2180
+ return class extends Model$1 {
2181
+ static CREATED_AT = "created_at";
2182
+ static UPDATED_AT = "updated_at";
2183
+ static DELETED_AT = "deleted_at";
2184
+ timestamps = true;
2185
+ dateFormat = "YYYY-MM-DD HH:mm:ss";
2186
+ usesTimestamps() {
2187
+ return this.timestamps;
2188
+ }
2189
+ updateTimestamps() {
2190
+ const time = this.freshTimestampString();
2191
+ const updatedAtColumn = this.getUpdatedAtColumn();
2192
+ if (updatedAtColumn && !this.isDirty(updatedAtColumn)) this.setUpdatedAt(time);
2193
+ const createdAtColumn = this.getCreatedAtColumn();
2194
+ if (!this.exists && createdAtColumn && !this.isDirty(createdAtColumn)) this.setCreatedAt(time);
2195
+ return this;
2196
+ }
2197
+ getCreatedAtColumn() {
2198
+ return this.constructor.CREATED_AT;
2199
+ }
2200
+ getUpdatedAtColumn() {
2201
+ return this.constructor.UPDATED_AT;
2202
+ }
2203
+ setCreatedAt(value) {
2204
+ this.attributes[this.getCreatedAtColumn()] = value;
2205
+ return this;
2206
+ }
2207
+ setUpdatedAt(value) {
2208
+ this.attributes[this.getUpdatedAtColumn()] = value;
2209
+ return this;
2210
+ }
2211
+ freshTimestamp() {
2212
+ const time = /* @__PURE__ */ new Date();
2213
+ time.setMilliseconds(0);
2214
+ return time;
2215
+ }
2216
+ freshTimestampString() {
2217
+ return this.fromDateTime(this.freshTimestamp());
2218
+ }
2219
+ };
2220
+ };
2221
+ var has_timestamps_default = HasTimestamps;
2222
+
2223
+ //#endregion
2224
+ //#region src/concerns/hides-attributes.ts
2225
+ var hides_attributes_exports = /* @__PURE__ */ __export({ default: () => hides_attributes_default });
2226
+ const HidesAttributes = (Model$1) => {
2227
+ return class extends Model$1 {
2228
+ hidden = [];
2229
+ visible = [];
2230
+ makeVisible(...keys) {
2231
+ const visible = flattenDeep(keys);
2232
+ if (this.visible.length > 0) this.visible = [...this.visible, ...visible];
2233
+ this.hidden = (0, radashi.diff)(this.hidden, visible);
2234
+ return this;
2235
+ }
2236
+ makeHidden(key, ...keys) {
2237
+ const hidden = flattenDeep([...key, ...keys]);
2238
+ if (this.hidden.length > 0) this.hidden = [...this.hidden, ...hidden];
2239
+ return this;
2240
+ }
2241
+ getHidden() {
2242
+ return this.hidden;
2243
+ }
2244
+ getVisible() {
2245
+ return this.visible;
2246
+ }
2247
+ setHidden(hidden) {
2248
+ this.hidden = hidden;
2249
+ return this;
2250
+ }
2251
+ setVisible(visible) {
2252
+ this.visible = visible;
2253
+ return this;
2254
+ }
2255
+ };
2256
+ };
2257
+ var hides_attributes_default = HidesAttributes;
2258
+
2259
+ //#endregion
2260
+ //#region src/concerns/unique-ids.ts
2261
+ var unique_ids_exports = /* @__PURE__ */ __export({ default: () => unique_ids_default });
2262
+ const UniqueIds = (Model$1) => {
2263
+ return class extends Model$1 {
2264
+ useUniqueIds = false;
2265
+ usesUniqueIds() {
2266
+ return this.useUniqueIds;
2267
+ }
2268
+ uniqueIds() {
2269
+ return [];
2270
+ }
2271
+ setUniqueIds() {
2272
+ const uniqueIds = this.uniqueIds();
2273
+ for (const column of uniqueIds) if (this[column] === null || this[column] === void 0) this[column] = this.newUniqueId();
2274
+ }
2275
+ };
2276
+ };
2277
+ var unique_ids_default = UniqueIds;
2278
+
2279
+ //#endregion
2280
+ //#region src/casts/attribute.ts
2281
+ var Attribute = class Attribute {
2282
+ get;
2283
+ set;
2284
+ withCaching = false;
2285
+ withObjectCaching = true;
2286
+ constructor({ get: get$1 = null, set: set$1 = null }) {
2287
+ this.get = get$1;
2288
+ this.set = set$1;
2289
+ }
2290
+ static make({ get: get$1 = null, set: set$1 = null }) {
2291
+ return new Attribute({
2292
+ get: get$1,
2293
+ set: set$1
2294
+ });
2295
+ }
2296
+ static get(get$1) {
2297
+ return new Attribute({ get: get$1 });
2298
+ }
2299
+ static set(set$1) {
2300
+ return new Attribute({ set: set$1 });
2301
+ }
2302
+ withoutObjectCaching() {
2303
+ this.withObjectCaching = false;
2304
+ return this;
2305
+ }
2306
+ shouldCache() {
2307
+ this.withCaching = true;
2308
+ return this;
2309
+ }
2310
+ };
2311
+ var attribute_default = Attribute;
2312
+
2313
+ //#endregion
2314
+ //#region src/query-builder.ts
2315
+ const Inference = class {};
2316
+ var QueryBuilder = class QueryBuilder extends Inference {
2317
+ model;
2318
+ schema;
2319
+ connector;
2320
+ constructor(config, connector) {
2321
+ super();
2322
+ this.connector = connector(config);
2323
+ return this.asProxy();
2324
+ }
2325
+ asProxy() {
2326
+ return new Proxy(this, {
2327
+ get: function(target, prop) {
2328
+ var _target$connector$cli;
2329
+ if (typeof target[prop] !== "undefined") return target[prop];
2330
+ if (["destroy", "schema"].includes(prop)) return target.connector.schema;
2331
+ const skipReturning = !!((_target$connector$cli = target.connector.client.config) === null || _target$connector$cli === void 0 || (_target$connector$cli = _target$connector$cli.client) === null || _target$connector$cli === void 0 ? void 0 : _target$connector$cli.includes("mysql")) && prop === "returning";
2332
+ if ([
2333
+ "select",
2334
+ "from",
2335
+ "where",
2336
+ "orWhere",
2337
+ "whereColumn",
2338
+ "whereRaw",
2339
+ "whereNot",
2340
+ "orWhereNot",
2341
+ "whereIn",
2342
+ "orWhereIn",
2343
+ "whereNotIn",
2344
+ "orWhereNotIn",
2345
+ "whereNull",
2346
+ "orWhereNull",
2347
+ "whereNotNull",
2348
+ "orWhereNotNull",
2349
+ "whereExists",
2350
+ "orWhereExists",
2351
+ "whereNotExists",
2352
+ "orWhereNotExists",
2353
+ "whereBetween",
2354
+ "orWhereBetween",
2355
+ "whereNotBetween",
2356
+ "orWhereNotBetween",
2357
+ "whereLike",
2358
+ "orWhereLike",
2359
+ "whereILike",
2360
+ "orWhereILike",
2361
+ "whereJsonObject",
2362
+ "whereJsonPath",
2363
+ "whereJsonSupersetOf",
2364
+ "whereJsonSubsetOf",
2365
+ "join",
2366
+ "joinRaw",
2367
+ "leftJoin",
2368
+ "leftOuterJoin",
2369
+ "rightJoin",
2370
+ "rightOuterJoin",
2371
+ "crossJoin",
2372
+ "transacting",
2373
+ "groupBy",
2374
+ "groupByRaw",
2375
+ "returning",
2376
+ "having",
2377
+ "havingRaw",
2378
+ "havingBetween",
2379
+ "limit",
2380
+ "offset",
2381
+ "orderBy",
2382
+ "orderByRaw",
2383
+ "union",
2384
+ "insert",
2385
+ "forUpdate",
2386
+ "forShare",
2387
+ "distinct",
2388
+ "clearOrder",
2389
+ "clear",
2390
+ "clearSelect",
2391
+ "clearWhere",
2392
+ "clearHaving",
2393
+ "clearGroup"
2394
+ ].includes(prop) && !skipReturning) return (...args) => {
2395
+ target.connector[prop](...args);
2396
+ return target.asProxy();
2397
+ };
2398
+ return target.connector[prop];
2399
+ },
2400
+ set: function(target, prop, value) {
2401
+ if (typeof target[prop] !== "undefined") {
2402
+ target[prop] = value;
2403
+ return target;
2404
+ }
2405
+ target.connector[prop] = value;
2406
+ return target;
2407
+ }
2408
+ });
2409
+ }
2410
+ async beginTransaction() {
2411
+ return await this.connector.transaction();
2412
+ }
2413
+ table(table) {
2414
+ const c = this.connector.table(table);
2415
+ return new QueryBuilder(null, () => c);
2416
+ }
2417
+ transaction(callback) {
2418
+ if (callback) return this.connector.transaction((trx) => {
2419
+ return callback(new QueryBuilder(null, () => trx));
2420
+ });
2421
+ return callback;
2422
+ }
2423
+ async find(id, columns = ["*"]) {
2424
+ return await this.connector.where("id", id).first(...columns);
2425
+ }
2426
+ async get(_columns = ["*"]) {
2427
+ return await this.connector;
2428
+ }
2429
+ async exists() {
2430
+ const result = await this.connector.first();
2431
+ return result !== null && result !== void 0;
2432
+ }
2433
+ skip(...args) {
2434
+ return this.offset(...args);
2435
+ }
2436
+ take(...args) {
2437
+ return this.limit(...args);
2438
+ }
2439
+ async chunk(count, callback) {
2440
+ if (this.connector._statements.filter((item) => item.grouping === "order").length === 0) throw new Error("You must specify an orderBy clause when using this function.");
2441
+ let page = 1;
2442
+ let countResults;
2443
+ do {
2444
+ const results = await this.clone().forPage(page, count).get();
2445
+ countResults = results.length;
2446
+ if (countResults == 0) break;
2447
+ if (await callback(results, page) === false) return false;
2448
+ page++;
2449
+ } while (countResults === count);
2450
+ return true;
2451
+ }
2452
+ async paginate(page = 1, perPage = 15, _pageName, _page) {
2453
+ const total = await this.clone().clearOrder().count("*");
2454
+ let results;
2455
+ if (total > 0) {
2456
+ const skip = (page - 1) * perPage;
2457
+ this.take(perPage).skip(skip);
2458
+ results = await this.get();
2459
+ } else results = [];
2460
+ return new paginator_default(results, parseInt(total), perPage, page);
2461
+ }
2462
+ forPage(page = 1, perPage = 15) {
2463
+ return this.offset((page - 1) * perPage).limit(perPage);
2464
+ }
2465
+ toSQL(...args) {
2466
+ return this.connector.toSQL(...args);
2467
+ }
2468
+ async count(column) {
2469
+ const [{ aggregate }] = await this.connector.count(column, { as: "aggregate" });
2470
+ return Number(aggregate);
2471
+ }
2472
+ async min(column) {
2473
+ const [{ aggregate }] = await this.connector.min(column, { as: "aggregate" });
2474
+ return Number(aggregate);
2475
+ }
2476
+ async max(column) {
2477
+ const [{ aggregate }] = await this.connector.max(column, { as: "aggregate" });
2478
+ return Number(aggregate);
2479
+ }
2480
+ async sum(column) {
2481
+ const [{ aggregate }] = await this.connector.sum(column, { as: "aggregate" });
2482
+ return Number(aggregate);
2483
+ }
2484
+ async avg(column) {
2485
+ const [{ aggregate }] = await this.connector.avg(column, { as: "aggregate" });
2486
+ return Number(aggregate);
2487
+ }
2488
+ clone() {
2489
+ const c = this.connector.clone();
2490
+ return new QueryBuilder(null, () => c);
2491
+ }
2492
+ async delete() {
2493
+ return await this.connector.delete();
2494
+ }
2495
+ async insert(...args) {
2496
+ return await this.connector.insert(...args);
2497
+ }
2498
+ async update(...args) {
2499
+ return await this.connector.update(...args);
2500
+ }
2501
+ destroy(...args) {
2502
+ return this.connector.destroy(...args);
2503
+ }
2504
+ get _statements() {
2505
+ return this.connector._statements;
2506
+ }
2507
+ get _single() {
2508
+ return this.connector._single;
2509
+ }
2510
+ get from() {
2511
+ return this.connector.from;
2512
+ }
2513
+ };
2514
+ var query_builder_default = QueryBuilder;
2515
+
2516
+ //#endregion
2517
+ //#region src/arquebus.ts
2518
+ var arquebus = class arquebus {
2519
+ static connectorFactory = null;
2520
+ static instance = null;
2521
+ manager;
2522
+ connections;
2523
+ models;
2524
+ constructor() {
2525
+ this.manager = {};
2526
+ this.connections = {};
2527
+ this.models = {};
2528
+ }
2529
+ getConstructor() {
2530
+ return this.constructor;
2531
+ }
2532
+ static getInstance() {
2533
+ if (this.instance === null) this.instance = new arquebus();
2534
+ return this.instance;
2535
+ }
2536
+ /**
2537
+ * Initialize a new database connection
2538
+ *
2539
+ * @returns
2540
+ */
2541
+ static fire(connection = null) {
2542
+ return this.getInstance().getConnection(connection);
2543
+ }
2544
+ /**
2545
+ * Initialize a new database connection
2546
+ *
2547
+ * This is an alias of `arquebus.fire()` and will be removed in the future
2548
+ *
2549
+ * @deprecated since version 0.3.0
2550
+ * @alias fire
2551
+ *
2552
+ * @returns
2553
+ */
2554
+ static connection(connection = null) {
2555
+ return this.fire(connection);
2556
+ }
2557
+ static setConnectorFactory(connectorFactory) {
2558
+ this.connectorFactory = connectorFactory;
2559
+ }
2560
+ static getConnectorFactory() {
2561
+ return this.connectorFactory ?? knex.default;
2562
+ }
2563
+ static addConnection(config, name = "default") {
2564
+ return this.getInstance().addConnection(config, name);
2565
+ }
2566
+ static beginTransaction(connection = null) {
2567
+ return this.getInstance().beginTransaction(connection);
2568
+ }
2569
+ static transaction(callback, connection = null) {
2570
+ return this.getInstance().transaction(callback, connection);
2571
+ }
2572
+ static table(name, connection = null) {
2573
+ return this.getInstance().table(name, connection);
2574
+ }
2575
+ static schema(connection = null) {
2576
+ return this.getInstance().schema(connection);
2577
+ }
2578
+ static async destroyAll() {
2579
+ await this.getInstance().destroyAll();
2580
+ }
2581
+ static createModel(name, options) {
2582
+ return this.getInstance().createModel(name, options);
2583
+ }
2584
+ connection(connection = null) {
2585
+ return this.getConnection(connection);
2586
+ }
2587
+ getConnection(name = null) {
2588
+ name = name || "default";
2589
+ const resolvedName = this.connections[name] ? name : "default";
2590
+ if (this.manager[resolvedName] === void 0) {
2591
+ const queryBuilder = new query_builder_default(this.connections[resolvedName], arquebus.getConnectorFactory());
2592
+ this.manager[resolvedName] = queryBuilder;
2593
+ }
2594
+ return this.manager[resolvedName];
2595
+ }
2596
+ addConnection(config, name = "default") {
2597
+ this.connections[name] = {
2598
+ ...config,
2599
+ connection: {
2600
+ ...config.connection,
2601
+ dateStrings: true,
2602
+ typeCast: function(field, next) {
2603
+ if (field.type === "JSON") return field.string("utf8");
2604
+ return next();
2605
+ }
2606
+ }
2607
+ };
2608
+ }
2609
+ /**
2610
+ * Autoload the config file
2611
+ *
2612
+ * @param addConnection
2613
+ * @default true
2614
+ * If set to `false` we will no attempt add the connection, we
2615
+ * will just go ahead and return the config
2616
+ *
2617
+ * @returns
2618
+ */
2619
+ static async autoLoad(addConnection = true) {
2620
+ let config;
2621
+ const jsPath = path.default.resolve("arquebus.config.js");
2622
+ const tsPath = path.default.resolve("arquebus.config.ts");
2623
+ const instance = this.getInstance();
2624
+ if ((0, fs.existsSync)(jsPath)) {
2625
+ config = (await import(jsPath)).default;
2626
+ if (addConnection) instance.addConnection(config, config.client);
2627
+ return config;
2628
+ }
2629
+ if ((0, fs.existsSync)(tsPath)) if (process.env.NODE_ENV !== "production") {
2630
+ config = (await import(tsPath)).default;
2631
+ if (addConnection) instance.addConnection(config, config.client);
2632
+ return config;
2633
+ } else throw new Error("arquebus.config.ts found in production without build step");
2634
+ const candidateDirs = [
2635
+ process.cwd(),
2636
+ path.default.join(process.cwd(), "test", "cli"),
2637
+ path.default.join(process.cwd(), "test")
2638
+ ];
2639
+ for (const dir of candidateDirs) {
2640
+ const found = __h3ravel_shared.FileSystem.resolveFileUp("arquebus.config", [
2641
+ "js",
2642
+ "ts",
2643
+ "cjs"
2644
+ ], dir);
2645
+ if (found) if (!found.endsWith(".ts") || process.env.NODE_ENV !== "production") {
2646
+ config = (await import(found)).default;
2647
+ if (addConnection) instance.addConnection(config, config.client);
2648
+ return config;
2649
+ } else throw new Error("arquebus.config.ts found in production without build step");
2650
+ }
2651
+ return {};
2652
+ }
2653
+ beginTransaction(connection = null) {
2654
+ return this.connection(connection).beginTransaction();
2655
+ }
2656
+ transaction(callback, connection = null) {
2657
+ return this.connection(connection).transaction(callback);
2658
+ }
2659
+ table(name, connection = null) {
2660
+ return this.connection(connection).table(name);
2661
+ }
2662
+ schema(connection = null) {
2663
+ return this.connection(connection).schema;
2664
+ }
2665
+ async destroyAll() {
2666
+ await Promise.all(Object.values(this.manager).map((connection) => {
2667
+ return connection === null || connection === void 0 ? void 0 : connection.destroy();
2668
+ }));
2669
+ }
2670
+ createModel(name, options = {}) {
2671
+ let BaseModel$1 = Model;
2672
+ if ("plugins" in options) BaseModel$1 = compose(BaseModel$1, ...options.plugins ?? []);
2673
+ this.models = {
2674
+ ...this.models,
2675
+ [name]: class extends BaseModel$1 {
2676
+ table = (options === null || options === void 0 ? void 0 : options.table) ?? null;
2677
+ connection = (options === null || options === void 0 ? void 0 : options.connection) ?? null;
2678
+ timestamps = (options === null || options === void 0 ? void 0 : options.timestamps) ?? true;
2679
+ primaryKey = (options === null || options === void 0 ? void 0 : options.primaryKey) ?? "id";
2680
+ keyType = (options === null || options === void 0 ? void 0 : options.keyType) ?? "int";
2681
+ incrementing = (options === null || options === void 0 ? void 0 : options.incrementing) ?? true;
2682
+ with = (options === null || options === void 0 ? void 0 : options.with) ?? [];
2683
+ casts = (options === null || options === void 0 ? void 0 : options.casts) ?? {};
2684
+ static CREATED_AT = (options === null || options === void 0 ? void 0 : options.CREATED_AT) ?? "created_at";
2685
+ static UPDATED_AT = (options === null || options === void 0 ? void 0 : options.UPDATED_AT) ?? "updated_at";
2686
+ static DELETED_AT = (options === null || options === void 0 ? void 0 : options.DELETED_AT) ?? "deleted_at";
2687
+ }
2688
+ };
2689
+ if ("attributes" in options) for (const attribute in options.attributes) {
2690
+ if (options.attributes[attribute] instanceof attribute_default === false) throw new Error("Attribute must be an instance of \"Attribute\"");
2691
+ this.models[name].prototype[getAttrMethod(attribute)] = () => {
2692
+ var _options$attributes;
2693
+ return (_options$attributes = options.attributes) === null || _options$attributes === void 0 ? void 0 : _options$attributes[attribute];
2694
+ };
2695
+ }
2696
+ if ("relations" in options) for (const relation in options.relations) this.models[name].prototype[getRelationMethod(relation)] = function() {
2697
+ var _options$relations;
2698
+ return (_options$relations = options.relations) === null || _options$relations === void 0 ? void 0 : _options$relations[relation](this);
2699
+ };
2700
+ if ("scopes" in options) for (const scope in options.scopes) this.models[name].prototype[getScopeMethod(scope)] = options.scopes[scope];
2701
+ this.models[name].setConnectionResolver(this);
2702
+ return this.models[name];
2703
+ }
2704
+ };
2705
+ var arquebus_default = arquebus;
2706
+
2707
+ //#endregion
2708
+ //#region src/model.ts
2709
+ const ModelClass = class {};
2710
+ const BaseModel = compose(ModelClass, has_attributes_default, hides_attributes_default, has_relations_default, has_timestamps_default, has_hooks_default, has_global_scopes_default, unique_ids_default);
2711
+ var Model = class Model extends BaseModel {
2712
+ builder = null;
2713
+ table = null;
2714
+ keyType = "int";
2715
+ incrementing = true;
2716
+ withCount = [];
2717
+ primaryKey = "id";
2718
+ perPage = 15;
2719
+ static globalScopes = {};
2720
+ static pluginInitializers = {};
2721
+ static _booted = {};
2722
+ static resolver;
2723
+ connection = null;
2724
+ eagerLoad = {};
2725
+ exists = false;
2726
+ with = [];
2727
+ name;
2728
+ trx = null;
2729
+ constructor(attributes = {}) {
2730
+ super();
2731
+ this.bootIfNotBooted();
2732
+ this.initializePlugins();
2733
+ this.syncOriginal();
2734
+ this.fill(attributes);
2735
+ return this.asProxy();
2736
+ }
2737
+ static query(trx = null) {
2738
+ return new this().newQuery(trx);
2739
+ }
2740
+ static on(connection = null) {
2741
+ const instance = new this();
2742
+ instance.setConnection(connection);
2743
+ return instance.newQuery();
2744
+ }
2745
+ static init(attributes = {}) {
2746
+ return new this(attributes);
2747
+ }
2748
+ static extend(plugin, options) {
2749
+ plugin(this, options);
2750
+ }
2751
+ static make(attributes = {}) {
2752
+ const instance = new this();
2753
+ for (const attribute in attributes) if (typeof instance[getRelationMethod(attribute)] !== "function") instance.setAttribute(attribute, attributes[attribute]);
2754
+ else {
2755
+ const relation = instance[getRelationMethod(attribute)]();
2756
+ const related = relation.getRelated().constructor;
2757
+ if (relation instanceof has_one_default || relation instanceof belongs_to_default) instance.setRelation(attribute, related.make(attributes[attribute]));
2758
+ else if ((relation instanceof has_many_default || relation instanceof belongs_to_many_default) && Array.isArray(attributes[attribute])) instance.setRelation(attribute, new collection_default(attributes[attribute].map((item) => related.make(item))));
2759
+ }
2760
+ return instance;
2761
+ }
2762
+ getConstructor() {
2763
+ return this.constructor;
2764
+ }
2765
+ bootIfNotBooted() {
2766
+ if (this.constructor._booted[this.constructor.name] === void 0) {
2767
+ this.constructor._booted[this.constructor.name] = true;
2768
+ this.constructor.booting();
2769
+ this.initialize();
2770
+ this.constructor.boot();
2771
+ this.constructor.booted();
2772
+ }
2773
+ }
2774
+ static booting() {}
2775
+ static boot() {}
2776
+ static booted() {}
2777
+ static setConnectionResolver(resolver) {
2778
+ this.resolver = resolver;
2779
+ }
2780
+ initialize() {}
2781
+ initializePlugins() {
2782
+ if (typeof this.constructor.pluginInitializers[this.constructor.name] === "undefined") return;
2783
+ for (const method of this.constructor.pluginInitializers[this.constructor.name]) this[method]();
2784
+ }
2785
+ addPluginInitializer(method) {
2786
+ if (!this.constructor.pluginInitializers[this.constructor.name]) this.constructor.pluginInitializers[this.constructor.name] = [];
2787
+ this.constructor.pluginInitializers[this.constructor.name].push(method);
2788
+ }
2789
+ newInstance(attributes = {}, exists = false) {
2790
+ const model = new this.constructor();
2791
+ model.exists = exists;
2792
+ model.setConnection(this.getConnectionName());
2793
+ model.setTable(this.getTable());
2794
+ model.fill(attributes);
2795
+ return model;
2796
+ }
2797
+ newFromBuilder(attributes = {}, connection = null) {
2798
+ const model = this.newInstance({}, true);
2799
+ model.setRawAttributes(attributes, true);
2800
+ model.setConnection(connection || this.getConnectionName());
2801
+ return model;
2802
+ }
2803
+ asProxy() {
2804
+ return new Proxy(this, {
2805
+ get: function(target, prop) {
2806
+ if (target[prop] !== void 0) return target[prop];
2807
+ if (typeof prop === "string") return target.getAttribute(prop);
2808
+ },
2809
+ set: function(target, prop, value) {
2810
+ if (target[prop] !== void 0 && typeof target !== "function") {
2811
+ target[prop] = value;
2812
+ return target;
2813
+ }
2814
+ if (typeof prop === "string") return target.setAttribute(prop, value);
2815
+ return target;
2816
+ }
2817
+ });
2818
+ }
2819
+ getKey() {
2820
+ return this.getAttribute(this.getKeyName());
2821
+ }
2822
+ getKeyName() {
2823
+ return this.primaryKey;
2824
+ }
2825
+ getForeignKey() {
2826
+ return snakeCase(this.constructor.name) + "_" + this.getKeyName();
2827
+ }
2828
+ getConnectionName() {
2829
+ return this.connection;
2830
+ }
2831
+ getTable() {
2832
+ return this.table || (0, pluralize.default)(snakeCase(this.constructor.name));
2833
+ }
2834
+ getConnection() {
2835
+ if (this.constructor.resolver) return this.constructor.resolver.getConnection(this.connection);
2836
+ return arquebus_default.fire(this.connection);
2837
+ }
2838
+ setConnection(connection) {
2839
+ this.connection = connection;
2840
+ return this;
2841
+ }
2842
+ getKeyType() {
2843
+ return this.keyType;
2844
+ }
2845
+ newQuery(trx = null) {
2846
+ return this.addGlobalScopes(this.newQueryWithoutScopes(trx));
2847
+ }
2848
+ newQueryWithoutScopes(trx = null) {
2849
+ return this.newModelQuery(trx).with(this.with).withCount(this.withCount);
2850
+ }
2851
+ newModelQuery(trx = null) {
2852
+ return new builder_default(trx || this.getConnection()).setModel(this);
2853
+ }
2854
+ addGlobalScopes(builder) {
2855
+ const globalScopes = this.getGlobalScopes();
2856
+ for (const identifier in globalScopes) {
2857
+ const scope = globalScopes[identifier];
2858
+ builder.withGlobalScope(identifier, scope);
2859
+ }
2860
+ return builder;
2861
+ }
2862
+ hasNamedScope(name) {
2863
+ const scope = getScopeMethod(name);
2864
+ return typeof this[scope] === "function";
2865
+ }
2866
+ callNamedScope(scope, parameters) {
2867
+ const scopeMethod = getScopeMethod(scope);
2868
+ return this[scopeMethod](...parameters);
2869
+ }
2870
+ setTable(table) {
2871
+ this.table = table;
2872
+ return this;
2873
+ }
2874
+ newCollection(models = []) {
2875
+ return new collection_default(models);
2876
+ }
2877
+ async load(...relations) {
2878
+ await this.constructor.query().with(...relations).eagerLoadRelations([this]);
2879
+ return this;
2880
+ }
2881
+ async loadAggregate(relations, column, callback = null) {
2882
+ await new collection_default([this]).loadAggregate(relations, column, callback);
2883
+ return this;
2884
+ }
2885
+ async loadCount(...relations) {
2886
+ relations = flattenDeep(relations);
2887
+ return await this.loadAggregate(relations, "*", "count");
2888
+ }
2889
+ async loadMax(relations, column) {
2890
+ return await this.loadAggregate(relations, column, "max");
2891
+ }
2892
+ async loadMin(relations, column) {
2893
+ return await this.loadAggregate(relations, column, "min");
2894
+ }
2895
+ async loadSum(relations, column) {
2896
+ return await this.loadAggregate(relations, column, "sum");
2897
+ }
2898
+ async increment(column, amount = 1, extra = {}, options = {}) {
2899
+ return await this.incrementOrDecrement(column, amount, extra, "increment", options);
2900
+ }
2901
+ async decrement(column, amount = 1, extra = {}, options = {}) {
2902
+ return await this.incrementOrDecrement(column, amount, extra, "decrement", options);
2903
+ }
2904
+ async incrementOrDecrement(column, amount, extra, method, options) {
2905
+ const query = this.newModelQuery(options.client);
2906
+ if (!this.exists) return await query[method](column, amount, extra);
2907
+ this.attributes[column] = this[column] + (method === "increment" ? amount : amount * -1);
2908
+ for (const key in extra) this.attributes[key] = extra[key];
2909
+ await this.execHooks("updating", options);
2910
+ return await tap(await query.where(this.getKeyName(), this.getKey())[method](column, amount, extra), async () => {
2911
+ this.syncChanges();
2912
+ await this.execHooks("updated", options);
2913
+ this.syncOriginalAttribute(column);
2914
+ });
2915
+ }
2916
+ toData() {
2917
+ return (0, radashi.assign)(this.attributesToData(), this.relationsToData());
2918
+ }
2919
+ toJSON() {
2920
+ return this.toData();
2921
+ }
2922
+ toJson(...args) {
2923
+ return JSON.stringify(this.toData(), ...args);
2924
+ }
2925
+ toString() {
2926
+ return this.toJson();
2927
+ }
2928
+ fill(attributes) {
2929
+ for (const key in attributes) this.setAttribute(key, attributes[key]);
2930
+ return this;
2931
+ }
2932
+ transacting(trx) {
2933
+ this.trx = trx;
2934
+ return this;
2935
+ }
2936
+ trashed() {
2937
+ return this[this.getDeletedAtColumn()] !== null;
2938
+ }
2939
+ getIncrementing() {
2940
+ return this.incrementing;
2941
+ }
2942
+ setIncrementing(value) {
2943
+ this.incrementing = value;
2944
+ return this;
2945
+ }
2946
+ async save(options = {}) {
2947
+ const query = this.newModelQuery(options.client);
2948
+ let saved;
2949
+ await this.execHooks("saving", options);
2950
+ if (this.exists) if (this.isDirty() === false) saved = true;
2951
+ else {
2952
+ await this.execHooks("updating", options);
2953
+ if (this.usesTimestamps()) this.updateTimestamps();
2954
+ const dirty = this.getDirty();
2955
+ if (Object.keys(dirty).length > 0) {
2956
+ await query.where(this.getKeyName(), this.getKey()).query.update(dirty);
2957
+ this.syncChanges();
2958
+ await this.execHooks("updated", options);
2959
+ }
2960
+ saved = true;
2961
+ }
2962
+ else {
2963
+ if (this.usesUniqueIds()) this.setUniqueIds();
2964
+ await this.execHooks("creating", options);
2965
+ if (this.usesTimestamps()) this.updateTimestamps();
2966
+ const attributes = this.getAttributes();
2967
+ if (this.getIncrementing()) {
2968
+ var _data$;
2969
+ const keyName = this.getKeyName();
2970
+ const data = await query.insert([attributes], [keyName]);
2971
+ this.setAttribute(keyName, ((_data$ = data[0]) === null || _data$ === void 0 ? void 0 : _data$[keyName]) || data[0]);
2972
+ } else if (Object.keys(attributes).length > 0) await query.insert(attributes);
2973
+ this.exists = true;
2974
+ await this.execHooks("created", options);
2975
+ saved = true;
2976
+ }
2977
+ if (saved) {
2978
+ await this.execHooks("saved", options);
2979
+ this.syncOriginal();
2980
+ }
2981
+ return saved;
2982
+ }
2983
+ async update(attributes = {}, options = {}) {
2984
+ if (!this.exists) return false;
2985
+ for (const key in attributes) this[key] = attributes[key];
2986
+ return await this.save(options);
2987
+ }
2988
+ async delete(options = {}) {
2989
+ await this.execHooks("deleting", options);
2990
+ await this.performDeleteOnModel(options);
2991
+ await this.execHooks("deleted", options);
2992
+ return true;
2993
+ }
2994
+ async performDeleteOnModel(options = {}) {
2995
+ await this.setKeysForSaveQuery(this.newModelQuery(options.client)).delete();
2996
+ this.exists = false;
2997
+ }
2998
+ setKeysForSaveQuery(query) {
2999
+ query.where(this.getKeyName(), "=", this.getKey());
3000
+ return query;
3001
+ }
3002
+ async forceDelete(options = {}) {
3003
+ return await this.delete(options);
3004
+ }
3005
+ fresh() {
3006
+ if (!this.exists) return;
3007
+ return this.constructor.query().where(this.getKeyName(), this.getKey()).first();
3008
+ }
3009
+ async refresh() {
3010
+ if (!this.exists) return Promise.resolve(void 0);
3011
+ this.attributes = { ...(await this.constructor.query().where(this.getKeyName(), this.getKey()).first()).attributes };
3012
+ await this.load((0, collect_js.default)(this.relations).reject((relation) => {
3013
+ return relation instanceof Pivot;
3014
+ }).keys().all());
3015
+ this.syncOriginal();
3016
+ return this;
3017
+ }
3018
+ newPivot(parent, attributes, table, exists, using = null) {
3019
+ return using ? using.fromRawAttributes(parent, attributes, table, exists) : Pivot.fromAttributes(parent, attributes, table, exists);
3020
+ }
3021
+ qualifyColumn(column) {
3022
+ if (column.includes(".")) return column;
3023
+ return `${this.getTable()}.${column}`;
3024
+ }
3025
+ getQualifiedKeyName() {
3026
+ return this.qualifyColumn(this.getKeyName());
3027
+ }
3028
+ async push(options = {}) {
3029
+ if (!await this.save(options)) return false;
3030
+ for (const relation in this.relations) {
3031
+ let models = this.relations[relation];
3032
+ models = models instanceof collection_default ? models.all() : [models];
3033
+ for (const model of models) if (!await model.push(options)) return false;
3034
+ }
3035
+ return true;
3036
+ }
3037
+ is(model) {
3038
+ return model && model instanceof Model && this.getKey() === model.getKey() && this.getTable() === model.getTable() && this.getConnectionName() === model.getConnectionName();
3039
+ }
3040
+ isNot(model) {
3041
+ return !this.is(model);
3042
+ }
3043
+ };
3044
+ var Pivot = class extends Model {
3045
+ incrementing = false;
3046
+ guarded = [];
3047
+ pivotParent = null;
3048
+ foreignKey = null;
3049
+ relatedKey = null;
3050
+ setPivotKeys(foreignKey, relatedKey) {
3051
+ this.foreignKey = foreignKey;
3052
+ this.relatedKey = relatedKey;
3053
+ return this;
3054
+ }
3055
+ static fromRawAttributes(parent, attributes, table, exists = false) {
3056
+ const instance = this.fromAttributes(parent, {}, table, exists);
3057
+ instance.timestamps = instance.hasTimestampAttributes(attributes);
3058
+ instance.attributes = attributes;
3059
+ instance.exists = exists;
3060
+ return instance;
3061
+ }
3062
+ static fromAttributes(parent, attributes, table, exists = false) {
3063
+ const instance = new this();
3064
+ instance.timestamps = instance.hasTimestampAttributes(attributes);
3065
+ instance.setConnection(parent.connection).setTable(table).fill(attributes).syncOriginal();
3066
+ instance.pivotParent = parent;
3067
+ instance.exists = exists;
3068
+ return instance;
3069
+ }
3070
+ hasTimestampAttributes(attributes = null) {
3071
+ return (attributes || this.attributes)[this.constructor.CREATED_AT] !== void 0;
3072
+ }
3073
+ };
3074
+ var model_default = Model;
3075
+
3076
+ //#endregion
3077
+ //#region src/relations/belongs-to.ts
3078
+ var BelongsTo = class extends compose(relation_default, supports_default_models_default) {
3079
+ foreignKey;
3080
+ ownerKey;
3081
+ child;
3082
+ relationName;
3083
+ constructor(query, child, foreignKey, ownerKey, relationName) {
3084
+ super(query, child);
3085
+ this.foreignKey = foreignKey;
3086
+ this.ownerKey = ownerKey;
3087
+ this.child = child;
3088
+ this.relationName = relationName;
3089
+ this.addConstraints();
3090
+ return this.asProxy();
3091
+ }
3092
+ async getResults() {
3093
+ if (this.child[this.foreignKey] === null) return this.getDefaultFor(this.parent);
3094
+ return await this.query.first() || this.getDefaultFor(this.parent);
3095
+ }
3096
+ match(models, results, relation) {
3097
+ const foreign = this.foreignKey;
3098
+ const owner = this.ownerKey;
3099
+ const dictionary = {};
3100
+ results.map((result) => {
3101
+ const attribute = result.attributes[owner];
3102
+ dictionary[attribute] = result;
3103
+ });
3104
+ models.map((model) => {
3105
+ const attribute = model[foreign];
3106
+ if (dictionary[attribute] !== void 0) model.setRelation(relation, dictionary[attribute]);
3107
+ });
3108
+ return models;
3109
+ }
3110
+ getQualifiedForeignKeyName() {
3111
+ return this.child.qualifyColumn(this.foreignKey);
3112
+ }
3113
+ getRelationExistenceQuery(query, parentQuery, columns = ["*"]) {
3114
+ if (parentQuery.getQuery()._single.table === query.getQuery()._single.table) return this.getRelationExistenceQueryForSelfRelation(query, parentQuery, columns);
3115
+ return query.select(columns).whereColumn(this.getQualifiedForeignKeyName(), "=", query.qualifyColumn(this.ownerKey));
3116
+ }
3117
+ getRelationExistenceQueryForSelfRelation(query, parentQuery, columns = ["*"]) {
3118
+ const hash = this.getRelationCountHash();
3119
+ query.select(columns).from(query.getModel().getTable() + " as " + hash);
3120
+ query.getModel().setTable(hash);
3121
+ return query.whereColumn(`${hash}.${this.ownerKey}`, "=", this.getQualifiedForeignKeyName());
3122
+ }
3123
+ initRelation(models, relation) {
3124
+ models.forEach((model) => {
3125
+ model.setRelation(relation, this.getDefaultFor(model));
3126
+ });
3127
+ return models;
3128
+ }
3129
+ addEagerConstraints(models) {
3130
+ const key = `${this.related.getTable()}.${this.ownerKey}`;
3131
+ this.query.whereIn(key, this.getEagerModelKeys(models));
3132
+ }
3133
+ getEagerModelKeys(models) {
3134
+ const keys = [];
3135
+ models.forEach((model) => {
3136
+ const value = model[this.foreignKey];
3137
+ if (value !== null && value !== void 0) keys.push(value);
3138
+ });
3139
+ keys.sort();
3140
+ return [...new Set(keys)];
3141
+ }
3142
+ associate(model) {
3143
+ const ownerKey = model instanceof Model ? model.attributes[this.ownerKey] : model;
3144
+ this.child[this.foreignKey] = ownerKey;
3145
+ if (model instanceof Model) this.child.setRelation(this.relationName, model);
3146
+ else this.child.unsetRelation(this.relationName);
3147
+ return this.child;
3148
+ }
3149
+ dissociate() {
3150
+ this.child[this.foreignKey] = null;
3151
+ return this.child.setRelation(this.relationName, null);
3152
+ }
3153
+ addConstraints() {
3154
+ if (this.constructor.constraints) {
3155
+ const table = this.related.getTable();
3156
+ this.query.where(`${table}.${this.ownerKey}`, "=", this.child[this.foreignKey]);
3157
+ }
3158
+ }
3159
+ newRelatedInstanceFor(_parent) {
3160
+ return this.related.newInstance();
3161
+ }
3162
+ };
3163
+ var belongs_to_default = BelongsTo;
3164
+
3165
+ //#endregion
3166
+ //#region src/relations/has-many-through.ts
3167
+ var HasManyThrough = class extends relation_default {
3168
+ throughParent;
3169
+ farParent;
3170
+ firstKey;
3171
+ secondKey;
3172
+ localKey;
3173
+ secondLocalKey;
3174
+ constructor(query, farParent, throughParent, firstKey, secondKey, localKey, secondLocalKey) {
3175
+ super(query, throughParent);
3176
+ this.localKey = localKey;
3177
+ this.firstKey = firstKey;
3178
+ this.secondKey = secondKey;
3179
+ this.farParent = farParent;
3180
+ this.throughParent = throughParent;
3181
+ this.secondLocalKey = secondLocalKey;
3182
+ return this.asProxy();
3183
+ }
3184
+ addConstraints() {
3185
+ const localValue = this.farParent[this.localKey];
3186
+ this.performJoin();
3187
+ if (this.constructor.constraints) this.query.where(this.getQualifiedFirstKeyName(), "=", localValue);
3188
+ }
3189
+ performJoin(query = null) {
3190
+ query = query || this.query;
3191
+ const farKey = this.getQualifiedFarKeyName();
3192
+ query.join(this.throughParent.getTable(), this.getQualifiedParentKeyName(), "=", farKey);
3193
+ if (this.throughParentSoftDeletes()) query.withGlobalScope("SoftDeletableHasManyThrough", (query$1) => {
3194
+ query$1.whereNull(this.throughParent.getQualifiedDeletedAtColumn());
3195
+ });
3196
+ }
3197
+ getQualifiedParentKeyName() {
3198
+ return this.parent.qualifyColumn(this.secondLocalKey);
3199
+ }
3200
+ throughParentSoftDeletes() {
3201
+ return this.throughParent.pluginInitializers["SoftDeletes"] !== void 0;
3202
+ }
3203
+ withTrashedParents() {
3204
+ this.query.withoutGlobalScope("SoftDeletableHasManyThrough");
3205
+ return this;
3206
+ }
3207
+ addEagerConstraints(models) {
3208
+ const whereIn = this.whereInMethod(this.farParent, this.localKey);
3209
+ this.whereInEager(whereIn, this.getQualifiedFirstKeyName(), this.getKeys(models, this.localKey));
3210
+ }
3211
+ initRelation(models, relation) {
3212
+ for (const model of models) model.setRelation(relation, this.related.newCollection());
3213
+ return models;
3214
+ }
3215
+ match(models, results, relation) {
3216
+ const dictionary = this.buildDictionary(results);
3217
+ for (const model of models) {
3218
+ const key = this.getDictionaryKey(model.getAttribute(this.localKey));
3219
+ if (dictionary[key] !== void 0) model.setRelation(relation, this.related.newCollection(dictionary[key]));
3220
+ }
3221
+ return models;
3222
+ }
3223
+ buildDictionary(results) {
3224
+ const dictionary = {};
3225
+ for (const result of results) {
3226
+ if (dictionary[result.laravel_through_key] === void 0) dictionary[result.laravel_through_key] = [];
3227
+ dictionary[result.laravel_through_key].push(result);
3228
+ }
3229
+ return dictionary;
3230
+ }
3231
+ async firstOrNew(attributes) {
3232
+ return await this.where(attributes).first() || this.related.newInstance(attributes);
3233
+ }
3234
+ async updateOrCreate(attributes, values = {}) {
3235
+ return tap(await this.firstOrCreate(attributes, values), async (instance) => {
3236
+ if (!instance.wasRecentlyCreated) await instance.fill(values).save();
3237
+ });
3238
+ }
3239
+ async firstWhere(column, operator = null, value = null, boolean = "and") {
3240
+ return await this.where(column, operator, value, boolean).first();
3241
+ }
3242
+ async first(columns = ["*"]) {
3243
+ const results = await this.take(1).get(columns);
3244
+ return results.count() > 0 ? results.first() : null;
3245
+ }
3246
+ async firstOrFail(...columns) {
3247
+ const model = await this.first(...columns);
3248
+ if (model) return model;
3249
+ throw new ModelNotFoundError().setModel(this.related.constructor);
3250
+ }
3251
+ async firstOr(columns = ["*"], callback = null) {
3252
+ if (typeof columns === "function") {
3253
+ callback = columns;
3254
+ columns = ["*"];
3255
+ }
3256
+ const model = await this.first(columns);
3257
+ if (model) return model;
3258
+ return callback === null || callback === void 0 ? void 0 : callback();
3259
+ }
3260
+ async find(id, columns = ["*"]) {
3261
+ if ((0, radashi.isArray)(id)) return await this.findMany(id, columns);
3262
+ return await this.where(this.getRelated().getQualifiedKeyName(), "=", id).first(columns);
3263
+ }
3264
+ async findMany(ids, columns = ["*"]) {
3265
+ if (ids.length === 0) return this.getRelated().newCollection();
3266
+ return await this.whereIn(this.getRelated().getQualifiedKeyName(), ids).get(columns);
3267
+ }
3268
+ async findOrFail(id, columns = ["*"]) {
3269
+ const result = await this.find(id, columns);
3270
+ if (Array.isArray(id)) {
3271
+ if (result.count() === id.length) return result;
3272
+ } else if (result) return result;
3273
+ throw new ModelNotFoundError().setModel(this.related.constructor, id);
3274
+ }
3275
+ async getResults() {
3276
+ return this.farParent[this.localKey] ? await this.get() : this.related.newCollection();
3277
+ }
3278
+ async get(columns = ["*"]) {
3279
+ const builder = this.prepareQueryBuilder(columns);
3280
+ let models = await builder.getModels();
3281
+ if (models.count() > 0) models = await builder.eagerLoadRelations(models);
3282
+ return this.related.newCollection(models);
3283
+ }
3284
+ async paginate(perPage = null, columns = ["*"], pageName = "page", page = null) {
3285
+ this.query.addSelect(this.shouldSelect(columns));
3286
+ return await this.query.paginate(perPage ?? 15, columns, pageName, page);
3287
+ }
3288
+ shouldSelect(columns = ["*"]) {
3289
+ if ((columns === null || columns === void 0 ? void 0 : columns.at(0)) == "*") columns = [this.related.getTable() + ".*"];
3290
+ return [...columns, this.getQualifiedFirstKeyName() + " as laravel_through_key"];
3291
+ }
3292
+ async chunk(count, callback) {
3293
+ return await this.prepareQueryBuilder().chunk(count, callback);
3294
+ }
3295
+ prepareQueryBuilder(columns = ["*"]) {
3296
+ const builder = this.query.applyScopes();
3297
+ return builder.addSelect(this.shouldSelect(builder.getQuery().columns ? [] : columns));
3298
+ }
3299
+ getRelationExistenceQuery(query, parentQuery, columns = ["*"]) {
3300
+ if (parentQuery.getQuery().from === query.getQuery().from) return this.getRelationExistenceQueryForSelfRelation(query, parentQuery, columns);
3301
+ if (parentQuery.getQuery().from === this.throughParent.getTable()) return this.getRelationExistenceQueryForThroughSelfRelation(query, parentQuery, columns);
3302
+ this.performJoin(query);
3303
+ return query.select(columns).where(this.getQualifiedLocalKeyName(), "=", this.getQualifiedFirstKeyName());
3304
+ }
3305
+ getRelationExistenceQueryForSelfRelation(query, parentQuery, columns = ["*"]) {
3306
+ const hash = this.getRelationCountHash();
3307
+ query.from(query.getModel().getTable() + " as " + hash);
3308
+ query.join(this.throughParent.getTable(), this.getQualifiedParentKeyName(), "=", hash + "." + this.secondKey);
3309
+ if (this.throughParentSoftDeletes()) query.whereNull(this.throughParent.getQualifiedDeletedAtColumn());
3310
+ query.getModel().setTable(hash);
3311
+ return query.select(columns).whereColumn(parentQuery.getQuery().from + "." + this.localKey, "=", this.getQualifiedFirstKeyName());
3312
+ }
3313
+ getRelationExistenceQueryForThroughSelfRelation(query, parentQuery, columns = ["*"]) {
3314
+ const hash = this.getRelationCountHash();
3315
+ const table = this.throughParent.getTable() + " as " + hash;
3316
+ query.join(table, hash + "." + this.secondLocalKey, "=", this.getQualifiedFarKeyName());
3317
+ if (this.throughParentSoftDeletes()) query.whereNull(hash + "." + this.throughParent.getDeletedAtColumn());
3318
+ return query.select(columns).where(parentQuery.getQuery().from + "." + this.localKey, "=", hash + "." + this.firstKey);
3319
+ }
3320
+ getQualifiedFarKeyName() {
3321
+ return this.getQualifiedForeignKeyName();
3322
+ }
3323
+ getFirstKeyName() {
3324
+ return this.firstKey;
3325
+ }
3326
+ getQualifiedFirstKeyName() {
3327
+ return this.throughParent.qualifyColumn(this.firstKey);
3328
+ }
3329
+ getForeignKeyName() {
3330
+ return this.secondKey;
3331
+ }
3332
+ getQualifiedForeignKeyName() {
3333
+ return this.related.qualifyColumn(this.secondKey);
3334
+ }
3335
+ getLocalKeyName() {
3336
+ return this.localKey;
3337
+ }
3338
+ getQualifiedLocalKeyName() {
3339
+ return this.farParent.qualifyColumn(this.localKey);
3340
+ }
3341
+ getSecondLocalKeyName() {
3342
+ return this.secondLocalKey;
3343
+ }
3344
+ };
3345
+ var has_many_through_default = HasManyThrough;
3346
+
3347
+ //#endregion
3348
+ //#region src/relations/has-one-through.ts
3349
+ var HasOneThrough = class extends compose(has_many_through_default, supports_default_models_default) {
3350
+ async getResults() {
3351
+ return await this.first() || this.getDefaultFor(this.farParent);
3352
+ }
3353
+ initRelation(models, relation) {
3354
+ for (const model of models) model.setRelation(relation, this.getDefaultFor(model));
3355
+ return models;
3356
+ }
3357
+ match(models, results, relation) {
3358
+ const dictionary = this.buildDictionary(results);
3359
+ for (const model of models) {
3360
+ const key = this.getDictionaryKey(model.getAttribute(this.localKey));
3361
+ if (dictionary[key] !== void 0) {
3362
+ const value = dictionary[key];
3363
+ model.setRelation(relation, value[0]);
3364
+ }
3365
+ }
3366
+ return models;
3367
+ }
3368
+ newRelatedInstanceFor(_parent) {
3369
+ return this.related.newInstance();
3370
+ }
3371
+ };
3372
+ var has_one_through_default = HasOneThrough;
3373
+
3374
+ //#endregion
3375
+ //#region src/concerns/has-relations.ts
3376
+ var has_relations_exports = /* @__PURE__ */ __export({ default: () => has_relations_default });
3377
+ const HasRelations = (Model$1) => {
3378
+ return class extends Model$1 {
3379
+ relations = {};
3380
+ getRelation(relation) {
3381
+ return this.relations[relation];
3382
+ }
3383
+ setRelation(relation, value) {
3384
+ this.relations[relation] = value;
3385
+ return this;
3386
+ }
3387
+ unsetRelation(relation) {
3388
+ this.relations = (0, radashi.omit)(this.relations, [relation]);
3389
+ return this;
3390
+ }
3391
+ relationLoaded(relation) {
3392
+ return this.relations[relation] !== void 0;
3393
+ }
3394
+ related(relation) {
3395
+ if (typeof this[getRelationMethod(relation)] !== "function") throw new RelationNotFoundError(`Model [${this.constructor.name}]'s relation [${relation}] doesn't exist.`);
3396
+ return this[getRelationMethod(relation)]();
3397
+ }
3398
+ async getRelated(relation) {
3399
+ return await this.related(relation).getResults();
3400
+ }
3401
+ relationsToData() {
3402
+ const data = {};
3403
+ for (const key in this.relations) {
3404
+ if (this.hidden.includes(key)) continue;
3405
+ if (this.visible.length > 0 && this.visible.includes(key) === false) continue;
3406
+ data[key] = this.relations[key] instanceof Array ? this.relations[key].map((item) => item.toData()) : this.relations[key] === null ? null : this.relations[key].toData();
3407
+ }
3408
+ return data;
3409
+ }
3410
+ guessBelongsToRelation() {
3411
+ var _e$stack;
3412
+ const functionName = (((_e$stack = (/* @__PURE__ */ new Error()).stack) === null || _e$stack === void 0 ? void 0 : _e$stack.split("\n")[2]) ?? "").split(" ")[5];
3413
+ return getRelationName(functionName);
3414
+ }
3415
+ joiningTable(related, instance = null) {
3416
+ return [instance ? instance.joiningTableSegment() : snakeCase(related.name), this.joiningTableSegment()].sort().join("_").toLocaleLowerCase();
3417
+ }
3418
+ joiningTableSegment() {
3419
+ return snakeCase(this.constructor.name);
3420
+ }
3421
+ hasOne(related, foreignKey, localKey) {
3422
+ const query = related.query();
3423
+ const instance = new related();
3424
+ foreignKey = foreignKey || this.getForeignKey();
3425
+ localKey = localKey || this.getKeyName();
3426
+ return new has_one_default(query, this, instance.getTable() + "." + foreignKey, localKey);
3427
+ }
3428
+ hasMany(related, foreignKey, localKey) {
3429
+ const query = related.query();
3430
+ const instance = new related();
3431
+ foreignKey = foreignKey || this.getForeignKey();
3432
+ localKey = localKey || this.getKeyName();
3433
+ return new has_many_default(query, this, instance.getTable() + "." + foreignKey, localKey);
3434
+ }
3435
+ belongsTo(related, foreignKey, ownerKey, relation) {
3436
+ const query = related.query();
3437
+ const instance = new related();
3438
+ foreignKey = foreignKey || instance.getForeignKey();
3439
+ ownerKey = ownerKey || instance.getKeyName();
3440
+ relation = relation || this.guessBelongsToRelation();
3441
+ return new belongs_to_default(query, this, foreignKey, ownerKey, relation);
3442
+ }
3443
+ belongsToMany(related, table, foreignPivotKey, relatedPivotKey, parentKey, relatedKey) {
3444
+ const query = related.query();
3445
+ const instance = new related();
3446
+ table = table || this.joiningTable(related, instance);
3447
+ foreignPivotKey = foreignPivotKey || this.getForeignKey();
3448
+ relatedPivotKey = relatedPivotKey || instance.getForeignKey();
3449
+ parentKey = parentKey || this.getKeyName();
3450
+ relatedKey = relatedKey || instance.getKeyName();
3451
+ return new belongs_to_many_default(query, this, table, foreignPivotKey, relatedPivotKey, parentKey, relatedKey);
3452
+ }
3453
+ hasOneThrough(related, through, firstKey, secondKey, localKey, secondLocalKey) {
3454
+ through = new through();
3455
+ const query = related.query();
3456
+ firstKey = firstKey || this.getForeignKey();
3457
+ secondKey = secondKey || through.getForeignKey();
3458
+ return new has_one_through_default(query, this, through, firstKey, secondKey, localKey || this.getKeyName(), secondLocalKey || through.getKeyName());
3459
+ }
3460
+ hasManyThrough(related, through, firstKey, secondKey, localKey, secondLocalKey) {
3461
+ through = new through();
3462
+ const query = related.query();
3463
+ firstKey = firstKey || this.getForeignKey();
3464
+ secondKey = secondKey || through.getForeignKey();
3465
+ return new has_many_through_default(query, this, through, firstKey, secondKey, localKey || this.getKeyName(), secondLocalKey || through.getKeyName());
3466
+ }
3467
+ };
3468
+ };
3469
+ var has_relations_default = HasRelations;
3470
+
3471
+ //#endregion
3472
+ //#region src/concerns/has-unique-ids.ts
3473
+ var has_unique_ids_exports = /* @__PURE__ */ __export({ default: () => has_unique_ids_default });
3474
+ const HasUniqueIds = (Model$1) => {
3475
+ return class extends Model$1 {
3476
+ useUniqueIds = true;
3477
+ uniqueIds() {
3478
+ return [this.getKeyName()];
3479
+ }
3480
+ getKeyType() {
3481
+ if (this.uniqueIds().includes(this.getKeyName())) return "string";
3482
+ return this.keyType;
3483
+ }
3484
+ getIncrementing() {
3485
+ if (this.uniqueIds().includes(this.getKeyName())) return false;
3486
+ return this.incrementing;
3487
+ }
3488
+ };
3489
+ };
3490
+ var has_unique_ids_default = HasUniqueIds;
3491
+
3492
+ //#endregion
3493
+ Object.defineProperty(exports, 'HasAttributes', {
3494
+ enumerable: true,
3495
+ get: function () {
3496
+ return has_attributes_exports;
3497
+ }
3498
+ });
3499
+ Object.defineProperty(exports, 'HasGlobalScopes', {
3500
+ enumerable: true,
3501
+ get: function () {
3502
+ return has_global_scopes_exports;
3503
+ }
3504
+ });
3505
+ Object.defineProperty(exports, 'HasHooks', {
3506
+ enumerable: true,
3507
+ get: function () {
3508
+ return has_hooks_exports;
3509
+ }
3510
+ });
3511
+ Object.defineProperty(exports, 'HasRelations', {
3512
+ enumerable: true,
3513
+ get: function () {
3514
+ return has_relations_exports;
3515
+ }
3516
+ });
3517
+ Object.defineProperty(exports, 'HasTimestamps', {
3518
+ enumerable: true,
3519
+ get: function () {
3520
+ return has_timestamps_exports;
3521
+ }
3522
+ });
3523
+ Object.defineProperty(exports, 'HasUniqueIds', {
3524
+ enumerable: true,
3525
+ get: function () {
3526
+ return has_unique_ids_exports;
3527
+ }
3528
+ });
3529
+ Object.defineProperty(exports, 'HidesAttributes', {
3530
+ enumerable: true,
3531
+ get: function () {
3532
+ return hides_attributes_exports;
3533
+ }
3534
+ });
3535
+ Object.defineProperty(exports, 'UniqueIds', {
3536
+ enumerable: true,
3537
+ get: function () {
3538
+ return unique_ids_exports;
3539
+ }
3540
+ });