@wirechunk/cli 0.0.7 → 0.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/main.js CHANGED
@@ -1,12 +1,16 @@
1
1
  #!/usr/bin/env node
2
2
  import EventEmitter from "node:events";
3
- import require$$1$1 from "node:child_process";
3
+ import require$$1$1, { spawn } from "node:child_process";
4
4
  import require$$2$2, { resolve as resolve$1 } from "node:path";
5
5
  import require$$3$1, { readFileSync, existsSync } from "node:fs";
6
6
  import process$2 from "node:process";
7
7
  import os from "node:os";
8
8
  import tty from "node:tty";
9
+ import assert from "node:assert";
9
10
  import { webcrypto, randomUUID } from "node:crypto";
11
+ import require$$5$2, { readFile, writeFile } from "node:fs/promises";
12
+ import { hash, argon2id } from "argon2";
13
+ import jwt from "jsonwebtoken";
10
14
  import { AsyncLocalStorage } from "node:async_hooks";
11
15
  import require$$1$5, { Transform } from "node:stream";
12
16
  import { pipeline } from "node:stream/promises";
@@ -22,7 +26,6 @@ import require$$0$b from "path";
22
26
  import require$$0$a from "stream";
23
27
  import require$$1$3 from "string_decoder";
24
28
  import require$$0$c from "buffer";
25
- import require$$5$2, { readFile, writeFile } from "node:fs/promises";
26
29
  import { parseEnv as parseEnv$1 } from "node:util";
27
30
  import require$$0$d from "os";
28
31
  import require$$1$4 from "tty";
@@ -31,7 +34,6 @@ import require$$5$1 from "assert";
31
34
  import require$$2$4 from "node:url";
32
35
  import require$$2$3 from "node:string_decoder";
33
36
  import require$$0$f from "zlib";
34
- import { hash, argon2id } from "argon2";
35
37
  var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
36
38
  function getDefaultExportFromCjs(x) {
37
39
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
@@ -4016,6 +4018,39 @@ const applyStyle = (self2, string2) => {
4016
4018
  Object.defineProperties(createChalk.prototype, styles);
4017
4019
  const chalk = createChalk();
4018
4020
  createChalk({ level: stderrColor ? stderrColor.level : 0 });
4021
+ const validatePasswordComplexity = (password) => {
4022
+ if (password.length < 10) {
4023
+ return {
4024
+ ok: false,
4025
+ error: "Password must be at least 10 characters long."
4026
+ };
4027
+ }
4028
+ if (password.length > 120) {
4029
+ return {
4030
+ ok: false,
4031
+ error: "Password must be at most 120 characters long."
4032
+ };
4033
+ }
4034
+ if (!/[a-zA-Z]/.test(password)) {
4035
+ return {
4036
+ ok: false,
4037
+ error: "Password must contain at least one letter."
4038
+ };
4039
+ }
4040
+ if (!/\d/.test(password)) {
4041
+ return {
4042
+ ok: false,
4043
+ error: "Password must contain at least one digit."
4044
+ };
4045
+ }
4046
+ return {
4047
+ ok: true,
4048
+ value: void 0
4049
+ };
4050
+ };
4051
+ const hashPassword = (password) => hash(password, {
4052
+ type: argon2id
4053
+ });
4019
4054
  const POOL_SIZE_MULTIPLIER = 128;
4020
4055
  let pool, poolOffset;
4021
4056
  function fillPool(bytes) {
@@ -4053,19 +4088,6 @@ function customAlphabet(alphabet2, size = 21) {
4053
4088
  }
4054
4089
  const alphabet = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
4055
4090
  const cleanSmallId = customAlphabet(alphabet, 22);
4056
- customAlphabet(alphabet, 7);
4057
- const tinyAlphabet = "23456789abcdefghijkmnopqrstuvwxyz";
4058
- const startWithLowercaseLetterPattern = /^[a-z]/;
4059
- const startsWithLowercaseLetter = (s) => startWithLowercaseLetterPattern.test(s);
4060
- const cleanLowercaseLettersAlphabet = "abcdefghijkmnopqrstuvwxyz";
4061
- const randomLowercaseLetter = () => cleanLowercaseLettersAlphabet[Math.floor(Math.random() * cleanLowercaseLettersAlphabet.length)];
4062
- const cleanTinyId = () => {
4063
- const id2 = customAlphabet(tinyAlphabet, 6)();
4064
- if (startsWithLowercaseLetter(id2)) {
4065
- return id2;
4066
- }
4067
- return `${randomLowercaseLetter()}${id2}`;
4068
- };
4069
4091
  const domainRegex = /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i;
4070
4092
  const validDomain = (domain) => domainRegex.test(domain);
4071
4093
  const removeColons = (domain) => domain.replaceAll(":", "");
@@ -4089,45 +4111,183 @@ const normalizeDomain = (domain, { allowPort = false } = {}) => {
4089
4111
  }
4090
4112
  return normalizedDomain || null;
4091
4113
  };
4092
- const extractParts = (email2) => {
4093
- const [name, domain] = email2.split("@");
4094
- return { name, domain };
4114
+ const permissionAssetEdit = {
4115
+ object: "Asset",
4116
+ action: "edit"
4095
4117
  };
4096
- const normalizeEmailAddress = (email2) => {
4097
- const emailTrimmed = email2.trim().toLowerCase();
4098
- if (!emailTrimmed) {
4099
- return { ok: false, error: "An email address is required." };
4100
- }
4101
- if (emailTrimmed.length > 60 || !emailTrimmed.includes("@") || !emailTrimmed.includes(".")) {
4102
- return {
4103
- ok: false,
4104
- error: "It does not look like the email address you provided is valid."
4105
- };
4106
- }
4107
- const { name, domain } = extractParts(emailTrimmed);
4108
- if (!name) {
4109
- return {
4110
- ok: false,
4111
- error: "It does not look like the email address you provided is valid. Please check the name."
4112
- };
4113
- }
4114
- if (!domain || !validDomain(domain)) {
4115
- return {
4116
- ok: false,
4117
- error: "It does not look like the email address you provided is valid. Please check the domain."
4118
- };
4119
- }
4120
- return { ok: true, value: emailTrimmed };
4118
+ const permissionAssetView = {
4119
+ object: "Asset",
4120
+ action: "view"
4121
4121
  };
4122
- const siteDomainKey = "siteDomain";
4123
- const submittedAtKey = "submittedAt";
4124
- const defaultNotificationEmailBodyTemplate = `Form entry from your site {{${siteDomainKey}}}:
4125
-
4126
- {{#each .}}{{@key}}: {{{.}}}
4127
- {{/each}}
4128
-
4129
- Submitted {{${submittedAtKey}}}
4130
- `;
4122
+ const permissionExtensionCreate = {
4123
+ object: "Extension",
4124
+ action: "create"
4125
+ };
4126
+ const permissionExtensionCreateVersion = {
4127
+ object: "Extension",
4128
+ action: "createVersion"
4129
+ };
4130
+ const permissionSiteCreate = {
4131
+ object: "Site",
4132
+ action: "create"
4133
+ };
4134
+ const permissionTemplateCreate = {
4135
+ object: "Template",
4136
+ action: "create"
4137
+ };
4138
+ const permissionUserCreate = {
4139
+ object: "User",
4140
+ action: "create"
4141
+ };
4142
+ const permissionPlatformEdit = {
4143
+ object: "Platform",
4144
+ action: "edit"
4145
+ };
4146
+ const permissionComponentEdit = {
4147
+ object: "Component",
4148
+ action: "edit"
4149
+ };
4150
+ const permissionCourseEdit = {
4151
+ object: "Course",
4152
+ action: "edit"
4153
+ };
4154
+ const permissionCustomComponentEdit = {
4155
+ object: "CustomComponent",
4156
+ action: "edit"
4157
+ };
4158
+ const permissionCustomFieldEdit = {
4159
+ object: "CustomField",
4160
+ action: "edit"
4161
+ };
4162
+ const permissionExtensionEdit = {
4163
+ object: "Extension",
4164
+ action: "edit"
4165
+ };
4166
+ const permissionFileUploadAsExtension = {
4167
+ object: "File",
4168
+ action: "uploadAsExtension"
4169
+ };
4170
+ const permissionHelpTicketEditStatus = {
4171
+ object: "HelpTicket",
4172
+ action: "editStatus"
4173
+ };
4174
+ const permissionSequenceEdit = {
4175
+ object: "Sequence",
4176
+ action: "edit"
4177
+ };
4178
+ const permissionSequenceUserEdit = {
4179
+ object: "SequenceUser",
4180
+ action: "edit"
4181
+ };
4182
+ const permissionSiteEdit = {
4183
+ object: "Site",
4184
+ action: "edit"
4185
+ };
4186
+ const permissionSiteEditDomain = {
4187
+ object: "Site",
4188
+ action: "editDomain"
4189
+ };
4190
+ const permissionSiteEditTls = {
4191
+ object: "Site",
4192
+ action: "editTls"
4193
+ };
4194
+ const permissionSubscriptionEdit = {
4195
+ object: "Subscription",
4196
+ action: "edit"
4197
+ };
4198
+ const permissionTemplateEdit = {
4199
+ object: "Template",
4200
+ action: "edit"
4201
+ };
4202
+ const permissionUserEditEmail = {
4203
+ object: "User",
4204
+ action: "editEmail"
4205
+ };
4206
+ const permissionUserEditOrg = {
4207
+ object: "User",
4208
+ action: "editOrg"
4209
+ };
4210
+ const permissionUserEditStatus = {
4211
+ object: "User",
4212
+ action: "editStatus"
4213
+ };
4214
+ const permissionUserEditRole = {
4215
+ object: "User",
4216
+ action: "editRole"
4217
+ };
4218
+ const permissionUserEditProfile = {
4219
+ object: "User",
4220
+ action: "editProfile"
4221
+ };
4222
+ const permissionUserEditCustomFields = {
4223
+ object: "User",
4224
+ action: "editCustomFields"
4225
+ };
4226
+ const permissionFormTemplateSync = {
4227
+ object: "FormTemplate",
4228
+ action: "sync"
4229
+ };
4230
+ const permissionPageTemplateSync = {
4231
+ object: "PageTemplate",
4232
+ action: "sync"
4233
+ };
4234
+ const permissionPlatformView = {
4235
+ object: "Platform",
4236
+ action: "view"
4237
+ };
4238
+ const permissionCourseView = {
4239
+ object: "Course",
4240
+ action: "view"
4241
+ };
4242
+ const permissionExtensionView = {
4243
+ object: "Extension",
4244
+ action: "view"
4245
+ };
4246
+ const permissionSiteView = {
4247
+ object: "Site",
4248
+ action: "view"
4249
+ };
4250
+ const permissionTemplateView = {
4251
+ object: "Template",
4252
+ action: "view"
4253
+ };
4254
+ const allPermissions = [
4255
+ permissionAssetEdit,
4256
+ permissionAssetView,
4257
+ permissionExtensionCreate,
4258
+ permissionExtensionCreateVersion,
4259
+ permissionExtensionEdit,
4260
+ permissionExtensionView,
4261
+ permissionTemplateCreate,
4262
+ permissionComponentEdit,
4263
+ permissionCourseEdit,
4264
+ permissionCustomComponentEdit,
4265
+ permissionCustomFieldEdit,
4266
+ permissionFileUploadAsExtension,
4267
+ permissionHelpTicketEditStatus,
4268
+ permissionSequenceEdit,
4269
+ permissionSequenceUserEdit,
4270
+ permissionSiteCreate,
4271
+ permissionSiteEdit,
4272
+ permissionSiteEditDomain,
4273
+ permissionSiteEditTls,
4274
+ permissionSiteView,
4275
+ permissionSubscriptionEdit,
4276
+ permissionTemplateEdit,
4277
+ permissionTemplateView,
4278
+ permissionUserCreate,
4279
+ permissionUserEditEmail,
4280
+ permissionUserEditOrg,
4281
+ permissionUserEditStatus,
4282
+ permissionUserEditRole,
4283
+ permissionUserEditProfile,
4284
+ permissionUserEditCustomFields,
4285
+ permissionFormTemplateSync,
4286
+ permissionPageTemplateSync,
4287
+ permissionPlatformEdit,
4288
+ permissionPlatformView,
4289
+ permissionCourseView
4290
+ ];
4131
4291
  var Roarr = {};
4132
4292
  var createLogger = {};
4133
4293
  var config$2 = {};
@@ -10283,11 +10443,11 @@ function isValidIP(ip, version2) {
10283
10443
  }
10284
10444
  return false;
10285
10445
  }
10286
- function isValidJWT$1(jwt, alg) {
10287
- if (!jwtRegex.test(jwt))
10446
+ function isValidJWT$1(jwt2, alg) {
10447
+ if (!jwtRegex.test(jwt2))
10288
10448
  return false;
10289
10449
  try {
10290
- const [header] = jwt.split(".");
10450
+ const [header] = jwt2.split(".");
10291
10451
  if (!header)
10292
10452
  return false;
10293
10453
  const base642 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
@@ -22868,645 +23028,137 @@ const createPool = async (connectionUri, clientConfigurationInput) => {
22868
23028
  }), pool2, clientConfiguration);
22869
23029
  };
22870
23030
  const sql = createSqlTag();
22871
- const localhostRegex1 = /localhost:\d{2,4}$/;
22872
- const localhostRegex2 = /localhost$/;
22873
- const isLocalhost = (domain) => localhostRegex1.test(domain) || localhostRegex2.test(domain);
22874
- const envFilePath = ".env";
22875
- const envLocalFilePath = ".env.local";
22876
- const hasEnvFile = existsSync(envFilePath);
22877
- const requireApiToken = (env2) => {
22878
- if (!env2.WIRECHUNK_API_TOKEN) {
22879
- console.error(
22880
- "Missing API token for authentication. Provide a WIRECHUNK_API_TOKEN environment variable."
22881
- );
22882
- process$2.exit(1);
22883
- }
22884
- return env2.WIRECHUNK_API_TOKEN;
22885
- };
22886
- const requireCoreDbUrl = (env2) => {
22887
- if (!env2.CORE_DATABASE_URL) {
22888
- if (hasEnvFile) {
22889
- console.error("Missing CORE_DATABASE_URL in environment");
22890
- } else {
22891
- console.error(`Missing CORE_DATABASE_URL in environment, no ${envFilePath} file found`);
23031
+ function $constructor(name, initializer2, params) {
23032
+ function init(inst, def) {
23033
+ if (!inst._zod) {
23034
+ Object.defineProperty(inst, "_zod", {
23035
+ value: {
23036
+ def,
23037
+ constr: _2,
23038
+ traits: /* @__PURE__ */ new Set()
23039
+ },
23040
+ enumerable: false
23041
+ });
23042
+ }
23043
+ if (inst._zod.traits.has(name)) {
23044
+ return;
23045
+ }
23046
+ inst._zod.traits.add(name);
23047
+ initializer2(inst, def);
23048
+ const proto2 = _2.prototype;
23049
+ const keys = Object.keys(proto2);
23050
+ for (let i = 0; i < keys.length; i++) {
23051
+ const k = keys[i];
23052
+ if (!(k in inst)) {
23053
+ inst[k] = proto2[k].bind(inst);
23054
+ }
22892
23055
  }
22893
- process$2.exit(1);
22894
- }
22895
- return env2.CORE_DATABASE_URL;
22896
- };
22897
- const coreServerUrlFromEnv = (env2) => {
22898
- const url = env2.CORE_SERVER_URL;
22899
- if (url) {
22900
- return url.endsWith("/api") ? url.substring(0, url.length - 4) : url;
22901
- }
22902
- const adminDomain = env2.ADMIN_DOMAIN;
22903
- if (adminDomain) {
22904
- return isLocalhost(adminDomain) ? `http://${adminDomain}` : `https://${adminDomain}`;
22905
23056
  }
22906
- return "https://wirechunk.com";
22907
- };
22908
- const parseEnv = async (envMode) => {
22909
- const env2 = {};
22910
- if (hasEnvFile) {
22911
- const envFileRaw = await readFile(envFilePath, "utf8");
22912
- Object.assign(env2, parseEnv$1(envFileRaw));
23057
+ const Parent = params?.Parent ?? Object;
23058
+ class Definition extends Parent {
22913
23059
  }
22914
- if (envMode) {
22915
- const modeFilePath = `.env.${envMode}`;
22916
- if (existsSync(modeFilePath)) {
22917
- const modeFileRaw = await readFile(modeFilePath, "utf8");
22918
- Object.assign(env2, parseEnv$1(modeFileRaw));
23060
+ Object.defineProperty(Definition, "name", { value: name });
23061
+ function _2(def) {
23062
+ var _a2;
23063
+ const inst = params?.Parent ? new Definition() : this;
23064
+ init(inst, def);
23065
+ (_a2 = inst._zod).deferred ?? (_a2.deferred = []);
23066
+ for (const fn of inst._zod.deferred) {
23067
+ fn();
22919
23068
  }
23069
+ return inst;
22920
23070
  }
22921
- if (existsSync(envLocalFilePath)) {
22922
- const envLocalFileRaw = await readFile(envLocalFilePath, "utf8");
22923
- Object.assign(env2, parseEnv$1(envLocalFileRaw));
22924
- }
22925
- if (envMode) {
22926
- const modeLocalFilePath = `.env.${envMode}.local`;
22927
- if (existsSync(modeLocalFilePath)) {
22928
- const modeLocalFileRaw = await readFile(modeLocalFilePath, "utf8");
22929
- Object.assign(env2, parseEnv$1(modeLocalFileRaw));
23071
+ Object.defineProperty(_2, "init", { value: init });
23072
+ Object.defineProperty(_2, Symbol.hasInstance, {
23073
+ value: (inst) => {
23074
+ if (params?.Parent && inst instanceof params.Parent)
23075
+ return true;
23076
+ return inst?._zod?.traits?.has(name);
22930
23077
  }
23078
+ });
23079
+ Object.defineProperty(_2, "name", { value: name });
23080
+ return _2;
23081
+ }
23082
+ class $ZodAsyncError2 extends Error {
23083
+ constructor() {
23084
+ super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
22931
23085
  }
22932
- Object.assign(env2, process$2.env);
23086
+ }
23087
+ class $ZodEncodeError2 extends Error {
23088
+ constructor(name) {
23089
+ super(`Encountered unidirectional transform during encode: ${name}`);
23090
+ this.name = "ZodEncodeError";
23091
+ }
23092
+ }
23093
+ const globalConfig = {};
23094
+ function config(newConfig) {
23095
+ return globalConfig;
23096
+ }
23097
+ function getEnumValues(entries) {
23098
+ const numericValues = Object.values(entries).filter((v) => typeof v === "number");
23099
+ const values = Object.entries(entries).filter(([k, _2]) => numericValues.indexOf(+k) === -1).map(([_2, v]) => v);
23100
+ return values;
23101
+ }
23102
+ function jsonStringifyReplacer(_2, value) {
23103
+ if (typeof value === "bigint")
23104
+ return value.toString();
23105
+ return value;
23106
+ }
23107
+ function cached(getter) {
22933
23108
  return {
22934
- ...env2,
22935
- CORE_SERVER_URL: coreServerUrlFromEnv(env2)
22936
- };
22937
- };
22938
- var dist$1 = {};
22939
- var utilities = {};
22940
- var extractJson = {};
22941
- var hasRequiredExtractJson;
22942
- function requireExtractJson() {
22943
- if (hasRequiredExtractJson) return extractJson;
22944
- hasRequiredExtractJson = 1;
22945
- Object.defineProperty(extractJson, "__esModule", {
22946
- value: true
22947
- });
22948
- extractJson.default = void 0;
22949
- const closeCharacterMap = {
22950
- '"': '"',
22951
- "[": "]",
22952
- "{": "}"
22953
- };
22954
- const defaultParser = JSON.parse.bind(JSON);
22955
- const extractJson$1 = (subject, configuration) => {
22956
- const parser2 = configuration && configuration.parser ? configuration.parser : defaultParser;
22957
- const filter2 = configuration && configuration.filter;
22958
- const foundObjects = [];
22959
- const rule2 = /["[{]/g;
22960
- let subjectOffset = 0;
22961
- while (true) {
22962
- const offsetSubject = subject.slice(subjectOffset);
22963
- const openCharacterMatch = rule2.exec(offsetSubject);
22964
- if (!openCharacterMatch) {
22965
- break;
22966
- }
22967
- const openCharacter = openCharacterMatch[0];
22968
- const closeCharacter = closeCharacterMap[openCharacter];
22969
- const startIndex = openCharacterMatch.index;
22970
- let haystack = offsetSubject.slice(startIndex);
22971
- while (haystack.length) {
22972
- if (!filter2 || filter2(haystack)) {
22973
- try {
22974
- const result2 = parser2(haystack);
22975
- foundObjects.push(result2);
22976
- subjectOffset += startIndex + haystack.length;
22977
- rule2.lastIndex = 0;
22978
- break;
22979
- } catch (error2) {
22980
- }
22981
- }
22982
- const offsetIndex = haystack.slice(0, -1).lastIndexOf(closeCharacter) + 1;
22983
- haystack = haystack.slice(0, offsetIndex);
23109
+ get value() {
23110
+ {
23111
+ const value = getter();
23112
+ Object.defineProperty(this, "value", { value });
23113
+ return value;
22984
23114
  }
22985
23115
  }
22986
- return foundObjects;
22987
23116
  };
22988
- var _default2 = extractJson$1;
22989
- extractJson.default = _default2;
22990
- return extractJson;
22991
23117
  }
22992
- var hasRequiredUtilities;
22993
- function requireUtilities() {
22994
- if (hasRequiredUtilities) return utilities;
22995
- hasRequiredUtilities = 1;
22996
- (function(exports) {
22997
- Object.defineProperty(exports, "__esModule", {
22998
- value: true
22999
- });
23000
- Object.defineProperty(exports, "extractJson", {
23001
- enumerable: true,
23002
- get: function() {
23003
- return _extractJson.default;
23004
- }
23005
- });
23006
- var _extractJson = _interopRequireDefault(requireExtractJson());
23007
- function _interopRequireDefault(obj) {
23008
- return obj && obj.__esModule ? obj : { default: obj };
23009
- }
23010
- })(utilities);
23011
- return utilities;
23118
+ function nullish(input) {
23119
+ return input === null || input === void 0;
23012
23120
  }
23013
- var hasRequiredDist$1;
23014
- function requireDist$1() {
23015
- if (hasRequiredDist$1) return dist$1;
23016
- hasRequiredDist$1 = 1;
23017
- (function(exports) {
23018
- Object.defineProperty(exports, "__esModule", {
23019
- value: true
23020
- });
23021
- Object.defineProperty(exports, "extractJson", {
23022
- enumerable: true,
23023
- get: function() {
23024
- return _utilities.extractJson;
23121
+ function cleanRegex(source2) {
23122
+ const start = source2.startsWith("^") ? 1 : 0;
23123
+ const end = source2.endsWith("$") ? source2.length - 1 : source2.length;
23124
+ return source2.slice(start, end);
23125
+ }
23126
+ const EVALUATING = Symbol("evaluating");
23127
+ function defineLazy(object2, key, getter) {
23128
+ let value = void 0;
23129
+ Object.defineProperty(object2, key, {
23130
+ get() {
23131
+ if (value === EVALUATING) {
23132
+ return void 0;
23025
23133
  }
23026
- });
23027
- var _utilities = requireUtilities();
23028
- })(dist$1);
23029
- return dist$1;
23134
+ if (value === void 0) {
23135
+ value = EVALUATING;
23136
+ value = getter();
23137
+ }
23138
+ return value;
23139
+ },
23140
+ set(v) {
23141
+ Object.defineProperty(object2, key, {
23142
+ value: v
23143
+ // configurable: true,
23144
+ });
23145
+ },
23146
+ configurable: true
23147
+ });
23030
23148
  }
23031
- var distExports = requireDist$1();
23032
- const getAutoExplainPayload = (noticeMessage) => {
23033
- const matches = distExports.extractJson(noticeMessage);
23034
- if (matches.length === 0) {
23035
- throw new Error("Notice message does not contain a recognizable JSON payload.");
23036
- }
23037
- if (matches.length > 1) {
23038
- throw new Error("Notice message contains multiple JSON payloads.");
23039
- }
23040
- return matches[0];
23041
- };
23042
- const isAutoExplainJsonMessage = (noticeMessage) => {
23043
- return noticeMessage.trim().startsWith("duration:") && noticeMessage.includes("{");
23044
- };
23045
- const toZeroIfInfinity = (value) => Number.isFinite(value) ? value : 0;
23046
- function parseNumber(milliseconds) {
23047
- return {
23048
- days: Math.trunc(milliseconds / 864e5),
23049
- hours: Math.trunc(milliseconds / 36e5 % 24),
23050
- minutes: Math.trunc(milliseconds / 6e4 % 60),
23051
- seconds: Math.trunc(milliseconds / 1e3 % 60),
23052
- milliseconds: Math.trunc(milliseconds % 1e3),
23053
- microseconds: Math.trunc(toZeroIfInfinity(milliseconds * 1e3) % 1e3),
23054
- nanoseconds: Math.trunc(toZeroIfInfinity(milliseconds * 1e6) % 1e3)
23055
- };
23056
- }
23057
- function parseBigint(milliseconds) {
23058
- return {
23059
- days: milliseconds / 86400000n,
23060
- hours: milliseconds / 3600000n % 24n,
23061
- minutes: milliseconds / 60000n % 60n,
23062
- seconds: milliseconds / 1000n % 60n,
23063
- milliseconds: milliseconds % 1000n,
23064
- microseconds: 0n,
23065
- nanoseconds: 0n
23066
- };
23067
- }
23068
- function parseMilliseconds(milliseconds) {
23069
- switch (typeof milliseconds) {
23070
- case "number": {
23071
- if (Number.isFinite(milliseconds)) {
23072
- return parseNumber(milliseconds);
23073
- }
23074
- break;
23075
- }
23076
- case "bigint": {
23077
- return parseBigint(milliseconds);
23078
- }
23079
- }
23080
- throw new TypeError("Expected a finite number or bigint");
23081
- }
23082
- const isZero = (value) => value === 0 || value === 0n;
23083
- const pluralize = (word, count) => count === 1 || count === 1n ? word : `${word}s`;
23084
- const SECOND_ROUNDING_EPSILON = 1e-7;
23085
- const ONE_DAY_IN_MILLISECONDS = 24n * 60n * 60n * 1000n;
23086
- function prettyMilliseconds(milliseconds, options) {
23087
- const isBigInt = typeof milliseconds === "bigint";
23088
- if (!isBigInt && !Number.isFinite(milliseconds)) {
23089
- throw new TypeError("Expected a finite number or bigint");
23090
- }
23091
- options = { ...options };
23092
- const sign = milliseconds < 0 ? "-" : "";
23093
- milliseconds = milliseconds < 0 ? -milliseconds : milliseconds;
23094
- if (options.colonNotation) {
23095
- options.compact = false;
23096
- options.formatSubMilliseconds = false;
23097
- options.separateMilliseconds = false;
23098
- options.verbose = false;
23099
- }
23100
- if (options.compact) {
23101
- options.unitCount = 1;
23102
- options.secondsDecimalDigits = 0;
23103
- options.millisecondsDecimalDigits = 0;
23104
- }
23105
- let result2 = [];
23106
- const floorDecimals = (value, decimalDigits) => {
23107
- const flooredInterimValue = Math.floor(value * 10 ** decimalDigits + SECOND_ROUNDING_EPSILON);
23108
- const flooredValue = Math.round(flooredInterimValue) / 10 ** decimalDigits;
23109
- return flooredValue.toFixed(decimalDigits);
23110
- };
23111
- const add = (value, long, short, valueString) => {
23112
- if ((result2.length === 0 || !options.colonNotation) && isZero(value) && !(options.colonNotation && short === "m")) {
23113
- return;
23114
- }
23115
- valueString ??= String(value);
23116
- if (options.colonNotation) {
23117
- const wholeDigits = valueString.includes(".") ? valueString.split(".")[0].length : valueString.length;
23118
- const minLength = result2.length > 0 ? 2 : 1;
23119
- valueString = "0".repeat(Math.max(0, minLength - wholeDigits)) + valueString;
23120
- } else {
23121
- valueString += options.verbose ? " " + pluralize(long, value) : short;
23122
- }
23123
- result2.push(valueString);
23124
- };
23125
- const parsed = parseMilliseconds(milliseconds);
23126
- const days = BigInt(parsed.days);
23127
- if (options.hideYearAndDays) {
23128
- add(BigInt(days) * 24n + BigInt(parsed.hours), "hour", "h");
23129
- } else {
23130
- if (options.hideYear) {
23131
- add(days, "day", "d");
23132
- } else {
23133
- add(days / 365n, "year", "y");
23134
- add(days % 365n, "day", "d");
23135
- }
23136
- add(Number(parsed.hours), "hour", "h");
23137
- }
23138
- add(Number(parsed.minutes), "minute", "m");
23139
- if (!options.hideSeconds) {
23140
- if (options.separateMilliseconds || options.formatSubMilliseconds || !options.colonNotation && milliseconds < 1e3 && !options.subSecondsAsDecimals) {
23141
- const seconds = Number(parsed.seconds);
23142
- const milliseconds2 = Number(parsed.milliseconds);
23143
- const microseconds = Number(parsed.microseconds);
23144
- const nanoseconds = Number(parsed.nanoseconds);
23145
- add(seconds, "second", "s");
23146
- if (options.formatSubMilliseconds) {
23147
- add(milliseconds2, "millisecond", "ms");
23148
- add(microseconds, "microsecond", "µs");
23149
- add(nanoseconds, "nanosecond", "ns");
23150
- } else {
23151
- const millisecondsAndBelow = milliseconds2 + microseconds / 1e3 + nanoseconds / 1e6;
23152
- const millisecondsDecimalDigits = typeof options.millisecondsDecimalDigits === "number" ? options.millisecondsDecimalDigits : 0;
23153
- const roundedMilliseconds = millisecondsAndBelow >= 1 ? Math.round(millisecondsAndBelow) : Math.ceil(millisecondsAndBelow);
23154
- const millisecondsString = millisecondsDecimalDigits ? millisecondsAndBelow.toFixed(millisecondsDecimalDigits) : roundedMilliseconds;
23155
- add(
23156
- Number.parseFloat(millisecondsString),
23157
- "millisecond",
23158
- "ms",
23159
- millisecondsString
23160
- );
23161
- }
23162
- } else {
23163
- const seconds = (isBigInt ? Number(milliseconds % ONE_DAY_IN_MILLISECONDS) : milliseconds) / 1e3 % 60;
23164
- const secondsDecimalDigits = typeof options.secondsDecimalDigits === "number" ? options.secondsDecimalDigits : 1;
23165
- const secondsFixed = floorDecimals(seconds, secondsDecimalDigits);
23166
- const secondsString = options.keepDecimalsOnWholeSeconds ? secondsFixed : secondsFixed.replace(/\.0+$/, "");
23167
- add(Number.parseFloat(secondsString), "second", "s", secondsString);
23168
- }
23169
- }
23170
- if (result2.length === 0) {
23171
- return sign + "0" + (options.verbose ? " milliseconds" : "ms");
23172
- }
23173
- const separator = options.colonNotation ? ":" : " ";
23174
- if (typeof options.unitCount === "number") {
23175
- result2 = result2.slice(0, Math.max(options.unitCount, 1));
23176
- }
23177
- return sign + result2.join(separator);
23178
- }
23179
- const errorProperties = [
23180
- {
23181
- property: "name",
23182
- enumerable: false
23183
- },
23184
- {
23185
- property: "message",
23186
- enumerable: false
23187
- },
23188
- {
23189
- property: "stack",
23190
- enumerable: false
23191
- },
23192
- {
23193
- property: "code",
23194
- enumerable: true
23195
- },
23196
- {
23197
- property: "cause",
23198
- enumerable: false
23199
- },
23200
- {
23201
- property: "errors",
23202
- enumerable: false
23203
- }
23204
- ];
23205
- const toJsonWasCalled = /* @__PURE__ */ new WeakSet();
23206
- const toJSON = (from) => {
23207
- toJsonWasCalled.add(from);
23208
- const json2 = from.toJSON();
23209
- toJsonWasCalled.delete(from);
23210
- return json2;
23211
- };
23212
- const destroyCircular = ({
23213
- from,
23214
- seen,
23215
- to,
23216
- forceEnumerable,
23217
- maxDepth,
23218
- depth,
23219
- useToJSON,
23220
- serialize
23221
- }) => {
23222
- if (!to) {
23223
- if (Array.isArray(from)) {
23224
- to = [];
23225
- } else {
23226
- to = {};
23227
- }
23228
- }
23229
- seen.push(from);
23230
- if (depth >= maxDepth) {
23231
- return to;
23232
- }
23233
- if (useToJSON && typeof from.toJSON === "function" && !toJsonWasCalled.has(from)) {
23234
- return toJSON(from);
23235
- }
23236
- const continueDestroyCircular = (value) => destroyCircular({
23237
- from: value,
23238
- seen: [...seen],
23239
- forceEnumerable,
23240
- maxDepth,
23241
- depth,
23242
- useToJSON,
23243
- serialize
23244
- });
23245
- for (const [key, value] of Object.entries(from)) {
23246
- if (value && value instanceof Uint8Array && value.constructor.name === "Buffer") {
23247
- to[key] = "[object Buffer]";
23248
- continue;
23249
- }
23250
- if (value !== null && typeof value === "object" && typeof value.pipe === "function") {
23251
- to[key] = "[object Stream]";
23252
- continue;
23253
- }
23254
- if (typeof value === "function") {
23255
- continue;
23256
- }
23257
- if (!value || typeof value !== "object") {
23258
- try {
23259
- to[key] = value;
23260
- } catch {
23261
- }
23262
- continue;
23263
- }
23264
- if (!seen.includes(from[key])) {
23265
- depth++;
23266
- to[key] = continueDestroyCircular(from[key]);
23267
- continue;
23268
- }
23269
- to[key] = "[Circular]";
23270
- }
23271
- {
23272
- for (const { property, enumerable } of errorProperties) {
23273
- if (from[property] !== void 0 && from[property] !== null) {
23274
- Object.defineProperty(to, property, {
23275
- value: isErrorLike(from[property]) || Array.isArray(from[property]) ? continueDestroyCircular(from[property]) : from[property],
23276
- enumerable: true,
23277
- configurable: true,
23278
- writable: true
23279
- });
23280
- }
23281
- }
23282
- }
23283
- return to;
23284
- };
23285
- function serializeError(value, options = {}) {
23286
- const {
23287
- maxDepth = Number.POSITIVE_INFINITY,
23288
- useToJSON = true
23289
- } = options;
23290
- if (typeof value === "object" && value !== null) {
23291
- return destroyCircular({
23292
- from: value,
23293
- seen: [],
23294
- forceEnumerable: true,
23295
- maxDepth,
23296
- depth: 0,
23297
- useToJSON,
23298
- serialize: true
23299
- });
23300
- }
23301
- if (typeof value === "function") {
23302
- return `[Function: ${value.name || "anonymous"}]`;
23303
- }
23304
- return value;
23305
- }
23306
- function isErrorLike(value) {
23307
- return Boolean(value) && typeof value === "object" && typeof value.name === "string" && typeof value.message === "string" && typeof value.stack === "string";
23308
- }
23309
- const stringifyCallSite = (callSite) => {
23310
- return (callSite.fileName || "") + ":" + callSite.lineNumber + ":" + callSite.columnNumber;
23311
- };
23312
- const defaultConfiguration = {
23313
- logValues: true
23314
- };
23315
- const createQueryLoggingInterceptor = (userConfiguration) => {
23316
- const configuration = {
23317
- ...defaultConfiguration,
23318
- ...userConfiguration
23319
- };
23320
- return {
23321
- afterQueryExecution: (context, query2, result2) => {
23322
- let rowCount = null;
23323
- if (result2.rowCount) {
23324
- rowCount = result2.rowCount;
23325
- }
23326
- for (const notice of result2.notices) {
23327
- if (!notice.message) {
23328
- continue;
23329
- }
23330
- if (isAutoExplainJsonMessage(notice.message)) {
23331
- context.log.info({
23332
- autoExplain: getAutoExplainPayload(notice.message)
23333
- }, "auto explain");
23334
- }
23335
- }
23336
- context.log.debug({
23337
- executionTime: prettyMilliseconds(Number(process.hrtime.bigint() - BigInt(context.queryInputTime)) / 1e6),
23338
- rowCount
23339
- }, "query execution result");
23340
- return null;
23341
- },
23342
- beforeQueryExecution: async (context, query2) => {
23343
- let stackTrace;
23344
- if (context.stackTrace) {
23345
- stackTrace = [];
23346
- for (const callSite of context.stackTrace) {
23347
- if (callSite.fileName !== null && !callSite.fileName.includes("node_modules/slonik/") && !callSite.fileName.includes("next_tick")) {
23348
- stackTrace.push(stringifyCallSite(callSite));
23349
- }
23350
- }
23351
- }
23352
- let values;
23353
- if (configuration.logValues) {
23354
- values = [];
23355
- for (const value of query2.values) {
23356
- if (Buffer.isBuffer(value)) {
23357
- values.push("[Buffer " + value.byteLength + "]");
23358
- } else {
23359
- values.push(value);
23360
- }
23361
- }
23362
- }
23363
- context.log.debug({
23364
- sql: query2.sql,
23365
- stackTrace,
23366
- values
23367
- }, "executing query");
23368
- return null;
23369
- },
23370
- name: "slonik-interceptor-query-logging",
23371
- queryExecutionError: (context, query2, error2) => {
23372
- context.log.error({
23373
- error: serializeError(error2)
23374
- }, "query execution produced an error");
23375
- return null;
23376
- }
23377
- };
23378
- };
23379
- function $constructor(name, initializer2, params) {
23380
- function init(inst, def) {
23381
- if (!inst._zod) {
23382
- Object.defineProperty(inst, "_zod", {
23383
- value: {
23384
- def,
23385
- constr: _2,
23386
- traits: /* @__PURE__ */ new Set()
23387
- },
23388
- enumerable: false
23389
- });
23390
- }
23391
- if (inst._zod.traits.has(name)) {
23392
- return;
23393
- }
23394
- inst._zod.traits.add(name);
23395
- initializer2(inst, def);
23396
- const proto2 = _2.prototype;
23397
- const keys = Object.keys(proto2);
23398
- for (let i = 0; i < keys.length; i++) {
23399
- const k = keys[i];
23400
- if (!(k in inst)) {
23401
- inst[k] = proto2[k].bind(inst);
23402
- }
23403
- }
23404
- }
23405
- const Parent = params?.Parent ?? Object;
23406
- class Definition extends Parent {
23407
- }
23408
- Object.defineProperty(Definition, "name", { value: name });
23409
- function _2(def) {
23410
- var _a2;
23411
- const inst = params?.Parent ? new Definition() : this;
23412
- init(inst, def);
23413
- (_a2 = inst._zod).deferred ?? (_a2.deferred = []);
23414
- for (const fn of inst._zod.deferred) {
23415
- fn();
23416
- }
23417
- return inst;
23418
- }
23419
- Object.defineProperty(_2, "init", { value: init });
23420
- Object.defineProperty(_2, Symbol.hasInstance, {
23421
- value: (inst) => {
23422
- if (params?.Parent && inst instanceof params.Parent)
23423
- return true;
23424
- return inst?._zod?.traits?.has(name);
23425
- }
23426
- });
23427
- Object.defineProperty(_2, "name", { value: name });
23428
- return _2;
23429
- }
23430
- class $ZodAsyncError2 extends Error {
23431
- constructor() {
23432
- super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
23433
- }
23434
- }
23435
- class $ZodEncodeError2 extends Error {
23436
- constructor(name) {
23437
- super(`Encountered unidirectional transform during encode: ${name}`);
23438
- this.name = "ZodEncodeError";
23439
- }
23440
- }
23441
- const globalConfig = {};
23442
- function config(newConfig) {
23443
- return globalConfig;
23444
- }
23445
- function getEnumValues(entries) {
23446
- const numericValues = Object.values(entries).filter((v) => typeof v === "number");
23447
- const values = Object.entries(entries).filter(([k, _2]) => numericValues.indexOf(+k) === -1).map(([_2, v]) => v);
23448
- return values;
23449
- }
23450
- function jsonStringifyReplacer(_2, value) {
23451
- if (typeof value === "bigint")
23452
- return value.toString();
23453
- return value;
23454
- }
23455
- function cached(getter) {
23456
- return {
23457
- get value() {
23458
- {
23459
- const value = getter();
23460
- Object.defineProperty(this, "value", { value });
23461
- return value;
23462
- }
23463
- }
23464
- };
23465
- }
23466
- function nullish(input) {
23467
- return input === null || input === void 0;
23468
- }
23469
- function cleanRegex(source2) {
23470
- const start = source2.startsWith("^") ? 1 : 0;
23471
- const end = source2.endsWith("$") ? source2.length - 1 : source2.length;
23472
- return source2.slice(start, end);
23473
- }
23474
- const EVALUATING = Symbol("evaluating");
23475
- function defineLazy(object2, key, getter) {
23476
- let value = void 0;
23477
- Object.defineProperty(object2, key, {
23478
- get() {
23479
- if (value === EVALUATING) {
23480
- return void 0;
23481
- }
23482
- if (value === void 0) {
23483
- value = EVALUATING;
23484
- value = getter();
23485
- }
23486
- return value;
23487
- },
23488
- set(v) {
23489
- Object.defineProperty(object2, key, {
23490
- value: v
23491
- // configurable: true,
23492
- });
23493
- },
23494
- configurable: true
23495
- });
23496
- }
23497
- function assignProp(target, prop, value) {
23498
- Object.defineProperty(target, prop, {
23499
- value,
23500
- writable: true,
23501
- enumerable: true,
23502
- configurable: true
23503
- });
23504
- }
23505
- function mergeDefs(...defs) {
23506
- const mergedDescriptors = {};
23507
- for (const def of defs) {
23508
- const descriptors = Object.getOwnPropertyDescriptors(def);
23509
- Object.assign(mergedDescriptors, descriptors);
23149
+ function assignProp(target, prop, value) {
23150
+ Object.defineProperty(target, prop, {
23151
+ value,
23152
+ writable: true,
23153
+ enumerable: true,
23154
+ configurable: true
23155
+ });
23156
+ }
23157
+ function mergeDefs(...defs) {
23158
+ const mergedDescriptors = {};
23159
+ for (const def of defs) {
23160
+ const descriptors = Object.getOwnPropertyDescriptors(def);
23161
+ Object.assign(mergedDescriptors, descriptors);
23510
23162
  }
23511
23163
  return Object.defineProperties({}, mergedDescriptors);
23512
23164
  }
@@ -26158,202 +25810,715 @@ function intersection(left, right) {
26158
25810
  left,
26159
25811
  right
26160
25812
  });
26161
- }
26162
- const ZodEnum2 = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {
26163
- $ZodEnum.init(inst, def);
26164
- ZodType2.init(inst, def);
26165
- inst.enum = def.entries;
26166
- inst.options = Object.values(def.entries);
26167
- const keys = new Set(Object.keys(def.entries));
26168
- inst.extract = (values, params) => {
26169
- const newEntries = {};
26170
- for (const value of values) {
26171
- if (keys.has(value)) {
26172
- newEntries[value] = def.entries[value];
26173
- } else
26174
- throw new Error(`Key ${value} not found in enum`);
25813
+ }
25814
+ const ZodEnum2 = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {
25815
+ $ZodEnum.init(inst, def);
25816
+ ZodType2.init(inst, def);
25817
+ inst.enum = def.entries;
25818
+ inst.options = Object.values(def.entries);
25819
+ const keys = new Set(Object.keys(def.entries));
25820
+ inst.extract = (values, params) => {
25821
+ const newEntries = {};
25822
+ for (const value of values) {
25823
+ if (keys.has(value)) {
25824
+ newEntries[value] = def.entries[value];
25825
+ } else
25826
+ throw new Error(`Key ${value} not found in enum`);
25827
+ }
25828
+ return new ZodEnum2({
25829
+ ...def,
25830
+ checks: [],
25831
+ ...normalizeParams(params),
25832
+ entries: newEntries
25833
+ });
25834
+ };
25835
+ inst.exclude = (values, params) => {
25836
+ const newEntries = { ...def.entries };
25837
+ for (const value of values) {
25838
+ if (keys.has(value)) {
25839
+ delete newEntries[value];
25840
+ } else
25841
+ throw new Error(`Key ${value} not found in enum`);
25842
+ }
25843
+ return new ZodEnum2({
25844
+ ...def,
25845
+ checks: [],
25846
+ ...normalizeParams(params),
25847
+ entries: newEntries
25848
+ });
25849
+ };
25850
+ });
25851
+ function _enum$1(values, params) {
25852
+ const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
25853
+ return new ZodEnum2({
25854
+ type: "enum",
25855
+ entries,
25856
+ ...normalizeParams(params)
25857
+ });
25858
+ }
25859
+ const ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
25860
+ $ZodTransform.init(inst, def);
25861
+ ZodType2.init(inst, def);
25862
+ inst._zod.parse = (payload, _ctx) => {
25863
+ if (_ctx.direction === "backward") {
25864
+ throw new $ZodEncodeError2(inst.constructor.name);
25865
+ }
25866
+ payload.addIssue = (issue$12) => {
25867
+ if (typeof issue$12 === "string") {
25868
+ payload.issues.push(issue(issue$12, payload.value, def));
25869
+ } else {
25870
+ const _issue = issue$12;
25871
+ if (_issue.fatal)
25872
+ _issue.continue = false;
25873
+ _issue.code ?? (_issue.code = "custom");
25874
+ _issue.input ?? (_issue.input = payload.value);
25875
+ _issue.inst ?? (_issue.inst = inst);
25876
+ payload.issues.push(issue(_issue));
25877
+ }
25878
+ };
25879
+ const output = def.transform(payload.value, payload);
25880
+ if (output instanceof Promise) {
25881
+ return output.then((output2) => {
25882
+ payload.value = output2;
25883
+ return payload;
25884
+ });
25885
+ }
25886
+ payload.value = output;
25887
+ return payload;
25888
+ };
25889
+ });
25890
+ function transform$2(fn) {
25891
+ return new ZodTransform({
25892
+ type: "transform",
25893
+ transform: fn
25894
+ });
25895
+ }
25896
+ const ZodOptional2 = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => {
25897
+ $ZodOptional.init(inst, def);
25898
+ ZodType2.init(inst, def);
25899
+ inst.unwrap = () => inst._zod.def.innerType;
25900
+ });
25901
+ function optional(innerType) {
25902
+ return new ZodOptional2({
25903
+ type: "optional",
25904
+ innerType
25905
+ });
25906
+ }
25907
+ const ZodNullable2 = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => {
25908
+ $ZodNullable.init(inst, def);
25909
+ ZodType2.init(inst, def);
25910
+ inst.unwrap = () => inst._zod.def.innerType;
25911
+ });
25912
+ function nullable(innerType) {
25913
+ return new ZodNullable2({
25914
+ type: "nullable",
25915
+ innerType
25916
+ });
25917
+ }
25918
+ const ZodDefault2 = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => {
25919
+ $ZodDefault.init(inst, def);
25920
+ ZodType2.init(inst, def);
25921
+ inst.unwrap = () => inst._zod.def.innerType;
25922
+ inst.removeDefault = inst.unwrap;
25923
+ });
25924
+ function _default(innerType, defaultValue) {
25925
+ return new ZodDefault2({
25926
+ type: "default",
25927
+ innerType,
25928
+ get defaultValue() {
25929
+ return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
25930
+ }
25931
+ });
25932
+ }
25933
+ const ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => {
25934
+ $ZodPrefault.init(inst, def);
25935
+ ZodType2.init(inst, def);
25936
+ inst.unwrap = () => inst._zod.def.innerType;
25937
+ });
25938
+ function prefault(innerType, defaultValue) {
25939
+ return new ZodPrefault({
25940
+ type: "prefault",
25941
+ innerType,
25942
+ get defaultValue() {
25943
+ return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
25944
+ }
25945
+ });
25946
+ }
25947
+ const ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => {
25948
+ $ZodNonOptional.init(inst, def);
25949
+ ZodType2.init(inst, def);
25950
+ inst.unwrap = () => inst._zod.def.innerType;
25951
+ });
25952
+ function nonoptional(innerType, params) {
25953
+ return new ZodNonOptional({
25954
+ type: "nonoptional",
25955
+ innerType,
25956
+ ...normalizeParams(params)
25957
+ });
25958
+ }
25959
+ const ZodCatch2 = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => {
25960
+ $ZodCatch.init(inst, def);
25961
+ ZodType2.init(inst, def);
25962
+ inst.unwrap = () => inst._zod.def.innerType;
25963
+ inst.removeCatch = inst.unwrap;
25964
+ });
25965
+ function _catch(innerType, catchValue) {
25966
+ return new ZodCatch2({
25967
+ type: "catch",
25968
+ innerType,
25969
+ catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
25970
+ });
25971
+ }
25972
+ const ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => {
25973
+ $ZodPipe.init(inst, def);
25974
+ ZodType2.init(inst, def);
25975
+ inst.in = def.in;
25976
+ inst.out = def.out;
25977
+ });
25978
+ function pipe(in_, out) {
25979
+ return new ZodPipe({
25980
+ type: "pipe",
25981
+ in: in_,
25982
+ out
25983
+ // ...util.normalizeParams(params),
25984
+ });
25985
+ }
25986
+ const ZodReadonly2 = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => {
25987
+ $ZodReadonly.init(inst, def);
25988
+ ZodType2.init(inst, def);
25989
+ inst.unwrap = () => inst._zod.def.innerType;
25990
+ });
25991
+ function readonly(innerType) {
25992
+ return new ZodReadonly2({
25993
+ type: "readonly",
25994
+ innerType
25995
+ });
25996
+ }
25997
+ const ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => {
25998
+ $ZodCustom.init(inst, def);
25999
+ ZodType2.init(inst, def);
26000
+ });
26001
+ function refine(fn, _params = {}) {
26002
+ return _refine(ZodCustom, fn, _params);
26003
+ }
26004
+ function superRefine(fn) {
26005
+ return _superRefine(fn);
26006
+ }
26007
+ const localhostRegex1 = /localhost:\d{2,4}$/;
26008
+ const localhostRegex2 = /localhost$/;
26009
+ const isLocalhost = (domain) => localhostRegex1.test(domain) || localhostRegex2.test(domain);
26010
+ const envFilePath = ".env";
26011
+ const envLocalFilePath = ".env.local";
26012
+ const hasEnvFile = existsSync(envFilePath);
26013
+ const requireApiToken = (env2) => {
26014
+ if (!env2.WIRECHUNK_API_TOKEN) {
26015
+ console.error(
26016
+ "Missing API token for authentication. Provide a WIRECHUNK_API_TOKEN environment variable."
26017
+ );
26018
+ process$2.exit(1);
26019
+ }
26020
+ return env2.WIRECHUNK_API_TOKEN;
26021
+ };
26022
+ const requireCoreDbUrl = (env2) => {
26023
+ const url = env2.WIRECHUNK_CORE_DATABASE_URL;
26024
+ if (!url) {
26025
+ const message = "Missing WIRECHUNK_CORE_DATABASE_URL in environment";
26026
+ if (hasEnvFile) {
26027
+ console.error(message);
26028
+ } else {
26029
+ console.error(`${message}, no ${envFilePath} file found`);
26030
+ }
26031
+ process$2.exit(1);
26032
+ }
26033
+ return url;
26034
+ };
26035
+ const coreServerUrlFromEnv = (env2) => {
26036
+ const url = env2.WIRECHUNK_CORE_SERVER_URL;
26037
+ if (url) {
26038
+ return url.endsWith("/api") ? url.substring(0, url.length - 4) : url;
26039
+ }
26040
+ const adminDomain = env2.ADMIN_DOMAIN;
26041
+ if (adminDomain) {
26042
+ return isLocalhost(adminDomain) ? `http://${adminDomain}` : `https://${adminDomain}`;
26043
+ }
26044
+ return "https://wirechunk.com";
26045
+ };
26046
+ const parseEnv = async (envMode) => {
26047
+ const env2 = {};
26048
+ if (hasEnvFile) {
26049
+ const envFileRaw = await readFile(envFilePath, "utf8");
26050
+ Object.assign(env2, parseEnv$1(envFileRaw));
26051
+ }
26052
+ if (envMode) {
26053
+ const modeFilePath = `.env.${envMode}`;
26054
+ if (existsSync(modeFilePath)) {
26055
+ const modeFileRaw = await readFile(modeFilePath, "utf8");
26056
+ Object.assign(env2, parseEnv$1(modeFileRaw));
26057
+ }
26058
+ }
26059
+ if (existsSync(envLocalFilePath)) {
26060
+ const envLocalFileRaw = await readFile(envLocalFilePath, "utf8");
26061
+ Object.assign(env2, parseEnv$1(envLocalFileRaw));
26062
+ }
26063
+ if (envMode) {
26064
+ const modeLocalFilePath = `.env.${envMode}.local`;
26065
+ if (existsSync(modeLocalFilePath)) {
26066
+ const modeLocalFileRaw = await readFile(modeLocalFilePath, "utf8");
26067
+ Object.assign(env2, parseEnv$1(modeLocalFileRaw));
26068
+ }
26069
+ }
26070
+ Object.assign(env2, process$2.env);
26071
+ return {
26072
+ ...env2,
26073
+ WIRECHUNK_CORE_SERVER_URL: coreServerUrlFromEnv(env2)
26074
+ };
26075
+ };
26076
+ var dist$1 = {};
26077
+ var utilities = {};
26078
+ var extractJson = {};
26079
+ var hasRequiredExtractJson;
26080
+ function requireExtractJson() {
26081
+ if (hasRequiredExtractJson) return extractJson;
26082
+ hasRequiredExtractJson = 1;
26083
+ Object.defineProperty(extractJson, "__esModule", {
26084
+ value: true
26085
+ });
26086
+ extractJson.default = void 0;
26087
+ const closeCharacterMap = {
26088
+ '"': '"',
26089
+ "[": "]",
26090
+ "{": "}"
26091
+ };
26092
+ const defaultParser = JSON.parse.bind(JSON);
26093
+ const extractJson$1 = (subject, configuration) => {
26094
+ const parser2 = configuration && configuration.parser ? configuration.parser : defaultParser;
26095
+ const filter2 = configuration && configuration.filter;
26096
+ const foundObjects = [];
26097
+ const rule2 = /["[{]/g;
26098
+ let subjectOffset = 0;
26099
+ while (true) {
26100
+ const offsetSubject = subject.slice(subjectOffset);
26101
+ const openCharacterMatch = rule2.exec(offsetSubject);
26102
+ if (!openCharacterMatch) {
26103
+ break;
26104
+ }
26105
+ const openCharacter = openCharacterMatch[0];
26106
+ const closeCharacter = closeCharacterMap[openCharacter];
26107
+ const startIndex = openCharacterMatch.index;
26108
+ let haystack = offsetSubject.slice(startIndex);
26109
+ while (haystack.length) {
26110
+ if (!filter2 || filter2(haystack)) {
26111
+ try {
26112
+ const result2 = parser2(haystack);
26113
+ foundObjects.push(result2);
26114
+ subjectOffset += startIndex + haystack.length;
26115
+ rule2.lastIndex = 0;
26116
+ break;
26117
+ } catch (error2) {
26118
+ }
26119
+ }
26120
+ const offsetIndex = haystack.slice(0, -1).lastIndexOf(closeCharacter) + 1;
26121
+ haystack = haystack.slice(0, offsetIndex);
26122
+ }
26123
+ }
26124
+ return foundObjects;
26125
+ };
26126
+ var _default2 = extractJson$1;
26127
+ extractJson.default = _default2;
26128
+ return extractJson;
26129
+ }
26130
+ var hasRequiredUtilities;
26131
+ function requireUtilities() {
26132
+ if (hasRequiredUtilities) return utilities;
26133
+ hasRequiredUtilities = 1;
26134
+ (function(exports) {
26135
+ Object.defineProperty(exports, "__esModule", {
26136
+ value: true
26137
+ });
26138
+ Object.defineProperty(exports, "extractJson", {
26139
+ enumerable: true,
26140
+ get: function() {
26141
+ return _extractJson.default;
26142
+ }
26143
+ });
26144
+ var _extractJson = _interopRequireDefault(requireExtractJson());
26145
+ function _interopRequireDefault(obj) {
26146
+ return obj && obj.__esModule ? obj : { default: obj };
26147
+ }
26148
+ })(utilities);
26149
+ return utilities;
26150
+ }
26151
+ var hasRequiredDist$1;
26152
+ function requireDist$1() {
26153
+ if (hasRequiredDist$1) return dist$1;
26154
+ hasRequiredDist$1 = 1;
26155
+ (function(exports) {
26156
+ Object.defineProperty(exports, "__esModule", {
26157
+ value: true
26158
+ });
26159
+ Object.defineProperty(exports, "extractJson", {
26160
+ enumerable: true,
26161
+ get: function() {
26162
+ return _utilities.extractJson;
26163
+ }
26164
+ });
26165
+ var _utilities = requireUtilities();
26166
+ })(dist$1);
26167
+ return dist$1;
26168
+ }
26169
+ var distExports = requireDist$1();
26170
+ const getAutoExplainPayload = (noticeMessage) => {
26171
+ const matches = distExports.extractJson(noticeMessage);
26172
+ if (matches.length === 0) {
26173
+ throw new Error("Notice message does not contain a recognizable JSON payload.");
26174
+ }
26175
+ if (matches.length > 1) {
26176
+ throw new Error("Notice message contains multiple JSON payloads.");
26177
+ }
26178
+ return matches[0];
26179
+ };
26180
+ const isAutoExplainJsonMessage = (noticeMessage) => {
26181
+ return noticeMessage.trim().startsWith("duration:") && noticeMessage.includes("{");
26182
+ };
26183
+ const toZeroIfInfinity = (value) => Number.isFinite(value) ? value : 0;
26184
+ function parseNumber(milliseconds) {
26185
+ return {
26186
+ days: Math.trunc(milliseconds / 864e5),
26187
+ hours: Math.trunc(milliseconds / 36e5 % 24),
26188
+ minutes: Math.trunc(milliseconds / 6e4 % 60),
26189
+ seconds: Math.trunc(milliseconds / 1e3 % 60),
26190
+ milliseconds: Math.trunc(milliseconds % 1e3),
26191
+ microseconds: Math.trunc(toZeroIfInfinity(milliseconds * 1e3) % 1e3),
26192
+ nanoseconds: Math.trunc(toZeroIfInfinity(milliseconds * 1e6) % 1e3)
26193
+ };
26194
+ }
26195
+ function parseBigint(milliseconds) {
26196
+ return {
26197
+ days: milliseconds / 86400000n,
26198
+ hours: milliseconds / 3600000n % 24n,
26199
+ minutes: milliseconds / 60000n % 60n,
26200
+ seconds: milliseconds / 1000n % 60n,
26201
+ milliseconds: milliseconds % 1000n,
26202
+ microseconds: 0n,
26203
+ nanoseconds: 0n
26204
+ };
26205
+ }
26206
+ function parseMilliseconds(milliseconds) {
26207
+ switch (typeof milliseconds) {
26208
+ case "number": {
26209
+ if (Number.isFinite(milliseconds)) {
26210
+ return parseNumber(milliseconds);
26211
+ }
26212
+ break;
26213
+ }
26214
+ case "bigint": {
26215
+ return parseBigint(milliseconds);
26216
+ }
26217
+ }
26218
+ throw new TypeError("Expected a finite number or bigint");
26219
+ }
26220
+ const isZero = (value) => value === 0 || value === 0n;
26221
+ const pluralize = (word, count) => count === 1 || count === 1n ? word : `${word}s`;
26222
+ const SECOND_ROUNDING_EPSILON = 1e-7;
26223
+ const ONE_DAY_IN_MILLISECONDS = 24n * 60n * 60n * 1000n;
26224
+ function prettyMilliseconds(milliseconds, options) {
26225
+ const isBigInt = typeof milliseconds === "bigint";
26226
+ if (!isBigInt && !Number.isFinite(milliseconds)) {
26227
+ throw new TypeError("Expected a finite number or bigint");
26228
+ }
26229
+ options = { ...options };
26230
+ const sign = milliseconds < 0 ? "-" : "";
26231
+ milliseconds = milliseconds < 0 ? -milliseconds : milliseconds;
26232
+ if (options.colonNotation) {
26233
+ options.compact = false;
26234
+ options.formatSubMilliseconds = false;
26235
+ options.separateMilliseconds = false;
26236
+ options.verbose = false;
26237
+ }
26238
+ if (options.compact) {
26239
+ options.unitCount = 1;
26240
+ options.secondsDecimalDigits = 0;
26241
+ options.millisecondsDecimalDigits = 0;
26242
+ }
26243
+ let result2 = [];
26244
+ const floorDecimals = (value, decimalDigits) => {
26245
+ const flooredInterimValue = Math.floor(value * 10 ** decimalDigits + SECOND_ROUNDING_EPSILON);
26246
+ const flooredValue = Math.round(flooredInterimValue) / 10 ** decimalDigits;
26247
+ return flooredValue.toFixed(decimalDigits);
26248
+ };
26249
+ const add = (value, long, short, valueString) => {
26250
+ if ((result2.length === 0 || !options.colonNotation) && isZero(value) && !(options.colonNotation && short === "m")) {
26251
+ return;
26252
+ }
26253
+ valueString ??= String(value);
26254
+ if (options.colonNotation) {
26255
+ const wholeDigits = valueString.includes(".") ? valueString.split(".")[0].length : valueString.length;
26256
+ const minLength = result2.length > 0 ? 2 : 1;
26257
+ valueString = "0".repeat(Math.max(0, minLength - wholeDigits)) + valueString;
26258
+ } else {
26259
+ valueString += options.verbose ? " " + pluralize(long, value) : short;
26260
+ }
26261
+ result2.push(valueString);
26262
+ };
26263
+ const parsed = parseMilliseconds(milliseconds);
26264
+ const days = BigInt(parsed.days);
26265
+ if (options.hideYearAndDays) {
26266
+ add(BigInt(days) * 24n + BigInt(parsed.hours), "hour", "h");
26267
+ } else {
26268
+ if (options.hideYear) {
26269
+ add(days, "day", "d");
26270
+ } else {
26271
+ add(days / 365n, "year", "y");
26272
+ add(days % 365n, "day", "d");
26273
+ }
26274
+ add(Number(parsed.hours), "hour", "h");
26275
+ }
26276
+ add(Number(parsed.minutes), "minute", "m");
26277
+ if (!options.hideSeconds) {
26278
+ if (options.separateMilliseconds || options.formatSubMilliseconds || !options.colonNotation && milliseconds < 1e3 && !options.subSecondsAsDecimals) {
26279
+ const seconds = Number(parsed.seconds);
26280
+ const milliseconds2 = Number(parsed.milliseconds);
26281
+ const microseconds = Number(parsed.microseconds);
26282
+ const nanoseconds = Number(parsed.nanoseconds);
26283
+ add(seconds, "second", "s");
26284
+ if (options.formatSubMilliseconds) {
26285
+ add(milliseconds2, "millisecond", "ms");
26286
+ add(microseconds, "microsecond", "µs");
26287
+ add(nanoseconds, "nanosecond", "ns");
26288
+ } else {
26289
+ const millisecondsAndBelow = milliseconds2 + microseconds / 1e3 + nanoseconds / 1e6;
26290
+ const millisecondsDecimalDigits = typeof options.millisecondsDecimalDigits === "number" ? options.millisecondsDecimalDigits : 0;
26291
+ const roundedMilliseconds = millisecondsAndBelow >= 1 ? Math.round(millisecondsAndBelow) : Math.ceil(millisecondsAndBelow);
26292
+ const millisecondsString = millisecondsDecimalDigits ? millisecondsAndBelow.toFixed(millisecondsDecimalDigits) : roundedMilliseconds;
26293
+ add(
26294
+ Number.parseFloat(millisecondsString),
26295
+ "millisecond",
26296
+ "ms",
26297
+ millisecondsString
26298
+ );
26299
+ }
26300
+ } else {
26301
+ const seconds = (isBigInt ? Number(milliseconds % ONE_DAY_IN_MILLISECONDS) : milliseconds) / 1e3 % 60;
26302
+ const secondsDecimalDigits = typeof options.secondsDecimalDigits === "number" ? options.secondsDecimalDigits : 1;
26303
+ const secondsFixed = floorDecimals(seconds, secondsDecimalDigits);
26304
+ const secondsString = options.keepDecimalsOnWholeSeconds ? secondsFixed : secondsFixed.replace(/\.0+$/, "");
26305
+ add(Number.parseFloat(secondsString), "second", "s", secondsString);
26306
+ }
26307
+ }
26308
+ if (result2.length === 0) {
26309
+ return sign + "0" + (options.verbose ? " milliseconds" : "ms");
26310
+ }
26311
+ const separator = options.colonNotation ? ":" : " ";
26312
+ if (typeof options.unitCount === "number") {
26313
+ result2 = result2.slice(0, Math.max(options.unitCount, 1));
26314
+ }
26315
+ return sign + result2.join(separator);
26316
+ }
26317
+ const errorProperties = [
26318
+ {
26319
+ property: "name",
26320
+ enumerable: false
26321
+ },
26322
+ {
26323
+ property: "message",
26324
+ enumerable: false
26325
+ },
26326
+ {
26327
+ property: "stack",
26328
+ enumerable: false
26329
+ },
26330
+ {
26331
+ property: "code",
26332
+ enumerable: true
26333
+ },
26334
+ {
26335
+ property: "cause",
26336
+ enumerable: false
26337
+ },
26338
+ {
26339
+ property: "errors",
26340
+ enumerable: false
26341
+ }
26342
+ ];
26343
+ const toJsonWasCalled = /* @__PURE__ */ new WeakSet();
26344
+ const toJSON = (from) => {
26345
+ toJsonWasCalled.add(from);
26346
+ const json2 = from.toJSON();
26347
+ toJsonWasCalled.delete(from);
26348
+ return json2;
26349
+ };
26350
+ const destroyCircular = ({
26351
+ from,
26352
+ seen,
26353
+ to,
26354
+ forceEnumerable,
26355
+ maxDepth,
26356
+ depth,
26357
+ useToJSON,
26358
+ serialize
26359
+ }) => {
26360
+ if (!to) {
26361
+ if (Array.isArray(from)) {
26362
+ to = [];
26363
+ } else {
26364
+ to = {};
26365
+ }
26366
+ }
26367
+ seen.push(from);
26368
+ if (depth >= maxDepth) {
26369
+ return to;
26370
+ }
26371
+ if (useToJSON && typeof from.toJSON === "function" && !toJsonWasCalled.has(from)) {
26372
+ return toJSON(from);
26373
+ }
26374
+ const continueDestroyCircular = (value) => destroyCircular({
26375
+ from: value,
26376
+ seen: [...seen],
26377
+ forceEnumerable,
26378
+ maxDepth,
26379
+ depth,
26380
+ useToJSON,
26381
+ serialize
26382
+ });
26383
+ for (const [key, value] of Object.entries(from)) {
26384
+ if (value && value instanceof Uint8Array && value.constructor.name === "Buffer") {
26385
+ to[key] = "[object Buffer]";
26386
+ continue;
26175
26387
  }
26176
- return new ZodEnum2({
26177
- ...def,
26178
- checks: [],
26179
- ...normalizeParams(params),
26180
- entries: newEntries
26181
- });
26182
- };
26183
- inst.exclude = (values, params) => {
26184
- const newEntries = { ...def.entries };
26185
- for (const value of values) {
26186
- if (keys.has(value)) {
26187
- delete newEntries[value];
26188
- } else
26189
- throw new Error(`Key ${value} not found in enum`);
26388
+ if (value !== null && typeof value === "object" && typeof value.pipe === "function") {
26389
+ to[key] = "[object Stream]";
26390
+ continue;
26190
26391
  }
26191
- return new ZodEnum2({
26192
- ...def,
26193
- checks: [],
26194
- ...normalizeParams(params),
26195
- entries: newEntries
26196
- });
26197
- };
26198
- });
26199
- function _enum$1(values, params) {
26200
- const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
26201
- return new ZodEnum2({
26202
- type: "enum",
26203
- entries,
26204
- ...normalizeParams(params)
26205
- });
26206
- }
26207
- const ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
26208
- $ZodTransform.init(inst, def);
26209
- ZodType2.init(inst, def);
26210
- inst._zod.parse = (payload, _ctx) => {
26211
- if (_ctx.direction === "backward") {
26212
- throw new $ZodEncodeError2(inst.constructor.name);
26392
+ if (typeof value === "function") {
26393
+ continue;
26213
26394
  }
26214
- payload.addIssue = (issue$12) => {
26215
- if (typeof issue$12 === "string") {
26216
- payload.issues.push(issue(issue$12, payload.value, def));
26217
- } else {
26218
- const _issue = issue$12;
26219
- if (_issue.fatal)
26220
- _issue.continue = false;
26221
- _issue.code ?? (_issue.code = "custom");
26222
- _issue.input ?? (_issue.input = payload.value);
26223
- _issue.inst ?? (_issue.inst = inst);
26224
- payload.issues.push(issue(_issue));
26395
+ if (!value || typeof value !== "object") {
26396
+ try {
26397
+ to[key] = value;
26398
+ } catch {
26225
26399
  }
26226
- };
26227
- const output = def.transform(payload.value, payload);
26228
- if (output instanceof Promise) {
26229
- return output.then((output2) => {
26230
- payload.value = output2;
26231
- return payload;
26232
- });
26400
+ continue;
26233
26401
  }
26234
- payload.value = output;
26235
- return payload;
26236
- };
26237
- });
26238
- function transform$2(fn) {
26239
- return new ZodTransform({
26240
- type: "transform",
26241
- transform: fn
26242
- });
26243
- }
26244
- const ZodOptional2 = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => {
26245
- $ZodOptional.init(inst, def);
26246
- ZodType2.init(inst, def);
26247
- inst.unwrap = () => inst._zod.def.innerType;
26248
- });
26249
- function optional(innerType) {
26250
- return new ZodOptional2({
26251
- type: "optional",
26252
- innerType
26253
- });
26254
- }
26255
- const ZodNullable2 = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => {
26256
- $ZodNullable.init(inst, def);
26257
- ZodType2.init(inst, def);
26258
- inst.unwrap = () => inst._zod.def.innerType;
26259
- });
26260
- function nullable(innerType) {
26261
- return new ZodNullable2({
26262
- type: "nullable",
26263
- innerType
26264
- });
26265
- }
26266
- const ZodDefault2 = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => {
26267
- $ZodDefault.init(inst, def);
26268
- ZodType2.init(inst, def);
26269
- inst.unwrap = () => inst._zod.def.innerType;
26270
- inst.removeDefault = inst.unwrap;
26271
- });
26272
- function _default(innerType, defaultValue) {
26273
- return new ZodDefault2({
26274
- type: "default",
26275
- innerType,
26276
- get defaultValue() {
26277
- return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
26402
+ if (!seen.includes(from[key])) {
26403
+ depth++;
26404
+ to[key] = continueDestroyCircular(from[key]);
26405
+ continue;
26278
26406
  }
26279
- });
26280
- }
26281
- const ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => {
26282
- $ZodPrefault.init(inst, def);
26283
- ZodType2.init(inst, def);
26284
- inst.unwrap = () => inst._zod.def.innerType;
26285
- });
26286
- function prefault(innerType, defaultValue) {
26287
- return new ZodPrefault({
26288
- type: "prefault",
26289
- innerType,
26290
- get defaultValue() {
26291
- return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
26407
+ to[key] = "[Circular]";
26408
+ }
26409
+ {
26410
+ for (const { property, enumerable } of errorProperties) {
26411
+ if (from[property] !== void 0 && from[property] !== null) {
26412
+ Object.defineProperty(to, property, {
26413
+ value: isErrorLike(from[property]) || Array.isArray(from[property]) ? continueDestroyCircular(from[property]) : from[property],
26414
+ enumerable: true,
26415
+ configurable: true,
26416
+ writable: true
26417
+ });
26418
+ }
26292
26419
  }
26293
- });
26294
- }
26295
- const ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => {
26296
- $ZodNonOptional.init(inst, def);
26297
- ZodType2.init(inst, def);
26298
- inst.unwrap = () => inst._zod.def.innerType;
26299
- });
26300
- function nonoptional(innerType, params) {
26301
- return new ZodNonOptional({
26302
- type: "nonoptional",
26303
- innerType,
26304
- ...normalizeParams(params)
26305
- });
26306
- }
26307
- const ZodCatch2 = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => {
26308
- $ZodCatch.init(inst, def);
26309
- ZodType2.init(inst, def);
26310
- inst.unwrap = () => inst._zod.def.innerType;
26311
- inst.removeCatch = inst.unwrap;
26312
- });
26313
- function _catch(innerType, catchValue) {
26314
- return new ZodCatch2({
26315
- type: "catch",
26316
- innerType,
26317
- catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
26318
- });
26319
- }
26320
- const ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => {
26321
- $ZodPipe.init(inst, def);
26322
- ZodType2.init(inst, def);
26323
- inst.in = def.in;
26324
- inst.out = def.out;
26325
- });
26326
- function pipe(in_, out) {
26327
- return new ZodPipe({
26328
- type: "pipe",
26329
- in: in_,
26330
- out
26331
- // ...util.normalizeParams(params),
26332
- });
26333
- }
26334
- const ZodReadonly2 = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => {
26335
- $ZodReadonly.init(inst, def);
26336
- ZodType2.init(inst, def);
26337
- inst.unwrap = () => inst._zod.def.innerType;
26338
- });
26339
- function readonly(innerType) {
26340
- return new ZodReadonly2({
26341
- type: "readonly",
26342
- innerType
26343
- });
26344
- }
26345
- const ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => {
26346
- $ZodCustom.init(inst, def);
26347
- ZodType2.init(inst, def);
26348
- });
26349
- function refine(fn, _params = {}) {
26350
- return _refine(ZodCustom, fn, _params);
26420
+ }
26421
+ return to;
26422
+ };
26423
+ function serializeError(value, options = {}) {
26424
+ const {
26425
+ maxDepth = Number.POSITIVE_INFINITY,
26426
+ useToJSON = true
26427
+ } = options;
26428
+ if (typeof value === "object" && value !== null) {
26429
+ return destroyCircular({
26430
+ from: value,
26431
+ seen: [],
26432
+ forceEnumerable: true,
26433
+ maxDepth,
26434
+ depth: 0,
26435
+ useToJSON,
26436
+ serialize: true
26437
+ });
26438
+ }
26439
+ if (typeof value === "function") {
26440
+ return `[Function: ${value.name || "anonymous"}]`;
26441
+ }
26442
+ return value;
26351
26443
  }
26352
- function superRefine(fn) {
26353
- return _superRefine(fn);
26444
+ function isErrorLike(value) {
26445
+ return Boolean(value) && typeof value === "object" && typeof value.name === "string" && typeof value.message === "string" && typeof value.stack === "string";
26354
26446
  }
26447
+ const stringifyCallSite = (callSite) => {
26448
+ return (callSite.fileName || "") + ":" + callSite.lineNumber + ":" + callSite.columnNumber;
26449
+ };
26450
+ const defaultConfiguration = {
26451
+ logValues: true
26452
+ };
26453
+ const createQueryLoggingInterceptor = (userConfiguration) => {
26454
+ const configuration = {
26455
+ ...defaultConfiguration,
26456
+ ...userConfiguration
26457
+ };
26458
+ return {
26459
+ afterQueryExecution: (context, query2, result2) => {
26460
+ let rowCount = null;
26461
+ if (result2.rowCount) {
26462
+ rowCount = result2.rowCount;
26463
+ }
26464
+ for (const notice of result2.notices) {
26465
+ if (!notice.message) {
26466
+ continue;
26467
+ }
26468
+ if (isAutoExplainJsonMessage(notice.message)) {
26469
+ context.log.info({
26470
+ autoExplain: getAutoExplainPayload(notice.message)
26471
+ }, "auto explain");
26472
+ }
26473
+ }
26474
+ context.log.debug({
26475
+ executionTime: prettyMilliseconds(Number(process.hrtime.bigint() - BigInt(context.queryInputTime)) / 1e6),
26476
+ rowCount
26477
+ }, "query execution result");
26478
+ return null;
26479
+ },
26480
+ beforeQueryExecution: async (context, query2) => {
26481
+ let stackTrace;
26482
+ if (context.stackTrace) {
26483
+ stackTrace = [];
26484
+ for (const callSite of context.stackTrace) {
26485
+ if (callSite.fileName !== null && !callSite.fileName.includes("node_modules/slonik/") && !callSite.fileName.includes("next_tick")) {
26486
+ stackTrace.push(stringifyCallSite(callSite));
26487
+ }
26488
+ }
26489
+ }
26490
+ let values;
26491
+ if (configuration.logValues) {
26492
+ values = [];
26493
+ for (const value of query2.values) {
26494
+ if (Buffer.isBuffer(value)) {
26495
+ values.push("[Buffer " + value.byteLength + "]");
26496
+ } else {
26497
+ values.push(value);
26498
+ }
26499
+ }
26500
+ }
26501
+ context.log.debug({
26502
+ sql: query2.sql,
26503
+ stackTrace,
26504
+ values
26505
+ }, "executing query");
26506
+ return null;
26507
+ },
26508
+ name: "slonik-interceptor-query-logging",
26509
+ queryExecutionError: (context, query2, error2) => {
26510
+ context.log.error({
26511
+ error: serializeError(error2)
26512
+ }, "query execution produced an error");
26513
+ return null;
26514
+ }
26515
+ };
26516
+ };
26355
26517
  const extensionDbName = (id2) => `ext_${id2}`;
26356
26518
  const voidSelectSchema = object({});
26519
+ const stringIdSelectSchema = object({
26520
+ id: string()
26521
+ });
26357
26522
  const requireExtensionIdOptionOrEnvVar = (options, env2) => {
26358
26523
  const extensionId = options.extensionId || env2.EXTENSION_ID;
26359
26524
  if (!extensionId) {
@@ -26400,61 +26565,298 @@ const getExtensionDbConnectInfo = (opts, env2) => {
26400
26565
  dbName
26401
26566
  };
26402
26567
  };
26568
+ const revokeAllUserPlatformPermissions = async ({
26569
+ platformAdminId
26570
+ }, db) => {
26571
+ await db.query(
26572
+ sql.type(
26573
+ voidSelectSchema
26574
+ )`delete from "Permissions" where "platformAdminId" = ${platformAdminId}`
26575
+ );
26576
+ };
26577
+ const grantAllUserPlatformPermissions = async ({
26578
+ platformAdminId
26579
+ }, db) => {
26580
+ await db.query(
26581
+ sql.type(
26582
+ voidSelectSchema
26583
+ )`insert into "Permissions" ("platformAdminId", "object", "action") values ${sql.join(
26584
+ allPermissions.map(
26585
+ (permission) => sql.fragment`(${platformAdminId}, ${permission.object}, ${permission.action})`
26586
+ ),
26587
+ sql.fragment`,`
26588
+ )} on conflict ("platformAdminId", "object", "action") do nothing`
26589
+ );
26590
+ };
26591
+ const devAdminPlatformId = "ths9gw8";
26592
+ const devUserEmail = "dev@example.com";
26593
+ const devUserPassword = "password00";
26403
26594
  const platformHandleAvailable = async (handle, db) => !await db.maybeOne(
26404
26595
  sql.type(voidSelectSchema)`select from "Platforms" where "handle" = ${handle}`
26405
26596
  );
26406
- const randomString = () => randomUUID().replaceAll("-", "").slice(0, 10);
26597
+ const findSiteByDomainResult = object({
26598
+ id: string(),
26599
+ platformId: string()
26600
+ });
26601
+ const devJwtSecret = "abcd1234abcd1234abcd1234abcd1234";
26602
+ const tokenExpiresInSeconds = 60 * 60 * 24 * 365 * 5;
26603
+ const resolveEnvFilePath = (cwd, envMode) => envMode ? resolve$1(cwd, `./.env.${envMode}.local`) : resolve$1(cwd, "./.env.local");
26604
+ const requireJwtSecret = (opts, env2) => {
26605
+ const secret = env2.WIRECHUNK_CORE_JWT_SECRET;
26606
+ if (secret) {
26607
+ return secret;
26608
+ }
26609
+ if (opts.dev) {
26610
+ return devJwtSecret;
26611
+ }
26612
+ console.error("Missing WIRECHUNK_CORE_JWT_SECRET in environment");
26613
+ process.exit(1);
26614
+ };
26615
+ const signAuthToken = (sessionId, secret, expiresInSeconds) => jwt.sign(
26616
+ {
26617
+ sessionId,
26618
+ originalCreatedAt: Date.now()
26619
+ },
26620
+ secret,
26621
+ { algorithm: "HS256", expiresIn: expiresInSeconds }
26622
+ );
26407
26623
  const bootstrap = async (opts, env2) => {
26408
26624
  const db = await createPool(requireCoreDbUrl(env2));
26409
- const platformId = cleanTinyId();
26410
- const name = opts.name.trim();
26411
- let handle = opts.handle?.trim().toLowerCase().replace(/\s+/g, "-");
26625
+ const cwd = process.cwd();
26626
+ const envFilePath2 = resolveEnvFilePath(cwd, opts.envMode);
26627
+ if (opts.dev && (opts.name !== void 0 || opts.handle !== void 0 || opts.adminSiteDomain !== void 0)) {
26628
+ console.error("--dev cannot be combined with --name, --handle, or --admin-site-domain");
26629
+ process.exit(1);
26630
+ }
26631
+ const name = opts.dev ? "Dev" : opts.name?.trim();
26632
+ if (!name) {
26633
+ console.error("Missing required option: --name");
26634
+ process.exit(1);
26635
+ }
26636
+ let handle = opts.dev ? "dev" : opts.handle?.trim().toLowerCase().replace(/\s+/g, "-");
26412
26637
  if (!handle) {
26413
26638
  handle = name.toLowerCase().replace(/\s+/g, "-");
26414
26639
  if (!await platformHandleAvailable(handle, db)) {
26415
- handle = `${handle}-${randomString()}`;
26640
+ const randomString = randomUUID().replaceAll("-", "").toLowerCase().slice(0, 10);
26641
+ handle = `${handle}-${randomString}`;
26416
26642
  }
26417
26643
  } else if (!await platformHandleAvailable(handle, db)) {
26418
26644
  console.error(`Handle "${handle}" is already in use`);
26419
26645
  process.exit(1);
26420
26646
  }
26421
- const adminSiteDomain = normalizeDomain(opts.adminSiteDomain, { allowPort: true });
26647
+ const rawAdminSiteDomain = opts.dev ? "localhost:8080" : opts.adminSiteDomain?.trim();
26648
+ if (!rawAdminSiteDomain) {
26649
+ console.error("Missing required option: --admin-site-domain");
26650
+ process.exit(1);
26651
+ }
26652
+ const adminSiteDomain = normalizeDomain(rawAdminSiteDomain, { allowPort: true });
26422
26653
  if (!adminSiteDomain) {
26423
26654
  console.error("Invalid admin site domain");
26424
26655
  process.exit(1);
26425
26656
  }
26426
- let emailSendFrom;
26427
- if (opts.emailSendFrom) {
26428
- const normalizeEmailSendFromResult = normalizeEmailAddress(opts.emailSendFrom);
26429
- if (!normalizeEmailSendFromResult.ok) {
26430
- console.error(normalizeEmailSendFromResult.error);
26431
- process.exit(1);
26657
+ let devUserPasswordHash = null;
26658
+ if (opts.dev) {
26659
+ devUserPasswordHash = await hashPassword(devUserPassword);
26660
+ }
26661
+ const result2 = await db.transaction(async (db2) => {
26662
+ const existingSiteForDomain = await db2.maybeOne(
26663
+ sql.type(findSiteByDomainResult)`
26664
+ select "id", "platformId"
26665
+ from "Sites"
26666
+ where "domain" = ${adminSiteDomain}
26667
+ `
26668
+ );
26669
+ if (existingSiteForDomain) {
26670
+ return {
26671
+ code: 1,
26672
+ error: `Domain "${adminSiteDomain}" is already in use by the platform with ID ${existingSiteForDomain.platformId}`
26673
+ };
26432
26674
  }
26433
- emailSendFrom = normalizeEmailSendFromResult.value;
26434
- } else {
26435
- emailSendFrom = `site@${adminSiteDomain}`;
26675
+ const insertPlatformQuery = opts.dev ? sql.type(stringIdSelectSchema)`
26676
+ insert into "Platforms" (
26677
+ "id",
26678
+ "handle",
26679
+ "name"
26680
+ )
26681
+ values (
26682
+ ${devAdminPlatformId},
26683
+ ${handle},
26684
+ ${name}
26685
+ )
26686
+ returning "id"
26687
+ ` : sql.type(stringIdSelectSchema)`
26688
+ insert into "Platforms" (
26689
+ "handle",
26690
+ "name"
26691
+ )
26692
+ values (
26693
+ ${handle},
26694
+ ${name}
26695
+ )
26696
+ returning "id"
26697
+ `;
26698
+ const platform = await db2.one(insertPlatformQuery);
26699
+ const adminSiteId = cleanSmallId();
26700
+ await db2.query(
26701
+ sql.type(voidSelectSchema)`
26702
+ insert into "Sites" (
26703
+ "id",
26704
+ "platformId",
26705
+ "domain",
26706
+ "name"
26707
+ )
26708
+ values (
26709
+ ${adminSiteId},
26710
+ ${platform.id},
26711
+ ${adminSiteDomain},
26712
+ ${name}
26713
+ )
26714
+ `
26715
+ );
26716
+ await db2.query(
26717
+ sql.type(voidSelectSchema)`
26718
+ update "Platforms"
26719
+ set "mainSiteId" = ${adminSiteId}
26720
+ where "id" = ${platform.id}
26721
+ `
26722
+ );
26723
+ if (opts.dev) {
26724
+ assert(devUserPasswordHash, "Missing dev user password hash.");
26725
+ const devUserId = cleanSmallId();
26726
+ await db2.query(
26727
+ sql.type(voidSelectSchema)`
26728
+ insert into "Users" (
26729
+ "id",
26730
+ "platformId",
26731
+ "email",
26732
+ "emailVerified",
26733
+ "password",
26734
+ "passwordStatus",
26735
+ "status",
26736
+ "firstName",
26737
+ "lastName",
26738
+ "role"
26739
+ )
26740
+ values (
26741
+ ${devUserId},
26742
+ ${platform.id},
26743
+ ${devUserEmail},
26744
+ true,
26745
+ ${devUserPasswordHash},
26746
+ 'Ok',
26747
+ 'Active',
26748
+ 'Mocky',
26749
+ 'McStubbs',
26750
+ ''
26751
+ )
26752
+ `
26753
+ );
26754
+ const devPlatformAdminId = cleanSmallId();
26755
+ await db2.query(
26756
+ sql.type(voidSelectSchema)`
26757
+ insert into "PlatformAdmins" (
26758
+ "id",
26759
+ "platformId",
26760
+ "userId",
26761
+ "owner",
26762
+ "active"
26763
+ )
26764
+ values (
26765
+ ${devPlatformAdminId},
26766
+ ${platform.id},
26767
+ ${devUserId},
26768
+ true,
26769
+ true
26770
+ )
26771
+ `
26772
+ );
26773
+ await grantAllUserPlatformPermissions(
26774
+ {
26775
+ platformAdminId: devPlatformAdminId
26776
+ },
26777
+ db2
26778
+ );
26779
+ return {
26780
+ code: 0,
26781
+ platformId: platform.id
26782
+ };
26783
+ }
26784
+ return {
26785
+ code: 0,
26786
+ platformId: platform.id
26787
+ };
26788
+ });
26789
+ if (result2.code !== 0) {
26790
+ console.error(result2.error);
26791
+ process.exit(result2.code);
26436
26792
  }
26793
+ console.log(
26794
+ `Created platform ${name} with handle ${handle} (ID ${result2.platformId}) and admin site ${adminSiteDomain}`
26795
+ );
26796
+ const jwtSecret = requireJwtSecret(opts, env2);
26797
+ const sessionId = cleanSmallId();
26798
+ const apiTokenId = cleanSmallId();
26437
26799
  await db.transaction(async (db2) => {
26438
26800
  await db2.query(
26439
26801
  sql.type(voidSelectSchema)`
26440
- insert into "Platforms" (
26802
+ insert into "Sessions" (
26803
+ "id",
26804
+ "platformId",
26805
+ "createdByIpAddress"
26806
+ )
26807
+ values (
26808
+ ${sessionId},
26809
+ ${result2.platformId},
26810
+ ''
26811
+ )
26812
+ `
26813
+ );
26814
+ await db2.query(
26815
+ sql.type(voidSelectSchema)`
26816
+ insert into "ApiTokens" (
26441
26817
  "id",
26442
- "handle",
26443
26818
  "name",
26444
- "defaultFormNotificationEmailBodyTemplate",
26445
- "emailSendFromAddress"
26819
+ "sessionId"
26446
26820
  )
26447
26821
  values (
26448
- ${platformId},
26449
- ${handle},
26450
- ${name},
26451
- ${defaultNotificationEmailBodyTemplate},
26452
- ${emailSendFrom}
26822
+ ${apiTokenId},
26823
+ 'Bootstrap CLI token',
26824
+ ${sessionId}
26453
26825
  )
26454
26826
  `
26455
26827
  );
26828
+ const values = allPermissions.map(
26829
+ ({ object: object2, action }) => sql.fragment`(${apiTokenId}, ${object2}, ${action})`
26830
+ );
26831
+ if (values.length) {
26832
+ await db2.query(
26833
+ sql.type(voidSelectSchema)`
26834
+ insert into "Permissions" ("apiTokenId", "object", "action")
26835
+ values ${sql.join(values, sql.fragment`, `)}
26836
+ `
26837
+ );
26838
+ }
26456
26839
  });
26457
- console.log(`Created platform ${name} with handle ${handle} (ID ${platformId})`);
26840
+ const token = signAuthToken(sessionId, jwtSecret, tokenExpiresInSeconds);
26841
+ if (opts.verbose) {
26842
+ console.log(`Loading file ${envFilePath2} to update environment variables`);
26843
+ }
26844
+ if (existsSync(envFilePath2)) {
26845
+ const envFile = await readFile(envFilePath2, "utf8");
26846
+ let lines = replaceEnvVar(envFile.split("\n"), "WIRECHUNK_API_TOKEN", token);
26847
+ lines = replaceEnvVar(lines, "WIRECHUNK_PLATFORM_ID", result2.platformId);
26848
+ await writeFile(envFilePath2, lines.join("\n"));
26849
+ } else {
26850
+ if (opts.verbose) {
26851
+ console.log(`Creating file ${envFilePath2}`);
26852
+ }
26853
+ await writeFile(
26854
+ envFilePath2,
26855
+ `WIRECHUNK_API_TOKEN=${token}
26856
+ WIRECHUNK_PLATFORM_ID=${result2.platformId}
26857
+ `
26858
+ );
26859
+ }
26458
26860
  };
26459
26861
  const validateExtensionConfig = validate25;
26460
26862
  function validate25(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) {
@@ -43946,7 +44348,7 @@ function requireErrors() {
43946
44348
  const classRegExp = /^([A-Z][a-z0-9]*)+$/;
43947
44349
  const nodeInternalPrefix = "__node_internal_";
43948
44350
  const codes = {};
43949
- function assert(value, message) {
44351
+ function assert2(value, message) {
43950
44352
  if (!value) {
43951
44353
  throw new codes.ERR_INTERNAL_ASSERTION(message);
43952
44354
  }
@@ -43962,7 +44364,7 @@ function requireErrors() {
43962
44364
  }
43963
44365
  function getMessage(key, msg, args) {
43964
44366
  if (typeof msg === "function") {
43965
- assert(
44367
+ assert2(
43966
44368
  msg.length <= args.length,
43967
44369
  // Default options do not count.
43968
44370
  `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${msg.length}).`
@@ -43970,7 +44372,7 @@ function requireErrors() {
43970
44372
  return msg(...args);
43971
44373
  }
43972
44374
  const expectedLength = (msg.match(/%[dfijoOs]/g) || []).length;
43973
- assert(
44375
+ assert2(
43974
44376
  expectedLength === args.length,
43975
44377
  `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).`
43976
44378
  );
@@ -44044,7 +44446,7 @@ function requireErrors() {
44044
44446
  E(
44045
44447
  "ERR_INVALID_ARG_TYPE",
44046
44448
  (name, expected, actual) => {
44047
- assert(typeof name === "string", "'name' must be a string");
44449
+ assert2(typeof name === "string", "'name' must be a string");
44048
44450
  if (!Array.isArray(expected)) {
44049
44451
  expected = [expected];
44050
44452
  }
@@ -44059,13 +44461,13 @@ function requireErrors() {
44059
44461
  const instances = [];
44060
44462
  const other = [];
44061
44463
  for (const value of expected) {
44062
- assert(typeof value === "string", "All expected entries have to be of type string");
44464
+ assert2(typeof value === "string", "All expected entries have to be of type string");
44063
44465
  if (kTypes.includes(value)) {
44064
44466
  types2.push(value.toLowerCase());
44065
44467
  } else if (classRegExp.test(value)) {
44066
44468
  instances.push(value);
44067
44469
  } else {
44068
- assert(value !== "object", 'The value "object" should be written as "Object"');
44470
+ assert2(value !== "object", 'The value "object" should be written as "Object"');
44069
44471
  other.push(value);
44070
44472
  }
44071
44473
  }
@@ -44178,7 +44580,7 @@ function requireErrors() {
44178
44580
  E(
44179
44581
  "ERR_MISSING_ARGS",
44180
44582
  (...args) => {
44181
- assert(args.length > 0, "At least one arg needs to be specified");
44583
+ assert2(args.length > 0, "At least one arg needs to be specified");
44182
44584
  let msg;
44183
44585
  const len = args.length;
44184
44586
  args = (Array.isArray(args) ? args : [args]).map((a) => `"${a}"`).join(" or ");
@@ -44203,7 +44605,7 @@ function requireErrors() {
44203
44605
  E(
44204
44606
  "ERR_OUT_OF_RANGE",
44205
44607
  (str, range2, input) => {
44206
- assert(range2, 'Missing "range" argument');
44608
+ assert2(range2, 'Missing "range" argument');
44207
44609
  let received;
44208
44610
  if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {
44209
44611
  received = addNumericalSeparator(String(input));
@@ -65034,6 +65436,80 @@ const CreateExtensionVersionDocument = {
65034
65436
  }
65035
65437
  ]
65036
65438
  };
65439
+ const CreateExtensionDocument = {
65440
+ kind: "Document",
65441
+ definitions: [
65442
+ {
65443
+ kind: "OperationDefinition",
65444
+ operation: "mutation",
65445
+ name: { kind: "Name", value: "CreateExtension" },
65446
+ variableDefinitions: [
65447
+ {
65448
+ kind: "VariableDefinition",
65449
+ variable: { kind: "Variable", name: { kind: "Name", value: "input" } },
65450
+ type: {
65451
+ kind: "NonNullType",
65452
+ type: { kind: "NamedType", name: { kind: "Name", value: "CreateExtensionInput" } }
65453
+ }
65454
+ }
65455
+ ],
65456
+ selectionSet: {
65457
+ kind: "SelectionSet",
65458
+ selections: [
65459
+ {
65460
+ kind: "Field",
65461
+ name: { kind: "Name", value: "createExtension" },
65462
+ arguments: [
65463
+ {
65464
+ kind: "Argument",
65465
+ name: { kind: "Name", value: "input" },
65466
+ value: { kind: "Variable", name: { kind: "Name", value: "input" } }
65467
+ }
65468
+ ],
65469
+ selectionSet: {
65470
+ kind: "SelectionSet",
65471
+ selections: [
65472
+ { kind: "Field", name: { kind: "Name", value: "__typename" } },
65473
+ {
65474
+ kind: "InlineFragment",
65475
+ typeCondition: {
65476
+ kind: "NamedType",
65477
+ name: { kind: "Name", value: "CreateExtensionSuccessResult" }
65478
+ },
65479
+ selectionSet: {
65480
+ kind: "SelectionSet",
65481
+ selections: [
65482
+ {
65483
+ kind: "Field",
65484
+ name: { kind: "Name", value: "extension" },
65485
+ selectionSet: {
65486
+ kind: "SelectionSet",
65487
+ selections: [
65488
+ { kind: "Field", name: { kind: "Name", value: "id" } },
65489
+ { kind: "Field", name: { kind: "Name", value: "name" } },
65490
+ { kind: "Field", name: { kind: "Name", value: "enabled" } }
65491
+ ]
65492
+ }
65493
+ }
65494
+ ]
65495
+ }
65496
+ },
65497
+ {
65498
+ kind: "InlineFragment",
65499
+ typeCondition: { kind: "NamedType", name: { kind: "Name", value: "Error" } },
65500
+ selectionSet: {
65501
+ kind: "SelectionSet",
65502
+ selections: [{ kind: "Field", name: { kind: "Name", value: "message" } }]
65503
+ }
65504
+ }
65505
+ ]
65506
+ }
65507
+ }
65508
+ ]
65509
+ }
65510
+ }
65511
+ ]
65512
+ };
65037
65513
  const createExtensionVersion$1 = ({
65038
65514
  client: client2,
65039
65515
  variables,
@@ -65106,7 +65582,7 @@ const createExtensionVersion = async (opts, env2) => {
65106
65582
  let extensionVersionId;
65107
65583
  let signedUrl;
65108
65584
  try {
65109
- const url = `${env2.CORE_SERVER_URL}/api`;
65585
+ const url = `${env2.WIRECHUNK_CORE_SERVER_URL}/api`;
65110
65586
  if (opts.verbose) {
65111
65587
  console.log(`POST ${url}`);
65112
65588
  }
@@ -65127,6 +65603,12 @@ const createExtensionVersion = async (opts, env2) => {
65127
65603
  });
65128
65604
  if (result2.createExtensionVersion.__typename === "CreateExtensionVersionSuccessResult") {
65129
65605
  extensionVersionId = result2.createExtensionVersion.extensionVersion.id;
65606
+ if (!result2.createExtensionVersion.signedUrl) {
65607
+ console.error(
65608
+ "Failed to upload source code for the extension version: a signed URL for the upload is not set"
65609
+ );
65610
+ process.exit(1);
65611
+ }
65130
65612
  signedUrl = result2.createExtensionVersion.signedUrl;
65131
65613
  } else {
65132
65614
  console.error(
@@ -65186,39 +65668,241 @@ const createExtensionVersion = async (opts, env2) => {
65186
65668
  }
65187
65669
  console.log(`Created version ${versionName} (ID ${extensionVersionId})`);
65188
65670
  };
65189
- const validatePasswordComplexity = (password) => {
65190
- if (password.length < 10) {
65191
- return {
65192
- ok: false,
65193
- error: "Password must be at least 10 characters long."
65194
- };
65671
+ const toConfigObject = (raw) => {
65672
+ const parsed = parseEnv$1(raw);
65673
+ const configEntries = Object.entries(parsed).filter(
65674
+ (entry) => entry[1] !== void 0
65675
+ );
65676
+ return Object.fromEntries(configEntries);
65677
+ };
65678
+ const resolveServerAndDbOptions = (manifest) => {
65679
+ if (!manifest.server) {
65680
+ return { enableServer: false, enableDb: false };
65195
65681
  }
65196
- if (password.length > 120) {
65682
+ let enableServer = !!manifest.server.enable;
65683
+ let enableDb;
65684
+ if (manifest.server.database?.enable && manifest.server.enable === false) {
65685
+ console.warn("WARNING: Automatically disabling database because server is disabled");
65686
+ enableDb = false;
65687
+ } else if (manifest.server.database?.enable && !manifest.server.enable) {
65688
+ console.warn("WARNING: Automatically enabling server because database is enabled");
65689
+ enableServer = true;
65690
+ enableDb = true;
65691
+ } else {
65692
+ enableDb = !!manifest.server.database?.enable;
65693
+ }
65694
+ return { enableServer, enableDb };
65695
+ };
65696
+ const formatValidationErrors = (errors2) => {
65697
+ if (!errors2 || errors2.length === 0) {
65698
+ return "Invalid extension config.";
65699
+ }
65700
+ return errors2.map((error2) => {
65701
+ const path2 = error2.instancePath || "/";
65702
+ const message = error2.message ?? "is invalid";
65703
+ return `${path2} ${message}`.trim();
65704
+ }).join("; ");
65705
+ };
65706
+ const createExtension = async (opts, env2) => {
65707
+ const cwd = process.cwd();
65708
+ let nameFromConfig = null;
65709
+ let extensionConfigError = null;
65710
+ let manifest = null;
65711
+ if (opts.dev) {
65712
+ const extensionDir = await requireValidExtensionDir(cwd);
65713
+ manifest = extensionDir.manifest;
65714
+ nameFromConfig = manifest.name;
65715
+ } else if (!opts.name) {
65716
+ const extensionConfigPath = resolve$1(cwd, "extension.json");
65717
+ if (existsSync(extensionConfigPath)) {
65718
+ if (opts.verbose) {
65719
+ console.log(`Loading extension config ${extensionConfigPath}`);
65720
+ }
65721
+ try {
65722
+ const parsedExtensionConfig = JSON.parse(
65723
+ await readFile(extensionConfigPath, "utf8")
65724
+ );
65725
+ if (validateExtensionConfig(parsedExtensionConfig)) {
65726
+ nameFromConfig = parsedExtensionConfig.name;
65727
+ } else {
65728
+ extensionConfigError = `Invalid extension config at ${extensionConfigPath}: ${formatValidationErrors(validateExtensionConfig.errors)}`;
65729
+ }
65730
+ } catch (error2) {
65731
+ extensionConfigError = `Failed to read extension config at ${extensionConfigPath}: ${parseErrorMessage(error2)}`;
65732
+ }
65733
+ } else {
65734
+ extensionConfigError = `extension.json not found at ${extensionConfigPath}`;
65735
+ }
65736
+ }
65737
+ const platformId = (opts.platformId ?? env2.WIRECHUNK_PLATFORM_ID)?.trim();
65738
+ const name = (opts.name ?? nameFromConfig)?.trim();
65739
+ if (!platformId || !name) {
65740
+ const missing = [];
65741
+ const details = [];
65742
+ if (!platformId) {
65743
+ missing.push("platform ID");
65744
+ details.push("Pass --platform-id or set WIRECHUNK_PLATFORM_ID.");
65745
+ }
65746
+ if (!name) {
65747
+ missing.push("extension name");
65748
+ details.push(
65749
+ extensionConfigError ?? "Provide --name or add a valid extension.json file in the current directory."
65750
+ );
65751
+ }
65752
+ console.error(`${missing.join(" and ")} missing. ${details.join(" ")}`);
65753
+ process.exit(1);
65754
+ }
65755
+ const apiToken = requireApiToken(env2);
65756
+ const enabled = !opts.disabled;
65757
+ let config2 = null;
65758
+ if (opts.configFile) {
65759
+ const configFilePath = resolve$1(cwd, opts.configFile);
65760
+ if (opts.verbose) {
65761
+ console.log(`Loading config file ${configFilePath}`);
65762
+ }
65763
+ const configFile = await readFile(configFilePath, "utf8");
65764
+ try {
65765
+ config2 = toConfigObject(configFile);
65766
+ } catch (error2) {
65767
+ console.error(`Failed to parse config file at ${configFilePath}:`, parseErrorMessage(error2));
65768
+ process.exit(1);
65769
+ }
65770
+ }
65771
+ const url = `${env2.WIRECHUNK_CORE_SERVER_URL}/api`;
65772
+ if (opts.verbose) {
65773
+ console.log(`POST ${url}`);
65774
+ }
65775
+ try {
65776
+ const client2 = new GraphQLClient(url);
65777
+ let devServerDbOptions = null;
65778
+ if (opts.dev) {
65779
+ if (!manifest) {
65780
+ console.error("The --dev flag requires a valid extension.json manifest.");
65781
+ process.exit(1);
65782
+ }
65783
+ devServerDbOptions = resolveServerAndDbOptions(manifest);
65784
+ }
65785
+ const result2 = await client2.request({
65786
+ document: CreateExtensionDocument,
65787
+ variables: {
65788
+ input: {
65789
+ platformId,
65790
+ name,
65791
+ enabled,
65792
+ config: config2 ? JSON.stringify(config2) : void 0
65793
+ }
65794
+ },
65795
+ requestHeaders: {
65796
+ Authorization: `Bearer ${apiToken}`
65797
+ }
65798
+ });
65799
+ if (result2.createExtension.__typename === "CreateExtensionSuccessResult") {
65800
+ const extension = result2.createExtension.extension;
65801
+ console.log(`Created extension ${extension.name} (ID ${extension.id})`);
65802
+ const envFilePath2 = opts.envMode ? resolve$1(cwd, `./.env.${opts.envMode}.local`) : resolve$1(cwd, "./.env.local");
65803
+ const envLines = await (async () => {
65804
+ if (existsSync(envFilePath2)) {
65805
+ if (opts.verbose) {
65806
+ console.log(`Loading file ${envFilePath2} to update environment variables`);
65807
+ }
65808
+ const envFile = await readFile(envFilePath2, "utf8");
65809
+ return envFile.split("\n");
65810
+ }
65811
+ if (opts.verbose) {
65812
+ console.log(`Creating file ${envFilePath2}`);
65813
+ }
65814
+ return [];
65815
+ })();
65816
+ let updatedEnvLines = replaceEnvVar(envLines, "EXTENSION_ID", extension.id);
65817
+ if (devServerDbOptions?.enableDb) {
65818
+ const { url: extensionDbUrl } = getExtensionDbConnectInfo(
65819
+ { extensionId: extension.id },
65820
+ env2
65821
+ );
65822
+ updatedEnvLines = replaceEnvVar(updatedEnvLines, "DATABASE_URL", extensionDbUrl.toString());
65823
+ }
65824
+ const envContents = updatedEnvLines.join("\n");
65825
+ await writeFile(envFilePath2, envContents.endsWith("\n") ? envContents : `${envContents}
65826
+ `);
65827
+ if (opts.dev) {
65828
+ if (!devServerDbOptions) {
65829
+ console.error("The --dev flag requires a valid extension.json manifest.");
65830
+ process.exit(1);
65831
+ }
65832
+ const { enableServer, enableDb } = devServerDbOptions;
65833
+ const versionResult = await client2.request({
65834
+ document: CreateExtensionVersionDocument,
65835
+ variables: {
65836
+ input: {
65837
+ extensionId: extension.id,
65838
+ extensionName: extension.name,
65839
+ versionName: "1",
65840
+ manifest: JSON.stringify(manifest),
65841
+ enableServer,
65842
+ enableDb,
65843
+ autoDeploy: false
65844
+ }
65845
+ },
65846
+ requestHeaders: {
65847
+ Authorization: `Bearer ${apiToken}`
65848
+ }
65849
+ });
65850
+ if (versionResult.createExtensionVersion.__typename !== "CreateExtensionVersionSuccessResult") {
65851
+ console.error(
65852
+ `Failed to create dev extension version (${versionResult.createExtensionVersion.__typename}):`,
65853
+ versionResult.createExtensionVersion.message
65854
+ );
65855
+ process.exit(1);
65856
+ }
65857
+ if (opts.verbose) {
65858
+ console.log(
65859
+ `Created dev extension version 1 (ID ${versionResult.createExtensionVersion.extensionVersion.id})`
65860
+ );
65861
+ console.log("Skipping upload in dev mode.");
65862
+ }
65863
+ }
65864
+ return;
65865
+ }
65866
+ console.error(
65867
+ `Failed to create an extension (${result2.createExtension.__typename}):`,
65868
+ result2.createExtension.message
65869
+ );
65870
+ process.exit(1);
65871
+ } catch (error2) {
65872
+ console.error("Failed to create an extension:", parseErrorMessage(error2));
65873
+ process.exit(1);
65874
+ }
65875
+ };
65876
+ const extractParts = (email2) => {
65877
+ const [name, domain] = email2.split("@");
65878
+ return { name, domain };
65879
+ };
65880
+ const normalizeEmailAddress = (email2) => {
65881
+ const emailTrimmed = email2.trim().toLowerCase();
65882
+ if (!emailTrimmed) {
65883
+ return { ok: false, error: "An email address is required." };
65884
+ }
65885
+ if (emailTrimmed.length > 60 || !emailTrimmed.includes("@") || !emailTrimmed.includes(".")) {
65197
65886
  return {
65198
65887
  ok: false,
65199
- error: "Password must be at most 120 characters long."
65888
+ error: "It does not look like the email address you provided is valid."
65200
65889
  };
65201
65890
  }
65202
- if (!/[a-zA-Z]/.test(password)) {
65891
+ const { name, domain } = extractParts(emailTrimmed);
65892
+ if (!name) {
65203
65893
  return {
65204
65894
  ok: false,
65205
- error: "Password must contain at least one letter."
65895
+ error: "It does not look like the email address you provided is valid. Please check the name."
65206
65896
  };
65207
65897
  }
65208
- if (!/\d/.test(password)) {
65898
+ if (!domain || !validDomain(domain)) {
65209
65899
  return {
65210
65900
  ok: false,
65211
- error: "Password must contain at least one digit."
65901
+ error: "It does not look like the email address you provided is valid. Please check the domain."
65212
65902
  };
65213
65903
  }
65214
- return {
65215
- ok: true,
65216
- value: void 0
65217
- };
65904
+ return { ok: true, value: emailTrimmed };
65218
65905
  };
65219
- const hashPassword = (password) => hash(password, {
65220
- type: argon2id
65221
- });
65222
65906
  const detailedUniqueIntegrityConstraintViolationError = (error2) => {
65223
65907
  const message = error2.message === "Query violates a unique integrity constraint." ? `A database uniqueness constraint was violated when inserting or updating` : error2.message;
65224
65908
  const details = [];
@@ -65411,206 +66095,6 @@ const createUser = async (opts, env2) => {
65411
66095
  process.exit(1);
65412
66096
  }
65413
66097
  };
65414
- const permissionAssetEdit = {
65415
- object: "Asset",
65416
- action: "edit"
65417
- };
65418
- const permissionAssetView = {
65419
- object: "Asset",
65420
- action: "view"
65421
- };
65422
- const permissionExtensionCreate = {
65423
- object: "Extension",
65424
- action: "create"
65425
- };
65426
- const permissionExtensionCreateVersion = {
65427
- object: "Extension",
65428
- action: "createVersion"
65429
- };
65430
- const permissionSiteCreate = {
65431
- object: "Site",
65432
- action: "create"
65433
- };
65434
- const permissionTemplateCreate = {
65435
- object: "Template",
65436
- action: "create"
65437
- };
65438
- const permissionUserCreate = {
65439
- object: "User",
65440
- action: "create"
65441
- };
65442
- const permissionPlatformEdit = {
65443
- object: "Platform",
65444
- action: "edit"
65445
- };
65446
- const permissionComponentEdit = {
65447
- object: "Component",
65448
- action: "edit"
65449
- };
65450
- const permissionCourseEdit = {
65451
- object: "Course",
65452
- action: "edit"
65453
- };
65454
- const permissionCustomComponentEdit = {
65455
- object: "CustomComponent",
65456
- action: "edit"
65457
- };
65458
- const permissionCustomFieldEdit = {
65459
- object: "CustomField",
65460
- action: "edit"
65461
- };
65462
- const permissionExtensionEdit = {
65463
- object: "Extension",
65464
- action: "edit"
65465
- };
65466
- const permissionFileUploadAsExtension = {
65467
- object: "File",
65468
- action: "uploadAsExtension"
65469
- };
65470
- const permissionHelpTicketEditStatus = {
65471
- object: "HelpTicket",
65472
- action: "editStatus"
65473
- };
65474
- const permissionSequenceEdit = {
65475
- object: "Sequence",
65476
- action: "edit"
65477
- };
65478
- const permissionSequenceUserEdit = {
65479
- object: "SequenceUser",
65480
- action: "edit"
65481
- };
65482
- const permissionSiteEdit = {
65483
- object: "Site",
65484
- action: "edit"
65485
- };
65486
- const permissionSiteEditDomain = {
65487
- object: "Site",
65488
- action: "editDomain"
65489
- };
65490
- const permissionSiteEditTls = {
65491
- object: "Site",
65492
- action: "editTls"
65493
- };
65494
- const permissionSubscriptionEdit = {
65495
- object: "Subscription",
65496
- action: "edit"
65497
- };
65498
- const permissionTemplateEdit = {
65499
- object: "Template",
65500
- action: "edit"
65501
- };
65502
- const permissionUserEditEmail = {
65503
- object: "User",
65504
- action: "editEmail"
65505
- };
65506
- const permissionUserEditOrg = {
65507
- object: "User",
65508
- action: "editOrg"
65509
- };
65510
- const permissionUserEditStatus = {
65511
- object: "User",
65512
- action: "editStatus"
65513
- };
65514
- const permissionUserEditRole = {
65515
- object: "User",
65516
- action: "editRole"
65517
- };
65518
- const permissionUserEditProfile = {
65519
- object: "User",
65520
- action: "editProfile"
65521
- };
65522
- const permissionUserEditCustomFields = {
65523
- object: "User",
65524
- action: "editCustomFields"
65525
- };
65526
- const permissionFormTemplateSync = {
65527
- object: "FormTemplate",
65528
- action: "sync"
65529
- };
65530
- const permissionPageTemplateSync = {
65531
- object: "PageTemplate",
65532
- action: "sync"
65533
- };
65534
- const permissionPlatformView = {
65535
- object: "Platform",
65536
- action: "view"
65537
- };
65538
- const permissionCourseView = {
65539
- object: "Course",
65540
- action: "view"
65541
- };
65542
- const permissionExtensionView = {
65543
- object: "Extension",
65544
- action: "view"
65545
- };
65546
- const permissionSiteView = {
65547
- object: "Site",
65548
- action: "view"
65549
- };
65550
- const permissionTemplateView = {
65551
- object: "Template",
65552
- action: "view"
65553
- };
65554
- const allPermissions = [
65555
- permissionAssetEdit,
65556
- permissionAssetView,
65557
- permissionExtensionCreate,
65558
- permissionExtensionCreateVersion,
65559
- permissionExtensionEdit,
65560
- permissionExtensionView,
65561
- permissionTemplateCreate,
65562
- permissionComponentEdit,
65563
- permissionCourseEdit,
65564
- permissionCustomComponentEdit,
65565
- permissionCustomFieldEdit,
65566
- permissionFileUploadAsExtension,
65567
- permissionHelpTicketEditStatus,
65568
- permissionSequenceEdit,
65569
- permissionSequenceUserEdit,
65570
- permissionSiteCreate,
65571
- permissionSiteEdit,
65572
- permissionSiteEditDomain,
65573
- permissionSiteEditTls,
65574
- permissionSiteView,
65575
- permissionSubscriptionEdit,
65576
- permissionTemplateEdit,
65577
- permissionTemplateView,
65578
- permissionUserCreate,
65579
- permissionUserEditEmail,
65580
- permissionUserEditOrg,
65581
- permissionUserEditStatus,
65582
- permissionUserEditRole,
65583
- permissionUserEditProfile,
65584
- permissionUserEditCustomFields,
65585
- permissionFormTemplateSync,
65586
- permissionPageTemplateSync,
65587
- permissionPlatformEdit,
65588
- permissionPlatformView,
65589
- permissionCourseView
65590
- ];
65591
- const revokeAllUserPlatformPermissions = async ({
65592
- platformAdminId
65593
- }, db) => {
65594
- await db.query(
65595
- sql.type(
65596
- voidSelectSchema
65597
- )`delete from "Permissions" where "platformAdminId" = ${platformAdminId}`
65598
- );
65599
- };
65600
- const grantAllUserPlatformPermissions = async ({
65601
- platformAdminId
65602
- }, db) => {
65603
- await db.query(
65604
- sql.type(
65605
- voidSelectSchema
65606
- )`insert into "Permissions" ("id", "platformAdminId", "object", "action") values ${sql.join(
65607
- allPermissions.map(
65608
- (permission) => sql.fragment`(${cleanSmallId()}, ${platformAdminId}, ${permission.object}, ${permission.action})`
65609
- ),
65610
- sql.fragment`,`
65611
- )} on conflict ("platformAdminId", "object", "action") do nothing`
65612
- );
65613
- };
65614
66098
  const findPlatformAdminSchema = object({
65615
66099
  id: string(),
65616
66100
  platformId: string(),
@@ -65647,8 +66131,8 @@ const editAdmin = async (opts, env2) => {
65647
66131
  if (!platformAdmin) {
65648
66132
  platformAdmin = await db2.one(
65649
66133
  sql.type(findPlatformAdminSchema)`
65650
- insert into "PlatformAdmins" ("id", "platformId", "userId", "owner", "active")
65651
- values (${cleanSmallId()}, ${platformId}, ${userId}, true, ${active ?? true})
66134
+ insert into "PlatformAdmins" ("platformId", "userId", "owner", "active")
66135
+ values (${platformId}, ${userId}, true, ${active ?? true})
65652
66136
  returning "id", "platformId", "active"
65653
66137
  `
65654
66138
  );
@@ -65918,6 +66402,90 @@ const initDb = async (opts, env2) => {
65918
66402
  coreDbUrl: coreDbUrlObject
65919
66403
  });
65920
66404
  };
66405
+ const parseStartFlag = (value, name) => {
66406
+ const trimmed = value?.trim();
66407
+ if (!trimmed) {
66408
+ return void 0;
66409
+ }
66410
+ if (trimmed === "true") {
66411
+ return true;
66412
+ }
66413
+ console.error(`${name} must be "true" or empty`);
66414
+ process.exit(1);
66415
+ };
66416
+ const startCore = async (opts, env2) => {
66417
+ const image = env2.WIRECHUNK_CORE_DEV_SERVER_IMAGE;
66418
+ if (!image) {
66419
+ console.error("Missing WIRECHUNK_CORE_DEV_SERVER_IMAGE in environment");
66420
+ process.exit(1);
66421
+ }
66422
+ const databaseUrl = env2.WIRECHUNK_CORE_DATABASE_URL_DOCKER || env2.WIRECHUNK_CORE_DATABASE_URL;
66423
+ if (!databaseUrl) {
66424
+ console.error(
66425
+ "Missing WIRECHUNK_CORE_DATABASE_URL_DOCKER or WIRECHUNK_CORE_DATABASE_URL in environment"
66426
+ );
66427
+ process.exit(1);
66428
+ }
66429
+ const envKeep = parseStartFlag(env2.WIRECHUNK_CORE_START_KEEP, "WIRECHUNK_CORE_START_KEEP");
66430
+ const envAttach = parseStartFlag(env2.WIRECHUNK_CORE_START_ATTACH, "WIRECHUNK_CORE_START_ATTACH");
66431
+ const keep = opts.keep ?? envKeep ?? false;
66432
+ const attach = opts.attach ?? envAttach ?? false;
66433
+ const cwd = resolve$1(process.cwd());
66434
+ const args = [
66435
+ "run",
66436
+ "--name",
66437
+ "wirechunk-core",
66438
+ "--env-file",
66439
+ ".env",
66440
+ "--env-file",
66441
+ ".env.local",
66442
+ "-e",
66443
+ `DATABASE_URL=${databaseUrl}`,
66444
+ "-e",
66445
+ "PORT=8080",
66446
+ "-v",
66447
+ `${cwd}:/ext`,
66448
+ "-p",
66449
+ "8080:8080",
66450
+ "-p",
66451
+ "9001:9001"
66452
+ ];
66453
+ if (!keep) {
66454
+ args.push("--rm");
66455
+ }
66456
+ if (attach) {
66457
+ args.push("-it");
66458
+ } else {
66459
+ args.push("-d");
66460
+ }
66461
+ args.push(image);
66462
+ if (opts.verbose) {
66463
+ console.log(`Running docker ${args.join(" ")}`);
66464
+ }
66465
+ let exitCode = 0;
66466
+ try {
66467
+ const result2 = await new Promise(
66468
+ (resolvePromise, rejectPromise) => {
66469
+ const child = spawn("docker", args, { stdio: "inherit" });
66470
+ child.on("error", rejectPromise);
66471
+ child.on("close", (code2, signal) => {
66472
+ resolvePromise({ code: code2, signal });
66473
+ });
66474
+ }
66475
+ );
66476
+ if (result2.signal) {
66477
+ console.error(`docker exited with signal ${result2.signal}`);
66478
+ process.exit(1);
66479
+ }
66480
+ exitCode = result2.code ?? 1;
66481
+ } catch (err) {
66482
+ console.error("Failed to run docker:", err);
66483
+ process.exit(1);
66484
+ }
66485
+ if (exitCode !== 0) {
66486
+ process.exit(exitCode);
66487
+ }
66488
+ };
65921
66489
  const program = new Command().name("wirechunk").option("--verbose", "output debug logging").option(
65922
66490
  "--env-mode <mode>",
65923
66491
  'the mode to use for finding .env files to load environment variables, such as "test" to load .env, .env.test, .env.local, and .env.test.local; also for finding config files to include when creating an extension or extension version, such as config.production.json'
@@ -65928,8 +66496,8 @@ then the .env.local file, and then from the environment. Variables from the envi
65928
66496
  highest precedence.
65929
66497
 
65930
66498
  Environment variables used by some commands:
65931
- CORE_SERVER_URL (the core admin server URL for commands using the API)
65932
- CORE_DATABASE_URL (the core database URL for commands requiring direct database access)`);
66499
+ WIRECHUNK_CORE_SERVER_URL (the core admin server URL for commands using the API)
66500
+ WIRECHUNK_CORE_DATABASE_URL (the core database URL for commands requiring direct database access)`);
65933
66501
  const withOptionsAndEnv = (action) => async (options, cmd) => {
65934
66502
  const mergedOptions = { ...program.opts(), ...options };
65935
66503
  if (mergedOptions.verbose) {
@@ -65938,13 +66506,11 @@ const withOptionsAndEnv = (action) => async (options, cmd) => {
65938
66506
  const env2 = await parseEnv(mergedOptions.envMode);
65939
66507
  return action(mergedOptions, env2);
65940
66508
  };
65941
- program.command("bootstrap").description("create a platform").requiredOption("--name <string>", "the name of the platform").option("--handle <string>", "the handle of the platform (used by the admin site)").requiredOption(
65942
- "--admin-site-domain <string>",
65943
- "the domain of the platform admin site (dashboard)"
65944
- ).option(
65945
- "--email-send-from <string>",
65946
- 'the email address from which to send emails, defaults to "site@<admin-site-domain>'
65947
- ).action(withOptionsAndEnv(bootstrap));
66509
+ program.command("bootstrap").description("create a platform").option("--dev", "bootstrap with development defaults").option("--name <string>", "the name of the platform").option("--handle <string>", "the handle of the platform").option("--admin-site-domain <string>", "the domain of the admin site (dashboard)").action(withOptionsAndEnv(bootstrap));
66510
+ program.command("create-extension").description("create an extension").option("--platform-id <string>", "the ID of the platform").option("--name <string>", "the name of the extension").option(
66511
+ "--config-file <string>",
66512
+ "the path to a file containing environment-style key-value pairs for the extension config"
66513
+ ).option("--dev", "create a dev extension version without uploading code", false).option("--disabled", "create the extension disabled", false).action(withOptionsAndEnv(createExtension));
65948
66514
  program.command("create-extension-version").description("create an extension version").option(
65949
66515
  "--extension-id <string>",
65950
66516
  "the ID of the extension, can be set with an EXTENSION_ID environment variable instead"
@@ -65975,5 +66541,14 @@ extDev.command("init-db").description(
65975
66541
  "--extension-id <string>",
65976
66542
  "the ID of the extension, can be set with an EXTENSION_ID environment variable instead"
65977
66543
  ).option("--db-name <string>", "a custom name for the database, applicable only for testing").action(withOptionsAndEnv(initDb));
66544
+ extDev.command("start-core").description("start the core dev server in Docker").option("--keep", "keep the container after exit (omit --rm)").option("--attach", "run the container attached (omit -d)").option("--tty", "allocate a TTY when attached, requires --attach").action(
66545
+ withOptionsAndEnv((options, env2) => {
66546
+ if (options.tty && !options.attach) {
66547
+ console.error("--tty requires --attach");
66548
+ process.exit(1);
66549
+ }
66550
+ return startCore(options, env2);
66551
+ })
66552
+ );
65978
66553
  program.command("edit-admin").description("edit a platform admin user or make a user a platform admin").requiredOption("--platform-id <string>", "the ID of the platform to edit").requiredOption("--user-id <string>", "the ID of the admin user to edit").option("--owner", "grants the user full permission to manage everything on the platform").option("--no-owner", "removes owner privileges on the platform").option("--active", "activates or deactivates the user’s admin access on the platform").option("--no-active", "deactivates the user’s admin access on the platform").option("--revoke-all-permissions", "revokes all permission of the user on their platform").action(withOptionsAndEnv(editAdmin));
65979
66554
  await program.parseAsync();