@backifydev/cli 0.4.10 → 0.4.12

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 (3) hide show
  1. package/README.md +3 -0
  2. package/dist/index.js +1293 -478
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1577,8 +1577,8 @@ function searchOperations(operations, query = "", group) {
1577
1577
  let best = 0;
1578
1578
  for (const [fieldWords, weight] of fields)
1579
1579
  for (const word of fieldWords) {
1580
- const base = singular(word);
1581
- const value = base === exact ? weight : related.has(base) ? weight * 0.8 : base.startsWith(exact) && term.length >= 3 ? weight * 0.6 : nearlyEqual(base, exact) ? weight * 0.5 : 0;
1580
+ const base2 = singular(word);
1581
+ const value = base2 === exact ? weight : related.has(base2) ? weight * 0.8 : base2.startsWith(exact) && term.length >= 3 ? weight * 0.6 : nearlyEqual(base2, exact) ? weight * 0.5 : 0;
1582
1582
  if (value > best)
1583
1583
  best = value;
1584
1584
  }
@@ -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)));
@@ -7683,7 +7683,7 @@ async function runMove(call2, prefix, options, context2) {
7683
7683
  const placements = await call2(prefix + "/environments/placements");
7684
7684
  const current = placements.find((item) => item.kind === options.kind);
7685
7685
  if (!current) throw new CommandError("This application has no " + options.kind + " environment.", "environment_not_activated", { kind: options.kind });
7686
- const base = prefix + "/environments/" + current.environmentId + "/moves";
7686
+ const base2 = prefix + "/environments/" + current.environmentId + "/moves";
7687
7687
  const confirmed = async (summary, details) => {
7688
7688
  if (options.yes) return;
7689
7689
  if (!context2.confirm) throw new CommandError("Refusing to change a hosting move without confirmation. Review this and re-run with --yes:\n" + summary, "confirmation_required", { kind: options.kind, ...details });
@@ -7691,17 +7691,17 @@ async function runMove(call2, prefix, options, context2) {
7691
7691
  };
7692
7692
  if (options.moveAction === "request") {
7693
7693
  const query = "destinationTargetId=" + encodeURIComponent(options.target) + "&windowStart=" + encodeURIComponent(options.windowStart) + "&windowEnd=" + encodeURIComponent(options.windowEnd);
7694
- const preflight = await call2(base + "/preflight?" + query);
7694
+ const preflight = await call2(base2 + "/preflight?" + query);
7695
7695
  const checks = pad([["CHECK", "RESULT", "DETAIL"], ...preflight.checks.map((check) => [check.name, check.state, check.detail ?? ""])]);
7696
7696
  const failed = preflight.checks.filter((check) => check.state === "failed").map((check) => check.id);
7697
7697
  if (!preflight.ready) return { exitCode: 2, value: { status: "blocked", kind: options.kind, destinationTargetId: options.target, failed, checks: preflight.checks }, text: [...checks, "", "The " + options.kind + " environment cannot be moved to this hosting target in this window. Nothing was changed."].join("\n") };
7698
7698
  if (options.check) return { value: { status: "ready", kind: options.kind, destinationTargetId: options.target, checks: preflight.checks }, text: [...checks, "", "All checks passed. Nothing was changed; re-run without --check to request the move."].join("\n") };
7699
7699
  await confirmed("Request moving the " + options.kind + " environment to deployment target " + options.target + " in the window " + options.windowStart + " to " + options.windowEnd + ". Another person must approve it; the environment goes into maintenance only when the move is started.", { destinationTargetId: options.target });
7700
- const result = await call2(base, { method: "POST", body: JSON.stringify({ destinationTargetId: options.target, windowStart: options.windowStart, windowEnd: options.windowEnd }) });
7700
+ const result = await call2(base2, { method: "POST", body: JSON.stringify({ destinationTargetId: options.target, windowStart: options.windowStart, windowEnd: options.windowEnd }) });
7701
7701
  if (!result.created || !result.move) return { exitCode: 2, value: { status: "blocked", kind: options.kind, destinationTargetId: options.target, failed: result.preflight.checks.filter((check) => check.state === "failed").map((check) => check.id), checks: result.preflight.checks }, text: "The checks no longer pass. Nothing was changed." };
7702
7702
  return { value: { status: "requested", kind: options.kind, move: result.move }, text: ["The move of the " + options.kind + " environment awaits approval. Another person approves it on the organization's Approvals page.", "", ...moveSummary(result.move)].join("\n") };
7703
7703
  }
7704
- const moves = await call2(base);
7704
+ const moves = await call2(base2);
7705
7705
  const move = moves.find((item) => !moveTerminal(item)) ?? moves[0];
7706
7706
  if (options.moveAction === "status") return { value: { move: move ?? null }, text: move ? moveSummary(move).join("\n") : "The " + options.kind + " environment has no hosting move." };
7707
7707
  if (!move) throw new CommandError("The " + options.kind + " environment has no hosting move.", "hosting_move_not_found", { kind: options.kind });
@@ -7713,15 +7713,15 @@ async function runMove(call2, prefix, options, context2) {
7713
7713
  if (options.active !== move.sourceTargetId && options.active !== move.destinationTargetId) throw new CommandError("--active must be the current target " + move.sourceTargetId + " or the destination " + move.destinationTargetId + ".", "hosting_move_confirm_target_invalid", { kind: options.kind });
7714
7714
  await confirmed("Confirm that deployment target " + options.active + " is serving the " + options.kind + " environment. The outcome of the switch is unknown; only confirm after checking.", { action, active: options.active });
7715
7715
  }
7716
- const updated = await call2(base + "/" + move.id + "/" + action, { method: "POST", ...action === "confirm" ? { body: JSON.stringify({ activeTargetId: options.active }) } : {} });
7716
+ const updated = await call2(base2 + "/" + move.id + "/" + action, { method: "POST", ...action === "confirm" ? { body: JSON.stringify({ activeTargetId: options.active }) } : {} });
7717
7717
  return { value: { status: action, kind: options.kind, move: updated }, text: ["The " + options.kind + " move: " + action + " accepted.", "", ...moveSummary(updated)].join("\n") };
7718
7718
  }
7719
7719
  async function runMoveBack(call2, prefix, options) {
7720
7720
  const placements = await call2(prefix + "/environments/placements");
7721
7721
  const current = placements.find((item) => item.kind === options.kind);
7722
7722
  if (!current) throw new CommandError("This application has no " + options.kind + " environment.", "environment_not_activated", { kind: options.kind });
7723
- const base = prefix + "/environments/" + current.environmentId + "/moves";
7724
- const moves = await call2(base);
7723
+ const base2 = prefix + "/environments/" + current.environmentId + "/moves";
7724
+ const moves = await call2(base2);
7725
7725
  const completed = moves.find((item) => item.state === "completed");
7726
7726
  if (!completed) throw new CommandError("The " + options.kind + " environment has no completed hosting move to move back.", "hosting_move_not_found", { kind: options.kind });
7727
7727
  const kept2 = completed.retained ? " The copy there is kept until " + completed.retained.retainedUntil + "; it is reused and checked first." : "";
@@ -7733,7 +7733,7 @@ async function runMoveBack(call2, prefix, options) {
7733
7733
  "confirmation_required",
7734
7734
  { kind: options.kind, moveId: completed.id, ...slug ? { confirm: slug } : {} }
7735
7735
  );
7736
- const result = await call2(base + "/" + completed.id + "/move-back", { method: "POST", body: JSON.stringify({ windowStart: options.windowStart, windowEnd: options.windowEnd }) });
7736
+ const result = await call2(base2 + "/" + completed.id + "/move-back", { method: "POST", body: JSON.stringify({ windowStart: options.windowStart, windowEnd: options.windowEnd }) });
7737
7737
  if (!result.created || !result.move) {
7738
7738
  const failed = result.preflight.checks.filter((check) => check.state === "failed");
7739
7739
  return {
@@ -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.12",
8047
8047
  description: "Command-line setup and diagnostics for Backify applications",
8048
8048
  type: "module",
8049
8049
  bin: {
@@ -8510,11 +8510,11 @@ function ensureSessionOutlasts(session, durationMs, now = Date.now()) {
8510
8510
  if (remaining < durationMs) throw new CliAuthenticationRequired(`Backify CLI access for this app ends in ${Math.max(1, Math.floor(remaining / 6e4))} minute(s), before backify ship could finish (it waits up to ${Math.ceil(durationMs / 6e4)} minutes). Nothing was pushed. Ask the user to sign in, then run backify connect --reauth and ship again. The browser lets them choose 7, 14, 30, or 90 days.`);
8511
8511
  }
8512
8512
  function apiClient(session, transport = fetch) {
8513
- const base = apiAddress(session.apiUrl);
8513
+ const base2 = apiAddress(session.apiUrl);
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(base2 + 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, guid5, 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
+ guid5 = /^([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 = guid5);
12127
12128
  $ZodStringFormat.init(inst, def);
12128
12129
  });
12129
12130
  $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => {
@@ -13441,14 +13442,14 @@ var init_memoizer = __esm({
13441
13442
  var _a3;
13442
13443
  (_a3 = inst._zod).deferred ?? (_a3.deferred = []);
13443
13444
  inst._zod.deferred.push(() => {
13444
- const base = inst._zod.parse;
13445
+ const base2 = inst._zod.parse;
13445
13446
  const wrapped = (payload, ctx) => {
13446
13447
  if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value))
13447
13448
  throw new $ZodCyclicError();
13448
- return base(payload, ctx);
13449
+ return base2(payload, ctx);
13449
13450
  };
13450
13451
  inst._zod.parse = wrapped;
13451
- if (inst._zod.run === base)
13452
+ if (inst._zod.run === base2)
13452
13453
  inst._zod.run = wrapped;
13453
13454
  });
13454
13455
  },
@@ -13460,15 +13461,15 @@ var init_memoizer = __esm({
13460
13461
  let lastBucket;
13461
13462
  (_a3 = inst._zod).deferred ?? (_a3.deferred = []);
13462
13463
  inst._zod.deferred.push(() => {
13463
- const base = inst._zod.parse;
13464
+ const base2 = inst._zod.parse;
13464
13465
  const wrapped = (payload, ctx) => {
13465
13466
  if (isRecursiveInst === void 0) {
13466
13467
  const walked = isRecursive(inst, /* @__PURE__ */ new Set(), false);
13467
13468
  if (walked === NONE) {
13468
- inst._zod.parse = base;
13469
+ inst._zod.parse = base2;
13469
13470
  if (inst._zod.run === wrapped)
13470
- inst._zod.run = base;
13471
- return base(payload, ctx);
13471
+ inst._zod.run = base2;
13472
+ return base2(payload, ctx);
13472
13473
  }
13473
13474
  if (walked === PROVEN || rechecked)
13474
13475
  isRecursiveInst = true;
@@ -13477,7 +13478,7 @@ var init_memoizer = __esm({
13477
13478
  }
13478
13479
  const input = payload.value;
13479
13480
  if (!isRef(input))
13480
- return base(payload, ctx);
13481
+ return base2(payload, ctx);
13481
13482
  let state = ctx[STATE];
13482
13483
  if (!state) {
13483
13484
  state = { buckets: /* @__PURE__ */ new WeakMap(), backEdges: void 0 };
@@ -13506,7 +13507,7 @@ var init_memoizer = __esm({
13506
13507
  }
13507
13508
  handoff = bucket;
13508
13509
  const depth = open.length;
13509
- const result = base(payload, ctx);
13510
+ const result = base2(payload, ctx);
13510
13511
  handoff = void 0;
13511
13512
  const entry = open.length > depth ? open.pop() : void 0;
13512
13513
  if (result instanceof Promise) {
@@ -13521,7 +13522,7 @@ var init_memoizer = __esm({
13521
13522
  return result;
13522
13523
  };
13523
13524
  inst._zod.parse = wrapped;
13524
- if (inst._zod.run === base)
13525
+ if (inst._zod.run === base2)
13525
13526
  inst._zod.run = wrapped;
13526
13527
  });
13527
13528
  }
@@ -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
  });
@@ -18683,8 +18684,8 @@ var init_zod_json_schema_compat = __esm({
18683
18684
  function isPlainObject2(value) {
18684
18685
  return value !== null && typeof value === "object" && !Array.isArray(value);
18685
18686
  }
18686
- function mergeCapabilities(base, additional) {
18687
- const result = { ...base };
18687
+ function mergeCapabilities(base2, additional) {
18688
+ const result = { ...base2 };
18688
18689
  for (const key in additional) {
18689
18690
  const k = key;
18690
18691
  const addValue = additional[k];
@@ -23543,10 +23544,10 @@ var require_fast_uri = __commonJS({
23543
23544
  schemelessOptions.skipEscape = true;
23544
23545
  return serialize(resolved, schemelessOptions);
23545
23546
  }
23546
- function resolveComponent(base, relative5, options, skipNormalization) {
23547
+ function resolveComponent(base2, relative5, options, skipNormalization) {
23547
23548
  const target = {};
23548
23549
  if (!skipNormalization) {
23549
- base = parse4(serialize(base, options), options);
23550
+ base2 = parse4(serialize(base2, options), options);
23550
23551
  relative5 = parse4(serialize(relative5, options), options);
23551
23552
  }
23552
23553
  options = options || {};
@@ -23566,33 +23567,33 @@ var require_fast_uri = __commonJS({
23566
23567
  target.query = relative5.query;
23567
23568
  } else {
23568
23569
  if (!relative5.path) {
23569
- target.path = base.path;
23570
+ target.path = base2.path;
23570
23571
  if (relative5.query !== void 0) {
23571
23572
  target.query = relative5.query;
23572
23573
  } else {
23573
- target.query = base.query;
23574
+ target.query = base2.query;
23574
23575
  }
23575
23576
  } else {
23576
23577
  if (relative5.path[0] === "/") {
23577
23578
  target.path = removeDotSegments(relative5.path);
23578
23579
  } else {
23579
- const baseHasAuthority = base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0;
23580
- if (baseHasAuthority && !base.path) {
23580
+ const baseHasAuthority = base2.userinfo !== void 0 || base2.host !== void 0 || base2.port !== void 0;
23581
+ if (baseHasAuthority && !base2.path) {
23581
23582
  target.path = "/" + relative5.path;
23582
- } else if (!base.path) {
23583
+ } else if (!base2.path) {
23583
23584
  target.path = relative5.path;
23584
23585
  } else {
23585
- target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative5.path;
23586
+ target.path = base2.path.slice(0, base2.path.lastIndexOf("/") + 1) + relative5.path;
23586
23587
  }
23587
- target.path = base.scheme === void 0 && !baseHasAuthority && target.path[0] !== "/" ? removeDotSegmentsRelative(target.path) : removeDotSegments(target.path);
23588
+ target.path = base2.scheme === void 0 && !baseHasAuthority && target.path[0] !== "/" ? removeDotSegmentsRelative(target.path) : removeDotSegments(target.path);
23588
23589
  }
23589
23590
  target.query = relative5.query;
23590
23591
  }
23591
- target.userinfo = base.userinfo;
23592
- target.host = base.host;
23593
- target.port = base.port;
23592
+ target.userinfo = base2.userinfo;
23593
+ target.host = base2.host;
23594
+ target.port = base2.port;
23594
23595
  }
23595
- target.scheme = base.scheme;
23596
+ target.scheme = base2.scheme;
23596
23597
  }
23597
23598
  target.fragment = relative5.fragment;
23598
23599
  return target;
@@ -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.");
@@ -30296,9 +30297,11 @@ __export(tasks_exports, {
30296
30297
  runTaskCommand: () => runTaskCommand,
30297
30298
  runtimeUpgradeText: () => runtimeUpgradeText,
30298
30299
  startTask: () => startTask,
30300
+ suggestionText: () => suggestionText,
30299
30301
  taskArguments: () => taskArguments,
30300
30302
  taskDraft: () => taskDraft,
30301
30303
  taskHelp: () => taskHelp,
30304
+ teamDetailsText: () => teamDetailsText,
30302
30305
  teamsText: () => teamsText
30303
30306
  });
30304
30307
  import { readFileSync as readFileSync15 } from "node:fs";
@@ -30466,7 +30469,7 @@ async function setLocations(call2, organizationId, values, options, context2) {
30466
30469
  if (workspaceId) {
30467
30470
  const workspace = current.workspace;
30468
30471
  const defaultRegion = defaultChoice === "inherit" ? null : defaultChoice ?? workspace.defaultRegion ?? null;
30469
- await call2(`/workspaces/${workspaceId}`, { method: "PATCH", headers: json3, body: JSON.stringify({
30472
+ await call2(`/workspaces/${workspaceId}`, { method: "PATCH", headers: json4, body: JSON.stringify({
30470
30473
  name: workspace.name,
30471
30474
  description: workspace.description ?? null,
30472
30475
  isDefault: workspace.isDefault,
@@ -30481,7 +30484,7 @@ async function setLocations(call2, organizationId, values, options, context2) {
30481
30484
  repositoryNamePostfix: workspace.repositoryNamePostfix ?? ""
30482
30485
  }) });
30483
30486
  } else {
30484
- await call2(`/organizations/${organizationId}`, { method: "PATCH", headers: json3, body: JSON.stringify({ name: current.organization.name, region: defaultChoice ?? current.organization.defaultRegion, allowedRegions }) });
30487
+ await call2(`/organizations/${organizationId}`, { method: "PATCH", headers: json4, body: JSON.stringify({ name: current.organization.name, region: defaultChoice ?? current.organization.defaultRegion, allowedRegions }) });
30485
30488
  }
30486
30489
  const { organization: _organization, workspace: _workspace, ...view } = await readLocations(call2, organizationId, workspaceId);
30487
30490
  return { value: view, text: "Locations saved.\n" + locationsText(view), exitCode: 0 };
@@ -30510,7 +30513,7 @@ async function setClouds(call2, organizationId, values, options, context2) {
30510
30513
  if (!context2.confirm) throw new OpsError(`Refusing to change hosting clouds without confirmation. Re-run with --yes to allow ${change}.`, "confirmation_required");
30511
30514
  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
30515
  }
30513
- const saved = await call2(path, { method: "PUT", headers: json3, body: JSON.stringify({ allowedClouds: chosen ? [...new Set(chosen.map((cloud) => cloud.id))] : null }) });
30516
+ const saved = await call2(path, { method: "PUT", headers: json4, body: JSON.stringify({ allowedClouds: chosen ? [...new Set(chosen.map((cloud) => cloud.id))] : null }) });
30514
30517
  return { value: saved, text: "Hosting clouds saved.\n" + cloudsText(saved), exitCode: 0 };
30515
30518
  }
30516
30519
  function scopedGrants(entries, scopeType, flag) {
@@ -30557,19 +30560,24 @@ function teamsText(snapshot) {
30557
30560
  ].join("\n");
30558
30561
  }).join("\n");
30559
30562
  }
30560
- async function teamCommand(call2, organizationId, sub, target, values, options, context2) {
30563
+ function changeConfirmation(options, context2) {
30564
+ return async (summary) => {
30565
+ if (options.yes) return;
30566
+ if (!context2.confirm) throw new OpsError(`Refusing to change team access without confirmation. Re-run with --yes to ${summary}.`, "confirmation_required");
30567
+ if (!await context2.confirm(summary[0].toUpperCase() + summary.slice(1) + "?")) throw new OpsError("Not confirmed. Nothing was changed.", "not_confirmed");
30568
+ };
30569
+ }
30570
+ async function teamCommand(call2, organizationId, positional, values, options, context2) {
30561
30571
  const root = `/organizations/${organizationId}`;
30572
+ const [sub, target] = positional;
30573
+ const confirm = changeConfirmation(options, context2);
30574
+ if (sub && !["list", "grant", "revoke"].includes(sub)) return teamPeopleCommand(call2, organizationId, sub, positional, values, confirm);
30562
30575
  const snapshot = await call2(`${root}/access`);
30563
30576
  if (!sub || sub === "list") return { value: snapshot.teams.map((team) => ({
30564
30577
  ...team,
30565
30578
  members: snapshot.teamMembers.filter((member) => member.teamId === team.id).map((member) => member.userId),
30566
30579
  roles: snapshot.assignments.filter((assignment) => assignment.subjectType === "team" && assignment.subjectId === team.id)
30567
30580
  })), text: teamsText(snapshot) };
30568
- const confirm = async (summary) => {
30569
- if (options.yes) return;
30570
- if (!context2.confirm) throw new OpsError(`Refusing to change team access without confirmation. Re-run with --yes to ${summary}.`, "confirmation_required");
30571
- if (!await context2.confirm(summary[0].toUpperCase() + summary.slice(1) + "?")) throw new OpsError("Not confirmed. Nothing was changed.", "not_confirmed");
30572
- };
30573
30581
  if (sub === "grant") {
30574
30582
  const team = snapshot.teams.find((value) => value.id === target || value.name.toLowerCase() === target?.toLowerCase());
30575
30583
  if (!team) throw new Error("Name the team by ID or name, e.g. backify teams grant Support --role Viewer --app <id>.");
@@ -30577,7 +30585,7 @@ async function teamCommand(call2, organizationId, sub, target, values, options,
30577
30585
  if (!role) throw new Error("Pass --role <role>, e.g. --role Developer.");
30578
30586
  const scope = accessScope(organizationId, values);
30579
30587
  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 }) });
30588
+ const assignment = await call2(`${root}/access/assignments`, { method: "POST", headers: json4, body: JSON.stringify({ subjectType: "team", subjectId: team.id, ...scope, role, expiresAt: null }) });
30581
30589
  return { value: assignment, text: `${role} granted to ${team.name} on ${scope.scopeType} ${scope.scopeId} (assignment ${assignment.id}).`, exitCode: 0 };
30582
30590
  }
30583
30591
  if (sub === "revoke") {
@@ -30588,7 +30596,128 @@ async function teamCommand(call2, organizationId, sub, target, values, options,
30588
30596
  await call2(`${root}/access/assignments/${grant.id}`, { method: "DELETE" });
30589
30597
  return { value: { revoked: grant.id }, text: `${grant.role} revoked from ${team?.name ?? "the team"}.`, exitCode: 0 };
30590
30598
  }
30591
- throw new Error("Use backify teams, backify teams grant <team> --role <role> [--workspace <id>|--app <id>], or backify teams revoke <assignment-id>.");
30599
+ throw new Error("Use backify teams, backify teams show|create|add|suggest|remove|join|requests|approve|decline|activity, backify teams grant <team> --role <role> [--workspace <id>|--app <id>], or backify teams revoke <assignment-id>.");
30600
+ }
30601
+ function teamDetailsText(team) {
30602
+ return [
30603
+ `${team.name} (${team.id})${team.myRole ? " \u2014 you are " + (team.myRole === "manager" ? "a manager" : "a member") : ""}`,
30604
+ `Members (${team.members.length}):`,
30605
+ ...team.members.length ? team.members.map((member) => ` ${member.displayName} <${member.email}>${member.role === "manager" ? " [manager]" : ""}${member.isSuspended ? " [suspended]" : ""}`) : [" none"],
30606
+ ...team.pending.length ? ["On their way in:", ...team.pending.map((person) => ` ${person.email}: ${person.status === "suggested" ? "suggested" + (person.requestedBy ? " by " + person.requestedBy : "") + ", waiting for a manager" + (person.requestId ? ` [request ${person.requestId}]` : "") : "invited, not joined yet"}`)] : [],
30607
+ `Owns (${team.applications.length + team.hiddenApplications}):`,
30608
+ ...team.applications.length ? team.applications.map((app) => ` ${app.name} (${app.workspaceName}, ${app.status}): members have Application owner`) : [" no applications you can see"],
30609
+ "Roles granted:",
30610
+ ...team.grants.length ? team.grants.map((grant) => ` ${grant.role} on ${grant.scopeType} ${grant.scopeId} [assignment ${grant.id}]`) : [" none"]
30611
+ ].join("\n");
30612
+ }
30613
+ function suggestionText(reply) {
30614
+ return reply.people.map((person) => `${person.email}: ${outcomeText[person.outcome] ?? person.outcome}${person.detail ? " (" + person.detail + ")" : ""}`).join("\n");
30615
+ }
30616
+ async function resolveTeam(call2, root, target, example) {
30617
+ const team = (await call2(`${root}/teams/summary`)).find((value) => value.id === target || value.name.toLowerCase() === target?.toLowerCase());
30618
+ if (!team) throw new Error(`Name the team by ID or name, e.g. ${example}.`);
30619
+ return team;
30620
+ }
30621
+ async function teamPeopleCommand(call2, organizationId, sub, positional, values, confirm) {
30622
+ const root = `/organizations/${organizationId}`;
30623
+ const [, target] = positional;
30624
+ switch (sub) {
30625
+ case "show": {
30626
+ const team = await resolveTeam(call2, root, target, "backify teams show Support");
30627
+ const details = await call2(`${root}/teams/${team.id}`);
30628
+ return { value: details, text: teamDetailsText(details) };
30629
+ }
30630
+ case "create": {
30631
+ const name2 = positional.slice(1).join(" ").trim();
30632
+ if (!name2) throw new Error("Name the team, e.g. backify teams create Payments.");
30633
+ await confirm(`create team ${name2}`);
30634
+ const created = await call2(`${root}/teams`, { method: "POST", headers: json4, body: JSON.stringify({ name: name2, description: values.description?.[0] ?? "" }) });
30635
+ return { value: created, text: `Team ${created.name} created (${created.id}). Add people with backify teams add "${created.name}" <email...>.`, exitCode: 0 };
30636
+ }
30637
+ case "add":
30638
+ case "suggest": {
30639
+ const team = await resolveTeam(call2, root, target, `backify teams ${sub} Support ada@example.com`);
30640
+ const emails = positional.slice(2);
30641
+ if (!emails.length || emails.some((email2) => !emailPattern.test(email2))) throw new Error(`Pass one or more email addresses, e.g. backify teams ${sub} ${team.name} ada@example.com.`);
30642
+ const [role] = values.role ?? [];
30643
+ if (role !== void 0 && !["member", "manager"].includes(role)) throw new Error("--role is member or manager.");
30644
+ await confirm(`${sub} ${emails.join(", ")} ${sub === "add" ? "to" : "for"} team ${team.name}`);
30645
+ const reply = await call2(`${root}/teams/${team.id}/requests`, { method: "POST", headers: json4, body: JSON.stringify({ emails, note: values.note?.[0] ?? null }) });
30646
+ const lines = [suggestionText(reply)];
30647
+ if (role === "manager") {
30648
+ const details = await call2(`${root}/teams/${team.id}`);
30649
+ for (const email2 of emails) {
30650
+ const member = details.members.find((value) => value.email.toLowerCase() === email2.toLowerCase());
30651
+ if (!member) {
30652
+ lines.push(`${email2}: not in the team yet, so not made a manager`);
30653
+ continue;
30654
+ }
30655
+ await call2(`${root}/teams/${team.id}/members/${member.userId}`, { method: "PUT", headers: json4, body: JSON.stringify({ role: "manager" }) });
30656
+ lines.push(`${email2}: now a manager of ${team.name}`);
30657
+ }
30658
+ }
30659
+ return { value: reply, text: lines.join("\n"), exitCode: reply.people.every((person) => person.outcome === "skipped") ? 1 : 0 };
30660
+ }
30661
+ case "remove": {
30662
+ const team = await resolveTeam(call2, root, target, "backify teams remove Support ada@example.com");
30663
+ const email2 = positional[2];
30664
+ const details = await call2(`${root}/teams/${team.id}`);
30665
+ const member = details.members.find((value) => value.email.toLowerCase() === email2?.toLowerCase());
30666
+ if (!member) throw new Error(`Pass the email of someone in ${team.name}; backify teams show ${team.name} lists them.`);
30667
+ await confirm(`remove ${member.displayName} from team ${team.name}; they lose the access the team gives`);
30668
+ await call2(`${root}/teams/${team.id}/members/${member.userId}`, { method: "DELETE" });
30669
+ return { value: { removed: member.userId }, text: `${member.displayName} removed from ${team.name}.`, exitCode: 0 };
30670
+ }
30671
+ case "join": {
30672
+ const team = await resolveTeam(call2, root, target, "backify teams join Support");
30673
+ const reply = await call2(`${root}/teams/${team.id}/requests`, { method: "POST", headers: json4, body: JSON.stringify({ join: true, note: values.note?.[0] ?? null }) });
30674
+ return { value: reply, text: suggestionText(reply), exitCode: reply.people.every((person) => person.outcome === "skipped") ? 1 : 0 };
30675
+ }
30676
+ case "requests": {
30677
+ const path = target ? `${root}/teams/${(await resolveTeam(call2, root, target, "backify teams requests Support")).id}/requests` : `${root}/team-requests`;
30678
+ const rows = await call2(path);
30679
+ return { value: rows, text: rows.length ? rows.map((row) => `${row.id} ${row.teamName} ${row.displayName ?? row.email} ${row.status} suggested by ${row.requestedBy}${row.note ? ": " + row.note : ""}${row.canDecide && row.status === "pending" ? " (you can approve)" : ""}`).join("\n") : "No team requests." };
30680
+ }
30681
+ case "approve":
30682
+ case "decline": {
30683
+ if (!target || !isUuid(target)) throw new Error("Pass the request ID; backify teams requests lists them.");
30684
+ await confirm(`${sub} team request ${target}`);
30685
+ const reply = await call2(`${root}/team-requests/${target}/${sub}`, { method: "POST" });
30686
+ return { value: reply, text: suggestionText({ people: [reply] }), exitCode: 0 };
30687
+ }
30688
+ case "activity": {
30689
+ const team = await resolveTeam(call2, root, target, "backify teams activity Support");
30690
+ const page = await call2(`${root}/teams/${team.id}/activity?pageSize=50`);
30691
+ return { value: page, text: page.items.length ? page.items.map((item) => `${item.createdAt} ${item.actorName ?? item.actor} ${item.action.toLowerCase().replace(/_/g, " ")} ${item.resourceId}`).join("\n") : `No recent activity on applications ${team.name} owns.` };
30692
+ }
30693
+ }
30694
+ throw new Error("Unknown teams command.");
30695
+ }
30696
+ async function appOwnerCommand(call2, organizationId, appId, values, confirm) {
30697
+ if (!appId || !isUuid(appId)) throw new Error("Pass the application ID: backify apps owner <app-id> [--user <email> | --team <team>].");
30698
+ const [email2] = values.user ?? [], [teamName] = values.team ?? [];
30699
+ if (email2 && teamName) throw new Error("Pass --user or --team, not both.");
30700
+ const ownership = await call2(`/apps/${appId}/ownership`);
30701
+ if (!email2 && !teamName) {
30702
+ const who = ownership.ownerTeam ? `team ${ownership.ownerTeam.displayName}` : ownership.owner?.displayName ?? "nobody";
30703
+ return { value: ownership, text: `Owner: ${who}.${ownership.canChangeOwner ? " Change it with --user <email> or --team <team>." : ""}` };
30704
+ }
30705
+ let body, name2;
30706
+ if (teamName) {
30707
+ const team = await resolveTeam(call2, `/organizations/${organizationId}`, teamName, "backify apps owner <app-id> --team Payments");
30708
+ body = { userId: null, teamId: team.id, version: ownership.version };
30709
+ name2 = "team " + team.name;
30710
+ } else {
30711
+ if (!emailPattern.test(email2)) throw new Error("--user takes an email address.");
30712
+ const people = await call2(`/organizations/${organizationId}/access/people?search=${encodeURIComponent(email2)}&pageSize=10`);
30713
+ const person = people.items.find((item) => item.email.toLowerCase() === email2.toLowerCase());
30714
+ if (!person) throw new Error(`${email2} is not a member of this organization.`);
30715
+ body = { userId: person.id, teamId: null, version: ownership.version };
30716
+ name2 = person.displayName;
30717
+ }
30718
+ await confirm(`make ${name2} the owner of application ${appId}; ${teamName ? "everyone in the team gets" : "they get"} Application owner there`);
30719
+ await call2(`/apps/${appId}/owner`, { method: "PUT", headers: json4, body: JSON.stringify(body) });
30720
+ return { value: body, text: `${name2[0].toUpperCase() + name2.slice(1)} now owns application ${appId}.`, exitCode: 0 };
30592
30721
  }
30593
30722
  function costsText(view) {
30594
30723
  const trend = view.change === null ? "no costs in the previous " + view.days + " days" : `${view.change >= 0 ? "up" : "down"} ${Math.abs(Math.round(view.change * 100))}% from the previous ${view.days} days (${usd(view.previousTotal)})`;
@@ -30690,7 +30819,19 @@ async function runTaskCommand(command2, args2, context2) {
30690
30819
  case "teams list":
30691
30820
  case "teams grant":
30692
30821
  case "teams revoke":
30693
- return { result: await teamCommand(call2, organizationId, sub, target, values, options, context2), json: options.json };
30822
+ case "teams show":
30823
+ case "teams create":
30824
+ case "teams add":
30825
+ case "teams suggest":
30826
+ case "teams remove":
30827
+ case "teams join":
30828
+ case "teams requests":
30829
+ case "teams approve":
30830
+ case "teams decline":
30831
+ case "teams activity":
30832
+ return { result: await teamCommand(call2, organizationId, positional, values, options, context2), json: options.json };
30833
+ case "apps owner":
30834
+ return { result: await appOwnerCommand(call2, organizationId, target, values, changeConfirmation(options, context2)), json: options.json };
30694
30835
  case "costs": {
30695
30836
  const [days] = values.days ?? [], [groupBy] = values.by ?? [], [workspaceId] = values.workspace ?? [], [applicationId] = values.app ?? [], [ownerId] = values.owner ?? [];
30696
30837
  if (days !== void 0 && !/^\d{1,3}$/.test(days)) throw new Error("--days takes a number of days from 1 to 366.");
@@ -30783,7 +30924,7 @@ async function runTaskCommand(command2, args2, context2) {
30783
30924
  throw new Error("Unknown command.\n\n" + taskHelp);
30784
30925
  }
30785
30926
  }
30786
- var taskHelp, purposes, upgradeEnded, upgradeInProgress, json3, workspaceOption, connection, usd, percent;
30927
+ var taskHelp, purposes, upgradeEnded, upgradeInProgress, json4, workspaceOption, connection, emailPattern, outcomeText, usd, percent;
30787
30928
  var init_tasks = __esm({
30788
30929
  "src/tasks.ts"() {
30789
30930
  "use strict";
@@ -30828,6 +30969,18 @@ var init_tasks = __esm({
30828
30969
  " backify teams Teams, their members and the roles they grant",
30829
30970
  " backify teams grant <team> --role <role> [--workspace <id>|--app <id>] [--yes]",
30830
30971
  " backify teams revoke <assignment-id> [--yes] Grant or revoke a team role on the organization, a workspace or an application",
30972
+ " backify teams show <team> Members and managers, people on their way in, owned applications and roles",
30973
+ " backify teams create <name> [--description <text>] [--yes]",
30974
+ " backify teams add <team> <email...> [--role manager] [--yes] Add people (managers); people not in the organization yet are invited",
30975
+ " backify teams suggest <team> <email...> [--note <text>] [--yes]",
30976
+ " Suggest people; a team manager approves",
30977
+ " backify teams join <team> [--note <text>] Ask to join a team",
30978
+ " backify teams remove <team> <email> [--yes] Remove someone from a team",
30979
+ " backify teams requests [<team>] Suggestions waiting for you, or one team's",
30980
+ " backify teams approve|decline <request-id> [--yes] Decide a suggestion",
30981
+ " backify teams activity <team> Recent work by the team on the applications it owns",
30982
+ " backify apps owner <app-id> [--user <email>|--team <team>] [--yes]",
30983
+ " Show or change who owns an application: a person or a team",
30831
30984
  ...orgProtectionUsage,
30832
30985
  ...orgPatchesUsage,
30833
30986
  ...orgUpdatesUsage,
@@ -30888,7 +31041,7 @@ var init_tasks = __esm({
30888
31041
  };
30889
31042
  upgradeEnded = (upgrade) => ["committed", "rolled-back", "failed"].includes(upgrade.phase);
30890
31043
  upgradeInProgress = (upgrade) => !!upgrade && !upgradeEnded(upgrade) && upgrade.state !== "awaiting-approval";
30891
- json3 = { "content-type": "application/json" };
31044
+ json4 = { "content-type": "application/json" };
30892
31045
  workspaceOption = (values) => {
30893
31046
  const id = values.workspace?.[0];
30894
31047
  if (id !== void 0 && !isUuid(id)) throw new Error("--workspace takes a workspace ID (UUID).");
@@ -30899,6 +31052,15 @@ var init_tasks = __esm({
30899
31052
  if (!id || !isUuid(id)) throw new Error("Pass --connection <cloud-connection-id>.");
30900
31053
  return id;
30901
31054
  };
31055
+ emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
31056
+ outcomeText = {
31057
+ requested: "suggested, waiting for a team manager",
31058
+ added: "added to the team",
31059
+ invited: "invited to the organization; joins the team on accepting",
31060
+ invitation_updated: "team added to their pending invitation",
31061
+ declined: "declined",
31062
+ skipped: "skipped"
31063
+ };
30902
31064
  usd = (amount) => "$" + amount.toFixed(2);
30903
31065
  percent = (value) => value === null ? "new" : (value >= 0 ? "+" : "") + Math.round(value * 100) + "%";
30904
31066
  }
@@ -30915,7 +31077,7 @@ async function runSsoCommand(args2, context2) {
30915
31077
  const secretOnStdin = args2.includes("--client-secret-stdin");
30916
31078
  const { options, positional, values } = taskArguments(args2.filter((arg) => arg !== "--client-secret-stdin"));
30917
31079
  const { call: call2, organizationId } = await organizationCall(context2, options.organizationId);
30918
- const base = `/organizations/${organizationId}/sso`;
31080
+ const base2 = `/organizations/${organizationId}/sso`;
30919
31081
  const value = (name2) => values[name2]?.at(-1);
30920
31082
  const id = (index, what) => {
30921
31083
  const raw = positional[index];
@@ -30927,9 +31089,9 @@ async function runSsoCommand(args2, context2) {
30927
31089
  if (!context2.confirm) throw new OpsError("Pass --yes to confirm when no terminal can ask: " + message, "confirmation_required");
30928
31090
  if (!await context2.confirm(message)) throw new OpsError("Not confirmed. Nothing changed.", "not_confirmed");
30929
31091
  };
30930
- const overview = async () => (await call2(base)).overview;
31092
+ const overview = async () => (await call2(base2)).overview;
30931
31093
  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) });
31094
+ const send2 = (path, method, body) => call2(base2 + path, { method, headers: json5, body: body === void 0 ? void 0 : JSON.stringify(body) });
30933
31095
  const [area, action] = positional;
30934
31096
  switch (`${area ?? ""} ${["connections", "domains", "mappings", "scim"].includes(area ?? "") ? action ?? "" : ""}`.trim()) {
30935
31097
  case "": {
@@ -31021,7 +31183,7 @@ async function runSsoCommand(args2, context2) {
31021
31183
  return done(connection2, "Metadata refreshed.\n" + connectionLine(connection2));
31022
31184
  }
31023
31185
  case "sign-ins": {
31024
- const attempts = await call2(`${base}/connections/${id(1, "connection")}/sign-ins`);
31186
+ const attempts = await call2(`${base2}/connections/${id(1, "connection")}/sign-ins`);
31025
31187
  return done(attempts, attempts.length ? attempts.map((attempt) => [
31026
31188
  `${attempt.at} ${attempt.succeeded ? "ok" : "FAILED"}${attempt.isTest ? " (test)" : ""} ${attempt.email ?? ""} ${attempt.code ?? ""}`,
31027
31189
  attempt.diagnostic ? " " + attempt.diagnostic : "",
@@ -31055,7 +31217,7 @@ async function runSsoCommand(args2, context2) {
31055
31217
  }
31056
31218
  case "require": {
31057
31219
  const domainId = id(1, "domain");
31058
- const preview = await call2(`${base}/domains/${domainId}/enforcement-preview`);
31220
+ const preview = await call2(`${base2}/domains/${domainId}/enforcement-preview`);
31059
31221
  const impact = `${preview.affected} members use @${preview.domain}: ${preview.alreadyUsingSso} already use single sign-on, ${preview.needToSwitch} must switch on their next sign-in, ${preview.exempt} break-glass owners are exempt.`;
31060
31222
  if (!preview.ready) throw new OpsError("Single sign-on can't be required yet. " + preview.blockers.join(" "), "sso_not_ready", { preview });
31061
31223
  await confirm(`Require single sign-on for ${preview.domain} through ${preview.connectionName}? ${impact}`);
@@ -31131,7 +31293,7 @@ function connectionLine(connection2) {
31131
31293
  function domainLine(domain) {
31132
31294
  return `${domain.id} ${domain.domain} ${domain.ssoRequired ? "SSO required" : domain.verifiedAt ? "verified" : `waiting for DNS (TXT ${domain.record} = ${domain.value})`}`;
31133
31295
  }
31134
- var ssoHelp, json4;
31296
+ var ssoHelp, json5;
31135
31297
  var init_sso = __esm({
31136
31298
  "src/sso.ts"() {
31137
31299
  "use strict";
@@ -31163,7 +31325,7 @@ var init_sso = __esm({
31163
31325
  "Options: --organization <id> --json",
31164
31326
  "Client secrets and SCIM tokens are never printed except a new SCIM token, once. Pass secrets on standard input, never as arguments."
31165
31327
  ].join("\n");
31166
- json4 = { "content-type": "application/json" };
31328
+ json5 = { "content-type": "application/json" };
31167
31329
  }
31168
31330
  });
31169
31331
 
@@ -31311,12 +31473,12 @@ __export(auth_identity_exports, {
31311
31473
  function authIdentityArguments(args2) {
31312
31474
  if (args2.includes("--help") || args2.includes("-h")) return "help";
31313
31475
  const { flags, values, positional } = parse(args2, "auth identity", ["--json"], ["--app", "--environment", "--confirm"]);
31314
- const action = (positional[0] ?? "status").toLowerCase(), json6 = flags.has("--json");
31476
+ const action = (positional[0] ?? "status").toLowerCase(), json7 = flags.has("--json");
31315
31477
  if (!["status", "move", "move-back", "clear"].includes(action) || positional.length > 1) throw new Error("Unknown auth identity command: " + positional.join(" ") + "\n\n" + authIdentityHelp);
31316
31478
  if (action === "status" && (values["--environment"] !== void 0 || values["--confirm"] !== void 0)) throw new Error("--environment and --confirm apply to auth identity move.");
31317
31479
  if (action === "clear" && values["--confirm"] !== void 0) throw new Error("--confirm applies to auth identity move and move-back.");
31318
31480
  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 };
31481
+ return { action, ...values["--environment"] !== void 0 ? { environment: values["--environment"] } : {}, ...values["--confirm"] !== void 0 ? { confirm: values["--confirm"] } : {}, json: json7 };
31320
31482
  }
31321
31483
  function pad3(rows) {
31322
31484
  const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
@@ -31356,15 +31518,15 @@ function resolveEnvironment(input, environments, statuses) {
31356
31518
  }
31357
31519
  async function runAuthIdentity(call2, applicationId, options) {
31358
31520
  if (!uuid10.test(applicationId)) throw new Error("Use a valid application ID.");
31359
- const prefix = "/apps/" + applicationId, base = prefix + "/auth/identity";
31360
- const statuses = await call2(base);
31521
+ const prefix = "/apps/" + applicationId, base2 = prefix + "/auth/identity";
31522
+ const statuses = await call2(base2);
31361
31523
  const environments = await call2(prefix + "/environments").catch(() => []);
31362
31524
  const names = new Map(environments.map((value) => [value.id, value.name]));
31363
31525
  if (options.action === "status") return { value: statuses, text: identityStatusText(statuses, names) };
31364
31526
  const target = resolveEnvironment(options.environment, environments, statuses), label = names.get(target.environmentId) ?? target.kind;
31365
31527
  if (target.authority === "relocating" || target.authority === "returning") throw new CommandError("Sign-in data for " + label + " is already being moved.", "identity_relocation_in_progress", { environmentId: target.environmentId });
31366
31528
  if (options.action === "clear") {
31367
- const relocation2 = await call2(base + "/clear", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ environmentId: target.environmentId }) });
31529
+ const relocation2 = await call2(base2 + "/clear", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ environmentId: target.environmentId }) });
31368
31530
  return {
31369
31531
  value: { status: relocation2.clearedAt ? "cleared" : "clearing", environmentId: target.environmentId, relocation: relocation2 },
31370
31532
  text: relocation2.clearedAt ? "What the failed move left in " + label + "'s database is already cleared." : "Clearing what the failed move left in " + label + "'s database. Sign-in for " + label + " stays with Backify.\nCheck progress with: backify auth identity"
@@ -31377,7 +31539,7 @@ async function runAuthIdentity(call2, applicationId, options) {
31377
31539
  const summary = "Moving sign-in data for " + label + " back to Backify pauses sign-in for that environment and user management for the application while the data is moved. Users, roles, passkeys and signed-in sessions are kept. Afterwards, sign-in for " + label + " stops working while Backify is unavailable.";
31378
31540
  throw new CommandError((options.confirm ? "The confirmation does not match the application slug. " : "") + summary + "\nConfirm with the application slug: backify auth identity move-back --environment " + options.environment + " --confirm " + (slug2 ?? "<application-slug>"), options.confirm ? "confirmation_mismatch" : "confirmation_required", slug2 ? { confirm: slug2 } : {});
31379
31541
  }
31380
- const relocation2 = await call2(base + "/move-back", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ environmentId: target.environmentId }) });
31542
+ const relocation2 = await call2(base2 + "/move-back", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ environmentId: target.environmentId }) });
31381
31543
  return { value: { status: "moving-back", environmentId: target.environmentId, relocation: relocation2 }, text: ["Moving sign-in data for " + label + " back to Backify.", "Sign-in for this environment and user management for the application are paused until it finishes, usually within a minute.", "Check progress with: backify auth identity"].join("\n") };
31382
31544
  }
31383
31545
  if (target.authority === "relocating") throw new CommandError("Sign-in data for " + label + " is already being moved.", "identity_relocation_in_progress", { environmentId: target.environmentId });
@@ -31387,7 +31549,7 @@ async function runAuthIdentity(call2, applicationId, options) {
31387
31549
  const summary = "Moving sign-in data for " + label + " pauses sign-in for that environment and user management for the application while the data is moved. It can be moved back later with backify auth identity move-back. Afterwards, sign-in for " + label + " keeps working if Backify is unavailable.";
31388
31550
  throw new CommandError((options.confirm ? "The confirmation does not match the application slug. " : "") + summary + "\nConfirm with the application slug: backify auth identity move --environment " + options.environment + " --confirm " + (slug ?? "<application-slug>"), options.confirm ? "confirmation_mismatch" : "confirmation_required", slug ? { confirm: slug } : {});
31389
31551
  }
31390
- const relocation = await call2(base + "/relocate", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ environmentId: target.environmentId }) });
31552
+ const relocation = await call2(base2 + "/relocate", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ environmentId: target.environmentId }) });
31391
31553
  return { value: { status: "moving", environmentId: target.environmentId, relocation }, text: ["Moving sign-in data for " + label + ": " + relocation.users + " users, " + relocation.links + " linked identities, " + relocation.passkeys + " passkeys, " + relocation.sessions + " sessions.", "Sign-in for this environment and user management for the application are paused until it finishes, usually within a minute.", "Check progress with: backify auth identity"].join("\n") };
31392
31554
  }
31393
31555
  var authIdentityHelp, uuid10, where, identityFailureText;
@@ -31796,10 +31958,10 @@ function exportReference(name2) {
31796
31958
  const capability2 = sdkCapability(name2);
31797
31959
  return capability2 ? { kind: "capability", capability: capability2 } : void 0;
31798
31960
  }
31799
- function memberReference(base, name2) {
31800
- if (base?.kind === "namespace")
31801
- return exportReference(base.member(name2));
31802
- if (base?.kind === "root") {
31961
+ function memberReference(base2, name2) {
31962
+ if (base2?.kind === "namespace")
31963
+ return exportReference(base2.member(name2));
31964
+ if (base2?.kind === "root") {
31803
31965
  const capability2 = sdkCapability(name2);
31804
31966
  return capability2 ? { kind: "capability", capability: capability2 } : void 0;
31805
31967
  }
@@ -31906,15 +32068,15 @@ function analyzeFile(file, used, diagnostics, wrappers) {
31906
32068
  report({ severity: "error", code: "retired-sdk-import", docs: "https://docs.backify.dev/sdk", message: "This SDK entrypoint was removed. Use @backifydev/sdk/app in server code and fetch application APIs from browsers." }, statement);
31907
32069
  if (module === "@backifydev/sdk/app")
31908
32070
  serverOnly = true;
31909
- const base = moduleReference(module), clause = statement.importClause;
31910
- if (!base || !clause || clause.isTypeOnly || !clause.namedBindings)
32071
+ const base2 = moduleReference(module), clause = statement.importClause;
32072
+ if (!base2 || !clause || clause.isTypeOnly || !clause.namedBindings)
31911
32073
  continue;
31912
32074
  if (ts3.isNamespaceImport(clause.namedBindings))
31913
- bind(clause.namedBindings.name, base);
32075
+ bind(clause.namedBindings.name, base2);
31914
32076
  else
31915
32077
  for (const element of clause.namedBindings.elements)
31916
32078
  if (!element.isTypeOnly)
31917
- bind(element.name, memberReference(base, (element.propertyName ?? element.name).text));
32079
+ bind(element.name, memberReference(base2, (element.propertyName ?? element.name).text));
31918
32080
  }
31919
32081
  const resolve10 = (node2) => {
31920
32082
  if (ts3.isParenthesizedExpression(node2) || ts3.isAsExpression(node2) || ts3.isNonNullExpression(node2) || ts3.isAwaitExpression(node2) || ts3.isSatisfiesExpression(node2))
@@ -31941,16 +32103,16 @@ function analyzeFile(file, used, diagnostics, wrappers) {
31941
32103
  };
31942
32104
  const collect = (node2) => {
31943
32105
  if (ts3.isVariableDeclaration(node2) && node2.initializer) {
31944
- const base = resolve10(node2.initializer);
31945
- if (base && ts3.isIdentifier(node2.name))
31946
- bind(node2.name, base);
31947
- else if (base && ts3.isObjectBindingPattern(node2.name))
32106
+ const base2 = resolve10(node2.initializer);
32107
+ if (base2 && ts3.isIdentifier(node2.name))
32108
+ bind(node2.name, base2);
32109
+ else if (base2 && ts3.isObjectBindingPattern(node2.name))
31948
32110
  for (const element of node2.name.elements) {
31949
32111
  if (element.dotDotDotToken || !ts3.isIdentifier(element.name))
31950
32112
  continue;
31951
32113
  const property3 = element.propertyName ?? element.name;
31952
32114
  if (ts3.isIdentifier(property3) || ts3.isStringLiteral(property3))
31953
- bind(element.name, memberReference(base, property3.text));
32115
+ bind(element.name, memberReference(base2, property3.text));
31954
32116
  }
31955
32117
  }
31956
32118
  ts3.forEachChild(node2, collect);
@@ -32297,7 +32459,7 @@ function readBody(req, limit = 300 * 1024 * 1024) {
32297
32459
  req.on("error", reject);
32298
32460
  });
32299
32461
  }
32300
- function json5(res, status, body) {
32462
+ function json6(res, status, body) {
32301
32463
  res.writeHead(status, { "content-type": "application/json" });
32302
32464
  res.end(JSON.stringify(body));
32303
32465
  }
@@ -32336,9 +32498,9 @@ function startGateway(options) {
32336
32498
  const storageCredential = sealed({ kind: "storage" });
32337
32499
  const buckets = new Map((config2.storage?.buckets ?? []).map((b) => [b.name, b]));
32338
32500
  const objectPath = (bucket, key) => {
32339
- const base = resolve7(storageDir, bucket);
32340
- const path = resolve7(base, ...key.split("/"));
32341
- if (!buckets.has(bucket) || !path.startsWith(base + sep)) throw new InvalidKey();
32501
+ const base2 = resolve7(storageDir, bucket);
32502
+ const path = resolve7(base2, ...key.split("/"));
32503
+ if (!buckets.has(bucket) || !path.startsWith(base2 + sep)) throw new InvalidKey();
32342
32504
  return path;
32343
32505
  };
32344
32506
  const cookie = (req, name2) => req.headers.cookie?.split(/;\s*/).map((p) => p.split("=")).find(([k]) => k === name2)?.[1];
@@ -32387,21 +32549,21 @@ function startGateway(options) {
32387
32549
  if (url2.pathname.startsWith("/signed/")) return await signed(req, res, url2);
32388
32550
  if (url2.pathname.startsWith("/files/")) {
32389
32551
  const [, , bucket, ...rest] = url2.pathname.split("/");
32390
- if (!buckets.get(bucket)?.public) return json5(res, 404, { error: { code: "not_found", message: "Not found" } });
32552
+ if (!buckets.get(bucket)?.public) return json6(res, 404, { error: { code: "not_found", message: "Not found" } });
32391
32553
  return sendFile(res, objectPath(bucket, rest.map(decodeURIComponent).join("/")));
32392
32554
  }
32393
32555
  const apiPrefix = config2.kind === "api" ? "/" : "/api";
32394
32556
  if (config2.kind !== "web" || !options.frontendPort || url2.pathname === apiPrefix || url2.pathname.startsWith(apiPrefix === "/" ? "/" : apiPrefix + "/") || url2.pathname === (config2.server?.health ?? "/healthz")) {
32395
32557
  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" } });
32558
+ if (!port) return json6(res, 503, { error: { code: "starting", message: "The backend is starting or failed to start; see the terminal" } });
32397
32559
  const user = sessionUser(req);
32398
32560
  if (user) req.headers["x-backify-user"] = options.identity.signUser(user);
32399
32561
  return proxy(req, res, port);
32400
32562
  }
32401
32563
  return proxy(req, res, options.frontendPort);
32402
32564
  } 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 } });
32565
+ if (error2 instanceof InvalidKey) return json6(res, 400, { error: { code: "invalid_key", message: error2.message } });
32566
+ if (!res.headersSent) json6(res, 500, { error: { code: "gateway_error", message: error2.message } });
32405
32567
  }
32406
32568
  });
32407
32569
  server.on("upgrade", (req, socket, head) => {
@@ -32421,12 +32583,12 @@ function startGateway(options) {
32421
32583
  response.pipe(res);
32422
32584
  });
32423
32585
  upstream.on("error", () => {
32424
- if (!res.headersSent) json5(res, 502, { error: { code: "bad_gateway", message: `Nothing is listening on port ${port} yet` } });
32586
+ if (!res.headersSent) json6(res, 502, { error: { code: "bad_gateway", message: `Nothing is listening on port ${port} yet` } });
32425
32587
  });
32426
32588
  req.pipe(upstream);
32427
32589
  }
32428
32590
  function sendFile(res, path, contentType2) {
32429
- if (!existsSync16(path) || !statSync2(path).isFile()) return json5(res, 404, { error: { code: "not_found", message: "Not found" } });
32591
+ if (!existsSync16(path) || !statSync2(path).isFile()) return json6(res, 404, { error: { code: "not_found", message: "Not found" } });
32430
32592
  const meta2 = existsSync16(path + ".meta.json") ? JSON.parse(readFileSync22(path + ".meta.json", "utf8")) : {};
32431
32593
  res.writeHead(200, { "content-type": contentType2 ?? meta2.contentType ?? "application/octet-stream" });
32432
32594
  createReadStream(path).pipe(res);
@@ -32436,7 +32598,7 @@ function startGateway(options) {
32436
32598
  const returnTo = url2.searchParams.get("returnTo")?.startsWith("/") ? url2.searchParams.get("returnTo") : "/";
32437
32599
  if (action === "me") {
32438
32600
  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" } });
32601
+ 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
32602
  }
32441
32603
  if (action === "signout") {
32442
32604
  res.writeHead(302, { location: "/", "set-cookie": `${SESSION}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0` });
@@ -32445,7 +32607,7 @@ function startGateway(options) {
32445
32607
  if (action === "login" && req.method === "POST") {
32446
32608
  const form = new URLSearchParams((await readBody(req, 64 * 1024)).toString());
32447
32609
  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" } });
32610
+ if (!/^[^@\s]+@[^@\s]+$/.test(email2)) return json6(res, 400, { error: { code: "invalid_email", message: "Enter an email address" } });
32449
32611
  const list = (name2) => (form.get(name2) ?? "").split(",").map((s) => s.trim()).filter(Boolean);
32450
32612
  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
32613
  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 +32626,7 @@ function startGateway(options) {
32464
32626
  <p><label>Permissions (comma separated)<br><input name="permissions" style="width:100%"></label></p>
32465
32627
  <button>Sign in</button></form></body>`);
32466
32628
  }
32467
- return json5(res, 404, { error: { code: "not_found", message: "Unknown auth endpoint" } });
32629
+ return json6(res, 404, { error: { code: "not_found", message: "Unknown auth endpoint" } });
32468
32630
  }
32469
32631
  async function broker(req, res, url2) {
32470
32632
  if (req.headers.authorization !== "Bearer " + options.workloadToken) return brokerError(res, 401, "unauthorized", "Invalid workload token");
@@ -32474,7 +32636,7 @@ function startGateway(options) {
32474
32636
  if (!config2.protection?.dynamicRules) return brokerError(res, 403, "protection_scope_required", "Declare protection.dynamicRules in backify.config.ts.");
32475
32637
  const now = Date.now();
32476
32638
  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()]);
32639
+ if (path.endsWith("/list")) return json6(res, 200, [...dynamicRules.values()]);
32478
32640
  const ip = typeof body.ip === "string" ? body.ip : "";
32479
32641
  if (!parseCidr(ip)) return brokerError(res, 400, "invalid_ip", "Use an IPv4 or IPv6 IP or CIDR range.");
32480
32642
  if (path.endsWith("/remove")) {
@@ -32483,43 +32645,43 @@ function startGateway(options) {
32483
32645
  dynamicRules.delete(key2);
32484
32646
  removed++;
32485
32647
  }
32486
- return json5(res, 200, { removed });
32648
+ return json6(res, 200, { removed });
32487
32649
  }
32488
32650
  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
32651
  const key = body.action + "|" + ip;
32490
32652
  if (!dynamicRules.has(key) && dynamicRules.size >= 1e4) return brokerError(res, 409, "protection_rule_limit", "At most 10,000 active rules.");
32491
32653
  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
32654
  dynamicRules.set(key, rule);
32493
- return json5(res, 200, rule);
32655
+ return json6(res, 200, rule);
32494
32656
  }
32495
- if (path === "/v1/token/renew") return json5(res, 200, { token: options.workloadToken, expiresAt: new Date(Date.now() + 864e5).toISOString() });
32657
+ if (path === "/v1/token/renew") return json6(res, 200, { token: options.workloadToken, expiresAt: new Date(Date.now() + 864e5).toISOString() });
32496
32658
  if (path === "/v1/storage/credentials" || path === "/v1/storage/sign") {
32497
32659
  const bucket = String(body.bucket);
32498
32660
  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() });
32661
+ 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
32662
  const expires = Date.now() + Number(body.expiresInSeconds ?? 300) * 1e3;
32501
32663
  objectPath(bucket, String(body.key));
32502
32664
  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() });
32665
+ 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
32666
  }
32505
32667
  if (path === "/v1/mail/send") {
32506
32668
  const id = "mail_" + randomBytes4(6).toString("hex");
32507
32669
  writeFileSync13(join19(mailDir, id + ".json"), JSON.stringify(body, null, 2));
32508
32670
  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" });
32671
+ return json6(res, 200, { id, status: "sent", from: "noreply@localhost" });
32510
32672
  }
32511
32673
  if (path === "/v1/http/fetch") {
32512
32674
  const target = new URL(String(body.url));
32513
32675
  if (target.protocol !== "https:") return brokerError(res, 403, "https_required", `Outbound HTTP to ${target.hostname} must use https`);
32514
32676
  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" });
32677
+ const bytes2 = Buffer.from(await response.arrayBuffer());
32678
+ return json6(res, 200, { status: response.status, headers: Object.fromEntries(response.headers), body: bytes2.toString("base64"), encoding: "base64" });
32517
32679
  }
32518
32680
  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
32681
  return brokerError(res, 404, "not_found", "Unknown broker endpoint " + path);
32520
32682
  }
32521
32683
  async function storage(req, res, url2) {
32522
- if (req.headers.authorization !== "Bearer " + storageCredential) return json5(res, 403, {});
32684
+ if (req.headers.authorization !== "Bearer " + storageCredential) return json6(res, 403, {});
32523
32685
  const rest = url2.pathname.slice("/storage/local".length);
32524
32686
  if (rest === "" || rest === "/") {
32525
32687
  const prefix = url2.searchParams.get("prefix") ?? "";
@@ -32532,7 +32694,7 @@ function startGateway(options) {
32532
32694
  }
32533
32695
  };
32534
32696
  walk2(storageDir);
32535
- return json5(res, 200, { keys: files.filter((f) => f.startsWith(prefix)).sort() });
32697
+ return json6(res, 200, { keys: files.filter((f) => f.startsWith(prefix)).sort() });
32536
32698
  }
32537
32699
  const [bucket, ...key] = rest.slice(1).split("/").map(decodeURIComponent);
32538
32700
  const path = objectPath(bucket, key.join("/"));
@@ -32553,7 +32715,7 @@ function startGateway(options) {
32553
32715
  }
32554
32716
  async function signed(req, res, url2) {
32555
32717
  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" } });
32718
+ if (!grant || grant.kind !== "signed") return json6(res, 403, { error: { code: "expired", message: "The signed URL is invalid or expired" } });
32557
32719
  const path = objectPath(grant.bucket, grant.key);
32558
32720
  if (grant.operation === "upload" && req.method === "PUT") {
32559
32721
  mkdirSync6(dirname7(path), { recursive: true });
@@ -32563,7 +32725,7 @@ function startGateway(options) {
32563
32725
  return res.end();
32564
32726
  }
32565
32727
  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" } });
32728
+ return json6(res, 405, { error: { code: "method_not_allowed", message: "Wrong method for this signed URL" } });
32567
32729
  }
32568
32730
  return new Promise((resolveServer, reject) => {
32569
32731
  server.once("error", reject);
@@ -32582,7 +32744,7 @@ var init_local_gateway = __esm({
32582
32744
  super("Invalid object key");
32583
32745
  }
32584
32746
  };
32585
- brokerError = (res, status, code, message) => json5(res, status, { error: { code, message, requestId: randomBytes4(6).toString("hex") } });
32747
+ brokerError = (res, status, code, message) => json6(res, status, { error: { code, message, requestId: randomBytes4(6).toString("hex") } });
32586
32748
  }
32587
32749
  });
32588
32750
 
@@ -32884,7 +33046,7 @@ function extractSettings(args2) {
32884
33046
  }
32885
33047
  return { rest, settings };
32886
33048
  }
32887
- function replacementsArguments(positional, flags, values, settings, json6, yes) {
33049
+ function replacementsArguments(positional, flags, values, settings, json7, yes) {
32888
33050
  const sub = (positional[1] ?? "list").toLowerCase();
32889
33051
  if (!["list", "add", "verify", "remove"].includes(sub)) throw new Error("Unknown replacements command: " + positional.slice(1).join(" ") + "\n\n" + handoffHelp);
32890
33052
  const takesId = sub === "verify" || sub === "remove";
@@ -32893,7 +33055,7 @@ function replacementsArguments(positional, flags, values, settings, json6, yes)
32893
33055
  if (values["--confirm"] !== void 0 || values["--out"] !== void 0) throw new Error("--confirm and --out do not apply to handoff replacements.");
32894
33056
  if (sub !== "add" && (addOnlyFlags.some((name2) => values[name2] !== void 0) || Object.keys(settings).length > 0 || flags.has("--consent"))) throw new Error(addOnlyMessage);
32895
33057
  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 } };
33058
+ if (sub !== "add") return { action: "replacements", yes, json: json7, replacement: { action: sub, ...takesId ? { id: positional[2] } : {}, settings: {}, consent: false } };
32897
33059
  const kind2 = values["--kind"]?.toLowerCase(), secretName = values["--secret-name"];
32898
33060
  if (!values["--environment"]) throw new Error("Name the environment with --environment <name|id|kind>.");
32899
33061
  if (!kind2 || !replacementKinds.includes(kind2)) throw new Error("Choose what you are replacing with --kind " + replacementKinds.join(", ") + ".");
@@ -32901,22 +33063,22 @@ function replacementsArguments(positional, flags, values, settings, json6, yes)
32901
33063
  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
33064
  const subject = values["--subject"] ?? (kind2 === "mail" || kind2 === "ai" ? kind2 : void 0);
32903
33065
  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") } };
33066
+ return { action: "replacements", yes, json: json7, replacement: { action: "add", environment: values["--environment"], kind: kind2, subject, settings, secretName, consent: flags.has("--consent") } };
32905
33067
  }
32906
33068
  function handoffArguments(args2) {
32907
33069
  if (args2.includes("--help") || args2.includes("-h")) return "help";
32908
33070
  const { rest, settings } = extractSettings(args2);
32909
33071
  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");
33072
+ const action = (positional[0] ?? "status").toLowerCase(), json7 = flags.has("--json"), yes = flags.has("--yes");
32911
33073
  const azureSessionId = values["--azure-session"];
32912
33074
  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);
33075
+ if (action === "replacements") return replacementsArguments(positional, flags, values, settings, json7, yes);
32914
33076
  if (Object.keys(settings).length || flags.has("--consent") || addOnlyFlags.some((name2) => values[name2] !== void 0)) throw new Error(addOnlyMessage);
32915
33077
  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
33078
  if (values["--confirm"] !== void 0 && action !== "request") throw new Error("--confirm applies to handoff request.");
32917
33079
  if (values["--out"] !== void 0 && action !== "package" && action !== "foundation") throw new Error("--out applies to handoff foundation and handoff package.");
32918
33080
  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 };
33081
+ return { action, ...values["--confirm"] !== void 0 ? { confirm: values["--confirm"] } : {}, ...values["--out"] !== void 0 ? { out: values["--out"] } : {}, ...azureSessionId !== void 0 ? { azureSessionId } : {}, yes, json: json7 };
32920
33082
  }
32921
33083
  function pad4(rows) {
32922
33084
  const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
@@ -33034,17 +33196,17 @@ function replacementSettings(settings) {
33034
33196
  return result;
33035
33197
  }
33036
33198
  async function runReplacements(call2, prefix, options, context2) {
33037
- const replacement = options.replacement, base = prefix + "/replacements";
33199
+ const replacement = options.replacement, base2 = prefix + "/replacements";
33038
33200
  if (replacement.action === "add") {
33039
33201
  const { kind: kind2, subject, secretName, environment: named } = replacement;
33040
33202
  if (!replacement.consent) throw new CommandError(consentSummary(kind2, subject, named, secretName) + "\nNothing was changed. Add --consent to record it.", "consent_required", { kind: kind2, subject, secretName });
33041
33203
  const status = await call2(prefix), environmentId = resolveReplacementEnvironment(named, status.inventory?.environments);
33042
- const created = await call2(base, { method: "POST", body: JSON.stringify({ environmentId, kind: kind2, subject, settings: replacementSettings(replacement.settings), secretReference: secretName, consent: true }) });
33204
+ const created = await call2(base2, { method: "POST", body: JSON.stringify({ environmentId, kind: kind2, subject, settings: replacementSettings(replacement.settings), secretReference: secretName, consent: true }) });
33043
33205
  return { value: { status: "recorded", replacement: created }, text: ["Replacement recorded for " + subjectText(created) + " in " + named + ".", "Your environment is checking it: " + replacementState(created) + ". Run backify handoff replacements to see the result, or backify handoff replacements verify " + created.id + " to check again."].join("\n") };
33044
33206
  }
33045
33207
  if (replacement.action === "verify") {
33046
33208
  if (!uuid12.test(replacement.id)) throw new Error("Use a valid replacement ID. List them with backify handoff replacements.");
33047
- const checked2 = await call2(base + "/" + replacement.id + "/verify", { method: "POST" });
33209
+ const checked2 = await call2(base2 + "/" + replacement.id + "/verify", { method: "POST" });
33048
33210
  return { value: { status: "verifying", replacement: checked2 }, text: "Check requested for " + subjectText(checked2) + ": " + replacementState(checked2) + ". It usually takes a minute; run backify handoff replacements to see the result." };
33049
33211
  }
33050
33212
  if (replacement.action === "remove") {
@@ -33054,10 +33216,10 @@ async function runReplacements(call2, prefix, options, context2) {
33054
33216
  if (!context2.confirm) throw new CommandError("Refusing to remove a replacement without confirmation. Review this and re-run with --yes:\n" + summary, "confirmation_required", { id: replacement.id });
33055
33217
  if (!await context2.confirm(summary)) throw new CommandError("Not confirmed. Nothing was changed.", "not_confirmed");
33056
33218
  }
33057
- await call2(base + "/" + replacement.id, { method: "DELETE" });
33219
+ await call2(base2 + "/" + replacement.id, { method: "DELETE" });
33058
33220
  return { value: { status: "removed", id: replacement.id }, text: "Replacement removed. The dependency counts as hosted by Backify again." };
33059
33221
  }
33060
- const list = await call2(base);
33222
+ const list = await call2(base2);
33061
33223
  let environments = [];
33062
33224
  try {
33063
33225
  environments = (await call2(prefix)).inventory?.environments ?? [];
@@ -33148,7 +33310,7 @@ var init_handoff = __esm({
33148
33310
  uuid12 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
33149
33311
  checkRows = (checks) => pad4([["CHECK", "RESULT", "DETAIL"], ...checks.map((check) => [check.name, check.state, check.detail ?? ""])]);
33150
33312
  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";
33313
+ sizeText = (bytes2) => bytes2 === void 0 ? "" : bytes2 < 1024 ? bytes2 + " B" : bytes2 < 1024 * 1024 ? (bytes2 / 1024).toFixed(1) + " KB" : (bytes2 / 1024 / 1024).toFixed(1) + " MB";
33152
33314
  manifestFiles = (manifest) => Array.isArray(manifest.files) ? manifest.files.map((file) => ({ ...file, path: file.name ?? file.path ?? "" })) : [];
33153
33315
  sha2562 = (text2) => createHash5("sha256").update(text2, "utf8").digest("hex");
33154
33316
  normalizedHash = (value) => value.trim().toLowerCase().replace(/^sha256[:-]/, "");
@@ -33289,6 +33451,207 @@ var init_logs_history = __esm({
33289
33451
  }
33290
33452
  });
33291
33453
 
33454
+ // src/monitoring-dashboards.ts
33455
+ var monitoring_dashboards_exports = {};
33456
+ __export(monitoring_dashboards_exports, {
33457
+ INSIGHT_RANGES: () => INSIGHT_RANGES,
33458
+ monitoringDashboardArguments: () => monitoringDashboardArguments,
33459
+ monitoringDashboardsHelp: () => monitoringDashboardsHelp,
33460
+ runMonitoringDashboards: () => runMonitoringDashboards,
33461
+ widgetList: () => widgetList
33462
+ });
33463
+ function widgetList(value) {
33464
+ return value.split(",").map((item) => item.trim()).filter(Boolean).map((item) => {
33465
+ const [type, size, ...rest] = item.split(":");
33466
+ 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`);
33467
+ if (size !== void 0 && !SIZES.includes(size)) throw new Error("Widget sizes are small, medium or large.");
33468
+ return size ? { type, size } : { type };
33469
+ });
33470
+ }
33471
+ function monitoringDashboardArguments(args2) {
33472
+ const first = args2.find((arg) => !arg.startsWith("-") && args2[args2.indexOf(arg) - 1] !== "--app");
33473
+ if (!first || !["widgets", "capabilities", "dashboards"].includes(first)) return null;
33474
+ if (args2.includes("--help") || args2.includes("-h")) return "help";
33475
+ const { flags, values, positional } = parse(args2, "monitoring " + first, ["--json", "--organization"], ["--app", "--range", "--environment", "--name", "--widgets", "--add", "--remove", "--workspace"]);
33476
+ const json7 = flags.has("--json");
33477
+ const organization = flags.has("--organization"), workspace = values["--workspace"];
33478
+ if ((organization || workspace) && first !== "dashboards") throw new Error("--organization and --workspace apply to monitoring dashboards only.");
33479
+ if ([organization, Boolean(workspace), Boolean(values["--app"])].filter(Boolean).length > 1) throw new Error("Choose one of --app, --workspace or --organization.");
33480
+ if (workspace && !uuid14.test(workspace)) throw new Error("--workspace takes a workspace ID. List workspaces with: backify workspaces");
33481
+ const scoped = organization ? { scope: { kind: "organization" } } : workspace ? { scope: { kind: "workspace", id: workspace.toLowerCase() } } : {};
33482
+ const [, action = "list", target, ...extra] = positional;
33483
+ const only = (allowed) => {
33484
+ const unexpected = Object.keys(values).filter((key) => key !== "--app" && key !== "--workspace" && !allowed.includes(key));
33485
+ if (unexpected.length) throw new Error(`${unexpected.join(", ")} does not apply here.
33486
+
33487
+ ${monitoringDashboardsHelp}`);
33488
+ };
33489
+ if (first === "widgets") {
33490
+ if (positional.length > 1) throw new Error(monitoringDashboardsHelp);
33491
+ only([]);
33492
+ return { action: "widgets", json: json7 };
33493
+ }
33494
+ if (first === "capabilities") {
33495
+ if (positional.length > 1) throw new Error(monitoringDashboardsHelp);
33496
+ only(["--range", "--environment"]);
33497
+ const range = values["--range"]?.toLowerCase() ?? "7d";
33498
+ if (!INSIGHT_RANGES.includes(range)) throw new Error("--range takes 24h, 7d or 30d.");
33499
+ const environment = values["--environment"]?.toLowerCase();
33500
+ if (environment && !(uuid14.test(environment) || ENVIRONMENT_FLOW.includes(environment))) throw new Error("--environment takes prototype, preview, production or an environment UUID.");
33501
+ return { action: "capabilities", range, ...environment ? { environment } : {}, json: json7 };
33502
+ }
33503
+ if (extra.length) throw new Error("Unexpected arguments: " + extra.join(" ") + "\n\n" + monitoringDashboardsHelp);
33504
+ switch (action) {
33505
+ case "list":
33506
+ if (target) throw new Error(monitoringDashboardsHelp);
33507
+ only([]);
33508
+ return { action: "list", ...scoped, json: json7 };
33509
+ case "create": {
33510
+ only(["--name", "--widgets"]);
33511
+ const name2 = values["--name"]?.trim();
33512
+ if (!name2 || target) throw new Error("Usage: backify monitoring dashboards create --name <name> [--widgets <type[:size],...>]");
33513
+ return { action: "create", ...scoped, name: name2, widgets: values["--widgets"] ? widgetList(values["--widgets"]) : [], json: json7 };
33514
+ }
33515
+ case "update": {
33516
+ only(["--name", "--widgets", "--add", "--remove"]);
33517
+ if (values["--widgets"] && (values["--add"] || values["--remove"])) throw new Error("Use --widgets to replace every widget, or --add and --remove to change some.");
33518
+ if (!values["--name"] && !values["--widgets"] && !values["--add"] && !values["--remove"]) throw new Error("Give --name, --widgets, --add or --remove.");
33519
+ return {
33520
+ action: "update",
33521
+ ...scoped,
33522
+ dashboard: dashboardRef(target),
33523
+ ...values["--name"] ? { name: values["--name"].trim() } : {},
33524
+ ...values["--widgets"] ? { widgets: widgetList(values["--widgets"]) } : {},
33525
+ add: values["--add"] ? widgetList(values["--add"]) : [],
33526
+ remove: values["--remove"] ? values["--remove"].split(",").map((item) => item.trim()).filter(Boolean) : [],
33527
+ json: json7
33528
+ };
33529
+ }
33530
+ case "delete":
33531
+ only([]);
33532
+ if (target === "overview") throw new Error("Reset the overview with: backify monitoring dashboards reset");
33533
+ return { action: "delete", ...scoped, dashboard: dashboardRef(target), json: json7 };
33534
+ case "reset":
33535
+ only([]);
33536
+ if (target) throw new Error(monitoringDashboardsHelp);
33537
+ return { action: "delete", ...scoped, dashboard: "overview", json: json7 };
33538
+ }
33539
+ throw new Error("Unknown monitoring dashboards command: " + action + "\n\n" + monitoringDashboardsHelp);
33540
+ }
33541
+ function capacityLines(name2, capacity, limitLabel, connections) {
33542
+ const forecast = capacity.forecast;
33543
+ return [
33544
+ `${name2}${capacity.environmentName ? " (" + capacity.environmentName + ")" : ""}: ${bytes(capacity.usedBytes)}${capacity.limitBytes ? ` of ${bytes(capacity.limitBytes)} ${limitLabel} (${percent2(capacity.usedRatio)})` : ""}. Level: ${capacity.level}.`,
33545
+ ...connections && capacity.connectionLimit ? [` Connections: ${number4(capacity.itemCount)} of ${capacity.connectionLimit} (${percent2(capacity.connectionRatio)}).`] : !connections && capacity.itemCount != null ? [` Files: ${capacity.itemCount}.`] : [],
33546
+ 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).",
33547
+ ` Measured: ${capacity.measuredAt ?? "not yet"}.`
33548
+ ];
33549
+ }
33550
+ function dashboardLines(items) {
33551
+ return items.flatMap((item) => [
33552
+ `${item.kind === "overview" ? "overview" : item.id} ${item.name}${item.kind === "overview" ? item.customized ? " (customized)" : " (automatic)" : ""}`,
33553
+ ...item.widgets.length ? pad([[" WIDGET", "TYPE", "SIZE"], ...item.widgets.map((widget) => [" " + widget.id, widget.type, widget.size])]) : [" No widgets."]
33554
+ ]);
33555
+ }
33556
+ async function runMonitoringDashboards(call2, applicationId, options) {
33557
+ if (options.action === "widgets") {
33558
+ const catalog = await call2("/monitoring/widgets");
33559
+ const names = new Map([["applications", "Applications"], ...catalog.capabilities.map((item) => [item.key, item.title])]);
33560
+ 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") };
33561
+ }
33562
+ const scope = "scope" in options ? options.scope : void 0;
33563
+ if (!scope && !uuid14.test(applicationId)) throw new Error("Use a valid application ID.");
33564
+ const base2 = scope?.kind === "organization" ? "/monitoring/organization" : scope?.kind === "workspace" ? "/monitoring/workspaces/" + scope.id : "/monitoring/applications/" + applicationId;
33565
+ switch (options.action) {
33566
+ case "capabilities": {
33567
+ const query = new URLSearchParams({ range: options.range });
33568
+ if (options.environment) query.set("environmentId", await resolveEnvironment2(call2, "/apps/" + applicationId, options.environment));
33569
+ const data = await call2(base2 + "/capabilities?" + query.toString());
33570
+ const ai = data.ai;
33571
+ const lines = [
33572
+ `Capabilities with monitoring pages: ${data.monitored.join(", ") || "none"}. Range ${data.range}, generated ${data.generatedAt}.`,
33573
+ ...data.database ? ["", ...capacityLines("Database", data.database, "recommended for the scale", true)] : [],
33574
+ ...data.storage ? ["", ...capacityLines("Storage", data.storage, "included", false)] : [],
33575
+ ...ai ? [
33576
+ "",
33577
+ `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)}.`,
33578
+ ...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)])]) : []
33579
+ ] : []
33580
+ ];
33581
+ return { value: data, text: lines.join("\n") };
33582
+ }
33583
+ case "list": {
33584
+ const items = await call2(base2 + "/dashboards");
33585
+ return { value: items, text: dashboardLines(items).join("\n") };
33586
+ }
33587
+ case "create": {
33588
+ const created = await call2(base2 + "/dashboards", { method: "POST", body: JSON.stringify({ name: options.name, widgets: options.widgets }) });
33589
+ return { value: created, text: `Created monitoring page ${created.id}.
33590
+ ` + dashboardLines([created]).join("\n") };
33591
+ }
33592
+ case "update": {
33593
+ let widgets = options.widgets;
33594
+ if (!widgets && (options.add.length || options.remove.length)) {
33595
+ const current = (await call2(base2 + "/dashboards")).find((item) => options.dashboard === "overview" ? item.kind === "overview" : item.id?.toLowerCase() === options.dashboard);
33596
+ if (!current) throw new Error("The monitoring page was not found.");
33597
+ const missing = options.remove.filter((id) => !current.widgets.some((widget) => widget.id === id));
33598
+ if (missing.length) throw new Error("No widget with id " + missing.join(", ") + " on this page.");
33599
+ widgets = [...current.widgets.filter((widget) => !options.remove.includes(widget.id)).map((widget) => ({ id: widget.id, type: widget.type, size: widget.size })), ...options.add];
33600
+ }
33601
+ const updated = await call2(base2 + "/dashboards/" + encodeURIComponent(options.dashboard), { method: "PUT", body: JSON.stringify({ ...options.name ? { name: options.name } : {}, ...widgets ? { widgets } : {} }) });
33602
+ return { value: updated, text: "Updated.\n" + dashboardLines([updated]).join("\n") };
33603
+ }
33604
+ case "delete": {
33605
+ await call2(base2 + "/dashboards/" + encodeURIComponent(options.dashboard), { method: "DELETE" });
33606
+ return { value: { deleted: options.dashboard }, text: options.dashboard === "overview" ? "The overview shows the automatic widgets again." : "Deleted monitoring page " + options.dashboard + "." };
33607
+ }
33608
+ }
33609
+ }
33610
+ var uuid14, INSIGHT_RANGES, SIZES, monitoringDashboardsHelp, dashboardRef, bytes, percent2, number4;
33611
+ var init_monitoring_dashboards = __esm({
33612
+ "src/monitoring-dashboards.ts"() {
33613
+ "use strict";
33614
+ init_logs_history();
33615
+ init_release_flow();
33616
+ uuid14 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
33617
+ INSIGHT_RANGES = ["24h", "7d", "30d"];
33618
+ SIZES = ["small", "medium", "large"];
33619
+ monitoringDashboardsHelp = [
33620
+ "Usage:",
33621
+ " backify monitoring widgets [--json]",
33622
+ " The widget catalog: every widget type, its capability, default size and the dashboards that can hold it.",
33623
+ " backify monitoring capabilities [--range 24h|7d|30d] [--environment <prototype|preview|production|UUID>] [--json]",
33624
+ " Database size and connections against the limits of the environment's scale, storage against the included",
33625
+ " allowance, both with a growth forecast, and AI usage per model (calls, average prompt and response size, cost).",
33626
+ " backify monitoring dashboards [--json]",
33627
+ " The monitoring pages: the overview and custom pages, with their widgets. Add --organization or",
33628
+ " --workspace <workspace-id> to any dashboards command for the organization's or a workspace's pages.",
33629
+ " backify monitoring dashboards create --name <name> [--widgets <type[:size],...>] [--json]",
33630
+ " backify monitoring dashboards update <page-id|overview> [--name <name>] [--widgets <type[:size],...>]",
33631
+ " [--add <type[:size],...>] [--remove <widget-id,...>] [--json]",
33632
+ " --widgets replaces every widget; --add appends and --remove takes widgets away. Sizes: small, medium, large.",
33633
+ " backify monitoring dashboards delete <page-id> [--json]",
33634
+ " backify monitoring dashboards reset [--json]",
33635
+ " Puts the overview back to the automatic widgets (for an application, those of the capabilities it uses).",
33636
+ " --app <application> Default: the application in this folder",
33637
+ " --organization The organization's monitoring pages; changes need organization management",
33638
+ " --workspace <id> A workspace's monitoring pages; changes need workspace management"
33639
+ ].join("\n");
33640
+ dashboardRef = (value) => {
33641
+ if (!value || !(value === "overview" || uuid14.test(value))) throw new Error("Name the page by its id, or overview. List pages with: backify monitoring dashboards");
33642
+ return value.toLowerCase();
33643
+ };
33644
+ bytes = (value) => {
33645
+ if (value == null) return "-";
33646
+ const units = ["B", "KB", "MB", "GB", "TB"];
33647
+ const exponent = value > 0 ? Math.min(units.length - 1, Math.floor(Math.log(value) / Math.log(1e3))) : 0;
33648
+ return (value / 1e3 ** exponent).toFixed(exponent ? 1 : 0) + " " + units[exponent];
33649
+ };
33650
+ percent2 = (value) => value == null ? "-" : Math.round(value * 100) + "%";
33651
+ number4 = (value) => value == null ? "-" : Number.isInteger(value) ? String(value) : value.toFixed(1);
33652
+ }
33653
+ });
33654
+
33292
33655
  // src/monitoring.ts
33293
33656
  var monitoring_exports = {};
33294
33657
  __export(monitoring_exports, {
@@ -33302,13 +33665,13 @@ function monitoringArguments(args2) {
33302
33665
  const { flags, values, positional } = parse(args2, "monitoring", ["--json"], ["--app", "--environment", "--range"]);
33303
33666
  if (positional.length) throw new Error("Unknown monitoring command: " + positional.join(" ") + "\n\n" + monitoringHelp);
33304
33667
  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.");
33668
+ if (environment && !(uuid15.test(environment) || ENVIRONMENT_FLOW.includes(environment))) throw new Error("--environment takes prototype, preview, production or an environment UUID.");
33306
33669
  const range = values["--range"]?.toLowerCase() ?? "24h";
33307
33670
  if (!MONITORING_RANGES.includes(range)) throw new Error("--range takes 1h, 6h, 24h or 7d.");
33308
33671
  return { ...environment ? { environment } : {}, range, json: flags.has("--json") };
33309
33672
  }
33310
33673
  async function runMonitoring(call2, applicationId, options) {
33311
- if (!uuid14.test(applicationId)) throw new Error("Use a valid application ID.");
33674
+ if (!uuid15.test(applicationId)) throw new Error("Use a valid application ID.");
33312
33675
  const prefix = "/apps/" + applicationId;
33313
33676
  const environmentId = options.environment ? await resolveEnvironment2(call2, prefix, options.environment) : void 0;
33314
33677
  const query = new URLSearchParams({ range: options.range });
@@ -33323,14 +33686,14 @@ async function runMonitoring(call2, applicationId, options) {
33323
33686
  ].join("\n");
33324
33687
  return { value: { ...environmentId ? { environmentId } : {}, range: options.range, ...snapshot }, text: text2 };
33325
33688
  }
33326
- var MONITORING_RANGES, uuid14, monitoringHelp, reading;
33689
+ var MONITORING_RANGES, uuid15, monitoringHelp, reading;
33327
33690
  var init_monitoring = __esm({
33328
33691
  "src/monitoring.ts"() {
33329
33692
  "use strict";
33330
33693
  init_logs_history();
33331
33694
  init_release_flow();
33332
33695
  MONITORING_RANGES = ["1h", "6h", "24h", "7d"];
33333
- uuid14 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
33696
+ uuid15 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
33334
33697
  monitoringHelp = [
33335
33698
  "Usage: backify monitoring [--environment <prototype|preview|production|UUID>] [--range 1h|6h|24h|7d] [--json]",
33336
33699
  "",
@@ -33353,7 +33716,7 @@ __export(operation_progress_exports, {
33353
33716
  function operationArguments(args2) {
33354
33717
  if (args2.includes("--help") || args2.includes("-h")) return "help";
33355
33718
  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].");
33719
+ if (positional.length !== 1 || !uuid16.test(positional[0])) throw new Error("Use backify operation <operation-id> [--wait] [--json].");
33357
33720
  return { operationId: positional[0].toLowerCase(), wait: flags.has("--wait"), json: flags.has("--json") };
33358
33721
  }
33359
33722
  async function runOperation(call2, options, context2 = {}) {
@@ -33375,12 +33738,12 @@ async function runOperation(call2, options, context2 = {}) {
33375
33738
  ].join("\n");
33376
33739
  return { value: { operation, logs }, text: text2, ...operation.status === "failed" ? { exitCode: 1 } : options.wait && !finished.has(operation.status) ? { exitCode: 2 } : {} };
33377
33740
  }
33378
- var uuid15, finished, operationHelp, line;
33741
+ var uuid16, finished, operationHelp, line;
33379
33742
  var init_operation_progress = __esm({
33380
33743
  "src/operation-progress.ts"() {
33381
33744
  "use strict";
33382
33745
  init_release_flow();
33383
- uuid15 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
33746
+ uuid16 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
33384
33747
  finished = /* @__PURE__ */ new Set(["succeeded", "failed", "cancelled"]);
33385
33748
  operationHelp = [
33386
33749
  "Usage: backify operation <operation-id> [--wait] [--json]",
@@ -33620,23 +33983,23 @@ async function diagnoseEnvironment(root = process.cwd(), options = {}, probes =
33620
33983
 
33621
33984
  // src/integrations.ts
33622
33985
  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");
33625
- const base = "/apps/" + options.applicationId + "/integrations/connectors";
33626
- if (command2 === "list") return base;
33986
+ const uuid17 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
33987
+ if (!uuid17.test(options.applicationId)) throw new Error("An application UUID is required");
33988
+ const base2 = "/apps/" + options.applicationId + "/integrations/connectors";
33989
+ if (command2 === "list") return base2;
33627
33990
  if (command2 === "catalog") return "/apps/" + options.applicationId + "/integrations/catalog";
33628
33991
  if (command2 === "discover") return "/apps/" + options.applicationId + "/integrations/discover?" + new URLSearchParams({ query: options.query ?? "" });
33629
33992
  if (command2 === "prepare") return "/apps/" + options.applicationId + "/integrations/prepare";
33630
33993
  if (command2 === "contract" && options.revisionId) {
33631
- if (!uuid16.test(options.revisionId)) throw new Error("Use --revision with a discovered revision UUID");
33994
+ if (!uuid17.test(options.revisionId)) throw new Error("Use --revision with a discovered revision UUID");
33632
33995
  return "/apps/" + options.applicationId + "/integrations/definitions/" + options.revisionId;
33633
33996
  }
33634
33997
  if (command2 === "status") {
33635
- if (!options.adoptionId || !uuid16.test(options.adoptionId)) throw new Error("Use --adoption with an adoption request UUID");
33998
+ if (!options.adoptionId || !uuid17.test(options.adoptionId)) throw new Error("Use --adoption with an adoption request UUID");
33636
33999
  return "/apps/" + options.applicationId + "/integrations/adoptions/" + options.adoptionId;
33637
34000
  }
33638
- if (!options.connectionId || !uuid16.test(options.connectionId)) throw new Error("Use --connection with an integration connection UUID");
33639
- const connection2 = base + "/" + options.connectionId;
34001
+ if (!options.connectionId || !uuid17.test(options.connectionId)) throw new Error("Use --connection with an integration connection UUID");
34002
+ const connection2 = base2 + "/" + options.connectionId;
33640
34003
  if (command2 === "contract" || command2 === "types") return connection2 + "/" + command2;
33641
34004
  if (command2 === "describe") {
33642
34005
  if (!options.operationId) throw new Error("Use --operation to select an operation");
@@ -33658,14 +34021,14 @@ function integrationPreparation(input) {
33658
34021
  }
33659
34022
  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
34023
  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);
34024
+ const uuid17 = /^(?:[a-f0-9]{8}-)(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i;
34025
+ if (!options.connectionId || !options.environmentId || ![options.applicationId, options.connectionId, options.environmentId].every((id) => uuid17.test(id))) throw new Error(integrationWebhooksUsage);
33663
34026
  const path = "/apps/" + options.applicationId + "/integrations/connectors/" + options.connectionId;
33664
34027
  if (command2 === "webhooks" || command2 === "webhook-deliveries") return { path: path + "/" + command2 + "?" + new URLSearchParams({ environmentId: options.environmentId }) };
33665
34028
  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 ?? ""))
34029
+ if (command2 === "webhook-job" && options.bindingId && uuid17.test(options.bindingId) && /^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/.test(options.job ?? ""))
33667
34030
  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)
34031
+ if (command2 === "webhook-replay" && options.receiptId && uuid17.test(options.receiptId) && options.confirm)
33669
34032
  return { path: path + "/webhook-deliveries/" + options.receiptId + "/replay", init: { method: "POST", headers, body: JSON.stringify({ environmentId: options.environmentId, confirm: true }) } };
33670
34033
  throw new Error(integrationWebhooksUsage);
33671
34034
  }
@@ -33927,12 +34290,12 @@ async function setupAuth(call2, options) {
33927
34290
  if (!uuid6.test(app) || options.requestId && !uuid6.test(options.requestId)) throw new Error("Use valid application and sign-in setup request IDs.");
33928
34291
  if (!Number.isFinite(timeout) || timeout < 1e3 || timeout > 36e5) throw new Error("Use --timeout between 1 and 3600 seconds.");
33929
34292
  const origin = authOrigin(options.authUrl), now = options.now ?? Date.now, deadline = now() + timeout;
33930
- const base = "/apps/" + app + "/auth/setup/requests";
34293
+ const base2 = "/apps/" + app + "/auth/setup/requests";
33931
34294
  const read = async (value) => {
33932
34295
  validateAuthSetupStatus(value, app);
33933
34296
  return value;
33934
34297
  };
33935
- let status = await read(options.requestId ? await call2(base + "/" + options.requestId) : await call2(base, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ providers: configuredProviders(options.providers), requestKey: randomUUID3(), source: "cli" }) }));
34298
+ let status = await read(options.requestId ? await call2(base2 + "/" + options.requestId) : await call2(base2, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ providers: configuredProviders(options.providers), requestKey: randomUUID3(), source: "cli" }) }));
33936
34299
  const link = setupUrl(origin, app, status);
33937
34300
  const missing = () => [...new Set(status.effective.filter((cell) => status.providers.includes(cell.provider) && !cell.configured).map((cell) => cell.provider))];
33938
34301
  const result = (reason) => ({
@@ -33973,7 +34336,7 @@ async function setupAuth(call2, options) {
33973
34336
  throw error2;
33974
34337
  }
33975
34338
  if (options.signal?.aborted) return result("cancelled");
33976
- status = await read(await call2(base + "/" + status.id));
34339
+ status = await read(await call2(base2 + "/" + status.id));
33977
34340
  if (setupUrl(origin, app, status) !== link) throw new Error("The sign-in setup request changed while waiting.");
33978
34341
  }
33979
34342
  }
@@ -34019,15 +34382,15 @@ function privacyRequestCall(appId, args2) {
34019
34382
  };
34020
34383
  const [area, action, id] = args2;
34021
34384
  if (area !== "requests" || !action) throw new Error(privacyRequestsUsage);
34022
- const base = `/apps/${appId}/compliance/requests`;
34385
+ const base2 = `/apps/${appId}/compliance/requests`;
34023
34386
  const request = () => {
34024
34387
  if (!id || !guid.test(id)) throw new Error(`Give the request ID: backify privacy requests ${action} <request-id>.`);
34025
- return `${base}/${id}`;
34388
+ return `${base2}/${id}`;
34026
34389
  };
34027
34390
  switch (action) {
34028
34391
  case "list": {
34029
34392
  const status = option2("--status");
34030
- return { method: "GET", path: status ? `${base}?status=${encodeURIComponent(status)}` : base };
34393
+ return { method: "GET", path: status ? `${base2}?status=${encodeURIComponent(status)}` : base2 };
34031
34394
  }
34032
34395
  case "show":
34033
34396
  return { method: "GET", path: request() };
@@ -34038,7 +34401,7 @@ function privacyRequestCall(appId, args2) {
34038
34401
  if (!type || !subjectKind || !subject || !verificationMethod) throw new Error("Specify --type, --subject-kind, --subject and --verified-by.\n" + privacyRequestsUsage);
34039
34402
  const environment = option2("--environment");
34040
34403
  if (environment !== void 0 && !guid.test(environment)) throw new Error("--environment must be an environment UUID.");
34041
- return { method: "POST", path: base, body: { type, subjectKind, subject, verificationMethod, verificationNote: option2("--note"), receivedAt: option2("--received"), environmentId: environment } };
34404
+ return { method: "POST", path: base2, body: { type, subjectKind, subject, verificationMethod, verificationNote: option2("--note"), receivedAt: option2("--received"), environmentId: environment } };
34042
34405
  }
34043
34406
  case "update": {
34044
34407
  const extend2 = option2("--extend");
@@ -34057,6 +34420,113 @@ function privacyRequestCall(appId, args2) {
34057
34420
  }
34058
34421
  }
34059
34422
 
34423
+ // src/notifications.ts
34424
+ var notificationsUsage = [
34425
+ "Use backify notifications <action>:",
34426
+ " list [--action | --unread] [--organization <id>] [--workspace <id>] [--app <id>] [--category <category>] [--cursor <cursor>] [--limit <n>] [--json]",
34427
+ " --action lists open items that need you; a wider scope includes the narrower ones",
34428
+ " summary [--json] unread and open-action counts per organization, workspace and application",
34429
+ " read <notification-id> | read --all [--organization <id>] [--workspace <id>] [--app <id>]",
34430
+ " dismiss <notification-id> removes it from your inbox only; the underlying request is unchanged",
34431
+ " preferences [--json] your channels per category",
34432
+ " preferences set <category> [--email on|off|default] [--in-app on|off|default] [--organization <id>] [--workspace <id> | --app <id>]",
34433
+ `Categories: ${["approvals", "requests", "deployments", "reliability", "security", "vulnerabilities", "billing", "domains", "access", "operations"].join(", ")}.`,
34434
+ "Items that need your action always reach the portal inbox, and required security and billing notices are always emailed."
34435
+ ].join("\n");
34436
+ var notificationCategories = ["approvals", "requests", "deployments", "reliability", "security", "vulnerabilities", "billing", "domains", "access", "operations"];
34437
+ var guid2 = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
34438
+ var base = "/account/notifications";
34439
+ function notificationCall(args2) {
34440
+ const option2 = (name2) => {
34441
+ const index = args2.indexOf(name2);
34442
+ return index >= 0 ? args2[index + 1] : void 0;
34443
+ };
34444
+ const id = (value, name2) => {
34445
+ if (value === void 0) return void 0;
34446
+ if (!guid2.test(value)) throw new Error(`${name2} must be a UUID.`);
34447
+ return value;
34448
+ };
34449
+ const scope = () => ({ organizationId: id(option2("--organization"), "--organization"), workspaceId: id(option2("--workspace"), "--workspace"), applicationId: id(option2("--app"), "--app") });
34450
+ const [action = "list", target] = args2;
34451
+ switch (action) {
34452
+ case "list": {
34453
+ if (args2.includes("--action") && args2.includes("--unread")) throw new Error("Choose --action or --unread, not both.");
34454
+ const query = new URLSearchParams({ view: args2.includes("--action") ? "action" : args2.includes("--unread") ? "unread" : "all" });
34455
+ for (const [key, value] of Object.entries(scope())) if (value) query.set(key, value);
34456
+ const category = option2("--category");
34457
+ if (category !== void 0) {
34458
+ if (!notificationCategories.includes(category)) throw new Error("--category must be one of: " + notificationCategories.join(", ") + ".");
34459
+ query.set("category", category);
34460
+ }
34461
+ const cursor = option2("--cursor"), limit = option2("--limit");
34462
+ if (cursor !== void 0) {
34463
+ if (!/^\d+$/.test(cursor)) throw new Error("--cursor takes the nextCursor value of the previous page.");
34464
+ query.set("cursor", cursor);
34465
+ }
34466
+ if (limit !== void 0) {
34467
+ if (!/^\d+$/.test(limit) || Number(limit) < 1 || Number(limit) > 100) throw new Error("--limit takes 1 to 100.");
34468
+ query.set("limit", limit);
34469
+ }
34470
+ return { method: "GET", path: `${base}?${query}` };
34471
+ }
34472
+ case "summary":
34473
+ return { method: "GET", path: `${base}/summary` };
34474
+ case "read": {
34475
+ if (args2.includes("--all")) return { method: "POST", path: `${base}/read`, body: scope() };
34476
+ if (!target || !guid2.test(target)) throw new Error("Give the notification ID (backify notifications read <notification-id>) or --all.");
34477
+ return { method: "POST", path: `${base}/${target}/read` };
34478
+ }
34479
+ case "dismiss":
34480
+ if (!target || !guid2.test(target)) throw new Error("Give the notification ID: backify notifications dismiss <notification-id>.");
34481
+ return { method: "POST", path: `${base}/${target}/archive` };
34482
+ case "preferences": {
34483
+ if (target === void 0 || target.startsWith("--")) return { method: "GET", path: `${base}/preferences` };
34484
+ if (target !== "set") throw new Error(notificationsUsage);
34485
+ const category = args2[2];
34486
+ if (!category || !notificationCategories.includes(category)) throw new Error("Give a category: " + notificationCategories.join(", ") + ".");
34487
+ const channel = (name2) => {
34488
+ const value = option2(name2);
34489
+ if (value === void 0) return void 0;
34490
+ if (!["on", "off", "default"].includes(value)) throw new Error(`${name2} takes on, off or default.`);
34491
+ return value === "default" ? null : value === "on";
34492
+ };
34493
+ const email2 = channel("--email"), inApp = channel("--in-app");
34494
+ if (email2 === void 0 && inApp === void 0) throw new Error("Specify --email and/or --in-app.");
34495
+ const scoped = scope();
34496
+ if ((scoped.workspaceId || scoped.applicationId) && !scoped.organizationId) throw new Error("A workspace or application setting needs --organization.");
34497
+ if (scoped.workspaceId && scoped.applicationId) throw new Error("Choose --workspace or --app, not both.");
34498
+ const entry = {
34499
+ category,
34500
+ ...email2 !== void 0 ? { email: email2 } : {},
34501
+ ...inApp !== void 0 ? { inApp } : {},
34502
+ organizationId: scoped.organizationId ?? null,
34503
+ workspaceId: scoped.workspaceId ?? null,
34504
+ applicationId: scoped.applicationId ?? null
34505
+ };
34506
+ return { method: "PUT", path: `${base}/preferences`, preferences: { entry } };
34507
+ }
34508
+ default:
34509
+ throw new Error(notificationsUsage);
34510
+ }
34511
+ }
34512
+ var sameScope = (first, second) => first.category === second.category && (first.organizationId ?? null) === (second.organizationId ?? null) && (first.workspaceId ?? null) === (second.workspaceId ?? null) && (first.applicationId ?? null) === (second.applicationId ?? null);
34513
+ function mergePreference(current, change) {
34514
+ const existing = current.find((entry) => sameScope(entry, change.entry));
34515
+ const merged = { ...existing, ...change.entry };
34516
+ return { preferences: [...current.filter((entry) => !sameScope(entry, change.entry)), merged] };
34517
+ }
34518
+ function formatNotifications(page) {
34519
+ if (!page.items.length) return "No notifications.";
34520
+ const lines = page.items.map((item) => {
34521
+ const state = item.actionable && !item.resolvedAt ? "ACTION" : item.resolvedAt ? (item.resolution ?? "resolved").toUpperCase() : item.readAt ? "read" : "NEW";
34522
+ return `${item.createdAt} [${state}] [${item.severity}] ${item.title}
34523
+ ${item.body}
34524
+ ${item.path} (id ${item.id})`;
34525
+ });
34526
+ if (page.nextCursor) lines.push(`More: backify notifications list --cursor ${page.nextCursor}`);
34527
+ return lines.join("\n");
34528
+ }
34529
+
34060
34530
  // src/outbound-http.ts
34061
34531
  var outboundHttpUsage = [
34062
34532
  "Use backify outbound <action> --environment <UUID> [--app <application-id>]:",
@@ -34069,7 +34539,7 @@ var outboundHttpUsage = [
34069
34539
  " requests [--search <text>] [--outcome allowed|blocked|not-allowed]",
34070
34540
  "List environments with backify events environments. Quote wildcards so your shell does not expand them."
34071
34541
  ].join("\n");
34072
- var guid2 = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
34542
+ var guid3 = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
34073
34543
  function outboundHttpCall(appId, args2) {
34074
34544
  const option2 = (name2) => {
34075
34545
  const index = args2.indexOf(name2);
@@ -34077,8 +34547,8 @@ function outboundHttpCall(appId, args2) {
34077
34547
  };
34078
34548
  const [action, value] = args2;
34079
34549
  const environment = option2("--environment");
34080
- if (!action || !environment || !guid2.test(environment)) throw new Error(outboundHttpUsage);
34081
- const base = `/apps/${appId}/outbound-http/environments/${environment}`;
34550
+ if (!action || !environment || !guid3.test(environment)) throw new Error(outboundHttpUsage);
34551
+ const base2 = `/apps/${appId}/outbound-http/environments/${environment}`;
34082
34552
  const query = (names) => {
34083
34553
  const params = new URLSearchParams();
34084
34554
  for (const name2 of names) {
@@ -34091,31 +34561,294 @@ function outboundHttpCall(appId, args2) {
34091
34561
  const positional = value !== void 0 && !value.startsWith("--") ? value : void 0;
34092
34562
  switch (action) {
34093
34563
  case "show":
34094
- return { method: "GET", path: base };
34564
+ return { method: "GET", path: base2 };
34095
34565
  case "default":
34096
34566
  if (positional !== "allow" && positional !== "deny") throw new Error("Use backify outbound default allow|deny --environment <UUID>.");
34097
- return { method: "PUT", path: base + "/default", body: { action: positional } };
34567
+ return { method: "PUT", path: base2 + "/default", body: { action: positional } };
34098
34568
  case "allow":
34099
34569
  case "block":
34100
34570
  if (!positional) throw new Error(`Give a host, wildcard or HTTPS URL: backify outbound ${action} <pattern> --environment <UUID>.`);
34101
- return { method: "POST", path: base + "/rules", body: { pattern: positional, action } };
34571
+ return { method: "POST", path: base2 + "/rules", body: { pattern: positional, action } };
34102
34572
  case "remove":
34103
- if (!positional || !guid2.test(positional)) throw new Error("Give the rule ID from backify outbound show: backify outbound remove <rule-id> --environment <UUID>.");
34104
- return { method: "DELETE", path: `${base}/rules/${positional}` };
34573
+ if (!positional || !guid3.test(positional)) throw new Error("Give the rule ID from backify outbound show: backify outbound remove <rule-id> --environment <UUID>.");
34574
+ return { method: "DELETE", path: `${base2}/rules/${positional}` };
34105
34575
  case "destinations":
34106
- return { method: "GET", path: base + "/destinations" + query(["search"]) };
34576
+ return { method: "GET", path: base2 + "/destinations" + query(["search"]) };
34107
34577
  case "requests": {
34108
34578
  const outcome = option2("--outcome");
34109
34579
  if (outcome !== void 0 && !["allowed", "blocked", "not-allowed"].includes(outcome)) throw new Error("--outcome must be allowed, blocked or not-allowed.");
34110
- return { method: "GET", path: base + "/requests" + query(["search", "outcome"]) };
34580
+ return { method: "GET", path: base2 + "/requests" + query(["search", "outcome"]) };
34111
34581
  }
34112
34582
  default:
34113
34583
  throw new Error(outboundHttpUsage);
34114
34584
  }
34115
34585
  }
34116
34586
 
34587
+ // src/capability-data.ts
34588
+ var guid4 = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
34589
+ var bucketName = /^[a-z0-9](?:[a-z0-9-]{1,61}[a-z0-9])$/;
34590
+ function reader(args2) {
34591
+ const option2 = (name2) => {
34592
+ const index = args2.indexOf(name2);
34593
+ return index >= 0 ? args2[index + 1] : void 0;
34594
+ };
34595
+ const flag = (name2) => args2.includes(name2);
34596
+ const positional = (from = 1) => {
34597
+ for (let index = from; index < args2.length; index++) {
34598
+ if (args2[index].startsWith("--")) {
34599
+ if (!["--folders", "--deleted", "--overwrite", "--yes"].includes(args2[index])) index++;
34600
+ continue;
34601
+ }
34602
+ return args2[index];
34603
+ }
34604
+ return void 0;
34605
+ };
34606
+ return { option: option2, flag, positional };
34607
+ }
34608
+ function environmentOf(args2, usage) {
34609
+ const environment = reader(args2).option("--environment");
34610
+ if (!environment || !guid4.test(environment)) throw new Error(usage);
34611
+ return environment;
34612
+ }
34613
+ var storageUsage = [
34614
+ "Use backify storage <action> [--app <application-id>]:",
34615
+ " environments environments that have storage",
34616
+ " usage bytes, files and buckets across environments",
34617
+ " buckets --environment <UUID>",
34618
+ " ls --environment <UUID> --bucket <name> [--prefix <folder/>] [--folders] [--deleted]",
34619
+ " --folders lists one folder: its files and subfolders",
34620
+ " upload <file> --environment <UUID> --bucket <name> --key <key> [--overwrite] (at most 100 MiB)",
34621
+ " download --environment <UUID> --bucket <name> --key <key> [--out <file>]",
34622
+ " rm --environment <UUID> --bucket <name> --key <key> --yes soft delete; restore while retained",
34623
+ " restore --environment <UUID> --bucket <name> --key <key>"
34624
+ ].join("\n");
34625
+ function storageCall(appId, args2) {
34626
+ const { option: option2, flag, positional } = reader(args2);
34627
+ const action = args2[0];
34628
+ const root = `/apps/${appId}/storage`;
34629
+ if (action === "environments") return { method: "GET", path: root + "/environments" };
34630
+ if (action === "usage") return { method: "GET", path: root + "/usage" };
34631
+ const environment = environmentOf(args2, storageUsage);
34632
+ const base2 = `${root}/environments/${environment}`;
34633
+ if (action === "buckets") return { method: "GET", path: base2 + "/buckets" };
34634
+ const bucket = option2("--bucket");
34635
+ if (!bucket || !bucketName.test(bucket)) throw new Error("Give the bucket with --bucket <name>; list them with backify storage buckets --environment <UUID>.");
34636
+ const files = `${base2}/buckets/${encodeURIComponent(bucket)}`;
34637
+ const key = option2("--key");
34638
+ const needKey = () => {
34639
+ if (!key) throw new Error(`Give the file with --key <key>: backify storage ${action} --environment <UUID> --bucket ${bucket} --key <key>.`);
34640
+ return key;
34641
+ };
34642
+ switch (action) {
34643
+ case "ls": {
34644
+ const query = new URLSearchParams();
34645
+ const prefix = option2("--prefix");
34646
+ if (prefix) query.set("prefix", prefix);
34647
+ if (flag("--folders") && !flag("--deleted")) query.set("delimiter", "/");
34648
+ const continuation = option2("--continue");
34649
+ if (continuation) query.set("continuationToken", continuation);
34650
+ return { method: "GET", path: files + (flag("--deleted") ? "/deleted-files" : "/files") + (query.size ? "?" + query : "") };
34651
+ }
34652
+ case "upload": {
34653
+ const file = positional();
34654
+ if (!file) throw new Error("Give the local file: backify storage upload <file> --environment <UUID> --bucket <name> --key <key>.");
34655
+ const target = needKey();
34656
+ return { method: "PUT", path: `${files}/file?` + new URLSearchParams({ key: target, ...flag("--overwrite") ? { overwrite: "true" } : {} }), upload: { file, key: target } };
34657
+ }
34658
+ case "download": {
34659
+ const target = needKey();
34660
+ return { method: "GET", path: `${files}/file?` + new URLSearchParams({ key: target }), download: { key: target, out: option2("--out") } };
34661
+ }
34662
+ case "rm": {
34663
+ const target = needKey();
34664
+ if (!flag("--yes")) throw new Error(`Deleting ${target} needs --yes. It stays restorable with backify storage restore while the bucket retains deleted files.`);
34665
+ return { method: "DELETE", path: `${files}/file?` + new URLSearchParams({ key: target, confirmation: target }) };
34666
+ }
34667
+ case "restore":
34668
+ return { method: "POST", path: `${files}/restore?` + new URLSearchParams({ key: needKey() }) };
34669
+ default:
34670
+ throw new Error(storageUsage);
34671
+ }
34672
+ }
34673
+ var databaseDataUsage = [
34674
+ "Use backify database <action> --environment <UUID> [--app <application-id>]:",
34675
+ " extensions | insights [--hours <1-168>] installed extensions; slow queries and likely missing indexes",
34676
+ " tables tables with estimated rows and sizes",
34677
+ " rows <table> [--offset <n>] [--limit <1-100>] rows as stored (not masked); needs database.manage",
34678
+ " query <sql> | query --file <sql-file> one read-only SELECT, at most 100 rows, five-second limit",
34679
+ " backups stored backups",
34680
+ " backup take a backup now",
34681
+ " restore <backup-id> --confirm <application-slug> replace all data with a backup (a safety backup is taken first)"
34682
+ ].join("\n");
34683
+ function databaseCall(appId, args2, readFile = () => {
34684
+ throw new Error("Reading files is not available.");
34685
+ }) {
34686
+ const { option: option2, positional } = reader(args2);
34687
+ const action = args2[0];
34688
+ const environment = environmentOf(args2, databaseDataUsage);
34689
+ const inspection = `/apps/${appId}/environments/${environment}/database`;
34690
+ const manage = `/apps/${appId}/database/environments/${environment}`;
34691
+ switch (action) {
34692
+ case "extensions":
34693
+ return { method: "GET", path: inspection + "/extensions" };
34694
+ case "insights": {
34695
+ const hours = option2("--hours");
34696
+ 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.");
34697
+ return { method: "GET", path: inspection + "/insights" + (hours ? "?hours=" + hours : "") };
34698
+ }
34699
+ case "tables":
34700
+ return { method: "GET", path: manage + "/tables" };
34701
+ case "rows": {
34702
+ const table = positional();
34703
+ 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>.");
34704
+ const offset = option2("--offset") ?? "0", limit = option2("--limit") ?? "50";
34705
+ 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.");
34706
+ return { method: "GET", path: `${manage}/tables/${encodeURIComponent(table)}/rows?offset=${offset}&limit=${limit}` };
34707
+ }
34708
+ case "query": {
34709
+ const file = option2("--file");
34710
+ const sql = file ? readFile(file) : positional();
34711
+ if (!sql?.trim()) throw new Error('Give one SELECT: backify database query "SELECT \u2026" --environment <UUID>, or --file <sql-file>.');
34712
+ return { method: "POST", path: manage + "/query", body: { sql } };
34713
+ }
34714
+ case "backups":
34715
+ return { method: "GET", path: manage + "/backups" };
34716
+ case "backup":
34717
+ return { method: "POST", path: manage + "/backups" };
34718
+ case "restore": {
34719
+ const backup = positional(), confirmation = option2("--confirm");
34720
+ 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>.");
34721
+ if (!confirmation) throw new Error("Restoring replaces all data in this environment's database. Confirm with --confirm <application-slug>.");
34722
+ return { method: "POST", path: `${manage}/backups/${backup}/restore`, body: { confirmation } };
34723
+ }
34724
+ default:
34725
+ throw new Error(databaseDataUsage);
34726
+ }
34727
+ }
34728
+ var backendUsage = [
34729
+ "Use backify backend <action> --environment <UUID> [--app <application-id>]:",
34730
+ " show release, health, scale and routes of the live release",
34731
+ " routes one line per endpoint: method, path, access and operation",
34732
+ " openapi [--out <file>] the release's OpenAPI document"
34733
+ ].join("\n");
34734
+ function backendCall(appId, args2) {
34735
+ const action = args2[0];
34736
+ const environment = environmentOf(args2, backendUsage);
34737
+ const base2 = `/apps/${appId}/environments/${environment}/backend`;
34738
+ if (action === "show" || action === "routes") return { method: "GET", path: base2 };
34739
+ if (action === "openapi") return { method: "GET", path: base2 + "/openapi.json", download: { key: "openapi.json", out: reader(args2).option("--out") } };
34740
+ throw new Error(backendUsage);
34741
+ }
34742
+ function routeLines(routes) {
34743
+ const access = (auth2) => auth2.kind === "role" ? "role " + auth2.role : auth2.kind === "permission" ? "permission " + auth2.permission : auth2.kind === "user" ? "signed-in user" : "public";
34744
+ return routes.map((route) => [route.method.padEnd(6), route.path, "\xB7", access(route.auth), "\xB7", route.operationId].join(" "));
34745
+ }
34746
+ var jobsUsage = [
34747
+ "Use backify jobs <action> --environment <UUID> [--app <application-id>]:",
34748
+ " show declared jobs, schedules and subscriptions with recent state",
34749
+ " runs [--job <name>] [--status pending|running|completed|failed|cancelled]",
34750
+ " insights [--range 24h|7d|30d] job runs over time, by status and by job"
34751
+ ].join("\n");
34752
+ function jobsCall(appId, args2) {
34753
+ const { option: option2 } = reader(args2);
34754
+ const action = args2[0];
34755
+ const environment = environmentOf(args2, jobsUsage);
34756
+ const base2 = `/apps/${appId}/environments/${environment}/jobs`;
34757
+ switch (action) {
34758
+ case "show":
34759
+ return { method: "GET", path: base2 };
34760
+ case "runs": {
34761
+ const query = new URLSearchParams();
34762
+ const job = option2("--job"), status = option2("--status");
34763
+ if (status && !["pending", "running", "completed", "failed", "cancelled"].includes(status)) throw new Error("--status must be pending, running, completed, failed or cancelled.");
34764
+ if (job) query.set("job", job);
34765
+ if (status) query.set("status", status);
34766
+ return { method: "GET", path: base2 + "/runs" + (query.size ? "?" + query : "") };
34767
+ }
34768
+ case "insights": {
34769
+ const range = option2("--range") ?? "7d";
34770
+ if (!["24h", "7d", "30d"].includes(range)) throw new Error("--range must be 24h, 7d or 30d.");
34771
+ return { method: "GET", path: base2 + "/insights?range=" + range };
34772
+ }
34773
+ default:
34774
+ throw new Error(jobsUsage);
34775
+ }
34776
+ }
34777
+
34117
34778
  // src/index.ts
34118
34779
  init_platform_patches();
34780
+
34781
+ // src/scale.ts
34782
+ var json2 = { "content-type": "application/json" };
34783
+ var scaleUsage = [
34784
+ "Use backify scale [<environment>] [options] [--app <application-id>]:",
34785
+ " backify scale each environment's instance size and instances, with the plan's limits",
34786
+ " backify scale <environment> --size <S|M|L|XL> scale up or down: CPU and memory per instance",
34787
+ " backify scale <environment> --instances <n> scale out or in: the most instances Backify runs as traffic grows",
34788
+ " backify scale <environment> --min <n> instances that always run; --scale-to-zero is --min 0, --always-on is at least 1",
34789
+ " backify scale <environment> --concurrency <n> concurrent requests per instance before another one starts",
34790
+ "<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."
34791
+ ].join("\n");
34792
+ function instances(count) {
34793
+ return `${count} instance${count === 1 ? "" : "s"}`;
34794
+ }
34795
+ function scaleLine(scale, sizes) {
34796
+ const size = sizes.find((item) => item.name === scale.size);
34797
+ const count = scale.minReplicas === scale.maxReplicas ? instances(scale.maxReplicas) : `${scale.minReplicas} to ${instances(scale.maxReplicas)}`;
34798
+ return `${count} of ${scale.size}${size ? ` (${size.cpu} vCPU, ${size.memory.replace("Gi", " GiB")})` : ""}, ${scale.concurrentRequests} concurrent requests per instance`;
34799
+ }
34800
+ function scaleText(view) {
34801
+ return [
34802
+ `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(", ")}.`,
34803
+ ...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"}`)
34804
+ ].join("\n");
34805
+ }
34806
+ function integer(value, name2) {
34807
+ if (value === void 0) return void 0;
34808
+ const number5 = Number(value);
34809
+ if (!/^\d+$/.test(value) || !Number.isSafeInteger(number5)) throw new Error(`${name2} takes a whole number.`);
34810
+ return number5;
34811
+ }
34812
+ async function appScale(call2, appId, args2) {
34813
+ const value = (name2) => {
34814
+ const index = args2.indexOf(name2);
34815
+ return index >= 0 ? args2[index + 1] : void 0;
34816
+ };
34817
+ const takesValue = /* @__PURE__ */ new Set(["--size", "--instances", "--min", "--concurrency"]);
34818
+ const positional = args2.filter((arg, index) => !arg.startsWith("--") && !takesValue.has(args2[index - 1] ?? ""));
34819
+ const known = /* @__PURE__ */ new Set([...takesValue, "--always-on", "--scale-to-zero", "--json"]);
34820
+ const unknown2 = args2.find((arg) => arg.startsWith("--") && !known.has(arg));
34821
+ if (unknown2 || positional.length > 1) throw new Error(scaleUsage);
34822
+ const path = `/apps/${appId}/scale`;
34823
+ const view = await call2(path);
34824
+ const [target] = positional;
34825
+ const size = value("--size")?.toUpperCase(), max = integer(value("--instances"), "--instances"), concurrency = integer(value("--concurrency"), "--concurrency");
34826
+ let min = integer(value("--min"), "--min");
34827
+ if (args2.includes("--always-on") && args2.includes("--scale-to-zero")) throw new Error("Use either --always-on or --scale-to-zero.");
34828
+ const changes = size !== void 0 || max !== void 0 || min !== void 0 || concurrency !== void 0 || args2.includes("--always-on") || args2.includes("--scale-to-zero");
34829
+ if (!target) {
34830
+ if (changes) throw new Error("Name the environment to scale, for example backify scale production --instances 5.");
34831
+ return { value: view, text: scaleText(view) };
34832
+ }
34833
+ const wanted = target.toLowerCase();
34834
+ const environment = view.environments.find((item) => item.id.toLowerCase() === wanted || item.name.toLowerCase() === wanted) ?? (() => {
34835
+ const byKind = view.environments.filter((item) => item.kind === wanted);
34836
+ return byKind.length === 1 ? byKind[0] : void 0;
34837
+ })();
34838
+ if (!environment) throw new Error(`No environment named ${target}. Environments: ${view.environments.map((item) => item.name).join(", ") || "none"}.`);
34839
+ if (!changes) return { value: environment, text: `${environment.name}: ${scaleLine(environment.scale, view.sizes)}` };
34840
+ 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(", ")}.`);
34841
+ const maxReplicas = max ?? environment.scale.maxReplicas;
34842
+ if (args2.includes("--scale-to-zero")) min = 0;
34843
+ if (args2.includes("--always-on")) min = Math.max(1, min ?? environment.scale.minReplicas);
34844
+ const minReplicas = min ?? Math.min(environment.scale.minReplicas, maxReplicas);
34845
+ const body = { size: size ?? environment.scale.size, minReplicas, maxReplicas, concurrentRequests: concurrency ?? environment.scale.concurrentRequests };
34846
+ const result = await call2(`${path}/${environment.id}`, { method: "PUT", headers: json2, body: JSON.stringify(body) });
34847
+ const restart = result.operationId ? ` The live version restarts at the new scale (operation ${result.operationId}; follow it with backify operation ${result.operationId} --wait).` : "";
34848
+ return { value: result, text: `Saved. ${result.environment.name}: ${scaleLine(result.environment.scale, view.sizes)}.${restart}` };
34849
+ }
34850
+
34851
+ // src/index.ts
34119
34852
  init_updates();
34120
34853
  init_protection2();
34121
34854
 
@@ -34132,10 +34865,10 @@ async function pairingCode(args2, input) {
34132
34865
  const chunks = [];
34133
34866
  let size = 0;
34134
34867
  for await (const chunk of input) {
34135
- const bytes = Buffer.from(chunk);
34136
- size += bytes.length;
34868
+ const bytes2 = Buffer.from(chunk);
34869
+ size += bytes2.length;
34137
34870
  if (size > 256) throw new Error("Invalid pairing input; expected one 64-character hexadecimal code.");
34138
- chunks.push(bytes);
34871
+ chunks.push(bytes2);
34139
34872
  }
34140
34873
  code = Buffer.concat(chunks).toString("utf8").trim();
34141
34874
  } else {
@@ -34292,9 +35025,9 @@ function reconnectingApiClient(session, reconnect2, transport = fetch) {
34292
35025
  init_development();
34293
35026
  init_setup();
34294
35027
  init_dist();
34295
- import { readFileSync as readFileSync24, existsSync as existsSync19, rmSync as rmSync5 } from "node:fs";
35028
+ import { readFileSync as readFileSync24, writeFileSync as writeFileSync15, existsSync as existsSync19, rmSync as rmSync5 } from "node:fs";
34296
35029
  import { homedir as homedir3 } from "node:os";
34297
- import { join as join21 } from "node:path";
35030
+ import { basename as basename4, join as join21 } from "node:path";
34298
35031
  import { spawn as spawn5 } from "node:child_process";
34299
35032
  var [command, ...args] = process.argv.slice(2);
34300
35033
  var configPath = join21(homedir3(), ".backify.json");
@@ -34339,6 +35072,7 @@ var help = [
34339
35072
  "Apps: new <name> [--template web|api|worker] [--dir <directory>] | lock [--check] | check [--lockfile-only] | dev [--port <port>]",
34340
35073
  "Setup: init | sync | doctor [--environment] | upgrade [--json]",
34341
35074
  "Account: signup [--name <organization>] [--plan <plan>] | login | logout | connect | disconnect | status | apps",
35075
+ " notifications [list [--action|--unread] | summary | read <id>|--all | dismiss <id> | preferences [set <category> --email on|off|default --in-app on|off|default]] (backify notifications --help)",
34342
35076
  "Coding: tools configure --agent <tool> [--transport http|stdio] [--config <path>] [--dry-run] | mcp [--organization <organization-id>]",
34343
35077
  "Org admin: ops search [<query>] | ops describe <operation-id> | ops get|run <operation-id> [--param <name>=<value>] [--body <file>] [--yes] [--organization <id>] [--json]",
34344
35078
  "SSO: sso [guide <provider> | connections add|update|remove | test|on|off|sign-ins <connection-id> | domains | require|unrequire <domain-id> | break-glass | group-sync | mappings | scim] (backify sso --help)",
@@ -34351,9 +35085,11 @@ var help = [
34351
35085
  " Releases move prototype -> preview -> production through the activated environments (backify environments --help)",
34352
35086
  " hosting [--json] shows targets, environments and resources, marking kept ones | rollback <deployment-id> [--yes] (a rollback never restores the database)",
34353
35087
  "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)",
35088
+ "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
35089
  "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)",
35090
+ " monitoring widgets | capabilities [--range 24h|7d|30d] | dashboards [create|update|delete|reset] [--organization|--workspace <id>] (widget catalog, capacity and forecasts, monitoring pages)",
34355
35091
  "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",
35092
+ "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
35093
  "",
34358
35094
  "Docs: https://docs.backify.dev/"
34359
35095
  ].join("\n");
@@ -34393,7 +35129,7 @@ async function main() {
34393
35129
  console.log(help);
34394
35130
  return;
34395
35131
  }
34396
- switch (command) {
35132
+ switch (command === "apps" && args[0] === "owner" ? "app-owner" : command) {
34397
35133
  case "version":
34398
35134
  case "--version":
34399
35135
  case "-v": {
@@ -34419,7 +35155,8 @@ async function main() {
34419
35155
  case "billing":
34420
35156
  case "members":
34421
35157
  case "costs":
34422
- case "teams": {
35158
+ case "teams":
35159
+ case "app-owner": {
34423
35160
  const { OpsError: OpsError2, terminalConfirm: terminalConfirm2 } = await Promise.resolve().then(() => (init_ops(), ops_exports));
34424
35161
  const { runTaskCommand: runTaskCommand2, taskHelp: taskHelp2 } = await Promise.resolve().then(() => (init_tasks(), tasks_exports));
34425
35162
  if (args.includes("--help") || command === "task" && !args.length) {
@@ -34430,7 +35167,7 @@ async function main() {
34430
35167
  const controller = new AbortController(), stop = () => controller.abort();
34431
35168
  process.once("SIGINT", stop);
34432
35169
  process.once("SIGTERM", stop);
34433
- const json6 = args.includes("--json");
35170
+ const json7 = args.includes("--json");
34434
35171
  try {
34435
35172
  const { result } = await runTaskCommand2(command, args, {
34436
35173
  configPath,
@@ -34442,10 +35179,10 @@ async function main() {
34442
35179
  progress: (message) => console.error(message),
34443
35180
  signal: controller.signal
34444
35181
  });
34445
- console.log(json6 ? JSON.stringify(result.value, null, 2) : result.text);
35182
+ console.log(json7 ? JSON.stringify(result.value, null, 2) : result.text);
34446
35183
  if (result.exitCode !== void 0) process.exitCode = result.exitCode;
34447
35184
  } catch (error2) {
34448
- if (!(error2 instanceof OpsError2) || !json6) throw error2;
35185
+ if (!(error2 instanceof OpsError2) || !json7) throw error2;
34449
35186
  console.log(JSON.stringify({ schemaVersion: 1, status: "failed", exitCode: 1, error: error2.message, code: error2.code, ...error2.details }, null, 2));
34450
35187
  process.exitCode = 1;
34451
35188
  } finally {
@@ -34461,7 +35198,7 @@ async function main() {
34461
35198
  console.log(ssoHelp2);
34462
35199
  break;
34463
35200
  }
34464
- const json6 = args.includes("--json");
35201
+ const json7 = args.includes("--json");
34465
35202
  try {
34466
35203
  const { result } = await runSsoCommand2(args, {
34467
35204
  configPath,
@@ -34472,10 +35209,10 @@ async function main() {
34472
35209
  openBrowser,
34473
35210
  progress: (message) => console.error(message)
34474
35211
  });
34475
- console.log(json6 ? JSON.stringify(result.value, null, 2) : result.text);
35212
+ console.log(json7 ? JSON.stringify(result.value, null, 2) : result.text);
34476
35213
  if (result.exitCode !== void 0) process.exitCode = result.exitCode;
34477
35214
  } catch (error2) {
34478
- if (!(error2 instanceof OpsError2) || !json6) throw error2;
35215
+ if (!(error2 instanceof OpsError2) || !json7) throw error2;
34479
35216
  console.log(JSON.stringify({ schemaVersion: 1, status: "failed", exitCode: 1, error: error2.message, code: error2.code, ...error2.details }, null, 2));
34480
35217
  process.exitCode = 1;
34481
35218
  }
@@ -34527,7 +35264,7 @@ async function main() {
34527
35264
  if (args[0] === "identity") {
34528
35265
  const identity = await Promise.resolve().then(() => (init_auth_identity(), auth_identity_exports));
34529
35266
  const { CommandError: CommandError2 } = await Promise.resolve().then(() => (init_release_flow(), release_flow_exports));
34530
- const json6 = args.includes("--json");
35267
+ const json7 = args.includes("--json");
34531
35268
  try {
34532
35269
  const options2 = identity.authIdentityArguments(args.slice(1));
34533
35270
  if (options2 === "help") {
@@ -34535,10 +35272,10 @@ async function main() {
34535
35272
  break;
34536
35273
  }
34537
35274
  const result = await identity.runAuthIdentity(call, applicationGuid(option("--app") ?? projectApplication()), options2);
34538
- console.log(json6 ? JSON.stringify(result.value, null, 2) : result.text);
35275
+ console.log(json7 ? JSON.stringify(result.value, null, 2) : result.text);
34539
35276
  if (result.exitCode !== void 0) process.exitCode = result.exitCode;
34540
35277
  } catch (error2) {
34541
- if (!(error2 instanceof CommandError2) || !json6) throw error2;
35278
+ if (!(error2 instanceof CommandError2) || !json7) throw error2;
34542
35279
  console.log(JSON.stringify({ schemaVersion: 1, status: "failed", exitCode: 1, error: error2.message, code: error2.code, ...error2.details }, null, 2));
34543
35280
  process.exitCode = 1;
34544
35281
  }
@@ -34856,7 +35593,7 @@ Next: ${here ? "" : `cd ${directory} && `}npm install && npm run dev`);
34856
35593
  case "promote": {
34857
35594
  const flow = await Promise.resolve().then(() => (init_release_flow(), release_flow_exports));
34858
35595
  const { terminalConfirm: terminalConfirm2 } = await Promise.resolve().then(() => (init_ops(), ops_exports));
34859
- const json6 = args.includes("--json");
35596
+ const json7 = args.includes("--json");
34860
35597
  try {
34861
35598
  const options = command === "environments" ? flow.environmentsArguments(args) : command === "promote" ? flow.promoteArguments(args) : args.includes("--help") || args.includes("-h") ? "help" : void 0;
34862
35599
  if (options === "help") {
@@ -34866,10 +35603,10 @@ Next: ${here ? "" : `cd ${directory} && `}npm install && npm run dev`);
34866
35603
  if (command === "release-flow" && args.some((value, index) => value !== "--json" && value !== "--app" && args[index - 1] !== "--app")) throw new Error(flow.releaseFlowHelp);
34867
35604
  const application = applicationGuid(option("--app") ?? projectApplication()), context2 = { confirm: terminalConfirm2() };
34868
35605
  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);
35606
+ console.log(json7 ? JSON.stringify(result.value, null, 2) : result.text);
34870
35607
  if (result.exitCode !== void 0) process.exitCode = result.exitCode;
34871
35608
  } catch (error2) {
34872
- if (!(error2 instanceof flow.CommandError) || !json6) throw error2;
35609
+ if (!(error2 instanceof flow.CommandError) || !json7) throw error2;
34873
35610
  console.log(JSON.stringify({ schemaVersion: 1, status: "failed", exitCode: 1, error: error2.message, code: error2.code, ...error2.details }, null, 2));
34874
35611
  process.exitCode = 1;
34875
35612
  }
@@ -34880,7 +35617,7 @@ Next: ${here ? "" : `cd ${directory} && `}npm install && npm run dev`);
34880
35617
  const hostingModule = await Promise.resolve().then(() => (init_hosting(), hosting_exports));
34881
35618
  const { CommandError: CommandError2 } = await Promise.resolve().then(() => (init_release_flow(), release_flow_exports));
34882
35619
  const { terminalConfirm: terminalConfirm2 } = await Promise.resolve().then(() => (init_ops(), ops_exports));
34883
- const json6 = args.includes("--json");
35620
+ const json7 = args.includes("--json");
34884
35621
  try {
34885
35622
  const options = command === "hosting" ? hostingModule.hostingArguments(args) : hostingModule.rollbackArguments(args);
34886
35623
  if (options === "help") {
@@ -34889,9 +35626,9 @@ Next: ${here ? "" : `cd ${directory} && `}npm install && npm run dev`);
34889
35626
  }
34890
35627
  const application = applicationGuid(option("--app") ?? projectApplication());
34891
35628
  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);
35629
+ console.log(json7 ? JSON.stringify(result.value, null, 2) : result.text);
34893
35630
  } catch (error2) {
34894
- if (!(error2 instanceof CommandError2) || !json6) throw error2;
35631
+ if (!(error2 instanceof CommandError2) || !json7) throw error2;
34895
35632
  console.log(JSON.stringify({ schemaVersion: 1, status: "failed", exitCode: 1, error: error2.message, code: error2.code, ...error2.details }, null, 2));
34896
35633
  process.exitCode = 1;
34897
35634
  }
@@ -34901,7 +35638,7 @@ Next: ${here ? "" : `cd ${directory} && `}npm install && npm run dev`);
34901
35638
  const handoff2 = await Promise.resolve().then(() => (init_handoff(), handoff_exports));
34902
35639
  const { CommandError: CommandError2 } = await Promise.resolve().then(() => (init_release_flow(), release_flow_exports));
34903
35640
  const { terminalConfirm: terminalConfirm2 } = await Promise.resolve().then(() => (init_ops(), ops_exports));
34904
- const json6 = args.includes("--json");
35641
+ const json7 = args.includes("--json");
34905
35642
  try {
34906
35643
  const options = handoff2.handoffArguments(args);
34907
35644
  if (options === "help") {
@@ -34909,10 +35646,10 @@ Next: ${here ? "" : `cd ${directory} && `}npm install && npm run dev`);
34909
35646
  break;
34910
35647
  }
34911
35648
  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);
35649
+ console.log(json7 ? JSON.stringify(result.value, null, 2) : result.text);
34913
35650
  if (result.exitCode !== void 0) process.exitCode = result.exitCode;
34914
35651
  } catch (error2) {
34915
- if (!(error2 instanceof CommandError2) || !json6) throw error2;
35652
+ if (!(error2 instanceof CommandError2) || !json7) throw error2;
34916
35653
  console.log(JSON.stringify({ schemaVersion: 1, status: "failed", exitCode: 1, error: error2.message, code: error2.code, ...error2.details }, null, 2));
34917
35654
  process.exitCode = 1;
34918
35655
  }
@@ -34920,7 +35657,7 @@ Next: ${here ? "" : `cd ${directory} && `}npm install && npm run dev`);
34920
35657
  }
34921
35658
  case "logs": {
34922
35659
  const history = await Promise.resolve().then(() => (init_logs_history(), logs_history_exports));
34923
- const json6 = args.includes("--json");
35660
+ const json7 = args.includes("--json");
34924
35661
  try {
34925
35662
  const options = history.logsArguments(args);
34926
35663
  if (options === "help") {
@@ -34929,10 +35666,10 @@ Next: ${here ? "" : `cd ${directory} && `}npm install && npm run dev`);
34929
35666
  }
34930
35667
  const application = applicationGuid(option("--app") ?? projectApplication());
34931
35668
  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);
35669
+ console.log(json7 ? JSON.stringify(result.value, null, 2) : result.text);
34933
35670
  } catch (error2) {
34934
35671
  const flow = await Promise.resolve().then(() => (init_release_flow(), release_flow_exports));
34935
- if (!(error2 instanceof flow.CommandError) || !json6) throw error2;
35672
+ if (!(error2 instanceof flow.CommandError) || !json7) throw error2;
34936
35673
  console.log(JSON.stringify({ schemaVersion: 1, status: "failed", exitCode: 1, error: error2.message, code: error2.code, ...error2.details }, null, 2));
34937
35674
  process.exitCode = 1;
34938
35675
  }
@@ -34941,17 +35678,26 @@ Next: ${here ? "" : `cd ${directory} && `}npm install && npm run dev`);
34941
35678
  case "monitoring":
34942
35679
  case "operation": {
34943
35680
  const flow = await Promise.resolve().then(() => (init_release_flow(), release_flow_exports));
34944
- const json6 = args.includes("--json");
35681
+ const json7 = args.includes("--json");
34945
35682
  try {
34946
35683
  let result;
34947
35684
  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);
35685
+ const dashboards = await Promise.resolve().then(() => (init_monitoring_dashboards(), monitoring_dashboards_exports));
35686
+ const pages = dashboards.monitoringDashboardArguments(args);
35687
+ if (pages === "help") {
35688
+ console.log(dashboards.monitoringDashboardsHelp);
34952
35689
  break;
34953
35690
  }
34954
- result = await monitoring.runMonitoring(call, applicationGuid(option("--app") ?? projectApplication()), options);
35691
+ if (pages) result = await dashboards.runMonitoringDashboards(call, pages.action === "widgets" || "scope" in pages && pages.scope ? "" : applicationGuid(option("--app") ?? projectApplication()), pages);
35692
+ else {
35693
+ const monitoring = await Promise.resolve().then(() => (init_monitoring(), monitoring_exports));
35694
+ const options = monitoring.monitoringArguments(args);
35695
+ if (options === "help") {
35696
+ console.log(monitoring.monitoringHelp + "\n\n" + dashboards.monitoringDashboardsHelp);
35697
+ break;
35698
+ }
35699
+ result = await monitoring.runMonitoring(call, applicationGuid(option("--app") ?? projectApplication()), options);
35700
+ }
34955
35701
  } else {
34956
35702
  const progress = await Promise.resolve().then(() => (init_operation_progress(), operation_progress_exports));
34957
35703
  const options = progress.operationArguments(args);
@@ -34959,12 +35705,12 @@ Next: ${here ? "" : `cd ${directory} && `}npm install && npm run dev`);
34959
35705
  console.log(progress.operationHelp);
34960
35706
  break;
34961
35707
  }
34962
- result = await progress.runOperation(call, options, { progress: json6 ? void 0 : (text2) => console.log(text2) });
35708
+ result = await progress.runOperation(call, options, { progress: json7 ? void 0 : (text2) => console.log(text2) });
34963
35709
  }
34964
- console.log(json6 ? JSON.stringify(result.value, null, 2) : result.text);
35710
+ console.log(json7 ? JSON.stringify(result.value, null, 2) : result.text);
34965
35711
  if (result.exitCode !== void 0) process.exitCode = result.exitCode;
34966
35712
  } catch (error2) {
34967
- if (!(error2 instanceof flow.CommandError) || !json6) throw error2;
35713
+ if (!(error2 instanceof flow.CommandError) || !json7) throw error2;
34968
35714
  console.log(JSON.stringify({ schemaVersion: 1, status: "failed", exitCode: 1, error: error2.message, code: error2.code, ...error2.details }, null, 2));
34969
35715
  process.exitCode = 1;
34970
35716
  }
@@ -34978,17 +35724,76 @@ Next: ${here ? "" : `cd ${directory} && `}npm install && npm run dev`);
34978
35724
  break;
34979
35725
  }
34980
35726
  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.";
35727
+ if (!args.length || args.includes("--help")) {
35728
+ console.log(databaseDataUsage);
35729
+ if (!args.length) process.exitCode = 2;
35730
+ break;
35731
+ }
35732
+ const request = databaseCall(applicationGuid(option("--app") ?? projectApplication()), args, (path) => readFileSync24(path, "utf8"));
35733
+ console.log(JSON.stringify(await call(request.path, { method: request.method, body: request.body ? JSON.stringify(request.body) : void 0 }), null, 2));
35734
+ break;
35735
+ }
35736
+ case "storage": {
35737
+ if (!args.length || args.includes("--help")) {
35738
+ console.log(storageUsage);
35739
+ if (!args.length) process.exitCode = 2;
35740
+ break;
35741
+ }
35742
+ const request = storageCall(applicationGuid(option("--app") ?? projectApplication()), args);
35743
+ if (request.upload) {
35744
+ const data = readFileSync24(request.upload.file);
35745
+ if (data.byteLength > 100 * 1024 * 1024) throw new Error(request.upload.file + " is larger than 100 MiB, the upload limit.");
35746
+ const form = new FormData();
35747
+ form.append("file", new Blob([data]), basename4(request.upload.file));
35748
+ console.log(JSON.stringify(await call(request.path, { method: request.method, body: form }), null, 2));
35749
+ } else if (request.download) {
35750
+ const bytes2 = await call(request.path, { headers: { accept: "application/octet-stream" } });
35751
+ const out = request.download.out ?? basename4(request.download.key);
35752
+ writeFileSync15(out, bytes2);
35753
+ console.log("Saved " + request.download.key + " to " + out + " (" + bytes2.byteLength + " bytes).");
35754
+ } else {
35755
+ const result = await call(request.path, { method: request.method, body: request.body ? JSON.stringify(request.body) : void 0 });
35756
+ 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));
35757
+ }
35758
+ break;
35759
+ }
35760
+ case "backend": {
35761
+ if (!args.length || args.includes("--help")) {
35762
+ console.log(backendUsage);
35763
+ if (!args.length) process.exitCode = 2;
35764
+ break;
35765
+ }
35766
+ const request = backendCall(applicationGuid(option("--app") ?? projectApplication()), args);
35767
+ const result = await call(request.path);
35768
+ if (args[0] === "routes") console.log(routeLines(result.routes ?? []).join("\n") || "This release declares no endpoints.");
35769
+ else if (request.download?.out) {
35770
+ writeFileSync15(request.download.out, JSON.stringify(result, null, 2) + "\n");
35771
+ console.log("Saved the OpenAPI document to " + request.download.out + ".");
35772
+ } else console.log(JSON.stringify(result, null, 2));
35773
+ break;
35774
+ }
35775
+ case "jobs": {
35776
+ if (!args.length || args.includes("--help")) {
35777
+ console.log(jobsUsage);
35778
+ if (!args.length) process.exitCode = 2;
35779
+ break;
35780
+ }
35781
+ const request = jobsCall(applicationGuid(option("--app") ?? projectApplication()), args);
35782
+ console.log(JSON.stringify(await call(request.path), null, 2));
35783
+ break;
35784
+ }
35785
+ case "notifications": {
34982
35786
  if (args.includes("--help")) {
34983
- console.log(usage);
35787
+ console.log(notificationsUsage);
34984
35788
  break;
34985
35789
  }
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));
35790
+ if (!userConfig.token) throw new Error("Sign in first: backify login");
35791
+ const account = apiClient({ token: userConfig.token, organizationId: userConfig.organizationId ?? "", apiUrl: process.env.BACKIFY_API_URL ?? userConfig.apiUrl ?? "https://api.backify.dev/api" });
35792
+ const request = notificationCall(args);
35793
+ const body = request.preferences ? mergePreference((await account(request.path)).preferences, request.preferences) : request.body;
35794
+ const result = await account(request.path, { method: request.method, body: body ? JSON.stringify(body) : void 0 });
35795
+ const listing = request.method === "GET" && request.path.startsWith("/account/notifications?");
35796
+ console.log(listing && !args.includes("--json") ? formatNotifications(result) : JSON.stringify(result, null, 2));
34992
35797
  break;
34993
35798
  }
34994
35799
  case "privacy": {
@@ -35033,6 +35838,16 @@ Next: ${here ? "" : `cd ${directory} && `}npm install && npm run dev`);
35033
35838
  process.exitCode = result.exitCode;
35034
35839
  break;
35035
35840
  }
35841
+ case "scale": {
35842
+ if (args.includes("--help")) {
35843
+ console.log(scaleUsage);
35844
+ break;
35845
+ }
35846
+ const appId = applicationGuid(option("--app") ?? projectApplication());
35847
+ const result = await appScale(call, appId, args.filter((value, index) => value !== "--app" && args[index - 1] !== "--app"));
35848
+ console.log(args.includes("--json") ? JSON.stringify(result.value, null, 2) : result.text);
35849
+ break;
35850
+ }
35036
35851
  case "patches": {
35037
35852
  if (args.includes("--help")) {
35038
35853
  console.log(patchesUsage);