drizzle-kit 0.24.0 → 0.24.1-3d751e8

Sign up to get free protection for your applications and to get access to all the features.
package/bin.cjs CHANGED
@@ -5687,11 +5687,30 @@ var init_mysqlSchema = __esm({
5687
5687
  }
5688
5688
  });
5689
5689
 
5690
+ // src/extensions/vector.ts
5691
+ var vectorOps;
5692
+ var init_vector = __esm({
5693
+ "src/extensions/vector.ts"() {
5694
+ "use strict";
5695
+ vectorOps = [
5696
+ "vector_l2_ops",
5697
+ "vector_ip_ops",
5698
+ "vector_cosine_ops",
5699
+ "vector_l1_ops",
5700
+ "bit_hamming_ops",
5701
+ "bit_jaccard_ops",
5702
+ "halfvec_l2_ops",
5703
+ "sparsevec_l2_ops"
5704
+ ];
5705
+ }
5706
+ });
5707
+
5690
5708
  // src/serializer/pgSchema.ts
5691
5709
  var indexV2, columnV2, tableV2, enumSchemaV1, enumSchema, pgSchemaV2, references, columnV1, tableV1, pgSchemaV1, indexColumn, index2, indexV4, indexV5, indexV6, fk2, sequenceSchema, sequenceSquashed, columnV7, column2, columnSquashed, tableV32, compositePK2, uniqueConstraint2, tableV42, tableV5, tableV6, tableV7, table2, schemaHash2, kitInternals2, pgSchemaInternalV3, pgSchemaInternalV4, pgSchemaInternalV5, pgSchemaInternalV6, pgSchemaExternal, pgSchemaInternalV7, pgSchemaInternal, tableSquashed2, tableSquashedV42, pgSchemaSquashedV4, pgSchemaSquashedV6, pgSchemaSquashed, pgSchemaV3, pgSchemaV4, pgSchemaV5, pgSchemaV6, pgSchemaV7, pgSchema, backwardCompatiblePgSchema, PgSquasher, squashPgScheme, dryPg;
5692
5710
  var init_pgSchema = __esm({
5693
5711
  "src/serializer/pgSchema.ts"() {
5694
5712
  "use strict";
5713
+ init_vector();
5695
5714
  init_global();
5696
5715
  init_lib();
5697
5716
  indexV2 = objectType({
@@ -5938,7 +5957,8 @@ var init_pgSchema = __esm({
5938
5957
  objectType({
5939
5958
  isArray: booleanType().optional(),
5940
5959
  dimensions: numberType().optional(),
5941
- rawType: stringType().optional()
5960
+ rawType: stringType().optional(),
5961
+ isDefaultAnExpression: booleanType().optional()
5942
5962
  }).optional()
5943
5963
  )
5944
5964
  }).optional()
@@ -6076,7 +6096,7 @@ var init_pgSchema = __esm({
6076
6096
  squashIdx: (idx) => {
6077
6097
  index2.parse(idx);
6078
6098
  return `${idx.name};${idx.columns.map(
6079
- (c) => `${c.expression}--${c.isExpression}--${c.asc}--${c.nulls}--${c.opclass}`
6099
+ (c) => `${c.expression}--${c.isExpression}--${c.asc}--${c.nulls}--${c.opclass && vectorOps.includes(c.opclass) ? c.opclass : ""}`
6080
6100
  ).join(",,")};${idx.isUnique};${idx.concurrently};${idx.method};${idx.where};${JSON.stringify(idx.with)}`;
6081
6101
  },
6082
6102
  unsquashIdx: (input) => {
@@ -6564,7 +6584,7 @@ var init_sqliteSchema = __esm({
6564
6584
  function isPgArrayType(sqlType) {
6565
6585
  return sqlType.match(/.*\[\d*\].*|.*\[\].*/g) !== null;
6566
6586
  }
6567
- var import_fs, import_path, import_url, copy, objectValues, assertV1OutFolder, dryJournal, prepareOutFolder, validatorForDialect, validateWithReport, prepareMigrationFolder, prepareMigrationMeta, schemaRenameKey, tableRenameKey, columnRenameKey, normaliseSQLiteUrl;
6587
+ var import_fs, import_path, import_url, copy, objectValues, assertV1OutFolder, dryJournal, prepareOutFolder, validatorForDialect, validateWithReport, prepareMigrationFolder, prepareMigrationMeta, schemaRenameKey, tableRenameKey, columnRenameKey, normaliseSQLiteUrl, normalisePGliteUrl;
6568
6588
  var init_utils = __esm({
6569
6589
  "src/utils.ts"() {
6570
6590
  "use strict";
@@ -6761,6 +6781,12 @@ var init_utils = __esm({
6761
6781
  }
6762
6782
  assertUnreachable(type);
6763
6783
  };
6784
+ normalisePGliteUrl = (it) => {
6785
+ if (it.startsWith("file:")) {
6786
+ return it.substring(5);
6787
+ }
6788
+ return it;
6789
+ };
6764
6790
  }
6765
6791
  });
6766
6792
 
@@ -11215,7 +11241,7 @@ var init_outputs = __esm({
11215
11241
  });
11216
11242
 
11217
11243
  // src/cli/validations/common.ts
11218
- var assertCollisions, sqliteDriversLiterals, prefixes, prefix, sqliteDriver, postgresDriver, driver, configMigrations, configCommonSchema, casing, introspectParams, configIntrospectCliSchema, configGenerateSchema, configPushSchema, drivers, wrapParam;
11244
+ var assertCollisions, sqliteDriversLiterals, postgresqlDriversLiterals, prefixes, prefix, sqliteDriver, postgresDriver, driver, configMigrations, configCommonSchema, casing, introspectParams, configIntrospectCliSchema, configGenerateSchema, configPushSchema, drivers, wrapParam;
11219
11245
  var init_common = __esm({
11220
11246
  "src/cli/validations/common.ts"() {
11221
11247
  "use strict";
@@ -11245,6 +11271,10 @@ var init_common = __esm({
11245
11271
  literalType("d1-http"),
11246
11272
  literalType("expo")
11247
11273
  ];
11274
+ postgresqlDriversLiterals = [
11275
+ literalType("aws-data-api"),
11276
+ literalType("pglite")
11277
+ ];
11248
11278
  prefixes = [
11249
11279
  "index",
11250
11280
  "timestamp",
@@ -11257,7 +11287,7 @@ var init_common = __esm({
11257
11287
  const _2 = "";
11258
11288
  }
11259
11289
  sqliteDriver = unionType(sqliteDriversLiterals);
11260
- postgresDriver = literalType("aws-data-api");
11290
+ postgresDriver = unionType(postgresqlDriversLiterals);
11261
11291
  driver = unionType([sqliteDriver, postgresDriver]);
11262
11292
  configMigrations = objectType({
11263
11293
  table: stringType().optional(),
@@ -11313,7 +11343,7 @@ var init_common = __esm({
11313
11343
  strict: booleanType().default(false),
11314
11344
  out: stringType().optional()
11315
11345
  });
11316
- drivers = ["turso", "d1-http", "expo", "aws-data-api"];
11346
+ drivers = ["turso", "d1-http", "expo", "aws-data-api", "pglite"];
11317
11347
  wrapParam = (name, param, optional = false, type) => {
11318
11348
  const check2 = `[${source_default.green("\u2713")}]`;
11319
11349
  const cross = `[${source_default.red("x")}]`;
@@ -11370,9 +11400,9 @@ var init_cli = __esm({
11370
11400
  tablesFilter: unionType([stringType(), stringType().array()]).optional(),
11371
11401
  schemaFilter: unionType([stringType(), stringType().array()]).optional().default(["public"]),
11372
11402
  extensionsFilters: literalType("postgis").array().optional(),
11373
- introspectCasing: casing,
11403
+ casing,
11374
11404
  breakpoints: booleanType().optional().default(true),
11375
- database: objectType({
11405
+ migrations: objectType({
11376
11406
  prefix: prefix.optional().default("index")
11377
11407
  }).optional()
11378
11408
  }).passthrough();
@@ -11485,6 +11515,10 @@ var init_postgres = __esm({
11485
11515
  database: stringType().min(1),
11486
11516
  secretArn: stringType().min(1),
11487
11517
  resourceArn: stringType().min(1)
11518
+ }),
11519
+ objectType({
11520
+ driver: literalType("pglite"),
11521
+ url: stringType().min(1)
11488
11522
  })
11489
11523
  ]);
11490
11524
  printConfigConnectionIssues2 = (options) => {
@@ -17506,11 +17540,11 @@ var init_utils4 = __esm({
17506
17540
  dialect: "postgresql",
17507
17541
  out: config.out,
17508
17542
  breakpoints: config.breakpoints,
17509
- casing: config.introspectCasing,
17543
+ casing: config.casing,
17510
17544
  credentials: parsed2.data,
17511
17545
  tablesFilter,
17512
17546
  schemasFilter,
17513
- prefix: ((_a = config.database) == null ? void 0 : _a.prefix) || "index"
17547
+ prefix: ((_a = config.migrations) == null ? void 0 : _a.prefix) || "index"
17514
17548
  };
17515
17549
  }
17516
17550
  if (dialect7 === "mysql") {
@@ -17523,11 +17557,11 @@ var init_utils4 = __esm({
17523
17557
  dialect: "mysql",
17524
17558
  out: config.out,
17525
17559
  breakpoints: config.breakpoints,
17526
- casing: config.introspectCasing,
17560
+ casing: config.casing,
17527
17561
  credentials: parsed2.data,
17528
17562
  tablesFilter,
17529
17563
  schemasFilter,
17530
- prefix: ((_b = config.database) == null ? void 0 : _b.prefix) || "index"
17564
+ prefix: ((_b = config.migrations) == null ? void 0 : _b.prefix) || "index"
17531
17565
  };
17532
17566
  }
17533
17567
  if (dialect7 === "sqlite") {
@@ -17540,11 +17574,11 @@ var init_utils4 = __esm({
17540
17574
  dialect: "sqlite",
17541
17575
  out: config.out,
17542
17576
  breakpoints: config.breakpoints,
17543
- casing: config.introspectCasing,
17577
+ casing: config.casing,
17544
17578
  credentials: parsed2.data,
17545
17579
  tablesFilter,
17546
17580
  schemasFilter,
17547
- prefix: ((_c = config.database) == null ? void 0 : _c.prefix) || "index"
17581
+ prefix: ((_c = config.migrations) == null ? void 0 : _c.prefix) || "index"
17548
17582
  };
17549
17583
  }
17550
17584
  assertUnreachable(dialect7);
@@ -18372,24 +18406,6 @@ var init_pgImports = __esm({
18372
18406
  }
18373
18407
  });
18374
18408
 
18375
- // src/extensions/vector.ts
18376
- var vectorOps;
18377
- var init_vector = __esm({
18378
- "src/extensions/vector.ts"() {
18379
- "use strict";
18380
- vectorOps = [
18381
- "vector_l2_ops",
18382
- "vector_ip_ops",
18383
- "vector_cosine_ops",
18384
- "vector_l1_ops",
18385
- "bit_hamming_ops",
18386
- "bit_jaccard_ops",
18387
- "halfvec_l2_ops",
18388
- "sparsevec_l2_ops"
18389
- ];
18390
- }
18391
- });
18392
-
18393
18409
  // src/serializer/pgSerializer.ts
18394
18410
  var pgSerializer_exports = {};
18395
18411
  __export(pgSerializer_exports, {
@@ -18433,7 +18449,7 @@ function buildArrayString(array, sqlType) {
18433
18449
  }).join(",");
18434
18450
  return `{${values}}`;
18435
18451
  }
18436
- var import_drizzle_orm5, import_pg_core2, import_pg_core3, dialect5, indexName2, generatePgSnapshot, trimChar, fromDatabase2, columnToDefault, defaultForColumn;
18452
+ var import_drizzle_orm5, import_pg_core2, import_pg_core3, dialect5, indexName2, generatePgSnapshot, trimChar, fromDatabase2, defaultForColumn;
18437
18453
  var init_pgSerializer = __esm({
18438
18454
  "src/serializer/pgSerializer.ts"() {
18439
18455
  "use strict";
@@ -18556,7 +18572,7 @@ ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${so
18556
18572
  columnToSet.default = `'${buildArrayString(
18557
18573
  column7.default,
18558
18574
  sqlTypeLowered
18559
- )}'::${sqlTypeLowered}`;
18575
+ )}'`;
18560
18576
  } else {
18561
18577
  columnToSet.default = column7.default;
18562
18578
  }
@@ -18877,7 +18893,7 @@ ${withStyle.errorWarning(
18877
18893
  const sequencesInColumns = [];
18878
18894
  const all = allTables.map((row) => {
18879
18895
  return new Promise(async (res, rej) => {
18880
- var _a, _b, _c, _d;
18896
+ var _a, _b, _c, _d, _e, _f;
18881
18897
  const tableName = row.table_name;
18882
18898
  if (!tablesFilter(tableName))
18883
18899
  return res("");
@@ -18908,7 +18924,7 @@ ${withStyle.errorWarning(
18908
18924
  WHEN 'int2'::regtype THEN 'smallserial'
18909
18925
  END
18910
18926
  ELSE format_type(a.atttypid, a.atttypmod)
18911
- END AS data_type, INFORMATION_SCHEMA.COLUMNS.table_name,
18927
+ END AS data_type, INFORMATION_SCHEMA.COLUMNS.table_name, ns.nspname as type_schema,
18912
18928
  pg_get_serial_sequence('"${tableSchema}"."${tableName}"', a.attname)::regclass as seq_name, INFORMATION_SCHEMA.COLUMNS.column_name,
18913
18929
  INFORMATION_SCHEMA.COLUMNS.column_default, INFORMATION_SCHEMA.COLUMNS.data_type as additional_dt,
18914
18930
  INFORMATION_SCHEMA.COLUMNS.udt_name as enum_name,
@@ -18919,6 +18935,7 @@ ${withStyle.errorWarning(
18919
18935
  INFORMATION_SCHEMA.COLUMNS.identity_cycle
18920
18936
  FROM pg_attribute a
18921
18937
  JOIN INFORMATION_SCHEMA.COLUMNS ON INFORMATION_SCHEMA.COLUMNS.column_name = a.attname
18938
+ JOIN pg_type t ON t.oid = a.atttypid LEFT JOIN pg_namespace ns ON ns.oid = t.typnamespace
18922
18939
  WHERE a.attrelid = '"${tableSchema}"."${tableName}"'::regclass and INFORMATION_SCHEMA.COLUMNS.table_name = '${tableName}' and INFORMATION_SCHEMA.COLUMNS.table_schema = '${tableSchema}'
18923
18940
  AND a.attnum > 0
18924
18941
  AND NOT a.attisdropped
@@ -18938,30 +18955,42 @@ ${withStyle.errorWarning(
18938
18955
  }
18939
18956
  const tableForeignKeys = await db.query(
18940
18957
  `SELECT
18941
- tc.table_schema,
18942
- tc.constraint_name,
18943
- tc.table_name,
18944
- kcu.column_name,
18945
- (
18946
- SELECT ccu.table_schema
18947
- FROM information_schema.constraint_column_usage ccu
18948
- WHERE ccu.constraint_name = tc.constraint_name
18949
- LIMIT 1
18950
- ) AS foreign_table_schema,
18951
- ccu.table_name AS foreign_table_name,
18952
- ccu.column_name AS foreign_column_name,
18953
- rc.delete_rule,
18954
- rc.update_rule
18955
- FROM
18956
- information_schema.table_constraints AS tc
18957
- JOIN information_schema.key_column_usage AS kcu
18958
- ON tc.constraint_name = kcu.constraint_name
18959
- AND tc.table_schema = kcu.table_schema
18960
- JOIN information_schema.constraint_column_usage AS ccu
18961
- ON ccu.constraint_name = tc.constraint_name
18962
- JOIN information_schema.referential_constraints AS rc
18963
- ON ccu.constraint_name = rc.constraint_name
18964
- WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name='${tableName}' and tc.table_schema='${tableSchema}';`
18958
+ con.contype AS constraint_type,
18959
+ nsp.nspname AS constraint_schema,
18960
+ con.conname AS constraint_name,
18961
+ rel.relname AS table_name,
18962
+ att.attname AS column_name,
18963
+ fnsp.nspname AS foreign_table_schema,
18964
+ frel.relname AS foreign_table_name,
18965
+ fatt.attname AS foreign_column_name,
18966
+ CASE con.confupdtype
18967
+ WHEN 'a' THEN 'NO ACTION'
18968
+ WHEN 'r' THEN 'RESTRICT'
18969
+ WHEN 'n' THEN 'SET NULL'
18970
+ WHEN 'c' THEN 'CASCADE'
18971
+ WHEN 'd' THEN 'SET DEFAULT'
18972
+ END AS update_rule,
18973
+ CASE con.confdeltype
18974
+ WHEN 'a' THEN 'NO ACTION'
18975
+ WHEN 'r' THEN 'RESTRICT'
18976
+ WHEN 'n' THEN 'SET NULL'
18977
+ WHEN 'c' THEN 'CASCADE'
18978
+ WHEN 'd' THEN 'SET DEFAULT'
18979
+ END AS delete_rule
18980
+ FROM
18981
+ pg_catalog.pg_constraint con
18982
+ JOIN pg_catalog.pg_class rel ON rel.oid = con.conrelid
18983
+ JOIN pg_catalog.pg_namespace nsp ON nsp.oid = con.connamespace
18984
+ LEFT JOIN pg_catalog.pg_attribute att ON att.attnum = ANY (con.conkey)
18985
+ AND att.attrelid = con.conrelid
18986
+ LEFT JOIN pg_catalog.pg_class frel ON frel.oid = con.confrelid
18987
+ LEFT JOIN pg_catalog.pg_namespace fnsp ON fnsp.oid = frel.relnamespace
18988
+ LEFT JOIN pg_catalog.pg_attribute fatt ON fatt.attnum = ANY (con.confkey)
18989
+ AND fatt.attrelid = con.confrelid
18990
+ WHERE
18991
+ nsp.nspname = '${tableSchema}'
18992
+ AND rel.relname = '${tableName}'
18993
+ AND con.contype IN ('f');`
18965
18994
  );
18966
18995
  foreignKeysCount += tableForeignKeys.length;
18967
18996
  if (progressCallback) {
@@ -18973,8 +19002,8 @@ ${withStyle.errorWarning(
18973
19002
  const columnTo = fk4.foreign_column_name;
18974
19003
  const schemaTo = fk4.foreign_table_schema;
18975
19004
  const foreignKeyName = fk4.constraint_name;
18976
- const onUpdate = fk4.update_rule.toLowerCase();
18977
- const onDelete = fk4.delete_rule.toLowerCase();
19005
+ const onUpdate = (_a = fk4.update_rule) == null ? void 0 : _a.toLowerCase();
19006
+ const onDelete = (_b = fk4.delete_rule) == null ? void 0 : _b.toLowerCase();
18978
19007
  if (typeof foreignKeysToReturn[foreignKeyName] !== "undefined") {
18979
19008
  foreignKeysToReturn[foreignKeyName].columnsFrom.push(columnFrom);
18980
19009
  foreignKeysToReturn[foreignKeyName].columnsTo.push(columnTo);
@@ -19019,6 +19048,8 @@ ${withStyle.errorWarning(
19019
19048
  const columnDimensions = columnResponse.array_dimensions;
19020
19049
  const enumType2 = columnResponse.enum_name;
19021
19050
  let columnType = columnResponse.data_type;
19051
+ const typeSchema = columnResponse.type_schema;
19052
+ const defaultValueRes = columnResponse.column_default;
19022
19053
  const isGenerated = columnResponse.is_generated === "ALWAYS";
19023
19054
  const generationExpression = columnResponse.generation_expression;
19024
19055
  const isIdentity = columnResponse.is_identity === "YES";
@@ -19049,12 +19080,7 @@ ${withStyle.errorWarning(
19049
19080
  columns: cprimaryKey.map((c) => c.column_name)
19050
19081
  };
19051
19082
  }
19052
- const defaultValue = defaultForColumn(columnResponse);
19053
- const isSerial = columnType === "serial";
19054
19083
  let columnTypeMapped = columnType;
19055
- if (columnTypeMapped.startsWith("numeric(")) {
19056
- columnTypeMapped = columnTypeMapped.replace(",", ", ");
19057
- }
19058
19084
  if (columnAdditionalDT === "ARRAY") {
19059
19085
  if (typeof internals.tables[tableName] === "undefined") {
19060
19086
  internals.tables[tableName] = {
@@ -19082,6 +19108,34 @@ ${withStyle.errorWarning(
19082
19108
  }
19083
19109
  }
19084
19110
  }
19111
+ const defaultValue = defaultForColumn(
19112
+ columnResponse,
19113
+ internals,
19114
+ tableName
19115
+ );
19116
+ if (defaultValue === "NULL" || defaultValueRes && defaultValueRes.startsWith("(") && defaultValueRes.endsWith(")")) {
19117
+ if (typeof internals.tables[tableName] === "undefined") {
19118
+ internals.tables[tableName] = {
19119
+ columns: {
19120
+ [columnName]: {
19121
+ isDefaultAnExpression: true
19122
+ }
19123
+ }
19124
+ };
19125
+ } else {
19126
+ if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
19127
+ internals.tables[tableName].columns[columnName] = {
19128
+ isDefaultAnExpression: true
19129
+ };
19130
+ } else {
19131
+ internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
19132
+ }
19133
+ }
19134
+ }
19135
+ const isSerial = columnType === "serial";
19136
+ if (columnTypeMapped.startsWith("numeric(")) {
19137
+ columnTypeMapped = columnTypeMapped.replace(",", ", ");
19138
+ }
19085
19139
  if (columnAdditionalDT === "ARRAY") {
19086
19140
  for (let i2 = 1; i2 < Number(columnDimensions); i2++) {
19087
19141
  columnTypeMapped += "[]";
@@ -19095,7 +19149,7 @@ ${withStyle.errorWarning(
19095
19149
  // filter vectors, but in future we should filter any extension that was installed by user
19096
19150
  columnAdditionalDT === "USER-DEFINED" && !["vector", "geometry"].includes(enumType2) ? enumType2 : columnTypeMapped
19097
19151
  ),
19098
- typeSchema: enumsToReturn[`${tableSchema}.${enumType2}`] !== void 0 ? enumsToReturn[`${tableSchema}.${enumType2}`].schema : void 0,
19152
+ typeSchema: enumsToReturn[`${typeSchema}.${enumType2}`] !== void 0 ? enumsToReturn[`${typeSchema}.${enumType2}`].schema : void 0,
19099
19153
  primaryKey: primaryKey.length === 1 && cprimaryKey.length < 2,
19100
19154
  // default: isSerial ? undefined : defaultValue,
19101
19155
  notNull: columnResponse.is_nullable === "NO",
@@ -19107,13 +19161,13 @@ ${withStyle.errorWarning(
19107
19161
  minValue: stringFromDatabaseIdentityProperty(identityMinimum),
19108
19162
  maxValue: stringFromDatabaseIdentityProperty(identityMaximum),
19109
19163
  startWith: stringFromDatabaseIdentityProperty(identityStart),
19110
- cache: ((_a = sequencesToReturn[identityName]) == null ? void 0 : _a.cache) ? (_b = sequencesToReturn[identityName]) == null ? void 0 : _b.cache : ((_c = sequencesToReturn[`${tableSchema}.${identityName}`]) == null ? void 0 : _c.cache) ? (_d = sequencesToReturn[`${tableSchema}.${identityName}`]) == null ? void 0 : _d.cache : void 0,
19164
+ cache: ((_c = sequencesToReturn[identityName]) == null ? void 0 : _c.cache) ? (_d = sequencesToReturn[identityName]) == null ? void 0 : _d.cache : ((_e = sequencesToReturn[`${tableSchema}.${identityName}`]) == null ? void 0 : _e.cache) ? (_f = sequencesToReturn[`${tableSchema}.${identityName}`]) == null ? void 0 : _f.cache : void 0,
19111
19165
  cycle: identityCycle,
19112
19166
  schema: tableSchema
19113
19167
  } : void 0
19114
19168
  };
19115
19169
  if (identityName) {
19116
- delete sequencesToReturn[`${tableSchema}.${identityName}`];
19170
+ delete sequencesToReturn[`${tableSchema}.${identityName.startsWith('"') && identityName.endsWith('"') ? identityName.slice(1, -1) : identityName}`];
19117
19171
  delete sequencesToReturn[identityName];
19118
19172
  }
19119
19173
  if (!isSerial && typeof defaultValue !== "undefined") {
@@ -19267,59 +19321,72 @@ ${withStyle.errorWarning(
19267
19321
  internal: internals
19268
19322
  };
19269
19323
  };
19270
- columnToDefault = {
19271
- "numeric(": "::numeric",
19272
- // text: "::text",
19273
- // "character varying": "::character varying",
19274
- // "double precision": "::double precision",
19275
- // "time with time zone": "::time with time zone",
19276
- "time without time zone": "::time without time zone",
19277
- // "timestamp with time zone": "::timestamp with time zone",
19278
- "timestamp without time zone": "::timestamp without time zone",
19279
- "timestamp(": "::timestamp without time zone",
19280
- // date: "::date",
19281
- // interval: "::interval",
19282
- // character: "::bpchar",
19283
- // macaddr8: "::macaddr8",
19284
- // macaddr: "::macaddr",
19285
- // inet: "::inet",
19286
- // cidr: "::cidr",
19287
- // jsonb: "::jsonb",
19288
- // json: "::json",
19289
- "character(": "::bpchar"
19290
- };
19291
- defaultForColumn = (column7) => {
19324
+ defaultForColumn = (column7, internals, tableName) => {
19325
+ var _a, _b;
19326
+ const columnName = column7.attname;
19327
+ const isArray3 = ((_b = (_a = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a.columns[columnName]) == null ? void 0 : _b.isArray) ?? false;
19292
19328
  if (column7.column_default === null) {
19293
19329
  return void 0;
19294
19330
  }
19295
19331
  if (column7.data_type === "serial" || column7.data_type === "smallserial" || column7.data_type === "bigserial") {
19296
19332
  return void 0;
19297
19333
  }
19298
- const hasDifferentDefaultCast = Object.keys(columnToDefault).find((it) => column7.data_type.startsWith(it));
19334
+ if (column7.column_default.endsWith("[]")) {
19335
+ column7.column_default = column7.column_default.slice(0, -2);
19336
+ }
19337
+ column7.column_default = column7.column_default.replace(/::(.*?)(?<![^\w"])(?=$)/, "");
19299
19338
  const columnDefaultAsString = column7.column_default.toString();
19300
- if (columnDefaultAsString.endsWith(
19301
- hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : column7.data_type
19302
- )) {
19303
- const nonPrefixPart = column7.column_default.length - (hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : `::${column7.data_type}`).length - 1;
19304
- const rt = column7.column_default.toString().substring(1, nonPrefixPart);
19305
- if (/^-?[\d.]+(?:e-?\d+)?$/.test(rt) && !column7.data_type.startsWith("numeric")) {
19306
- return Number(rt);
19307
- } else if (column7.data_type === "json" || column7.data_type === "jsonb") {
19308
- const jsonWithoutSpaces = JSON.stringify(JSON.parse(rt));
19309
- return `'${jsonWithoutSpaces}'${hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : `::${column7.data_type}`}`;
19310
- } else if (column7.data_type === "boolean") {
19311
- return column7.column_default === "true";
19312
- } else {
19313
- return `'${rt}'`;
19314
- }
19315
- } else {
19316
- if (/^-?[\d.]+(?:e-?\d+)?$/.test(columnDefaultAsString) && !column7.data_type.startsWith("numeric")) {
19339
+ if (isArray3) {
19340
+ return `'{${columnDefaultAsString.slice(2, -2).split(/\s*,\s*/g).map((value) => {
19341
+ if (["integer", "smallint", "bigint", "double precision", "real"].includes(column7.data_type.slice(0, -2))) {
19342
+ return value;
19343
+ } else if (column7.data_type.startsWith("timestamp")) {
19344
+ return `${value}`;
19345
+ } else if (column7.data_type.slice(0, -2) === "interval") {
19346
+ return value.replaceAll('"', `"`);
19347
+ } else if (column7.data_type.slice(0, -2) === "boolean") {
19348
+ return value === "t" ? "true" : "false";
19349
+ } else if (["json", "jsonb"].includes(column7.data_type.slice(0, -2))) {
19350
+ return JSON.stringify(JSON.stringify(JSON.parse(JSON.parse(value)), null, 0));
19351
+ } else {
19352
+ return `"${value}"`;
19353
+ }
19354
+ }).join(",")}}'`;
19355
+ }
19356
+ if (["integer", "smallint", "bigint", "double precision", "real"].includes(column7.data_type)) {
19357
+ if (/^-?[\d.]+(?:e-?\d+)?$/.test(columnDefaultAsString)) {
19317
19358
  return Number(columnDefaultAsString);
19318
- } else if (column7.data_type === "boolean") {
19319
- return column7.column_default === "true";
19320
19359
  } else {
19321
- return `${columnDefaultAsString}`;
19360
+ if (typeof internals.tables[tableName] === "undefined") {
19361
+ internals.tables[tableName] = {
19362
+ columns: {
19363
+ [columnName]: {
19364
+ isDefaultAnExpression: true
19365
+ }
19366
+ }
19367
+ };
19368
+ } else {
19369
+ if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
19370
+ internals.tables[tableName].columns[columnName] = {
19371
+ isDefaultAnExpression: true
19372
+ };
19373
+ } else {
19374
+ internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
19375
+ }
19376
+ }
19377
+ return columnDefaultAsString;
19322
19378
  }
19379
+ } else if (column7.data_type === "json" || column7.data_type === "jsonb") {
19380
+ const jsonWithoutSpaces = JSON.stringify(JSON.parse(columnDefaultAsString.slice(1, -1)));
19381
+ return `'${jsonWithoutSpaces}'::${column7.data_type}`;
19382
+ } else if (column7.data_type === "boolean") {
19383
+ return column7.column_default === "true";
19384
+ } else if (columnDefaultAsString === "NULL") {
19385
+ return `NULL`;
19386
+ } else if (columnDefaultAsString.startsWith("'") && columnDefaultAsString.endsWith("'")) {
19387
+ return columnDefaultAsString;
19388
+ } else {
19389
+ return `${columnDefaultAsString.replace(/\\/g, "`\\")}`;
19323
19390
  }
19324
19391
  };
19325
19392
  }
@@ -22905,7 +22972,7 @@ var init_sqlgenerator = __esm({
22905
22972
  if (pgNativeTypes.has(it))
22906
22973
  return true;
22907
22974
  const toCheck = it.replace(/ /g, "");
22908
- return toCheck.startsWith("varchar(") || toCheck.startsWith("char(") || toCheck.startsWith("numeric(") || toCheck.startsWith("timestamp(") || toCheck.startsWith("intervalyear(") || toCheck.startsWith("intervalmonth(") || toCheck.startsWith("intervalday(") || toCheck.startsWith("intervalhour(") || toCheck.startsWith("intervalminute(") || toCheck.startsWith("intervalsecond(") || toCheck.startsWith("intervalyeartomonth(") || toCheck.startsWith("intervaldaytohour(") || toCheck.startsWith("intervaldaytominute(") || toCheck.startsWith("intervaldaytosecond(") || toCheck.startsWith("intervalhourtominute(") || toCheck.startsWith("intervalhourtosecond(") || toCheck.startsWith("intervalminutetosecond(") || toCheck.startsWith("vector(") || toCheck.startsWith("geometry(") || /^(\w+)(\[\d*])+$/.test(it);
22975
+ return toCheck.startsWith("varchar(") || toCheck.startsWith("char(") || toCheck.startsWith("numeric(") || toCheck.startsWith("timestamp(") || toCheck.startsWith("doubleprecision[") || toCheck.startsWith("intervalyear(") || toCheck.startsWith("intervalmonth(") || toCheck.startsWith("intervalday(") || toCheck.startsWith("intervalhour(") || toCheck.startsWith("intervalminute(") || toCheck.startsWith("intervalsecond(") || toCheck.startsWith("intervalyeartomonth(") || toCheck.startsWith("intervaldaytohour(") || toCheck.startsWith("intervaldaytominute(") || toCheck.startsWith("intervaldaytosecond(") || toCheck.startsWith("intervalhourtominute(") || toCheck.startsWith("intervalhourtosecond(") || toCheck.startsWith("intervalminutetosecond(") || toCheck.startsWith("vector(") || toCheck.startsWith("geometry(") || /^(\w+)(\[\d*])+$/.test(it);
22909
22976
  };
22910
22977
  Convertor = class {
22911
22978
  };
@@ -71698,7 +71765,7 @@ __export(connections_exports, {
71698
71765
  connectToSQLite: () => connectToSQLite,
71699
71766
  preparePostgresDB: () => preparePostgresDB
71700
71767
  });
71701
- var preparePostgresDB, parseMysqlCredentials, connectToMySQL, prepareSqliteParams, connectToSQLite;
71768
+ var preparePostgresDB, parseMysqlCredentials, connectToMySQL, prepareSqliteParams, preparePGliteParams, connectToSQLite;
71702
71769
  var init_connections = __esm({
71703
71770
  "src/cli/connections.ts"() {
71704
71771
  "use strict";
@@ -71710,7 +71777,8 @@ var init_connections = __esm({
71710
71777
  init_outputs();
71711
71778
  preparePostgresDB = async (credentials2) => {
71712
71779
  if ("driver" in credentials2) {
71713
- if (credentials2.driver === "aws-data-api") {
71780
+ const { driver: driver2 } = credentials2;
71781
+ if (driver2 === "aws-data-api") {
71714
71782
  assertPackages("@aws-sdk/client-rds-data");
71715
71783
  const { RDSDataClient, ExecuteStatementCommand, TypeHint } = await Promise.resolve().then(() => __toESM(require_dist_cjs55()));
71716
71784
  const { AwsDataApiSession, drizzle } = await import("drizzle-orm/aws-data-api/pg");
@@ -71767,7 +71835,35 @@ var init_connections = __esm({
71767
71835
  migrate: migrateFn
71768
71836
  };
71769
71837
  }
71770
- assertUnreachable(credentials2.driver);
71838
+ if (driver2 === "pglite") {
71839
+ assertPackages("@electric-sql/pglite");
71840
+ const { PGlite } = await import("@electric-sql/pglite");
71841
+ const { drizzle } = await import("drizzle-orm/pglite");
71842
+ const { migrate: migrate2 } = await import("drizzle-orm/pglite/migrator");
71843
+ const pglite = new PGlite(normalisePGliteUrl(credentials2.url));
71844
+ await pglite.waitReady;
71845
+ const drzl = drizzle(pglite);
71846
+ const migrateFn = async (config) => {
71847
+ return migrate2(drzl, config);
71848
+ };
71849
+ const query = async (sql, params = []) => {
71850
+ const result = await pglite.query(sql, params);
71851
+ return result.rows;
71852
+ };
71853
+ const proxy = async (params) => {
71854
+ const preparedParams = preparePGliteParams(params.params);
71855
+ if (params.method === "values" || params.method === "get" || params.method === "all") {
71856
+ const result2 = await pglite.query(params.sql, preparedParams, {
71857
+ rowMode: params.mode
71858
+ });
71859
+ return result2.rows;
71860
+ }
71861
+ const result = await pglite.query(params.sql, preparedParams);
71862
+ return result.rows;
71863
+ };
71864
+ return { query, proxy, migrate: migrateFn };
71865
+ }
71866
+ assertUnreachable(driver2);
71771
71867
  }
71772
71868
  if (await checkPackage("pg")) {
71773
71869
  console.log(withStyle.info(`Using 'pg' driver for database querying`));
@@ -71985,6 +72081,15 @@ var init_connections = __esm({
71985
72081
  return param;
71986
72082
  });
71987
72083
  };
72084
+ preparePGliteParams = (params) => {
72085
+ return params.map((param) => {
72086
+ if (param && typeof param === "object" && "type" in param && "value" in param && param.type === "binary") {
72087
+ const value = typeof param.value === "object" ? JSON.stringify(param.value) : param.value;
72088
+ return value;
72089
+ }
72090
+ return param;
72091
+ });
72092
+ };
71988
72093
  connectToSQLite = async (credentials2) => {
71989
72094
  if ("driver" in credentials2) {
71990
72095
  const { driver: driver2 } = credentials2;
@@ -74154,7 +74259,7 @@ var init_pgIntrospect = __esm({
74154
74259
  });
74155
74260
 
74156
74261
  // src/introspect-sqlite.ts
74157
- var sqliteImportsList, indexName3, objToStatement2, relations, withCasing, schemaToTypeScript, isCyclic, isSelf, mapColumnDefault, column4, createTableColumns, createTableIndexes, createTableUniques, createTablePKs, createTableFKs;
74262
+ var sqliteImportsList, indexName3, objToStatement2, relations, escapeColumnKey, withCasing, schemaToTypeScript, isCyclic, isSelf, mapColumnDefault, column4, createTableColumns, createTableIndexes, createTableUniques, createTablePKs, createTableFKs;
74158
74263
  var init_introspect_sqlite = __esm({
74159
74264
  "src/introspect-sqlite.ts"() {
74160
74265
  "use strict";
@@ -74181,12 +74286,18 @@ var init_introspect_sqlite = __esm({
74181
74286
  return statement;
74182
74287
  };
74183
74288
  relations = /* @__PURE__ */ new Set();
74289
+ escapeColumnKey = (value) => {
74290
+ if (/^(?![a-zA-Z_$][a-zA-Z0-9_$]*$).+$/.test(value)) {
74291
+ return `"${value}"`;
74292
+ }
74293
+ return value;
74294
+ };
74184
74295
  withCasing = (value, casing2) => {
74185
- if (typeof casing2 === "undefined") {
74186
- return value;
74296
+ if (casing2 === "preserve") {
74297
+ return escapeColumnKey(value);
74187
74298
  }
74188
74299
  if (casing2 === "camel") {
74189
- return value.camelCase();
74300
+ return escapeColumnKey(value.camelCase());
74190
74301
  }
74191
74302
  return value;
74192
74303
  };
@@ -75184,7 +75295,7 @@ var require_pluralize = __commonJS({
75184
75295
  });
75185
75296
 
75186
75297
  // src/introspect-mysql.ts
75187
- var mysqlImportsList, objToStatement22, timeConfig, binaryConfig, importsPatch, relations2, prepareCasing, schemaToTypeScript2, isCyclic2, isSelf2, mapColumnDefault2, mapColumnDefaultForJson, column5, createTableColumns2, createTableIndexes2, createTableUniques2, createTablePKs2, createTableFKs2;
75298
+ var mysqlImportsList, objToStatement22, timeConfig, binaryConfig, importsPatch, relations2, escapeColumnKey2, prepareCasing, schemaToTypeScript2, isCyclic2, isSelf2, mapColumnDefault2, mapColumnDefaultForJson, column5, createTableColumns2, createTableIndexes2, createTableUniques2, createTablePKs2, createTableFKs2;
75188
75299
  var init_introspect_mysql = __esm({
75189
75300
  "src/introspect-mysql.ts"() {
75190
75301
  "use strict";
@@ -75255,14 +75366,20 @@ var init_introspect_mysql = __esm({
75255
75366
  "timestamp without time zone": "timestamp"
75256
75367
  };
75257
75368
  relations2 = /* @__PURE__ */ new Set();
75369
+ escapeColumnKey2 = (value) => {
75370
+ if (/^(?![a-zA-Z_$][a-zA-Z0-9_$]*$).+$/.test(value)) {
75371
+ return `"${value}"`;
75372
+ }
75373
+ return value;
75374
+ };
75258
75375
  prepareCasing = (casing2) => (value) => {
75259
- if (typeof casing2 === "undefined") {
75260
- return value;
75376
+ if (casing2 === "preserve") {
75377
+ return escapeColumnKey2(value);
75261
75378
  }
75262
75379
  if (casing2 === "camel") {
75263
- return value.camelCase();
75380
+ return escapeColumnKey2(value.camelCase());
75264
75381
  }
75265
- return value;
75382
+ return escapeColumnKey2(value);
75266
75383
  };
75267
75384
  schemaToTypeScript2 = (schema5, casing2) => {
75268
75385
  const withCasing4 = prepareCasing(casing2);
@@ -75728,7 +75845,33 @@ import { sql } from "drizzle-orm"
75728
75845
  });
75729
75846
 
75730
75847
  // src/introspect-pg.ts
75731
- var import_drizzle_orm8, import_relations, pgImportsList, objToStatement23, timeConfig2, possibleIntervals, intervalStrToObj, intervalConfig, importsPatch2, relations3, withCasing2, paramNameFor, schemaToTypeScript3, isCyclic3, isSelf3, column6, dimensionsInArray, createTableColumns3, createTableIndexes3, createTablePKs3, createTableUniques3, createTableFKs3;
75848
+ function generateIdentityParams(identity) {
75849
+ let paramsObj = `{ name: "${identity.name}"`;
75850
+ if (identity == null ? void 0 : identity.startWith) {
75851
+ paramsObj += `, startWith: ${identity.startWith}`;
75852
+ }
75853
+ if (identity == null ? void 0 : identity.increment) {
75854
+ paramsObj += `, increment: ${identity.increment}`;
75855
+ }
75856
+ if (identity == null ? void 0 : identity.minValue) {
75857
+ paramsObj += `, minValue: ${identity.minValue}`;
75858
+ }
75859
+ if (identity == null ? void 0 : identity.maxValue) {
75860
+ paramsObj += `, maxValue: ${identity.maxValue}`;
75861
+ }
75862
+ if (identity == null ? void 0 : identity.cache) {
75863
+ paramsObj += `, cache: ${identity.cache}`;
75864
+ }
75865
+ if (identity == null ? void 0 : identity.cycle) {
75866
+ paramsObj += `, cycle: true`;
75867
+ }
75868
+ paramsObj += " }";
75869
+ if ((identity == null ? void 0 : identity.type) === "always") {
75870
+ return `.generatedAlwaysAsIdentity(${paramsObj})`;
75871
+ }
75872
+ return `.generatedByDefaultAsIdentity(${paramsObj})`;
75873
+ }
75874
+ var import_drizzle_orm8, import_relations, pgImportsList, timeConfig2, possibleIntervals, intervalStrToObj, intervalConfig, mapColumnDefault3, importsPatch2, relations3, escapeColumnKey3, withCasing2, paramNameFor, schemaToTypeScript3, isCyclic3, isSelf3, buildArrayDefault, mapDefault, column6, dimensionsInArray, createTableColumns3, createTableIndexes3, createTablePKs3, createTableUniques3, createTableFKs3;
75732
75875
  var init_introspect_pg = __esm({
75733
75876
  "src/introspect-pg.ts"() {
75734
75877
  "use strict";
@@ -75772,16 +75915,6 @@ var init_introspect_pg = __esm({
75772
75915
  "line",
75773
75916
  "geometry"
75774
75917
  ]);
75775
- objToStatement23 = (json) => {
75776
- json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
75777
- const keys = Object.keys(json);
75778
- if (keys.length === 0)
75779
- return;
75780
- let statement = "{ ";
75781
- statement += keys.map((it) => `${it}: "${json[it]}"`).join(", ");
75782
- statement += " }";
75783
- return statement;
75784
- };
75785
75918
  timeConfig2 = (json) => {
75786
75919
  json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
75787
75920
  const keys = Object.keys(json);
@@ -75841,6 +75974,12 @@ var init_introspect_pg = __esm({
75841
75974
  statement += " }";
75842
75975
  return statement;
75843
75976
  };
75977
+ mapColumnDefault3 = (defaultValue, isExpression) => {
75978
+ if (isExpression) {
75979
+ return `sql\`${defaultValue}\``;
75980
+ }
75981
+ return defaultValue;
75982
+ };
75844
75983
  importsPatch2 = {
75845
75984
  "double precision": "doublePrecision",
75846
75985
  "timestamp without time zone": "timestamp",
@@ -75849,12 +75988,18 @@ var init_introspect_pg = __esm({
75849
75988
  "time with time zone": "time"
75850
75989
  };
75851
75990
  relations3 = /* @__PURE__ */ new Set();
75991
+ escapeColumnKey3 = (value) => {
75992
+ if (/^(?![a-zA-Z_$][a-zA-Z0-9_$]*$).+$/.test(value)) {
75993
+ return `"${value}"`;
75994
+ }
75995
+ return value;
75996
+ };
75852
75997
  withCasing2 = (value, casing2) => {
75853
75998
  if (casing2 === "preserve") {
75854
- return value;
75999
+ return escapeColumnKey3(value);
75855
76000
  }
75856
76001
  if (casing2 === "camel") {
75857
- return value.camelCase();
76002
+ return escapeColumnKey3(value.camelCase());
75858
76003
  }
75859
76004
  assertUnreachable(casing2);
75860
76005
  };
@@ -75874,7 +76019,13 @@ var init_introspect_pg = __esm({
75874
76019
  return [it[0], withCasing2(it[1], casing2)];
75875
76020
  })
75876
76021
  );
75877
- const enumTypes = new Set(Object.values(schema5.enums).map((it) => it.name));
76022
+ const enumTypes = Object.values(schema5.enums).reduce(
76023
+ (acc, cur) => {
76024
+ acc.add(`${cur.schema}.${cur.name}`);
76025
+ return acc;
76026
+ },
76027
+ /* @__PURE__ */ new Set()
76028
+ );
75878
76029
  const imports = Object.values(schema5.tables).reduce(
75879
76030
  (res, it) => {
75880
76031
  const idxImports = Object.values(it.indexes).map((idx) => idx.isUnique ? "uniqueIndex" : "index");
@@ -75895,11 +76046,9 @@ var init_introspect_pg = __esm({
75895
76046
  res.pg.push(...fkImpots);
75896
76047
  res.pg.push(...pkImports);
75897
76048
  res.pg.push(...uniqueImports);
75898
- if (enumTypes.size > 0) {
75899
- res.pg.push("pgEnum");
75900
- }
75901
76049
  const columnImports = Object.values(it.columns).map((col) => {
75902
- let patched = importsPatch2[col.type] || col.type;
76050
+ let patched = (importsPatch2[col.type] || col.type).replace("[]", "");
76051
+ patched = patched === "double precision" ? "doublePrecision" : patched;
75903
76052
  patched = patched.startsWith("varchar(") ? "varchar" : patched;
75904
76053
  patched = patched.startsWith("char(") ? "char" : patched;
75905
76054
  patched = patched.startsWith("numeric(") ? "numeric" : patched;
@@ -75916,12 +76065,54 @@ var init_introspect_pg = __esm({
75916
76065
  },
75917
76066
  { pg: [] }
75918
76067
  );
76068
+ Object.values(schema5.sequences).forEach((it) => {
76069
+ if (it.schema && it.schema !== "public" && it.schema !== "") {
76070
+ imports.pg.push("pgSchema");
76071
+ } else if (it.schema === "public") {
76072
+ imports.pg.push("pgSequence");
76073
+ }
76074
+ });
76075
+ Object.values(schema5.enums).forEach((it) => {
76076
+ if (it.schema && it.schema !== "public" && it.schema !== "") {
76077
+ imports.pg.push("pgSchema");
76078
+ } else if (it.schema === "public") {
76079
+ imports.pg.push("pgEnum");
76080
+ }
76081
+ });
75919
76082
  const enumStatements = Object.values(schema5.enums).map((it) => {
75920
76083
  const enumSchema3 = schemas[it.schema];
75921
76084
  const paramName = paramNameFor(it.name, enumSchema3);
75922
76085
  const func = enumSchema3 ? `${enumSchema3}.enum` : "pgEnum";
75923
76086
  const values = Object.values(it.values).map((it2) => `'${it2}'`).join(", ");
75924
76087
  return `export const ${withCasing2(paramName, casing2)} = ${func}("${it.name}", [${values}])
76088
+ `;
76089
+ }).join("").concat("\n");
76090
+ const sequencesStatements = Object.values(schema5.sequences).map((it) => {
76091
+ const seqSchema = schemas[it.schema];
76092
+ const paramName = paramNameFor(it.name, seqSchema);
76093
+ const func = seqSchema ? `${seqSchema}.sequence` : "pgSequence";
76094
+ let params = "";
76095
+ if (it.startWith) {
76096
+ params += `, startWith: "${it.startWith}"`;
76097
+ }
76098
+ if (it.increment) {
76099
+ params += `, increment: "${it.increment}"`;
76100
+ }
76101
+ if (it.minValue) {
76102
+ params += `, minValue: "${it.minValue}"`;
76103
+ }
76104
+ if (it.maxValue) {
76105
+ params += `, maxValue: "${it.maxValue}"`;
76106
+ }
76107
+ if (it.cache) {
76108
+ params += `, cache: "${it.cache}"`;
76109
+ }
76110
+ if (it.cycle) {
76111
+ params += `, cycle: true`;
76112
+ } else {
76113
+ params += `, cycle: false`;
76114
+ }
76115
+ return `export const ${withCasing2(paramName, casing2)} = ${func}("${it.name}"${params ? `, { ${params.trimChar(",")} }` : ""})
75925
76116
  `;
75926
76117
  }).join("").concat("\n");
75927
76118
  const schemaStatements = Object.entries(schemas).map((it) => {
@@ -75944,10 +76135,7 @@ var init_introspect_pg = __esm({
75944
76135
  schema5.internal
75945
76136
  );
75946
76137
  statement += "}";
75947
- const filteredFKs = Object.values(table4.foreignKeys).filter((it) => {
75948
- return it.columnsFrom.length > 1 || isSelf3(it);
75949
- });
75950
- if (Object.keys(table4.indexes).length > 0 || filteredFKs.length > 0 || Object.keys(table4.compositePrimaryKeys).length > 0 || Object.keys(table4.uniqueConstraints).length > 0) {
76138
+ if (Object.keys(table4.indexes).length > 0 || Object.values(table4.foreignKeys).length > 0 || Object.keys(table4.compositePrimaryKeys).length > 0 || Object.keys(table4.uniqueConstraints).length > 0) {
75951
76139
  statement += ",\n";
75952
76140
  statement += "(table) => {\n";
75953
76141
  statement += " return {\n";
@@ -75956,7 +76144,7 @@ var init_introspect_pg = __esm({
75956
76144
  Object.values(table4.indexes),
75957
76145
  casing2
75958
76146
  );
75959
- statement += createTableFKs3(Object.values(filteredFKs), schemas, casing2);
76147
+ statement += createTableFKs3(Object.values(table4.foreignKeys), schemas, casing2);
75960
76148
  statement += createTablePKs3(
75961
76149
  Object.values(table4.compositePrimaryKeys),
75962
76150
  casing2
@@ -75980,6 +76168,7 @@ var init_introspect_pg = __esm({
75980
76168
  `;
75981
76169
  let decalrations = schemaStatements;
75982
76170
  decalrations += enumStatements;
76171
+ decalrations += sequencesStatements;
75983
76172
  decalrations += "\n";
75984
76173
  decalrations += tableStatements.join("\n\n");
75985
76174
  const file = importsTs + decalrations;
@@ -75998,9 +76187,120 @@ var init_introspect_pg = __esm({
75998
76187
  isSelf3 = (fk4) => {
75999
76188
  return fk4.tableFrom === fk4.tableTo;
76000
76189
  };
76001
- column6 = (tableName, type, name, enumTypes, casing2, defaultValue, internals) => {
76002
- var _a;
76003
- const lowered = type.toLowerCase();
76190
+ buildArrayDefault = (defaultValue, typeName) => {
76191
+ if (typeof defaultValue === "string" && !(defaultValue.startsWith("{") || defaultValue.startsWith("'{"))) {
76192
+ return `sql\`${defaultValue}\``;
76193
+ }
76194
+ defaultValue = defaultValue.substring(2, defaultValue.length - 2);
76195
+ return `[${defaultValue.split(/\s*,\s*/g).map((value) => {
76196
+ if (typeName === "json" || typeName === "jsonb") {
76197
+ return value.substring(1, value.length - 1).replaceAll("\\", "");
76198
+ }
76199
+ return value;
76200
+ }).join(", ")}]`;
76201
+ };
76202
+ mapDefault = (tableName, type, name, enumTypes, typeSchema, defaultValue, internals) => {
76203
+ var _a, _b, _c, _d;
76204
+ const isExpression = ((_b = (_a = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a.columns[name]) == null ? void 0 : _b.isDefaultAnExpression) ?? false;
76205
+ const isArray3 = ((_d = (_c = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _c.columns[name]) == null ? void 0 : _d.isArray) ?? false;
76206
+ const lowered = type.toLowerCase().replace("[]", "");
76207
+ if (isArray3) {
76208
+ return typeof defaultValue !== "undefined" ? `.default(${buildArrayDefault(defaultValue, lowered)})` : "";
76209
+ }
76210
+ if (enumTypes.has(`${typeSchema}.${type.replace("[]", "")}`)) {
76211
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76212
+ }
76213
+ if (lowered.startsWith("integer")) {
76214
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76215
+ }
76216
+ if (lowered.startsWith("smallint")) {
76217
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76218
+ }
76219
+ if (lowered.startsWith("bigint")) {
76220
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76221
+ }
76222
+ if (lowered.startsWith("boolean")) {
76223
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76224
+ }
76225
+ if (lowered.startsWith("double precision")) {
76226
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76227
+ }
76228
+ if (lowered.startsWith("real")) {
76229
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76230
+ }
76231
+ if (lowered.startsWith("uuid")) {
76232
+ return defaultValue === "gen_random_uuid()" ? ".defaultRandom()" : defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
76233
+ }
76234
+ if (lowered.startsWith("numeric")) {
76235
+ defaultValue = defaultValue ? defaultValue.startsWith(`'`) && defaultValue.endsWith(`'`) ? defaultValue.substring(1, defaultValue.length - 1) : defaultValue : void 0;
76236
+ return defaultValue ? `.default('${mapColumnDefault3(defaultValue, isExpression)}')` : "";
76237
+ }
76238
+ if (lowered.startsWith("timestamp")) {
76239
+ return defaultValue === "now()" ? ".defaultNow()" : defaultValue === "CURRENT_TIMESTAMP" ? ".default(sql`CURRENT_TIMESTAMP`)" : defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76240
+ }
76241
+ if (lowered.startsWith("time")) {
76242
+ return defaultValue === "now()" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76243
+ }
76244
+ if (lowered.startsWith("interval")) {
76245
+ return defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76246
+ }
76247
+ if (lowered === "date") {
76248
+ return defaultValue === "now()" ? ".defaultNow()" : defaultValue === "CURRENT_DATE" ? `.default(sql\`${defaultValue}\`)` : defaultValue ? `.default(${defaultValue})` : "";
76249
+ }
76250
+ if (lowered.startsWith("text")) {
76251
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76252
+ }
76253
+ if (lowered.startsWith("jsonb")) {
76254
+ const def = typeof defaultValue !== "undefined" ? defaultValue.replace(/::(.*?)(?<![^\w"])(?=$)/, "").slice(1, -1) : null;
76255
+ return defaultValue ? `.default(${def})` : "";
76256
+ }
76257
+ if (lowered.startsWith("json")) {
76258
+ const def = defaultValue ? defaultValue.replace(/::(.*?)(?<![^\w"])(?=$)/, "").slice(1, -1) : null;
76259
+ return typeof defaultValue !== "undefined" ? `.default(${def})` : "";
76260
+ }
76261
+ if (lowered.startsWith("inet")) {
76262
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76263
+ }
76264
+ if (lowered.startsWith("cidr")) {
76265
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76266
+ }
76267
+ if (lowered.startsWith("macaddr8")) {
76268
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76269
+ }
76270
+ if (lowered.startsWith("macaddr")) {
76271
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76272
+ }
76273
+ if (lowered.startsWith("varchar")) {
76274
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76275
+ }
76276
+ if (lowered.startsWith("point")) {
76277
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76278
+ }
76279
+ if (lowered.startsWith("line")) {
76280
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76281
+ }
76282
+ if (lowered.startsWith("geometry")) {
76283
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76284
+ }
76285
+ if (lowered.startsWith("vector")) {
76286
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76287
+ }
76288
+ if (lowered.startsWith("char")) {
76289
+ return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
76290
+ }
76291
+ return "";
76292
+ };
76293
+ column6 = (tableName, type, name, enumTypes, typeSchema, casing2, defaultValue, internals) => {
76294
+ var _a, _b;
76295
+ const isExpression = ((_b = (_a = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a.columns[name]) == null ? void 0 : _b.isDefaultAnExpression) ?? false;
76296
+ const lowered = type.toLowerCase().replace("[]", "");
76297
+ if (enumTypes.has(`${typeSchema}.${type.replace("[]", "")}`)) {
76298
+ let out = `${withCasing2(name, casing2)}: ${withCasing2(
76299
+ paramNameFor(type.replace("[]", ""), typeSchema),
76300
+ casing2
76301
+ )}("${name}")`;
76302
+ return out;
76303
+ }
76004
76304
  if (lowered.startsWith("serial")) {
76005
76305
  return `${withCasing2(name, casing2)}: serial("${name}")`;
76006
76306
  }
@@ -76015,39 +76315,32 @@ var init_introspect_pg = __esm({
76015
76315
  }
76016
76316
  if (lowered.startsWith("integer")) {
76017
76317
  let out = `${withCasing2(name, casing2)}: integer("${name}")`;
76018
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76019
76318
  return out;
76020
76319
  }
76021
76320
  if (lowered.startsWith("smallint")) {
76022
76321
  let out = `${withCasing2(name, casing2)}: smallint("${name}")`;
76023
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76024
76322
  return out;
76025
76323
  }
76026
76324
  if (lowered.startsWith("bigint")) {
76027
76325
  let out = `// You can use { mode: "bigint" } if numbers are exceeding js number limitations
76028
76326
  `;
76029
76327
  out += `${withCasing2(name, casing2)}: bigint("${name}", { mode: "number" })`;
76030
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76031
76328
  return out;
76032
76329
  }
76033
76330
  if (lowered.startsWith("boolean")) {
76034
76331
  let out = `${withCasing2(name, casing2)}: boolean("${name}")`;
76035
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76036
76332
  return out;
76037
76333
  }
76038
76334
  if (lowered.startsWith("double precision")) {
76039
76335
  let out = `${withCasing2(name, casing2)}: doublePrecision("${name}")`;
76040
- out += defaultValue ? `.default(${defaultValue})` : "";
76041
76336
  return out;
76042
76337
  }
76043
76338
  if (lowered.startsWith("real")) {
76044
76339
  let out = `${withCasing2(name, casing2)}: real("${name}")`;
76045
- out += defaultValue ? `.default(${defaultValue})` : "";
76046
76340
  return out;
76047
76341
  }
76048
76342
  if (lowered.startsWith("uuid")) {
76049
76343
  let out = `${withCasing2(name, casing2)}: uuid("${name}")`;
76050
- out += defaultValue === "gen_random_uuid()" ? ".defaultRandom()" : defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
76051
76344
  return out;
76052
76345
  }
76053
76346
  if (lowered.startsWith("numeric")) {
@@ -76057,8 +76350,6 @@ var init_introspect_pg = __esm({
76057
76350
  params = { precision, scale };
76058
76351
  }
76059
76352
  let out = params ? `${withCasing2(name, casing2)}: numeric("${name}", ${timeConfig2(params)})` : `${withCasing2(name, casing2)}: numeric("${name}")`;
76060
- defaultValue = defaultValue ? defaultValue.startsWith(`'`) && defaultValue.endsWith(`'`) ? defaultValue.substring(1, defaultValue.length - 1) : defaultValue : void 0;
76061
- out += defaultValue ? `.default('${defaultValue}')` : "";
76062
76353
  return out;
76063
76354
  }
76064
76355
  if (lowered.startsWith("timestamp")) {
@@ -76073,8 +76364,6 @@ var init_introspect_pg = __esm({
76073
76364
  mode: "'string'"
76074
76365
  });
76075
76366
  let out = params ? `${withCasing2(name, casing2)}: timestamp("${name}", ${params})` : `${withCasing2(name, casing2)}: timestamp("${name}")`;
76076
- defaultValue = defaultValue === "now()" || defaultValue === "CURRENT_TIMESTAMP" ? ".defaultNow()" : defaultValue ? `.default(${defaultValue})` : "";
76077
- out += defaultValue;
76078
76367
  return out;
76079
76368
  }
76080
76369
  if (lowered.startsWith("time")) {
@@ -76085,63 +76374,46 @@ var init_introspect_pg = __esm({
76085
76374
  precision = precision ? precision : null;
76086
76375
  const params = timeConfig2({ precision, withTimezone });
76087
76376
  let out = params ? `${withCasing2(name, casing2)}: time("${name}", ${params})` : `${withCasing2(name, casing2)}: time("${name}")`;
76088
- defaultValue = defaultValue === "now()" ? ".defaultNow()" : defaultValue ? `.default(${defaultValue})` : "";
76089
- out += defaultValue;
76090
76377
  return out;
76091
76378
  }
76092
76379
  if (lowered.startsWith("interval")) {
76093
76380
  const params = intervalConfig(lowered);
76094
76381
  let out = params ? `${withCasing2(name, casing2)}: interval("${name}", ${params})` : `${withCasing2(name, casing2)}: interval("${name}")`;
76095
- out += defaultValue ? `.default(${defaultValue})` : "";
76096
76382
  return out;
76097
76383
  }
76098
76384
  if (lowered === "date") {
76099
76385
  let out = `${withCasing2(name, casing2)}: date("${name}")`;
76100
- defaultValue = defaultValue === "now()" ? ".defaultNow()" : defaultValue === "CURRENT_DATE" ? `.default(sql\`${defaultValue}\`)` : defaultValue ? `.default(${defaultValue})` : "";
76101
- out += defaultValue;
76102
76386
  return out;
76103
76387
  }
76104
76388
  if (lowered.startsWith("text")) {
76105
76389
  let out = `${withCasing2(name, casing2)}: text("${name}")`;
76106
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76107
76390
  return out;
76108
76391
  }
76109
- if (lowered === "json") {
76110
- let out = `${withCasing2(name, casing2)}: json("${name}")`;
76111
- defaultValue = (defaultValue == null ? void 0 : defaultValue.endsWith("::json")) ? defaultValue.substring(1, defaultValue.length - 7) : defaultValue;
76112
- const def = defaultValue ? defaultValue : null;
76113
- out += typeof defaultValue !== "undefined" ? `.default(${def})` : "";
76392
+ if (lowered.startsWith("jsonb")) {
76393
+ let out = `${withCasing2(name, casing2)}: jsonb("${name}")`;
76114
76394
  return out;
76115
76395
  }
76116
- if (lowered === "jsonb") {
76117
- let out = `${withCasing2(name, casing2)}: jsonb("${name}")`;
76118
- defaultValue = (defaultValue == null ? void 0 : defaultValue.endsWith("::jsonb")) ? defaultValue.substring(1, defaultValue.length - 8) : defaultValue;
76119
- const def = typeof defaultValue !== "undefined" ? defaultValue : null;
76120
- out += defaultValue ? `.default(${def})` : "";
76396
+ if (lowered.startsWith("json")) {
76397
+ let out = `${withCasing2(name, casing2)}: json("${name}")`;
76121
76398
  return out;
76122
76399
  }
76123
76400
  if (lowered.startsWith("inet")) {
76124
76401
  let out = `${withCasing2(name, casing2)}: inet("${name}")`;
76125
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76126
76402
  return out;
76127
76403
  }
76128
76404
  if (lowered.startsWith("cidr")) {
76129
76405
  let out = `${withCasing2(name, casing2)}: cidr("${name}")`;
76130
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76131
- return out;
76132
- }
76133
- if (lowered.startsWith("macaddr")) {
76134
- let out = `${withCasing2(name, casing2)}: macaddr("${name}")`;
76135
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76136
76406
  return out;
76137
76407
  }
76138
76408
  if (lowered.startsWith("macaddr8")) {
76139
76409
  let out = `${withCasing2(name, casing2)}: macaddr8("${name}")`;
76140
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76410
+ return out;
76411
+ }
76412
+ if (lowered.startsWith("macaddr")) {
76413
+ let out = `${withCasing2(name, casing2)}: macaddr("${name}")`;
76141
76414
  return out;
76142
76415
  }
76143
76416
  if (lowered.startsWith("varchar")) {
76144
- const split = lowered.split(" ");
76145
76417
  let out;
76146
76418
  if (lowered.length !== 7) {
76147
76419
  out = `${withCasing2(
@@ -76154,17 +76426,14 @@ var init_introspect_pg = __esm({
76154
76426
  } else {
76155
76427
  out = `${withCasing2(name, casing2)}: varchar("${name}")`;
76156
76428
  }
76157
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76158
76429
  return out;
76159
76430
  }
76160
76431
  if (lowered.startsWith("point")) {
76161
76432
  let out = `${withCasing2(name, casing2)}: point("${name}")`;
76162
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76163
76433
  return out;
76164
76434
  }
76165
76435
  if (lowered.startsWith("line")) {
76166
76436
  let out = `${withCasing2(name, casing2)}: point("${name}")`;
76167
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76168
76437
  return out;
76169
76438
  }
76170
76439
  if (lowered.startsWith("geometry")) {
@@ -76182,7 +76451,6 @@ var init_introspect_pg = __esm({
76182
76451
  } else {
76183
76452
  out = `${withCasing2(name, casing2)}: geometry("${name}")`;
76184
76453
  }
76185
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76186
76454
  if (isGeoUnknown) {
76187
76455
  let unknown2 = `// TODO: failed to parse geometry type because found more than 2 options inside geometry function '${type}'
76188
76456
  // Introspect is currently supporting only type and srid options
@@ -76193,7 +76461,6 @@ var init_introspect_pg = __esm({
76193
76461
  return out;
76194
76462
  }
76195
76463
  if (lowered.startsWith("vector")) {
76196
- const split = lowered.split(" ");
76197
76464
  let out;
76198
76465
  if (lowered.length !== 6) {
76199
76466
  out = `${withCasing2(
@@ -76206,7 +76473,6 @@ var init_introspect_pg = __esm({
76206
76473
  } else {
76207
76474
  out = `${withCasing2(name, casing2)}: vector("${name}")`;
76208
76475
  }
76209
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76210
76476
  return out;
76211
76477
  }
76212
76478
  if (lowered.startsWith("char")) {
@@ -76222,26 +76488,6 @@ var init_introspect_pg = __esm({
76222
76488
  } else {
76223
76489
  out = `${withCasing2(name, casing2)}: char("${name}")`;
76224
76490
  }
76225
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76226
- return out;
76227
- }
76228
- const columnInternals = (_a = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a.columns[name];
76229
- if (typeof columnInternals !== "undefined") {
76230
- if (columnInternals.isArray && columnInternals.rawType && enumTypes.has(columnInternals.rawType)) {
76231
- let out = `${withCasing2(columnInternals.rawType, casing2)}: ${withCasing2(
76232
- columnInternals.rawType,
76233
- casing2
76234
- )}("${name}")`;
76235
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76236
- return out;
76237
- }
76238
- }
76239
- if (enumTypes.has(type)) {
76240
- let out = `${withCasing2(name, casing2)}: ${withCasing2(
76241
- type,
76242
- casing2
76243
- )}("${name}")`;
76244
- out += typeof defaultValue !== "undefined" ? `.default(${defaultValue})` : "";
76245
76491
  return out;
76246
76492
  }
76247
76493
  let unknown = `// TODO: failed to parse database type '${type}'
@@ -76276,6 +76522,7 @@ var init_introspect_pg = __esm({
76276
76522
  it.type,
76277
76523
  it.name,
76278
76524
  enumTypes,
76525
+ it.typeSchema ?? "public",
76279
76526
  casing2,
76280
76527
  it.default,
76281
76528
  internals
@@ -76287,59 +76534,19 @@ var init_introspect_pg = __esm({
76287
76534
  (_d = (_c = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _c.columns[it.name]) == null ? void 0 : _d.dimensions
76288
76535
  );
76289
76536
  }
76537
+ statement += mapDefault(
76538
+ tableName,
76539
+ it.type,
76540
+ it.name,
76541
+ enumTypes,
76542
+ it.typeSchema ?? "public",
76543
+ it.default,
76544
+ internals
76545
+ );
76290
76546
  statement += it.primaryKey ? ".primaryKey()" : "";
76291
76547
  statement += it.notNull && !it.identity ? ".notNull()" : "";
76292
- function generateIdentityParams(identity) {
76293
- let paramsObj = `{ name: "${identity.name}"`;
76294
- if (identity == null ? void 0 : identity.startWith) {
76295
- paramsObj += `, startWith: ${identity.startWith}`;
76296
- }
76297
- if (identity == null ? void 0 : identity.increment) {
76298
- paramsObj += `, increment: ${identity.increment}`;
76299
- }
76300
- if (identity == null ? void 0 : identity.minValue) {
76301
- paramsObj += `, minValue: ${identity.minValue}`;
76302
- }
76303
- if (identity == null ? void 0 : identity.maxValue) {
76304
- paramsObj += `, maxValue: ${identity.maxValue}`;
76305
- }
76306
- if (identity == null ? void 0 : identity.cache) {
76307
- paramsObj += `, cache: ${identity.cache}`;
76308
- }
76309
- if (identity == null ? void 0 : identity.cycle) {
76310
- paramsObj += `, cycle: true`;
76311
- }
76312
- paramsObj += " }";
76313
- if ((identity == null ? void 0 : identity.type) === "always") {
76314
- return `.generatedAlwaysAsIdentity(${paramsObj})`;
76315
- }
76316
- return `.generatedByDefaultAsIdentity(${paramsObj})`;
76317
- }
76318
76548
  statement += it.identity ? generateIdentityParams(it.identity) : "";
76319
76549
  statement += it.generated ? `.generatedAlwaysAs(sql\`${it.generated.as}\`)` : "";
76320
- const fks2 = fkByColumnName[it.name];
76321
- if (fks2) {
76322
- const fksStatement = fks2.map((it2) => {
76323
- const onDelete = it2.onDelete && it2.onDelete !== "no action" ? it2.onDelete : null;
76324
- const onUpdate = it2.onUpdate && it2.onUpdate !== "no action" ? it2.onUpdate : null;
76325
- const params = { onDelete, onUpdate };
76326
- const typeSuffix = isCyclic3(it2) ? ": AnyPgColumn" : "";
76327
- const paramsStr = objToStatement23(params);
76328
- const tableSchema = schemas[it2.schemaTo || ""];
76329
- const paramName = paramNameFor(it2.tableTo, tableSchema);
76330
- if (paramsStr) {
76331
- return `.references(()${typeSuffix} => ${withCasing2(
76332
- paramName,
76333
- casing2
76334
- )}.${withCasing2(it2.columnsTo[0], casing2)}, ${paramsStr} )`;
76335
- }
76336
- return `.references(()${typeSuffix} => ${withCasing2(
76337
- paramName,
76338
- casing2
76339
- )}.${withCasing2(it2.columnsTo[0], casing2)})`;
76340
- }).join("");
76341
- statement += fksStatement;
76342
- }
76343
76550
  statement += ",\n";
76344
76551
  });
76345
76552
  return statement;
@@ -76363,7 +76570,7 @@ var init_introspect_pg = __esm({
76363
76570
  if (it2.isExpression) {
76364
76571
  return `sql\`${it2.expression}\``;
76365
76572
  } else {
76366
- return `table.${withCasing2(it2.expression, casing2)}${it2.opclass && vectorOps.includes(it2.opclass) ? `.op("${it2.opclass}")` : ""}`;
76573
+ return `table.${withCasing2(it2.expression, casing2)}${it2.asc ? ".asc()" : ".desc()"}${it2.nulls === "first" ? ".nullsFirst()" : ".nullsLast()"}${it2.opclass && vectorOps.includes(it2.opclass) ? `.op("${it2.opclass}")` : ""}`;
76367
76574
  }
76368
76575
  }).join(", ")})`;
76369
76576
  statement += it.where ? `.where(sql\`${it.where}\`)` : "";
@@ -80245,10 +80452,13 @@ var init_studio2 = __esm({
80245
80452
  const customDefaults = getCustomDefaults(pgSchema2);
80246
80453
  let dbUrl;
80247
80454
  if ("driver" in credentials2) {
80248
- if (credentials2.driver === "aws-data-api") {
80455
+ const { driver: driver2 } = credentials2;
80456
+ if (driver2 === "aws-data-api") {
80249
80457
  dbUrl = `aws-data-api://${credentials2.database}/${credentials2.secretArn}/${credentials2.resourceArn}`;
80458
+ } else if (driver2 === "pglite") {
80459
+ dbUrl = credentials2.url;
80250
80460
  } else {
80251
- assertUnreachable(credentials2.driver);
80461
+ assertUnreachable(driver2);
80252
80462
  }
80253
80463
  } else if ("url" in credentials2) {
80254
80464
  dbUrl = credentials2.url;
@@ -80519,7 +80729,7 @@ var init_studio2 = __esm({
80519
80729
  }
80520
80730
  });
80521
80731
 
80522
- // ../node_modules/.pnpm/@drizzle-team+brocli@0.8.2/node_modules/@drizzle-team/brocli/index.js
80732
+ // ../node_modules/.pnpm/@drizzle-team+brocli@0.10.1/node_modules/@drizzle-team/brocli/index.js
80523
80733
  var __create2 = Object.create;
80524
80734
  var __defProp2 = Object.defineProperty;
80525
80735
  var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
@@ -80966,130 +81176,299 @@ var require_shell_quote = __commonJS2({
80966
81176
  }
80967
81177
  });
80968
81178
  var BroCliError = class extends Error {
80969
- constructor(message) {
81179
+ constructor(message, event) {
80970
81180
  const errPrefix = "BroCli error: ";
80971
81181
  super(message === void 0 ? message : `${errPrefix}${message}`);
81182
+ this.event = event;
80972
81183
  }
80973
81184
  };
80974
81185
  var import_clone = __toESM2(require_clone(), 1);
80975
- var import_shell_quote = __toESM2(require_shell_quote(), 1);
80976
- var defaultTheme = (calledFor) => {
80977
- if (Array.isArray(calledFor)) {
80978
- const cmds = calledFor.filter((cmd) => !cmd.hidden);
80979
- const tableCmds = cmds.map((cmd) => ({
80980
- name: cmd.name,
80981
- aliases: cmd.aliases ? cmd.aliases.join(", ") : "-",
80982
- description: cmd.description ?? "-"
80983
- }));
80984
- console.log(`Here's the list of all available commands:`);
80985
- console.table(tableCmds);
80986
- console.log(
80987
- "To read the details about any particular command type: [commandName] --help"
80988
- );
80989
- } else {
80990
- const options = calledFor.options ? Object.values(calledFor.options).filter((opt) => {
80991
- var _a;
80992
- return !((_a = opt.config) == null ? void 0 : _a.isHidden);
80993
- }).map(
80994
- ({ config: opt }) => ({
80995
- name: opt.name,
80996
- aliases: opt.aliases.length ? `${opt.aliases.join(", ")}` : "-",
80997
- description: opt.description ?? "-",
80998
- type: opt.type,
80999
- required: opt.isRequired ? "\u2713" : "\u2717"
81000
- })
81001
- ) : void 0;
81002
- console.log(
81003
- `Command: ${calledFor.name}${calledFor.aliases ? ` [${calledFor.aliases.join(", ")}]` : ""}${calledFor.description ? ` - ${calledFor.description}` : ""}`
81004
- );
81005
- if (!(options == null ? void 0 : options.length))
81006
- return;
81007
- console.log("\nOptions:");
81008
- console.table(options);
81186
+ var getOptionTypeText = (option) => {
81187
+ let result = "";
81188
+ switch (option.type) {
81189
+ case "boolean":
81190
+ result = "";
81191
+ break;
81192
+ case "number": {
81193
+ if ((option.minVal ?? option.maxVal) !== void 0) {
81194
+ let text = "";
81195
+ if (option.isInt)
81196
+ text = text + `integer `;
81197
+ if (option.minVal !== void 0)
81198
+ text = text + `[${option.minVal};`;
81199
+ else
81200
+ text = text + `(\u221E;`;
81201
+ if (option.maxVal !== void 0)
81202
+ text = text + `${option.maxVal}]`;
81203
+ else
81204
+ text = text + `\u221E)`;
81205
+ result = text;
81206
+ break;
81207
+ }
81208
+ if (option.isInt) {
81209
+ result = "integer";
81210
+ break;
81211
+ }
81212
+ result = "number";
81213
+ break;
81214
+ }
81215
+ case "string": {
81216
+ if (option.enumVals) {
81217
+ result = "[ " + option.enumVals.join(" | ") + " ]";
81218
+ break;
81219
+ }
81220
+ result = "string";
81221
+ break;
81222
+ }
81223
+ case "positional": {
81224
+ result = `${option.isRequired ? "<" : "["}${option.enumVals ? option.enumVals.join("|") : option.name}${option.isRequired ? ">" : "]"}`;
81225
+ break;
81226
+ }
81227
+ }
81228
+ if (option.isRequired && option.type !== "positional")
81229
+ result = "!" + result.length ? " " : "" + result;
81230
+ return result;
81231
+ };
81232
+ var defaultEventHandler = async (event) => {
81233
+ var _a;
81234
+ switch (event.type) {
81235
+ case "command_help": {
81236
+ const command2 = event.command;
81237
+ const commandName = getCommandNameWithParents(command2);
81238
+ const cliName = event.name;
81239
+ const desc = command2.desc ?? command2.shortDesc;
81240
+ const subs = (_a = command2.subcommands) == null ? void 0 : _a.filter((s2) => !s2.hidden);
81241
+ const subcommands = subs && subs.length ? subs : void 0;
81242
+ if (desc !== void 0) {
81243
+ console.log(`
81244
+ ${desc}`);
81245
+ }
81246
+ const opts = Object.values(command2.options ?? {}).filter(
81247
+ (opt) => !opt.config.isHidden
81248
+ );
81249
+ const positionals = opts.filter((opt) => opt.config.type === "positional");
81250
+ const options = opts.filter((opt) => opt.config.type !== "positional");
81251
+ console.log("\nUsage:");
81252
+ if (command2.handler) {
81253
+ console.log(
81254
+ ` ${cliName ? cliName + " " : ""}${commandName}${positionals.length ? " " + positionals.map(({ config: p2 }) => getOptionTypeText(p2)).join(" ") : ""} [flags]`
81255
+ );
81256
+ } else
81257
+ console.log(` ${cliName ? cliName + " " : ""}${commandName} [command]`);
81258
+ if (command2.aliases) {
81259
+ console.log(`
81260
+ Aliases:`);
81261
+ console.log(` ${[command2.name, ...command2.aliases].join(", ")}`);
81262
+ }
81263
+ if (subcommands) {
81264
+ console.log("\nAvailable Commands:");
81265
+ const padding = 3;
81266
+ const maxLength = subcommands.reduce((p2, e2) => e2.name.length > p2 ? e2.name.length : p2, 0);
81267
+ const paddedLength = maxLength + padding;
81268
+ const preDescPad = 2 + paddedLength;
81269
+ const data = subcommands.map(
81270
+ (s2) => ` ${s2.name.padEnd(paddedLength)}${(() => {
81271
+ const description = s2.shortDesc ?? s2.desc;
81272
+ if (!(description == null ? void 0 : description.length))
81273
+ return "";
81274
+ const split = description.split("\n");
81275
+ const first = split.shift();
81276
+ const final = [first, ...split.map((s22) => "".padEnd(preDescPad) + s22)].join("\n");
81277
+ return final;
81278
+ })()}`
81279
+ ).join("\n");
81280
+ console.log(data);
81281
+ }
81282
+ if (options.length) {
81283
+ const aliasLength = options.reduce((p2, e2) => {
81284
+ const currentLength = e2.config.aliases.reduce((pa, a) => pa + a.length, 0) + (e2.config.aliases.length - 1) * 2 + 1;
81285
+ return currentLength > p2 ? currentLength : p2;
81286
+ }, 0);
81287
+ const paddedAliasLength = aliasLength > 0 ? aliasLength + 1 : 0;
81288
+ const nameLength = options.reduce((p2, e2) => {
81289
+ const typeLen = getOptionTypeText(e2.config).length;
81290
+ const length = typeLen > 0 ? e2.config.name.length + 1 + typeLen : e2.config.name.length;
81291
+ return length > p2 ? length : p2;
81292
+ }, 0) + 3;
81293
+ const preDescPad = paddedAliasLength + nameLength + 2;
81294
+ const data = options.map(
81295
+ ({ config: opt }) => ` ${`${opt.aliases.length ? opt.aliases.join(", ") + "," : ""}`.padEnd(paddedAliasLength)}${`${opt.name}${(() => {
81296
+ const typeText = getOptionTypeText(opt);
81297
+ return typeText.length ? " " + typeText : "";
81298
+ })()}`.padEnd(nameLength)}${(() => {
81299
+ var _a2;
81300
+ if (!((_a2 = opt.description) == null ? void 0 : _a2.length)) {
81301
+ return opt.default !== void 0 ? `default: ${JSON.stringify(opt.default)}` : "";
81302
+ }
81303
+ const split = opt.description.split("\n");
81304
+ const first = split.shift();
81305
+ const def = opt.default !== void 0 ? ` (default: ${JSON.stringify(opt.default)})` : "";
81306
+ const final = [first, ...split.map((s2) => "".padEnd(preDescPad) + s2)].join("\n") + def;
81307
+ return final;
81308
+ })()}`
81309
+ ).join("\n");
81310
+ console.log("\nFlags:");
81311
+ console.log(data);
81312
+ }
81313
+ console.log("\nGlobal flags:");
81314
+ console.log(` -h, --help help for ${commandName}`);
81315
+ console.log(` -v, --version version${cliName ? ` for ${cliName}` : ""}`);
81316
+ if (subcommands) {
81317
+ console.log(
81318
+ `
81319
+ Use "${cliName ? cliName + " " : ""}${commandName} [command] --help" for more information about a command.
81320
+ `
81321
+ );
81322
+ }
81323
+ return true;
81324
+ }
81325
+ case "global_help": {
81326
+ const cliName = event.name;
81327
+ const desc = event.description;
81328
+ const commands = event.commands.filter((c) => !c.hidden);
81329
+ if (desc !== void 0) {
81330
+ console.log(`${desc}
81331
+ `);
81332
+ }
81333
+ console.log("Usage:");
81334
+ console.log(` ${cliName ? cliName + " " : ""}[command]`);
81335
+ if (commands.length) {
81336
+ console.log("\nAvailable Commands:");
81337
+ const padding = 3;
81338
+ const maxLength = commands.reduce((p2, e2) => e2.name.length > p2 ? e2.name.length : p2, 0);
81339
+ const paddedLength = maxLength + padding;
81340
+ const data = commands.map(
81341
+ (\u0441) => ` ${\u0441.name.padEnd(paddedLength)}${(() => {
81342
+ const desc2 = \u0441.shortDesc ?? \u0441.desc;
81343
+ if (!(desc2 == null ? void 0 : desc2.length))
81344
+ return "";
81345
+ const split = desc2.split("\n");
81346
+ const first = split.shift();
81347
+ const final = [first, ...split.map((s2) => "".padEnd(paddedLength + 2) + s2)].join("\n");
81348
+ return final;
81349
+ })()}`
81350
+ ).join("\n");
81351
+ console.log(data);
81352
+ } else {
81353
+ console.log("\nNo available commands.");
81354
+ }
81355
+ console.log("\nFlags:");
81356
+ console.log(` -h, --help help${cliName ? ` for ${cliName}` : ""}`);
81357
+ console.log(` -v, --version version${cliName ? ` for ${cliName}` : ""}`);
81358
+ console.log("\n");
81359
+ return true;
81360
+ }
81361
+ case "version": {
81362
+ return true;
81363
+ }
81364
+ case "error": {
81365
+ let msg;
81366
+ switch (event.violation) {
81367
+ case "above_max": {
81368
+ const matchedName = event.offender.namePart;
81369
+ const data = event.offender.dataPart;
81370
+ const option = event.option;
81371
+ const max = option.maxVal;
81372
+ msg = `Invalid value: number type argument '${matchedName}' expects maximal value of ${max} as an input, got: ${data}`;
81373
+ break;
81374
+ }
81375
+ case "below_min": {
81376
+ const matchedName = event.offender.namePart;
81377
+ const data = event.offender.dataPart;
81378
+ const option = event.option;
81379
+ const min = option.minVal;
81380
+ msg = `Invalid value: number type argument '${matchedName}' expects minimal value of ${min} as an input, got: ${data}`;
81381
+ break;
81382
+ }
81383
+ case "expected_int": {
81384
+ const matchedName = event.offender.namePart;
81385
+ const data = event.offender.dataPart;
81386
+ msg = `Invalid value: number type argument '${matchedName}' expects an integer as an input, got: ${data}`;
81387
+ break;
81388
+ }
81389
+ case "invalid_boolean_syntax": {
81390
+ const matchedName = event.offender.namePart;
81391
+ const data = event.offender.dataPart;
81392
+ msg = `Invalid syntax: boolean type argument '${matchedName}' must have it's value passed in the following formats: ${matchedName}=<value> | ${matchedName} <value> | ${matchedName}.
81393
+ Allowed values: true, false, 0, 1`;
81394
+ break;
81395
+ }
81396
+ case "invalid_string_syntax": {
81397
+ const matchedName = event.offender.namePart;
81398
+ msg = `Invalid syntax: string type argument '${matchedName}' must have it's value passed in the following formats: ${matchedName}=<value> | ${matchedName} <value>`;
81399
+ break;
81400
+ }
81401
+ case "invalid_number_syntax": {
81402
+ const matchedName = event.offender.namePart;
81403
+ msg = `Invalid syntax: number type argument '${matchedName}' must have it's value passed in the following formats: ${matchedName}=<value> | ${matchedName} <value>`;
81404
+ break;
81405
+ }
81406
+ case "invalid_number_value": {
81407
+ const matchedName = event.offender.namePart;
81408
+ const data = event.offender.dataPart;
81409
+ msg = `Invalid value: number type argument '${matchedName}' expects a number as an input, got: ${data}`;
81410
+ break;
81411
+ }
81412
+ case "enum_violation": {
81413
+ const matchedName = event.offender.namePart;
81414
+ const data = event.offender.dataPart;
81415
+ const option = event.option;
81416
+ const values = option.enumVals;
81417
+ msg = option.type === "positional" ? `Invalid value: value for the positional argument '${option.name}' must be either one of the following: ${values.join(", ")}; Received: ${data}` : `Invalid value: value for the argument '${matchedName}' must be either one of the following: ${values.join(", ")}; Received: ${data}`;
81418
+ break;
81419
+ }
81420
+ case "unknown_command_error": {
81421
+ const msg2 = `Unknown command: '${event.offender}'.
81422
+ Type '--help' to get help on the cli.`;
81423
+ console.error(msg2);
81424
+ return true;
81425
+ }
81426
+ case "unknown_subcommand_error": {
81427
+ const cName = getCommandNameWithParents(event.command);
81428
+ const msg2 = `Unknown command: ${cName} ${event.offender}.
81429
+ Type '${cName} --help' to get the help on command.`;
81430
+ console.error(msg2);
81431
+ return true;
81432
+ }
81433
+ case "missing_args_error": {
81434
+ const missingOpts = event.missing;
81435
+ msg = `Command '${command.name}' is missing following required options: ${missingOpts.map((opt) => {
81436
+ const name = opt.shift();
81437
+ const aliases = opt;
81438
+ if (aliases.length)
81439
+ return `${name} [${aliases.join(", ")}]`;
81440
+ return name;
81441
+ }).join(", ")}`;
81442
+ break;
81443
+ }
81444
+ case "unrecognized_args_error": {
81445
+ const { command: command2, unrecognized } = event;
81446
+ msg = `Unrecognized options for command '${command2.name}': ${unrecognized.join(", ")}`;
81447
+ break;
81448
+ }
81449
+ case "unknown_error": {
81450
+ const e2 = event.error;
81451
+ console.error(typeof e2 === "object" && e2 !== null && "message" in e2 ? e2.message : e2);
81452
+ return true;
81453
+ }
81454
+ }
81455
+ console.error(msg);
81456
+ return true;
81457
+ }
81009
81458
  }
81459
+ return false;
81010
81460
  };
81461
+ var eventHandlerWrapper = (customEventHandler) => async (event) => await customEventHandler(event) ? true : await defaultEventHandler(event);
81462
+ var import_shell_quote = __toESM2(require_shell_quote(), 1);
81011
81463
  function isInt(value) {
81012
81464
  return value === Math.floor(value);
81013
81465
  }
81014
- var unknownCommand = (caller) => {
81015
- const msg = `Unknown command: '${caller}'.
81016
- Type '--help' to get help on the cli.`;
81017
- return new Error(msg);
81018
- };
81019
- var unknownSubcommand = (command2, caller) => {
81020
- const name = getCommandNameRecursive(command2);
81021
- const msg = `Unknown command: ${name} ${caller}.
81022
- Type '${name} --help' to get the help on command.`;
81023
- new Error(
81024
- msg
81025
- );
81026
- return new Error(msg);
81027
- };
81028
- var missingRequired = (command2, missingOpts) => {
81029
- const msg = `Command '${command2.name}' is missing following required options: ${missingOpts.map((opt) => {
81030
- const name = opt.shift();
81031
- const aliases = opt;
81032
- if (aliases.length)
81033
- return `${name} [${aliases.join(", ")}]`;
81034
- return name;
81035
- }).join(", ")}`;
81036
- return new Error(msg);
81037
- };
81038
- var unrecognizedOptions = (command2, unrecognizedArgs) => {
81039
- const msg = `Unrecognized options for command '${command2.name}': ${unrecognizedArgs.join(", ")}`;
81040
- return new Error(msg);
81041
- };
81042
- var invalidBooleanSyntax = (matchedName) => {
81043
- return new Error(
81044
- `Invalid syntax: boolean type argument '${matchedName}' must have it's value passed in the following formats: ${matchedName}=<value> | ${matchedName} <value> | ${matchedName}.
81045
- Allowed values: true, false, 0, 1`
81046
- );
81047
- };
81048
- var invalidStringSyntax = (matchedName) => {
81049
- return new Error(
81050
- `Invalid syntax: string type argument '${matchedName}' must have it's value passed in the following formats: ${matchedName}=<value> | ${matchedName} <value>`
81051
- );
81052
- };
81053
- var enumViolation = (matchedName, data, values) => {
81054
- return new Error(
81055
- `Invalid value: value for the argument '${matchedName}' must be either one of the following: ${values.join(", ")}; Received: ${data}`
81056
- );
81057
- };
81058
- var enumViolationPos = (matchedName, data, values) => {
81059
- return new Error(
81060
- `Invalid value: value for the argument '${matchedName}' must be either one of the following: ${values.join(", ")}; Received: ${data}`
81061
- );
81062
- };
81063
- var invalidNumberSyntax = (matchedName) => {
81064
- return new Error(
81065
- `Invalid syntax: number type argument '${matchedName}' must have it's value passed in the following formats: ${matchedName}=<value> | ${matchedName} <value>`
81066
- );
81067
- };
81068
- var invalidNumberValue = (matchedName, data) => {
81069
- return new Error(
81070
- `Invalid value: number type argument '${matchedName}' expects a number as an input, got: ${data}`
81071
- );
81072
- };
81073
- var invalidInteger = (matchedName, data) => {
81074
- return new Error(
81075
- `Invalid value: number type argument '${matchedName}' expects an integer as an input, got: ${data}`
81076
- );
81077
- };
81078
- var belowMin = (matchedName, data, min) => {
81079
- return new Error(
81080
- `Invalid value: number type argument '${matchedName}' expects minimal value of ${min} as an input, got: ${data}`
81081
- );
81082
- };
81083
- var aboveMax = (matchedName, data, max) => {
81084
- return new Error(
81085
- `Invalid value: number type argument '${matchedName}' expects maximal value of ${max} as an input, got: ${data}`
81086
- );
81087
- };
81466
+ var executeOrLog = async (target) => typeof target === "string" ? console.log(target) : target ? await target() : void 0;
81088
81467
  var generatePrefix = (name) => name.startsWith("-") ? name : name.length > 1 ? `--${name}` : `-${name}`;
81089
81468
  var validateOptions = (config) => {
81090
81469
  const cloned = (0, import_clone.default)(config);
81091
81470
  const entries = [];
81092
- const storedNames = {};
81471
+ const storedNames = [];
81093
81472
  const cfgEntries = Object.entries(cloned);
81094
81473
  for (const [key, value] of cfgEntries) {
81095
81474
  const cfg = value._.config;
@@ -81099,13 +81478,13 @@ var validateOptions = (config) => {
81099
81478
  continue;
81100
81479
  if (cfg.name.includes("=")) {
81101
81480
  throw new BroCliError(
81102
- `Can't define option ${cfg.name} - option names and aliases cannot contain '='!`
81481
+ `Can't define option '${generatePrefix(cfg.name)}' - option names and aliases cannot contain '='!`
81103
81482
  );
81104
81483
  }
81105
81484
  for (const alias of cfg.aliases) {
81106
81485
  if (alias.includes("=")) {
81107
81486
  throw new BroCliError(
81108
- `Can't define option ${cfg.name} - option names and aliases cannot contain '='!`
81487
+ `Can't define option '${generatePrefix(cfg.name)}' - option names and aliases cannot contain '='!`
81109
81488
  );
81110
81489
  }
81111
81490
  }
@@ -81123,33 +81502,33 @@ var validateOptions = (config) => {
81123
81502
  for (const name of allNames) {
81124
81503
  const match2 = reservedNames.find((n) => n === name);
81125
81504
  if (match2)
81126
- throw new BroCliError(`Can't define option ${cfg.name} - name '${match2}' is reserved!`);
81505
+ throw new BroCliError(`Can't define option '${cfg.name}' - name '${match2}' is reserved!`);
81127
81506
  }
81128
- const storageVals = Object.values(storedNames);
81129
- for (const storage2 of storageVals) {
81507
+ for (const storage2 of storedNames) {
81130
81508
  const nameOccupier = storage2.find((e2) => e2 === cfg.name);
81131
81509
  if (!nameOccupier)
81132
81510
  continue;
81133
81511
  throw new BroCliError(
81134
- `Can't define option '${cfg.name}': name is already in use by option '${storage2[0]}'!`
81512
+ `Can't define option '${cfg.name}' - name is already in use by option '${storage2[0]}'!`
81135
81513
  );
81136
81514
  }
81137
81515
  for (const alias of cfg.aliases) {
81138
- for (const storage2 of storageVals) {
81516
+ for (const storage2 of storedNames) {
81139
81517
  const nameOccupier = storage2.find((e2) => e2 === alias);
81140
81518
  if (!nameOccupier)
81141
81519
  continue;
81142
81520
  throw new BroCliError(
81143
- `Can't define option '${cfg.name}': alias '${alias}' is already in use by option '${storage2[0]}'!`
81521
+ `Can't define option '${cfg.name}' - alias '${alias}' is already in use by option '${storage2[0]}'!`
81144
81522
  );
81145
81523
  }
81146
81524
  }
81147
- storedNames[cfg.name] = [cfg.name, ...cfg.aliases];
81148
- storedNames[cfg.name].forEach((name, idx) => {
81149
- if (storedNames[cfg.name].findIndex((e2) => e2 === name) === idx)
81525
+ const currentNames = [cfg.name, ...cfg.aliases];
81526
+ storedNames.push(currentNames);
81527
+ currentNames.forEach((name, idx) => {
81528
+ if (currentNames.findIndex((e2) => e2 === name) === idx)
81150
81529
  return;
81151
81530
  throw new BroCliError(
81152
- `Can't define option '${cfg.name}': duplicate aliases '${name}'!`
81531
+ `Can't define option '${cfg.name}' - duplicate alias '${name}'!`
81153
81532
  );
81154
81533
  });
81155
81534
  entries.push([key, { config: cfg, $output: void 0 }]);
@@ -81170,14 +81549,17 @@ var command = (command2) => {
81170
81549
  `Can't define command '${cmd.name}' - command can't have subcommands and positional args at the same time!`
81171
81550
  );
81172
81551
  }
81552
+ if (!command2.handler && !command2.subcommands) {
81553
+ throw new BroCliError(
81554
+ `Can't define command '${cmd.name}' - command without subcommands must have a handler present!`
81555
+ );
81556
+ }
81173
81557
  const processedOptions = command2.options ? validateOptions(command2.options) : void 0;
81174
81558
  cmd.options = processedOptions;
81175
81559
  cmd.name = cmd.name ?? ((_a = cmd.aliases) == null ? void 0 : _a.shift());
81176
81560
  if (!cmd.name)
81177
81561
  throw new BroCliError(`Can't define command without name!`);
81178
81562
  cmd.aliases = ((_b = cmd.aliases) == null ? void 0 : _b.length) ? cmd.aliases : void 0;
81179
- if (!cmd.handler)
81180
- throw new BroCliError(`Can't define command '${cmd.name}' - command must have a handler!`);
81181
81563
  if (cmd.name.startsWith("-")) {
81182
81564
  throw new BroCliError(`Can't define command '${cmd.name}' - command name can't start with '-'!`);
81183
81565
  }
@@ -81207,7 +81589,7 @@ var command = (command2) => {
81207
81589
  }
81208
81590
  return cmd;
81209
81591
  };
81210
- var getCommandInner = (commands, candidates, args) => {
81592
+ var getCommandInner = (commands, candidates, args, cliName, cliDescription) => {
81211
81593
  const { data: arg, originalIndex: index4 } = candidates.shift();
81212
81594
  const command2 = commands.find((c) => {
81213
81595
  const names = c.aliases ? [c.name, ...c.aliases] : [c.name];
@@ -81228,12 +81610,20 @@ var getCommandInner = (commands, candidates, args) => {
81228
81610
  };
81229
81611
  }
81230
81612
  const newCandidates = candidates.map((c) => ({ data: c.data, originalIndex: c.originalIndex - 1 }));
81231
- const subcommand = getCommandInner(command2.subcommands, newCandidates, newArgs);
81232
- if (!subcommand.command)
81233
- throw unknownSubcommand(command2, candidates[0].data);
81613
+ const subcommand = getCommandInner(command2.subcommands, newCandidates, newArgs, cliName, cliDescription);
81614
+ if (!subcommand.command) {
81615
+ throw new BroCliError(void 0, {
81616
+ type: "error",
81617
+ violation: "unknown_subcommand_error",
81618
+ name: cliName,
81619
+ description: cliDescription,
81620
+ command: command2,
81621
+ offender: candidates[0].data
81622
+ });
81623
+ }
81234
81624
  return subcommand;
81235
81625
  };
81236
- var getCommand = (commands, args) => {
81626
+ var getCommand = (commands, args, cliName, cliDescription) => {
81237
81627
  var _a;
81238
81628
  const candidates = [];
81239
81629
  for (let i2 = 0; i2 < args.length; ++i2) {
@@ -81267,15 +81657,23 @@ var getCommand = (commands, args) => {
81267
81657
  args: removeByIndex(args, firstCandidate.originalIndex)
81268
81658
  };
81269
81659
  }
81270
- const { command: command2, args: argsRes } = getCommandInner(commands, candidates, args);
81271
- if (!command2)
81272
- throw unknownCommand(firstCandidate.data);
81660
+ const { command: command2, args: argsRes } = getCommandInner(commands, candidates, args, cliName, cliDescription);
81661
+ if (!command2) {
81662
+ throw new BroCliError(void 0, {
81663
+ type: "error",
81664
+ violation: "unknown_command_error",
81665
+ commands,
81666
+ name: cliName,
81667
+ description: cliDescription,
81668
+ offender: firstCandidate.data
81669
+ });
81670
+ }
81273
81671
  return {
81274
81672
  command: command2,
81275
81673
  args: argsRes
81276
81674
  };
81277
81675
  };
81278
- var parseArg = (options, positionals, arg, nextArg) => {
81676
+ var parseArg = (command2, options, positionals, arg, nextArg, cliName, cliDescription) => {
81279
81677
  let data = void 0;
81280
81678
  const argSplit = arg.split("=");
81281
81679
  const hasEq = arg.includes("=");
@@ -81296,8 +81694,18 @@ var parseArg = (options, positionals, arg, nextArg) => {
81296
81694
  if (!positionals.length)
81297
81695
  return {};
81298
81696
  const pos = positionals.shift();
81299
- if (pos[1].enumVals && !pos[1].enumVals.find((val2) => val2 === dataPart)) {
81300
- throw enumViolationPos(pos[1].name, arg, pos[1].enumVals);
81697
+ if (pos[1].enumVals && !pos[1].enumVals.find((val2) => val2 === arg)) {
81698
+ throw new BroCliError(void 0, {
81699
+ type: "error",
81700
+ name: cliName,
81701
+ description: cliDescription,
81702
+ violation: "enum_violation",
81703
+ command: command2,
81704
+ option: pos[1],
81705
+ offender: {
81706
+ dataPart: arg
81707
+ }
81708
+ });
81301
81709
  }
81302
81710
  data = arg;
81303
81711
  return {
@@ -81332,32 +81740,126 @@ var parseArg = (options, positionals, arg, nextArg) => {
81332
81740
  skipNext = false;
81333
81741
  return true;
81334
81742
  }
81335
- throw invalidBooleanSyntax(match2);
81743
+ throw new BroCliError(void 0, {
81744
+ type: "error",
81745
+ name: cliName,
81746
+ description: cliDescription,
81747
+ violation: "invalid_boolean_syntax",
81748
+ option: opt,
81749
+ command: command2,
81750
+ offender: {
81751
+ namePart,
81752
+ dataPart
81753
+ }
81754
+ });
81336
81755
  } else {
81337
81756
  const match2 = names.find((name) => name === namePart);
81338
81757
  if (!match2)
81339
81758
  return false;
81340
81759
  if (opt.type === "string") {
81341
- if (!hasEq && nextArg === void 0)
81342
- throw invalidStringSyntax(match2);
81760
+ if (!hasEq && nextArg === void 0) {
81761
+ throw new BroCliError(void 0, {
81762
+ type: "error",
81763
+ name: cliName,
81764
+ description: cliDescription,
81765
+ violation: "invalid_string_syntax",
81766
+ option: opt,
81767
+ command: command2,
81768
+ offender: {
81769
+ namePart,
81770
+ dataPart
81771
+ }
81772
+ });
81773
+ }
81343
81774
  if (opt.enumVals && !opt.enumVals.find((val2) => val2 === dataPart)) {
81344
- throw enumViolation(match2, dataPart, opt.enumVals);
81775
+ throw new BroCliError(void 0, {
81776
+ type: "error",
81777
+ name: cliName,
81778
+ description: cliDescription,
81779
+ violation: "enum_violation",
81780
+ option: opt,
81781
+ command: command2,
81782
+ offender: {
81783
+ namePart,
81784
+ dataPart
81785
+ }
81786
+ });
81345
81787
  }
81346
81788
  data = dataPart;
81347
81789
  return true;
81348
81790
  }
81349
- if (!hasEq && nextArg === void 0)
81350
- throw invalidNumberSyntax(match2);
81791
+ if (!hasEq && nextArg === void 0) {
81792
+ throw new BroCliError(void 0, {
81793
+ type: "error",
81794
+ name: cliName,
81795
+ description: cliDescription,
81796
+ violation: "invalid_number_syntax",
81797
+ option: opt,
81798
+ command: command2,
81799
+ offender: {
81800
+ namePart,
81801
+ dataPart
81802
+ }
81803
+ });
81804
+ }
81351
81805
  const numData = Number(dataPart);
81352
- if (isNaN(numData))
81353
- throw invalidNumberValue(match2, dataPart);
81354
- if (opt.isInt && !isInt(numData))
81355
- throw invalidInteger(match2, dataPart);
81356
- if (opt.minVal !== void 0 && numData < opt.minVal)
81357
- throw belowMin(match2, dataPart, opt.minVal);
81358
- if (opt.maxVal !== void 0 && numData > opt.maxVal)
81359
- throw aboveMax(match2, dataPart, opt.maxVal);
81360
- data = dataPart;
81806
+ if (isNaN(numData)) {
81807
+ throw new BroCliError(void 0, {
81808
+ type: "error",
81809
+ name: cliName,
81810
+ description: cliDescription,
81811
+ violation: "invalid_number_value",
81812
+ option: opt,
81813
+ command: command2,
81814
+ offender: {
81815
+ namePart,
81816
+ dataPart
81817
+ }
81818
+ });
81819
+ }
81820
+ if (opt.isInt && !isInt(numData)) {
81821
+ throw new BroCliError(void 0, {
81822
+ type: "error",
81823
+ name: cliName,
81824
+ description: cliDescription,
81825
+ violation: "expected_int",
81826
+ option: opt,
81827
+ command: command2,
81828
+ offender: {
81829
+ namePart,
81830
+ dataPart
81831
+ }
81832
+ });
81833
+ }
81834
+ if (opt.minVal !== void 0 && numData < opt.minVal) {
81835
+ throw new BroCliError(void 0, {
81836
+ type: "error",
81837
+ name: cliName,
81838
+ description: cliDescription,
81839
+ violation: "below_min",
81840
+ option: opt,
81841
+ command: command2,
81842
+ offender: {
81843
+ namePart,
81844
+ dataPart
81845
+ }
81846
+ });
81847
+ }
81848
+ if (opt.maxVal !== void 0 && numData > opt.maxVal) {
81849
+ throw new BroCliError(void 0, {
81850
+ type: "error",
81851
+ name: cliName,
81852
+ description: cliDescription,
81853
+ violation: "above_max",
81854
+ option: opt,
81855
+ command: command2,
81856
+ offender: {
81857
+ namePart,
81858
+ dataPart
81859
+ }
81860
+ });
81861
+ }
81862
+ data = numData;
81361
81863
  return true;
81362
81864
  }
81363
81865
  });
@@ -81368,7 +81870,7 @@ var parseArg = (options, positionals, arg, nextArg) => {
81368
81870
  option: option == null ? void 0 : option[1]
81369
81871
  };
81370
81872
  };
81371
- var parseOptions = (command2, args, omitKeysOfUndefinedOptions) => {
81873
+ var parseOptions = (command2, args, cliName, cliDescription, omitKeysOfUndefinedOptions) => {
81372
81874
  const options = command2.options;
81373
81875
  const optEntries = Object.entries(options ?? {}).map(
81374
81876
  (opt) => [opt[0], opt[1].config]
@@ -81388,16 +81890,16 @@ var parseOptions = (command2, args, omitKeysOfUndefinedOptions) => {
81388
81890
  skipNext,
81389
81891
  isHelp,
81390
81892
  isVersion
81391
- } = parseArg(nonPositionalEntries, positionalEntries, arg, nextArg);
81893
+ } = parseArg(command2, nonPositionalEntries, positionalEntries, arg, nextArg, cliName, cliDescription);
81392
81894
  if (!option)
81393
81895
  unrecognizedArgsArr.push(arg.split("=")[0]);
81394
81896
  if (skipNext)
81395
81897
  ++i2;
81396
- result[name] = data;
81397
81898
  if (isHelp)
81398
81899
  return "help";
81399
81900
  if (isVersion)
81400
81901
  return "version";
81902
+ result[name] = data;
81401
81903
  }
81402
81904
  for (const [optKey, option] of optEntries) {
81403
81905
  const data = result[optKey] ?? option.default;
@@ -81410,19 +81912,29 @@ var parseOptions = (command2, args, omitKeysOfUndefinedOptions) => {
81410
81912
  if (option.isRequired && result[optKey] === void 0)
81411
81913
  missingRequiredArr.push([option.name, ...option.aliases]);
81412
81914
  }
81413
- if (missingRequiredArr.length)
81414
- throw missingRequired(command2, missingRequiredArr);
81415
- if (unrecognizedArgsArr.length)
81416
- throw unrecognizedOptions(command2, unrecognizedArgsArr);
81417
- return result;
81418
- };
81419
- var executeOrLog = async (target) => {
81420
- if (!target || typeof target === "string")
81421
- console.log(target);
81422
- else
81423
- await target();
81915
+ if (missingRequiredArr.length) {
81916
+ throw new BroCliError(void 0, {
81917
+ type: "error",
81918
+ violation: "missing_args_error",
81919
+ name: cliName,
81920
+ description: cliDescription,
81921
+ command: command2,
81922
+ missing: missingRequiredArr
81923
+ });
81924
+ }
81925
+ if (unrecognizedArgsArr.length) {
81926
+ throw new BroCliError(void 0, {
81927
+ type: "error",
81928
+ violation: "unrecognized_args_error",
81929
+ name: cliName,
81930
+ description: cliDescription,
81931
+ command: command2,
81932
+ unrecognized: unrecognizedArgsArr
81933
+ });
81934
+ }
81935
+ return Object.keys(result).length ? result : void 0;
81424
81936
  };
81425
- var getCommandNameRecursive = (command2) => command2.parent ? `${getCommandNameRecursive(command2.parent)} ${command2.name}` : command2.name;
81937
+ var getCommandNameWithParents = (command2) => command2.parent ? `${getCommandNameWithParents(command2.parent)} ${command2.name}` : command2.name;
81426
81938
  var validateCommands = (commands, parent) => {
81427
81939
  const storedNames = {};
81428
81940
  for (const cmd of commands) {
@@ -81431,8 +81943,8 @@ var validateCommands = (commands, parent) => {
81431
81943
  const nameOccupier = storage2.find((e2) => e2 === cmd.name);
81432
81944
  if (!nameOccupier)
81433
81945
  continue;
81434
- throw new Error(
81435
- `Can't define command '${getCommandNameRecursive(cmd)}': name is already in use by command '${parent ? `${getCommandNameRecursive(parent)} ` : ""}${storage2[0]}'!`
81946
+ throw new BroCliError(
81947
+ `Can't define command '${getCommandNameWithParents(cmd)}': name is already in use by command '${parent ? `${getCommandNameWithParents(parent)} ` : ""}${storage2[0]}'!`
81436
81948
  );
81437
81949
  }
81438
81950
  if (cmd.aliases) {
@@ -81441,8 +81953,8 @@ var validateCommands = (commands, parent) => {
81441
81953
  const nameOccupier = storage2.find((e2) => e2 === alias);
81442
81954
  if (!nameOccupier)
81443
81955
  continue;
81444
- throw new Error(
81445
- `Can't define command '${getCommandNameRecursive(cmd)}': alias '${alias}' is already in use by command '${parent ? `${getCommandNameRecursive(parent)} ` : ""}${storage2[0]}'!`
81956
+ throw new BroCliError(
81957
+ `Can't define command '${getCommandNameWithParents(cmd)}': alias '${alias}' is already in use by command '${parent ? `${getCommandNameWithParents(parent)} ` : ""}${storage2[0]}'!`
81446
81958
  );
81447
81959
  }
81448
81960
  }
@@ -81454,53 +81966,135 @@ var validateCommands = (commands, parent) => {
81454
81966
  return commands;
81455
81967
  };
81456
81968
  var removeByIndex = (arr, idx) => [...arr.slice(0, idx), ...arr.slice(idx + 1, arr.length)];
81457
- var help = async (command2, commands, helpHandler) => typeof command2 === "object" ? command2.help !== void 0 ? await executeOrLog(command2.help) : await helpHandler(command2) : await helpHandler(commands);
81458
- var rawCli = async (commands, config) => {
81969
+ var run = async (commands, config) => {
81459
81970
  var _a, _b;
81460
- const processedCmds = validateCommands(commands);
81971
+ const eventHandler = (config == null ? void 0 : config.theme) ? eventHandlerWrapper(config.theme) : defaultEventHandler;
81461
81972
  const argSource = (config == null ? void 0 : config.argSource) ?? process.argv;
81462
81973
  const version3 = config == null ? void 0 : config.version;
81463
- const helpHandler = (config == null ? void 0 : config.help) ?? defaultTheme;
81974
+ const help = config == null ? void 0 : config.help;
81464
81975
  const omitKeysOfUndefinedOptions = (config == null ? void 0 : config.omitKeysOfUndefinedOptions) ?? false;
81465
- let args = argSource.slice(2, argSource.length);
81466
- if (!args.length)
81467
- return await helpHandler(processedCmds);
81468
- const helpIndex = args.findIndex((arg) => arg === "--help" || arg === "-h");
81469
- if (helpIndex !== -1 && (helpIndex > 0 ? ((_a = args[helpIndex - 1]) == null ? void 0 : _a.startsWith("-")) && !args[helpIndex - 1].includes("=") ? false : true : true)) {
81470
- const command3 = getCommand(processedCmds, args).command;
81471
- return help(command3, processedCmds, helpHandler);
81472
- }
81473
- const versionIndex = args.findIndex((arg) => arg === "--version" || arg === "-v");
81474
- if (versionIndex !== -1 && (versionIndex > 0 ? ((_b = args[versionIndex - 1]) == null ? void 0 : _b.startsWith("-")) ? false : true : true)) {
81475
- return await executeOrLog(version3);
81476
- }
81477
- const { command: command2, args: newArgs } = getCommand(processedCmds, args);
81478
- if (!command2)
81479
- return helpHandler(processedCmds);
81480
- if (command2 === "help") {
81481
- const { command: helpCommand } = getCommand(processedCmds, newArgs);
81482
- return help(helpCommand, processedCmds, helpHandler);
81483
- }
81484
- const optionResult = parseOptions(command2, newArgs, omitKeysOfUndefinedOptions);
81485
- if (optionResult === "help")
81486
- return await help(command2, commands, helpHandler);
81487
- if (optionResult === "version")
81488
- return await executeOrLog(version3);
81489
- if (optionResult) {
81490
- if (config == null ? void 0 : config.hook)
81491
- await config.hook("pre", command2);
81492
- await command2.handler(command2.transform ? await command2.transform(optionResult) : optionResult);
81493
- if (config == null ? void 0 : config.hook)
81494
- await config.hook("post", command2);
81495
- }
81496
- return void 0;
81497
- };
81498
- var run = async (commands, config) => {
81976
+ const cliName = config == null ? void 0 : config.name;
81977
+ const cliDescription = config == null ? void 0 : config.description;
81499
81978
  try {
81500
- await rawCli(commands, config);
81979
+ const processedCmds = validateCommands(commands);
81980
+ let args = argSource.slice(2, argSource.length);
81981
+ if (!args.length) {
81982
+ return help !== void 0 ? await executeOrLog(help) : await eventHandler({
81983
+ type: "global_help",
81984
+ description: cliDescription,
81985
+ name: cliName,
81986
+ commands: processedCmds
81987
+ });
81988
+ }
81989
+ const helpIndex = args.findIndex((arg) => arg === "--help" || arg === "-h");
81990
+ if (helpIndex !== -1 && (helpIndex > 0 ? ((_a = args[helpIndex - 1]) == null ? void 0 : _a.startsWith("-")) && !args[helpIndex - 1].includes("=") ? false : true : true)) {
81991
+ const command3 = getCommand(processedCmds, args, cliName, cliDescription).command;
81992
+ if (typeof command3 === "object") {
81993
+ return command3.help !== void 0 ? await executeOrLog(command3.help) : await eventHandler({
81994
+ type: "command_help",
81995
+ description: cliDescription,
81996
+ name: cliName,
81997
+ command: command3
81998
+ });
81999
+ } else {
82000
+ return help !== void 0 ? await executeOrLog(help) : await eventHandler({
82001
+ type: "global_help",
82002
+ description: cliDescription,
82003
+ name: cliName,
82004
+ commands: processedCmds
82005
+ });
82006
+ }
82007
+ }
82008
+ const versionIndex = args.findIndex((arg) => arg === "--version" || arg === "-v");
82009
+ if (versionIndex !== -1 && (versionIndex > 0 ? ((_b = args[versionIndex - 1]) == null ? void 0 : _b.startsWith("-")) ? false : true : true)) {
82010
+ return version3 !== void 0 ? await executeOrLog(version3) : await eventHandler({
82011
+ type: "version",
82012
+ name: cliName,
82013
+ description: cliDescription
82014
+ });
82015
+ }
82016
+ const { command: command2, args: newArgs } = getCommand(processedCmds, args, cliName, cliDescription);
82017
+ if (!command2) {
82018
+ return help !== void 0 ? await executeOrLog(help) : await eventHandler({
82019
+ type: "global_help",
82020
+ description: cliDescription,
82021
+ name: cliName,
82022
+ commands: processedCmds
82023
+ });
82024
+ }
82025
+ if (command2 === "help") {
82026
+ let helpCommand;
82027
+ let newestArgs = newArgs;
82028
+ do {
82029
+ const res = getCommand(processedCmds, newestArgs, cliName, cliDescription);
82030
+ helpCommand = res.command;
82031
+ newestArgs = res.args;
82032
+ } while (helpCommand === "help");
82033
+ return helpCommand ? helpCommand.help !== void 0 ? await executeOrLog(helpCommand.help) : await eventHandler({
82034
+ type: "command_help",
82035
+ description: cliDescription,
82036
+ name: cliName,
82037
+ command: helpCommand
82038
+ }) : help !== void 0 ? await executeOrLog(help) : await eventHandler({
82039
+ type: "global_help",
82040
+ description: cliDescription,
82041
+ name: cliName,
82042
+ commands: processedCmds
82043
+ });
82044
+ }
82045
+ const optionResult = parseOptions(command2, newArgs, cliName, cliDescription, omitKeysOfUndefinedOptions);
82046
+ if (optionResult === "help") {
82047
+ return command2.help !== void 0 ? await executeOrLog(command2.help) : await eventHandler({
82048
+ type: "command_help",
82049
+ description: cliDescription,
82050
+ name: cliName,
82051
+ command: command2
82052
+ });
82053
+ }
82054
+ if (optionResult === "version") {
82055
+ return version3 !== void 0 ? await executeOrLog(version3) : await eventHandler({
82056
+ type: "version",
82057
+ name: cliName,
82058
+ description: cliDescription
82059
+ });
82060
+ }
82061
+ if (command2.handler) {
82062
+ if (config == null ? void 0 : config.hook)
82063
+ await config.hook("before", command2);
82064
+ await command2.handler(command2.transform ? await command2.transform(optionResult) : optionResult);
82065
+ if (config == null ? void 0 : config.hook)
82066
+ await config.hook("after", command2);
82067
+ return;
82068
+ } else {
82069
+ return command2.help !== void 0 ? await executeOrLog(command2.help) : await eventHandler({
82070
+ type: "command_help",
82071
+ description: cliDescription,
82072
+ name: cliName,
82073
+ command: command2
82074
+ });
82075
+ }
81501
82076
  } catch (e2) {
81502
- console.error(typeof e2 === "object" && e2 !== null && "message" in e2 ? e2.message : e2);
81503
- process.exit(1);
82077
+ if (e2 instanceof BroCliError) {
82078
+ if (e2.event)
82079
+ await eventHandler(e2.event);
82080
+ else {
82081
+ if (!(config == null ? void 0 : config.noExit))
82082
+ console.error(e2.message);
82083
+ else
82084
+ return e2.message;
82085
+ }
82086
+ } else {
82087
+ await eventHandler({
82088
+ type: "error",
82089
+ violation: "unknown_error",
82090
+ name: cliName,
82091
+ description: cliDescription,
82092
+ error: e2
82093
+ });
82094
+ }
82095
+ if (!(config == null ? void 0 : config.noExit))
82096
+ process.exit(1);
82097
+ return;
81504
82098
  }
81505
82099
  };
81506
82100
  var OptionBuilderBase = class _OptionBuilderBase {
@@ -81578,7 +82172,7 @@ var OptionBuilderBase = class _OptionBuilderBase {
81578
82172
  max(value) {
81579
82173
  const config = this.config();
81580
82174
  const minVal = config.minVal;
81581
- if (minVal !== void 0 && minVal < value) {
82175
+ if (minVal !== void 0 && minVal > value) {
81582
82176
  throw new BroCliError("Unable to define option's max value to be lower than min value!");
81583
82177
  }
81584
82178
  return new _OptionBuilderBase({ ...config, maxVal: value });
@@ -82951,15 +83545,23 @@ var migrate = command({
82951
83545
  try {
82952
83546
  if (dialect7 === "postgresql") {
82953
83547
  if ("driver" in credentials2) {
82954
- if (credentials2.driver === "aws-data-api") {
83548
+ const { driver: driver2 } = credentials2;
83549
+ if (driver2 === "aws-data-api") {
82955
83550
  if (!await ormVersionGt("0.30.10")) {
82956
83551
  console.log(
82957
83552
  "To use 'aws-data-api' driver - please update drizzle-orm to the latest version"
82958
83553
  );
82959
83554
  process.exit(1);
82960
83555
  }
83556
+ } else if (driver2 === "pglite") {
83557
+ if (!await ormVersionGt("0.30.6")) {
83558
+ console.log(
83559
+ "To use 'pglite' driver - please update drizzle-orm to the latest version"
83560
+ );
83561
+ process.exit(1);
83562
+ }
82961
83563
  } else {
82962
- assertUnreachable(credentials2.driver);
83564
+ assertUnreachable(driver2);
82963
83565
  }
82964
83566
  }
82965
83567
  const { preparePostgresDB: preparePostgresDB2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
@@ -83088,15 +83690,23 @@ var push = command({
83088
83690
  );
83089
83691
  } else if (dialect7 === "postgresql") {
83090
83692
  if ("driver" in credentials2) {
83091
- if (credentials2.driver === "aws-data-api") {
83693
+ const { driver: driver2 } = credentials2;
83694
+ if (driver2 === "aws-data-api") {
83092
83695
  if (!await ormVersionGt("0.30.10")) {
83093
83696
  console.log(
83094
83697
  "To use 'aws-data-api' driver - please update drizzle-orm to the latest version"
83095
83698
  );
83096
83699
  process.exit(1);
83097
83700
  }
83701
+ } else if (driver2 === "pglite") {
83702
+ if (!await ormVersionGt("0.30.6")) {
83703
+ console.log(
83704
+ "To use 'pglite' driver - please update drizzle-orm to the latest version"
83705
+ );
83706
+ process.exit(1);
83707
+ }
83098
83708
  } else {
83099
- assertUnreachable(credentials2.driver);
83709
+ assertUnreachable(driver2);
83100
83710
  }
83101
83711
  }
83102
83712
  const { pgPush: pgPush2 } = await Promise.resolve().then(() => (init_push(), push_exports));
@@ -83233,15 +83843,23 @@ var pull = command({
83233
83843
  try {
83234
83844
  if (dialect7 === "postgresql") {
83235
83845
  if ("driver" in credentials2) {
83236
- if (credentials2.driver === "aws-data-api") {
83846
+ const { driver: driver2 } = credentials2;
83847
+ if (driver2 === "aws-data-api") {
83237
83848
  if (!await ormVersionGt("0.30.10")) {
83238
83849
  console.log(
83239
83850
  "To use 'aws-data-api' driver - please update drizzle-orm to the latest version"
83240
83851
  );
83241
83852
  process.exit(1);
83242
83853
  }
83854
+ } else if (driver2 === "pglite") {
83855
+ if (!await ormVersionGt("0.30.6")) {
83856
+ console.log(
83857
+ "To use 'pglite' driver - please update drizzle-orm to the latest version"
83858
+ );
83859
+ process.exit(1);
83860
+ }
83243
83861
  } else {
83244
- assertUnreachable(credentials2.driver);
83862
+ assertUnreachable(driver2);
83245
83863
  }
83246
83864
  }
83247
83865
  const { introspectPostgres: introspectPostgres2 } = await Promise.resolve().then(() => (init_introspect(), introspect_exports));
@@ -83331,15 +83949,23 @@ var studio = command({
83331
83949
  try {
83332
83950
  if (dialect7 === "postgresql") {
83333
83951
  if ("driver" in credentials2) {
83334
- if (credentials2.driver === "aws-data-api") {
83952
+ const { driver: driver2 } = credentials2;
83953
+ if (driver2 === "aws-data-api") {
83335
83954
  if (!await ormVersionGt("0.30.10")) {
83336
83955
  console.log(
83337
83956
  "To use 'aws-data-api' driver - please update drizzle-orm to the latest version"
83338
83957
  );
83339
83958
  process.exit(1);
83340
83959
  }
83960
+ } else if (driver2 === "pglite") {
83961
+ if (!await ormVersionGt("0.30.6")) {
83962
+ console.log(
83963
+ "To use 'pglite' driver - please update drizzle-orm to the latest version"
83964
+ );
83965
+ process.exit(1);
83966
+ }
83341
83967
  } else {
83342
- assertUnreachable(credentials2.driver);
83968
+ assertUnreachable(driver2);
83343
83969
  }
83344
83970
  }
83345
83971
  const { schema: schema5, relations: relations4, files } = schemaPath ? await preparePgSchema2(schemaPath) : { schema: {}, relations: {}, files: [] };
@@ -83402,7 +84028,7 @@ init_utils2();
83402
84028
  var version2 = async () => {
83403
84029
  const { npmVersion } = await ormCoreVersions();
83404
84030
  const ormVersion = npmVersion ? `drizzle-orm: v${npmVersion}` : "";
83405
- const envVersion = "0.24.0";
84031
+ const envVersion = "0.24.1-3d751e8";
83406
84032
  const kitVersion = envVersion ? `v${envVersion}` : "--";
83407
84033
  const versions = `drizzle-kit: ${kitVersion}
83408
84034
  ${ormVersion}`;
@@ -83437,6 +84063,7 @@ var legacy = [
83437
84063
  legacyCommand("check:sqlite", "check")
83438
84064
  ];
83439
84065
  run([generate, migrate, pull, push, studio, up, check, drop, ...legacy], {
84066
+ name: "drizzle-kit",
83440
84067
  version: version2
83441
84068
  });
83442
84069
  /*! Bundled license information: