@backifydev/cli 0.4.10 → 0.4.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +914 -383
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -2637,13 +2637,13 @@ var require_binaryParsers = __commonJS({
2637
2637
  if (offset % 8 + bits >= 8) {
2638
2638
  result = callback(0, inv(data[offsetBytes]) & mask, firstBits);
2639
2639
  }
2640
- var bytes = bits + offset >> 3;
2641
- for (var i = offsetBytes + 1; i < bytes; i++) {
2640
+ var bytes2 = bits + offset >> 3;
2641
+ for (var i = offsetBytes + 1; i < bytes2; i++) {
2642
2642
  result = callback(result, inv(data[i]), 8);
2643
2643
  }
2644
2644
  var lastBits = (bits + offset) % 8;
2645
2645
  if (lastBits > 0) {
2646
- result = callback(result, inv(data[bytes]) >> 8 - lastBits, lastBits);
2646
+ result = callback(result, inv(data[bytes2]) >> 8 - lastBits, lastBits);
2647
2647
  }
2648
2648
  return result;
2649
2649
  };
@@ -4792,9 +4792,9 @@ var require_parser = __commonJS({
4792
4792
  this.bufferLength = buffer.byteLength;
4793
4793
  }
4794
4794
  }
4795
- handlePacket(offset, code, length, bytes) {
4796
- const { reader } = this;
4797
- reader.setBuffer(offset, bytes);
4795
+ handlePacket(offset, code, length, bytes2) {
4796
+ const { reader: reader2 } = this;
4797
+ reader2.setBuffer(offset, bytes2);
4798
4798
  let message;
4799
4799
  switch (code) {
4800
4800
  case 50:
@@ -4822,132 +4822,132 @@ var require_parser = __commonJS({
4822
4822
  message = messages_1.emptyQuery;
4823
4823
  break;
4824
4824
  case 68:
4825
- message = parseDataRowMessage(reader);
4825
+ message = parseDataRowMessage(reader2);
4826
4826
  break;
4827
4827
  case 67:
4828
- message = parseCommandCompleteMessage(reader);
4828
+ message = parseCommandCompleteMessage(reader2);
4829
4829
  break;
4830
4830
  case 90:
4831
- message = parseReadyForQueryMessage(reader);
4831
+ message = parseReadyForQueryMessage(reader2);
4832
4832
  break;
4833
4833
  case 65:
4834
- message = parseNotificationMessage(reader);
4834
+ message = parseNotificationMessage(reader2);
4835
4835
  break;
4836
4836
  case 82:
4837
- message = parseAuthenticationResponse(reader, length);
4837
+ message = parseAuthenticationResponse(reader2, length);
4838
4838
  break;
4839
4839
  case 83:
4840
- message = parseParameterStatusMessage(reader);
4840
+ message = parseParameterStatusMessage(reader2);
4841
4841
  break;
4842
4842
  case 75:
4843
- message = parseBackendKeyData(reader);
4843
+ message = parseBackendKeyData(reader2);
4844
4844
  break;
4845
4845
  case 69:
4846
- message = parseErrorMessage(reader, "error");
4846
+ message = parseErrorMessage(reader2, "error");
4847
4847
  break;
4848
4848
  case 78:
4849
- message = parseErrorMessage(reader, "notice");
4849
+ message = parseErrorMessage(reader2, "notice");
4850
4850
  break;
4851
4851
  case 84:
4852
- message = parseRowDescriptionMessage(reader);
4852
+ message = parseRowDescriptionMessage(reader2);
4853
4853
  break;
4854
4854
  case 116:
4855
- message = parseParameterDescriptionMessage(reader);
4855
+ message = parseParameterDescriptionMessage(reader2);
4856
4856
  break;
4857
4857
  case 71:
4858
- message = parseCopyInMessage(reader);
4858
+ message = parseCopyInMessage(reader2);
4859
4859
  break;
4860
4860
  case 72:
4861
- message = parseCopyOutMessage(reader);
4861
+ message = parseCopyOutMessage(reader2);
4862
4862
  break;
4863
4863
  case 100:
4864
- message = parseCopyData(reader, length);
4864
+ message = parseCopyData(reader2, length);
4865
4865
  break;
4866
4866
  default:
4867
4867
  return new messages_1.DatabaseError("received invalid response: " + code.toString(16), length, "error");
4868
4868
  }
4869
- reader.setBuffer(0, emptyBuffer);
4869
+ reader2.setBuffer(0, emptyBuffer);
4870
4870
  message.length = length;
4871
4871
  return message;
4872
4872
  }
4873
4873
  };
4874
4874
  exports.Parser = Parser;
4875
- var parseReadyForQueryMessage = (reader) => {
4876
- const status = reader.string(1);
4875
+ var parseReadyForQueryMessage = (reader2) => {
4876
+ const status = reader2.string(1);
4877
4877
  return new messages_1.ReadyForQueryMessage(LATEINIT_LENGTH, status);
4878
4878
  };
4879
- var parseCommandCompleteMessage = (reader) => {
4880
- const text2 = reader.cstring();
4879
+ var parseCommandCompleteMessage = (reader2) => {
4880
+ const text2 = reader2.cstring();
4881
4881
  return new messages_1.CommandCompleteMessage(LATEINIT_LENGTH, text2);
4882
4882
  };
4883
- var parseCopyData = (reader, length) => {
4884
- const chunk = reader.bytes(length - 4);
4883
+ var parseCopyData = (reader2, length) => {
4884
+ const chunk = reader2.bytes(length - 4);
4885
4885
  return new messages_1.CopyDataMessage(LATEINIT_LENGTH, chunk);
4886
4886
  };
4887
- var parseCopyInMessage = (reader) => parseCopyMessage(reader, "copyInResponse");
4888
- var parseCopyOutMessage = (reader) => parseCopyMessage(reader, "copyOutResponse");
4889
- var parseCopyMessage = (reader, messageName) => {
4890
- const isBinary = reader.byte() !== 0;
4891
- const columnCount = reader.int16();
4887
+ var parseCopyInMessage = (reader2) => parseCopyMessage(reader2, "copyInResponse");
4888
+ var parseCopyOutMessage = (reader2) => parseCopyMessage(reader2, "copyOutResponse");
4889
+ var parseCopyMessage = (reader2, messageName) => {
4890
+ const isBinary = reader2.byte() !== 0;
4891
+ const columnCount = reader2.int16();
4892
4892
  const message = new messages_1.CopyResponse(LATEINIT_LENGTH, messageName, isBinary, columnCount);
4893
4893
  for (let i = 0; i < columnCount; i++) {
4894
- message.columnTypes[i] = reader.int16();
4894
+ message.columnTypes[i] = reader2.int16();
4895
4895
  }
4896
4896
  return message;
4897
4897
  };
4898
- var parseNotificationMessage = (reader) => {
4899
- const processId = reader.int32();
4900
- const channel = reader.cstring();
4901
- const payload = reader.cstring();
4898
+ var parseNotificationMessage = (reader2) => {
4899
+ const processId = reader2.int32();
4900
+ const channel = reader2.cstring();
4901
+ const payload = reader2.cstring();
4902
4902
  return new messages_1.NotificationResponseMessage(LATEINIT_LENGTH, processId, channel, payload);
4903
4903
  };
4904
- var parseRowDescriptionMessage = (reader) => {
4905
- const fieldCount = reader.int16();
4904
+ var parseRowDescriptionMessage = (reader2) => {
4905
+ const fieldCount = reader2.int16();
4906
4906
  const message = new messages_1.RowDescriptionMessage(LATEINIT_LENGTH, fieldCount);
4907
4907
  for (let i = 0; i < fieldCount; i++) {
4908
- message.fields[i] = parseField(reader);
4908
+ message.fields[i] = parseField(reader2);
4909
4909
  }
4910
4910
  return message;
4911
4911
  };
4912
- var parseField = (reader) => {
4913
- const name2 = reader.cstring();
4914
- const tableID = reader.uint32();
4915
- const columnID = reader.int16();
4916
- const dataTypeID = reader.uint32();
4917
- const dataTypeSize = reader.int16();
4918
- const dataTypeModifier = reader.int32();
4919
- const mode = reader.int16() === 0 ? "text" : "binary";
4912
+ var parseField = (reader2) => {
4913
+ const name2 = reader2.cstring();
4914
+ const tableID = reader2.uint32();
4915
+ const columnID = reader2.int16();
4916
+ const dataTypeID = reader2.uint32();
4917
+ const dataTypeSize = reader2.int16();
4918
+ const dataTypeModifier = reader2.int32();
4919
+ const mode = reader2.int16() === 0 ? "text" : "binary";
4920
4920
  return new messages_1.Field(name2, tableID, columnID, dataTypeID, dataTypeSize, dataTypeModifier, mode);
4921
4921
  };
4922
- var parseParameterDescriptionMessage = (reader) => {
4923
- const parameterCount = reader.int16();
4922
+ var parseParameterDescriptionMessage = (reader2) => {
4923
+ const parameterCount = reader2.int16();
4924
4924
  const message = new messages_1.ParameterDescriptionMessage(LATEINIT_LENGTH, parameterCount);
4925
4925
  for (let i = 0; i < parameterCount; i++) {
4926
- message.dataTypeIDs[i] = reader.uint32();
4926
+ message.dataTypeIDs[i] = reader2.uint32();
4927
4927
  }
4928
4928
  return message;
4929
4929
  };
4930
- var parseDataRowMessage = (reader) => {
4931
- const fieldCount = reader.int16();
4930
+ var parseDataRowMessage = (reader2) => {
4931
+ const fieldCount = reader2.int16();
4932
4932
  const fields = new Array(fieldCount);
4933
4933
  for (let i = 0; i < fieldCount; i++) {
4934
- const len = reader.int32();
4935
- fields[i] = len === -1 ? null : reader.string(len);
4934
+ const len = reader2.int32();
4935
+ fields[i] = len === -1 ? null : reader2.string(len);
4936
4936
  }
4937
4937
  return new messages_1.DataRowMessage(LATEINIT_LENGTH, fields);
4938
4938
  };
4939
- var parseParameterStatusMessage = (reader) => {
4940
- const name2 = reader.cstring();
4941
- const value = reader.cstring();
4939
+ var parseParameterStatusMessage = (reader2) => {
4940
+ const name2 = reader2.cstring();
4941
+ const value = reader2.cstring();
4942
4942
  return new messages_1.ParameterStatusMessage(LATEINIT_LENGTH, name2, value);
4943
4943
  };
4944
- var parseBackendKeyData = (reader) => {
4945
- const processID = reader.int32();
4946
- const secretKey = reader.int32();
4944
+ var parseBackendKeyData = (reader2) => {
4945
+ const processID = reader2.int32();
4946
+ const secretKey = reader2.int32();
4947
4947
  return new messages_1.BackendKeyDataMessage(LATEINIT_LENGTH, processID, secretKey);
4948
4948
  };
4949
- var parseAuthenticationResponse = (reader, length) => {
4950
- const code = reader.int32();
4949
+ var parseAuthenticationResponse = (reader2, length) => {
4950
+ const code = reader2.int32();
4951
4951
  const message = {
4952
4952
  name: "authenticationOk",
4953
4953
  length
@@ -4963,7 +4963,7 @@ var require_parser = __commonJS({
4963
4963
  case 5:
4964
4964
  if (message.length === 12) {
4965
4965
  message.name = "authenticationMD5Password";
4966
- const salt = reader.bytes(4);
4966
+ const salt = reader2.bytes(4);
4967
4967
  return new messages_1.AuthenticationMD5Password(LATEINIT_LENGTH, salt);
4968
4968
  }
4969
4969
  break;
@@ -4973,7 +4973,7 @@ var require_parser = __commonJS({
4973
4973
  message.mechanisms = [];
4974
4974
  let mechanism;
4975
4975
  do {
4976
- mechanism = reader.cstring();
4976
+ mechanism = reader2.cstring();
4977
4977
  if (mechanism) {
4978
4978
  message.mechanisms.push(mechanism);
4979
4979
  }
@@ -4982,23 +4982,23 @@ var require_parser = __commonJS({
4982
4982
  break;
4983
4983
  case 11:
4984
4984
  message.name = "authenticationSASLContinue";
4985
- message.data = reader.string(length - 8);
4985
+ message.data = reader2.string(length - 8);
4986
4986
  break;
4987
4987
  case 12:
4988
4988
  message.name = "authenticationSASLFinal";
4989
- message.data = reader.string(length - 8);
4989
+ message.data = reader2.string(length - 8);
4990
4990
  break;
4991
4991
  default:
4992
4992
  throw new Error("Unknown authenticationOk message type " + code);
4993
4993
  }
4994
4994
  return message;
4995
4995
  };
4996
- var parseErrorMessage = (reader, name2) => {
4996
+ var parseErrorMessage = (reader2, name2) => {
4997
4997
  const fields = {};
4998
- let fieldType = reader.string(1);
4998
+ let fieldType = reader2.string(1);
4999
4999
  while (fieldType !== "\0") {
5000
- fields[fieldType] = reader.cstring();
5001
- fieldType = reader.string(1);
5000
+ fields[fieldType] = reader2.cstring();
5001
+ fieldType = reader2.string(1);
5002
5002
  }
5003
5003
  const messageValue = fields.M;
5004
5004
  const message = name2 === "notice" ? new messages_1.NoticeMessage(LATEINIT_LENGTH, messageValue) : new messages_1.DatabaseError(messageValue, LATEINIT_LENGTH, name2);
@@ -7537,7 +7537,7 @@ function parse(args2, command2, booleans, valued) {
7537
7537
  return { flags, values, positional };
7538
7538
  }
7539
7539
  function moveArguments(flags, values, positional) {
7540
- const json6 = flags.has("--json"), yes = flags.has("--yes"), usage = "Use backify environments move <environment> --target <id> --window-start <ISO> --window-end <ISO> [--check] [--yes], or move status|start|abort|confirm <environment>.";
7540
+ const json7 = flags.has("--json"), yes = flags.has("--yes"), usage = "Use backify environments move <environment> --target <id> --window-start <ISO> --window-end <ISO> [--check] [--yes], or move status|start|abort|confirm <environment>.";
7541
7541
  if (values["--confirm"]) throw new Error(usage);
7542
7542
  const sub = positional[1]?.toLowerCase();
7543
7543
  const moveAction = sub === "status" || sub === "start" || sub === "abort" || sub === "confirm" ? sub : "request";
@@ -7553,10 +7553,10 @@ function moveArguments(flags, values, positional) {
7553
7553
  if (!target || !uuid3.test(target)) throw new Error("--target takes a deployment target ID.");
7554
7554
  if (!start || !end || Number.isNaN(Date.parse(start)) || Number.isNaN(Date.parse(end))) throw new Error("--window-start and --window-end take ISO date-times, for example 2026-11-20T22:00:00Z.");
7555
7555
  if (Date.parse(end) <= Date.parse(start)) throw new Error("--window-end must be after --window-start.");
7556
- return { action: "move", moveAction, kind: kind2, target, windowStart: new Date(start).toISOString(), windowEnd: new Date(end).toISOString(), check: flags.has("--check"), yes, json: json6 };
7556
+ return { action: "move", moveAction, kind: kind2, target, windowStart: new Date(start).toISOString(), windowEnd: new Date(end).toISOString(), check: flags.has("--check"), yes, json: json7 };
7557
7557
  }
7558
7558
  if (moveAction === "confirm" && (!active || !uuid3.test(active))) throw new Error("--active takes the ID of the deployment target that is serving the environment.");
7559
- return { action: "move", moveAction, kind: kind2, ...active ? { active } : {}, yes, json: json6 };
7559
+ return { action: "move", moveAction, kind: kind2, ...active ? { active } : {}, yes, json: json7 };
7560
7560
  }
7561
7561
  function moveBackArguments(flags, values, positional) {
7562
7562
  const usage = "Use backify environments move-back <environment> --window-start <ISO> --window-end <ISO> --confirm <application-slug>.";
@@ -7585,22 +7585,22 @@ function environmentsArguments(args2) {
7585
7585
  }
7586
7586
  if (values["--window-start"] || values["--window-end"] || values["--active"]) throw new Error("--window-start, --window-end and --active apply to environments move.");
7587
7587
  if (action === "placement") {
7588
- const json7 = flags.has("--json"), kind3 = positional[1]?.toLowerCase(), target = values["--target"]?.toLowerCase();
7588
+ const json8 = flags.has("--json"), kind3 = positional[1]?.toLowerCase(), target = values["--target"]?.toLowerCase();
7589
7589
  if (values["--confirm"] || positional.length > 2) throw new Error("Use backify environments placement [<environment> --target <deployment-target-id|default> [--check] [--yes]].");
7590
7590
  if (!kind3) {
7591
7591
  if (target || flags.has("--check") || flags.has("--yes")) throw new Error("Name the environment to place: backify environments placement <environment> --target <deployment-target-id|default>.");
7592
- return { action, yes: false, json: json7 };
7592
+ return { action, yes: false, json: json8 };
7593
7593
  }
7594
7594
  if (!ENVIRONMENT_FLOW.includes(kind3)) throw new Error("Unknown environment: " + positional[1] + ". Use " + ENVIRONMENT_FLOW.join(", ") + ".");
7595
7595
  if (!target || target !== "default" && !uuid3.test(target)) throw new Error("--target takes a deployment target ID, or default for the application's own target.");
7596
- return { action, kind: kind3, target, check: flags.has("--check"), yes: flags.has("--yes"), json: json7 };
7596
+ return { action, kind: kind3, target, check: flags.has("--check"), yes: flags.has("--yes"), json: json8 };
7597
7597
  }
7598
7598
  if (flags.has("--check") || values["--target"]) throw new Error("--target and --check apply to environments placement.");
7599
7599
  if (action !== "list" && action !== "add" && action !== "remove") throw new Error("Unknown environments command: " + action + "\n\n" + environmentsHelp);
7600
- const json6 = flags.has("--json");
7600
+ const json7 = flags.has("--json");
7601
7601
  if (action === "list") {
7602
7602
  if (positional.length > 1 || flags.has("--yes") || values["--confirm"]) throw new Error("backify environments takes only --app and --json.\n\n" + environmentsHelp);
7603
- return { action, yes: false, json: json6 };
7603
+ return { action, yes: false, json: json7 };
7604
7604
  }
7605
7605
  const kind2 = positional[1]?.toLowerCase();
7606
7606
  if (positional.length !== 2 || !kind2) throw new Error(`Use backify environments ${action} <preview|prototype>.`);
@@ -7608,7 +7608,7 @@ function environmentsArguments(args2) {
7608
7608
  if (!OPTIONAL_ENVIRONMENTS.includes(kind2)) throw new Error(`Unknown environment: ${positional[1]}. Use backify environments ${action} <preview|prototype>.`);
7609
7609
  if (action === "add" && values["--confirm"]) throw new Error("--confirm applies to environments remove. Use --yes to add without the prompt.");
7610
7610
  if (action === "remove" && flags.has("--yes")) throw new Error("Removing an environment is confirmed with --confirm <application-slug>, not --yes.");
7611
- return { action, kind: kind2, confirm: values["--confirm"], yes: flags.has("--yes"), json: json6 };
7611
+ return { action, kind: kind2, confirm: values["--confirm"], yes: flags.has("--yes"), json: json7 };
7612
7612
  }
7613
7613
  function pad(rows) {
7614
7614
  const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
@@ -8043,7 +8043,7 @@ var init_package = __esm({
8043
8043
  "package.json"() {
8044
8044
  package_default = {
8045
8045
  name: "@backifydev/cli",
8046
- version: "0.4.10",
8046
+ version: "0.4.11",
8047
8047
  description: "Command-line setup and diagnostics for Backify applications",
8048
8048
  type: "module",
8049
8049
  bin: {
@@ -8514,7 +8514,7 @@ function apiClient(session, transport = fetch) {
8514
8514
  return async (path, init) => {
8515
8515
  if (!path.startsWith("/") || path.startsWith("//")) throw new Error("Invalid API path.");
8516
8516
  if (session.expiresAt && Date.parse(session.expiresAt) <= Date.now()) throw new CliAuthenticationRequired();
8517
- const response = await transport(base + path, { ...init, redirect: "error", signal: AbortSignal.timeout(3e4), headers: { "content-type": "application/json", ...cliHeaders, "X-Organization-ID": session.organizationId, ...session.token ? { authorization: "Bearer " + session.token } : {}, ...init?.headers } });
8517
+ const response = await transport(base + path, { ...init, redirect: "error", signal: AbortSignal.timeout(3e4), headers: { ...init?.body instanceof FormData ? {} : { "content-type": "application/json" }, ...cliHeaders, "X-Organization-ID": session.organizationId, ...session.token ? { authorization: "Bearer " + session.token } : {}, ...init?.headers } });
8518
8518
  showClientNotice(response);
8519
8519
  if (!response.ok) {
8520
8520
  if (response.status === 401) throw new CliAuthenticationRequired();
@@ -8527,6 +8527,7 @@ function apiClient(session, transport = fetch) {
8527
8527
  throw new Error(message);
8528
8528
  }
8529
8529
  if (new Headers(init?.headers).get("accept")?.startsWith("text/plain")) return await response.text();
8530
+ if (new Headers(init?.headers).get("accept")?.startsWith("application/octet-stream")) return Buffer.from(await response.arrayBuffer());
8530
8531
  return response.status === 204 ? void 0 : await response.json();
8531
8532
  };
8532
8533
  }
@@ -8623,10 +8624,10 @@ async function readPrompt(input) {
8623
8624
  const chunks = [];
8624
8625
  let size = 0;
8625
8626
  for await (const chunk of input) {
8626
- const bytes = Buffer.from(chunk);
8627
- size += bytes.length;
8627
+ const bytes2 = Buffer.from(chunk);
8628
+ size += bytes2.length;
8628
8629
  if (size > 128e3) throw new Error("Prompt exceeds the size limit.");
8629
- chunks.push(bytes);
8630
+ chunks.push(bytes2);
8630
8631
  }
8631
8632
  const text2 = Buffer.concat(chunks).toString("utf8");
8632
8633
  if (!text2.trim() || text2.length > 32e3) throw new Error("Provide between 1 and 32000 characters of user prompt text.");
@@ -8977,10 +8978,10 @@ function opsArguments(args2) {
8977
8978
  case "--offset":
8978
8979
  case "--limit": {
8979
8980
  if (!/^\d{1,6}$/.test(value)) throw new Error(flag + " must be a non-negative integer.");
8980
- const number4 = Number(value);
8981
- if (flag === "--limit" && (number4 < 1 || number4 > 100)) throw new Error("--limit must be from 1 to 100.");
8982
- if (flag === "--offset") parsed.offset = number4;
8983
- else parsed.limit = number4;
8981
+ const number5 = Number(value);
8982
+ if (flag === "--limit" && (number5 < 1 || number5 > 100)) throw new Error("--limit must be from 1 to 100.");
8983
+ if (flag === "--offset") parsed.offset = number5;
8984
+ else parsed.limit = number5;
8984
8985
  break;
8985
8986
  }
8986
8987
  case "--param": {
@@ -9133,11 +9134,11 @@ function operationInput(operation, options, organizationId, context2 = {}) {
9133
9134
  if (Object.keys(parameters).length) input.parameters = parameters;
9134
9135
  if (options.body !== void 0) {
9135
9136
  const source = options.body.startsWith("@") && options.body.length > 1 ? options.body.substring(1) : options.body;
9136
- const bytes = readInput(source, context2, "body file");
9137
- if (operation.rawBodyContentType) input.rawBodyBase64 = bytes.toString("base64");
9137
+ const bytes2 = readInput(source, context2, "body file");
9138
+ if (operation.rawBodyContentType) input.rawBodyBase64 = bytes2.toString("base64");
9138
9139
  else {
9139
9140
  try {
9140
- input.body = JSON.parse(bytes.toString("utf8").replace(/^/, ""));
9141
+ input.body = JSON.parse(bytes2.toString("utf8").replace(/^/, ""));
9141
9142
  } catch {
9142
9143
  throw new OpsError(`The body in ${options.body === "-" ? "standard input" : source} is not valid JSON.`, "invalid_input");
9143
9144
  }
@@ -9153,8 +9154,8 @@ function redact(value) {
9153
9154
  function describeBody(body) {
9154
9155
  if (!body) return void 0;
9155
9156
  if (body.kind === "json") return redact(body.value);
9156
- const bytes = Math.floor(body.contentBase64.length * 3 / 4);
9157
- return body.kind === "raw" ? { contentType: body.contentType, bytes } : { file: body.name, field: body.field, contentType: body.contentType, bytes };
9157
+ const bytes2 = Math.floor(body.contentBase64.length * 3 / 4);
9158
+ return body.kind === "raw" ? { contentType: body.contentType, bytes: bytes2 } : { file: body.name, field: body.field, contentType: body.contentType, bytes: bytes2 };
9158
9159
  }
9159
9160
  function approvalMessage(operation, organizationId, url2, body) {
9160
9161
  const lines = [`Run ${operation.id}${operation.summary ? ` (${operation.summary})` : ""} in organization ${organizationId}?`, `${operation.method} ${url2}`];
@@ -9576,7 +9577,7 @@ async function orgProtection(call2, organizationId, action, values, yes, confirm
9576
9577
  const current = (await call2(path)).settings ?? {};
9577
9578
  const next = applyFlags(current, values, true);
9578
9579
  await confirmed(`Set the ${scope}'s protection to ${describeSettings(next)}? It applies to every application in the ${scope} at once, including applications that declare no protection in code.`);
9579
- await call2(path, { method: "PUT", headers: json2, body: JSON.stringify(next) });
9580
+ await call2(path, { method: "PUT", headers: json3, body: JSON.stringify(next) });
9580
9581
  const result = await read();
9581
9582
  return { ...result, text: "Protection saved.\n" + result.text, exitCode: 0 };
9582
9583
  }
@@ -9613,7 +9614,7 @@ async function appProtection(call2, appId, args2) {
9613
9614
  case "set": {
9614
9615
  const current = environmentPath ? (await call2(environmentPath)).overrides ?? {} : (await call2(appPath)).overrides ?? {};
9615
9616
  const next = applyFlags(current, values, false);
9616
- return { value: await call2(environmentPath ?? appPath, { method: "PUT", headers: json2, body: JSON.stringify(next) }), text: void 0 };
9617
+ return { value: await call2(environmentPath ?? appPath, { method: "PUT", headers: json3, body: JSON.stringify(next) }), text: void 0 };
9617
9618
  }
9618
9619
  case "reset":
9619
9620
  await call2(environmentPath ?? appPath, { method: "DELETE" });
@@ -9632,14 +9633,14 @@ async function appProtection(call2, appId, args2) {
9632
9633
  throw new Error(protectionUsage);
9633
9634
  }
9634
9635
  }
9635
- var MODES, json2, choice, blocks, describeSettings, orgProtectionUsage, protectionUsage;
9636
+ var MODES, json3, choice, blocks, describeSettings, orgProtectionUsage, protectionUsage;
9636
9637
  var init_protection2 = __esm({
9637
9638
  "src/protection.ts"() {
9638
9639
  "use strict";
9639
9640
  init_human_task();
9640
9641
  init_ops();
9641
9642
  MODES = ["off", "monitor", "standard", "strict"];
9642
- json2 = { "content-type": "application/json" };
9643
+ json3 = { "content-type": "application/json" };
9643
9644
  choice = (values, name2, allowed) => {
9644
9645
  const value = values[name2]?.[0];
9645
9646
  if (value !== void 0 && !allowed.includes(value)) throw new Error(`--${name2} must be ${allowed.slice(0, -1).join(", ")} or ${allowed.at(-1)}.`);
@@ -10412,16 +10413,16 @@ function cleanEnum(obj) {
10412
10413
  }
10413
10414
  function base64ToUint8Array(base643) {
10414
10415
  const binaryString = atob(base643);
10415
- const bytes = new Uint8Array(binaryString.length);
10416
+ const bytes2 = new Uint8Array(binaryString.length);
10416
10417
  for (let i = 0; i < binaryString.length; i++) {
10417
- bytes[i] = binaryString.charCodeAt(i);
10418
+ bytes2[i] = binaryString.charCodeAt(i);
10418
10419
  }
10419
- return bytes;
10420
+ return bytes2;
10420
10421
  }
10421
- function uint8ArrayToBase64(bytes) {
10422
+ function uint8ArrayToBase64(bytes2) {
10422
10423
  let binaryString = "";
10423
- for (let i = 0; i < bytes.length; i++) {
10424
- binaryString += String.fromCharCode(bytes[i]);
10424
+ for (let i = 0; i < bytes2.length; i++) {
10425
+ binaryString += String.fromCharCode(bytes2[i]);
10425
10426
  }
10426
10427
  return btoa(binaryString);
10427
10428
  }
@@ -10430,22 +10431,22 @@ function base64urlToUint8Array(base64url2) {
10430
10431
  const padding = "=".repeat((4 - base643.length % 4) % 4);
10431
10432
  return base64ToUint8Array(base643 + padding);
10432
10433
  }
10433
- function uint8ArrayToBase64url(bytes) {
10434
- return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
10434
+ function uint8ArrayToBase64url(bytes2) {
10435
+ return uint8ArrayToBase64(bytes2).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
10435
10436
  }
10436
10437
  function hexToUint8Array(hex) {
10437
10438
  const cleanHex = hex.replace(/^0x/, "");
10438
10439
  if (cleanHex.length % 2 !== 0) {
10439
10440
  throw new Error("Invalid hex string length");
10440
10441
  }
10441
- const bytes = new Uint8Array(cleanHex.length / 2);
10442
+ const bytes2 = new Uint8Array(cleanHex.length / 2);
10442
10443
  for (let i = 0; i < cleanHex.length; i += 2) {
10443
- bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);
10444
+ bytes2[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);
10444
10445
  }
10445
- return bytes;
10446
+ return bytes2;
10446
10447
  }
10447
- function uint8ArrayToHex(bytes) {
10448
- return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
10448
+ function uint8ArrayToHex(bytes2) {
10449
+ return Array.from(bytes2).map((b) => b.toString(16).padStart(2, "0")).join("");
10449
10450
  }
10450
10451
  function members(proto, table) {
10451
10452
  for (const key in table) {
@@ -11098,7 +11099,7 @@ function datetime(args2) {
11098
11099
  const timeRegex = args2.local ? `${qualified}|${timeSource({ precision: args2.precision })}` : qualified;
11099
11100
  return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
11100
11101
  }
11101
- var cuid, cuid2, ulid, xid, ksuid, nanoid, duration2, guid3, uuid9, email, _emoji, ipv4, ipv6, cidrv4, cidrv6, base642, base64url, httpProtocol, e164, dateSource, date, anyString, bigint, integer, number, boolean, _null, lowercase, uppercase;
11102
+ var cuid, cuid2, ulid, xid, ksuid, nanoid, duration2, guid4, uuid9, email, _emoji, ipv4, ipv6, cidrv4, cidrv6, base642, base64url, httpProtocol, e164, dateSource, date, anyString, bigint, integer2, number, boolean, _null, lowercase, uppercase;
11102
11103
  var init_regexes = __esm({
11103
11104
  "../../node_modules/zod/v4/core/regexes.js"() {
11104
11105
  cuid = /^[cC][0-9a-z]{6,}$/;
@@ -11108,7 +11109,7 @@ var init_regexes = __esm({
11108
11109
  ksuid = /^[A-Za-z0-9]{27}$/;
11109
11110
  nanoid = /^[a-zA-Z0-9_-]{21}$/;
11110
11111
  duration2 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
11111
- guid3 = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
11112
+ guid4 = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
11112
11113
  uuid9 = (version2) => {
11113
11114
  if (!version2)
11114
11115
  return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
@@ -11128,7 +11129,7 @@ var init_regexes = __esm({
11128
11129
  date = /* @__PURE__ */ anchor(dateSource);
11129
11130
  anyString = /^[\s\S]{0,}$/;
11130
11131
  bigint = /^-?\d+n?$/;
11131
- integer = /^-?\d+$/;
11132
+ integer2 = /^-?\d+$/;
11132
11133
  number = /^-?\d+(?:\.\d+)?$/;
11133
11134
  boolean = /^(?:true|false)$/i;
11134
11135
  _null = /^null$/i;
@@ -12123,7 +12124,7 @@ var init_schemas = __esm({
12123
12124
  $ZodString.init(inst, def);
12124
12125
  });
12125
12126
  $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => {
12126
- def.pattern ?? (def.pattern = guid3);
12127
+ def.pattern ?? (def.pattern = guid4);
12127
12128
  $ZodStringFormat.init(inst, def);
12128
12129
  });
12129
12130
  $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => {
@@ -14334,13 +14335,13 @@ function initializeContext(params) {
14334
14335
  external: params?.external ?? void 0
14335
14336
  };
14336
14337
  }
14337
- function handleUnrepresentable(schema, ctx, json6, params, message) {
14338
+ function handleUnrepresentable(schema, ctx, json7, params, message) {
14338
14339
  const result = typeof ctx.unrepresentable === "function" ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message }) : ctx.unrepresentable;
14339
14340
  if (result === "any")
14340
14341
  return false;
14341
14342
  if (result === void 0 || result === "throw")
14342
14343
  throw new Error(message);
14343
- Object.assign(json6, result);
14344
+ Object.assign(json7, result);
14344
14345
  return true;
14345
14346
  }
14346
14347
  function processSchema(schema, ctx, _params = { path: [], schemaPath: [] }) {
@@ -14574,12 +14575,12 @@ function foldObjects(members2) {
14574
14575
  }
14575
14576
  return folded;
14576
14577
  }
14577
- function foldIntersection(json6) {
14578
- const allOf = json6.allOf;
14578
+ function foldIntersection(json7) {
14579
+ const allOf = json7.allOf;
14579
14580
  if (!Array.isArray(allOf) || allOf.length < 2)
14580
14581
  return;
14581
14582
  for (const key of FOLDABLE_KEYS)
14582
- if (key in json6)
14583
+ if (key in json7)
14583
14584
  return;
14584
14585
  const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k])));
14585
14586
  let folded = null;
@@ -14598,8 +14599,8 @@ function foldIntersection(json6) {
14598
14599
  }
14599
14600
  if (!folded)
14600
14601
  return;
14601
- delete json6.allOf;
14602
- assignProps(json6, folded);
14602
+ delete json7.allOf;
14603
+ assignProps(json7, folded);
14603
14604
  }
14604
14605
  function finalize(ctx, schema) {
14605
14606
  const root = ctx.seen.get(schema);
@@ -14681,20 +14682,20 @@ function finalize(ctx, schema) {
14681
14682
  if (ctx.intersections.length) {
14682
14683
  const carriers = /* @__PURE__ */ new Map();
14683
14684
  for (const seen of ctx.seen.values()) {
14684
- for (const json6 of [seen.schema, seen.def]) {
14685
- const allOf = json6?.allOf;
14685
+ for (const json7 of [seen.schema, seen.def]) {
14686
+ const allOf = json7?.allOf;
14686
14687
  if (!Array.isArray(allOf))
14687
14688
  continue;
14688
14689
  const existing = carriers.get(allOf);
14689
14690
  if (existing)
14690
- existing.push(json6);
14691
+ existing.push(json7);
14691
14692
  else
14692
- carriers.set(allOf, [json6]);
14693
+ carriers.set(allOf, [json7]);
14693
14694
  }
14694
14695
  }
14695
14696
  for (const allOf of ctx.intersections) {
14696
- for (const json6 of carriers.get(allOf) ?? [])
14697
- foldIntersection(json6);
14697
+ for (const json7 of carriers.get(allOf) ?? [])
14698
+ foldIntersection(json7);
14698
14699
  }
14699
14700
  }
14700
14701
  }
@@ -14874,31 +14875,31 @@ function inputOptin(schema) {
14874
14875
  }
14875
14876
  return schema._zod.optin;
14876
14877
  }
14877
- function stringifyKeyNames(bySchema, json6, visited) {
14878
- if (json6.$ref) {
14879
- if (visited.has(json6))
14880
- return json6;
14881
- visited.add(json6);
14882
- const def = bySchema.get(json6)?.def;
14878
+ function stringifyKeyNames(bySchema, json7, visited) {
14879
+ if (json7.$ref) {
14880
+ if (visited.has(json7))
14881
+ return json7;
14882
+ visited.add(json7);
14883
+ const def = bySchema.get(json7)?.def;
14883
14884
  if (!def)
14884
- return json6;
14885
+ return json7;
14885
14886
  const inlined = stringifyKeyNames(bySchema, def, visited);
14886
- return inlined === def ? json6 : inlined;
14887
+ return inlined === def ? json7 : inlined;
14887
14888
  }
14888
14889
  for (const keyword of ["anyOf", "oneOf"]) {
14889
- const branches = json6[keyword];
14890
+ const branches = json7[keyword];
14890
14891
  if (!Array.isArray(branches))
14891
14892
  continue;
14892
14893
  const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited));
14893
14894
  if (mapped.some((branch, i) => branch !== branches[i]))
14894
- json6 = { ...json6, [keyword]: mapped };
14895
+ json7 = { ...json7, [keyword]: mapped };
14895
14896
  }
14896
- const types2 = Array.isArray(json6.type) ? json6.type : [json6.type];
14897
+ const types2 = Array.isArray(json7.type) ? json7.type : [json7.type];
14897
14898
  const numericType = !types2.includes("string") && types2.some((t) => t === "number" || t === "integer");
14898
- const values = json6.enum ?? (json6.const !== void 0 ? [json6.const] : void 0);
14899
+ const values = json7.enum ?? (json7.const !== void 0 ? [json7.const] : void 0);
14899
14900
  if (!numericType && !values?.some((v) => typeof v === "number"))
14900
- return json6;
14901
- const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json6;
14901
+ return json7;
14902
+ const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json7;
14902
14903
  if (rest.enum)
14903
14904
  rest.enum = rest.enum.map((v) => typeof v === "number" ? String(v) : v);
14904
14905
  else if (typeof rest.const === "number")
@@ -14907,7 +14908,7 @@ function stringifyKeyNames(bySchema, json6, visited) {
14907
14908
  return rest;
14908
14909
  rest.type = "string";
14909
14910
  if (!values)
14910
- rest.pattern = (types2.includes("number") ? number : integer).source;
14911
+ rest.pattern = (types2.includes("number") ? number : integer2).source;
14911
14912
  return rest;
14912
14913
  }
14913
14914
  function rewriteKeyNames(ctx) {
@@ -14936,7 +14937,7 @@ function rewriteKeyNames(ctx) {
14936
14937
  }
14937
14938
  }
14938
14939
  }
14939
- function serializeDefaultValue(value, schema, ctx, json6, params) {
14940
+ function serializeDefaultValue(value, schema, ctx, json7, params) {
14940
14941
  let unrepresentable = false;
14941
14942
  const serialized = JSON.stringify(value, (_, val) => {
14942
14943
  if (typeof val !== "bigint")
@@ -14946,7 +14947,7 @@ function serializeDefaultValue(value, schema, ctx, json6, params) {
14946
14947
  });
14947
14948
  if (!unrepresentable)
14948
14949
  return JSON.parse(serialized);
14949
- handleUnrepresentable(schema, ctx, json6, params, "BigInt defaults cannot be represented in JSON Schema");
14950
+ handleUnrepresentable(schema, ctx, json7, params, "BigInt defaults cannot be represented in JSON Schema");
14950
14951
  return UNREPRESENTABLE_DEFAULT;
14951
14952
  }
14952
14953
  var narrowMin, narrowMax, narrowBoth, addDivisor, addPattern, intersectMime, setFormat, minContributor, maxContributor, formatContributor, contributors, formatMap, exactPatterns, exactPattern, stringProcessor, numberProcessor, booleanProcessor, bigintProcessor, nullProcessor, neverProcessor, anyProcessor, unknownProcessor, dateProcessor, enumProcessor, literalProcessor, customProcessor, transformProcessor, arrayProcessor, objectProcessor, unionProcessor, intersectionProcessor, pendingRecords, recordProcessor, nullableProcessor, nonoptionalProcessor, UNREPRESENTABLE_DEFAULT, defaultProcessor, prefaultProcessor, catchProcessor, pipeProcessor, readonlyProcessor, optionalProcessor;
@@ -15030,29 +15031,29 @@ var init_json_schema_processors = __esm({
15030
15031
  ]);
15031
15032
  exactPattern = (p) => exactPatterns.get(p) ?? p;
15032
15033
  stringProcessor = (schema, ctx, _json, _params) => {
15033
- const json6 = _json;
15034
- json6.type = "string";
15034
+ const json7 = _json;
15035
+ json7.type = "string";
15035
15036
  const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema);
15036
15037
  if (typeof minimum === "number")
15037
- json6.minLength = minimum;
15038
+ json7.minLength = minimum;
15038
15039
  if (typeof maximum === "number")
15039
- json6.maxLength = maximum;
15040
+ json7.maxLength = maximum;
15040
15041
  if (format) {
15041
- json6.format = formatMap[format] ?? format;
15042
- if (json6.format === "")
15043
- delete json6.format;
15042
+ json7.format = formatMap[format] ?? format;
15043
+ if (json7.format === "")
15044
+ delete json7.format;
15044
15045
  if (format === "time" || laxFormat) {
15045
- delete json6.format;
15046
+ delete json7.format;
15046
15047
  }
15047
15048
  }
15048
15049
  if (contentEncoding)
15049
- json6.contentEncoding = contentEncoding;
15050
+ json7.contentEncoding = contentEncoding;
15050
15051
  if (patterns && patterns.size > 0) {
15051
15052
  const patternList = [...patterns].map(exactPattern);
15052
15053
  if (patternList.length === 1)
15053
- json6.pattern = patternList[0].source;
15054
+ json7.pattern = patternList[0].source;
15054
15055
  else if (patternList.length > 1) {
15055
- json6.allOf = [
15056
+ json7.allOf = [
15056
15057
  ...patternList.map((regex) => ({
15057
15058
  ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {},
15058
15059
  pattern: regex.source
@@ -15062,31 +15063,31 @@ var init_json_schema_processors = __esm({
15062
15063
  }
15063
15064
  };
15064
15065
  numberProcessor = (schema, ctx, _json, params) => {
15065
- const json6 = _json;
15066
+ const json7 = _json;
15066
15067
  const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema);
15067
- json6.type = isInt ? "integer" : "number";
15068
+ json7.type = isInt ? "integer" : "number";
15068
15069
  const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);
15069
15070
  const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);
15070
15071
  const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0";
15071
15072
  if (exMin) {
15072
15073
  if (legacy) {
15073
- json6.minimum = exclusiveMinimum;
15074
- json6.exclusiveMinimum = true;
15074
+ json7.minimum = exclusiveMinimum;
15075
+ json7.exclusiveMinimum = true;
15075
15076
  } else {
15076
- json6.exclusiveMinimum = exclusiveMinimum;
15077
+ json7.exclusiveMinimum = exclusiveMinimum;
15077
15078
  }
15078
15079
  } else if (typeof minimum === "number") {
15079
- json6.minimum = minimum;
15080
+ json7.minimum = minimum;
15080
15081
  }
15081
15082
  if (exMax) {
15082
15083
  if (legacy) {
15083
- json6.maximum = exclusiveMaximum;
15084
- json6.exclusiveMaximum = true;
15084
+ json7.maximum = exclusiveMaximum;
15085
+ json7.exclusiveMaximum = true;
15085
15086
  } else {
15086
- json6.exclusiveMaximum = exclusiveMaximum;
15087
+ json7.exclusiveMaximum = exclusiveMaximum;
15087
15088
  }
15088
15089
  } else if (typeof maximum === "number") {
15089
- json6.maximum = maximum;
15090
+ json7.maximum = maximum;
15090
15091
  }
15091
15092
  if (multipleOf) {
15092
15093
  const divisors = /* @__PURE__ */ new Set();
@@ -15094,66 +15095,66 @@ var init_json_schema_processors = __esm({
15094
15095
  if (Number.isFinite(divisor) && divisor !== 0)
15095
15096
  divisors.add(Math.abs(divisor));
15096
15097
  else
15097
- handleUnrepresentable(schema, ctx, json6, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);
15098
+ handleUnrepresentable(schema, ctx, json7, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);
15098
15099
  }
15099
15100
  const [first, ...rest] = divisors;
15100
15101
  if (first !== void 0)
15101
- json6.multipleOf = first;
15102
+ json7.multipleOf = first;
15102
15103
  if (rest.length)
15103
- json6.allOf = [...json6.allOf ?? [], ...rest.map((m) => ({ multipleOf: m }))];
15104
+ json7.allOf = [...json7.allOf ?? [], ...rest.map((m) => ({ multipleOf: m }))];
15104
15105
  }
15105
15106
  };
15106
- booleanProcessor = (_schema, _ctx, json6, _params) => {
15107
- json6.type = "boolean";
15107
+ booleanProcessor = (_schema, _ctx, json7, _params) => {
15108
+ json7.type = "boolean";
15108
15109
  };
15109
- bigintProcessor = (schema, ctx, json6, params) => {
15110
- handleUnrepresentable(schema, ctx, json6, params, "BigInt cannot be represented in JSON Schema");
15110
+ bigintProcessor = (schema, ctx, json7, params) => {
15111
+ handleUnrepresentable(schema, ctx, json7, params, "BigInt cannot be represented in JSON Schema");
15111
15112
  };
15112
- nullProcessor = (_schema, ctx, json6, _params) => {
15113
+ nullProcessor = (_schema, ctx, json7, _params) => {
15113
15114
  if (ctx.target === "openapi-3.0") {
15114
- json6.type = "string";
15115
- json6.nullable = true;
15116
- json6.enum = [null];
15115
+ json7.type = "string";
15116
+ json7.nullable = true;
15117
+ json7.enum = [null];
15117
15118
  } else {
15118
- json6.type = "null";
15119
+ json7.type = "null";
15119
15120
  }
15120
15121
  };
15121
- neverProcessor = (_schema, _ctx, json6, _params) => {
15122
- json6.not = {};
15122
+ neverProcessor = (_schema, _ctx, json7, _params) => {
15123
+ json7.not = {};
15123
15124
  };
15124
15125
  anyProcessor = (_schema, _ctx, _json, _params) => {
15125
15126
  };
15126
15127
  unknownProcessor = (_schema, _ctx, _json, _params) => {
15127
15128
  };
15128
- dateProcessor = (schema, ctx, json6, params) => {
15129
- handleUnrepresentable(schema, ctx, json6, params, "Date cannot be represented in JSON Schema");
15129
+ dateProcessor = (schema, ctx, json7, params) => {
15130
+ handleUnrepresentable(schema, ctx, json7, params, "Date cannot be represented in JSON Schema");
15130
15131
  };
15131
- enumProcessor = (schema, _ctx, json6, _params) => {
15132
+ enumProcessor = (schema, _ctx, json7, _params) => {
15132
15133
  const def = schema._zod.def;
15133
15134
  const values = getEnumValues(def.entries);
15134
15135
  if (values.length === 0) {
15135
- json6.not = {};
15136
+ json7.not = {};
15136
15137
  return;
15137
15138
  }
15138
15139
  if (values.every((v) => typeof v === "number"))
15139
- json6.type = "number";
15140
+ json7.type = "number";
15140
15141
  if (values.every((v) => typeof v === "string"))
15141
- json6.type = "string";
15142
- json6.enum = values;
15142
+ json7.type = "string";
15143
+ json7.enum = values;
15143
15144
  };
15144
- literalProcessor = (schema, ctx, json6, params) => {
15145
+ literalProcessor = (schema, ctx, json7, params) => {
15145
15146
  const def = schema._zod.def;
15146
15147
  if (def.values.length === 0) {
15147
- json6.not = {};
15148
+ json7.not = {};
15148
15149
  return;
15149
15150
  }
15150
15151
  const vals = [];
15151
15152
  for (const val of def.values) {
15152
15153
  if (val === void 0) {
15153
- if (handleUnrepresentable(schema, ctx, json6, params, "Literal `undefined` cannot be represented in JSON Schema"))
15154
+ if (handleUnrepresentable(schema, ctx, json7, params, "Literal `undefined` cannot be represented in JSON Schema"))
15154
15155
  return;
15155
15156
  } else if (typeof val === "bigint") {
15156
- if (handleUnrepresentable(schema, ctx, json6, params, "BigInt literals cannot be represented in JSON Schema"))
15157
+ if (handleUnrepresentable(schema, ctx, json7, params, "BigInt literals cannot be represented in JSON Schema"))
15157
15158
  return;
15158
15159
  vals.push(Number(val));
15159
15160
  } else {
@@ -15163,56 +15164,56 @@ var init_json_schema_processors = __esm({
15163
15164
  if (vals.length === 0) {
15164
15165
  } else if (vals.length === 1) {
15165
15166
  const val = vals[0];
15166
- json6.type = val === null ? "null" : typeof val;
15167
+ json7.type = val === null ? "null" : typeof val;
15167
15168
  if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
15168
- json6.enum = [val];
15169
+ json7.enum = [val];
15169
15170
  } else {
15170
- json6.const = val;
15171
+ json7.const = val;
15171
15172
  }
15172
15173
  } else {
15173
15174
  if (vals.every((v) => typeof v === "number"))
15174
- json6.type = "number";
15175
+ json7.type = "number";
15175
15176
  if (vals.every((v) => typeof v === "string"))
15176
- json6.type = "string";
15177
+ json7.type = "string";
15177
15178
  if (vals.every((v) => typeof v === "boolean"))
15178
- json6.type = "boolean";
15179
+ json7.type = "boolean";
15179
15180
  if (vals.every((v) => v === null))
15180
- json6.type = "null";
15181
- json6.enum = vals;
15181
+ json7.type = "null";
15182
+ json7.enum = vals;
15182
15183
  }
15183
15184
  };
15184
- customProcessor = (schema, ctx, json6, params) => {
15185
- handleUnrepresentable(schema, ctx, json6, params, "Custom types cannot be represented in JSON Schema");
15185
+ customProcessor = (schema, ctx, json7, params) => {
15186
+ handleUnrepresentable(schema, ctx, json7, params, "Custom types cannot be represented in JSON Schema");
15186
15187
  };
15187
- transformProcessor = (schema, ctx, json6, params) => {
15188
- handleUnrepresentable(schema, ctx, json6, params, "Transforms cannot be represented in JSON Schema");
15188
+ transformProcessor = (schema, ctx, json7, params) => {
15189
+ handleUnrepresentable(schema, ctx, json7, params, "Transforms cannot be represented in JSON Schema");
15189
15190
  };
15190
15191
  arrayProcessor = (schema, ctx, _json, params) => {
15191
- const json6 = _json;
15192
+ const json7 = _json;
15192
15193
  const def = schema._zod.def;
15193
15194
  const { minimum, maximum } = aggregateChecks(schema);
15194
15195
  if (typeof minimum === "number")
15195
- json6.minItems = minimum;
15196
+ json7.minItems = minimum;
15196
15197
  if (typeof maximum === "number")
15197
- json6.maxItems = maximum;
15198
- json6.type = "array";
15199
- json6.items = processSchema(def.element, ctx, {
15198
+ json7.maxItems = maximum;
15199
+ json7.type = "array";
15200
+ json7.items = processSchema(def.element, ctx, {
15200
15201
  ...params,
15201
15202
  path: [...params.path, "items"]
15202
15203
  });
15203
15204
  };
15204
15205
  objectProcessor = (schema, ctx, _json, params) => {
15205
- const json6 = _json;
15206
+ const json7 = _json;
15206
15207
  const def = schema._zod.def;
15207
15208
  const shape = def.shape;
15208
15209
  const symbolKeys = Object.getOwnPropertySymbols(shape);
15209
- if (symbolKeys.length && handleUnrepresentable(schema, ctx, json6, params, "Symbol keys cannot be represented in JSON Schema")) {
15210
+ if (symbolKeys.length && handleUnrepresentable(schema, ctx, json7, params, "Symbol keys cannot be represented in JSON Schema")) {
15210
15211
  return;
15211
15212
  }
15212
- json6.type = "object";
15213
- json6.properties = {};
15213
+ json7.type = "object";
15214
+ json7.properties = {};
15214
15215
  for (const key in shape) {
15215
- assignProp(json6.properties, key, processSchema(shape[key], ctx, {
15216
+ assignProp(json7.properties, key, processSchema(shape[key], ctx, {
15216
15217
  ...params,
15217
15218
  path: [...params.path, "properties", key]
15218
15219
  }));
@@ -15225,21 +15226,21 @@ var init_json_schema_processors = __esm({
15225
15226
  }
15226
15227
  }
15227
15228
  if (requiredKeys.length > 0) {
15228
- json6.required = requiredKeys;
15229
+ json7.required = requiredKeys;
15229
15230
  }
15230
15231
  if (def.catchall?._zod.def.type === "never") {
15231
- json6.additionalProperties = false;
15232
+ json7.additionalProperties = false;
15232
15233
  } else if (!def.catchall) {
15233
15234
  if (ctx.io === "output")
15234
- json6.additionalProperties = false;
15235
+ json7.additionalProperties = false;
15235
15236
  } else if (def.catchall) {
15236
- json6.additionalProperties = processSchema(def.catchall, ctx, {
15237
+ json7.additionalProperties = processSchema(def.catchall, ctx, {
15237
15238
  ...params,
15238
15239
  path: [...params.path, "additionalProperties"]
15239
15240
  });
15240
15241
  }
15241
15242
  };
15242
- unionProcessor = (schema, ctx, json6, params) => {
15243
+ unionProcessor = (schema, ctx, json7, params) => {
15243
15244
  const def = schema._zod.def;
15244
15245
  const isExclusive = def.inclusive === false;
15245
15246
  const options = def.options.map((x, i) => processSchema(x, ctx, {
@@ -15247,12 +15248,12 @@ var init_json_schema_processors = __esm({
15247
15248
  path: [...params.path, isExclusive ? "oneOf" : "anyOf", i]
15248
15249
  }));
15249
15250
  if (isExclusive) {
15250
- json6.oneOf = options;
15251
+ json7.oneOf = options;
15251
15252
  } else {
15252
- json6.anyOf = options;
15253
+ json7.anyOf = options;
15253
15254
  }
15254
15255
  };
15255
- intersectionProcessor = (schema, ctx, json6, params) => {
15256
+ intersectionProcessor = (schema, ctx, json7, params) => {
15256
15257
  const def = schema._zod.def;
15257
15258
  const a = processSchema(def.left, ctx, {
15258
15259
  ...params,
@@ -15267,14 +15268,14 @@ var init_json_schema_processors = __esm({
15267
15268
  ...isSimpleIntersection(a) ? a.allOf : [a],
15268
15269
  ...isSimpleIntersection(b) ? b.allOf : [b]
15269
15270
  ];
15270
- json6.allOf = allOf;
15271
+ json7.allOf = allOf;
15271
15272
  ctx.intersections.push(allOf);
15272
15273
  };
15273
15274
  pendingRecords = /* @__PURE__ */ new WeakMap();
15274
15275
  recordProcessor = (schema, ctx, _json, params) => {
15275
- const json6 = _json;
15276
+ const json7 = _json;
15276
15277
  const def = schema._zod.def;
15277
- json6.type = "object";
15278
+ json7.type = "object";
15278
15279
  const keyType = def.keyType;
15279
15280
  const patterns = aggregateChecks(keyType).patterns;
15280
15281
  if (def.mode === "loose" && patterns && patterns.size > 0) {
@@ -15282,13 +15283,13 @@ var init_json_schema_processors = __esm({
15282
15283
  ...params,
15283
15284
  path: [...params.path, "patternProperties", "*"]
15284
15285
  });
15285
- json6.patternProperties = {};
15286
+ json7.patternProperties = {};
15286
15287
  for (const pattern of patterns) {
15287
- assignProp(json6.patternProperties, exactPattern(pattern).source, valueSchema);
15288
+ assignProp(json7.patternProperties, exactPattern(pattern).source, valueSchema);
15288
15289
  }
15289
15290
  } else {
15290
15291
  if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") {
15291
- json6.propertyNames = processSchema(def.keyType, ctx, {
15292
+ json7.propertyNames = processSchema(def.keyType, ctx, {
15292
15293
  ...params,
15293
15294
  path: [...params.path, "propertyNames"]
15294
15295
  });
@@ -15300,7 +15301,7 @@ var init_json_schema_processors = __esm({
15300
15301
  }
15301
15302
  pending.push(schema);
15302
15303
  }
15303
- json6.additionalProperties = processSchema(def.valueType, ctx, {
15304
+ json7.additionalProperties = processSchema(def.valueType, ctx, {
15304
15305
  ...params,
15305
15306
  path: [...params.path, "additionalProperties"]
15306
15307
  });
@@ -15310,19 +15311,19 @@ var init_json_schema_processors = __esm({
15310
15311
  if (keyValues && !def.partial && !omittableOnInput) {
15311
15312
  const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number");
15312
15313
  if (validKeyValues.length > 0) {
15313
- json6.required = validKeyValues.map(String);
15314
+ json7.required = validKeyValues.map(String);
15314
15315
  }
15315
15316
  }
15316
15317
  };
15317
- nullableProcessor = (schema, ctx, json6, params) => {
15318
+ nullableProcessor = (schema, ctx, json7, params) => {
15318
15319
  const def = schema._zod.def;
15319
15320
  const inner = processSchema(def.innerType, ctx, params);
15320
15321
  const seen = ctx.seen.get(schema);
15321
15322
  if (ctx.target === "openapi-3.0") {
15322
15323
  seen.ref = def.innerType;
15323
- json6.nullable = true;
15324
+ json7.nullable = true;
15324
15325
  } else {
15325
- json6.anyOf = [inner, { type: "null" }];
15326
+ json7.anyOf = [inner, { type: "null" }];
15326
15327
  }
15327
15328
  };
15328
15329
  nonoptionalProcessor = (schema, ctx, _json, params) => {
@@ -15332,27 +15333,27 @@ var init_json_schema_processors = __esm({
15332
15333
  seen.ref = def.innerType;
15333
15334
  };
15334
15335
  UNREPRESENTABLE_DEFAULT = Symbol();
15335
- defaultProcessor = (schema, ctx, json6, params) => {
15336
+ defaultProcessor = (schema, ctx, json7, params) => {
15336
15337
  const def = schema._zod.def;
15337
15338
  processSchema(def.innerType, ctx, params);
15338
15339
  const seen = ctx.seen.get(schema);
15339
15340
  seen.ref = def.innerType;
15340
- const value = serializeDefaultValue(def.defaultValue, schema, ctx, json6, params);
15341
+ const value = serializeDefaultValue(def.defaultValue, schema, ctx, json7, params);
15341
15342
  if (value !== UNREPRESENTABLE_DEFAULT)
15342
- json6.default = value;
15343
+ json7.default = value;
15343
15344
  };
15344
- prefaultProcessor = (schema, ctx, json6, params) => {
15345
+ prefaultProcessor = (schema, ctx, json7, params) => {
15345
15346
  const def = schema._zod.def;
15346
15347
  processSchema(def.innerType, ctx, params);
15347
15348
  const seen = ctx.seen.get(schema);
15348
15349
  seen.ref = def.innerType;
15349
15350
  if (ctx.io !== "input")
15350
15351
  return;
15351
- const value = serializeDefaultValue(def.defaultValue, schema, ctx, json6, params);
15352
+ const value = serializeDefaultValue(def.defaultValue, schema, ctx, json7, params);
15352
15353
  if (value !== UNREPRESENTABLE_DEFAULT)
15353
- json6._prefault = value;
15354
+ json7._prefault = value;
15354
15355
  };
15355
- catchProcessor = (schema, ctx, json6, params) => {
15356
+ catchProcessor = (schema, ctx, json7, params) => {
15356
15357
  const def = schema._zod.def;
15357
15358
  processSchema(def.innerType, ctx, params);
15358
15359
  const seen = ctx.seen.get(schema);
@@ -15361,10 +15362,10 @@ var init_json_schema_processors = __esm({
15361
15362
  try {
15362
15363
  catchValue = def.catchValue(void 0);
15363
15364
  } catch {
15364
- handleUnrepresentable(schema, ctx, json6, params, "Dynamic catch values are not supported in JSON Schema");
15365
+ handleUnrepresentable(schema, ctx, json7, params, "Dynamic catch values are not supported in JSON Schema");
15365
15366
  return;
15366
15367
  }
15367
- json6.default = catchValue;
15368
+ json7.default = catchValue;
15368
15369
  };
15369
15370
  pipeProcessor = (schema, ctx, _json, params) => {
15370
15371
  const def = schema._zod.def;
@@ -15374,12 +15375,12 @@ var init_json_schema_processors = __esm({
15374
15375
  const seen = ctx.seen.get(schema);
15375
15376
  seen.ref = innerType;
15376
15377
  };
15377
- readonlyProcessor = (schema, ctx, json6, params) => {
15378
+ readonlyProcessor = (schema, ctx, json7, params) => {
15378
15379
  const def = schema._zod.def;
15379
15380
  processSchema(def.innerType, ctx, params);
15380
15381
  const seen = ctx.seen.get(schema);
15381
15382
  seen.ref = def.innerType;
15382
- json6.readOnly = true;
15383
+ json7.readOnly = true;
15383
15384
  };
15384
15385
  optionalProcessor = (schema, ctx, _json, params) => {
15385
15386
  const def = schema._zod.def;
@@ -16003,7 +16004,7 @@ var init_schemas3 = __esm({
16003
16004
  (inst, def) => {
16004
16005
  $ZodString.init(inst, def);
16005
16006
  ZodType.init(inst, def);
16006
- inst._zod.processJSONSchema = (ctx, json6, params) => stringProcessor(inst, ctx, json6, params);
16007
+ inst._zod.processJSONSchema = (ctx, json7, params) => stringProcessor(inst, ctx, json7, params);
16007
16008
  },
16008
16009
  /* @__PURE__ */ util_exports.derived({
16009
16010
  format: (inst) => aggregateChecks(inst).format ?? null,
@@ -16241,7 +16242,7 @@ var init_schemas3 = __esm({
16241
16242
  (inst, def) => {
16242
16243
  $ZodNumber.init(inst, def);
16243
16244
  ZodType.init(inst, def);
16244
- inst._zod.processJSONSchema = (ctx, json6, params) => numberProcessor(inst, ctx, json6, params);
16245
+ inst._zod.processJSONSchema = (ctx, json7, params) => numberProcessor(inst, ctx, json7, params);
16245
16246
  inst.isFinite = true;
16246
16247
  },
16247
16248
  /* @__PURE__ */ util_exports.derived({
@@ -16313,14 +16314,14 @@ var init_schemas3 = __esm({
16313
16314
  ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => {
16314
16315
  $ZodBoolean.init(inst, def);
16315
16316
  ZodType.init(inst, def);
16316
- inst._zod.processJSONSchema = (ctx, json6, params) => booleanProcessor(inst, ctx, json6, params);
16317
+ inst._zod.processJSONSchema = (ctx, json7, params) => booleanProcessor(inst, ctx, json7, params);
16317
16318
  });
16318
16319
  ZodBigInt = /* @__PURE__ */ $constructor(
16319
16320
  "ZodBigInt",
16320
16321
  (inst, def) => {
16321
16322
  $ZodBigInt.init(inst, def);
16322
16323
  ZodType.init(inst, def);
16323
- inst._zod.processJSONSchema = (ctx, json6, params) => bigintProcessor(inst, ctx, json6, params);
16324
+ inst._zod.processJSONSchema = (ctx, json7, params) => bigintProcessor(inst, ctx, json7, params);
16324
16325
  },
16325
16326
  /* @__PURE__ */ util_exports.derived({
16326
16327
  minValue: (inst) => aggregateChecks(inst).minimum ?? null,
@@ -16365,29 +16366,29 @@ var init_schemas3 = __esm({
16365
16366
  ZodNull = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => {
16366
16367
  $ZodNull.init(inst, def);
16367
16368
  ZodType.init(inst, def);
16368
- inst._zod.processJSONSchema = (ctx, json6, params) => nullProcessor(inst, ctx, json6, params);
16369
+ inst._zod.processJSONSchema = (ctx, json7, params) => nullProcessor(inst, ctx, json7, params);
16369
16370
  });
16370
16371
  ZodAny = /* @__PURE__ */ $constructor("ZodAny", (inst, def) => {
16371
16372
  $ZodAny.init(inst, def);
16372
16373
  ZodType.init(inst, def);
16373
- inst._zod.processJSONSchema = (ctx, json6, params) => anyProcessor(inst, ctx, json6, params);
16374
+ inst._zod.processJSONSchema = (ctx, json7, params) => anyProcessor(inst, ctx, json7, params);
16374
16375
  });
16375
16376
  ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => {
16376
16377
  $ZodUnknown.init(inst, def);
16377
16378
  ZodType.init(inst, def);
16378
- inst._zod.processJSONSchema = (ctx, json6, params) => unknownProcessor(inst, ctx, json6, params);
16379
+ inst._zod.processJSONSchema = (ctx, json7, params) => unknownProcessor(inst, ctx, json7, params);
16379
16380
  });
16380
16381
  ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => {
16381
16382
  $ZodNever.init(inst, def);
16382
16383
  ZodType.init(inst, def);
16383
- inst._zod.processJSONSchema = (ctx, json6, params) => neverProcessor(inst, ctx, json6, params);
16384
+ inst._zod.processJSONSchema = (ctx, json7, params) => neverProcessor(inst, ctx, json7, params);
16384
16385
  });
16385
16386
  ZodDate = /* @__PURE__ */ $constructor(
16386
16387
  "ZodDate",
16387
16388
  (inst, def) => {
16388
16389
  $ZodDate.init(inst, def);
16389
16390
  ZodType.init(inst, def);
16390
- inst._zod.processJSONSchema = (ctx, json6, params) => dateProcessor(inst, ctx, json6, params);
16391
+ inst._zod.processJSONSchema = (ctx, json7, params) => dateProcessor(inst, ctx, json7, params);
16391
16392
  inst.min = (value, params) => inst.check(_gte(value, params));
16392
16393
  inst.max = (value, params) => inst.check(_lte(value, params));
16393
16394
  },
@@ -16406,7 +16407,7 @@ var init_schemas3 = __esm({
16406
16407
  _ensureDefaultMemoizer();
16407
16408
  $ZodArray.init(inst, def);
16408
16409
  ZodType.init(inst, def);
16409
- inst._zod.processJSONSchema = (ctx, json6, params) => arrayProcessor(inst, ctx, json6, params);
16410
+ inst._zod.processJSONSchema = (ctx, json7, params) => arrayProcessor(inst, ctx, json7, params);
16410
16411
  inst.element = def.element;
16411
16412
  }, {
16412
16413
  min(n, params) {
@@ -16429,7 +16430,7 @@ var init_schemas3 = __esm({
16429
16430
  _ensureDefaultMemoizer();
16430
16431
  $ZodObjectJIT.init(inst, def);
16431
16432
  ZodType.init(inst, def);
16432
- inst._zod.processJSONSchema = (ctx, json6, params) => objectProcessor(inst, ctx, json6, params);
16433
+ inst._zod.processJSONSchema = (ctx, json7, params) => objectProcessor(inst, ctx, json7, params);
16433
16434
  util_exports.installLazyProp(inst, "shape", (self) => self._zod.def.shape, false);
16434
16435
  }, {
16435
16436
  keyof() {
@@ -16478,7 +16479,7 @@ var init_schemas3 = __esm({
16478
16479
  ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => {
16479
16480
  $ZodUnion.init(inst, def);
16480
16481
  ZodType.init(inst, def);
16481
- inst._zod.processJSONSchema = (ctx, json6, params) => unionProcessor(inst, ctx, json6, params);
16482
+ inst._zod.processJSONSchema = (ctx, json7, params) => unionProcessor(inst, ctx, json7, params);
16482
16483
  inst.options = def.options;
16483
16484
  });
16484
16485
  ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => {
@@ -16488,20 +16489,20 @@ var init_schemas3 = __esm({
16488
16489
  ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => {
16489
16490
  $ZodIntersection.init(inst, def);
16490
16491
  ZodType.init(inst, def);
16491
- inst._zod.processJSONSchema = (ctx, json6, params) => intersectionProcessor(inst, ctx, json6, params);
16492
+ inst._zod.processJSONSchema = (ctx, json7, params) => intersectionProcessor(inst, ctx, json7, params);
16492
16493
  });
16493
16494
  ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => {
16494
16495
  _ensureDefaultMemoizer();
16495
16496
  $ZodRecord.init(inst, def);
16496
16497
  ZodType.init(inst, def);
16497
- inst._zod.processJSONSchema = (ctx, json6, params) => recordProcessor(inst, ctx, json6, params);
16498
+ inst._zod.processJSONSchema = (ctx, json7, params) => recordProcessor(inst, ctx, json7, params);
16498
16499
  inst.keyType = def.keyType;
16499
16500
  inst.valueType = def.valueType;
16500
16501
  });
16501
16502
  ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {
16502
16503
  $ZodEnum.init(inst, def);
16503
16504
  ZodType.init(inst, def);
16504
- inst._zod.processJSONSchema = (ctx, json6, params) => enumProcessor(inst, ctx, json6, params);
16505
+ inst._zod.processJSONSchema = (ctx, json7, params) => enumProcessor(inst, ctx, json7, params);
16505
16506
  inst.enum = def.entries;
16506
16507
  inst.options = [...inst._zod.values];
16507
16508
  const keys = new Set(Object.keys(def.entries));
@@ -16539,7 +16540,7 @@ var init_schemas3 = __esm({
16539
16540
  ZodLiteral = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => {
16540
16541
  $ZodLiteral.init(inst, def);
16541
16542
  ZodType.init(inst, def);
16542
- inst._zod.processJSONSchema = (ctx, json6, params) => literalProcessor(inst, ctx, json6, params);
16543
+ inst._zod.processJSONSchema = (ctx, json7, params) => literalProcessor(inst, ctx, json7, params);
16543
16544
  inst.values = new Set(def.values);
16544
16545
  Object.defineProperty(inst, "value", {
16545
16546
  get() {
@@ -16554,7 +16555,7 @@ var init_schemas3 = __esm({
16554
16555
  _ensureDefaultMemoizer();
16555
16556
  $ZodTransform.init(inst, def);
16556
16557
  ZodType.init(inst, def);
16557
- inst._zod.processJSONSchema = (ctx, json6, params) => transformProcessor(inst, ctx, json6, params);
16558
+ inst._zod.processJSONSchema = (ctx, json7, params) => transformProcessor(inst, ctx, json7, params);
16558
16559
  inst._zod.parse = (payload, _ctx) => {
16559
16560
  if (_ctx.direction === "backward") {
16560
16561
  throw new $ZodEncodeError(inst.constructor.name);
@@ -16587,51 +16588,51 @@ var init_schemas3 = __esm({
16587
16588
  ZodOptional = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => {
16588
16589
  $ZodOptional.init(inst, def);
16589
16590
  ZodType.init(inst, def);
16590
- inst._zod.processJSONSchema = (ctx, json6, params) => optionalProcessor(inst, ctx, json6, params);
16591
+ inst._zod.processJSONSchema = (ctx, json7, params) => optionalProcessor(inst, ctx, json7, params);
16591
16592
  inst.unwrap = () => inst._zod.def.innerType;
16592
16593
  });
16593
16594
  ZodExactOptional = /* @__PURE__ */ $constructor("ZodExactOptional", (inst, def) => {
16594
16595
  $ZodExactOptional.init(inst, def);
16595
16596
  ZodType.init(inst, def);
16596
- inst._zod.processJSONSchema = (ctx, json6, params) => optionalProcessor(inst, ctx, json6, params);
16597
+ inst._zod.processJSONSchema = (ctx, json7, params) => optionalProcessor(inst, ctx, json7, params);
16597
16598
  inst.unwrap = () => inst._zod.def.innerType;
16598
16599
  });
16599
16600
  ZodNullable = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => {
16600
16601
  $ZodNullable.init(inst, def);
16601
16602
  ZodType.init(inst, def);
16602
- inst._zod.processJSONSchema = (ctx, json6, params) => nullableProcessor(inst, ctx, json6, params);
16603
+ inst._zod.processJSONSchema = (ctx, json7, params) => nullableProcessor(inst, ctx, json7, params);
16603
16604
  inst.unwrap = () => inst._zod.def.innerType;
16604
16605
  });
16605
16606
  ZodDefault = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => {
16606
16607
  $ZodDefault.init(inst, def);
16607
16608
  ZodType.init(inst, def);
16608
- inst._zod.processJSONSchema = (ctx, json6, params) => defaultProcessor(inst, ctx, json6, params);
16609
+ inst._zod.processJSONSchema = (ctx, json7, params) => defaultProcessor(inst, ctx, json7, params);
16609
16610
  inst.unwrap = () => inst._zod.def.innerType;
16610
16611
  inst.removeDefault = inst.unwrap;
16611
16612
  });
16612
16613
  ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => {
16613
16614
  $ZodPrefault.init(inst, def);
16614
16615
  ZodType.init(inst, def);
16615
- inst._zod.processJSONSchema = (ctx, json6, params) => prefaultProcessor(inst, ctx, json6, params);
16616
+ inst._zod.processJSONSchema = (ctx, json7, params) => prefaultProcessor(inst, ctx, json7, params);
16616
16617
  inst.unwrap = () => inst._zod.def.innerType;
16617
16618
  });
16618
16619
  ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => {
16619
16620
  $ZodNonOptional.init(inst, def);
16620
16621
  ZodType.init(inst, def);
16621
- inst._zod.processJSONSchema = (ctx, json6, params) => nonoptionalProcessor(inst, ctx, json6, params);
16622
+ inst._zod.processJSONSchema = (ctx, json7, params) => nonoptionalProcessor(inst, ctx, json7, params);
16622
16623
  inst.unwrap = () => inst._zod.def.innerType;
16623
16624
  });
16624
16625
  ZodCatch = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => {
16625
16626
  $ZodCatch.init(inst, def);
16626
16627
  ZodType.init(inst, def);
16627
- inst._zod.processJSONSchema = (ctx, json6, params) => catchProcessor(inst, ctx, json6, params);
16628
+ inst._zod.processJSONSchema = (ctx, json7, params) => catchProcessor(inst, ctx, json7, params);
16628
16629
  inst.unwrap = () => inst._zod.def.innerType;
16629
16630
  inst.removeCatch = inst.unwrap;
16630
16631
  });
16631
16632
  ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => {
16632
16633
  $ZodPipe.init(inst, def);
16633
16634
  ZodType.init(inst, def);
16634
- inst._zod.processJSONSchema = (ctx, json6, params) => pipeProcessor(inst, ctx, json6, params);
16635
+ inst._zod.processJSONSchema = (ctx, json7, params) => pipeProcessor(inst, ctx, json7, params);
16635
16636
  inst.in = def.in;
16636
16637
  inst.out = def.out;
16637
16638
  });
@@ -16642,13 +16643,13 @@ var init_schemas3 = __esm({
16642
16643
  ZodReadonly = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => {
16643
16644
  $ZodReadonly.init(inst, def);
16644
16645
  ZodType.init(inst, def);
16645
- inst._zod.processJSONSchema = (ctx, json6, params) => readonlyProcessor(inst, ctx, json6, params);
16646
+ inst._zod.processJSONSchema = (ctx, json7, params) => readonlyProcessor(inst, ctx, json7, params);
16646
16647
  inst.unwrap = () => inst._zod.def.innerType;
16647
16648
  });
16648
16649
  ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => {
16649
16650
  $ZodCustom.init(inst, def);
16650
16651
  ZodType.init(inst, def);
16651
- inst._zod.processJSONSchema = (ctx, json6, params) => customProcessor(inst, ctx, json6, params);
16652
+ inst._zod.processJSONSchema = (ctx, json7, params) => customProcessor(inst, ctx, json7, params);
16652
16653
  });
16653
16654
  }
16654
16655
  });
@@ -23685,12 +23686,12 @@ var require_fast_uri = __commonJS({
23685
23686
  }
23686
23687
  function hasMalformedPercentEncoding(component) {
23687
23688
  if (component === void 0) return false;
23688
- let percent2 = component.indexOf("%");
23689
- while (percent2 !== -1) {
23690
- if (percent2 + 2 >= component.length || !/^[\da-f]{2}$/iu.test(component.slice(percent2 + 1, percent2 + 3))) {
23689
+ let percent3 = component.indexOf("%");
23690
+ while (percent3 !== -1) {
23691
+ if (percent3 + 2 >= component.length || !/^[\da-f]{2}$/iu.test(component.slice(percent3 + 1, percent3 + 3))) {
23691
23692
  return true;
23692
23693
  }
23693
- percent2 = component.indexOf("%", percent2 + 3);
23694
+ percent3 = component.indexOf("%", percent3 + 3);
23694
23695
  }
23695
23696
  return false;
23696
23697
  }
@@ -29209,13 +29210,13 @@ var init_streamableHttp = __esm({
29209
29210
  let receivedResponse = false;
29210
29211
  const processStream = async () => {
29211
29212
  try {
29212
- const reader = stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream({
29213
+ const reader2 = stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream({
29213
29214
  onRetry: (retryMs) => {
29214
29215
  this._serverRetryMs = retryMs;
29215
29216
  }
29216
29217
  })).getReader();
29217
29218
  while (true) {
29218
- const { value: event, done } = await reader.read();
29219
+ const { value: event, done } = await reader2.read();
29219
29220
  if (done) {
29220
29221
  break;
29221
29222
  }
@@ -30173,8 +30174,8 @@ var init_stdio2 = __esm({
30173
30174
  }
30174
30175
  send(message) {
30175
30176
  return new Promise((resolve10) => {
30176
- const json6 = serializeMessage(message);
30177
- if (this._stdout.write(json6)) {
30177
+ const json7 = serializeMessage(message);
30178
+ if (this._stdout.write(json7)) {
30178
30179
  resolve10();
30179
30180
  } else {
30180
30181
  this._stdout.once("drain", resolve10);
@@ -30210,7 +30211,7 @@ function createCodingMcpServer(options = {}) {
30210
30211
  throw new McpError(ErrorCode.InvalidRequest, signIn2);
30211
30212
  }
30212
30213
  };
30213
- const uuid16 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
30214
+ const uuid17 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
30214
30215
  const grantOf = (config2) => storedGrant(config2, endpoint2.href);
30215
30216
  async function renew() {
30216
30217
  try {
@@ -30226,7 +30227,7 @@ function createCodingMcpServer(options = {}) {
30226
30227
  const config2 = readConfig();
30227
30228
  const grant = grantOf(config2);
30228
30229
  const organizationIds = grant ? grant.organizationIds : config2.organizationId ? [config2.organizationId] : [];
30229
- if (!grant && (!config2.organizationId || !uuid16.test(config2.organizationId) || !config2.token || /[\r\n]/.test(config2.token) || /^bf(?:cli|agent|mcp)_/i.test(config2.token)))
30230
+ if (!grant && (!config2.organizationId || !uuid17.test(config2.organizationId) || !config2.token || /[\r\n]/.test(config2.token) || /^bf(?:cli|agent|mcp)_/i.test(config2.token)))
30230
30231
  throw new McpError(ErrorCode.InvalidRequest, signIn2);
30231
30232
  if (boundOrganizationId && !organizationIds.some((id) => id.toLowerCase() === boundOrganizationId.toLowerCase()))
30232
30233
  throw new McpError(ErrorCode.InvalidRequest, "Organization changed. Restart the Backify MCP connection to explicitly select the new organization.");
@@ -30466,7 +30467,7 @@ async function setLocations(call2, organizationId, values, options, context2) {
30466
30467
  if (workspaceId) {
30467
30468
  const workspace = current.workspace;
30468
30469
  const defaultRegion = defaultChoice === "inherit" ? null : defaultChoice ?? workspace.defaultRegion ?? null;
30469
- await call2(`/workspaces/${workspaceId}`, { method: "PATCH", headers: json3, body: JSON.stringify({
30470
+ await call2(`/workspaces/${workspaceId}`, { method: "PATCH", headers: json4, body: JSON.stringify({
30470
30471
  name: workspace.name,
30471
30472
  description: workspace.description ?? null,
30472
30473
  isDefault: workspace.isDefault,
@@ -30481,7 +30482,7 @@ async function setLocations(call2, organizationId, values, options, context2) {
30481
30482
  repositoryNamePostfix: workspace.repositoryNamePostfix ?? ""
30482
30483
  }) });
30483
30484
  } else {
30484
- await call2(`/organizations/${organizationId}`, { method: "PATCH", headers: json3, body: JSON.stringify({ name: current.organization.name, region: defaultChoice ?? current.organization.defaultRegion, allowedRegions }) });
30485
+ await call2(`/organizations/${organizationId}`, { method: "PATCH", headers: json4, body: JSON.stringify({ name: current.organization.name, region: defaultChoice ?? current.organization.defaultRegion, allowedRegions }) });
30485
30486
  }
30486
30487
  const { organization: _organization, workspace: _workspace, ...view } = await readLocations(call2, organizationId, workspaceId);
30487
30488
  return { value: view, text: "Locations saved.\n" + locationsText(view), exitCode: 0 };
@@ -30510,7 +30511,7 @@ async function setClouds(call2, organizationId, values, options, context2) {
30510
30511
  if (!context2.confirm) throw new OpsError(`Refusing to change hosting clouds without confirmation. Re-run with --yes to allow ${change}.`, "confirmation_required");
30511
30512
  if (!await context2.confirm(`Allow ${change} for new applications? Existing applications are not moved.`)) throw new OpsError("Not confirmed. Nothing was changed.", "not_confirmed");
30512
30513
  }
30513
- const saved = await call2(path, { method: "PUT", headers: json3, body: JSON.stringify({ allowedClouds: chosen ? [...new Set(chosen.map((cloud) => cloud.id))] : null }) });
30514
+ const saved = await call2(path, { method: "PUT", headers: json4, body: JSON.stringify({ allowedClouds: chosen ? [...new Set(chosen.map((cloud) => cloud.id))] : null }) });
30514
30515
  return { value: saved, text: "Hosting clouds saved.\n" + cloudsText(saved), exitCode: 0 };
30515
30516
  }
30516
30517
  function scopedGrants(entries, scopeType, flag) {
@@ -30577,7 +30578,7 @@ async function teamCommand(call2, organizationId, sub, target, values, options,
30577
30578
  if (!role) throw new Error("Pass --role <role>, e.g. --role Developer.");
30578
30579
  const scope = accessScope(organizationId, values);
30579
30580
  await confirm(`grant ${role} on ${scope.scopeType} ${scope.scopeId} to team ${team.name}`);
30580
- const assignment = await call2(`${root}/access/assignments`, { method: "POST", headers: json3, body: JSON.stringify({ subjectType: "team", subjectId: team.id, ...scope, role, expiresAt: null }) });
30581
+ const assignment = await call2(`${root}/access/assignments`, { method: "POST", headers: json4, body: JSON.stringify({ subjectType: "team", subjectId: team.id, ...scope, role, expiresAt: null }) });
30581
30582
  return { value: assignment, text: `${role} granted to ${team.name} on ${scope.scopeType} ${scope.scopeId} (assignment ${assignment.id}).`, exitCode: 0 };
30582
30583
  }
30583
30584
  if (sub === "revoke") {
@@ -30783,7 +30784,7 @@ async function runTaskCommand(command2, args2, context2) {
30783
30784
  throw new Error("Unknown command.\n\n" + taskHelp);
30784
30785
  }
30785
30786
  }
30786
- var taskHelp, purposes, upgradeEnded, upgradeInProgress, json3, workspaceOption, connection, usd, percent;
30787
+ var taskHelp, purposes, upgradeEnded, upgradeInProgress, json4, workspaceOption, connection, usd, percent;
30787
30788
  var init_tasks = __esm({
30788
30789
  "src/tasks.ts"() {
30789
30790
  "use strict";
@@ -30888,7 +30889,7 @@ var init_tasks = __esm({
30888
30889
  };
30889
30890
  upgradeEnded = (upgrade) => ["committed", "rolled-back", "failed"].includes(upgrade.phase);
30890
30891
  upgradeInProgress = (upgrade) => !!upgrade && !upgradeEnded(upgrade) && upgrade.state !== "awaiting-approval";
30891
- json3 = { "content-type": "application/json" };
30892
+ json4 = { "content-type": "application/json" };
30892
30893
  workspaceOption = (values) => {
30893
30894
  const id = values.workspace?.[0];
30894
30895
  if (id !== void 0 && !isUuid(id)) throw new Error("--workspace takes a workspace ID (UUID).");
@@ -30929,7 +30930,7 @@ async function runSsoCommand(args2, context2) {
30929
30930
  };
30930
30931
  const overview = async () => (await call2(base)).overview;
30931
30932
  const done = (result, text2) => ({ result: { value: result, text: text2 }, json: options.json });
30932
- const send2 = (path, method, body) => call2(base + path, { method, headers: json4, body: body === void 0 ? void 0 : JSON.stringify(body) });
30933
+ const send2 = (path, method, body) => call2(base + path, { method, headers: json5, body: body === void 0 ? void 0 : JSON.stringify(body) });
30933
30934
  const [area, action] = positional;
30934
30935
  switch (`${area ?? ""} ${["connections", "domains", "mappings", "scim"].includes(area ?? "") ? action ?? "" : ""}`.trim()) {
30935
30936
  case "": {
@@ -31131,7 +31132,7 @@ function connectionLine(connection2) {
31131
31132
  function domainLine(domain) {
31132
31133
  return `${domain.id} ${domain.domain} ${domain.ssoRequired ? "SSO required" : domain.verifiedAt ? "verified" : `waiting for DNS (TXT ${domain.record} = ${domain.value})`}`;
31133
31134
  }
31134
- var ssoHelp, json4;
31135
+ var ssoHelp, json5;
31135
31136
  var init_sso = __esm({
31136
31137
  "src/sso.ts"() {
31137
31138
  "use strict";
@@ -31163,7 +31164,7 @@ var init_sso = __esm({
31163
31164
  "Options: --organization <id> --json",
31164
31165
  "Client secrets and SCIM tokens are never printed except a new SCIM token, once. Pass secrets on standard input, never as arguments."
31165
31166
  ].join("\n");
31166
- json4 = { "content-type": "application/json" };
31167
+ json5 = { "content-type": "application/json" };
31167
31168
  }
31168
31169
  });
31169
31170
 
@@ -31311,12 +31312,12 @@ __export(auth_identity_exports, {
31311
31312
  function authIdentityArguments(args2) {
31312
31313
  if (args2.includes("--help") || args2.includes("-h")) return "help";
31313
31314
  const { flags, values, positional } = parse(args2, "auth identity", ["--json"], ["--app", "--environment", "--confirm"]);
31314
- const action = (positional[0] ?? "status").toLowerCase(), json6 = flags.has("--json");
31315
+ const action = (positional[0] ?? "status").toLowerCase(), json7 = flags.has("--json");
31315
31316
  if (!["status", "move", "move-back", "clear"].includes(action) || positional.length > 1) throw new Error("Unknown auth identity command: " + positional.join(" ") + "\n\n" + authIdentityHelp);
31316
31317
  if (action === "status" && (values["--environment"] !== void 0 || values["--confirm"] !== void 0)) throw new Error("--environment and --confirm apply to auth identity move.");
31317
31318
  if (action === "clear" && values["--confirm"] !== void 0) throw new Error("--confirm applies to auth identity move and move-back.");
31318
31319
  if (action !== "status" && values["--environment"] === void 0) throw new Error("Name the environment to " + (action === "clear" ? "clear" : "move") + " with --environment <name|id>.");
31319
- return { action, ...values["--environment"] !== void 0 ? { environment: values["--environment"] } : {}, ...values["--confirm"] !== void 0 ? { confirm: values["--confirm"] } : {}, json: json6 };
31320
+ return { action, ...values["--environment"] !== void 0 ? { environment: values["--environment"] } : {}, ...values["--confirm"] !== void 0 ? { confirm: values["--confirm"] } : {}, json: json7 };
31320
31321
  }
31321
31322
  function pad3(rows) {
31322
31323
  const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
@@ -32297,7 +32298,7 @@ function readBody(req, limit = 300 * 1024 * 1024) {
32297
32298
  req.on("error", reject);
32298
32299
  });
32299
32300
  }
32300
- function json5(res, status, body) {
32301
+ function json6(res, status, body) {
32301
32302
  res.writeHead(status, { "content-type": "application/json" });
32302
32303
  res.end(JSON.stringify(body));
32303
32304
  }
@@ -32387,21 +32388,21 @@ function startGateway(options) {
32387
32388
  if (url2.pathname.startsWith("/signed/")) return await signed(req, res, url2);
32388
32389
  if (url2.pathname.startsWith("/files/")) {
32389
32390
  const [, , bucket, ...rest] = url2.pathname.split("/");
32390
- if (!buckets.get(bucket)?.public) return json5(res, 404, { error: { code: "not_found", message: "Not found" } });
32391
+ if (!buckets.get(bucket)?.public) return json6(res, 404, { error: { code: "not_found", message: "Not found" } });
32391
32392
  return sendFile(res, objectPath(bucket, rest.map(decodeURIComponent).join("/")));
32392
32393
  }
32393
32394
  const apiPrefix = config2.kind === "api" ? "/" : "/api";
32394
32395
  if (config2.kind !== "web" || !options.frontendPort || url2.pathname === apiPrefix || url2.pathname.startsWith(apiPrefix === "/" ? "/" : apiPrefix + "/") || url2.pathname === (config2.server?.health ?? "/healthz")) {
32395
32396
  const port = options.webPort();
32396
- if (!port) return json5(res, 503, { error: { code: "starting", message: "The backend is starting or failed to start; see the terminal" } });
32397
+ if (!port) return json6(res, 503, { error: { code: "starting", message: "The backend is starting or failed to start; see the terminal" } });
32397
32398
  const user = sessionUser(req);
32398
32399
  if (user) req.headers["x-backify-user"] = options.identity.signUser(user);
32399
32400
  return proxy(req, res, port);
32400
32401
  }
32401
32402
  return proxy(req, res, options.frontendPort);
32402
32403
  } catch (error2) {
32403
- if (error2 instanceof InvalidKey) return json5(res, 400, { error: { code: "invalid_key", message: error2.message } });
32404
- if (!res.headersSent) json5(res, 500, { error: { code: "gateway_error", message: error2.message } });
32404
+ if (error2 instanceof InvalidKey) return json6(res, 400, { error: { code: "invalid_key", message: error2.message } });
32405
+ if (!res.headersSent) json6(res, 500, { error: { code: "gateway_error", message: error2.message } });
32405
32406
  }
32406
32407
  });
32407
32408
  server.on("upgrade", (req, socket, head) => {
@@ -32421,12 +32422,12 @@ function startGateway(options) {
32421
32422
  response.pipe(res);
32422
32423
  });
32423
32424
  upstream.on("error", () => {
32424
- if (!res.headersSent) json5(res, 502, { error: { code: "bad_gateway", message: `Nothing is listening on port ${port} yet` } });
32425
+ if (!res.headersSent) json6(res, 502, { error: { code: "bad_gateway", message: `Nothing is listening on port ${port} yet` } });
32425
32426
  });
32426
32427
  req.pipe(upstream);
32427
32428
  }
32428
32429
  function sendFile(res, path, contentType2) {
32429
- if (!existsSync16(path) || !statSync2(path).isFile()) return json5(res, 404, { error: { code: "not_found", message: "Not found" } });
32430
+ if (!existsSync16(path) || !statSync2(path).isFile()) return json6(res, 404, { error: { code: "not_found", message: "Not found" } });
32430
32431
  const meta2 = existsSync16(path + ".meta.json") ? JSON.parse(readFileSync22(path + ".meta.json", "utf8")) : {};
32431
32432
  res.writeHead(200, { "content-type": contentType2 ?? meta2.contentType ?? "application/octet-stream" });
32432
32433
  createReadStream(path).pipe(res);
@@ -32436,7 +32437,7 @@ function startGateway(options) {
32436
32437
  const returnTo = url2.searchParams.get("returnTo")?.startsWith("/") ? url2.searchParams.get("returnTo") : "/";
32437
32438
  if (action === "me") {
32438
32439
  const user = sessionUser(req);
32439
- return user ? json5(res, 200, { id: user.id, email: user.email, name: user.name, roles: user.roles, permissions: user.permissions }) : json5(res, 401, { error: { code: "unauthenticated", message: "Not signed in" } });
32440
+ return user ? json6(res, 200, { id: user.id, email: user.email, name: user.name, roles: user.roles, permissions: user.permissions }) : json6(res, 401, { error: { code: "unauthenticated", message: "Not signed in" } });
32440
32441
  }
32441
32442
  if (action === "signout") {
32442
32443
  res.writeHead(302, { location: "/", "set-cookie": `${SESSION}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0` });
@@ -32445,7 +32446,7 @@ function startGateway(options) {
32445
32446
  if (action === "login" && req.method === "POST") {
32446
32447
  const form = new URLSearchParams((await readBody(req, 64 * 1024)).toString());
32447
32448
  const email2 = (form.get("email") ?? "").trim().toLowerCase();
32448
- if (!/^[^@\s]+@[^@\s]+$/.test(email2)) return json5(res, 400, { error: { code: "invalid_email", message: "Enter an email address" } });
32449
+ if (!/^[^@\s]+@[^@\s]+$/.test(email2)) return json6(res, 400, { error: { code: "invalid_email", message: "Enter an email address" } });
32449
32450
  const list = (name2) => (form.get(name2) ?? "").split(",").map((s) => s.trim()).filter(Boolean);
32450
32451
  const user = { id: "dev-" + createHmac("sha256", "backify-dev").update(email2).digest("hex").slice(0, 16), email: email2, name: form.get("name") || void 0, roles: list("roles"), permissions: list("permissions") };
32451
32452
  res.writeHead(302, { location: form.get("returnTo")?.startsWith("/") ? form.get("returnTo") : "/", "set-cookie": `${SESSION}=${encodeURIComponent(sealed({ ...user, exp: Date.now() + 864e5 }))}; Path=/; HttpOnly; SameSite=Lax` });
@@ -32464,7 +32465,7 @@ function startGateway(options) {
32464
32465
  <p><label>Permissions (comma separated)<br><input name="permissions" style="width:100%"></label></p>
32465
32466
  <button>Sign in</button></form></body>`);
32466
32467
  }
32467
- return json5(res, 404, { error: { code: "not_found", message: "Unknown auth endpoint" } });
32468
+ return json6(res, 404, { error: { code: "not_found", message: "Unknown auth endpoint" } });
32468
32469
  }
32469
32470
  async function broker(req, res, url2) {
32470
32471
  if (req.headers.authorization !== "Bearer " + options.workloadToken) return brokerError(res, 401, "unauthorized", "Invalid workload token");
@@ -32474,7 +32475,7 @@ function startGateway(options) {
32474
32475
  if (!config2.protection?.dynamicRules) return brokerError(res, 403, "protection_scope_required", "Declare protection.dynamicRules in backify.config.ts.");
32475
32476
  const now = Date.now();
32476
32477
  for (const [key2, rule2] of dynamicRules) if (Date.parse(rule2.expiresAt) <= now) dynamicRules.delete(key2);
32477
- if (path.endsWith("/list")) return json5(res, 200, [...dynamicRules.values()]);
32478
+ if (path.endsWith("/list")) return json6(res, 200, [...dynamicRules.values()]);
32478
32479
  const ip = typeof body.ip === "string" ? body.ip : "";
32479
32480
  if (!parseCidr(ip)) return brokerError(res, 400, "invalid_ip", "Use an IPv4 or IPv6 IP or CIDR range.");
32480
32481
  if (path.endsWith("/remove")) {
@@ -32483,43 +32484,43 @@ function startGateway(options) {
32483
32484
  dynamicRules.delete(key2);
32484
32485
  removed++;
32485
32486
  }
32486
- return json5(res, 200, { removed });
32487
+ return json6(res, 200, { removed });
32487
32488
  }
32488
32489
  if (body.action !== "allow" && body.action !== "block" || typeof body.reason !== "string" || !body.reason.trim() || body.reason.length > 400 || body.ttl !== void 0 && (!Number.isInteger(body.ttl) || Number(body.ttl) < 1 || Number(body.ttl) > 2592e3)) return brokerError(res, 400, "invalid_rule", "Use allow/block, a short reason and TTL of 1 second to 30 days.");
32489
32490
  const key = body.action + "|" + ip;
32490
32491
  if (!dynamicRules.has(key) && dynamicRules.size >= 1e4) return brokerError(res, 409, "protection_rule_limit", "At most 10,000 active rules.");
32491
32492
  const rule = { id: dynamicRules.get(key)?.id ?? crypto.randomUUID(), cidr: ip, action: body.action, reason: body.reason, expiresAt: new Date(now + Number(body.ttl ?? 86400) * 1e3).toISOString() };
32492
32493
  dynamicRules.set(key, rule);
32493
- return json5(res, 200, rule);
32494
+ return json6(res, 200, rule);
32494
32495
  }
32495
- if (path === "/v1/token/renew") return json5(res, 200, { token: options.workloadToken, expiresAt: new Date(Date.now() + 864e5).toISOString() });
32496
+ if (path === "/v1/token/renew") return json6(res, 200, { token: options.workloadToken, expiresAt: new Date(Date.now() + 864e5).toISOString() });
32496
32497
  if (path === "/v1/storage/credentials" || path === "/v1/storage/sign") {
32497
32498
  const bucket = String(body.bucket);
32498
32499
  if (!buckets.has(bucket)) return brokerError(res, 403, "bucket_not_declared", `Bucket ${bucket} is not declared in backify.config.ts storage.buckets`);
32499
- if (path === "/v1/storage/credentials") return json5(res, 200, { provider: "local", endpoint: `http://127.0.0.1:${options.port}/storage`, container: "local", prefix: bucket + "/", credential: storageCredential, expiresAt: new Date(Date.now() + 36e5).toISOString() });
32500
+ if (path === "/v1/storage/credentials") return json6(res, 200, { provider: "local", endpoint: `http://127.0.0.1:${options.port}/storage`, container: "local", prefix: bucket + "/", credential: storageCredential, expiresAt: new Date(Date.now() + 36e5).toISOString() });
32500
32501
  const expires = Date.now() + Number(body.expiresInSeconds ?? 300) * 1e3;
32501
32502
  objectPath(bucket, String(body.key));
32502
32503
  const token2 = sealed({ kind: "signed", bucket, key: String(body.key), operation: body.operation, contentType: body.contentType, exp: expires });
32503
- return json5(res, 200, { url: `http://localhost:${options.port}/signed/${encodeURIComponent(token2)}`, method: body.operation === "upload" ? "PUT" : "GET", headers: body.contentType ? { "content-type": String(body.contentType) } : {}, expiresAt: new Date(expires).toISOString() });
32504
+ return json6(res, 200, { url: `http://localhost:${options.port}/signed/${encodeURIComponent(token2)}`, method: body.operation === "upload" ? "PUT" : "GET", headers: body.contentType ? { "content-type": String(body.contentType) } : {}, expiresAt: new Date(expires).toISOString() });
32504
32505
  }
32505
32506
  if (path === "/v1/mail/send") {
32506
32507
  const id = "mail_" + randomBytes4(6).toString("hex");
32507
32508
  writeFileSync13(join19(mailDir, id + ".json"), JSON.stringify(body, null, 2));
32508
32509
  options.log(`mail to ${JSON.stringify(body.to)}: "${String(body.subject)}" (saved in .backify/dev/mail/${id}.json)`);
32509
- return json5(res, 200, { id, status: "sent", from: "noreply@localhost" });
32510
+ return json6(res, 200, { id, status: "sent", from: "noreply@localhost" });
32510
32511
  }
32511
32512
  if (path === "/v1/http/fetch") {
32512
32513
  const target = new URL(String(body.url));
32513
32514
  if (target.protocol !== "https:") return brokerError(res, 403, "https_required", `Outbound HTTP to ${target.hostname} must use https`);
32514
32515
  const response = await fetch(target, { method: String(body.method ?? "GET"), headers: body.headers, body: body.body, signal: AbortSignal.timeout(Number(body.timeoutSeconds ?? 30) * 1e3) });
32515
- const bytes = Buffer.from(await response.arrayBuffer());
32516
- return json5(res, 200, { status: response.status, headers: Object.fromEntries(response.headers), body: bytes.toString("base64"), encoding: "base64" });
32516
+ const bytes2 = Buffer.from(await response.arrayBuffer());
32517
+ return json6(res, 200, { status: response.status, headers: Object.fromEntries(response.headers), body: bytes2.toString("base64"), encoding: "base64" });
32517
32518
  }
32518
32519
  if (path.startsWith("/v1/ai/") || path.startsWith("/v1/integrations/")) return brokerError(res, 501, "not_available_locally", `${path.split("/")[2]} is not available in local development yet; test it in a preview environment`);
32519
32520
  return brokerError(res, 404, "not_found", "Unknown broker endpoint " + path);
32520
32521
  }
32521
32522
  async function storage(req, res, url2) {
32522
- if (req.headers.authorization !== "Bearer " + storageCredential) return json5(res, 403, {});
32523
+ if (req.headers.authorization !== "Bearer " + storageCredential) return json6(res, 403, {});
32523
32524
  const rest = url2.pathname.slice("/storage/local".length);
32524
32525
  if (rest === "" || rest === "/") {
32525
32526
  const prefix = url2.searchParams.get("prefix") ?? "";
@@ -32532,7 +32533,7 @@ function startGateway(options) {
32532
32533
  }
32533
32534
  };
32534
32535
  walk2(storageDir);
32535
- return json5(res, 200, { keys: files.filter((f) => f.startsWith(prefix)).sort() });
32536
+ return json6(res, 200, { keys: files.filter((f) => f.startsWith(prefix)).sort() });
32536
32537
  }
32537
32538
  const [bucket, ...key] = rest.slice(1).split("/").map(decodeURIComponent);
32538
32539
  const path = objectPath(bucket, key.join("/"));
@@ -32553,7 +32554,7 @@ function startGateway(options) {
32553
32554
  }
32554
32555
  async function signed(req, res, url2) {
32555
32556
  const grant = unseal(decodeURIComponent(url2.pathname.slice("/signed/".length)));
32556
- if (!grant || grant.kind !== "signed") return json5(res, 403, { error: { code: "expired", message: "The signed URL is invalid or expired" } });
32557
+ if (!grant || grant.kind !== "signed") return json6(res, 403, { error: { code: "expired", message: "The signed URL is invalid or expired" } });
32557
32558
  const path = objectPath(grant.bucket, grant.key);
32558
32559
  if (grant.operation === "upload" && req.method === "PUT") {
32559
32560
  mkdirSync6(dirname7(path), { recursive: true });
@@ -32563,7 +32564,7 @@ function startGateway(options) {
32563
32564
  return res.end();
32564
32565
  }
32565
32566
  if (grant.operation === "download" && req.method === "GET") return sendFile(res, path);
32566
- return json5(res, 405, { error: { code: "method_not_allowed", message: "Wrong method for this signed URL" } });
32567
+ return json6(res, 405, { error: { code: "method_not_allowed", message: "Wrong method for this signed URL" } });
32567
32568
  }
32568
32569
  return new Promise((resolveServer, reject) => {
32569
32570
  server.once("error", reject);
@@ -32582,7 +32583,7 @@ var init_local_gateway = __esm({
32582
32583
  super("Invalid object key");
32583
32584
  }
32584
32585
  };
32585
- brokerError = (res, status, code, message) => json5(res, status, { error: { code, message, requestId: randomBytes4(6).toString("hex") } });
32586
+ brokerError = (res, status, code, message) => json6(res, status, { error: { code, message, requestId: randomBytes4(6).toString("hex") } });
32586
32587
  }
32587
32588
  });
32588
32589
 
@@ -32884,7 +32885,7 @@ function extractSettings(args2) {
32884
32885
  }
32885
32886
  return { rest, settings };
32886
32887
  }
32887
- function replacementsArguments(positional, flags, values, settings, json6, yes) {
32888
+ function replacementsArguments(positional, flags, values, settings, json7, yes) {
32888
32889
  const sub = (positional[1] ?? "list").toLowerCase();
32889
32890
  if (!["list", "add", "verify", "remove"].includes(sub)) throw new Error("Unknown replacements command: " + positional.slice(1).join(" ") + "\n\n" + handoffHelp);
32890
32891
  const takesId = sub === "verify" || sub === "remove";
@@ -32893,7 +32894,7 @@ function replacementsArguments(positional, flags, values, settings, json6, yes)
32893
32894
  if (values["--confirm"] !== void 0 || values["--out"] !== void 0) throw new Error("--confirm and --out do not apply to handoff replacements.");
32894
32895
  if (sub !== "add" && (addOnlyFlags.some((name2) => values[name2] !== void 0) || Object.keys(settings).length > 0 || flags.has("--consent"))) throw new Error(addOnlyMessage);
32895
32896
  if (yes && sub !== "remove") throw new Error("--yes applies to handoff replacements remove. Adding a replacement is consented with --consent.");
32896
- if (sub !== "add") return { action: "replacements", yes, json: json6, replacement: { action: sub, ...takesId ? { id: positional[2] } : {}, settings: {}, consent: false } };
32897
+ if (sub !== "add") return { action: "replacements", yes, json: json7, replacement: { action: sub, ...takesId ? { id: positional[2] } : {}, settings: {}, consent: false } };
32897
32898
  const kind2 = values["--kind"]?.toLowerCase(), secretName = values["--secret-name"];
32898
32899
  if (!values["--environment"]) throw new Error("Name the environment with --environment <name|id|kind>.");
32899
32900
  if (!kind2 || !replacementKinds.includes(kind2)) throw new Error("Choose what you are replacing with --kind " + replacementKinds.join(", ") + ".");
@@ -32901,22 +32902,22 @@ function replacementsArguments(positional, flags, values, settings, json6, yes)
32901
32902
  if (!validSecretName(secretName)) throw new Error("--secret-name is the name of a vault secret: letters, digits and hyphens, at most 127, and not starting with backify-rt-. It is not the secret's value.");
32902
32903
  const subject = values["--subject"] ?? (kind2 === "mail" || kind2 === "ai" ? kind2 : void 0);
32903
32904
  if (!subject) throw new Error("Name what the replacement is for with --subject: the connection ID for an integration, entra or google for a sign-in provider.");
32904
- return { action: "replacements", yes, json: json6, replacement: { action: "add", environment: values["--environment"], kind: kind2, subject, settings, secretName, consent: flags.has("--consent") } };
32905
+ return { action: "replacements", yes, json: json7, replacement: { action: "add", environment: values["--environment"], kind: kind2, subject, settings, secretName, consent: flags.has("--consent") } };
32905
32906
  }
32906
32907
  function handoffArguments(args2) {
32907
32908
  if (args2.includes("--help") || args2.includes("-h")) return "help";
32908
32909
  const { rest, settings } = extractSettings(args2);
32909
32910
  const { flags, values, positional } = parse(rest, "handoff", ["--json", "--yes", "--consent"], ["--app", "--confirm", "--out", "--azure-session", ...addOnlyFlags]);
32910
- const action = (positional[0] ?? "status").toLowerCase(), json6 = flags.has("--json"), yes = flags.has("--yes");
32911
+ const action = (positional[0] ?? "status").toLowerCase(), json7 = flags.has("--json"), yes = flags.has("--yes");
32911
32912
  const azureSessionId = values["--azure-session"];
32912
32913
  if (azureSessionId !== void 0 && (action !== "start" || !uuid12.test(azureSessionId))) throw new Error("--azure-session requires a valid Azure session ID and applies to handoff start.");
32913
- if (action === "replacements") return replacementsArguments(positional, flags, values, settings, json6, yes);
32914
+ if (action === "replacements") return replacementsArguments(positional, flags, values, settings, json7, yes);
32914
32915
  if (Object.keys(settings).length || flags.has("--consent") || addOnlyFlags.some((name2) => values[name2] !== void 0)) throw new Error(addOnlyMessage);
32915
32916
  if (!["status", "check", "request", "start", "abort", "foundation", "package"].includes(action) || positional.length > 1) throw new Error("Unknown handoff command: " + positional.join(" ") + "\n\n" + handoffHelp);
32916
32917
  if (values["--confirm"] !== void 0 && action !== "request") throw new Error("--confirm applies to handoff request.");
32917
32918
  if (values["--out"] !== void 0 && action !== "package" && action !== "foundation") throw new Error("--out applies to handoff foundation and handoff package.");
32918
32919
  if (yes && action !== "start" && action !== "abort") throw new Error(action === "request" ? "Requesting a handoff is confirmed with --confirm <application-slug>, not --yes." : "--yes applies to handoff start and abort.");
32919
- return { action, ...values["--confirm"] !== void 0 ? { confirm: values["--confirm"] } : {}, ...values["--out"] !== void 0 ? { out: values["--out"] } : {}, ...azureSessionId !== void 0 ? { azureSessionId } : {}, yes, json: json6 };
32920
+ return { action, ...values["--confirm"] !== void 0 ? { confirm: values["--confirm"] } : {}, ...values["--out"] !== void 0 ? { out: values["--out"] } : {}, ...azureSessionId !== void 0 ? { azureSessionId } : {}, yes, json: json7 };
32920
32921
  }
32921
32922
  function pad4(rows) {
32922
32923
  const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
@@ -33148,7 +33149,7 @@ var init_handoff = __esm({
33148
33149
  uuid12 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
33149
33150
  checkRows = (checks) => pad4([["CHECK", "RESULT", "DETAIL"], ...checks.map((check) => [check.name, check.state, check.detail ?? ""])]);
33150
33151
  failedIds = (checks) => checks.filter((check) => check.state === "failed").map((check) => check.id);
33151
- sizeText = (bytes) => bytes === void 0 ? "" : bytes < 1024 ? bytes + " B" : bytes < 1024 * 1024 ? (bytes / 1024).toFixed(1) + " KB" : (bytes / 1024 / 1024).toFixed(1) + " MB";
33152
+ sizeText = (bytes2) => bytes2 === void 0 ? "" : bytes2 < 1024 ? bytes2 + " B" : bytes2 < 1024 * 1024 ? (bytes2 / 1024).toFixed(1) + " KB" : (bytes2 / 1024 / 1024).toFixed(1) + " MB";
33152
33153
  manifestFiles = (manifest) => Array.isArray(manifest.files) ? manifest.files.map((file) => ({ ...file, path: file.name ?? file.path ?? "" })) : [];
33153
33154
  sha2562 = (text2) => createHash5("sha256").update(text2, "utf8").digest("hex");
33154
33155
  normalizedHash = (value) => value.trim().toLowerCase().replace(/^sha256[:-]/, "");
@@ -33289,6 +33290,207 @@ var init_logs_history = __esm({
33289
33290
  }
33290
33291
  });
33291
33292
 
33293
+ // src/monitoring-dashboards.ts
33294
+ var monitoring_dashboards_exports = {};
33295
+ __export(monitoring_dashboards_exports, {
33296
+ INSIGHT_RANGES: () => INSIGHT_RANGES,
33297
+ monitoringDashboardArguments: () => monitoringDashboardArguments,
33298
+ monitoringDashboardsHelp: () => monitoringDashboardsHelp,
33299
+ runMonitoringDashboards: () => runMonitoringDashboards,
33300
+ widgetList: () => widgetList
33301
+ });
33302
+ function widgetList(value) {
33303
+ return value.split(",").map((item) => item.trim()).filter(Boolean).map((item) => {
33304
+ const [type, size, ...rest] = item.split(":");
33305
+ if (!/^[a-z]+\.[a-z-]+$/.test(type ?? "") || rest.length) throw new Error(`Use widget types such as database.size or ai.models:large (got "${item}"). List them with: backify monitoring widgets`);
33306
+ if (size !== void 0 && !SIZES.includes(size)) throw new Error("Widget sizes are small, medium or large.");
33307
+ return size ? { type, size } : { type };
33308
+ });
33309
+ }
33310
+ function monitoringDashboardArguments(args2) {
33311
+ const first = args2.find((arg) => !arg.startsWith("-") && args2[args2.indexOf(arg) - 1] !== "--app");
33312
+ if (!first || !["widgets", "capabilities", "dashboards"].includes(first)) return null;
33313
+ if (args2.includes("--help") || args2.includes("-h")) return "help";
33314
+ const { flags, values, positional } = parse(args2, "monitoring " + first, ["--json", "--organization"], ["--app", "--range", "--environment", "--name", "--widgets", "--add", "--remove", "--workspace"]);
33315
+ const json7 = flags.has("--json");
33316
+ const organization = flags.has("--organization"), workspace = values["--workspace"];
33317
+ if ((organization || workspace) && first !== "dashboards") throw new Error("--organization and --workspace apply to monitoring dashboards only.");
33318
+ if ([organization, Boolean(workspace), Boolean(values["--app"])].filter(Boolean).length > 1) throw new Error("Choose one of --app, --workspace or --organization.");
33319
+ if (workspace && !uuid14.test(workspace)) throw new Error("--workspace takes a workspace ID. List workspaces with: backify workspaces");
33320
+ const scoped = organization ? { scope: { kind: "organization" } } : workspace ? { scope: { kind: "workspace", id: workspace.toLowerCase() } } : {};
33321
+ const [, action = "list", target, ...extra] = positional;
33322
+ const only = (allowed) => {
33323
+ const unexpected = Object.keys(values).filter((key) => key !== "--app" && key !== "--workspace" && !allowed.includes(key));
33324
+ if (unexpected.length) throw new Error(`${unexpected.join(", ")} does not apply here.
33325
+
33326
+ ${monitoringDashboardsHelp}`);
33327
+ };
33328
+ if (first === "widgets") {
33329
+ if (positional.length > 1) throw new Error(monitoringDashboardsHelp);
33330
+ only([]);
33331
+ return { action: "widgets", json: json7 };
33332
+ }
33333
+ if (first === "capabilities") {
33334
+ if (positional.length > 1) throw new Error(monitoringDashboardsHelp);
33335
+ only(["--range", "--environment"]);
33336
+ const range = values["--range"]?.toLowerCase() ?? "7d";
33337
+ if (!INSIGHT_RANGES.includes(range)) throw new Error("--range takes 24h, 7d or 30d.");
33338
+ const environment = values["--environment"]?.toLowerCase();
33339
+ if (environment && !(uuid14.test(environment) || ENVIRONMENT_FLOW.includes(environment))) throw new Error("--environment takes prototype, preview, production or an environment UUID.");
33340
+ return { action: "capabilities", range, ...environment ? { environment } : {}, json: json7 };
33341
+ }
33342
+ if (extra.length) throw new Error("Unexpected arguments: " + extra.join(" ") + "\n\n" + monitoringDashboardsHelp);
33343
+ switch (action) {
33344
+ case "list":
33345
+ if (target) throw new Error(monitoringDashboardsHelp);
33346
+ only([]);
33347
+ return { action: "list", ...scoped, json: json7 };
33348
+ case "create": {
33349
+ only(["--name", "--widgets"]);
33350
+ const name2 = values["--name"]?.trim();
33351
+ if (!name2 || target) throw new Error("Usage: backify monitoring dashboards create --name <name> [--widgets <type[:size],...>]");
33352
+ return { action: "create", ...scoped, name: name2, widgets: values["--widgets"] ? widgetList(values["--widgets"]) : [], json: json7 };
33353
+ }
33354
+ case "update": {
33355
+ only(["--name", "--widgets", "--add", "--remove"]);
33356
+ if (values["--widgets"] && (values["--add"] || values["--remove"])) throw new Error("Use --widgets to replace every widget, or --add and --remove to change some.");
33357
+ if (!values["--name"] && !values["--widgets"] && !values["--add"] && !values["--remove"]) throw new Error("Give --name, --widgets, --add or --remove.");
33358
+ return {
33359
+ action: "update",
33360
+ ...scoped,
33361
+ dashboard: dashboardRef(target),
33362
+ ...values["--name"] ? { name: values["--name"].trim() } : {},
33363
+ ...values["--widgets"] ? { widgets: widgetList(values["--widgets"]) } : {},
33364
+ add: values["--add"] ? widgetList(values["--add"]) : [],
33365
+ remove: values["--remove"] ? values["--remove"].split(",").map((item) => item.trim()).filter(Boolean) : [],
33366
+ json: json7
33367
+ };
33368
+ }
33369
+ case "delete":
33370
+ only([]);
33371
+ if (target === "overview") throw new Error("Reset the overview with: backify monitoring dashboards reset");
33372
+ return { action: "delete", ...scoped, dashboard: dashboardRef(target), json: json7 };
33373
+ case "reset":
33374
+ only([]);
33375
+ if (target) throw new Error(monitoringDashboardsHelp);
33376
+ return { action: "delete", ...scoped, dashboard: "overview", json: json7 };
33377
+ }
33378
+ throw new Error("Unknown monitoring dashboards command: " + action + "\n\n" + monitoringDashboardsHelp);
33379
+ }
33380
+ function capacityLines(name2, capacity, limitLabel, connections) {
33381
+ const forecast = capacity.forecast;
33382
+ return [
33383
+ `${name2}${capacity.environmentName ? " (" + capacity.environmentName + ")" : ""}: ${bytes(capacity.usedBytes)}${capacity.limitBytes ? ` of ${bytes(capacity.limitBytes)} ${limitLabel} (${percent2(capacity.usedRatio)})` : ""}. Level: ${capacity.level}.`,
33384
+ ...connections && capacity.connectionLimit ? [` Connections: ${number4(capacity.itemCount)} of ${capacity.connectionLimit} (${percent2(capacity.connectionRatio)}).`] : !connections && capacity.itemCount != null ? [` Files: ${capacity.itemCount}.`] : [],
33385
+ forecast ? ` Forecast: ${bytes(forecast.projectedIn30Days)} in 30 days, ${bytes(forecast.projectedIn90Days)} in 90 days${forecast.limitReachedAt ? `; reaches the limit around ${forecast.limitReachedAt.slice(0, 10)}` : ""}.` : " Forecast: needs at least two readings (taken every 6 hours).",
33386
+ ` Measured: ${capacity.measuredAt ?? "not yet"}.`
33387
+ ];
33388
+ }
33389
+ function dashboardLines(items) {
33390
+ return items.flatMap((item) => [
33391
+ `${item.kind === "overview" ? "overview" : item.id} ${item.name}${item.kind === "overview" ? item.customized ? " (customized)" : " (automatic)" : ""}`,
33392
+ ...item.widgets.length ? pad([[" WIDGET", "TYPE", "SIZE"], ...item.widgets.map((widget) => [" " + widget.id, widget.type, widget.size])]) : [" No widgets."]
33393
+ ]);
33394
+ }
33395
+ async function runMonitoringDashboards(call2, applicationId, options) {
33396
+ if (options.action === "widgets") {
33397
+ const catalog = await call2("/monitoring/widgets");
33398
+ const names = new Map([["applications", "Applications"], ...catalog.capabilities.map((item) => [item.key, item.title])]);
33399
+ return { value: catalog, text: pad([["TYPE", "CAPABILITY", "SIZE", "DASHBOARDS", "TITLE"], ...catalog.widgets.map((widget) => [widget.type, names.get(widget.capability) ?? widget.capability, widget.defaultSize, (widget.scopes ?? ["application"]).join(","), widget.title + (widget.requiresBilling ? " (billing access)" : "")])]).join("\n") };
33400
+ }
33401
+ const scope = "scope" in options ? options.scope : void 0;
33402
+ if (!scope && !uuid14.test(applicationId)) throw new Error("Use a valid application ID.");
33403
+ const base = scope?.kind === "organization" ? "/monitoring/organization" : scope?.kind === "workspace" ? "/monitoring/workspaces/" + scope.id : "/monitoring/applications/" + applicationId;
33404
+ switch (options.action) {
33405
+ case "capabilities": {
33406
+ const query = new URLSearchParams({ range: options.range });
33407
+ if (options.environment) query.set("environmentId", await resolveEnvironment2(call2, "/apps/" + applicationId, options.environment));
33408
+ const data = await call2(base + "/capabilities?" + query.toString());
33409
+ const ai = data.ai;
33410
+ const lines = [
33411
+ `Capabilities with monitoring pages: ${data.monitored.join(", ") || "none"}. Range ${data.range}, generated ${data.generatedAt}.`,
33412
+ ...data.database ? ["", ...capacityLines("Database", data.database, "recommended for the scale", true)] : [],
33413
+ ...data.storage ? ["", ...capacityLines("Storage", data.storage, "included", false)] : [],
33414
+ ...ai ? [
33415
+ "",
33416
+ `AI: ${number4(ai.usage.totals.calls)} calls, average prompt ${number4(ai.usage.totals.averageInputTokens)} tokens, average response ${number4(ai.usage.totals.averageOutputTokens)} tokens, estimated cost $${(ai.usage.totals.costUsd ?? 0).toFixed(4)}.`,
33417
+ ...ai.models.length ? pad([[" MODEL", "PROVIDER MODEL", "CALLS", "AVG IN", "AVG OUT", "COST USD"], ...ai.models.map((model) => [" " + model.model, model.providerModel, String(model.calls), number4(model.averageInputTokens), number4(model.averageOutputTokens), model.costUsd == null ? "-" : model.costUsd.toFixed(4)])]) : []
33418
+ ] : []
33419
+ ];
33420
+ return { value: data, text: lines.join("\n") };
33421
+ }
33422
+ case "list": {
33423
+ const items = await call2(base + "/dashboards");
33424
+ return { value: items, text: dashboardLines(items).join("\n") };
33425
+ }
33426
+ case "create": {
33427
+ const created = await call2(base + "/dashboards", { method: "POST", body: JSON.stringify({ name: options.name, widgets: options.widgets }) });
33428
+ return { value: created, text: `Created monitoring page ${created.id}.
33429
+ ` + dashboardLines([created]).join("\n") };
33430
+ }
33431
+ case "update": {
33432
+ let widgets = options.widgets;
33433
+ if (!widgets && (options.add.length || options.remove.length)) {
33434
+ const current = (await call2(base + "/dashboards")).find((item) => options.dashboard === "overview" ? item.kind === "overview" : item.id?.toLowerCase() === options.dashboard);
33435
+ if (!current) throw new Error("The monitoring page was not found.");
33436
+ const missing = options.remove.filter((id) => !current.widgets.some((widget) => widget.id === id));
33437
+ if (missing.length) throw new Error("No widget with id " + missing.join(", ") + " on this page.");
33438
+ widgets = [...current.widgets.filter((widget) => !options.remove.includes(widget.id)).map((widget) => ({ id: widget.id, type: widget.type, size: widget.size })), ...options.add];
33439
+ }
33440
+ const updated = await call2(base + "/dashboards/" + encodeURIComponent(options.dashboard), { method: "PUT", body: JSON.stringify({ ...options.name ? { name: options.name } : {}, ...widgets ? { widgets } : {} }) });
33441
+ return { value: updated, text: "Updated.\n" + dashboardLines([updated]).join("\n") };
33442
+ }
33443
+ case "delete": {
33444
+ await call2(base + "/dashboards/" + encodeURIComponent(options.dashboard), { method: "DELETE" });
33445
+ return { value: { deleted: options.dashboard }, text: options.dashboard === "overview" ? "The overview shows the automatic widgets again." : "Deleted monitoring page " + options.dashboard + "." };
33446
+ }
33447
+ }
33448
+ }
33449
+ var uuid14, INSIGHT_RANGES, SIZES, monitoringDashboardsHelp, dashboardRef, bytes, percent2, number4;
33450
+ var init_monitoring_dashboards = __esm({
33451
+ "src/monitoring-dashboards.ts"() {
33452
+ "use strict";
33453
+ init_logs_history();
33454
+ init_release_flow();
33455
+ uuid14 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
33456
+ INSIGHT_RANGES = ["24h", "7d", "30d"];
33457
+ SIZES = ["small", "medium", "large"];
33458
+ monitoringDashboardsHelp = [
33459
+ "Usage:",
33460
+ " backify monitoring widgets [--json]",
33461
+ " The widget catalog: every widget type, its capability, default size and the dashboards that can hold it.",
33462
+ " backify monitoring capabilities [--range 24h|7d|30d] [--environment <prototype|preview|production|UUID>] [--json]",
33463
+ " Database size and connections against the limits of the environment's scale, storage against the included",
33464
+ " allowance, both with a growth forecast, and AI usage per model (calls, average prompt and response size, cost).",
33465
+ " backify monitoring dashboards [--json]",
33466
+ " The monitoring pages: the overview and custom pages, with their widgets. Add --organization or",
33467
+ " --workspace <workspace-id> to any dashboards command for the organization's or a workspace's pages.",
33468
+ " backify monitoring dashboards create --name <name> [--widgets <type[:size],...>] [--json]",
33469
+ " backify monitoring dashboards update <page-id|overview> [--name <name>] [--widgets <type[:size],...>]",
33470
+ " [--add <type[:size],...>] [--remove <widget-id,...>] [--json]",
33471
+ " --widgets replaces every widget; --add appends and --remove takes widgets away. Sizes: small, medium, large.",
33472
+ " backify monitoring dashboards delete <page-id> [--json]",
33473
+ " backify monitoring dashboards reset [--json]",
33474
+ " Puts the overview back to the automatic widgets (for an application, those of the capabilities it uses).",
33475
+ " --app <application> Default: the application in this folder",
33476
+ " --organization The organization's monitoring pages; changes need organization management",
33477
+ " --workspace <id> A workspace's monitoring pages; changes need workspace management"
33478
+ ].join("\n");
33479
+ dashboardRef = (value) => {
33480
+ if (!value || !(value === "overview" || uuid14.test(value))) throw new Error("Name the page by its id, or overview. List pages with: backify monitoring dashboards");
33481
+ return value.toLowerCase();
33482
+ };
33483
+ bytes = (value) => {
33484
+ if (value == null) return "-";
33485
+ const units = ["B", "KB", "MB", "GB", "TB"];
33486
+ const exponent = value > 0 ? Math.min(units.length - 1, Math.floor(Math.log(value) / Math.log(1e3))) : 0;
33487
+ return (value / 1e3 ** exponent).toFixed(exponent ? 1 : 0) + " " + units[exponent];
33488
+ };
33489
+ percent2 = (value) => value == null ? "-" : Math.round(value * 100) + "%";
33490
+ number4 = (value) => value == null ? "-" : Number.isInteger(value) ? String(value) : value.toFixed(1);
33491
+ }
33492
+ });
33493
+
33292
33494
  // src/monitoring.ts
33293
33495
  var monitoring_exports = {};
33294
33496
  __export(monitoring_exports, {
@@ -33302,13 +33504,13 @@ function monitoringArguments(args2) {
33302
33504
  const { flags, values, positional } = parse(args2, "monitoring", ["--json"], ["--app", "--environment", "--range"]);
33303
33505
  if (positional.length) throw new Error("Unknown monitoring command: " + positional.join(" ") + "\n\n" + monitoringHelp);
33304
33506
  const environment = values["--environment"]?.toLowerCase();
33305
- if (environment && !(uuid14.test(environment) || ENVIRONMENT_FLOW.includes(environment))) throw new Error("--environment takes prototype, preview, production or an environment UUID.");
33507
+ if (environment && !(uuid15.test(environment) || ENVIRONMENT_FLOW.includes(environment))) throw new Error("--environment takes prototype, preview, production or an environment UUID.");
33306
33508
  const range = values["--range"]?.toLowerCase() ?? "24h";
33307
33509
  if (!MONITORING_RANGES.includes(range)) throw new Error("--range takes 1h, 6h, 24h or 7d.");
33308
33510
  return { ...environment ? { environment } : {}, range, json: flags.has("--json") };
33309
33511
  }
33310
33512
  async function runMonitoring(call2, applicationId, options) {
33311
- if (!uuid14.test(applicationId)) throw new Error("Use a valid application ID.");
33513
+ if (!uuid15.test(applicationId)) throw new Error("Use a valid application ID.");
33312
33514
  const prefix = "/apps/" + applicationId;
33313
33515
  const environmentId = options.environment ? await resolveEnvironment2(call2, prefix, options.environment) : void 0;
33314
33516
  const query = new URLSearchParams({ range: options.range });
@@ -33323,14 +33525,14 @@ async function runMonitoring(call2, applicationId, options) {
33323
33525
  ].join("\n");
33324
33526
  return { value: { ...environmentId ? { environmentId } : {}, range: options.range, ...snapshot }, text: text2 };
33325
33527
  }
33326
- var MONITORING_RANGES, uuid14, monitoringHelp, reading;
33528
+ var MONITORING_RANGES, uuid15, monitoringHelp, reading;
33327
33529
  var init_monitoring = __esm({
33328
33530
  "src/monitoring.ts"() {
33329
33531
  "use strict";
33330
33532
  init_logs_history();
33331
33533
  init_release_flow();
33332
33534
  MONITORING_RANGES = ["1h", "6h", "24h", "7d"];
33333
- uuid14 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
33535
+ uuid15 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
33334
33536
  monitoringHelp = [
33335
33537
  "Usage: backify monitoring [--environment <prototype|preview|production|UUID>] [--range 1h|6h|24h|7d] [--json]",
33336
33538
  "",
@@ -33353,7 +33555,7 @@ __export(operation_progress_exports, {
33353
33555
  function operationArguments(args2) {
33354
33556
  if (args2.includes("--help") || args2.includes("-h")) return "help";
33355
33557
  const { flags, positional } = parse(args2, "operation", ["--wait", "--json"], ["--app"]);
33356
- if (positional.length !== 1 || !uuid15.test(positional[0])) throw new Error("Use backify operation <operation-id> [--wait] [--json].");
33558
+ if (positional.length !== 1 || !uuid16.test(positional[0])) throw new Error("Use backify operation <operation-id> [--wait] [--json].");
33357
33559
  return { operationId: positional[0].toLowerCase(), wait: flags.has("--wait"), json: flags.has("--json") };
33358
33560
  }
33359
33561
  async function runOperation(call2, options, context2 = {}) {
@@ -33375,12 +33577,12 @@ async function runOperation(call2, options, context2 = {}) {
33375
33577
  ].join("\n");
33376
33578
  return { value: { operation, logs }, text: text2, ...operation.status === "failed" ? { exitCode: 1 } : options.wait && !finished.has(operation.status) ? { exitCode: 2 } : {} };
33377
33579
  }
33378
- var uuid15, finished, operationHelp, line;
33580
+ var uuid16, finished, operationHelp, line;
33379
33581
  var init_operation_progress = __esm({
33380
33582
  "src/operation-progress.ts"() {
33381
33583
  "use strict";
33382
33584
  init_release_flow();
33383
- uuid15 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
33585
+ uuid16 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
33384
33586
  finished = /* @__PURE__ */ new Set(["succeeded", "failed", "cancelled"]);
33385
33587
  operationHelp = [
33386
33588
  "Usage: backify operation <operation-id> [--wait] [--json]",
@@ -33620,22 +33822,22 @@ async function diagnoseEnvironment(root = process.cwd(), options = {}, probes =
33620
33822
 
33621
33823
  // src/integrations.ts
33622
33824
  function integrationDiscoveryPath(command2, options) {
33623
- const uuid16 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
33624
- if (!uuid16.test(options.applicationId)) throw new Error("An application UUID is required");
33825
+ const uuid17 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
33826
+ if (!uuid17.test(options.applicationId)) throw new Error("An application UUID is required");
33625
33827
  const base = "/apps/" + options.applicationId + "/integrations/connectors";
33626
33828
  if (command2 === "list") return base;
33627
33829
  if (command2 === "catalog") return "/apps/" + options.applicationId + "/integrations/catalog";
33628
33830
  if (command2 === "discover") return "/apps/" + options.applicationId + "/integrations/discover?" + new URLSearchParams({ query: options.query ?? "" });
33629
33831
  if (command2 === "prepare") return "/apps/" + options.applicationId + "/integrations/prepare";
33630
33832
  if (command2 === "contract" && options.revisionId) {
33631
- if (!uuid16.test(options.revisionId)) throw new Error("Use --revision with a discovered revision UUID");
33833
+ if (!uuid17.test(options.revisionId)) throw new Error("Use --revision with a discovered revision UUID");
33632
33834
  return "/apps/" + options.applicationId + "/integrations/definitions/" + options.revisionId;
33633
33835
  }
33634
33836
  if (command2 === "status") {
33635
- if (!options.adoptionId || !uuid16.test(options.adoptionId)) throw new Error("Use --adoption with an adoption request UUID");
33837
+ if (!options.adoptionId || !uuid17.test(options.adoptionId)) throw new Error("Use --adoption with an adoption request UUID");
33636
33838
  return "/apps/" + options.applicationId + "/integrations/adoptions/" + options.adoptionId;
33637
33839
  }
33638
- if (!options.connectionId || !uuid16.test(options.connectionId)) throw new Error("Use --connection with an integration connection UUID");
33840
+ if (!options.connectionId || !uuid17.test(options.connectionId)) throw new Error("Use --connection with an integration connection UUID");
33639
33841
  const connection2 = base + "/" + options.connectionId;
33640
33842
  if (command2 === "contract" || command2 === "types") return connection2 + "/" + command2;
33641
33843
  if (command2 === "describe") {
@@ -33658,14 +33860,14 @@ function integrationPreparation(input) {
33658
33860
  }
33659
33861
  var integrationWebhooksUsage = "Use backify integrations webhooks|webhook-deliveries --connection <UUID> --environment <UUID>, webhook-job with --binding <UUID> --job <name>, or webhook-replay with --receipt <UUID> --yes.";
33660
33862
  function integrationWebhookCall(command2, options) {
33661
- const uuid16 = /^(?:[a-f0-9]{8}-)(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i;
33662
- if (!options.connectionId || !options.environmentId || ![options.applicationId, options.connectionId, options.environmentId].every((id) => uuid16.test(id))) throw new Error(integrationWebhooksUsage);
33863
+ const uuid17 = /^(?:[a-f0-9]{8}-)(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i;
33864
+ if (!options.connectionId || !options.environmentId || ![options.applicationId, options.connectionId, options.environmentId].every((id) => uuid17.test(id))) throw new Error(integrationWebhooksUsage);
33663
33865
  const path = "/apps/" + options.applicationId + "/integrations/connectors/" + options.connectionId;
33664
33866
  if (command2 === "webhooks" || command2 === "webhook-deliveries") return { path: path + "/" + command2 + "?" + new URLSearchParams({ environmentId: options.environmentId }) };
33665
33867
  const headers = { "content-type": "application/json" };
33666
- if (command2 === "webhook-job" && options.bindingId && uuid16.test(options.bindingId) && /^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/.test(options.job ?? ""))
33868
+ if (command2 === "webhook-job" && options.bindingId && uuid17.test(options.bindingId) && /^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/.test(options.job ?? ""))
33667
33869
  return { path: path + "/webhooks/" + options.bindingId, init: { method: "PUT", headers, body: JSON.stringify({ environmentId: options.environmentId, job: options.job }) } };
33668
- if (command2 === "webhook-replay" && options.receiptId && uuid16.test(options.receiptId) && options.confirm)
33870
+ if (command2 === "webhook-replay" && options.receiptId && uuid17.test(options.receiptId) && options.confirm)
33669
33871
  return { path: path + "/webhook-deliveries/" + options.receiptId + "/replay", init: { method: "POST", headers, body: JSON.stringify({ environmentId: options.environmentId, confirm: true }) } };
33670
33872
  throw new Error(integrationWebhooksUsage);
33671
33873
  }
@@ -34114,8 +34316,271 @@ function outboundHttpCall(appId, args2) {
34114
34316
  }
34115
34317
  }
34116
34318
 
34319
+ // src/capability-data.ts
34320
+ var guid3 = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
34321
+ var bucketName = /^[a-z0-9](?:[a-z0-9-]{1,61}[a-z0-9])$/;
34322
+ function reader(args2) {
34323
+ const option2 = (name2) => {
34324
+ const index = args2.indexOf(name2);
34325
+ return index >= 0 ? args2[index + 1] : void 0;
34326
+ };
34327
+ const flag = (name2) => args2.includes(name2);
34328
+ const positional = (from = 1) => {
34329
+ for (let index = from; index < args2.length; index++) {
34330
+ if (args2[index].startsWith("--")) {
34331
+ if (!["--folders", "--deleted", "--overwrite", "--yes"].includes(args2[index])) index++;
34332
+ continue;
34333
+ }
34334
+ return args2[index];
34335
+ }
34336
+ return void 0;
34337
+ };
34338
+ return { option: option2, flag, positional };
34339
+ }
34340
+ function environmentOf(args2, usage) {
34341
+ const environment = reader(args2).option("--environment");
34342
+ if (!environment || !guid3.test(environment)) throw new Error(usage);
34343
+ return environment;
34344
+ }
34345
+ var storageUsage = [
34346
+ "Use backify storage <action> [--app <application-id>]:",
34347
+ " environments environments that have storage",
34348
+ " usage bytes, files and buckets across environments",
34349
+ " buckets --environment <UUID>",
34350
+ " ls --environment <UUID> --bucket <name> [--prefix <folder/>] [--folders] [--deleted]",
34351
+ " --folders lists one folder: its files and subfolders",
34352
+ " upload <file> --environment <UUID> --bucket <name> --key <key> [--overwrite] (at most 100 MiB)",
34353
+ " download --environment <UUID> --bucket <name> --key <key> [--out <file>]",
34354
+ " rm --environment <UUID> --bucket <name> --key <key> --yes soft delete; restore while retained",
34355
+ " restore --environment <UUID> --bucket <name> --key <key>"
34356
+ ].join("\n");
34357
+ function storageCall(appId, args2) {
34358
+ const { option: option2, flag, positional } = reader(args2);
34359
+ const action = args2[0];
34360
+ const root = `/apps/${appId}/storage`;
34361
+ if (action === "environments") return { method: "GET", path: root + "/environments" };
34362
+ if (action === "usage") return { method: "GET", path: root + "/usage" };
34363
+ const environment = environmentOf(args2, storageUsage);
34364
+ const base = `${root}/environments/${environment}`;
34365
+ if (action === "buckets") return { method: "GET", path: base + "/buckets" };
34366
+ const bucket = option2("--bucket");
34367
+ if (!bucket || !bucketName.test(bucket)) throw new Error("Give the bucket with --bucket <name>; list them with backify storage buckets --environment <UUID>.");
34368
+ const files = `${base}/buckets/${encodeURIComponent(bucket)}`;
34369
+ const key = option2("--key");
34370
+ const needKey = () => {
34371
+ if (!key) throw new Error(`Give the file with --key <key>: backify storage ${action} --environment <UUID> --bucket ${bucket} --key <key>.`);
34372
+ return key;
34373
+ };
34374
+ switch (action) {
34375
+ case "ls": {
34376
+ const query = new URLSearchParams();
34377
+ const prefix = option2("--prefix");
34378
+ if (prefix) query.set("prefix", prefix);
34379
+ if (flag("--folders") && !flag("--deleted")) query.set("delimiter", "/");
34380
+ const continuation = option2("--continue");
34381
+ if (continuation) query.set("continuationToken", continuation);
34382
+ return { method: "GET", path: files + (flag("--deleted") ? "/deleted-files" : "/files") + (query.size ? "?" + query : "") };
34383
+ }
34384
+ case "upload": {
34385
+ const file = positional();
34386
+ if (!file) throw new Error("Give the local file: backify storage upload <file> --environment <UUID> --bucket <name> --key <key>.");
34387
+ const target = needKey();
34388
+ return { method: "PUT", path: `${files}/file?` + new URLSearchParams({ key: target, ...flag("--overwrite") ? { overwrite: "true" } : {} }), upload: { file, key: target } };
34389
+ }
34390
+ case "download": {
34391
+ const target = needKey();
34392
+ return { method: "GET", path: `${files}/file?` + new URLSearchParams({ key: target }), download: { key: target, out: option2("--out") } };
34393
+ }
34394
+ case "rm": {
34395
+ const target = needKey();
34396
+ if (!flag("--yes")) throw new Error(`Deleting ${target} needs --yes. It stays restorable with backify storage restore while the bucket retains deleted files.`);
34397
+ return { method: "DELETE", path: `${files}/file?` + new URLSearchParams({ key: target, confirmation: target }) };
34398
+ }
34399
+ case "restore":
34400
+ return { method: "POST", path: `${files}/restore?` + new URLSearchParams({ key: needKey() }) };
34401
+ default:
34402
+ throw new Error(storageUsage);
34403
+ }
34404
+ }
34405
+ var databaseDataUsage = [
34406
+ "Use backify database <action> --environment <UUID> [--app <application-id>]:",
34407
+ " extensions | insights [--hours <1-168>] installed extensions; slow queries and likely missing indexes",
34408
+ " tables tables with estimated rows and sizes",
34409
+ " rows <table> [--offset <n>] [--limit <1-100>] rows as stored (not masked); needs database.manage",
34410
+ " query <sql> | query --file <sql-file> one read-only SELECT, at most 100 rows, five-second limit",
34411
+ " backups stored backups",
34412
+ " backup take a backup now",
34413
+ " restore <backup-id> --confirm <application-slug> replace all data with a backup (a safety backup is taken first)"
34414
+ ].join("\n");
34415
+ function databaseCall(appId, args2, readFile = () => {
34416
+ throw new Error("Reading files is not available.");
34417
+ }) {
34418
+ const { option: option2, positional } = reader(args2);
34419
+ const action = args2[0];
34420
+ const environment = environmentOf(args2, databaseDataUsage);
34421
+ const inspection = `/apps/${appId}/environments/${environment}/database`;
34422
+ const manage = `/apps/${appId}/database/environments/${environment}`;
34423
+ switch (action) {
34424
+ case "extensions":
34425
+ return { method: "GET", path: inspection + "/extensions" };
34426
+ case "insights": {
34427
+ const hours = option2("--hours");
34428
+ if (hours !== void 0 && (!/^\d{1,3}$/.test(hours) || Number(hours) < 1 || Number(hours) > 168)) throw new Error("--hours must be 1 to 168. insights lists slow queries and tables that likely need an index; add indexes with a new SQL migration.");
34429
+ return { method: "GET", path: inspection + "/insights" + (hours ? "?hours=" + hours : "") };
34430
+ }
34431
+ case "tables":
34432
+ return { method: "GET", path: manage + "/tables" };
34433
+ case "rows": {
34434
+ const table = positional();
34435
+ if (!table || !/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(table)) throw new Error("Give a table name: backify database rows <table> --environment <UUID>.");
34436
+ const offset = option2("--offset") ?? "0", limit = option2("--limit") ?? "50";
34437
+ if (!/^\d+$/.test(offset) || !/^\d+$/.test(limit) || Number(limit) < 1 || Number(limit) > 100) throw new Error("--offset must be 0 or more and --limit 1 to 100.");
34438
+ return { method: "GET", path: `${manage}/tables/${encodeURIComponent(table)}/rows?offset=${offset}&limit=${limit}` };
34439
+ }
34440
+ case "query": {
34441
+ const file = option2("--file");
34442
+ const sql = file ? readFile(file) : positional();
34443
+ if (!sql?.trim()) throw new Error('Give one SELECT: backify database query "SELECT \u2026" --environment <UUID>, or --file <sql-file>.');
34444
+ return { method: "POST", path: manage + "/query", body: { sql } };
34445
+ }
34446
+ case "backups":
34447
+ return { method: "GET", path: manage + "/backups" };
34448
+ case "backup":
34449
+ return { method: "POST", path: manage + "/backups" };
34450
+ case "restore": {
34451
+ const backup = positional(), confirmation = option2("--confirm");
34452
+ if (!backup || !/^[0-9a-f]{32}$/i.test(backup)) throw new Error("Give the backup ID from backify database backups: backify database restore <backup-id> --environment <UUID> --confirm <application-slug>.");
34453
+ if (!confirmation) throw new Error("Restoring replaces all data in this environment's database. Confirm with --confirm <application-slug>.");
34454
+ return { method: "POST", path: `${manage}/backups/${backup}/restore`, body: { confirmation } };
34455
+ }
34456
+ default:
34457
+ throw new Error(databaseDataUsage);
34458
+ }
34459
+ }
34460
+ var backendUsage = [
34461
+ "Use backify backend <action> --environment <UUID> [--app <application-id>]:",
34462
+ " show release, health, scale and routes of the live release",
34463
+ " routes one line per endpoint: method, path, access and operation",
34464
+ " openapi [--out <file>] the release's OpenAPI document"
34465
+ ].join("\n");
34466
+ function backendCall(appId, args2) {
34467
+ const action = args2[0];
34468
+ const environment = environmentOf(args2, backendUsage);
34469
+ const base = `/apps/${appId}/environments/${environment}/backend`;
34470
+ if (action === "show" || action === "routes") return { method: "GET", path: base };
34471
+ if (action === "openapi") return { method: "GET", path: base + "/openapi.json", download: { key: "openapi.json", out: reader(args2).option("--out") } };
34472
+ throw new Error(backendUsage);
34473
+ }
34474
+ function routeLines(routes) {
34475
+ const access = (auth2) => auth2.kind === "role" ? "role " + auth2.role : auth2.kind === "permission" ? "permission " + auth2.permission : auth2.kind === "user" ? "signed-in user" : "public";
34476
+ return routes.map((route) => [route.method.padEnd(6), route.path, "\xB7", access(route.auth), "\xB7", route.operationId].join(" "));
34477
+ }
34478
+ var jobsUsage = [
34479
+ "Use backify jobs <action> --environment <UUID> [--app <application-id>]:",
34480
+ " show declared jobs, schedules and subscriptions with recent state",
34481
+ " runs [--job <name>] [--status pending|running|completed|failed|cancelled]",
34482
+ " insights [--range 24h|7d|30d] job runs over time, by status and by job"
34483
+ ].join("\n");
34484
+ function jobsCall(appId, args2) {
34485
+ const { option: option2 } = reader(args2);
34486
+ const action = args2[0];
34487
+ const environment = environmentOf(args2, jobsUsage);
34488
+ const base = `/apps/${appId}/environments/${environment}/jobs`;
34489
+ switch (action) {
34490
+ case "show":
34491
+ return { method: "GET", path: base };
34492
+ case "runs": {
34493
+ const query = new URLSearchParams();
34494
+ const job = option2("--job"), status = option2("--status");
34495
+ if (status && !["pending", "running", "completed", "failed", "cancelled"].includes(status)) throw new Error("--status must be pending, running, completed, failed or cancelled.");
34496
+ if (job) query.set("job", job);
34497
+ if (status) query.set("status", status);
34498
+ return { method: "GET", path: base + "/runs" + (query.size ? "?" + query : "") };
34499
+ }
34500
+ case "insights": {
34501
+ const range = option2("--range") ?? "7d";
34502
+ if (!["24h", "7d", "30d"].includes(range)) throw new Error("--range must be 24h, 7d or 30d.");
34503
+ return { method: "GET", path: base + "/insights?range=" + range };
34504
+ }
34505
+ default:
34506
+ throw new Error(jobsUsage);
34507
+ }
34508
+ }
34509
+
34117
34510
  // src/index.ts
34118
34511
  init_platform_patches();
34512
+
34513
+ // src/scale.ts
34514
+ var json2 = { "content-type": "application/json" };
34515
+ var scaleUsage = [
34516
+ "Use backify scale [<environment>] [options] [--app <application-id>]:",
34517
+ " backify scale each environment's instance size and instances, with the plan's limits",
34518
+ " backify scale <environment> --size <S|M|L|XL> scale up or down: CPU and memory per instance",
34519
+ " backify scale <environment> --instances <n> scale out or in: the most instances Backify runs as traffic grows",
34520
+ " backify scale <environment> --min <n> instances that always run; --scale-to-zero is --min 0, --always-on is at least 1",
34521
+ " backify scale <environment> --concurrency <n> concurrent requests per instance before another one starts",
34522
+ "<environment> is production, preview, prototype, an environment name or its ID. Each environment scales on its own; options you leave out keep their current value."
34523
+ ].join("\n");
34524
+ function instances(count) {
34525
+ return `${count} instance${count === 1 ? "" : "s"}`;
34526
+ }
34527
+ function scaleLine(scale, sizes) {
34528
+ const size = sizes.find((item) => item.name === scale.size);
34529
+ const count = scale.minReplicas === scale.maxReplicas ? instances(scale.maxReplicas) : `${scale.minReplicas} to ${instances(scale.maxReplicas)}`;
34530
+ return `${count} of ${scale.size}${size ? ` (${size.cpu} vCPU, ${size.memory.replace("Gi", " GiB")})` : ""}, ${scale.concurrentRequests} concurrent requests per instance`;
34531
+ }
34532
+ function scaleText(view) {
34533
+ return [
34534
+ `Plan limit: instance sizes up to ${view.maxSize}, up to ${instances(view.maxReplicas)} per environment. Sizes: ${view.sizes.map((size) => `${size.name} ${size.cpu} vCPU/${size.memory.replace("Gi", " GiB")}`).join(", ")}.`,
34535
+ ...view.environments.map((environment) => `${environment.name}: ${scaleLine(environment.scale, view.sizes)}${environment.customized ? "" : " (default)"}${environment.applies ? "" : "; static site, scales automatically until it runs a container or functions"}${environment.canChange ? "" : "; view only"}`)
34536
+ ].join("\n");
34537
+ }
34538
+ function integer(value, name2) {
34539
+ if (value === void 0) return void 0;
34540
+ const number5 = Number(value);
34541
+ if (!/^\d+$/.test(value) || !Number.isSafeInteger(number5)) throw new Error(`${name2} takes a whole number.`);
34542
+ return number5;
34543
+ }
34544
+ async function appScale(call2, appId, args2) {
34545
+ const value = (name2) => {
34546
+ const index = args2.indexOf(name2);
34547
+ return index >= 0 ? args2[index + 1] : void 0;
34548
+ };
34549
+ const takesValue = /* @__PURE__ */ new Set(["--size", "--instances", "--min", "--concurrency"]);
34550
+ const positional = args2.filter((arg, index) => !arg.startsWith("--") && !takesValue.has(args2[index - 1] ?? ""));
34551
+ const known = /* @__PURE__ */ new Set([...takesValue, "--always-on", "--scale-to-zero", "--json"]);
34552
+ const unknown2 = args2.find((arg) => arg.startsWith("--") && !known.has(arg));
34553
+ if (unknown2 || positional.length > 1) throw new Error(scaleUsage);
34554
+ const path = `/apps/${appId}/scale`;
34555
+ const view = await call2(path);
34556
+ const [target] = positional;
34557
+ const size = value("--size")?.toUpperCase(), max = integer(value("--instances"), "--instances"), concurrency = integer(value("--concurrency"), "--concurrency");
34558
+ let min = integer(value("--min"), "--min");
34559
+ if (args2.includes("--always-on") && args2.includes("--scale-to-zero")) throw new Error("Use either --always-on or --scale-to-zero.");
34560
+ const changes = size !== void 0 || max !== void 0 || min !== void 0 || concurrency !== void 0 || args2.includes("--always-on") || args2.includes("--scale-to-zero");
34561
+ if (!target) {
34562
+ if (changes) throw new Error("Name the environment to scale, for example backify scale production --instances 5.");
34563
+ return { value: view, text: scaleText(view) };
34564
+ }
34565
+ const wanted = target.toLowerCase();
34566
+ const environment = view.environments.find((item) => item.id.toLowerCase() === wanted || item.name.toLowerCase() === wanted) ?? (() => {
34567
+ const byKind = view.environments.filter((item) => item.kind === wanted);
34568
+ return byKind.length === 1 ? byKind[0] : void 0;
34569
+ })();
34570
+ if (!environment) throw new Error(`No environment named ${target}. Environments: ${view.environments.map((item) => item.name).join(", ") || "none"}.`);
34571
+ if (!changes) return { value: environment, text: `${environment.name}: ${scaleLine(environment.scale, view.sizes)}` };
34572
+ if (size !== void 0 && !view.sizes.some((item) => item.name === size)) throw new Error(`--size takes one of ${view.sizes.map((item) => item.name).join(", ")}.`);
34573
+ const maxReplicas = max ?? environment.scale.maxReplicas;
34574
+ if (args2.includes("--scale-to-zero")) min = 0;
34575
+ if (args2.includes("--always-on")) min = Math.max(1, min ?? environment.scale.minReplicas);
34576
+ const minReplicas = min ?? Math.min(environment.scale.minReplicas, maxReplicas);
34577
+ const body = { size: size ?? environment.scale.size, minReplicas, maxReplicas, concurrentRequests: concurrency ?? environment.scale.concurrentRequests };
34578
+ const result = await call2(`${path}/${environment.id}`, { method: "PUT", headers: json2, body: JSON.stringify(body) });
34579
+ const restart = result.operationId ? ` The live version restarts at the new scale (operation ${result.operationId}; follow it with backify operation ${result.operationId} --wait).` : "";
34580
+ return { value: result, text: `Saved. ${result.environment.name}: ${scaleLine(result.environment.scale, view.sizes)}.${restart}` };
34581
+ }
34582
+
34583
+ // src/index.ts
34119
34584
  init_updates();
34120
34585
  init_protection2();
34121
34586
 
@@ -34132,10 +34597,10 @@ async function pairingCode(args2, input) {
34132
34597
  const chunks = [];
34133
34598
  let size = 0;
34134
34599
  for await (const chunk of input) {
34135
- const bytes = Buffer.from(chunk);
34136
- size += bytes.length;
34600
+ const bytes2 = Buffer.from(chunk);
34601
+ size += bytes2.length;
34137
34602
  if (size > 256) throw new Error("Invalid pairing input; expected one 64-character hexadecimal code.");
34138
- chunks.push(bytes);
34603
+ chunks.push(bytes2);
34139
34604
  }
34140
34605
  code = Buffer.concat(chunks).toString("utf8").trim();
34141
34606
  } else {
@@ -34292,9 +34757,9 @@ function reconnectingApiClient(session, reconnect2, transport = fetch) {
34292
34757
  init_development();
34293
34758
  init_setup();
34294
34759
  init_dist();
34295
- import { readFileSync as readFileSync24, existsSync as existsSync19, rmSync as rmSync5 } from "node:fs";
34760
+ import { readFileSync as readFileSync24, writeFileSync as writeFileSync15, existsSync as existsSync19, rmSync as rmSync5 } from "node:fs";
34296
34761
  import { homedir as homedir3 } from "node:os";
34297
- import { join as join21 } from "node:path";
34762
+ import { basename as basename4, join as join21 } from "node:path";
34298
34763
  import { spawn as spawn5 } from "node:child_process";
34299
34764
  var [command, ...args] = process.argv.slice(2);
34300
34765
  var configPath = join21(homedir3(), ".backify.json");
@@ -34351,9 +34816,11 @@ var help = [
34351
34816
  " Releases move prototype -> preview -> production through the activated environments (backify environments --help)",
34352
34817
  " hosting [--json] shows targets, environments and resources, marking kept ones | rollback <deployment-id> [--yes] (a rollback never restores the database)",
34353
34818
  "Logs: logs history --environment <prototype|preview|production|UUID> [--stream console|system|audit] [--since <30m|24h|7d> | --from <ISO> --to <ISO>] [--contains <text>] [--limit <n>] [--all] [--json] | logs recent [--environment <...>] (backify logs --help)",
34819
+ "Scale: scale [<environment> [--size <S|M|L|XL>] [--instances <n>] [--min <n> | --always-on | --scale-to-zero] [--concurrency <n>]] (each environment on its own; backify scale --help)",
34354
34820
  "Monitoring: monitoring [--environment <prototype|preview|production|UUID>] [--range 1h|6h|24h|7d] [--json] | operation <operation-id> [--wait] [--json] (activity log, one line per hosting target)",
34821
+ " monitoring widgets | capabilities [--range 24h|7d|30d] | dashboards [create|update|delete|reset] [--organization|--workspace <id>] (widget catalog, capacity and forecasts, monitoring pages)",
34355
34822
  "Handoff: handoff [status|check] | handoff request --confirm <application-slug> | handoff start|abort [--yes] | handoff package [--out <directory>] | handoff replacements [add|verify|remove] (backify handoff --help)",
34356
- "Platform: database extensions|insights --environment <UUID> [--hours <n>] | privacy requests list|show|create|update|close|preview | events environments|inspect|test | outbound show|default|allow|block|remove|destinations|requests --environment <UUID> | protection show|set|reset|traffic|requests|rules|remove-rule [--environment <UUID>] | patches [show|on|off] | updates [--fail-on <severity>] | auth setup [--providers <list>] | auth identity [move|move-back --environment <name|id> --confirm <application-slug> | clear --environment <name|id>] | domains connect [hostname] [--environment <activated environment>] | integrations connect <provider>|discover|prepare|status|list|catalog|search|describe|contract|types",
34823
+ "Data: storage environments|usage|buckets|ls|upload|download|rm|restore | database tables|rows|query|backups|backup|restore|extensions|insights | backend show|routes|openapi | jobs show|runs|insights (--environment <UUID>)\nPlatform: database extensions|insights --environment <UUID> [--hours <n>] | privacy requests list|show|create|update|close|preview | events environments|inspect|test | outbound show|default|allow|block|remove|destinations|requests --environment <UUID> | protection show|set|reset|traffic|requests|rules|remove-rule [--environment <UUID>] | patches [show|on|off] | updates [--fail-on <severity>] | auth setup [--providers <list>] | auth identity [move|move-back --environment <name|id> --confirm <application-slug> | clear --environment <name|id>] | domains connect [hostname] [--environment <activated environment>] | integrations connect <provider>|discover|prepare|status|list|catalog|search|describe|contract|types",
34357
34824
  "",
34358
34825
  "Docs: https://docs.backify.dev/"
34359
34826
  ].join("\n");
@@ -34430,7 +34897,7 @@ async function main() {
34430
34897
  const controller = new AbortController(), stop = () => controller.abort();
34431
34898
  process.once("SIGINT", stop);
34432
34899
  process.once("SIGTERM", stop);
34433
- const json6 = args.includes("--json");
34900
+ const json7 = args.includes("--json");
34434
34901
  try {
34435
34902
  const { result } = await runTaskCommand2(command, args, {
34436
34903
  configPath,
@@ -34442,10 +34909,10 @@ async function main() {
34442
34909
  progress: (message) => console.error(message),
34443
34910
  signal: controller.signal
34444
34911
  });
34445
- console.log(json6 ? JSON.stringify(result.value, null, 2) : result.text);
34912
+ console.log(json7 ? JSON.stringify(result.value, null, 2) : result.text);
34446
34913
  if (result.exitCode !== void 0) process.exitCode = result.exitCode;
34447
34914
  } catch (error2) {
34448
- if (!(error2 instanceof OpsError2) || !json6) throw error2;
34915
+ if (!(error2 instanceof OpsError2) || !json7) throw error2;
34449
34916
  console.log(JSON.stringify({ schemaVersion: 1, status: "failed", exitCode: 1, error: error2.message, code: error2.code, ...error2.details }, null, 2));
34450
34917
  process.exitCode = 1;
34451
34918
  } finally {
@@ -34461,7 +34928,7 @@ async function main() {
34461
34928
  console.log(ssoHelp2);
34462
34929
  break;
34463
34930
  }
34464
- const json6 = args.includes("--json");
34931
+ const json7 = args.includes("--json");
34465
34932
  try {
34466
34933
  const { result } = await runSsoCommand2(args, {
34467
34934
  configPath,
@@ -34472,10 +34939,10 @@ async function main() {
34472
34939
  openBrowser,
34473
34940
  progress: (message) => console.error(message)
34474
34941
  });
34475
- console.log(json6 ? JSON.stringify(result.value, null, 2) : result.text);
34942
+ console.log(json7 ? JSON.stringify(result.value, null, 2) : result.text);
34476
34943
  if (result.exitCode !== void 0) process.exitCode = result.exitCode;
34477
34944
  } catch (error2) {
34478
- if (!(error2 instanceof OpsError2) || !json6) throw error2;
34945
+ if (!(error2 instanceof OpsError2) || !json7) throw error2;
34479
34946
  console.log(JSON.stringify({ schemaVersion: 1, status: "failed", exitCode: 1, error: error2.message, code: error2.code, ...error2.details }, null, 2));
34480
34947
  process.exitCode = 1;
34481
34948
  }
@@ -34527,7 +34994,7 @@ async function main() {
34527
34994
  if (args[0] === "identity") {
34528
34995
  const identity = await Promise.resolve().then(() => (init_auth_identity(), auth_identity_exports));
34529
34996
  const { CommandError: CommandError2 } = await Promise.resolve().then(() => (init_release_flow(), release_flow_exports));
34530
- const json6 = args.includes("--json");
34997
+ const json7 = args.includes("--json");
34531
34998
  try {
34532
34999
  const options2 = identity.authIdentityArguments(args.slice(1));
34533
35000
  if (options2 === "help") {
@@ -34535,10 +35002,10 @@ async function main() {
34535
35002
  break;
34536
35003
  }
34537
35004
  const result = await identity.runAuthIdentity(call, applicationGuid(option("--app") ?? projectApplication()), options2);
34538
- console.log(json6 ? JSON.stringify(result.value, null, 2) : result.text);
35005
+ console.log(json7 ? JSON.stringify(result.value, null, 2) : result.text);
34539
35006
  if (result.exitCode !== void 0) process.exitCode = result.exitCode;
34540
35007
  } catch (error2) {
34541
- if (!(error2 instanceof CommandError2) || !json6) throw error2;
35008
+ if (!(error2 instanceof CommandError2) || !json7) throw error2;
34542
35009
  console.log(JSON.stringify({ schemaVersion: 1, status: "failed", exitCode: 1, error: error2.message, code: error2.code, ...error2.details }, null, 2));
34543
35010
  process.exitCode = 1;
34544
35011
  }
@@ -34856,7 +35323,7 @@ Next: ${here ? "" : `cd ${directory} && `}npm install && npm run dev`);
34856
35323
  case "promote": {
34857
35324
  const flow = await Promise.resolve().then(() => (init_release_flow(), release_flow_exports));
34858
35325
  const { terminalConfirm: terminalConfirm2 } = await Promise.resolve().then(() => (init_ops(), ops_exports));
34859
- const json6 = args.includes("--json");
35326
+ const json7 = args.includes("--json");
34860
35327
  try {
34861
35328
  const options = command === "environments" ? flow.environmentsArguments(args) : command === "promote" ? flow.promoteArguments(args) : args.includes("--help") || args.includes("-h") ? "help" : void 0;
34862
35329
  if (options === "help") {
@@ -34866,10 +35333,10 @@ Next: ${here ? "" : `cd ${directory} && `}npm install && npm run dev`);
34866
35333
  if (command === "release-flow" && args.some((value, index) => value !== "--json" && value !== "--app" && args[index - 1] !== "--app")) throw new Error(flow.releaseFlowHelp);
34867
35334
  const application = applicationGuid(option("--app") ?? projectApplication()), context2 = { confirm: terminalConfirm2() };
34868
35335
  const result = command === "environments" ? await flow.runEnvironments(call, application, options, context2) : command === "promote" ? await flow.promote(call, application, options, context2) : await flow.releaseFlow(call, application);
34869
- console.log(json6 ? JSON.stringify(result.value, null, 2) : result.text);
35336
+ console.log(json7 ? JSON.stringify(result.value, null, 2) : result.text);
34870
35337
  if (result.exitCode !== void 0) process.exitCode = result.exitCode;
34871
35338
  } catch (error2) {
34872
- if (!(error2 instanceof flow.CommandError) || !json6) throw error2;
35339
+ if (!(error2 instanceof flow.CommandError) || !json7) throw error2;
34873
35340
  console.log(JSON.stringify({ schemaVersion: 1, status: "failed", exitCode: 1, error: error2.message, code: error2.code, ...error2.details }, null, 2));
34874
35341
  process.exitCode = 1;
34875
35342
  }
@@ -34880,7 +35347,7 @@ Next: ${here ? "" : `cd ${directory} && `}npm install && npm run dev`);
34880
35347
  const hostingModule = await Promise.resolve().then(() => (init_hosting(), hosting_exports));
34881
35348
  const { CommandError: CommandError2 } = await Promise.resolve().then(() => (init_release_flow(), release_flow_exports));
34882
35349
  const { terminalConfirm: terminalConfirm2 } = await Promise.resolve().then(() => (init_ops(), ops_exports));
34883
- const json6 = args.includes("--json");
35350
+ const json7 = args.includes("--json");
34884
35351
  try {
34885
35352
  const options = command === "hosting" ? hostingModule.hostingArguments(args) : hostingModule.rollbackArguments(args);
34886
35353
  if (options === "help") {
@@ -34889,9 +35356,9 @@ Next: ${here ? "" : `cd ${directory} && `}npm install && npm run dev`);
34889
35356
  }
34890
35357
  const application = applicationGuid(option("--app") ?? projectApplication());
34891
35358
  const result = command === "hosting" ? await hostingModule.runHosting(call, application) : await hostingModule.runRollback(call, application, options, { confirm: terminalConfirm2() });
34892
- console.log(json6 ? JSON.stringify(result.value, null, 2) : result.text);
35359
+ console.log(json7 ? JSON.stringify(result.value, null, 2) : result.text);
34893
35360
  } catch (error2) {
34894
- if (!(error2 instanceof CommandError2) || !json6) throw error2;
35361
+ if (!(error2 instanceof CommandError2) || !json7) throw error2;
34895
35362
  console.log(JSON.stringify({ schemaVersion: 1, status: "failed", exitCode: 1, error: error2.message, code: error2.code, ...error2.details }, null, 2));
34896
35363
  process.exitCode = 1;
34897
35364
  }
@@ -34901,7 +35368,7 @@ Next: ${here ? "" : `cd ${directory} && `}npm install && npm run dev`);
34901
35368
  const handoff2 = await Promise.resolve().then(() => (init_handoff(), handoff_exports));
34902
35369
  const { CommandError: CommandError2 } = await Promise.resolve().then(() => (init_release_flow(), release_flow_exports));
34903
35370
  const { terminalConfirm: terminalConfirm2 } = await Promise.resolve().then(() => (init_ops(), ops_exports));
34904
- const json6 = args.includes("--json");
35371
+ const json7 = args.includes("--json");
34905
35372
  try {
34906
35373
  const options = handoff2.handoffArguments(args);
34907
35374
  if (options === "help") {
@@ -34909,10 +35376,10 @@ Next: ${here ? "" : `cd ${directory} && `}npm install && npm run dev`);
34909
35376
  break;
34910
35377
  }
34911
35378
  const result = await handoff2.runHandoff(call, applicationGuid(option("--app") ?? projectApplication()), options, { confirm: terminalConfirm2() });
34912
- console.log(json6 ? JSON.stringify(result.value, null, 2) : result.text);
35379
+ console.log(json7 ? JSON.stringify(result.value, null, 2) : result.text);
34913
35380
  if (result.exitCode !== void 0) process.exitCode = result.exitCode;
34914
35381
  } catch (error2) {
34915
- if (!(error2 instanceof CommandError2) || !json6) throw error2;
35382
+ if (!(error2 instanceof CommandError2) || !json7) throw error2;
34916
35383
  console.log(JSON.stringify({ schemaVersion: 1, status: "failed", exitCode: 1, error: error2.message, code: error2.code, ...error2.details }, null, 2));
34917
35384
  process.exitCode = 1;
34918
35385
  }
@@ -34920,7 +35387,7 @@ Next: ${here ? "" : `cd ${directory} && `}npm install && npm run dev`);
34920
35387
  }
34921
35388
  case "logs": {
34922
35389
  const history = await Promise.resolve().then(() => (init_logs_history(), logs_history_exports));
34923
- const json6 = args.includes("--json");
35390
+ const json7 = args.includes("--json");
34924
35391
  try {
34925
35392
  const options = history.logsArguments(args);
34926
35393
  if (options === "help") {
@@ -34929,10 +35396,10 @@ Next: ${here ? "" : `cd ${directory} && `}npm install && npm run dev`);
34929
35396
  }
34930
35397
  const application = applicationGuid(option("--app") ?? projectApplication());
34931
35398
  const result = options.action === "recent" ? await history.runLogsRecent(call, application, options) : await history.runLogsHistory(call, application, options);
34932
- console.log(json6 ? JSON.stringify(result.value, null, 2) : result.text);
35399
+ console.log(json7 ? JSON.stringify(result.value, null, 2) : result.text);
34933
35400
  } catch (error2) {
34934
35401
  const flow = await Promise.resolve().then(() => (init_release_flow(), release_flow_exports));
34935
- if (!(error2 instanceof flow.CommandError) || !json6) throw error2;
35402
+ if (!(error2 instanceof flow.CommandError) || !json7) throw error2;
34936
35403
  console.log(JSON.stringify({ schemaVersion: 1, status: "failed", exitCode: 1, error: error2.message, code: error2.code, ...error2.details }, null, 2));
34937
35404
  process.exitCode = 1;
34938
35405
  }
@@ -34941,17 +35408,26 @@ Next: ${here ? "" : `cd ${directory} && `}npm install && npm run dev`);
34941
35408
  case "monitoring":
34942
35409
  case "operation": {
34943
35410
  const flow = await Promise.resolve().then(() => (init_release_flow(), release_flow_exports));
34944
- const json6 = args.includes("--json");
35411
+ const json7 = args.includes("--json");
34945
35412
  try {
34946
35413
  let result;
34947
35414
  if (command === "monitoring") {
34948
- const monitoring = await Promise.resolve().then(() => (init_monitoring(), monitoring_exports));
34949
- const options = monitoring.monitoringArguments(args);
34950
- if (options === "help") {
34951
- console.log(monitoring.monitoringHelp);
35415
+ const dashboards = await Promise.resolve().then(() => (init_monitoring_dashboards(), monitoring_dashboards_exports));
35416
+ const pages = dashboards.monitoringDashboardArguments(args);
35417
+ if (pages === "help") {
35418
+ console.log(dashboards.monitoringDashboardsHelp);
34952
35419
  break;
34953
35420
  }
34954
- result = await monitoring.runMonitoring(call, applicationGuid(option("--app") ?? projectApplication()), options);
35421
+ if (pages) result = await dashboards.runMonitoringDashboards(call, pages.action === "widgets" || "scope" in pages && pages.scope ? "" : applicationGuid(option("--app") ?? projectApplication()), pages);
35422
+ else {
35423
+ const monitoring = await Promise.resolve().then(() => (init_monitoring(), monitoring_exports));
35424
+ const options = monitoring.monitoringArguments(args);
35425
+ if (options === "help") {
35426
+ console.log(monitoring.monitoringHelp + "\n\n" + dashboards.monitoringDashboardsHelp);
35427
+ break;
35428
+ }
35429
+ result = await monitoring.runMonitoring(call, applicationGuid(option("--app") ?? projectApplication()), options);
35430
+ }
34955
35431
  } else {
34956
35432
  const progress = await Promise.resolve().then(() => (init_operation_progress(), operation_progress_exports));
34957
35433
  const options = progress.operationArguments(args);
@@ -34959,12 +35435,12 @@ Next: ${here ? "" : `cd ${directory} && `}npm install && npm run dev`);
34959
35435
  console.log(progress.operationHelp);
34960
35436
  break;
34961
35437
  }
34962
- result = await progress.runOperation(call, options, { progress: json6 ? void 0 : (text2) => console.log(text2) });
35438
+ result = await progress.runOperation(call, options, { progress: json7 ? void 0 : (text2) => console.log(text2) });
34963
35439
  }
34964
- console.log(json6 ? JSON.stringify(result.value, null, 2) : result.text);
35440
+ console.log(json7 ? JSON.stringify(result.value, null, 2) : result.text);
34965
35441
  if (result.exitCode !== void 0) process.exitCode = result.exitCode;
34966
35442
  } catch (error2) {
34967
- if (!(error2 instanceof flow.CommandError) || !json6) throw error2;
35443
+ if (!(error2 instanceof flow.CommandError) || !json7) throw error2;
34968
35444
  console.log(JSON.stringify({ schemaVersion: 1, status: "failed", exitCode: 1, error: error2.message, code: error2.code, ...error2.details }, null, 2));
34969
35445
  process.exitCode = 1;
34970
35446
  }
@@ -34978,17 +35454,62 @@ Next: ${here ? "" : `cd ${directory} && `}npm install && npm run dev`);
34978
35454
  break;
34979
35455
  }
34980
35456
  case "database": {
34981
- const usage = "Use backify database extensions|insights --environment <UUID> [--hours <1-168>] [--app <application-id>]. insights lists slow queries and tables that likely need an index; add indexes with a new SQL migration.";
34982
- if (args.includes("--help")) {
34983
- console.log(usage);
35457
+ if (!args.length || args.includes("--help")) {
35458
+ console.log(databaseDataUsage);
35459
+ if (!args.length) process.exitCode = 2;
35460
+ break;
35461
+ }
35462
+ const request = databaseCall(applicationGuid(option("--app") ?? projectApplication()), args, (path) => readFileSync24(path, "utf8"));
35463
+ console.log(JSON.stringify(await call(request.path, { method: request.method, body: request.body ? JSON.stringify(request.body) : void 0 }), null, 2));
35464
+ break;
35465
+ }
35466
+ case "storage": {
35467
+ if (!args.length || args.includes("--help")) {
35468
+ console.log(storageUsage);
35469
+ if (!args.length) process.exitCode = 2;
35470
+ break;
35471
+ }
35472
+ const request = storageCall(applicationGuid(option("--app") ?? projectApplication()), args);
35473
+ if (request.upload) {
35474
+ const data = readFileSync24(request.upload.file);
35475
+ if (data.byteLength > 100 * 1024 * 1024) throw new Error(request.upload.file + " is larger than 100 MiB, the upload limit.");
35476
+ const form = new FormData();
35477
+ form.append("file", new Blob([data]), basename4(request.upload.file));
35478
+ console.log(JSON.stringify(await call(request.path, { method: request.method, body: form }), null, 2));
35479
+ } else if (request.download) {
35480
+ const bytes2 = await call(request.path, { headers: { accept: "application/octet-stream" } });
35481
+ const out = request.download.out ?? basename4(request.download.key);
35482
+ writeFileSync15(out, bytes2);
35483
+ console.log("Saved " + request.download.key + " to " + out + " (" + bytes2.byteLength + " bytes).");
35484
+ } else {
35485
+ const result = await call(request.path, { method: request.method, body: request.body ? JSON.stringify(request.body) : void 0 });
35486
+ console.log(request.method === "DELETE" ? "Deleted. Restore it with backify storage restore while the bucket retains deleted files." : request.method === "POST" ? "Restored." : JSON.stringify(result, null, 2));
35487
+ }
35488
+ break;
35489
+ }
35490
+ case "backend": {
35491
+ if (!args.length || args.includes("--help")) {
35492
+ console.log(backendUsage);
35493
+ if (!args.length) process.exitCode = 2;
35494
+ break;
35495
+ }
35496
+ const request = backendCall(applicationGuid(option("--app") ?? projectApplication()), args);
35497
+ const result = await call(request.path);
35498
+ if (args[0] === "routes") console.log(routeLines(result.routes ?? []).join("\n") || "This release declares no endpoints.");
35499
+ else if (request.download?.out) {
35500
+ writeFileSync15(request.download.out, JSON.stringify(result, null, 2) + "\n");
35501
+ console.log("Saved the OpenAPI document to " + request.download.out + ".");
35502
+ } else console.log(JSON.stringify(result, null, 2));
35503
+ break;
35504
+ }
35505
+ case "jobs": {
35506
+ if (!args.length || args.includes("--help")) {
35507
+ console.log(jobsUsage);
35508
+ if (!args.length) process.exitCode = 2;
34984
35509
  break;
34985
35510
  }
34986
- const environment = option("--environment"), hours = option("--hours");
34987
- if (!["extensions", "insights"].includes(args[0]) || !environment || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(environment) || hours !== void 0 && (args[0] !== "insights" || !/^\d{1,3}$/.test(hours) || Number(hours) < 1 || Number(hours) > 168))
34988
- throw new Error(usage);
34989
- const app = applicationGuid(option("--app") ?? projectApplication());
34990
- const query = hours ? "?hours=" + hours : "";
34991
- console.log(JSON.stringify(await call(`/apps/${app}/environments/${environment}/database/${args[0]}${query}`), null, 2));
35511
+ const request = jobsCall(applicationGuid(option("--app") ?? projectApplication()), args);
35512
+ console.log(JSON.stringify(await call(request.path), null, 2));
34992
35513
  break;
34993
35514
  }
34994
35515
  case "privacy": {
@@ -35033,6 +35554,16 @@ Next: ${here ? "" : `cd ${directory} && `}npm install && npm run dev`);
35033
35554
  process.exitCode = result.exitCode;
35034
35555
  break;
35035
35556
  }
35557
+ case "scale": {
35558
+ if (args.includes("--help")) {
35559
+ console.log(scaleUsage);
35560
+ break;
35561
+ }
35562
+ const appId = applicationGuid(option("--app") ?? projectApplication());
35563
+ const result = await appScale(call, appId, args.filter((value, index) => value !== "--app" && args[index - 1] !== "--app"));
35564
+ console.log(args.includes("--json") ? JSON.stringify(result.value, null, 2) : result.text);
35565
+ break;
35566
+ }
35036
35567
  case "patches": {
35037
35568
  if (args.includes("--help")) {
35038
35569
  console.log(patchesUsage);