@h3ravel/arquebus 2.0.0 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +1 -1
  2. package/bin/index.cjs +554 -420
  3. package/bin/index.js +542 -408
  4. package/dist/browser/index.cjs +54 -51
  5. package/dist/browser/index.d.ts +804 -737
  6. package/dist/browser/index.js +48 -44
  7. package/dist/concerns/index.cjs +152 -143
  8. package/dist/concerns/index.d.ts +849 -776
  9. package/dist/concerns/index.js +143 -133
  10. package/dist/index.cjs +186 -185
  11. package/dist/index.d.ts +856 -782
  12. package/dist/index.js +179 -177
  13. package/dist/inspector/index.cjs +175 -174
  14. package/dist/inspector/index.d.ts +0 -1
  15. package/dist/inspector/index.js +161 -159
  16. package/dist/migrations/index.cjs +183 -182
  17. package/dist/migrations/index.d.ts +799 -727
  18. package/dist/migrations/index.js +172 -170
  19. package/dist/relations/index.cjs +152 -143
  20. package/dist/relations/index.d.ts +835 -762
  21. package/dist/relations/index.js +143 -133
  22. package/dist/seeders/index.cjs +7 -5
  23. package/dist/seeders/index.d.ts +797 -724
  24. package/dist/seeders/index.js +8 -6
  25. package/dist/{migrations/stubs/stubs → stubs}/migration-js.stub +1 -0
  26. package/dist/{migrations/stubs/stubs → stubs}/migration-ts.stub +1 -0
  27. package/dist/{migrations/stubs/stubs → stubs}/migration.create-js.stub +1 -0
  28. package/dist/{migrations/stubs/stubs → stubs}/migration.create-ts.stub +1 -0
  29. package/dist/{migrations/stubs/stubs → stubs}/migration.update-js.stub +1 -0
  30. package/dist/{migrations/stubs/stubs → stubs}/migration.update-ts.stub +1 -0
  31. package/dist/stubs/model-ts.stub +9 -0
  32. package/package.json +31 -31
  33. package/types/builder.ts +1 -1
  34. package/types/cli.ts +20 -0
  35. package/types/database.ts +69 -0
  36. package/types/index.ts +4 -0
  37. package/types/model-builder.ts +132 -0
  38. package/types/query-builder.ts +0 -1
  39. package/types/query-methods.ts +0 -1
  40. package/types/schema.ts +92 -0
  41. package/types/utils.ts +1 -40
  42. package/dist/stubs/stubs/model-ts.stub +0 -5
  43. /package/dist/stubs/{stubs/arquebus.config-js.stub → arquebus.config-js.stub} +0 -0
  44. /package/dist/stubs/{stubs/arquebus.config-ts.stub → arquebus.config-ts.stub} +0 -0
  45. /package/dist/stubs/{stubs/model-js.stub → model-js.stub} +0 -0
  46. /package/dist/stubs/{stubs/seeder-js.stub → seeder-js.stub} +0 -0
  47. /package/dist/stubs/{stubs/seeder-ts.stub → seeder-ts.stub} +0 -0
package/bin/index.cjs CHANGED
@@ -30,7 +30,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
30
30
  enumerable: true
31
31
  }) : target, mod));
32
32
  //#endregion
33
- let commander = require("commander");
33
+ let _h3ravel_musket = require("@h3ravel/musket");
34
34
  let _h3ravel_shared = require("@h3ravel/shared");
35
35
  let path = require("path");
36
36
  path = __toESM(path, 1);
@@ -39,20 +39,20 @@ resolve_from = __toESM(resolve_from, 1);
39
39
  let node_fs_promises = require("node:fs/promises");
40
40
  node_fs_promises = __toESM(node_fs_promises, 1);
41
41
  let node_path = require("node:path");
42
+ node_path = __toESM(node_path, 1);
43
+ let node_fs = require("node:fs");
42
44
  let node_url = require("node:url");
43
- let radashi = require("radashi");
44
- let dayjs_plugin_advancedFormat_js = require("dayjs/plugin/advancedFormat.js");
45
- dayjs_plugin_advancedFormat_js = __toESM(dayjs_plugin_advancedFormat_js, 1);
45
+ let _h3ravel_support = require("@h3ravel/support");
46
46
  let dayjs = require("dayjs");
47
47
  dayjs = __toESM(dayjs, 1);
48
- let collect_js = require("collect.js");
49
- collect_js = __toESM(collect_js, 1);
48
+ let dayjs_plugin_advancedFormat_js = require("dayjs/plugin/advancedFormat.js");
49
+ dayjs_plugin_advancedFormat_js = __toESM(dayjs_plugin_advancedFormat_js, 1);
50
+ let _h3ravel_collect_js = require("@h3ravel/collect.js");
50
51
  let knex = require("knex");
51
52
  knex = __toESM(knex, 1);
52
53
  let fs = require("fs");
53
54
  let pluralize = require("pluralize");
54
55
  pluralize = __toESM(pluralize, 1);
55
- let _h3ravel_support = require("@h3ravel/support");
56
56
  let dotenv = require("dotenv");
57
57
  //#region src/cli/utils.ts
58
58
  const join = path.default.join;
@@ -88,6 +88,169 @@ var TableGuesser = class TableGuesser {
88
88
  }
89
89
  };
90
90
  //#endregion
91
+ //#region src/cli/commands.ts
92
+ var ArquebusCommand = class extends _h3ravel_musket.Command {
93
+ pathOption(signature) {
94
+ return signature.option("path", {
95
+ short: "p",
96
+ optionalValue: true,
97
+ description: "The path used by the command."
98
+ });
99
+ }
100
+ };
101
+ var InitCommand = class extends ArquebusCommand {
102
+ buildSignature(signature) {
103
+ return signature.command("init").describe("Create a fresh Arquebus config.").argument("type", {
104
+ required: false,
105
+ default: "js",
106
+ choices: ["js", "ts"],
107
+ description: "Type of config to generate."
108
+ });
109
+ }
110
+ async handle() {
111
+ await this.app.initialize(this.argument("type", "js"));
112
+ }
113
+ };
114
+ var MakeMigrationCommand = class extends ArquebusCommand {
115
+ buildSignature(signature) {
116
+ return this.pathOption(signature.command("make:migration").describe("Create a new migration file.").argument("name", { description: "The migration name." }).option("type", {
117
+ short: "l",
118
+ default: "js",
119
+ choices: ["js", "ts"],
120
+ description: "Type of migration file to generate."
121
+ }).option("table", {
122
+ short: "t",
123
+ optionalValue: true,
124
+ description: "The table to migrate."
125
+ }).option("create", {
126
+ short: "c",
127
+ optionalValue: true,
128
+ description: "The table to create."
129
+ }));
130
+ }
131
+ async handle() {
132
+ await this.app.makeMigration(this.argument("name"), this.options());
133
+ }
134
+ };
135
+ var PublishMigrationsCommand = class extends ArquebusCommand {
136
+ buildSignature(signature) {
137
+ return this.pathOption(signature.command("migrate:publish").describe("Publish migration files from a package.").argument("package", { description: "The package to publish from." }));
138
+ }
139
+ async handle() {
140
+ await this.app.publishMigrations(this.argument("package"), this.options());
141
+ }
142
+ };
143
+ var MigrationPathCommand = class extends ArquebusCommand {
144
+ buildSignature(signature) {
145
+ return this.pathOption(signature.command(this.commandName).describe(this.commandDescription));
146
+ }
147
+ async handle() {
148
+ await this.execute(this.options());
149
+ }
150
+ };
151
+ var MigrateCommand = class extends ArquebusCommand {
152
+ buildSignature(signature) {
153
+ return this.pathOption(signature.command("migrate").describe("Run all pending migrations.").option("step", {
154
+ short: "s",
155
+ optionalValue: true,
156
+ description: "Run migrations in individual batches."
157
+ }));
158
+ }
159
+ async handle() {
160
+ await this.app.migrate(this.options());
161
+ }
162
+ };
163
+ var RollbackCommand = class extends ArquebusCommand {
164
+ buildSignature(signature) {
165
+ return this.pathOption(signature.command("migrate:rollback").describe("Rollback the last database migration.").option("step", {
166
+ short: "s",
167
+ optionalValue: true,
168
+ description: "The number of migrations to revert."
169
+ }));
170
+ }
171
+ async handle() {
172
+ await this.app.rollback(this.options());
173
+ }
174
+ };
175
+ var ResetCommand = class extends MigrationPathCommand {
176
+ commandName = "migrate:reset";
177
+ commandDescription = "Rollback all database migrations.";
178
+ execute(options) {
179
+ return this.app.reset(options);
180
+ }
181
+ };
182
+ var RefreshCommand = class extends MigrationPathCommand {
183
+ commandName = "migrate:refresh";
184
+ commandDescription = "Reset and re-run all migrations.";
185
+ execute(options) {
186
+ return this.app.refresh(options);
187
+ }
188
+ };
189
+ var FreshCommand = class extends MigrationPathCommand {
190
+ commandName = "migrate:fresh";
191
+ commandDescription = "Drop all tables and re-run all migrations.";
192
+ execute(options) {
193
+ return this.app.fresh(options);
194
+ }
195
+ };
196
+ var MigrationStatusCommand = class extends MigrationPathCommand {
197
+ commandName = "migrate:status";
198
+ commandDescription = "Show the status of each migration.";
199
+ execute(options) {
200
+ return this.app.status(options);
201
+ }
202
+ };
203
+ var SeedCommand = class extends MigrationPathCommand {
204
+ commandName = "db:seed";
205
+ commandDescription = "Run database seeders.";
206
+ execute(options) {
207
+ return this.app.seed(options);
208
+ }
209
+ };
210
+ var MakeFileCommand = class extends ArquebusCommand {
211
+ buildSignature(signature) {
212
+ return this.pathOption(signature.command(this.commandName).describe(this.commandDescription).argument("name", { description: `The ${this.fileDescription} name.` }).option("type", {
213
+ short: "l",
214
+ default: "js",
215
+ choices: ["js", "ts"],
216
+ description: `Type of ${this.fileDescription} file to generate.`
217
+ }).option("force", { description: `Overwrite an existing ${this.fileDescription} file.` }));
218
+ }
219
+ async handle() {
220
+ await this.execute(this.argument("name"), this.options());
221
+ }
222
+ };
223
+ var MakeSeederCommand = class extends MakeFileCommand {
224
+ commandName = "make:seeder";
225
+ commandDescription = "Create a new seeder file.";
226
+ fileDescription = "seeder";
227
+ execute(name, options) {
228
+ return this.app.makeSeeder(name, options);
229
+ }
230
+ };
231
+ var MakeModelCommand = class extends MakeFileCommand {
232
+ commandName = "make:model";
233
+ commandDescription = "Create a new model file.";
234
+ fileDescription = "model";
235
+ execute(name, options) {
236
+ return this.app.makeModel(name, options);
237
+ }
238
+ };
239
+ const ArquebusCommands = [
240
+ InitCommand,
241
+ MakeMigrationCommand,
242
+ PublishMigrationsCommand,
243
+ MigrateCommand,
244
+ RollbackCommand,
245
+ ResetCommand,
246
+ RefreshCommand,
247
+ FreshCommand,
248
+ MigrationStatusCommand,
249
+ SeedCommand,
250
+ MakeSeederCommand,
251
+ MakeModelCommand
252
+ ];
253
+ //#endregion
91
254
  //#region src/migrations/migration-repository.ts
92
255
  var MigrationRepository = class {
93
256
  resolver;
@@ -233,8 +396,7 @@ var CockroachDB = class {
233
396
  */
234
397
  async hasTable(table) {
235
398
  const subquery = this.knex.select().from("information_schema.tables").whereIn("table_schema", this.explodedSchema).andWhere({ table_name: table });
236
- const record = await this.knex.select(this.knex.raw("exists (?)", [subquery])).first();
237
- return (record === null || record === void 0 ? void 0 : record.exists) || false;
399
+ return (await this.knex.select(this.knex.raw("exists (?)", [subquery])).first())?.exists || false;
238
400
  }
239
401
  /**
240
402
  * Get all the available columns in the current schema/database. Can be filtered to a specific table
@@ -334,18 +496,17 @@ var CockroachDB = class {
334
496
  ${column ? "AND att.attname = ?" : ""}
335
497
  `, bindings)]);
336
498
  const parsedColumms = columns.rows.map((col) => {
337
- var _col$default_value;
338
499
  const constraintsForColumn = constraints.rows.filter((constraint) => constraint.table === col.table && constraint.column === col.name);
339
500
  const foreignKeyConstraint = constraintsForColumn.find((constraint) => constraint.type === "f");
340
501
  return {
341
502
  ...col,
342
503
  is_unique: constraintsForColumn.some((constraint) => ["u", "p"].includes(constraint.type)),
343
504
  is_primary_key: constraintsForColumn.some((constraint) => constraint.type === "p"),
344
- has_auto_increment: ["integer", "bigint"].includes(col.data_type) && (((_col$default_value = col.default_value) === null || _col$default_value === void 0 ? void 0 : _col$default_value.startsWith("nextval(")) ?? false),
505
+ has_auto_increment: ["integer", "bigint"].includes(col.data_type) && (col.default_value?.startsWith("nextval(") ?? false),
345
506
  default_value: parseDefaultValue$5(col.default_value),
346
- foreign_key_schema: (foreignKeyConstraint === null || foreignKeyConstraint === void 0 ? void 0 : foreignKeyConstraint.foreign_key_schema) ?? null,
347
- foreign_key_table: (foreignKeyConstraint === null || foreignKeyConstraint === void 0 ? void 0 : foreignKeyConstraint.foreign_key_table) ?? null,
348
- foreign_key_column: (foreignKeyConstraint === null || foreignKeyConstraint === void 0 ? void 0 : foreignKeyConstraint.foreign_key_column) ?? null
507
+ foreign_key_schema: foreignKeyConstraint?.foreign_key_schema ?? null,
508
+ foreign_key_table: foreignKeyConstraint?.foreign_key_table ?? null,
509
+ foreign_key_column: foreignKeyConstraint?.foreign_key_column ?? null
349
510
  };
350
511
  });
351
512
  if (table && column) return parsedColumms[0];
@@ -359,8 +520,7 @@ var CockroachDB = class {
359
520
  table_name: table,
360
521
  column_name: column
361
522
  });
362
- const record = await this.knex.select(this.knex.raw("exists (?)", [subquery])).first();
363
- return (record === null || record === void 0 ? void 0 : record.exists) || false;
523
+ return (await this.knex.select(this.knex.raw("exists (?)", [subquery])).first())?.exists || false;
364
524
  }
365
525
  /**
366
526
  * Get the primary key column for the given table
@@ -672,14 +832,13 @@ var MSSQL = class {
672
832
  WHERE
673
833
  OBJECT_SCHEMA_NAME (f.parent_object_id) = ?;
674
834
  `, [this.schema]);
675
- if (table) return result === null || result === void 0 ? void 0 : result.filter((row) => row.table === table);
835
+ if (table) return result?.filter((row) => row.table === table);
676
836
  return result;
677
837
  }
678
838
  };
679
839
  //#endregion
680
840
  //#region src/inspector/dialects/mysql.ts
681
841
  function rawColumnToColumn$1(rawColumn) {
682
- var _rawColumn$EXTRA;
683
842
  let dataType = rawColumn.COLUMN_TYPE.replace(/\(.*?\)/, "");
684
843
  if (rawColumn.COLUMN_TYPE.startsWith("tinyint(1)")) dataType = "boolean";
685
844
  return {
@@ -692,7 +851,7 @@ function rawColumnToColumn$1(rawColumn) {
692
851
  max_length: rawColumn.CHARACTER_MAXIMUM_LENGTH,
693
852
  numeric_precision: rawColumn.NUMERIC_PRECISION,
694
853
  numeric_scale: rawColumn.NUMERIC_SCALE,
695
- is_generated: !!((_rawColumn$EXTRA = rawColumn.EXTRA) === null || _rawColumn$EXTRA === void 0 ? void 0 : _rawColumn$EXTRA.endsWith("GENERATED")),
854
+ is_generated: !!rawColumn.EXTRA?.endsWith("GENERATED"),
696
855
  is_nullable: rawColumn.IS_NULLABLE === "YES",
697
856
  is_unique: rawColumn.COLUMN_KEY === "UNI",
698
857
  is_primary_key: rawColumn.CONSTRAINT_NAME === "PRIMARY" || rawColumn.COLUMN_KEY === "PRI",
@@ -885,11 +1044,10 @@ var oracleDB = class {
885
1044
  * Check if a table exists in the current schema/database
886
1045
  */
887
1046
  async hasTable(table) {
888
- const result = await this.knex.select(this.knex.raw(`
1047
+ return !!(await this.knex.select(this.knex.raw(`
889
1048
  /*+ OPTIMIZER_FEATURES_ENABLE('${OPTIMIZER_FEATURES}') */
890
1049
  COUNT(*) "count"
891
- `)).from("USER_TABLES").where({ TABLE_NAME: table }).first();
892
- return !!(result === null || result === void 0 ? void 0 : result.count);
1050
+ `)).from("USER_TABLES").where({ TABLE_NAME: table }).first())?.count;
893
1051
  }
894
1052
  /**
895
1053
  * Get all the available columns in the current schema/database. Can be filtered to a specific table
@@ -965,15 +1123,14 @@ var oracleDB = class {
965
1123
  * Check if a table exists in the current schema/database
966
1124
  */
967
1125
  async hasColumn(table, column) {
968
- const result = await this.knex.select(this.knex.raw(`
1126
+ return !!(await this.knex.select(this.knex.raw(`
969
1127
  /*+ OPTIMIZER_FEATURES_ENABLE('${OPTIMIZER_FEATURES}') NO_QUERY_TRANSFORMATION */
970
1128
  COUNT(*) "count"
971
1129
  `)).from("USER_TAB_COLS").where({
972
1130
  TABLE_NAME: table,
973
1131
  COLUMN_NAME: column,
974
1132
  HIDDEN_COLUMN: "NO"
975
- }).first();
976
- return !!(result === null || result === void 0 ? void 0 : result.count);
1133
+ }).first())?.count;
977
1134
  }
978
1135
  /**
979
1136
  * Get the primary key column for the given table
@@ -1139,13 +1296,12 @@ var Postgres = class {
1139
1296
  `, bindings)).rows;
1140
1297
  }
1141
1298
  async columnInfo(table, column) {
1142
- var _versionResponse$rows;
1143
1299
  const { knex } = this;
1144
1300
  const bindings = [];
1145
1301
  if (table) bindings.push(table);
1146
1302
  if (column) bindings.push(column);
1147
1303
  const schemaIn = this.explodedSchema.map((schemaName) => `${this.knex.raw("?", [schemaName])}::regnamespace`);
1148
- const majorVersion = ((_versionResponse$rows = (await this.knex.raw("SHOW server_version")).rows) === null || _versionResponse$rows === void 0 || (_versionResponse$rows = _versionResponse$rows[0]) === null || _versionResponse$rows === void 0 || (_versionResponse$rows = _versionResponse$rows.server_version) === null || _versionResponse$rows === void 0 || (_versionResponse$rows = _versionResponse$rows.split(".")) === null || _versionResponse$rows === void 0 ? void 0 : _versionResponse$rows[0]) ?? 10;
1304
+ const majorVersion = (await this.knex.raw("SHOW server_version")).rows?.[0]?.server_version?.split(".")?.[0] ?? 10;
1149
1305
  let generationSelect = `
1150
1306
  NULL AS generation_expression,
1151
1307
  pg_get_expr(ad.adbin, ad.adrelid) AS default_value,
@@ -1237,9 +1393,9 @@ var Postgres = class {
1237
1393
  is_primary_key: constraintsForColumn.some((constraint) => constraint.type === "p"),
1238
1394
  has_auto_increment: constraintsForColumn.some((constraint) => constraint.has_auto_increment),
1239
1395
  default_value: parseDefaultValue$1(col.default_value),
1240
- foreign_key_schema: (foreignKeyConstraint === null || foreignKeyConstraint === void 0 ? void 0 : foreignKeyConstraint.foreign_key_schema) ?? null,
1241
- foreign_key_table: (foreignKeyConstraint === null || foreignKeyConstraint === void 0 ? void 0 : foreignKeyConstraint.foreign_key_table) ?? null,
1242
- foreign_key_column: (foreignKeyConstraint === null || foreignKeyConstraint === void 0 ? void 0 : foreignKeyConstraint.foreign_key_column) ?? null
1396
+ foreign_key_schema: foreignKeyConstraint?.foreign_key_schema ?? null,
1397
+ foreign_key_table: foreignKeyConstraint?.foreign_key_table ?? null,
1398
+ foreign_key_column: foreignKeyConstraint?.foreign_key_column ?? null
1243
1399
  };
1244
1400
  });
1245
1401
  if (table && column) return parsedColumms[0];
@@ -1411,16 +1567,14 @@ var SeederRunner = class {
1411
1567
  this.resolver = resolver;
1412
1568
  }
1413
1569
  path(p) {
1414
- this.paths = Array.from(new Set([...this.paths, p]));
1570
+ this.paths = Array.from(/* @__PURE__ */ new Set([...this.paths, p]));
1415
1571
  }
1416
1572
  getPaths() {
1417
1573
  return this.paths;
1418
1574
  }
1419
1575
  resolveConnection(connection) {
1420
- var _getInstance, _ref, _instance$connections;
1421
1576
  const name = connection || this.connection || "default";
1422
- const instance = ((_getInstance = (_ref = this.resolver).getInstance) === null || _getInstance === void 0 ? void 0 : _getInstance.call(_ref)) ?? null;
1423
- if (!!!(instance === null || instance === void 0 || (_instance$connections = instance.connections) === null || _instance$connections === void 0 ? void 0 : _instance$connections[name])) this.resolver.autoLoad().catch(() => {
1577
+ if (!!!(this.resolver.getInstance?.() ?? null)?.connections?.[name]) this.resolver.autoLoad().catch(() => {
1424
1578
  /** noop */
1425
1579
  });
1426
1580
  return this.resolver.fire(name);
@@ -1458,9 +1612,6 @@ var SeederRunner = class {
1458
1612
  }
1459
1613
  };
1460
1614
  //#endregion
1461
- //#region src/seeders/index.ts
1462
- var seeders_exports = /* @__PURE__ */ __exportAll({ SeederRunner: () => SeederRunner });
1463
- //#endregion
1464
1615
  //#region src/casts/attribute.ts
1465
1616
  var Attribute = class Attribute {
1466
1617
  get;
@@ -1510,7 +1661,7 @@ var ModelNotFoundError = class extends BaseError {
1510
1661
  }
1511
1662
  setModel(model, ids = []) {
1512
1663
  this.model = model;
1513
- this.ids = (0, radashi.isArray)(ids) ? ids : [ids];
1664
+ this.ids = Array.isArray(ids) ? ids : [ids];
1514
1665
  this.message = `No query results for model [${model}]`;
1515
1666
  if (this.ids.length > 0) this.message += " " + this.ids.join(", ");
1516
1667
  else this.message += ".";
@@ -1601,25 +1752,29 @@ function compose$1(Base, ...mixins) {
1601
1752
  }, Base);
1602
1753
  }
1603
1754
  //#endregion
1755
+ //#region src/dayjs.ts
1756
+ const dayjs$1 = dayjs.default ?? dayjs;
1757
+ const advancedFormat = dayjs_plugin_advancedFormat_js.default ?? dayjs_plugin_advancedFormat_js;
1758
+ dayjs$1.extend(advancedFormat);
1759
+ //#endregion
1604
1760
  //#region src/utils.ts
1605
- dayjs.default.extend(dayjs_plugin_advancedFormat_js.default);
1606
1761
  const getRelationName = (relationMethod) => {
1607
- return (0, radashi.snake)(relationMethod.substring(8));
1762
+ return _h3ravel_support.Str.snake(relationMethod.substring(8));
1608
1763
  };
1609
1764
  const getRelationMethod = (relation) => {
1610
- return (0, radashi.camel)(`relation_${relation}`);
1765
+ return _h3ravel_support.Str.camel(`relation_${relation}`);
1611
1766
  };
1612
1767
  const getScopeMethod = (scope) => {
1613
- return (0, radashi.camel)(`scope_${scope}`);
1768
+ return _h3ravel_support.Str.camel(`scope_${scope}`);
1614
1769
  };
1615
1770
  const getAttrMethod = (attr) => {
1616
- return (0, radashi.camel)(`attribute_${attr}`);
1771
+ return _h3ravel_support.Str.camel(`attribute_${attr}`);
1617
1772
  };
1618
1773
  const getGetterMethod = (attr) => {
1619
- return (0, radashi.camel)(`get_${attr}_attribute`);
1774
+ return _h3ravel_support.Str.camel(`get_${attr}_attribute`);
1620
1775
  };
1621
1776
  const getSetterMethod = (attr) => {
1622
- return (0, radashi.camel)(`set_${attr}_attribute`);
1777
+ return _h3ravel_support.Str.camel(`set_${attr}_attribute`);
1623
1778
  };
1624
1779
  /**
1625
1780
  * Tap into a model a collection instance
@@ -1633,9 +1788,9 @@ const tap = (instance, callback) => {
1633
1788
  return result instanceof Promise ? result.then(() => instance) : instance;
1634
1789
  };
1635
1790
  const { compose } = mixin_exports;
1636
- const flatten$2 = (arr) => arr.flat();
1791
+ const flatten = (arr) => arr.flat();
1637
1792
  const flattenDeep = (arr) => Array.isArray(arr) ? arr.reduce((a, b) => a.concat(flattenDeep(b)), []) : [arr];
1638
- const snakeCase = (str) => (0, radashi.trim)((0, radashi.snake)(str.replace(/[^a-zA-Z0-9_-]/g, "-")), "_-");
1793
+ const snakeCase = (str) => _h3ravel_support.Str.trim(_h3ravel_support.Str.snake(str.replace(/[^a-zA-Z0-9_-]/g, "-")), "_-").replace(/_+/g, "_");
1639
1794
  //#endregion
1640
1795
  //#region src/relations/relation.ts
1641
1796
  var Relation = class {
@@ -1722,8 +1877,7 @@ var Relation = class {
1722
1877
  return this.parent.getQualifiedKeyName();
1723
1878
  }
1724
1879
  getExistenceCompareKey() {
1725
- var _this$getQualifiedFor;
1726
- return (_this$getQualifiedFor = this.getQualifiedForeignKeyName) === null || _this$getQualifiedFor === void 0 ? void 0 : _this$getQualifiedFor.call(this);
1880
+ return this.getQualifiedForeignKeyName?.();
1727
1881
  }
1728
1882
  };
1729
1883
  //#endregion
@@ -1864,8 +2018,7 @@ const HasAttributes = (Model) => {
1864
2018
  return this;
1865
2019
  }
1866
2020
  normalizeCastClassResponse(key, value) {
1867
- var _value$constructor;
1868
- return (value === null || value === void 0 || (_value$constructor = value.constructor) === null || _value$constructor === void 0 ? void 0 : _value$constructor.name) === "Object" ? value : { [key]: value };
2021
+ return value?.constructor?.name === "Object" ? value : { [key]: value };
1869
2022
  }
1870
2023
  syncOriginal() {
1871
2024
  this.original = this.getAttributes();
@@ -1975,9 +2128,9 @@ const HasAttributes = (Model) => {
1975
2128
  return null;
1976
2129
  }
1977
2130
  case "collection": try {
1978
- return (0, collect_js.default)(JSON.parse(value));
2131
+ return (0, _h3ravel_collect_js.collect)(JSON.parse(value));
1979
2132
  } catch {
1980
- return (0, collect_js.default)([]);
2133
+ return (0, _h3ravel_collect_js.collect)([]);
1981
2134
  }
1982
2135
  case "date": return this.asDate(value);
1983
2136
  case "datetime":
@@ -1990,8 +2143,8 @@ const HasAttributes = (Model) => {
1990
2143
  attributesToData() {
1991
2144
  let attributes = { ...this.attributes };
1992
2145
  for (const key in attributes) {
1993
- if (this.hidden.includes(key)) attributes = (0, radashi.omit)(attributes, [key]);
1994
- if (this.visible.length > 0 && this.visible.includes(key) === false) attributes = (0, radashi.omit)(attributes, [key]);
2146
+ if (this.hidden.includes(key)) attributes = _h3ravel_support.Arr.except(attributes, [key]);
2147
+ if (this.visible.length > 0 && this.visible.includes(key) === false) attributes = _h3ravel_support.Arr.except(attributes, [key]);
1995
2148
  }
1996
2149
  for (const key of this.getDates()) {
1997
2150
  if (attributes[key] === void 0) continue;
@@ -2003,7 +2156,7 @@ const HasAttributes = (Model) => {
2003
2156
  if (key in attributes === false) continue;
2004
2157
  attributes[key] = this.castAttribute(key, attributes[key]);
2005
2158
  if (key in attributes && ["date", "datetime"].includes(String(value))) attributes[key] = this.serializeDate(attributes[key]);
2006
- if (key in attributes && this.isCustomDateTimeCast(value)) attributes[key] = (0, dayjs.default)(attributes[key]).format(String(value).split(":")[1]);
2159
+ if (key in attributes && this.isCustomDateTimeCast(value)) attributes[key] = dayjs$1(attributes[key]).format(String(value).split(":")[1]);
2007
2160
  }
2008
2161
  for (const key of this.appends) attributes[key] = this.mutateAttribute(key, null);
2009
2162
  return attributes;
@@ -2019,7 +2172,7 @@ const HasAttributes = (Model) => {
2019
2172
  return this.getDates().includes(key) || this.isDateCastable(key);
2020
2173
  }
2021
2174
  serializeDate(date) {
2022
- return date ? (0, dayjs.default)(date).toISOString() : null;
2175
+ return date ? dayjs$1(date).toISOString() : null;
2023
2176
  }
2024
2177
  getDates() {
2025
2178
  return this.usesTimestamps() ? [this.getCreatedAtColumn(), this.getUpdatedAtColumn()] : [];
@@ -2046,13 +2199,13 @@ const HasAttributes = (Model) => {
2046
2199
  }
2047
2200
  hasCast(key, types = []) {
2048
2201
  if (key in this.casts) {
2049
- types = (0, radashi.flat)(types);
2202
+ types = flatten(types);
2050
2203
  return types.length > 0 ? types.includes(this.getCastType(key)) : true;
2051
2204
  }
2052
2205
  return false;
2053
2206
  }
2054
2207
  withDayjs(date) {
2055
- return (0, dayjs.default)(date);
2208
+ return dayjs$1(date);
2056
2209
  }
2057
2210
  isCustomCast(cast) {
2058
2211
  return typeof cast === "function" && new cast() instanceof CastsAttributes;
@@ -2069,7 +2222,7 @@ const HasAttributes = (Model) => {
2069
2222
  return this.hasCast(key, ["date", "datetime"]);
2070
2223
  }
2071
2224
  fromDateTime(value) {
2072
- return (0, dayjs.default)(this.asDateTime(value)).format(this.getDateFormat());
2225
+ return dayjs$1(this.asDateTime(value)).format(this.getDateFormat());
2073
2226
  }
2074
2227
  getDateFormat() {
2075
2228
  return this.dateFormat || "YYYY-MM-DD HH:mm:ss";
@@ -2084,7 +2237,7 @@ const HasAttributes = (Model) => {
2084
2237
  return new Date(value);
2085
2238
  }
2086
2239
  asDate(value) {
2087
- return (0, dayjs.default)(this.asDateTime(value)).startOf("day").toDate();
2240
+ return dayjs$1(this.asDateTime(value)).startOf("day").toDate();
2088
2241
  }
2089
2242
  };
2090
2243
  };
@@ -2105,10 +2258,14 @@ const HasGlobalScopes = (Model) => {
2105
2258
  static globalScopes;
2106
2259
  static addGlobalScope(scope, implementation = null) {
2107
2260
  if (typeof scope === "string" && implementation instanceof Scope) {
2108
- this.globalScopes = (0, radashi.set)(this.globalScopes ?? {}, this.name + "." + scope, implementation);
2261
+ const scopes = this.globalScopes ?? {};
2262
+ (0, _h3ravel_support.data_set)(scopes, this.name + "." + scope, implementation);
2263
+ this.globalScopes = scopes;
2109
2264
  return implementation;
2110
2265
  } else if (scope instanceof Scope) {
2111
- this.globalScopes = (0, radashi.set)(this.globalScopes ?? {}, this.name + "." + scope.constructor.name, scope);
2266
+ const scopes = this.globalScopes ?? {};
2267
+ (0, _h3ravel_support.data_set)(scopes, this.name + "." + scope.constructor.name, scope);
2268
+ this.globalScopes = scopes;
2112
2269
  return scope;
2113
2270
  }
2114
2271
  throw new InvalidArgumentError("Global scope must be an instance of Scope.");
@@ -2117,8 +2274,8 @@ const HasGlobalScopes = (Model) => {
2117
2274
  return this.getGlobalScope(scope) !== null;
2118
2275
  }
2119
2276
  static getGlobalScope(scope) {
2120
- if (typeof scope === "string") return (0, radashi.get)(this.globalScopes, this.name + "." + scope);
2121
- return (0, radashi.get)(this.globalScopes, this.name + "." + scope.constructor.name);
2277
+ if (typeof scope === "string") return (0, _h3ravel_support.data_get)(this.globalScopes ?? {}, this.name + "." + scope);
2278
+ return (0, _h3ravel_support.data_get)(this.globalScopes ?? {}, this.name + "." + scope.constructor.name);
2122
2279
  }
2123
2280
  static getAllGlobalScopes() {
2124
2281
  return this.globalScopes;
@@ -2127,7 +2284,7 @@ const HasGlobalScopes = (Model) => {
2127
2284
  this.globalScopes = scopes;
2128
2285
  }
2129
2286
  getGlobalScopes() {
2130
- return (0, radashi.get)(this.constructor.globalScopes, this.constructor.name, {});
2287
+ return (0, _h3ravel_support.data_get)(this.constructor.globalScopes ?? {}, this.constructor.name, {});
2131
2288
  }
2132
2289
  };
2133
2290
  };
@@ -2227,7 +2384,7 @@ const HasOneOrMany = (Relation) => {
2227
2384
  }
2228
2385
  buildDictionary(results) {
2229
2386
  const foreign = this.getForeignKeyName();
2230
- return (0, collect_js.default)(results).mapToDictionary((result) => [result[foreign], result]).all();
2387
+ return (0, _h3ravel_collect_js.collect)(results).mapToDictionary((result) => [result[foreign], result]).all();
2231
2388
  }
2232
2389
  async save(model) {
2233
2390
  this.setForeignAttributesForCreate(model);
@@ -2298,13 +2455,11 @@ var HasMany = class extends compose(Relation, HasOneOrMany) {
2298
2455
  return this.getParentKey() !== null ? await this.query.get() : new Collection([]);
2299
2456
  }
2300
2457
  getForeignKeyName() {
2301
- var _this$foreignKey;
2302
- const segments = (_this$foreignKey = this.foreignKey) === null || _this$foreignKey === void 0 ? void 0 : _this$foreignKey.split(".");
2303
- return segments === null || segments === void 0 ? void 0 : segments.pop();
2458
+ return (this.foreignKey?.split("."))?.pop();
2304
2459
  }
2305
2460
  buildDictionary(results) {
2306
2461
  const foreign = this.getForeignKeyName();
2307
- return (0, collect_js.collect)(results).mapToDictionary((result) => [result[foreign], result]).all();
2462
+ return (0, _h3ravel_collect_js.collect)(results).mapToDictionary((result) => [result[foreign], result]).all();
2308
2463
  }
2309
2464
  match(models, results, relation) {
2310
2465
  return this.matchOneOrMany(models, results, relation, "many");
@@ -2335,9 +2490,7 @@ var HasOne = class extends compose(Relation, HasOneOrMany, SupportsDefaultModels
2335
2490
  return this.matchOneOrMany(models, results, relation, "one");
2336
2491
  }
2337
2492
  getForeignKeyName() {
2338
- var _this$foreignKey;
2339
- const segments = (_this$foreignKey = this.foreignKey) === null || _this$foreignKey === void 0 ? void 0 : _this$foreignKey.split(".");
2340
- return segments === null || segments === void 0 ? void 0 : segments.pop();
2493
+ return (this.foreignKey?.split("."))?.pop();
2341
2494
  }
2342
2495
  async getResults() {
2343
2496
  if (this.getParentKey() === null) return this.getDefaultFor(this.parent);
@@ -2446,10 +2599,10 @@ var HasManyThrough = class extends Relation {
2446
2599
  }
2447
2600
  const model = await this.first(columns);
2448
2601
  if (model) return model;
2449
- return callback === null || callback === void 0 ? void 0 : callback();
2602
+ return callback?.();
2450
2603
  }
2451
2604
  async find(id, columns = ["*"]) {
2452
- if ((0, radashi.isArray)(id)) return await this.findMany(id, columns);
2605
+ if (Array.isArray(id)) return await this.findMany(id, columns);
2453
2606
  return await this.where(this.getRelated().getQualifiedKeyName(), "=", id).first(columns);
2454
2607
  }
2455
2608
  async findMany(ids, columns = ["*"]) {
@@ -2477,7 +2630,7 @@ var HasManyThrough = class extends Relation {
2477
2630
  return await this.query.paginate(perPage ?? 15, columns, pageName, page);
2478
2631
  }
2479
2632
  shouldSelect(columns = ["*"]) {
2480
- if ((columns === null || columns === void 0 ? void 0 : columns.at(0)) == "*") columns = [this.related.getTable() + ".*"];
2633
+ if (columns?.at(0) == "*") columns = [this.related.getTable() + ".*"];
2481
2634
  return [...columns, this.getQualifiedFirstKeyName() + " as laravel_through_key"];
2482
2635
  }
2483
2636
  async chunk(count, callback) {
@@ -2571,7 +2724,7 @@ const HasRelations = (Model) => {
2571
2724
  return this;
2572
2725
  }
2573
2726
  unsetRelation(relation) {
2574
- this.relations = (0, radashi.omit)(this.relations, [relation]);
2727
+ this.relations = _h3ravel_support.Arr.except(this.relations, [relation]);
2575
2728
  return this;
2576
2729
  }
2577
2730
  relationLoaded(relation) {
@@ -2594,8 +2747,7 @@ const HasRelations = (Model) => {
2594
2747
  return data;
2595
2748
  }
2596
2749
  guessBelongsToRelation() {
2597
- var _e$stack;
2598
- const functionName = (((_e$stack = (/* @__PURE__ */ new Error()).stack) === null || _e$stack === void 0 ? void 0 : _e$stack.split("\n")[2]) ?? "").split(" ")[5];
2750
+ const functionName = ((/* @__PURE__ */ new Error()).stack?.split("\n")[2] ?? "").split(" ")[5];
2599
2751
  return getRelationName(functionName);
2600
2752
  }
2601
2753
  joiningTable(related, instance = null) {
@@ -2705,7 +2857,7 @@ const HidesAttributes = (Model) => {
2705
2857
  makeVisible(...keys) {
2706
2858
  const visible = flattenDeep(keys);
2707
2859
  if (this.visible.length > 0) this.visible = [...this.visible, ...visible];
2708
- this.hidden = (0, radashi.diff)(this.hidden, visible);
2860
+ this.hidden = (0, _h3ravel_collect_js.collect)(this.hidden).diff(visible).all();
2709
2861
  return this;
2710
2862
  }
2711
2863
  makeHidden(key, ...keys) {
@@ -2849,10 +3001,9 @@ var QueryBuilder = class QueryBuilder extends Inference$1 {
2849
3001
  asProxy() {
2850
3002
  return new Proxy(this, {
2851
3003
  get: function(target, prop) {
2852
- var _target$connector$cli;
2853
3004
  if (typeof target[prop] !== "undefined") return target[prop];
2854
3005
  if (["destroy", "schema"].includes(prop)) return target.connector.schema;
2855
- 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";
3006
+ const skipReturning = !!target.connector.client.config?.client?.includes("mysql") && prop === "returning";
2856
3007
  if ([
2857
3008
  "select",
2858
3009
  "from",
@@ -3055,6 +3206,9 @@ var arquebus = class arquebus {
3055
3206
  if (this.instance === null) this.instance = new arquebus();
3056
3207
  return this.instance;
3057
3208
  }
3209
+ static withSchema() {
3210
+ return this;
3211
+ }
3058
3212
  /**
3059
3213
  * Initialize a new database connection
3060
3214
  *
@@ -3144,12 +3298,12 @@ var arquebus = class arquebus {
3144
3298
  const tsPath = path.default.resolve("arquebus.config.ts");
3145
3299
  const instance = this.getInstance();
3146
3300
  if ((0, fs.existsSync)(jsPath)) {
3147
- config = (await import(jsPath)).default;
3301
+ config = (await (0, _h3ravel_shared.importFile)(jsPath)).default;
3148
3302
  if (addConnection) instance.addConnection(config, config.client);
3149
3303
  return config;
3150
3304
  }
3151
3305
  if ((0, fs.existsSync)(tsPath)) if (process.env.NODE_ENV !== "production") {
3152
- config = (await import(tsPath)).default;
3306
+ config = (await (0, _h3ravel_shared.importFile)(tsPath)).default;
3153
3307
  if (addConnection) instance.addConnection(config, config.client);
3154
3308
  return config;
3155
3309
  } else throw new Error("arquebus.config.ts found in production without build step");
@@ -3165,7 +3319,7 @@ var arquebus = class arquebus {
3165
3319
  "cjs"
3166
3320
  ], dir);
3167
3321
  if (found) if (!found.endsWith(".ts") || process.env.NODE_ENV !== "production") {
3168
- config = (await import(found)).default;
3322
+ config = (await (0, _h3ravel_shared.importFile)(found)).default;
3169
3323
  if (addConnection) instance.addConnection(config, config.client);
3170
3324
  return config;
3171
3325
  } else throw new Error("arquebus.config.ts found in production without build step");
@@ -3186,7 +3340,7 @@ var arquebus = class arquebus {
3186
3340
  }
3187
3341
  async destroyAll() {
3188
3342
  await Promise.all(Object.values(this.manager).map((connection) => {
3189
- return connection === null || connection === void 0 ? void 0 : connection.destroy();
3343
+ return connection?.destroy();
3190
3344
  }));
3191
3345
  }
3192
3346
  createModel(name, options = {}) {
@@ -3195,29 +3349,25 @@ var arquebus = class arquebus {
3195
3349
  this.models = {
3196
3350
  ...this.models,
3197
3351
  [name]: class extends BaseModel {
3198
- table = (options === null || options === void 0 ? void 0 : options.table) ?? null;
3199
- connection = (options === null || options === void 0 ? void 0 : options.connection) ?? null;
3200
- timestamps = (options === null || options === void 0 ? void 0 : options.timestamps) ?? true;
3201
- primaryKey = (options === null || options === void 0 ? void 0 : options.primaryKey) ?? "id";
3202
- keyType = (options === null || options === void 0 ? void 0 : options.keyType) ?? "int";
3203
- incrementing = (options === null || options === void 0 ? void 0 : options.incrementing) ?? true;
3204
- with = (options === null || options === void 0 ? void 0 : options.with) ?? [];
3205
- casts = (options === null || options === void 0 ? void 0 : options.casts) ?? {};
3206
- static CREATED_AT = (options === null || options === void 0 ? void 0 : options.CREATED_AT) ?? "created_at";
3207
- static UPDATED_AT = (options === null || options === void 0 ? void 0 : options.UPDATED_AT) ?? "updated_at";
3208
- static DELETED_AT = (options === null || options === void 0 ? void 0 : options.DELETED_AT) ?? "deleted_at";
3352
+ table = options?.table ?? null;
3353
+ connection = options?.connection ?? null;
3354
+ timestamps = options?.timestamps ?? true;
3355
+ primaryKey = options?.primaryKey ?? "id";
3356
+ keyType = options?.keyType ?? "int";
3357
+ incrementing = options?.incrementing ?? true;
3358
+ with = options?.with ?? [];
3359
+ casts = options?.casts ?? {};
3360
+ static CREATED_AT = options?.CREATED_AT ?? "created_at";
3361
+ static UPDATED_AT = options?.UPDATED_AT ?? "updated_at";
3362
+ static DELETED_AT = options?.DELETED_AT ?? "deleted_at";
3209
3363
  }
3210
3364
  };
3211
3365
  if ("attributes" in options) for (const attribute in options.attributes) {
3212
3366
  if (options.attributes[attribute] instanceof Attribute === false) throw new Error("Attribute must be an instance of \"Attribute\"");
3213
- this.models[name].prototype[getAttrMethod(attribute)] = () => {
3214
- var _options$attributes;
3215
- return (_options$attributes = options.attributes) === null || _options$attributes === void 0 ? void 0 : _options$attributes[attribute];
3216
- };
3367
+ this.models[name].prototype[getAttrMethod(attribute)] = () => options.attributes?.[attribute];
3217
3368
  }
3218
3369
  if ("relations" in options) for (const relation in options.relations) this.models[name].prototype[getRelationMethod(relation)] = function() {
3219
- var _options$relations;
3220
- return (_options$relations = options.relations) === null || _options$relations === void 0 ? void 0 : _options$relations[relation](this);
3370
+ return options.relations?.[relation](this);
3221
3371
  };
3222
3372
  if ("scopes" in options) for (const scope in options.scopes) this.models[name].prototype[getScopeMethod(scope)] = options.scopes[scope];
3223
3373
  this.models[name].setConnectionResolver(this);
@@ -3255,6 +3405,9 @@ var Model = class Model extends BaseModel {
3255
3405
  this.buildRelationships(attributes);
3256
3406
  return this.asProxy();
3257
3407
  }
3408
+ static define() {
3409
+ return this;
3410
+ }
3258
3411
  static query(trx = null) {
3259
3412
  return new this().newQuery(trx);
3260
3413
  }
@@ -3438,7 +3591,7 @@ var Model = class Model extends BaseModel {
3438
3591
  });
3439
3592
  }
3440
3593
  toData() {
3441
- return (0, radashi.assign)(this.attributesToData(), this.relationsToData());
3594
+ return _h3ravel_support.Obj.deepMerge(this.attributesToData(), this.relationsToData());
3442
3595
  }
3443
3596
  toJSON() {
3444
3597
  return this.toData();
@@ -3449,6 +3602,15 @@ var Model = class Model extends BaseModel {
3449
3602
  toString() {
3450
3603
  return this.toJson();
3451
3604
  }
3605
+ getAttributes() {
3606
+ return super.getAttributes();
3607
+ }
3608
+ getAttribute(key) {
3609
+ return super.getAttribute(key);
3610
+ }
3611
+ setAttribute(key, value) {
3612
+ return super.setAttribute(key, value);
3613
+ }
3452
3614
  fill(attributes) {
3453
3615
  for (const key in attributes) this.setAttribute(key, attributes[key]);
3454
3616
  return this;
@@ -3489,10 +3651,9 @@ var Model = class Model extends BaseModel {
3489
3651
  if (this.usesTimestamps()) this.updateTimestamps();
3490
3652
  const attributes = this.getAttributes();
3491
3653
  if (this.getIncrementing()) {
3492
- var _data$;
3493
3654
  const keyName = this.getKeyName();
3494
3655
  const data = await query.insert([attributes], [keyName]);
3495
- this.setAttribute(keyName, ((_data$ = data[0]) === null || _data$ === void 0 ? void 0 : _data$[keyName]) || data[0]);
3656
+ this.setAttribute(keyName, data[0]?.[keyName] || data[0]);
3496
3657
  } else if (Object.keys(attributes).length > 0) await query.insert(attributes);
3497
3658
  this.exists = true;
3498
3659
  await this.execHooks("created", options);
@@ -3534,7 +3695,7 @@ var Model = class Model extends BaseModel {
3534
3695
  if (!this.exists) return Promise.resolve(void 0);
3535
3696
  const model = await this.constructor.query().where(this.getKeyName(), this.getKey()).first();
3536
3697
  this.attributes = { ...model.attributes };
3537
- await this.load((0, collect_js.default)(this.relations).reject((relation) => {
3698
+ await this.load((0, _h3ravel_collect_js.collect)(this.relations).reject((relation) => {
3538
3699
  return relation instanceof Pivot;
3539
3700
  }).keys().all());
3540
3701
  this.syncOriginal();
@@ -3598,7 +3759,7 @@ var Pivot = class extends Model {
3598
3759
  };
3599
3760
  //#endregion
3600
3761
  //#region src/collection.ts
3601
- var Collection = class Collection extends collect_js.Collection {
3762
+ var Collection = class extends _h3ravel_collect_js.Collection {
3602
3763
  newConstructor(...args) {
3603
3764
  return new (this.getConstructor())(...args);
3604
3765
  }
@@ -3607,17 +3768,18 @@ var Collection = class Collection extends collect_js.Collection {
3607
3768
  }
3608
3769
  async load(...relations) {
3609
3770
  if (this.isNotEmpty()) {
3610
- const items = await this.first().constructor.query().with(...relations).eagerLoadRelations(this.items);
3771
+ const items = await this.first().constructor.query().with(...relations).eagerLoadRelations(this.all());
3611
3772
  return this.newConstructor(items);
3612
3773
  }
3613
3774
  return this;
3614
3775
  }
3615
3776
  async loadAggregate(relations, column, action = null) {
3616
3777
  if (this.isEmpty()) return this;
3617
- 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());
3618
- const attributes = (0, radashi.diff)(Object.keys(models.first().getAttributes()), [models.first().getKeyName()]);
3778
+ const first = this.first();
3779
+ const models = (await first.newModelQuery().whereIn(first.getKeyName(), this.modelKeys()).select(first.getKeyName()).withAggregate(relations, column, action).get()).keyBy(first.getKeyName());
3780
+ const attributes = (0, _h3ravel_collect_js.collect)(Object.keys(models.first().getAttributes())).diff([models.first().getKeyName()]).all();
3619
3781
  this.each((model) => {
3620
- const extraAttributes = (0, radashi.pick)(models.get(model.getKey()).getAttributes(), attributes);
3782
+ const extraAttributes = _h3ravel_support.Arr.select(models.get(model.getKey()).getAttributes(), attributes);
3621
3783
  model.fill(extraAttributes).syncOriginalAttributes(...attributes);
3622
3784
  });
3623
3785
  return this;
@@ -3655,20 +3817,21 @@ var Collection = class Collection extends collect_js.Collection {
3655
3817
  diff(items) {
3656
3818
  const diff = new this.constructor();
3657
3819
  const dictionary = this.getDictionary(items);
3658
- this.items.map((item) => {
3820
+ this.all().map((item) => {
3659
3821
  if (dictionary[item.getKey()] === void 0) diff.add(item);
3660
3822
  });
3661
3823
  return diff;
3662
3824
  }
3663
- except(keys) {
3664
- const dictionary = (0, radashi.omit)(this.getDictionary(), keys);
3825
+ except(...keys) {
3826
+ const values = keys.length === 1 && Array.isArray(keys[0]) ? keys[0].map(String) : keys.map(String);
3827
+ const dictionary = _h3ravel_support.Arr.except(this.getDictionary(), values);
3665
3828
  return new this.constructor(Object.values(dictionary));
3666
3829
  }
3667
3830
  intersect(items) {
3668
3831
  const intersect = new this.constructor();
3669
- if ((0, radashi.isEmpty)(items)) return intersect;
3832
+ if (_h3ravel_support.Arr.isEmpty(items)) return intersect;
3670
3833
  const dictionary = this.getDictionary(items);
3671
- for (const item of this.items) if (dictionary[item.getKey()] !== void 0) intersect.add(item);
3834
+ for (const item of this.all()) if (dictionary[item.getKey()] !== void 0) intersect.add(item);
3672
3835
  return intersect;
3673
3836
  }
3674
3837
  unique(key, _strict = false) {
@@ -3677,20 +3840,21 @@ var Collection = class Collection extends collect_js.Collection {
3677
3840
  }
3678
3841
  find(key, defaultValue = null) {
3679
3842
  if (key instanceof Model) key = key.getKey();
3680
- if ((0, radashi.isArray)(key)) {
3843
+ if (Array.isArray(key)) {
3681
3844
  if (this.isEmpty()) return new this.constructor();
3682
3845
  return this.whereIn(this.first().getKeyName(), key);
3683
3846
  }
3684
- (0, collect_js.collect)(this.items).first((model) => {
3847
+ (0, _h3ravel_collect_js.collect)(this.all()).first((model) => {
3685
3848
  return model.getKey() == key;
3686
3849
  });
3687
- return this.items.filter((model) => {
3850
+ return this.all().filter((model) => {
3688
3851
  return model.getKey() == key;
3689
3852
  })[0] || defaultValue;
3690
3853
  }
3691
3854
  async fresh(...args) {
3692
3855
  if (this.isEmpty()) return new this.constructor();
3693
3856
  const model = this.first();
3857
+ if (!model) return new this.constructor();
3694
3858
  const freshModels = (await model.newQuery().with(...args).whereIn(model.getKeyName(), this.modelKeys()).get()).getDictionary();
3695
3859
  return this.filter((model) => {
3696
3860
  return model.exists && freshModels[model.getKey()] !== void 0;
@@ -3713,15 +3877,15 @@ var Collection = class Collection extends collect_js.Collection {
3713
3877
  item.append(attributes);
3714
3878
  });
3715
3879
  }
3716
- only(keys) {
3717
- if (keys === null) return new Collection(this.items);
3718
- const dictionary = (0, radashi.pick)(this.getDictionary(), keys);
3880
+ only(...keys) {
3881
+ const values = keys.length === 1 && Array.isArray(keys[0]) ? keys[0].map(String) : keys.map(String);
3882
+ const dictionary = _h3ravel_support.Arr.select(this.getDictionary(), values);
3719
3883
  return new this.constructor(Object.values(dictionary));
3720
3884
  }
3721
3885
  getDictionary(items) {
3722
- items = !items ? this.items : items;
3886
+ const values = !items ? this.all() : items instanceof _h3ravel_collect_js.Collection ? items.all() : items;
3723
3887
  const dictionary = {};
3724
- items.map((value) => {
3888
+ values.map((value) => {
3725
3889
  dictionary[value.getKey()] = value;
3726
3890
  });
3727
3891
  return dictionary;
@@ -3745,8 +3909,8 @@ var Collection = class Collection extends collect_js.Collection {
3745
3909
  return JSON.stringify(this.toData(), ...args);
3746
3910
  }
3747
3911
  [Symbol.iterator] = () => {
3748
- const items = this.items;
3749
- const length = this.items.length;
3912
+ const items = this.all();
3913
+ const length = items.length;
3750
3914
  let n = 0;
3751
3915
  return { next() {
3752
3916
  return n < length ? {
@@ -3793,24 +3957,24 @@ const InteractsWithPivotTable = (Relation) => {
3793
3957
  let records;
3794
3958
  const results = await this.getCurrentlyAttachedPivots();
3795
3959
  const current = results.length === 0 ? [] : results.map((result) => result.toData()).pluck(this.relatedPivotKey).all().map((i) => String(i));
3796
- const detach = (0, radashi.diff)(current, Object.keys(records = this.formatRecordsList(this.parseIds(ids))));
3960
+ const detach = (0, _h3ravel_collect_js.collect)(current).diff(Object.keys(records = this.formatRecordsList(this.parseIds(ids)))).all();
3797
3961
  if (detaching && detach.length > 0) {
3798
3962
  await this.detach(detach);
3799
3963
  changes.detached = this.castKeys(detach);
3800
3964
  }
3801
- changes = (0, radashi.assign)(changes, await this.attachNew(records, current, false));
3965
+ changes = _h3ravel_support.Obj.deepMerge(changes, await this.attachNew(records, current, false));
3802
3966
  return changes;
3803
3967
  }
3804
3968
  syncWithoutDetaching(ids) {
3805
3969
  return this.sync(ids, false);
3806
3970
  }
3807
3971
  syncWithPivotValues(ids, values, detaching = true) {
3808
- return this.sync((0, collect_js.collect)(this.parseIds(ids)).mapWithKeys((id) => {
3809
- return [id, values];
3972
+ return this.sync((0, _h3ravel_collect_js.collect)(this.parseIds(ids)).mapWithKeys((id) => {
3973
+ return [String(id), values];
3810
3974
  }), detaching);
3811
3975
  }
3812
3976
  withPivot(columns) {
3813
- this.pivotColumns = this.pivotColumns.concat((0, radashi.isArray)(columns) ? columns : Array.prototype.slice.call(columns));
3977
+ this.pivotColumns = this.pivotColumns.concat(Array.isArray(columns) ? columns : Array.prototype.slice.call(columns));
3814
3978
  return this;
3815
3979
  }
3816
3980
  async attachNew(records, current, touch = true) {
@@ -3846,9 +4010,9 @@ const InteractsWithPivotTable = (Relation) => {
3846
4010
  return parseInt(updated);
3847
4011
  }
3848
4012
  formatRecordsList(records) {
3849
- return (0, collect_js.collect)(records).mapWithKeys((attributes, id) => {
3850
- if (!(0, radashi.isArray)(attributes)) [id, attributes] = [attributes, {}];
3851
- return [id, attributes];
4013
+ return (0, _h3ravel_collect_js.collect)(records).mapWithKeys((attributes, id) => {
4014
+ if (!Array.isArray(attributes)) [id, attributes] = [attributes, {}];
4015
+ return [String(id), attributes];
3852
4016
  }).all();
3853
4017
  }
3854
4018
  async getCurrentlyAttachedPivots() {
@@ -3918,7 +4082,7 @@ const InteractsWithPivotTable = (Relation) => {
3918
4082
  }
3919
4083
  formatAttachRecord(key, value, attributes, hasTimestamps) {
3920
4084
  const [id, newAttributes] = this.extractAttachIdAndAttributes(key, value, attributes);
3921
- return (0, radashi.assign)(this.baseAttachRecord(id, hasTimestamps), newAttributes);
4085
+ return _h3ravel_support.Obj.deepMerge(this.baseAttachRecord(id, hasTimestamps), newAttributes);
3922
4086
  }
3923
4087
  baseAttachRecord(id, timed) {
3924
4088
  let record = {};
@@ -3931,7 +4095,7 @@ const InteractsWithPivotTable = (Relation) => {
3931
4095
  return record;
3932
4096
  }
3933
4097
  extractAttachIdAndAttributes(key, value, newAttributes) {
3934
- return (0, radashi.isArray)(value) ? [key, {
4098
+ return Array.isArray(value) ? [key, {
3935
4099
  ...value,
3936
4100
  ...newAttributes
3937
4101
  }] : [value, newAttributes];
@@ -3942,7 +4106,7 @@ const InteractsWithPivotTable = (Relation) => {
3942
4106
  parseIds(value) {
3943
4107
  if (value instanceof Model) return [value[this.relatedKey]];
3944
4108
  if (value instanceof Collection) return value.pluck(this.relatedKey).all();
3945
- return (0, radashi.isArray)(value) ? value : [value];
4109
+ return Array.isArray(value) ? value : [value];
3946
4110
  }
3947
4111
  };
3948
4112
  };
@@ -4002,9 +4166,8 @@ var BelongsToMany = class extends compose(Relation, InteractsWithPivotTable) {
4002
4166
  return this;
4003
4167
  }
4004
4168
  async get(columns) {
4005
- var _builder$query;
4006
4169
  const builder = this.query.applyScopes();
4007
- 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;
4170
+ columns = builder.query?._statements?.find((item) => item.grouping == "columns") ? [] : columns;
4008
4171
  let models = await builder.select(this.shouldSelect(columns)).getModels();
4009
4172
  this.hydratePivotRelation(models);
4010
4173
  if (models.length > 0) models = await builder.eagerLoadRelations(models);
@@ -4053,7 +4216,7 @@ var BelongsToMany = class extends compose(Relation, InteractsWithPivotTable) {
4053
4216
  const value = model.attributes[key];
4054
4217
  if (key.startsWith("pivot_")) {
4055
4218
  values[key.substring(6)] = value;
4056
- model.attributes = (0, radashi.omit)(model.attributes, [key]);
4219
+ model.attributes = _h3ravel_support.Arr.except(model.attributes, [key]);
4057
4220
  }
4058
4221
  }
4059
4222
  return values;
@@ -4064,11 +4227,11 @@ var BelongsToMany = class extends compose(Relation, InteractsWithPivotTable) {
4064
4227
  return this.withPivot(this.createdAt(), this.updatedAt());
4065
4228
  }
4066
4229
  shouldSelect(columns = ["*"]) {
4067
- if ((0, radashi.isEqual)(columns, ["*"])) columns = [this.related.getTable() + ".*"];
4230
+ if (columns.length === 1 && columns[0] === "*") columns = [this.related.getTable() + ".*"];
4068
4231
  return columns.concat(this.aliasedPivotColumns());
4069
4232
  }
4070
4233
  aliasedPivotColumns() {
4071
- return (0, collect_js.collect)([this.foreignPivotKey, this.relatedPivotKey].concat(this.pivotColumns)).map((column) => {
4234
+ return (0, _h3ravel_collect_js.collect)([this.foreignPivotKey, this.relatedPivotKey].concat(this.pivotColumns)).map((column) => {
4072
4235
  return this.qualifyPivotColumn(column) + " as pivot_" + column;
4073
4236
  }).unique().all();
4074
4237
  }
@@ -4188,9 +4351,8 @@ var Builder = class Builder extends Inference {
4188
4351
  }
4189
4352
  asProxy() {
4190
4353
  return new Proxy(this, { get(target, prop) {
4191
- var _target$query$connect;
4192
4354
  if (typeof target[prop] !== "undefined") return target[prop];
4193
- 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";
4355
+ const skipReturning = !!target.query.connector?.client.config?.client?.includes("mysql") && prop === "returning";
4194
4356
  if ([
4195
4357
  "select",
4196
4358
  "from",
@@ -4284,7 +4446,7 @@ var Builder = class Builder extends Inference {
4284
4446
  };
4285
4447
  }
4286
4448
  if (prop.startsWith("where")) {
4287
- const column = (0, radashi.snake)(prop.substring(5));
4449
+ const column = _h3ravel_support.Str.snake(prop.substring(5));
4288
4450
  return (...args) => {
4289
4451
  target.query.where(column, ...args);
4290
4452
  return target.asProxy();
@@ -4359,7 +4521,8 @@ var Builder = class Builder extends Inference {
4359
4521
  }
4360
4522
  addUpdatedAtColumn(values) {
4361
4523
  if (!this.model.usesTimestamps() || this.model.getUpdatedAtColumn() === null) return values;
4362
- values = (0, radashi.assign)({ [this.model.getUpdatedAtColumn()]: this.model.freshTimestampString() }, values);
4524
+ const column = this.model.getUpdatedAtColumn();
4525
+ values = _h3ravel_support.Obj.deepMerge({ [column]: this.model.freshTimestampString() }, values);
4363
4526
  return values;
4364
4527
  }
4365
4528
  delete() {
@@ -4387,9 +4550,8 @@ var Builder = class Builder extends Inference {
4387
4550
  return this.model;
4388
4551
  }
4389
4552
  setModel(model) {
4390
- var _this$query;
4391
4553
  this.model = model;
4392
- 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());
4554
+ if (typeof this.query?.client?.table == "function") this.query = this.query.client.table(this.model.getTable());
4393
4555
  else this.query = this.query.table(this.model.getTable());
4394
4556
  return this;
4395
4557
  }
@@ -4432,7 +4594,7 @@ var Builder = class Builder extends Inference {
4432
4594
  }
4433
4595
  withoutGlobalScope(scope) {
4434
4596
  if (typeof scope !== "string") scope = scope.constructor.name;
4435
- this.globalScopes = (0, radashi.omit)(this.globalScopes, [scope]);
4597
+ this.globalScopes = _h3ravel_support.Arr.except(this.globalScopes, [scope]);
4436
4598
  return this;
4437
4599
  }
4438
4600
  macro(name, callback) {
@@ -4449,7 +4611,7 @@ var Builder = class Builder extends Inference {
4449
4611
  let eagerLoads = {};
4450
4612
  if (typeof args[1] === "function") {
4451
4613
  const eagerLoad = this.parseWithRelations({ [args[0]]: args[1] });
4452
- this.eagerLoad = (0, radashi.assign)(this.eagerLoad, eagerLoad);
4614
+ this.eagerLoad = _h3ravel_support.Obj.deepMerge(this.eagerLoad, eagerLoad);
4453
4615
  return this;
4454
4616
  }
4455
4617
  const relations = flattenDeep(args);
@@ -4458,13 +4620,13 @@ var Builder = class Builder extends Inference {
4458
4620
  let eagerLoad;
4459
4621
  if (typeof relation === "string") eagerLoad = { [relation]: (q) => q };
4460
4622
  else if (typeof relation === "object") eagerLoad = relation;
4461
- eagerLoads = (0, radashi.assign)(eagerLoads, eagerLoad);
4623
+ eagerLoads = _h3ravel_support.Obj.deepMerge(eagerLoads, eagerLoad);
4462
4624
  }
4463
- this.eagerLoad = (0, radashi.assign)(this.eagerLoad, this.parseWithRelations(eagerLoads));
4625
+ this.eagerLoad = _h3ravel_support.Obj.deepMerge(this.eagerLoad, this.parseWithRelations(eagerLoads));
4464
4626
  return this;
4465
4627
  }
4466
4628
  has(relation, operator = ">=", count = 1, boolean = "and", callback = null) {
4467
- if ((0, radashi.isString)(relation)) {
4629
+ if (typeof relation === "string") {
4468
4630
  if (relation.includes(".")) return this.hasNested(relation, operator, count, boolean, callback);
4469
4631
  relation = this.getRelationWithoutConstraints(getRelationMethod(relation));
4470
4632
  }
@@ -4541,7 +4703,7 @@ var Builder = class Builder extends Inference {
4541
4703
  let eagerLoad;
4542
4704
  if (typeof relation === "string") eagerLoad = { [relation]: (q) => q };
4543
4705
  else if (typeof relation === "object") eagerLoad = relation;
4544
- eagerLoads = (0, radashi.assign)(eagerLoads, eagerLoad);
4706
+ eagerLoads = _h3ravel_support.Obj.deepMerge(eagerLoads, eagerLoad);
4545
4707
  }
4546
4708
  relations = eagerLoads;
4547
4709
  const db = this.model.getConnection();
@@ -4560,7 +4722,7 @@ var Builder = class Builder extends Inference {
4560
4722
  } else expression = column;
4561
4723
  const query = relation.getRelationExistenceQuery(relation.getRelated().newModelQuery(), this, db.raw(expression));
4562
4724
  constraints(query);
4563
- alias = alias || (0, radashi.snake)(`${name} ${action} ${column}`.replace("/[^[:alnum:][:space:]_]/u", ""));
4725
+ alias = alias || _h3ravel_support.Str.snake(`${name} ${action} ${column}`.replace("/[^[:alnum:][:space:]_]/u", ""));
4564
4726
  if (action === "exists") this.select(db.raw(`exists(${query.toSql().sql}) as ${alias}`));
4565
4727
  else this.selectSub(action ? query : query.limit(1), alias);
4566
4728
  }
@@ -4584,7 +4746,7 @@ var Builder = class Builder extends Inference {
4584
4746
  }
4585
4747
  parseSub(query) {
4586
4748
  if (query instanceof Builder || query instanceof Relation) return [query.toSql().sql, query.toSql().bindings];
4587
- else if ((0, radashi.isString)(query)) return [query, []];
4749
+ else if (typeof query === "string") return [query, []];
4588
4750
  else throw new Error("A subquery must be a query builder instance, a Closure, or a string.");
4589
4751
  }
4590
4752
  prependDatabaseNameIfCrossDatabaseQuery(query) {
@@ -4641,15 +4803,15 @@ var Builder = class Builder extends Inference {
4641
4803
  if (prefix !== "") prefix += ".";
4642
4804
  for (const key in relations) {
4643
4805
  const value = relations[key];
4644
- if ((0, radashi.isString)(value) || Number.isFinite(parseInt(value))) continue;
4806
+ if (typeof value === "string" || Number.isFinite(parseInt(value))) continue;
4645
4807
  const [attribute, attributeSelectConstraint] = this.parseNameAndAttributeSelectionConstraint(key, value);
4646
4808
  preparedRelationships = Object.assign({}, preparedRelationships, { [`${prefix}${attribute}`]: attributeSelectConstraint }, this.prepareNestedWithRelationships(value, `${prefix}${attribute}`));
4647
- relations = (0, radashi.omit)(relations, [key]);
4809
+ relations = _h3ravel_support.Arr.except(relations, [key]);
4648
4810
  }
4649
4811
  for (const key in relations) {
4650
4812
  const value = relations[key];
4651
4813
  let attribute = key, attributeSelectConstraint = value;
4652
- if ((0, radashi.isString)(value)) [attribute, attributeSelectConstraint] = this.parseNameAndAttributeSelectionConstraint(value);
4814
+ if (typeof value === "string") [attribute, attributeSelectConstraint] = this.parseNameAndAttributeSelectionConstraint(value);
4653
4815
  preparedRelationships[`${prefix}${attribute}`] = this.combineConstraints([attributeSelectConstraint, preparedRelationships[`${prefix}${attribute}`] || (() => {})]);
4654
4816
  }
4655
4817
  return preparedRelationships;
@@ -4697,8 +4859,8 @@ var Builder = class Builder extends Inference {
4697
4859
  }
4698
4860
  async findOrFail(...args) {
4699
4861
  const data = await this.find(...args);
4700
- if ((0, radashi.isArray)(args[0])) {
4701
- if (data.count() !== args[0].length) throw new ModelNotFoundError().setModel(this.model.constructor.name, (0, radashi.diff)(args[0], data.modelKeys()));
4862
+ if (Array.isArray(args[0])) {
4863
+ if (data.count() !== args[0].length) throw new ModelNotFoundError().setModel(this.model.constructor.name, (0, _h3ravel_collect_js.collect)(args[0]).diff(data.modelKeys()).all());
4702
4864
  return data;
4703
4865
  }
4704
4866
  if (data === null) throw new ModelNotFoundError().setModel(this.model.constructor.name, args[0]);
@@ -4712,12 +4874,12 @@ var Builder = class Builder extends Inference {
4712
4874
  async firstOrNew(attributes = {}, values = {}) {
4713
4875
  const instance = await this.where(attributes).first();
4714
4876
  if (instance !== null) return instance;
4715
- return this.newModelInstance((0, radashi.assign)(attributes, values));
4877
+ return this.newModelInstance(_h3ravel_support.Obj.deepMerge(attributes, values));
4716
4878
  }
4717
4879
  async firstOrCreate(attributes = {}, values = {}) {
4718
4880
  const instance = await this.where(attributes).first();
4719
4881
  if (instance !== null) return instance;
4720
- return tap(this.newModelInstance((0, radashi.assign)(attributes, values)), async (instance) => {
4882
+ return tap(this.newModelInstance(_h3ravel_support.Obj.deepMerge(attributes, values)), async (instance) => {
4721
4883
  await instance.save({ client: this.query });
4722
4884
  });
4723
4885
  }
@@ -4737,22 +4899,21 @@ var Builder = class Builder extends Inference {
4737
4899
  return this;
4738
4900
  }
4739
4901
  async find(id, columns) {
4740
- if ((0, radashi.isArray)(id) || id instanceof Collection) return await this.findMany(id, columns);
4902
+ if (Array.isArray(id) || id instanceof Collection) return await this.findMany(id, columns);
4741
4903
  return await this.where(this.model.getKeyName(), id).first(columns);
4742
4904
  }
4743
4905
  async findMany(ids, columns = ["*"]) {
4744
- if (ids instanceof Collection) ids = ids.modelKeys();
4745
- ids = (0, radashi.isArray)(ids) ? ids : [ids];
4746
- if (ids.length === 0) return new Collection([]);
4747
- return await this.whereIn(this.model.getKeyName(), ids).get(columns);
4906
+ const values = ids instanceof Collection ? ids.modelKeys() : Array.isArray(ids) ? ids : [ids];
4907
+ if (values.length === 0) return new Collection([]);
4908
+ return await this.whereIn(this.model.getKeyName(), values).get(columns);
4748
4909
  }
4749
4910
  async pluck(column) {
4750
4911
  return new Collection(await this.query.pluck(column));
4751
4912
  }
4752
4913
  async destroy(ids) {
4753
4914
  if (ids instanceof Collection) ids = ids.modelKeys();
4754
- if (ids instanceof collect_js.Collection) ids = ids.all();
4755
- ids = (0, radashi.isArray)(ids) ? ids : Array.prototype.slice.call(ids);
4915
+ if (ids instanceof _h3ravel_collect_js.Collection) ids = ids.all();
4916
+ ids = Array.isArray(ids) ? ids : Array.prototype.slice.call(ids);
4756
4917
  if (ids.length === 0) return 0;
4757
4918
  const key = this.model.newInstance().getKeyName();
4758
4919
  let count = 0;
@@ -4770,12 +4931,11 @@ var Builder = class Builder extends Inference {
4770
4931
  return await this.model.newModelQuery().get(columns);
4771
4932
  }
4772
4933
  async paginate(page = 1, perPage = 10) {
4773
- var _this;
4774
4934
  page = page || 1;
4775
- perPage = perPage || ((_this = this) === null || _this === void 0 || (_this = _this.model) === null || _this === void 0 ? void 0 : _this.perPage) || 15;
4935
+ perPage = perPage || this?.model?.perPage || 15;
4776
4936
  this.applyScopes();
4777
4937
  const total = await this.query.clone().clearOrder().clearSelect().count(this.primaryKey);
4778
- let results = [];
4938
+ let results;
4779
4939
  if (total > 0) {
4780
4940
  const skip = (page - 1) * (perPage ?? 10);
4781
4941
  this.take(perPage).skip(skip);
@@ -4785,7 +4945,7 @@ var Builder = class Builder extends Inference {
4785
4945
  return new Paginator(results, parseInt(total), perPage, page);
4786
4946
  }
4787
4947
  async getModels(...columns) {
4788
- columns = (0, radashi.flat)(columns);
4948
+ columns = flatten(columns);
4789
4949
  if (columns.length > 0) {
4790
4950
  if (this.query._statements.filter((item) => item.grouping == "columns").length == 0 && columns[0] !== "*") this.query.select(...columns);
4791
4951
  }
@@ -4875,7 +5035,7 @@ var SQLite = class {
4875
5035
  column: column.name
4876
5036
  }));
4877
5037
  const tables = await this.tables();
4878
- return flatten$2(await Promise.all(tables.map(async (table) => await this.columns(table))));
5038
+ return flatten(await Promise.all(tables.map(async (table) => await this.columns(table))));
4879
5039
  }
4880
5040
  async columnInfo(table, column) {
4881
5041
  const getColumnsForTable = async (table) => {
@@ -4901,17 +5061,17 @@ var SQLite = class {
4901
5061
  is_generated: raw.hidden !== 0,
4902
5062
  generation_expression: null,
4903
5063
  is_nullable: raw.notnull === 0,
4904
- is_unique: !!(index === null || index === void 0 ? void 0 : index.unique) && (indexInfo === null || indexInfo === void 0 ? void 0 : indexInfo.length) === 1,
5064
+ is_unique: !!index?.unique && indexInfo?.length === 1,
4905
5065
  is_primary_key: raw.pk === 1,
4906
5066
  has_auto_increment: raw.pk === 1 && tablesWithAutoIncrementPrimaryKeys.includes(table),
4907
- foreign_key_column: (foreignKey === null || foreignKey === void 0 ? void 0 : foreignKey.to) || null,
4908
- foreign_key_table: (foreignKey === null || foreignKey === void 0 ? void 0 : foreignKey.table) || null
5067
+ foreign_key_column: foreignKey?.to || null,
5068
+ foreign_key_table: foreignKey?.table || null
4909
5069
  };
4910
5070
  });
4911
5071
  };
4912
5072
  if (!table) {
4913
5073
  const tables = await this.tables();
4914
- return flatten$2(await Promise.all(tables.map(async (table) => await getColumnsForTable(table))));
5074
+ return flatten(await Promise.all(tables.map(async (table) => await getColumnsForTable(table))));
4915
5075
  }
4916
5076
  if (table && !column) return await getColumnsForTable(table);
4917
5077
  return (await getColumnsForTable(table)).find((columnInfo) => columnInfo.name === column);
@@ -4942,7 +5102,7 @@ var SQLite = class {
4942
5102
  constraint_name: null
4943
5103
  }));
4944
5104
  const tables = await this.tables();
4945
- return flatten$2(await Promise.all(tables.map(async (table) => await this.foreignKeys(table))));
5105
+ return flatten(await Promise.all(tables.map(async (table) => await this.foreignKeys(table))));
4946
5106
  }
4947
5107
  async uniqueConstraints(table) {
4948
5108
  if (table) {
@@ -4958,7 +5118,7 @@ var SQLite = class {
4958
5118
  });
4959
5119
  }
4960
5120
  const tables = await this.tables();
4961
- return flatten$2(await Promise.all(tables.map(async (table) => await this.uniqueConstraints(table))));
5121
+ return flatten(await Promise.all(tables.map(async (table) => await this.uniqueConstraints(table))));
4962
5122
  }
4963
5123
  };
4964
5124
  //#endregion
@@ -5127,8 +5287,7 @@ var Migrator = class {
5127
5287
  else await callback(connection);
5128
5288
  }
5129
5289
  async runMethod(connection, migration, method) {
5130
- var _migration$method;
5131
- await ((_migration$method = migration[method]) === null || _migration$method === void 0 ? void 0 : _migration$method.call(migration, connection.schema, connection));
5290
+ await migration[method]?.(connection.schema, connection);
5132
5291
  }
5133
5292
  async resolvePath(filePath) {
5134
5293
  try {
@@ -5157,7 +5316,7 @@ var Migrator = class {
5157
5316
  return path.default.basename(filePath).replace(".js", "");
5158
5317
  }
5159
5318
  path(p) {
5160
- this.paths = Array.from(new Set([...this.paths, p]));
5319
+ this.paths = Array.from(/* @__PURE__ */ new Set([...this.paths, p]));
5161
5320
  }
5162
5321
  getPaths() {
5163
5322
  return this.paths;
@@ -5326,8 +5485,7 @@ var Migrate = class {
5326
5485
  * @returns
5327
5486
  */
5328
5487
  async setupConnection(config) {
5329
- var _config$migrations;
5330
- const table = (config === null || config === void 0 || (_config$migrations = config.migrations) === null || _config$migrations === void 0 ? void 0 : _config$migrations.table) || "migrations";
5488
+ const table = config?.migrations?.table || "migrations";
5331
5489
  if (config.skipConnection !== true) {
5332
5490
  arquebus.addConnection(config, "default");
5333
5491
  Object.entries(config.connections || {}).forEach(([name, connection]) => {
@@ -5387,7 +5545,6 @@ var MigrationCreator = class {
5387
5545
  let stub;
5388
5546
  if (!table) {
5389
5547
  const customPath = path.default.join(this.customStubPath ?? "", `migration-${this.type}.stub`);
5390
- console.log("\n", customPath, "---");
5391
5548
  stub = await _h3ravel_shared.FileSystem.fileExists(customPath) ? customPath : this.stubPath(`/migration-${this.type}.stub`);
5392
5549
  } else if (create) {
5393
5550
  const customPath = path.default.join(this.customStubPath ?? "", `migration.create-${this.type}.stub`);
@@ -5406,7 +5563,7 @@ var MigrationCreator = class {
5406
5563
  return name.replace(/_+([a-z])/g, (match, char) => char.toUpperCase());
5407
5564
  }
5408
5565
  getPath(name, dir) {
5409
- const datePrefix = (0, dayjs.default)().format("YYYY_MM_DD_HHmmss");
5566
+ const datePrefix = dayjs$1().format("YYYY_MM_DD_HHmmss");
5410
5567
  return path.default.join(dir, `${datePrefix}_${name}.${this.type}`);
5411
5568
  }
5412
5569
  async firePostCreateHooks(table, filePath) {
@@ -5420,7 +5577,9 @@ var MigrationCreator = class {
5420
5577
  }
5421
5578
  stubPath(stub = "") {
5422
5579
  const __dirname = this.getDirname({});
5423
- return path.default.join(__dirname, "stubs", stub);
5580
+ const resolved = [path.default.join(__dirname, "stubs", stub), path.default.join(__dirname, "../stubs", stub)].find((candidate) => (0, node_fs.existsSync)(candidate));
5581
+ if (!resolved) throw new Error(`Migration stub not found: ${stub}`);
5582
+ return resolved;
5424
5583
  }
5425
5584
  getDirname(meta) {
5426
5585
  if (typeof __dirname !== "undefined") return __dirname;
@@ -5430,20 +5589,33 @@ var MigrationCreator = class {
5430
5589
  };
5431
5590
  //#endregion
5432
5591
  //#region package.json
5433
- var version = "2.0.0";
5592
+ var version = "3.0.1";
5434
5593
  //#endregion
5435
5594
  //#region src/cli/index.ts
5436
- (class Cli {
5595
+ (class Cli extends _h3ravel_musket.Application {
5437
5596
  cwd;
5438
- output = _h3ravel_shared.Logger.log();
5597
+ output = _h3ravel_shared.Logger;
5439
5598
  config = {};
5440
5599
  basePath = "";
5441
- modulePath;
5600
+ modulePath = "";
5442
5601
  configPath;
5443
- modulePackage;
5602
+ modulePackage = { version: "N/A" };
5444
5603
  constructor(basePath) {
5604
+ super();
5445
5605
  this.basePath = basePath ?? (process.env.TEST === "true" ? "test/cli" : "");
5446
5606
  }
5607
+ static async init() {
5608
+ (0, dotenv.config)({ quiet: true });
5609
+ const instance = new Cli();
5610
+ await instance.loadPaths();
5611
+ await instance.loadConfig();
5612
+ await instance.run();
5613
+ }
5614
+ registerMusketListeners(musket) {
5615
+ musket.afterHandle.once(async () => {
5616
+ process.exit(0);
5617
+ });
5618
+ }
5447
5619
  terminateNotFound() {
5448
5620
  const cmd = _h3ravel_shared.Logger.log([["arquebus init", [
5449
5621
  "italic",
@@ -5452,13 +5624,24 @@ var version = "2.0.0";
5452
5624
  ]]], "", false);
5453
5625
  this.output.error(`ERROR: Arquebus config not found. Run ${cmd} first.`);
5454
5626
  }
5455
- static init() {
5456
- (0, dotenv.config)({ quiet: true });
5457
- const instance = new Cli();
5458
- Promise.all([instance.loadPaths(), instance.loadConfig()]).then(([_, e]) => e.run());
5627
+ ensureConfigured() {
5628
+ if (!this.configPath) this.terminateNotFound();
5629
+ }
5630
+ resolveBasePath(requestedPath) {
5631
+ return requestedPath ? node_path.default.join(this.cwd, requestedPath) : this.cwd;
5632
+ }
5633
+ async resolveStub(name) {
5634
+ const candidates = [node_path.default.join(this.modulePath, "src/stubs", name), node_path.default.join(this.modulePath, "dist/stubs", name)];
5635
+ for (const candidate of candidates) if (await _h3ravel_shared.FileSystem.fileExists(candidate)) return candidate;
5636
+ throw new Error(`Arquebus stub not found: ${name}`);
5637
+ }
5638
+ migrationReporter() {
5639
+ return (message, status) => {
5640
+ if (status && status !== "quiet") this.output[status](message);
5641
+ };
5459
5642
  }
5460
5643
  async loadPaths() {
5461
- this.cwd = path.default.join(process.cwd(), this.basePath);
5644
+ this.cwd = node_path.default.join(process.cwd(), this.basePath);
5462
5645
  this.configPath = _h3ravel_shared.FileSystem.resolveFileUp("arquebus.config", [
5463
5646
  "js",
5464
5647
  "ts",
@@ -5466,7 +5649,7 @@ var version = "2.0.0";
5466
5649
  ], this.cwd) ?? void 0;
5467
5650
  this.modulePath = Utils.findModulePkg("@h3ravel/arquebus", this.cwd) ?? "";
5468
5651
  try {
5469
- this.modulePackage = await import(path.default.join(this.modulePath, "package.json"));
5652
+ this.modulePackage = JSON.parse(await (0, node_fs_promises.readFile)(node_path.default.join(this.modulePath, "package.json"), "utf8"));
5470
5653
  } catch {
5471
5654
  this.modulePackage = { version: "N/A" };
5472
5655
  }
@@ -5474,233 +5657,184 @@ var version = "2.0.0";
5474
5657
  }
5475
5658
  async loadConfig() {
5476
5659
  try {
5477
- var _this$config$migratio;
5478
- this.config = (await import(this.configPath ?? "----")).default;
5479
- if ((_this$config$migratio = this.config.migrations) === null || _this$config$migratio === void 0 ? void 0 : _this$config$migratio.path) {
5480
- var _this$config$migratio2;
5481
- await (0, node_fs_promises.mkdir)(path.default.join(this.cwd, (_this$config$migratio2 = this.config.migrations) === null || _this$config$migratio2 === void 0 ? void 0 : _this$config$migratio2.path), { recursive: true });
5482
- }
5660
+ this.config = (await (0, _h3ravel_shared.importFile)(this.configPath ?? "----")).default;
5661
+ if (this.config.migrations?.path) await (0, node_fs_promises.mkdir)(node_path.default.join(this.cwd, this.config.migrations.path), { recursive: true });
5483
5662
  } catch {
5484
5663
  this.config = {};
5485
5664
  }
5486
5665
  return this;
5487
5666
  }
5488
5667
  async run() {
5489
- const cliVersion = ["Arquebus CLI version:", _h3ravel_shared.Logger.log(version, "green", false)].join(" ");
5490
- const localVersion = ["Arquebus Local version:", _h3ravel_shared.Logger.log(this.modulePackage.version || "None", "green", false)].join(" ");
5491
- commander.program.name("arquebus").version(`${cliVersion}\n${localVersion}`);
5492
- commander.program.command("init").description("Create a fresh Arquebus config.").addArgument(new commander.Argument("[type]", "Type of config to generate.").choices(["js", "ts"]).default("js", "generates a js config")).action(async (type) => {
5493
- if (!this.modulePath) this.output.error(["ERROR: No local arquebus install found", " Try running: npm install arquebus --save"]);
5494
- if (this.configPath) this.output.error(`ERROR: ${this.configPath} already exists`);
5495
- try {
5496
- const stubPath = `./arquebus.config.${type}`;
5497
- const code = await (0, node_fs_promises.readFile)(path.default.join(this.modulePath, `/src/stubs/arquebus.config-${type}.stub`), { encoding: "utf8" });
5498
- await (0, node_fs_promises.writeFile)(path.default.join(this.cwd, stubPath), code);
5499
- this.output.success(`Initialized: Arquebus has been initialized as ${stubPath}`);
5500
- } catch (e) {
5501
- this.output.error("ERROR: " + e);
5502
- }
5503
- });
5504
- commander.program.command("make:migration <name>").description("Create a new migration file.").addOption(new commander.Option("-l, --type [string]", "Type of migration file to generate.").choices(["js", "ts"]).default("js", "generates a js migration file")).option("-t, --table [string]", "The table to migrate").option("-c, --create [string]", "The table to be created").option("-p, --path [path]", "The path to the migrations directory.").action(async (name, opts) => {
5505
- if (!this.configPath) this.terminateNotFound();
5506
- try {
5507
- var _this$config$migratio3;
5508
- name = (0, radashi.snake)(name);
5509
- const migrationPath = path.default.join(this.cwd, opts.path ?? ((_this$config$migratio3 = this.config.migrations) === null || _this$config$migratio3 === void 0 ? void 0 : _this$config$migratio3.path) ?? "./migrations");
5510
- let table = opts.table;
5511
- let create = Boolean(opts.create) && opts.create !== "";
5512
- if (!table && typeof opts.create === "string") {
5513
- table = opts.create;
5514
- create = true;
5515
- }
5516
- if (!table) {
5517
- const guessed = TableGuesser.guess(name);
5518
- table = guessed[0];
5519
- create = !!guessed[1];
5520
- }
5521
- this.output.info("INFO: Creating Migration");
5522
- const fileName = await new MigrationCreator(void 0, opts.type).create(name, migrationPath, table, create);
5523
- this.output.success(`INFO: Migration Created \n ${_h3ravel_shared.Logger.log(path.default.basename(fileName), "gray", false)}`, true);
5524
- } catch (e) {
5525
- this.output.error("ERROR: " + e);
5526
- }
5527
- });
5528
- /**
5529
- * Publish migrations from third party vendors
5530
- */
5531
- commander.program.command("migrate:publish <package>").description("Publish any migration files from packages.").option("-p, --path [path]", "The path to the migrations directory.").action(async (pkg, opts) => {
5532
- if (!this.configPath) this.terminateNotFound();
5533
- try {
5534
- var _this$config$migratio4;
5535
- const packagePath = Utils.findModulePkg(pkg) ?? "";
5536
- const basePath = path.default.join(this.cwd, opts.path ?? ((_this$config$migratio4 = this.config.migrations) === null || _this$config$migratio4 === void 0 ? void 0 : _this$config$migratio4.path) ?? "./migrations");
5537
- const pkgJson = await import(path.default.join(packagePath, "package.json"));
5538
- if (!packagePath) this.output.error(`ERROR: package ${pkg} not found`);
5539
- const creator = new MigrationCreator(path.default.join(packagePath, pkgJson.migrations ?? "migrations"));
5540
- const pkgInf = _h3ravel_shared.Logger.log(path.default.basename(pkgJson.name + "@" + pkgJson.version), ["italic", "gray"], false);
5541
- this.output.info(`INFO: Publishing migrations from ${pkgInf}`);
5542
- await creator.publish(basePath, (fileName) => {
5543
- this.output.split("INFO: Migration Published", fileName, "success");
5544
- });
5545
- } catch (e) {
5546
- this.output.error("ERROR: " + e);
5547
- }
5548
- });
5549
- /**
5550
- * Run all pending migrations
5551
- */
5552
- commander.program.command("migrate").description("Run all pending migrations.").option("-s, --step [number]", "Force the migrations to be run so they can be rolled back individually.").option("-p, --path [path]", "The path to the migrations directory.").action(async (opts) => {
5553
- if (!this.configPath) this.terminateNotFound();
5554
- const basePath = opts.path ? path.default.join(this.cwd, opts.path) : this.cwd;
5555
- try {
5556
- const step = typeof opts.step === "string" ? parseInt(opts.step) : opts.step;
5557
- await new Migrate(basePath).run(this.config, {
5558
- ...opts,
5559
- step
5560
- }, true);
5561
- } catch (e) {
5562
- this.output.error("ERROR: " + e);
5563
- }
5564
- });
5565
- /**
5566
- * Rollaback the last migration
5567
- */
5568
- commander.program.command("migrate:rollback").description("Rollback the last database migration.").option("-s, --step [number]", "The number of migrations to be reverted.").option("-p, --path [path]", "The path to the migrations directory.").action(async (opts) => {
5569
- if (!this.configPath) this.terminateNotFound();
5570
- const basePath = opts.path ? path.default.join(this.cwd, opts.path) : this.cwd;
5571
- try {
5572
- await new Migrate(basePath, void 0, (msg, sts) => {
5573
- if (sts) this.output[sts](msg);
5574
- }).rollback(this.config, {
5575
- ...opts,
5576
- step: typeof opts.step === "string" ? parseInt(opts.step) : opts.step
5577
- }, true);
5578
- } catch (e) {
5579
- this.output.error("ERROR: " + e);
5580
- }
5581
- });
5582
- /**
5583
- * Rollback all database migrations
5584
- */
5585
- commander.program.command("migrate:reset").description("Rollback all database migrations.").option("-p, --path [path]", "The path to the migrations directory.").action(async (opts) => {
5586
- if (!this.configPath) this.terminateNotFound();
5587
- const basePath = opts.path ? path.default.join(this.cwd, opts.path) : this.cwd;
5588
- try {
5589
- await new Migrate(basePath, void 0, (msg, sts) => {
5590
- if (sts) this.output[sts](msg);
5591
- }).reset(this.config, opts, true);
5592
- } catch (e) {
5593
- this.output.error("ERROR: " + e);
5594
- }
5595
- });
5596
- /**
5597
- * Reset and re-run all migrations
5598
- */
5599
- commander.program.command("migrate:refresh").description("Reset and re-run all migrations.").option("-p, --path [path]", "The path to the migrations directory.").action(async (opts) => {
5600
- if (!this.configPath) this.terminateNotFound();
5601
- const basePath = opts.path ? path.default.join(this.cwd, opts.path) : this.cwd;
5602
- try {
5603
- await new Migrate(basePath, void 0, (msg, sts) => {
5604
- if (sts) this.output[sts](msg);
5605
- }).refresh(this.config, opts, true);
5606
- } catch (e) {
5607
- this.output.error("ERROR: " + e);
5608
- }
5609
- });
5610
- /**
5611
- * Drop all tables and re-run all migrations
5612
- */
5613
- commander.program.command("migrate:fresh").description("Drop all tables and re-run all migrations.").option("-p, --path [path]", "The path to the migrations directory.").action(async (opts) => {
5614
- if (!this.configPath) this.terminateNotFound();
5615
- const basePath = opts.path ? path.default.join(this.cwd, opts.path) : this.cwd;
5616
- try {
5617
- await new Migrate(basePath, void 0, (msg, sts) => {
5618
- if (sts) this.output[sts](msg);
5619
- }).fresh(this.config, opts, true);
5620
- } catch (e) {
5621
- this.output.error("ERROR: " + e);
5622
- }
5623
- });
5624
- /**
5625
- * Check the migration status
5626
- */
5627
- commander.program.command("migrate:status").description("Show the status of each migration.").option("-p, --path [path]", "The path to the migrations directory.").action(async (opts) => {
5628
- if (!this.configPath) this.terminateNotFound();
5629
- const basePath = opts.path ? path.default.join(this.cwd, opts.path) : this.cwd;
5630
- try {
5631
- const migrations = await new Migrate(basePath, void 0, (msg, sts) => {
5632
- if (sts) this.output[sts](msg);
5633
- }).status(this.config, opts, true);
5634
- if (migrations.length > 0) {
5635
- _h3ravel_shared.Logger.twoColumnDetail(_h3ravel_shared.Logger.log("Migration name", "gray", false), _h3ravel_shared.Logger.log("Batch / Status", "gray", false));
5636
- migrations.forEach((migration) => {
5637
- const status = migration.ran ? `[${migration.batch}] ${_h3ravel_shared.Logger.log("Ran", "green", false)}` : _h3ravel_shared.Logger.log("Pending", "yellow", false);
5638
- _h3ravel_shared.Logger.twoColumnDetail(migration.name, status);
5639
- });
5640
- } else console.log("No migrations found");
5641
- } catch (e) {
5642
- this.output.error("ERROR: " + e);
5643
- }
5644
- });
5645
- /**
5646
- * Run database seeders
5647
- */
5648
- commander.program.command("db:seed").description("Run database seeders.").option("-p, --path [path]", "The path to the seeders directory.").action(async (opts) => {
5649
- if (!this.configPath) this.terminateNotFound();
5650
- const basePath = opts.path ? path.default.join(this.cwd, opts.path) : this.cwd;
5651
- try {
5652
- var _this$config$seeders;
5653
- const { arquebus } = await new Migrate(basePath).setupConnection({
5654
- ...this.config,
5655
- skipConnection: false
5656
- });
5657
- const { SeederRunner } = await Promise.resolve().then(() => seeders_exports);
5658
- const runner = new SeederRunner(arquebus);
5659
- const seederPath = path.default.join(basePath, ((_this$config$seeders = this.config.seeders) === null || _this$config$seeders === void 0 ? void 0 : _this$config$seeders.path) ?? "./seeders");
5660
- await runner.setConnection(this.config.client).run([seederPath]);
5661
- this.output.success("Seeders executed successfully.");
5662
- } catch (e) {
5663
- this.output.error("ERROR: " + e);
5668
+ return await new _h3ravel_musket.Kernel(this).setCwd(this.cwd).setConfig({
5669
+ baseCommands: ArquebusCommands,
5670
+ name: "arquebus",
5671
+ hideMusketInfo: true,
5672
+ versionSeparator: "\n"
5673
+ }).setPackages([{
5674
+ name: "@h3ravel/arquebus",
5675
+ label: "Arquebus CLI",
5676
+ version,
5677
+ base: true
5678
+ }, {
5679
+ name: "@h3ravel/arquebus",
5680
+ label: "Arquebus ORM",
5681
+ version: this.modulePackage.version || "N/A"
5682
+ }]).bootstrap().run();
5683
+ }
5684
+ async initialize(type = "js") {
5685
+ if (!this.modulePath) this.output.error(["ERROR: No local arquebus install found", " Try running: pnpm add @h3ravel/arquebus"]);
5686
+ if (this.configPath) this.output.error(`ERROR: ${this.configPath} already exists`);
5687
+ try {
5688
+ const stubPath = `./arquebus.config.${type}`;
5689
+ const code = await (0, node_fs_promises.readFile)(await this.resolveStub(`arquebus.config-${type}.stub`), "utf8");
5690
+ await (0, node_fs_promises.writeFile)(node_path.default.join(this.cwd, stubPath), code);
5691
+ this.output.success(`Initialized: Arquebus has been initialized as ${stubPath}`);
5692
+ } catch (error) {
5693
+ this.output.error("ERROR: " + error);
5694
+ }
5695
+ }
5696
+ async makeMigration(rawName, options) {
5697
+ this.ensureConfigured();
5698
+ try {
5699
+ const name = _h3ravel_support.Str.snake(rawName);
5700
+ const migrationPath = node_path.default.join(this.cwd, options.path ?? this.config.migrations?.path ?? "./migrations");
5701
+ let table = options.table;
5702
+ let create = Boolean(options.create) && options.create !== "";
5703
+ if (!table && typeof options.create === "string") {
5704
+ table = options.create;
5705
+ create = true;
5664
5706
  }
5665
- });
5666
- /**
5667
- * Create a new seeder file
5668
- */
5669
- commander.program.command("make:seeder <name>").description("Create a new Seeder file.").addOption(new commander.Option("-l, --type [string]", "Type of seeder file to generate.").choices(["js", "ts"]).default("js", "generates a js seeder file")).option("--force", "Force creation if seeder already exists.", false).option("-p, --path [path]", "The path to the seeders directory.").action(async (name, opts) => {
5670
- var _this$config$seeders2;
5671
- if (!this.configPath) this.terminateNotFound();
5672
- const seederPath = path.default.join(this.cwd, opts.path ?? ((_this$config$seeders2 = this.config.seeders) === null || _this$config$seeders2 === void 0 ? void 0 : _this$config$seeders2.path) ?? "./seeders", _h3ravel_support.Str.of(name).snake("-") + "." + opts.type);
5673
- try {
5674
- if (!opts.force && await _h3ravel_shared.FileSystem.fileExists(seederPath)) this.output.error("ERROR: Seeder already exists.");
5675
- await (0, node_fs_promises.mkdir)(path.default.dirname(seederPath), { recursive: true });
5676
- let stub = await (0, node_fs_promises.readFile)(path.default.join(this.modulePath, `src/stubs/seeder-${opts.type}.stub`), "utf-8");
5677
- stub = stub.replace(/{{ name }}/g, name);
5678
- await (0, node_fs_promises.writeFile)(seederPath, stub);
5679
- this.output.split("INFO: Created Seeder", path.default.relative(this.cwd, seederPath));
5680
- } catch (e) {
5681
- this.output.error("ERROR: " + e);
5707
+ if (!table) {
5708
+ const guessed = TableGuesser.guess(name);
5709
+ table = guessed[0];
5710
+ create = Boolean(guessed[1]);
5682
5711
  }
5683
- });
5684
- /**
5685
- * Create a new model file
5686
- */
5687
- commander.program.command("make:model <name>").description("Create a new Model file.").addOption(new commander.Option("-l, --type [string]", "Type of migration file to generate.").choices(["js", "ts"]).default("js", "generates a js migration file")).option("--force", "Force creation if model already exists.", false).option("-p, --path [path]", "The path to the models directory.").action(async (name, opts) => {
5688
- var _this$config$models;
5689
- if (!this.configPath) this.terminateNotFound();
5690
- const modelPath = path.default.join(this.cwd, opts.path ?? ((_this$config$models = this.config.models) === null || _this$config$models === void 0 ? void 0 : _this$config$models.path) ?? "./models", name.toLowerCase() + "." + opts.type);
5691
- try {
5692
- if (!opts.force && await _h3ravel_shared.FileSystem.fileExists(modelPath)) this.output.error("ERROR: Model already exists.");
5693
- await (0, node_fs_promises.mkdir)(path.default.dirname(modelPath), { recursive: true });
5694
- let stub = await (0, node_fs_promises.readFile)(path.default.join(this.modulePath, `src/stubs/model-${opts.type}.stub`), "utf-8");
5695
- stub = stub.replace(/{{ name }}/g, name);
5696
- await (0, node_fs_promises.writeFile)(modelPath, stub);
5697
- this.output.success(`Created Model: ${modelPath}`);
5698
- } catch (e) {
5699
- this.output.error("ERROR: " + e);
5712
+ this.output.info("INFO: Creating Migration");
5713
+ const fileName = await new MigrationCreator(void 0, options.type ?? "js").create(name, migrationPath, table, create);
5714
+ this.output.success(`INFO: Migration Created \n ${_h3ravel_shared.Logger.log(node_path.default.basename(fileName), "gray", false)}`, true);
5715
+ } catch (error) {
5716
+ this.output.error("ERROR: " + error);
5717
+ }
5718
+ }
5719
+ async publishMigrations(pkg, options) {
5720
+ this.ensureConfigured();
5721
+ try {
5722
+ const packagePath = Utils.findModulePkg(pkg) ?? "";
5723
+ if (!packagePath) this.output.error(`ERROR: package ${pkg} not found`);
5724
+ const basePath = node_path.default.join(this.cwd, options.path ?? this.config.migrations?.path ?? "./migrations");
5725
+ const pkgJson = JSON.parse(await (0, node_fs_promises.readFile)(node_path.default.join(packagePath, "package.json"), "utf8"));
5726
+ const creator = new MigrationCreator(node_path.default.join(packagePath, pkgJson.migrations ?? "migrations"));
5727
+ const pkgInfo = _h3ravel_shared.Logger.log(node_path.default.basename(pkgJson.name + "@" + pkgJson.version), ["italic", "gray"], false);
5728
+ this.output.info(`INFO: Publishing migrations from ${pkgInfo}`);
5729
+ await creator.publish(basePath, (fileName) => {
5730
+ this.output.split("INFO: Migration Published", fileName, "success");
5731
+ });
5732
+ } catch (error) {
5733
+ this.output.error("ERROR: " + error);
5734
+ }
5735
+ }
5736
+ async migrate(options) {
5737
+ this.ensureConfigured();
5738
+ const basePath = this.resolveBasePath(options.path);
5739
+ try {
5740
+ const step = typeof options.step === "string" ? Number.parseInt(options.step) : options.step;
5741
+ await new Migrate(basePath).run(this.config, {
5742
+ ...options,
5743
+ step
5744
+ }, true);
5745
+ } catch (error) {
5746
+ this.output.error("ERROR: " + error);
5747
+ }
5748
+ }
5749
+ async rollback(options) {
5750
+ this.ensureConfigured();
5751
+ const basePath = this.resolveBasePath(options.path);
5752
+ try {
5753
+ const step = typeof options.step === "string" ? Number.parseInt(options.step) : options.step;
5754
+ await new Migrate(basePath, void 0, this.migrationReporter()).rollback(this.config, {
5755
+ ...options,
5756
+ step
5757
+ }, true);
5758
+ } catch (error) {
5759
+ this.output.error("ERROR: " + error);
5760
+ }
5761
+ }
5762
+ async reset(options) {
5763
+ await this.runMigrationOperation("reset", options);
5764
+ }
5765
+ async refresh(options) {
5766
+ await this.runMigrationOperation("refresh", options);
5767
+ }
5768
+ async fresh(options) {
5769
+ await this.runMigrationOperation("fresh", options);
5770
+ }
5771
+ async runMigrationOperation(operation, options) {
5772
+ this.ensureConfigured();
5773
+ const basePath = this.resolveBasePath(options.path);
5774
+ try {
5775
+ await new Migrate(basePath, void 0, this.migrationReporter())[operation](this.config, options, true);
5776
+ } catch (error) {
5777
+ this.output.error("ERROR: " + error);
5778
+ }
5779
+ }
5780
+ async status(options) {
5781
+ this.ensureConfigured();
5782
+ const basePath = this.resolveBasePath(options.path);
5783
+ try {
5784
+ const migrations = await new Migrate(basePath, void 0, this.migrationReporter()).status(this.config, options, true);
5785
+ if (migrations.length === 0) {
5786
+ this.output.info("No migrations found");
5787
+ return;
5700
5788
  }
5701
- });
5702
- await commander.program.parseAsync(process.argv);
5703
- process.exit(0);
5789
+ _h3ravel_shared.Logger.twoColumnDetail(_h3ravel_shared.Logger.log("Migration name", "gray", false), _h3ravel_shared.Logger.log("Batch / Status", "gray", false));
5790
+ migrations.forEach((migration) => {
5791
+ const status = migration.ran ? `[${migration.batch}] ${_h3ravel_shared.Logger.log("Ran", "green", false)}` : _h3ravel_shared.Logger.log("Pending", "yellow", false);
5792
+ _h3ravel_shared.Logger.twoColumnDetail(migration.name, status);
5793
+ });
5794
+ } catch (error) {
5795
+ this.output.error("ERROR: " + error);
5796
+ }
5797
+ }
5798
+ async seed(options) {
5799
+ this.ensureConfigured();
5800
+ const basePath = this.resolveBasePath(options.path);
5801
+ try {
5802
+ const { arquebus } = await new Migrate(basePath).setupConnection({
5803
+ ...this.config,
5804
+ skipConnection: false
5805
+ });
5806
+ const seederPath = node_path.default.join(basePath, this.config.seeders?.path ?? "./seeders");
5807
+ await new SeederRunner(arquebus).setConnection(this.config.client).run([seederPath]);
5808
+ this.output.success("Seeders executed successfully.");
5809
+ } catch (error) {
5810
+ this.output.error("ERROR: " + error);
5811
+ }
5812
+ }
5813
+ async makeSeeder(name, options) {
5814
+ this.ensureConfigured();
5815
+ const type = options.type ?? "js";
5816
+ const seederPath = node_path.default.join(this.cwd, options.path ?? this.config.seeders?.path ?? "./seeders", `${_h3ravel_support.Str.of(name).snake("-")}.${type}`);
5817
+ try {
5818
+ if (!options.force && await _h3ravel_shared.FileSystem.fileExists(seederPath)) this.output.error("ERROR: Seeder already exists.");
5819
+ await (0, node_fs_promises.mkdir)(node_path.default.dirname(seederPath), { recursive: true });
5820
+ await (0, node_fs_promises.writeFile)(seederPath, (await (0, node_fs_promises.readFile)(await this.resolveStub(`seeder-${type}.stub`), "utf8")).replace(/{{ name }}/g, name));
5821
+ this.output.split("INFO: Created Seeder", node_path.default.relative(this.cwd, seederPath));
5822
+ } catch (error) {
5823
+ this.output.error("ERROR: " + error);
5824
+ }
5825
+ }
5826
+ async makeModel(name, options) {
5827
+ this.ensureConfigured();
5828
+ const type = options.type ?? "js";
5829
+ const modelPath = node_path.default.join(this.cwd, options.path ?? this.config.models?.path ?? "./models", `${name.toLowerCase()}.${type}`);
5830
+ try {
5831
+ if (!options.force && await _h3ravel_shared.FileSystem.fileExists(modelPath)) this.output.error("ERROR: Model already exists.");
5832
+ await (0, node_fs_promises.mkdir)(node_path.default.dirname(modelPath), { recursive: true });
5833
+ await (0, node_fs_promises.writeFile)(modelPath, (await (0, node_fs_promises.readFile)(await this.resolveStub(`model-${type}.stub`), "utf8")).replace(/{{ name }}/g, name));
5834
+ this.output.success(`Created Model: ${modelPath}`);
5835
+ } catch (error) {
5836
+ this.output.error("ERROR: " + error);
5837
+ }
5704
5838
  }
5705
5839
  }).init();
5706
5840
  //#endregion