@dereekb/dbx-cli 13.11.10 → 13.11.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.esm.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { existsSync, mkdirSync, writeFileSync, appendFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
3
  export { CALL_MODEL_APP_FUNCTION_KEY } from '@dereekb/firebase';
4
- import { expirationDetails, generatePkceCodeVerifier, generatePkceCodeChallenge, noop, MS_IN_SECOND } from '@dereekb/util';
4
+ import { performAsyncTasks, compareStrings, expirationDetails, generatePkceCodeVerifier, generatePkceCodeChallenge, noop, MS_IN_SECOND } from '@dereekb/util';
5
5
  import { durationDataToMilliseconds, parseDurationString } from '@dereekb/date';
6
6
  import { readJsonFile, writeJsonFile, createMemoizedJsonFileAsyncKeyedValueCache } from '@dereekb/nestjs';
7
7
  import { homedir } from 'node:os';
@@ -9,13 +9,13 @@ import { createInterface } from 'node:readline';
9
9
  import yargs from 'yargs';
10
10
  import { hideBin } from 'yargs/helpers';
11
11
 
12
- function _array_like_to_array$8(arr, len) {
12
+ function _array_like_to_array$b(arr, len) {
13
13
  if (len == null || len > arr.length) len = arr.length;
14
14
  for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
15
15
  return arr2;
16
16
  }
17
- function _array_without_holes$5(arr) {
18
- if (Array.isArray(arr)) return _array_like_to_array$8(arr);
17
+ function _array_without_holes$8(arr) {
18
+ if (Array.isArray(arr)) return _array_like_to_array$b(arr);
19
19
  }
20
20
  function _assert_this_initialized(self) {
21
21
  if (self === void 0) {
@@ -49,7 +49,7 @@ function _construct(Parent, args, Class) {
49
49
  }
50
50
  return _construct.apply(null, arguments);
51
51
  }
52
- function _define_property$c(obj, key, value) {
52
+ function _define_property$d(obj, key, value) {
53
53
  if (key in obj) {
54
54
  Object.defineProperty(obj, key, {
55
55
  value: value,
@@ -92,13 +92,13 @@ function _instanceof$6(left, right) {
92
92
  function _is_native_function(fn) {
93
93
  return Function.toString.call(fn).indexOf("[native code]") !== -1;
94
94
  }
95
- function _iterable_to_array$5(iter) {
95
+ function _iterable_to_array$8(iter) {
96
96
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
97
97
  }
98
- function _non_iterable_spread$5() {
98
+ function _non_iterable_spread$8() {
99
99
  throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
100
100
  }
101
- function _object_spread$c(target) {
101
+ function _object_spread$d(target) {
102
102
  for(var i = 1; i < arguments.length; i++){
103
103
  var source = arguments[i] != null ? arguments[i] : {};
104
104
  var ownKeys = Object.keys(source);
@@ -108,7 +108,7 @@ function _object_spread$c(target) {
108
108
  }));
109
109
  }
110
110
  ownKeys.forEach(function(key) {
111
- _define_property$c(target, key, source[key]);
111
+ _define_property$d(target, key, source[key]);
112
112
  });
113
113
  }
114
114
  return target;
@@ -126,20 +126,20 @@ function _set_prototype_of(o, p) {
126
126
  };
127
127
  return _set_prototype_of(o, p);
128
128
  }
129
- function _to_consumable_array$5(arr) {
130
- return _array_without_holes$5(arr) || _iterable_to_array$5(arr) || _unsupported_iterable_to_array$8(arr) || _non_iterable_spread$5();
129
+ function _to_consumable_array$8(arr) {
130
+ return _array_without_holes$8(arr) || _iterable_to_array$8(arr) || _unsupported_iterable_to_array$b(arr) || _non_iterable_spread$8();
131
131
  }
132
132
  function _type_of$3(obj) {
133
133
  "@swc/helpers - typeof";
134
134
  return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
135
135
  }
136
- function _unsupported_iterable_to_array$8(o, minLen) {
136
+ function _unsupported_iterable_to_array$b(o, minLen) {
137
137
  if (!o) return;
138
- if (typeof o === "string") return _array_like_to_array$8(o, minLen);
138
+ if (typeof o === "string") return _array_like_to_array$b(o, minLen);
139
139
  var n = Object.prototype.toString.call(o).slice(8, -1);
140
140
  if (n === "Object" && o.constructor) n = o.constructor.name;
141
141
  if (n === "Map" || n === "Set") return Array.from(n);
142
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$8(o, minLen);
142
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$b(o, minLen);
143
143
  }
144
144
  function _wrap_native_super(Class) {
145
145
  var _cache = typeof Map === "function" ? new Map() : undefined;
@@ -188,7 +188,7 @@ function _is_native_reflect_construct() {
188
188
  /id_token[=:]\s*\S+/gi
189
189
  ];
190
190
  var _outputOptions = {};
191
- var _secretPatterns = _to_consumable_array$5(DEFAULT_CLI_SECRET_PATTERNS);
191
+ var _secretPatterns = _to_consumable_array$8(DEFAULT_CLI_SECRET_PATTERNS);
192
192
  var _errorMapper;
193
193
  /**
194
194
  * Configures output options from parsed CLI arguments.
@@ -294,7 +294,7 @@ function dumpResponse(data, meta) {
294
294
  if (!filePath) {
295
295
  return;
296
296
  }
297
- var content = _object_spread$c({
297
+ var content = _object_spread$d({
298
298
  ok: true,
299
299
  data: data
300
300
  }, meta ? {
@@ -362,7 +362,7 @@ function pickFromObject(obj, fields) {
362
362
  */ function outputResult(data, meta) {
363
363
  dumpResponse(data, meta);
364
364
  var outputData = _outputOptions.pick ? pickFields(data, _outputOptions.pick) : data;
365
- var output = _object_spread$c({
365
+ var output = _object_spread$d({
366
366
  ok: true,
367
367
  data: outputData
368
368
  }, meta ? {
@@ -389,7 +389,7 @@ function pickFromObject(obj, fields) {
389
389
  var _this;
390
390
  _this = _call_super(this, CliError, [
391
391
  input.message
392
- ]), _define_property$c(_this, "code", void 0), _define_property$c(_this, "suggestion", void 0);
392
+ ]), _define_property$d(_this, "code", void 0), _define_property$d(_this, "suggestion", void 0);
393
393
  _this.name = 'CliError';
394
394
  _this.code = input.code;
395
395
  _this.suggestion = input.suggestion;
@@ -419,7 +419,7 @@ function pickFromObject(obj, fields) {
419
419
  }
420
420
  }
421
421
  if (_instanceof$6(error, CliError)) {
422
- return _object_spread$c({
422
+ return _object_spread$d({
423
423
  ok: false,
424
424
  error: sanitizeString(error.message),
425
425
  code: error.code
@@ -441,7 +441,7 @@ function pickFromObject(obj, fields) {
441
441
  };
442
442
  }
443
443
 
444
- function asyncGeneratorStep$h(gen, resolve, reject, _next, _throw, key, arg) {
444
+ function asyncGeneratorStep$j(gen, resolve, reject, _next, _throw, key, arg) {
445
445
  try {
446
446
  var info = gen[key](arg);
447
447
  var value = info.value;
@@ -455,16 +455,16 @@ function asyncGeneratorStep$h(gen, resolve, reject, _next, _throw, key, arg) {
455
455
  Promise.resolve(value).then(_next, _throw);
456
456
  }
457
457
  }
458
- function _async_to_generator$h(fn) {
458
+ function _async_to_generator$j(fn) {
459
459
  return function() {
460
460
  var self = this, args = arguments;
461
461
  return new Promise(function(resolve, reject) {
462
462
  var gen = fn.apply(self, args);
463
463
  function _next(value) {
464
- asyncGeneratorStep$h(gen, resolve, reject, _next, _throw, "next", value);
464
+ asyncGeneratorStep$j(gen, resolve, reject, _next, _throw, "next", value);
465
465
  }
466
466
  function _throw(err) {
467
- asyncGeneratorStep$h(gen, resolve, reject, _next, _throw, "throw", err);
467
+ asyncGeneratorStep$j(gen, resolve, reject, _next, _throw, "throw", err);
468
468
  }
469
469
  _next(undefined);
470
470
  });
@@ -474,7 +474,7 @@ function _type_of$2(obj) {
474
474
  "@swc/helpers - typeof";
475
475
  return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
476
476
  }
477
- function _ts_generator$h(thisArg, body) {
477
+ function _ts_generator$j(thisArg, body) {
478
478
  var f, y, t, _ = {
479
479
  label: 0,
480
480
  sent: function() {
@@ -590,9 +590,9 @@ var MAX_MODEL_ACCESS_MULTI_READ_KEYS = 50;
590
590
  * @param input.fetcher - Optional fetch implementation override (used by tests).
591
591
  * @returns The parsed JSON response body cast to `R`.
592
592
  */ function callModelOverHttp(input) {
593
- return _async_to_generator$h(function() {
593
+ return _async_to_generator$j(function() {
594
594
  var _input_fetcher, fetcher, url, res, text, body, _input_params_call, bodyMessage, messageString, message;
595
- return _ts_generator$h(this, function(_state) {
595
+ return _ts_generator$j(this, function(_state) {
596
596
  switch(_state.label){
597
597
  case 0:
598
598
  fetcher = (_input_fetcher = input.fetcher) !== null && _input_fetcher !== void 0 ? _input_fetcher : fetch;
@@ -655,9 +655,9 @@ var MAX_MODEL_ACCESS_MULTI_READ_KEYS = 50;
655
655
  * @param input - The request envelope describing the API target, access token, model + key, and optional fetch override.
656
656
  * @returns The parsed `{ key, data }` envelope.
657
657
  */ function getModelOverHttp(input) {
658
- return _async_to_generator$h(function() {
658
+ return _async_to_generator$j(function() {
659
659
  var _input_fetcher, fetcher, url, res, _ref, ok, body, fallbackMessage;
660
- return _ts_generator$h(this, function(_state) {
660
+ return _ts_generator$j(this, function(_state) {
661
661
  switch(_state.label){
662
662
  case 0:
663
663
  fetcher = (_input_fetcher = input.fetcher) !== null && _input_fetcher !== void 0 ? _input_fetcher : fetch;
@@ -707,9 +707,9 @@ var MAX_MODEL_ACCESS_MULTI_READ_KEYS = 50;
707
707
  * @param input - The request envelope describing the API target, access token, model, keys, and optional fetch override.
708
708
  * @returns The parsed `{ results, errors }` envelope.
709
709
  */ function getMultipleModelsOverHttp(input) {
710
- return _async_to_generator$h(function() {
710
+ return _async_to_generator$j(function() {
711
711
  var _input_fetcher, fetcher, url, res, _ref, ok, body, fallbackMessage;
712
- return _ts_generator$h(this, function(_state) {
712
+ return _ts_generator$j(this, function(_state) {
713
713
  switch(_state.label){
714
714
  case 0:
715
715
  if (input.keys.length === 0) {
@@ -764,9 +764,9 @@ var MAX_MODEL_ACCESS_MULTI_READ_KEYS = 50;
764
764
  })();
765
765
  }
766
766
  function readJsonResponse(res) {
767
- return _async_to_generator$h(function() {
767
+ return _async_to_generator$j(function() {
768
768
  var text, body;
769
- return _ts_generator$h(this, function(_state) {
769
+ return _ts_generator$j(this, function(_state) {
770
770
  switch(_state.label){
771
771
  case 0:
772
772
  return [
@@ -811,105 +811,1045 @@ function codeForStatus(status) {
811
811
  function trimSlash$1(url) {
812
812
  return url.endsWith('/') ? url.slice(0, -1) : url;
813
813
  }
814
-
814
+
815
+ /**
816
+ * Creates a typed module-level slot.
817
+ *
818
+ * Each CLI exposes its current per-invocation context (auth tokens, API clients, env config, ...)
819
+ * via a slot so command handlers can read it without yargs strict-mode flagging unknown argv keys.
820
+ *
821
+ * Usage:
822
+ * ```ts
823
+ * const slot = createContextSlot<MyCliContext>({ notInitializedMessage: 'Auth middleware did not run.' });
824
+ * // in middleware:
825
+ * slot.set(buildContext(...));
826
+ * // in handler:
827
+ * const ctx = slot.require();
828
+ * ```
829
+ *
830
+ * @param input - Optional slot configuration.
831
+ * @param input.notInitializedMessage - Custom error message thrown by `require()` when the slot is unset.
832
+ * @returns A new {@link ContextSlot} for type `T`.
833
+ * @__NO_SIDE_EFFECTS__
834
+ */ function createContextSlot(input) {
835
+ var _ref;
836
+ var _value;
837
+ var notInitializedMessage = (_ref = input === null || input === void 0 ? void 0 : input.notInitializedMessage) !== null && _ref !== void 0 ? _ref : 'Context slot has not been initialized.';
838
+ return {
839
+ set: function set(value) {
840
+ _value = value;
841
+ },
842
+ get: function get() {
843
+ return _value;
844
+ },
845
+ require: function require() {
846
+ if (_value == null) {
847
+ throw new Error(notInitializedMessage);
848
+ }
849
+ return _value;
850
+ }
851
+ };
852
+ }
853
+
854
+ /**
855
+ * Module-level slot holding the {@link CliContext} for the current invocation.
856
+ *
857
+ * Stored here instead of on argv so that yargs strict-mode does not flag it as an unknown argument.
858
+ */ var _cliContextSlot = createContextSlot({
859
+ notInitializedMessage: 'CLI context not initialized — auth middleware must run before this command.'
860
+ });
861
+ var setCliContext = _cliContextSlot.set;
862
+ var getCliContext = _cliContextSlot.get;
863
+ /**
864
+ * Returns the current {@link CliContext} or throws — for use in command handlers that require auth.
865
+ */ var requireCliContext = _cliContextSlot.require;
866
+ /**
867
+ * Builds a {@link CliContext} for the current invocation.
868
+ *
869
+ * Bundles the env config and access token alongside helpers that POST/GET against
870
+ * `<env.apiBaseUrl>/model/*` with the cached Bearer token.
871
+ *
872
+ * @param input - The context inputs.
873
+ * @param input.cliName - The CLI's binary name.
874
+ * @param input.envName - The active env name.
875
+ * @param input.env - The resolved {@link CliEnvConfig} for the active env.
876
+ * @param input.accessToken - The Bearer access token to include on outgoing API calls.
877
+ * @param input.modelManifest - Optional generated {@link CliModelManifest} for key→modelType resolution.
878
+ * @returns The constructed {@link CliContext}.
879
+ * @__NO_SIDE_EFFECTS__
880
+ */ function createCliContext(input) {
881
+ var apiBaseUrl = input.env.apiBaseUrl;
882
+ var accessToken = input.accessToken;
883
+ return {
884
+ cliName: input.cliName,
885
+ envName: input.envName,
886
+ env: input.env,
887
+ accessToken: accessToken,
888
+ modelManifest: input.modelManifest,
889
+ callModel: function callModel(params) {
890
+ return callModelOverHttp({
891
+ apiBaseUrl: apiBaseUrl,
892
+ accessToken: accessToken,
893
+ params: params
894
+ });
895
+ },
896
+ getModel: function getModel(modelType, key) {
897
+ return getModelOverHttp({
898
+ apiBaseUrl: apiBaseUrl,
899
+ accessToken: accessToken,
900
+ modelType: modelType,
901
+ key: key
902
+ });
903
+ },
904
+ getMultipleModels: function getMultipleModels(modelType, keys) {
905
+ return getMultipleModelsOverHttp({
906
+ apiBaseUrl: apiBaseUrl,
907
+ accessToken: accessToken,
908
+ modelType: modelType,
909
+ keys: keys
910
+ });
911
+ }
912
+ };
913
+ }
914
+
915
+ function asyncGeneratorStep$i(gen, resolve, reject, _next, _throw, key, arg) {
916
+ try {
917
+ var info = gen[key](arg);
918
+ var value = info.value;
919
+ } catch (error) {
920
+ reject(error);
921
+ return;
922
+ }
923
+ if (info.done) {
924
+ resolve(value);
925
+ } else {
926
+ Promise.resolve(value).then(_next, _throw);
927
+ }
928
+ }
929
+ function _async_to_generator$i(fn) {
930
+ return function() {
931
+ var self = this, args = arguments;
932
+ return new Promise(function(resolve, reject) {
933
+ var gen = fn.apply(self, args);
934
+ function _next(value) {
935
+ asyncGeneratorStep$i(gen, resolve, reject, _next, _throw, "next", value);
936
+ }
937
+ function _throw(err) {
938
+ asyncGeneratorStep$i(gen, resolve, reject, _next, _throw, "throw", err);
939
+ }
940
+ _next(undefined);
941
+ });
942
+ };
943
+ }
944
+ function _ts_generator$i(thisArg, body) {
945
+ var f, y, t, _ = {
946
+ label: 0,
947
+ sent: function() {
948
+ if (t[0] & 1) throw t[1];
949
+ return t[1];
950
+ },
951
+ trys: [],
952
+ ops: []
953
+ }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
954
+ return d(g, "next", {
955
+ value: verb(0)
956
+ }), d(g, "throw", {
957
+ value: verb(1)
958
+ }), d(g, "return", {
959
+ value: verb(2)
960
+ }), typeof Symbol === "function" && d(g, Symbol.iterator, {
961
+ value: function() {
962
+ return this;
963
+ }
964
+ }), g;
965
+ function verb(n) {
966
+ return function(v) {
967
+ return step([
968
+ n,
969
+ v
970
+ ]);
971
+ };
972
+ }
973
+ function step(op) {
974
+ if (f) throw new TypeError("Generator is already executing.");
975
+ while(g && (g = 0, op[0] && (_ = 0)), _)try {
976
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
977
+ if (y = 0, t) op = [
978
+ op[0] & 2,
979
+ t.value
980
+ ];
981
+ switch(op[0]){
982
+ case 0:
983
+ case 1:
984
+ t = op;
985
+ break;
986
+ case 4:
987
+ _.label++;
988
+ return {
989
+ value: op[1],
990
+ done: false
991
+ };
992
+ case 5:
993
+ _.label++;
994
+ y = op[1];
995
+ op = [
996
+ 0
997
+ ];
998
+ continue;
999
+ case 7:
1000
+ op = _.ops.pop();
1001
+ _.trys.pop();
1002
+ continue;
1003
+ default:
1004
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
1005
+ _ = 0;
1006
+ continue;
1007
+ }
1008
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
1009
+ _.label = op[1];
1010
+ break;
1011
+ }
1012
+ if (op[0] === 6 && _.label < t[1]) {
1013
+ _.label = t[1];
1014
+ t = op;
1015
+ break;
1016
+ }
1017
+ if (t && _.label < t[2]) {
1018
+ _.label = t[2];
1019
+ _.ops.push(op);
1020
+ break;
1021
+ }
1022
+ if (t[2]) _.ops.pop();
1023
+ _.trys.pop();
1024
+ continue;
1025
+ }
1026
+ op = body.call(thisArg, _);
1027
+ } catch (e) {
1028
+ op = [
1029
+ 6,
1030
+ e
1031
+ ];
1032
+ y = 0;
1033
+ } finally{
1034
+ f = t = 0;
1035
+ }
1036
+ if (op[0] & 5) throw op[1];
1037
+ return {
1038
+ value: op[0] ? op[1] : void 0,
1039
+ done: true
1040
+ };
1041
+ }
1042
+ }
1043
+ /**
1044
+ * Wraps an {@link ActionCommandSpec} as a yargs `CommandModule`.
1045
+ *
1046
+ * The returned command:
1047
+ * - Calls {@link requireCliContext} so it fails loudly when auth middleware did not run.
1048
+ * - Invokes `spec.handler({ context, argv })`.
1049
+ * - Pipes the result through `spec.mapResult` when provided.
1050
+ * - Emits the value via {@link outputResult}; emits {@link outputError} + `process.exit(1)` on failure.
1051
+ *
1052
+ * @param spec - The action specification.
1053
+ * @returns The yargs command module ready to be registered under the `action` parent.
1054
+ * @__NO_SIDE_EFFECTS__
1055
+ */ function createActionCommand(spec) {
1056
+ return {
1057
+ command: spec.command,
1058
+ describe: spec.describe,
1059
+ builder: function builder(yargs) {
1060
+ var built = spec.builder ? spec.builder(yargs) : yargs;
1061
+ return spec.helpEpilogue ? built.epilogue(spec.helpEpilogue) : built;
1062
+ },
1063
+ handler: function handler(argv) {
1064
+ return _async_to_generator$i(function() {
1065
+ var context, result, e;
1066
+ return _ts_generator$i(this, function(_state) {
1067
+ switch(_state.label){
1068
+ case 0:
1069
+ _state.trys.push([
1070
+ 0,
1071
+ 2,
1072
+ ,
1073
+ 3
1074
+ ]);
1075
+ context = requireCliContext();
1076
+ return [
1077
+ 4,
1078
+ spec.handler({
1079
+ context: context,
1080
+ argv: argv
1081
+ })
1082
+ ];
1083
+ case 1:
1084
+ result = _state.sent();
1085
+ outputResult(spec.mapResult ? spec.mapResult(result) : result);
1086
+ return [
1087
+ 3,
1088
+ 3
1089
+ ];
1090
+ case 2:
1091
+ e = _state.sent();
1092
+ outputError(e);
1093
+ process.exit(1);
1094
+ return [
1095
+ 3,
1096
+ 3
1097
+ ];
1098
+ case 3:
1099
+ return [
1100
+ 2
1101
+ ];
1102
+ }
1103
+ });
1104
+ })();
1105
+ }
1106
+ };
1107
+ }
1108
+
1109
+ function _array_like_to_array$a(arr, len) {
1110
+ if (len == null || len > arr.length) len = arr.length;
1111
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
1112
+ return arr2;
1113
+ }
1114
+ function _array_with_holes$6(arr) {
1115
+ if (Array.isArray(arr)) return arr;
1116
+ }
1117
+ function _array_without_holes$7(arr) {
1118
+ if (Array.isArray(arr)) return _array_like_to_array$a(arr);
1119
+ }
1120
+ function _iterable_to_array$7(iter) {
1121
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
1122
+ }
1123
+ function _iterable_to_array_limit$6(arr, i) {
1124
+ var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
1125
+ if (_i == null) return;
1126
+ var _arr = [];
1127
+ var _n = true;
1128
+ var _d = false;
1129
+ var _s, _e;
1130
+ try {
1131
+ for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
1132
+ _arr.push(_s.value);
1133
+ if (i && _arr.length === i) break;
1134
+ }
1135
+ } catch (err) {
1136
+ _d = true;
1137
+ _e = err;
1138
+ } finally{
1139
+ try {
1140
+ if (!_n && _i["return"] != null) _i["return"]();
1141
+ } finally{
1142
+ if (_d) throw _e;
1143
+ }
1144
+ }
1145
+ return _arr;
1146
+ }
1147
+ function _non_iterable_rest$6() {
1148
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1149
+ }
1150
+ function _non_iterable_spread$7() {
1151
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1152
+ }
1153
+ function _sliced_to_array$6(arr, i) {
1154
+ return _array_with_holes$6(arr) || _iterable_to_array_limit$6(arr, i) || _unsupported_iterable_to_array$a(arr, i) || _non_iterable_rest$6();
1155
+ }
1156
+ function _to_consumable_array$7(arr) {
1157
+ return _array_without_holes$7(arr) || _iterable_to_array$7(arr) || _unsupported_iterable_to_array$a(arr) || _non_iterable_spread$7();
1158
+ }
1159
+ function _unsupported_iterable_to_array$a(o, minLen) {
1160
+ if (!o) return;
1161
+ if (typeof o === "string") return _array_like_to_array$a(o, minLen);
1162
+ var n = Object.prototype.toString.call(o).slice(8, -1);
1163
+ if (n === "Object" && o.constructor) n = o.constructor.name;
1164
+ if (n === "Map" || n === "Set") return Array.from(n);
1165
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$a(o, minLen);
1166
+ }
1167
+ /**
1168
+ * Default name of the parent command that groups all registered action specs.
1169
+ * Surfaces as `<cli> action <action>` (root) and `<cli> action <model> <action>` (model-scoped).
1170
+ */ var DEFAULT_ACTION_COMMAND_NAME = 'action';
1171
+ /**
1172
+ * Assembles the parent `action` command tree from a list of {@link ActionCommandSpec}s.
1173
+ *
1174
+ * Specs without a `model` are appended as direct subcommands of `action`. Specs with a
1175
+ * `model` are grouped under `action <model> <action>` (mirroring `buildManifestCommands`'
1176
+ * `model <model> <action>` shape) so the model-scoped surface stays browseable.
1177
+ *
1178
+ * @param specs - The action specs registered by the app.
1179
+ * @param options - Optional overrides (e.g. parent command name).
1180
+ * @returns An array containing a single parent `action` command, or empty when no specs were provided.
1181
+ * @__NO_SIDE_EFFECTS__
1182
+ */ function buildActionCommands(specs, options) {
1183
+ var result = [];
1184
+ if (specs.length > 0) {
1185
+ var _ref;
1186
+ var actionCommandName = (_ref = options === null || options === void 0 ? void 0 : options.actionCommandName) !== null && _ref !== void 0 ? _ref : DEFAULT_ACTION_COMMAND_NAME;
1187
+ var rootSpecs = specs.filter(function(s) {
1188
+ return !s.model;
1189
+ });
1190
+ var byModel = new Map();
1191
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1192
+ try {
1193
+ for(var _iterator = specs[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1194
+ var spec = _step.value;
1195
+ if (spec.model) {
1196
+ var list = byModel.get(spec.model);
1197
+ if (list) {
1198
+ list.push(spec);
1199
+ } else {
1200
+ byModel.set(spec.model, [
1201
+ spec
1202
+ ]);
1203
+ }
1204
+ }
1205
+ }
1206
+ } catch (err) {
1207
+ _didIteratorError = true;
1208
+ _iteratorError = err;
1209
+ } finally{
1210
+ try {
1211
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1212
+ _iterator.return();
1213
+ }
1214
+ } finally{
1215
+ if (_didIteratorError) {
1216
+ throw _iteratorError;
1217
+ }
1218
+ }
1219
+ }
1220
+ var sortedModels = _to_consumable_array$7(byModel.entries()).sort(function(param, param1) {
1221
+ var _param = _sliced_to_array$6(param, 1), a = _param[0], _param1 = _sliced_to_array$6(param1, 1), b = _param1[0];
1222
+ return a.localeCompare(b);
1223
+ });
1224
+ result = [
1225
+ {
1226
+ command: "".concat(actionCommandName, " <action>"),
1227
+ describe: "Run a composite action (".concat(specs.length, "). Use `").concat(actionCommandName, " --help` to list them."),
1228
+ builder: function builder(yargs) {
1229
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1230
+ try {
1231
+ for(var _iterator = rootSpecs[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1232
+ var spec = _step.value;
1233
+ yargs.command(createActionCommand(spec));
1234
+ }
1235
+ } catch (err) {
1236
+ _didIteratorError = true;
1237
+ _iteratorError = err;
1238
+ } finally{
1239
+ try {
1240
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1241
+ _iterator.return();
1242
+ }
1243
+ } finally{
1244
+ if (_didIteratorError) {
1245
+ throw _iteratorError;
1246
+ }
1247
+ }
1248
+ }
1249
+ var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
1250
+ try {
1251
+ var _loop = function() {
1252
+ var _step_value = _sliced_to_array$6(_step1.value, 2), model = _step_value[0], modelSpecs = _step_value[1];
1253
+ yargs.command({
1254
+ command: "".concat(model, " <action>"),
1255
+ describe: "Composite actions scoped to model '".concat(model, "' (").concat(modelSpecs.length, ")."),
1256
+ builder: function builder(yy) {
1257
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1258
+ try {
1259
+ for(var _iterator = modelSpecs[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1260
+ var spec = _step.value;
1261
+ yy.command(createActionCommand(spec));
1262
+ }
1263
+ } catch (err) {
1264
+ _didIteratorError = true;
1265
+ _iteratorError = err;
1266
+ } finally{
1267
+ try {
1268
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1269
+ _iterator.return();
1270
+ }
1271
+ } finally{
1272
+ if (_didIteratorError) {
1273
+ throw _iteratorError;
1274
+ }
1275
+ }
1276
+ }
1277
+ return yy.demandCommand(1, 'Please specify an action.');
1278
+ },
1279
+ handler: function handler() {
1280
+ return undefined;
1281
+ }
1282
+ });
1283
+ };
1284
+ for(var _iterator1 = sortedModels[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true)_loop();
1285
+ } catch (err) {
1286
+ _didIteratorError1 = true;
1287
+ _iteratorError1 = err;
1288
+ } finally{
1289
+ try {
1290
+ if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
1291
+ _iterator1.return();
1292
+ }
1293
+ } finally{
1294
+ if (_didIteratorError1) {
1295
+ throw _iteratorError1;
1296
+ }
1297
+ }
1298
+ }
1299
+ return yargs.demandCommand(1, 'Please specify an action.');
1300
+ },
1301
+ handler: function handler() {
1302
+ return undefined;
1303
+ }
1304
+ }
1305
+ ];
1306
+ }
1307
+ return result;
1308
+ }
1309
+
1310
+ function _array_like_to_array$9(arr, len) {
1311
+ if (len == null || len > arr.length) len = arr.length;
1312
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
1313
+ return arr2;
1314
+ }
1315
+ function _array_with_holes$5(arr) {
1316
+ if (Array.isArray(arr)) return arr;
1317
+ }
1318
+ function _array_without_holes$6(arr) {
1319
+ if (Array.isArray(arr)) return _array_like_to_array$9(arr);
1320
+ }
1321
+ function asyncGeneratorStep$h(gen, resolve, reject, _next, _throw, key, arg) {
1322
+ try {
1323
+ var info = gen[key](arg);
1324
+ var value = info.value;
1325
+ } catch (error) {
1326
+ reject(error);
1327
+ return;
1328
+ }
1329
+ if (info.done) {
1330
+ resolve(value);
1331
+ } else {
1332
+ Promise.resolve(value).then(_next, _throw);
1333
+ }
1334
+ }
1335
+ function _async_to_generator$h(fn) {
1336
+ return function() {
1337
+ var self = this, args = arguments;
1338
+ return new Promise(function(resolve, reject) {
1339
+ var gen = fn.apply(self, args);
1340
+ function _next(value) {
1341
+ asyncGeneratorStep$h(gen, resolve, reject, _next, _throw, "next", value);
1342
+ }
1343
+ function _throw(err) {
1344
+ asyncGeneratorStep$h(gen, resolve, reject, _next, _throw, "throw", err);
1345
+ }
1346
+ _next(undefined);
1347
+ });
1348
+ };
1349
+ }
1350
+ function _define_property$c(obj, key, value) {
1351
+ if (key in obj) {
1352
+ Object.defineProperty(obj, key, {
1353
+ value: value,
1354
+ enumerable: true,
1355
+ configurable: true,
1356
+ writable: true
1357
+ });
1358
+ } else {
1359
+ obj[key] = value;
1360
+ }
1361
+ return obj;
1362
+ }
1363
+ function _iterable_to_array$6(iter) {
1364
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
1365
+ }
1366
+ function _iterable_to_array_limit$5(arr, i) {
1367
+ var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
1368
+ if (_i == null) return;
1369
+ var _arr = [];
1370
+ var _n = true;
1371
+ var _d = false;
1372
+ var _s, _e;
1373
+ try {
1374
+ for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
1375
+ _arr.push(_s.value);
1376
+ if (i && _arr.length === i) break;
1377
+ }
1378
+ } catch (err) {
1379
+ _d = true;
1380
+ _e = err;
1381
+ } finally{
1382
+ try {
1383
+ if (!_n && _i["return"] != null) _i["return"]();
1384
+ } finally{
1385
+ if (_d) throw _e;
1386
+ }
1387
+ }
1388
+ return _arr;
1389
+ }
1390
+ function _non_iterable_rest$5() {
1391
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1392
+ }
1393
+ function _non_iterable_spread$6() {
1394
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1395
+ }
1396
+ function _object_spread$c(target) {
1397
+ for(var i = 1; i < arguments.length; i++){
1398
+ var source = arguments[i] != null ? arguments[i] : {};
1399
+ var ownKeys = Object.keys(source);
1400
+ if (typeof Object.getOwnPropertySymbols === "function") {
1401
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
1402
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
1403
+ }));
1404
+ }
1405
+ ownKeys.forEach(function(key) {
1406
+ _define_property$c(target, key, source[key]);
1407
+ });
1408
+ }
1409
+ return target;
1410
+ }
1411
+ function ownKeys$8(object, enumerableOnly) {
1412
+ var keys = Object.keys(object);
1413
+ if (Object.getOwnPropertySymbols) {
1414
+ var symbols = Object.getOwnPropertySymbols(object);
1415
+ keys.push.apply(keys, symbols);
1416
+ }
1417
+ return keys;
1418
+ }
1419
+ function _object_spread_props$8(target, source) {
1420
+ source = source != null ? source : {};
1421
+ if (Object.getOwnPropertyDescriptors) {
1422
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
1423
+ } else {
1424
+ ownKeys$8(Object(source)).forEach(function(key) {
1425
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
1426
+ });
1427
+ }
1428
+ return target;
1429
+ }
1430
+ function _sliced_to_array$5(arr, i) {
1431
+ return _array_with_holes$5(arr) || _iterable_to_array_limit$5(arr, i) || _unsupported_iterable_to_array$9(arr, i) || _non_iterable_rest$5();
1432
+ }
1433
+ function _to_consumable_array$6(arr) {
1434
+ return _array_without_holes$6(arr) || _iterable_to_array$6(arr) || _unsupported_iterable_to_array$9(arr) || _non_iterable_spread$6();
1435
+ }
1436
+ function _unsupported_iterable_to_array$9(o, minLen) {
1437
+ if (!o) return;
1438
+ if (typeof o === "string") return _array_like_to_array$9(o, minLen);
1439
+ var n = Object.prototype.toString.call(o).slice(8, -1);
1440
+ if (n === "Object" && o.constructor) n = o.constructor.name;
1441
+ if (n === "Map" || n === "Set") return Array.from(n);
1442
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$9(o, minLen);
1443
+ }
1444
+ function _ts_generator$h(thisArg, body) {
1445
+ var f, y, t, _ = {
1446
+ label: 0,
1447
+ sent: function() {
1448
+ if (t[0] & 1) throw t[1];
1449
+ return t[1];
1450
+ },
1451
+ trys: [],
1452
+ ops: []
1453
+ }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
1454
+ return d(g, "next", {
1455
+ value: verb(0)
1456
+ }), d(g, "throw", {
1457
+ value: verb(1)
1458
+ }), d(g, "return", {
1459
+ value: verb(2)
1460
+ }), typeof Symbol === "function" && d(g, Symbol.iterator, {
1461
+ value: function() {
1462
+ return this;
1463
+ }
1464
+ }), g;
1465
+ function verb(n) {
1466
+ return function(v) {
1467
+ return step([
1468
+ n,
1469
+ v
1470
+ ]);
1471
+ };
1472
+ }
1473
+ function step(op) {
1474
+ if (f) throw new TypeError("Generator is already executing.");
1475
+ while(g && (g = 0, op[0] && (_ = 0)), _)try {
1476
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
1477
+ if (y = 0, t) op = [
1478
+ op[0] & 2,
1479
+ t.value
1480
+ ];
1481
+ switch(op[0]){
1482
+ case 0:
1483
+ case 1:
1484
+ t = op;
1485
+ break;
1486
+ case 4:
1487
+ _.label++;
1488
+ return {
1489
+ value: op[1],
1490
+ done: false
1491
+ };
1492
+ case 5:
1493
+ _.label++;
1494
+ y = op[1];
1495
+ op = [
1496
+ 0
1497
+ ];
1498
+ continue;
1499
+ case 7:
1500
+ op = _.ops.pop();
1501
+ _.trys.pop();
1502
+ continue;
1503
+ default:
1504
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
1505
+ _ = 0;
1506
+ continue;
1507
+ }
1508
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
1509
+ _.label = op[1];
1510
+ break;
1511
+ }
1512
+ if (op[0] === 6 && _.label < t[1]) {
1513
+ _.label = t[1];
1514
+ t = op;
1515
+ break;
1516
+ }
1517
+ if (t && _.label < t[2]) {
1518
+ _.label = t[2];
1519
+ _.ops.push(op);
1520
+ break;
1521
+ }
1522
+ if (t[2]) _.ops.pop();
1523
+ _.trys.pop();
1524
+ continue;
1525
+ }
1526
+ op = body.call(thisArg, _);
1527
+ } catch (e) {
1528
+ op = [
1529
+ 6,
1530
+ e
1531
+ ];
1532
+ y = 0;
1533
+ } finally{
1534
+ f = t = 0;
1535
+ }
1536
+ if (op[0] & 5) throw op[1];
1537
+ return {
1538
+ value: op[0] ? op[1] : void 0,
1539
+ done: true
1540
+ };
1541
+ }
1542
+ }
1543
+ var _defaultResponseAdapter = {
1544
+ items: function items(raw) {
1545
+ return raw.results;
1546
+ },
1547
+ keys: function keys(raw) {
1548
+ return raw.keys;
1549
+ },
1550
+ cursorDocumentKey: function cursorDocumentKey(raw) {
1551
+ return raw.cursorDocumentKey;
1552
+ },
1553
+ hasMore: function hasMore(raw) {
1554
+ return raw.hasMore;
1555
+ }
1556
+ };
1557
+ function _defaultBuildRequestData(params, state, limit) {
1558
+ var base = _object_spread$c({}, params);
1559
+ if (state.cursorDocumentKey != null) {
1560
+ base.cursorDocumentKey = state.cursorDocumentKey;
1561
+ }
1562
+ if (limit != null) {
1563
+ base.limit = limit;
1564
+ }
1565
+ return base;
1566
+ }
1567
+ function _runItemTasks(input) {
1568
+ return _async_to_generator$h(function() {
1569
+ var context, items, keys, pageIndex, iterateItem, itemPerformTasksConfig, maxParallelPerPage, indexed, taskConfig, performResult;
1570
+ return _ts_generator$h(this, function(_state) {
1571
+ switch(_state.label){
1572
+ case 0:
1573
+ context = input.context, items = input.items, keys = input.keys, pageIndex = input.pageIndex, iterateItem = input.iterateItem, itemPerformTasksConfig = input.itemPerformTasksConfig, maxParallelPerPage = input.maxParallelPerPage;
1574
+ indexed = items.map(function(item, itemIndex) {
1575
+ var _keys_itemIndex;
1576
+ return {
1577
+ item: item,
1578
+ key: (_keys_itemIndex = keys[itemIndex]) !== null && _keys_itemIndex !== void 0 ? _keys_itemIndex : '',
1579
+ itemIndex: itemIndex
1580
+ };
1581
+ });
1582
+ taskConfig = _object_spread_props$8(_object_spread$c({
1583
+ sequential: true,
1584
+ throwError: true
1585
+ }, itemPerformTasksConfig), {
1586
+ maxParallelTasks: maxParallelPerPage !== null && maxParallelPerPage !== void 0 ? maxParallelPerPage : itemPerformTasksConfig === null || itemPerformTasksConfig === void 0 ? void 0 : itemPerformTasksConfig.maxParallelTasks
1587
+ });
1588
+ return [
1589
+ 4,
1590
+ performAsyncTasks(indexed, function(param) {
1591
+ var item = param.item, key = param.key, itemIndex = param.itemIndex;
1592
+ return iterateItem({
1593
+ context: context,
1594
+ item: item,
1595
+ key: key,
1596
+ pageIndex: pageIndex,
1597
+ itemIndex: itemIndex
1598
+ });
1599
+ }, taskConfig)
1600
+ ];
1601
+ case 1:
1602
+ performResult = _state.sent();
1603
+ return [
1604
+ 2,
1605
+ performResult.results.map(function(param) {
1606
+ var _param = _sliced_to_array$5(param, 2), output = _param[1];
1607
+ return output;
1608
+ })
1609
+ ];
1610
+ }
1611
+ });
1612
+ })();
1613
+ }
1614
+ function _processPage(input) {
1615
+ return _async_to_generator$h(function() {
1616
+ var context, raw, pageIndex, responseAdapter, iterateItem, iteratePage, itemPerformTasksConfig, maxParallelPerPage, items, keys, nextCursorDocumentKey, hasMore, itemResults, _tmp, pageResult, _tmp1, output;
1617
+ return _ts_generator$h(this, function(_state) {
1618
+ switch(_state.label){
1619
+ case 0:
1620
+ context = input.context, raw = input.raw, pageIndex = input.pageIndex, responseAdapter = input.responseAdapter, iterateItem = input.iterateItem, iteratePage = input.iteratePage, itemPerformTasksConfig = input.itemPerformTasksConfig, maxParallelPerPage = input.maxParallelPerPage;
1621
+ items = responseAdapter.items(raw);
1622
+ keys = responseAdapter.keys ? responseAdapter.keys(raw) : [];
1623
+ nextCursorDocumentKey = responseAdapter.cursorDocumentKey ? responseAdapter.cursorDocumentKey(raw) : undefined;
1624
+ hasMore = responseAdapter.hasMore ? responseAdapter.hasMore(raw) : nextCursorDocumentKey != null;
1625
+ if (!iterateItem) return [
1626
+ 3,
1627
+ 2
1628
+ ];
1629
+ return [
1630
+ 4,
1631
+ _runItemTasks({
1632
+ context: context,
1633
+ items: items,
1634
+ keys: keys,
1635
+ pageIndex: pageIndex,
1636
+ iterateItem: iterateItem,
1637
+ itemPerformTasksConfig: itemPerformTasksConfig,
1638
+ maxParallelPerPage: maxParallelPerPage
1639
+ })
1640
+ ];
1641
+ case 1:
1642
+ _tmp = _state.sent();
1643
+ return [
1644
+ 3,
1645
+ 3
1646
+ ];
1647
+ case 2:
1648
+ _tmp = undefined;
1649
+ _state.label = 3;
1650
+ case 3:
1651
+ itemResults = _tmp;
1652
+ if (!iteratePage) return [
1653
+ 3,
1654
+ 5
1655
+ ];
1656
+ return [
1657
+ 4,
1658
+ iteratePage({
1659
+ context: context,
1660
+ page: raw,
1661
+ items: items,
1662
+ keys: keys,
1663
+ pageIndex: pageIndex,
1664
+ pageItemResults: itemResults
1665
+ })
1666
+ ];
1667
+ case 4:
1668
+ _tmp1 = _state.sent();
1669
+ return [
1670
+ 3,
1671
+ 6
1672
+ ];
1673
+ case 5:
1674
+ _tmp1 = undefined;
1675
+ _state.label = 6;
1676
+ case 6:
1677
+ pageResult = _tmp1;
1678
+ output = {
1679
+ items: items,
1680
+ itemResults: itemResults,
1681
+ pageResult: pageResult,
1682
+ nextCursorDocumentKey: nextCursorDocumentKey,
1683
+ hasMore: hasMore
1684
+ };
1685
+ return [
1686
+ 2,
1687
+ output
1688
+ ];
1689
+ }
1690
+ });
1691
+ })();
1692
+ }
1693
+ function _computeEffectiveLimit(totalItemsLimit, limitPerPage, totalItems) {
1694
+ var remainingBudget = totalItemsLimit == null ? undefined : totalItemsLimit - totalItems;
1695
+ if (limitPerPage != null && remainingBudget != null) {
1696
+ return Math.min(limitPerPage, remainingBudget);
1697
+ }
1698
+ return limitPerPage !== null && limitPerPage !== void 0 ? limitPerPage : remainingBudget;
1699
+ }
1700
+ function _evaluateLoopExit(input) {
1701
+ var totalItemsLimit = input.totalItemsLimit, maxPages = input.maxPages, totalItems = input.totalItems, pageIndex = input.pageIndex, hasMore = input.hasMore, cursorDocumentKey = input.cursorDocumentKey;
1702
+ var reachedItemsLimit = totalItemsLimit != null && totalItems >= totalItemsLimit;
1703
+ var reachedPagesLimit = maxPages != null && pageIndex >= maxPages;
1704
+ if (reachedItemsLimit || reachedPagesLimit) {
1705
+ return {
1706
+ stop: true,
1707
+ hitLimit: true
1708
+ };
1709
+ }
1710
+ var exhausted = hasMore === false || cursorDocumentKey == null;
1711
+ return {
1712
+ stop: exhausted,
1713
+ hitLimit: false
1714
+ };
1715
+ }
815
1716
  /**
816
- * Creates a typed module-level slot.
1717
+ * Iterates a paginated `callModel` endpoint, exhausting (or stopping at the configured limit) all pages.
817
1718
  *
818
- * Each CLI exposes its current per-invocation context (auth tokens, API clients, env config, ...)
819
- * via a slot so command handlers can read it without yargs strict-mode flagging unknown argv keys.
1719
+ * Cursor-paginated analog of {@link iterateFirestoreDocumentSnapshots}, but speaking HTTP/`callModel`
1720
+ * rather than direct Firestore. The default response adapter reads the canonical
1721
+ * {@link OnCallQueryModelResult} shape — supply a custom adapter to iterate other array-returning
1722
+ * call types (e.g. a `getMultiple`-style standalone call).
820
1723
  *
821
- * Usage:
1724
+ * Concurrency: pages are fetched serially (cursor dependency); items within a page can run
1725
+ * in parallel via `maxParallelPerPage` (forwarded to `performAsyncTasks`).
1726
+ *
1727
+ * @example
822
1728
  * ```ts
823
- * const slot = createContextSlot<MyCliContext>({ notInitializedMessage: 'Auth middleware did not run.' });
824
- * // in middleware:
825
- * slot.set(buildContext(...));
826
- * // in handler:
827
- * const ctx = slot.require();
1729
+ * // Exhaust every published Guestbook entry for a single Guestbook.
1730
+ * const { totalItems, items } = await iterateDbxCliCallModel<QueryGuestbookEntriesParams, GuestbookEntry>({
1731
+ * context,
1732
+ * modelType: 'guestbookEntry',
1733
+ * params: { guestbook: 'gb/abc', published: true }
1734
+ * });
828
1735
  * ```
829
1736
  *
830
- * @param input - Optional slot configuration.
831
- * @param input.notInitializedMessage - Custom error message thrown by `require()` when the slot is unset.
832
- * @returns A new {@link ContextSlot} for type `T`.
833
- * @__NO_SIDE_EFFECTS__
834
- */ function createContextSlot(input) {
835
- var _ref;
836
- var _value;
837
- var notInitializedMessage = (_ref = input === null || input === void 0 ? void 0 : input.notInitializedMessage) !== null && _ref !== void 0 ? _ref : 'Context slot has not been initialized.';
838
- return {
839
- set: function set(value) {
840
- _value = value;
841
- },
842
- get: function get() {
843
- return _value;
844
- },
845
- require: function require() {
846
- if (_value == null) {
847
- throw new Error(notInitializedMessage);
848
- }
849
- return _value;
850
- }
851
- };
852
- }
853
-
854
- /**
855
- * Module-level slot holding the {@link CliContext} for the current invocation.
856
- *
857
- * Stored here instead of on argv so that yargs strict-mode does not flag it as an unknown argument.
858
- */ var _cliContextSlot = createContextSlot({
859
- notInitializedMessage: 'CLI context not initialized — auth middleware must run before this command.'
860
- });
861
- var setCliContext = _cliContextSlot.set;
862
- var getCliContext = _cliContextSlot.get;
863
- /**
864
- * Returns the current {@link CliContext} or throws — for use in command handlers that require auth.
865
- */ var requireCliContext = _cliContextSlot.require;
866
- /**
867
- * Builds a {@link CliContext} for the current invocation.
868
- *
869
- * Bundles the env config and access token alongside helpers that POST/GET against
870
- * `<env.apiBaseUrl>/model/*` with the cached Bearer token.
1737
+ * @example
1738
+ * ```ts
1739
+ * // Fan out to a child action per Guestbook, with 4-way parallelism per page.
1740
+ * const { itemResults } = await iterateDbxCliCallModel<QueryGuestbooksParams, Guestbook, OnCallQueryModelResult<Guestbook>, EntriesForGuestbook>({
1741
+ * context,
1742
+ * modelType: 'guestbook',
1743
+ * params: { published: true },
1744
+ * maxParallelPerPage: 4,
1745
+ * iterateItem: ({ context, key }) => queryGuestbookEntriesForGuestbook({ context, guestbook: key, published: true })
1746
+ * });
1747
+ * ```
871
1748
  *
872
- * @param input - The context inputs.
873
- * @param input.cliName - The CLI's binary name.
874
- * @param input.envName - The active env name.
875
- * @param input.env - The resolved {@link CliEnvConfig} for the active env.
876
- * @param input.accessToken - The Bearer access token to include on outgoing API calls.
877
- * @param input.modelManifest - Optional generated {@link CliModelManifest} for key→modelType resolution.
878
- * @returns The constructed {@link CliContext}.
879
- * @__NO_SIDE_EFFECTS__
880
- */ function createCliContext(input) {
881
- var apiBaseUrl = input.env.apiBaseUrl;
882
- var accessToken = input.accessToken;
883
- return {
884
- cliName: input.cliName,
885
- envName: input.envName,
886
- env: input.env,
887
- accessToken: accessToken,
888
- modelManifest: input.modelManifest,
889
- callModel: function callModel(params) {
890
- return callModelOverHttp({
891
- apiBaseUrl: apiBaseUrl,
892
- accessToken: accessToken,
893
- params: params
894
- });
895
- },
896
- getModel: function getModel(modelType, key) {
897
- return getModelOverHttp({
898
- apiBaseUrl: apiBaseUrl,
899
- accessToken: accessToken,
900
- modelType: modelType,
901
- key: key
902
- });
903
- },
904
- getMultipleModels: function getMultipleModels(modelType, keys) {
905
- return getMultipleModelsOverHttp({
906
- apiBaseUrl: apiBaseUrl,
907
- accessToken: accessToken,
908
- modelType: modelType,
909
- keys: keys
910
- });
911
- }
912
- };
1749
+ * @param config - Iterator configuration.
1750
+ * @returns The aggregate result.
1751
+ */ function iterateDbxCliCallModel(config) {
1752
+ return _async_to_generator$h(function() {
1753
+ var context, modelType, call, specifier, params, _config_buildRequestData, buildRequestData, _config_responseAdapter, responseAdapter, limitPerPage, totalItemsLimit, maxPages, iterateItem, iteratePage, itemPerformTasksConfig, maxParallelPerPage, _config_collectItems, collectItems, _config_collectItemResults, collectItemResults, _config_collectPageResults, collectPageResults, allItems, allItemResults, allPageResults, pageIndex, totalItems, cursorDocumentKey, hitLimit, keepGoing, collectItemsForPage, collectItemResultsForPage, collectPageResultsForPage, effectiveLimit, data, raw, pageOutcome, _allItems, _allItemResults, exit, result;
1754
+ return _ts_generator$h(this, function(_state) {
1755
+ switch(_state.label){
1756
+ case 0:
1757
+ context = config.context, modelType = config.modelType, call = config.call, specifier = config.specifier, params = config.params, _config_buildRequestData = config.buildRequestData, buildRequestData = _config_buildRequestData === void 0 ? _defaultBuildRequestData : _config_buildRequestData, _config_responseAdapter = config.responseAdapter, responseAdapter = _config_responseAdapter === void 0 ? _defaultResponseAdapter : _config_responseAdapter, limitPerPage = config.limitPerPage, totalItemsLimit = config.totalItemsLimit, maxPages = config.maxPages, iterateItem = config.iterateItem, iteratePage = config.iteratePage, itemPerformTasksConfig = config.itemPerformTasksConfig, maxParallelPerPage = config.maxParallelPerPage, _config_collectItems = config.collectItems, collectItems = _config_collectItems === void 0 ? true : _config_collectItems, _config_collectItemResults = config.collectItemResults, collectItemResults = _config_collectItemResults === void 0 ? iterateItem != null : _config_collectItemResults, _config_collectPageResults = config.collectPageResults, collectPageResults = _config_collectPageResults === void 0 ? iteratePage != null : _config_collectPageResults;
1758
+ allItems = [];
1759
+ allItemResults = [];
1760
+ allPageResults = [];
1761
+ pageIndex = 0;
1762
+ totalItems = 0;
1763
+ cursorDocumentKey = undefined;
1764
+ hitLimit = false;
1765
+ keepGoing = true;
1766
+ collectItemsForPage = collectItems;
1767
+ collectItemResultsForPage = iterateItem != null && collectItemResults;
1768
+ collectPageResultsForPage = iteratePage != null && collectPageResults;
1769
+ _state.label = 1;
1770
+ case 1:
1771
+ if (!keepGoing) return [
1772
+ 3,
1773
+ 4
1774
+ ];
1775
+ effectiveLimit = _computeEffectiveLimit(totalItemsLimit, limitPerPage, totalItems);
1776
+ data = buildRequestData(params, {
1777
+ pageIndex: pageIndex,
1778
+ cursorDocumentKey: cursorDocumentKey,
1779
+ visitedItems: totalItems
1780
+ }, effectiveLimit);
1781
+ return [
1782
+ 4,
1783
+ context.callModel({
1784
+ modelType: modelType,
1785
+ call: call,
1786
+ specifier: specifier,
1787
+ data: data
1788
+ })
1789
+ ];
1790
+ case 2:
1791
+ raw = _state.sent();
1792
+ return [
1793
+ 4,
1794
+ _processPage({
1795
+ context: context,
1796
+ raw: raw,
1797
+ pageIndex: pageIndex,
1798
+ responseAdapter: responseAdapter,
1799
+ iterateItem: iterateItem,
1800
+ iteratePage: iteratePage,
1801
+ itemPerformTasksConfig: itemPerformTasksConfig,
1802
+ maxParallelPerPage: maxParallelPerPage
1803
+ })
1804
+ ];
1805
+ case 3:
1806
+ pageOutcome = _state.sent();
1807
+ if (collectItemsForPage) {
1808
+ (_allItems = allItems).push.apply(_allItems, _to_consumable_array$6(pageOutcome.items));
1809
+ }
1810
+ if (collectItemResultsForPage && pageOutcome.itemResults) {
1811
+ (_allItemResults = allItemResults).push.apply(_allItemResults, _to_consumable_array$6(pageOutcome.itemResults));
1812
+ }
1813
+ if (collectPageResultsForPage && pageOutcome.pageResult !== undefined) {
1814
+ allPageResults.push(pageOutcome.pageResult);
1815
+ }
1816
+ totalItems += pageOutcome.items.length;
1817
+ cursorDocumentKey = pageOutcome.nextCursorDocumentKey;
1818
+ pageIndex += 1;
1819
+ exit = _evaluateLoopExit({
1820
+ totalItemsLimit: totalItemsLimit,
1821
+ maxPages: maxPages,
1822
+ totalItems: totalItems,
1823
+ pageIndex: pageIndex,
1824
+ hasMore: pageOutcome.hasMore,
1825
+ cursorDocumentKey: cursorDocumentKey
1826
+ });
1827
+ hitLimit = exit.hitLimit;
1828
+ keepGoing = !exit.stop;
1829
+ return [
1830
+ 3,
1831
+ 1
1832
+ ];
1833
+ case 4:
1834
+ result = _object_spread$c({
1835
+ totalPages: pageIndex,
1836
+ totalItems: totalItems,
1837
+ hitLimit: hitLimit,
1838
+ lastCursorDocumentKey: cursorDocumentKey
1839
+ }, collectItemsForPage ? {
1840
+ items: allItems
1841
+ } : {}, collectItemResultsForPage ? {
1842
+ itemResults: allItemResults
1843
+ } : {}, collectPageResultsForPage ? {
1844
+ pageResults: allPageResults
1845
+ } : {});
1846
+ return [
1847
+ 2,
1848
+ result
1849
+ ];
1850
+ }
1851
+ });
1852
+ })();
913
1853
  }
914
1854
 
915
1855
  function asyncGeneratorStep$g(gen, resolve, reject, _next, _throw, key, arg) {
@@ -1522,7 +2462,7 @@ function _ts_generator$f(thisArg, body) {
1522
2462
  }
1523
2463
  };
1524
2464
 
1525
- function _array_like_to_array$7(arr, len) {
2465
+ function _array_like_to_array$8(arr, len) {
1526
2466
  if (len == null || len > arr.length) len = arr.length;
1527
2467
  for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
1528
2468
  return arr2;
@@ -1566,19 +2506,19 @@ function _non_iterable_rest$4() {
1566
2506
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1567
2507
  }
1568
2508
  function _sliced_to_array$4(arr, i) {
1569
- return _array_with_holes$4(arr) || _iterable_to_array_limit$4(arr, i) || _unsupported_iterable_to_array$7(arr, i) || _non_iterable_rest$4();
2509
+ return _array_with_holes$4(arr) || _iterable_to_array_limit$4(arr, i) || _unsupported_iterable_to_array$8(arr, i) || _non_iterable_rest$4();
1570
2510
  }
1571
2511
  function _type_of$1(obj) {
1572
2512
  "@swc/helpers - typeof";
1573
2513
  return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
1574
2514
  }
1575
- function _unsupported_iterable_to_array$7(o, minLen) {
2515
+ function _unsupported_iterable_to_array$8(o, minLen) {
1576
2516
  if (!o) return;
1577
- if (typeof o === "string") return _array_like_to_array$7(o, minLen);
2517
+ if (typeof o === "string") return _array_like_to_array$8(o, minLen);
1578
2518
  var n = Object.prototype.toString.call(o).slice(8, -1);
1579
2519
  if (n === "Object" && o.constructor) n = o.constructor.name;
1580
2520
  if (n === "Map" || n === "Set") return Array.from(n);
1581
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$7(o, minLen);
2521
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$8(o, minLen);
1582
2522
  }
1583
2523
  /**
1584
2524
  * Resolves the manifest entry for `modelType`. Lookup tries
@@ -1717,6 +2657,31 @@ function isPlainObject(value) {
1717
2657
  return proto === Object.prototype || proto === null;
1718
2658
  }
1719
2659
 
2660
+ function _array_like_to_array$7(arr, len) {
2661
+ if (len == null || len > arr.length) len = arr.length;
2662
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
2663
+ return arr2;
2664
+ }
2665
+ function _array_without_holes$5(arr) {
2666
+ if (Array.isArray(arr)) return _array_like_to_array$7(arr);
2667
+ }
2668
+ function _iterable_to_array$5(iter) {
2669
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
2670
+ }
2671
+ function _non_iterable_spread$5() {
2672
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
2673
+ }
2674
+ function _to_consumable_array$5(arr) {
2675
+ return _array_without_holes$5(arr) || _iterable_to_array$5(arr) || _unsupported_iterable_to_array$7(arr) || _non_iterable_spread$5();
2676
+ }
2677
+ function _unsupported_iterable_to_array$7(o, minLen) {
2678
+ if (!o) return;
2679
+ if (typeof o === "string") return _array_like_to_array$7(o, minLen);
2680
+ var n = Object.prototype.toString.call(o).slice(8, -1);
2681
+ if (n === "Object" && o.constructor) n = o.constructor.name;
2682
+ if (n === "Map" || n === "Set") return Array.from(n);
2683
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$7(o, minLen);
2684
+ }
1720
2685
  /**
1721
2686
  * Default command name for the model-decode command. Top-level so it stays
1722
2687
  * out of the API-call namespace owned by `model <model> <action>`.
@@ -1809,7 +2774,7 @@ function runHandler$1(manifest, argv) {
1809
2774
  }
1810
2775
  decoded.push(toSegment(prefix, id, entry));
1811
2776
  }
1812
- var leaf = decoded[decoded.length - 1];
2777
+ var leaf = decoded.at(-1);
1813
2778
  var ancestors = decoded.slice(0, -1);
1814
2779
  return {
1815
2780
  key: trimmed,
@@ -1846,59 +2811,48 @@ function toSegment(prefix, id, entry) {
1846
2811
  * @returns the formatted block with a trailing newline.
1847
2812
  * @__NO_SIDE_EFFECTS__
1848
2813
  */ function renderDecodedKey(decoded) {
1849
- var lines = [];
1850
- var leaf = decoded.leaf;
1851
- if (leaf.modelName) {
1852
- lines.push("Model: ".concat(leaf.modelName));
1853
- if (leaf.identityConst) lines.push("identityConst: ".concat(leaf.identityConst));
1854
- if (leaf.modelType) lines.push("modelType: ".concat(leaf.modelType));
1855
- lines.push("prefix: ".concat(leaf.prefix));
1856
- lines.push("id: ".concat(leaf.id));
1857
- if (leaf.modelGroup) lines.push("modelGroup: ".concat(leaf.modelGroup));
1858
- if (leaf.parentIdentityConst) lines.push("parentIdentityConst: ".concat(leaf.parentIdentityConst));
1859
- if (leaf.sourcePackage) {
1860
- var sourceSuffix = leaf.sourceFile ? " (".concat(leaf.sourceFile, ")") : '';
1861
- lines.push("source: ".concat(leaf.sourcePackage).concat(sourceSuffix));
1862
- }
1863
- } else {
1864
- lines.push("Model: <unknown — prefix '".concat(leaf.prefix, "' not in manifest>"));
1865
- lines.push("prefix: ".concat(leaf.prefix));
1866
- lines.push("id: ".concat(leaf.id));
1867
- }
2814
+ var lines = _to_consumable_array$5(renderLeafLines(decoded.leaf));
1868
2815
  if (decoded.ancestors.length > 0) {
1869
- lines.push('');
1870
- lines.push('Parent chain:');
1871
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1872
- try {
1873
- for(var _iterator = decoded.ancestors[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1874
- var ancestor = _step.value;
1875
- if (ancestor.modelName) {
1876
- lines.push("- ".concat(ancestor.modelName, " — prefix ").concat(ancestor.prefix, ", id ").concat(ancestor.id));
1877
- } else {
1878
- lines.push("- <unknown> — prefix ".concat(ancestor.prefix, ", id ").concat(ancestor.id));
1879
- }
1880
- }
1881
- } catch (err) {
1882
- _didIteratorError = true;
1883
- _iteratorError = err;
1884
- } finally{
1885
- try {
1886
- if (!_iteratorNormalCompletion && _iterator.return != null) {
1887
- _iterator.return();
1888
- }
1889
- } finally{
1890
- if (_didIteratorError) {
1891
- throw _iteratorError;
1892
- }
1893
- }
1894
- }
2816
+ var _lines;
2817
+ (_lines = lines).push.apply(_lines, [
2818
+ '',
2819
+ 'Parent chain:'
2820
+ ].concat(_to_consumable_array$5(decoded.ancestors.map(renderAncestorLine))));
1895
2821
  }
1896
2822
  if (decoded.unresolvedPrefixes.length > 0) {
1897
- lines.push('');
1898
- lines.push("Unresolved prefix".concat(decoded.unresolvedPrefixes.length === 1 ? '' : 'es', ": ").concat(decoded.unresolvedPrefixes.join(', '), ". Run `model-info` to list known models."));
2823
+ var suffix = decoded.unresolvedPrefixes.length === 1 ? '' : 'es';
2824
+ lines.push('', "Unresolved prefix".concat(suffix, ": ").concat(decoded.unresolvedPrefixes.join(', '), ". Run `model-info` to list known models."));
1899
2825
  }
1900
2826
  return lines.join('\n') + '\n';
1901
2827
  }
2828
+ function renderLeafLines(leaf) {
2829
+ if (!leaf.modelName) {
2830
+ return [
2831
+ "Model: <unknown — prefix '".concat(leaf.prefix, "' not in manifest>"),
2832
+ "prefix: ".concat(leaf.prefix),
2833
+ "id: ".concat(leaf.id)
2834
+ ];
2835
+ }
2836
+ var lines = [
2837
+ "Model: ".concat(leaf.modelName)
2838
+ ];
2839
+ if (leaf.identityConst) lines.push("identityConst: ".concat(leaf.identityConst));
2840
+ if (leaf.modelType) lines.push("modelType: ".concat(leaf.modelType));
2841
+ lines.push("prefix: ".concat(leaf.prefix), "id: ".concat(leaf.id));
2842
+ if (leaf.modelGroup) lines.push("modelGroup: ".concat(leaf.modelGroup));
2843
+ if (leaf.parentIdentityConst) lines.push("parentIdentityConst: ".concat(leaf.parentIdentityConst));
2844
+ if (leaf.sourcePackage) {
2845
+ var sourceSuffix = leaf.sourceFile ? " (".concat(leaf.sourceFile, ")") : '';
2846
+ lines.push("source: ".concat(leaf.sourcePackage).concat(sourceSuffix));
2847
+ }
2848
+ return lines;
2849
+ }
2850
+ function renderAncestorLine(ancestor) {
2851
+ if (ancestor.modelName) {
2852
+ return "- ".concat(ancestor.modelName, " — prefix ").concat(ancestor.prefix, ", id ").concat(ancestor.id);
2853
+ }
2854
+ return "- <unknown> — prefix ".concat(ancestor.prefix, ", id ").concat(ancestor.id);
2855
+ }
1902
2856
 
1903
2857
  function _array_like_to_array$6(arr, len) {
1904
2858
  if (len == null || len > arr.length) len = arr.length;
@@ -2121,7 +3075,7 @@ function inferModelTypeFromKeys(keys, manifest) {
2121
3075
  function manifestPrefixList(manifest) {
2122
3076
  var prefixes = manifest.map(function(e) {
2123
3077
  return e.collectionPrefix;
2124
- }).sort();
3078
+ }).sort(compareStrings);
2125
3079
  return prefixes.join(', ');
2126
3080
  }
2127
3081
 
@@ -6638,20 +7592,18 @@ function _unsupported_iterable_to_array$2(o, minLen) {
6638
7592
  * @returns the formatted summary as a single string with a trailing newline.
6639
7593
  * @__NO_SIDE_EFFECTS__
6640
7594
  */ function renderModelManifestEntry(entry) {
6641
- var lines = [];
6642
- lines.push("# ".concat(entry.modelType) + (entry.modelGroup ? " \xb7 group ".concat(entry.modelGroup) : ''));
6643
- lines.push("Identity: ".concat(entry.identityConst));
6644
- lines.push("Collection prefix: ".concat(entry.collectionPrefix));
7595
+ var groupSuffix = entry.modelGroup ? " \xb7 group ".concat(entry.modelGroup) : '';
7596
+ var lines = [
7597
+ "# ".concat(entry.modelType).concat(groupSuffix),
7598
+ "Identity: ".concat(entry.identityConst),
7599
+ "Collection prefix: ".concat(entry.collectionPrefix)
7600
+ ];
6645
7601
  if (entry.parentIdentityConst) lines.push("Parent identity: ".concat(entry.parentIdentityConst));
6646
- lines.push("Source package: ".concat(entry.sourcePackage));
6647
- lines.push("Source file: ".concat(entry.sourceFile));
7602
+ lines.push("Source package: ".concat(entry.sourcePackage), "Source file: ".concat(entry.sourceFile));
6648
7603
  if (entry.description) {
6649
- lines.push('');
6650
- lines.push(entry.description);
7604
+ lines.push('', entry.description);
6651
7605
  }
6652
- lines.push('');
6653
- lines.push("Fields (".concat(entry.fields.length, "):"));
6654
- lines.push(renderFieldsTree(entry.fields, 0));
7606
+ lines.push('', "Fields (".concat(entry.fields.length, "):"), renderFieldsTree(entry.fields, 0));
6655
7607
  return lines.join('\n') + '\n';
6656
7608
  }
6657
7609
  /**
@@ -6665,10 +7617,18 @@ function _unsupported_iterable_to_array$2(o, minLen) {
6665
7617
  return renderFieldsTree(entry.fields, 0) + '\n';
6666
7618
  }
6667
7619
  function renderFieldsTree(fields, indent) {
6668
- var out = [];
6669
7620
  var includeConverter = fields.some(function(f) {
6670
7621
  return f.converter !== undefined;
6671
7622
  });
7623
+ var tableBlock = indentLines$1(renderTable(buildFieldsTableRows(fields, includeConverter)), indent);
7624
+ var nestedBlocks = fields.flatMap(function(field) {
7625
+ return renderNestedFieldBlock(field, indent);
7626
+ });
7627
+ return [
7628
+ tableBlock
7629
+ ].concat(_to_consumable_array$2(nestedBlocks)).join('\n');
7630
+ }
7631
+ function buildFieldsTableRows(fields, includeConverter) {
6672
7632
  var header = includeConverter ? [
6673
7633
  'NAME',
6674
7634
  'LONG NAME',
@@ -6681,63 +7641,34 @@ function renderFieldsTree(fields, indent) {
6681
7641
  'TYPE',
6682
7642
  'OPTIONAL'
6683
7643
  ];
6684
- var rows = [
7644
+ return [
6685
7645
  header
7646
+ ].concat(_to_consumable_array$2(fields.map(function(field) {
7647
+ return buildFieldRow(field, includeConverter);
7648
+ })));
7649
+ }
7650
+ function buildFieldRow(field, includeConverter) {
7651
+ var _field_tsType;
7652
+ var row = [
7653
+ field.name,
7654
+ field.longName,
7655
+ (_field_tsType = field.tsType) !== null && _field_tsType !== void 0 ? _field_tsType : '',
7656
+ field.optional ? 'yes' : 'no'
6686
7657
  ];
6687
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
6688
- try {
6689
- for(var _iterator = fields[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
6690
- var field = _step.value;
6691
- var _field_tsType;
6692
- var row = [
6693
- field.name,
6694
- field.longName,
6695
- (_field_tsType = field.tsType) !== null && _field_tsType !== void 0 ? _field_tsType : '',
6696
- field.optional ? 'yes' : 'no'
6697
- ];
6698
- if (includeConverter) row.push(field.converter ? truncate(field.converter, 60) : '');
6699
- rows.push(row);
6700
- }
6701
- } catch (err) {
6702
- _didIteratorError = true;
6703
- _iteratorError = err;
6704
- } finally{
6705
- try {
6706
- if (!_iteratorNormalCompletion && _iterator.return != null) {
6707
- _iterator.return();
6708
- }
6709
- } finally{
6710
- if (_didIteratorError) {
6711
- throw _iteratorError;
6712
- }
6713
- }
7658
+ if (includeConverter) {
7659
+ row.push(field.converter ? truncate(field.converter, 60) : '');
6714
7660
  }
6715
- out.push(indentLines$1(renderTable(rows), indent));
6716
- var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
6717
- try {
6718
- for(var _iterator1 = fields[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
6719
- var field1 = _step1.value;
6720
- if (field1.nestedFields && field1.nestedFields.length > 0) {
6721
- var label = field1.nestedIsArray ? 'array element' : 'sub-object';
6722
- out.push(indentLines$1("↳ ".concat(field1.name, " (").concat(label, ", ").concat(field1.nestedFields.length, " field").concat(field1.nestedFields.length === 1 ? '' : 's', ")"), indent + 2));
6723
- out.push(renderFieldsTree(field1.nestedFields, indent + 4));
6724
- }
6725
- }
6726
- } catch (err) {
6727
- _didIteratorError1 = true;
6728
- _iteratorError1 = err;
6729
- } finally{
6730
- try {
6731
- if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
6732
- _iterator1.return();
6733
- }
6734
- } finally{
6735
- if (_didIteratorError1) {
6736
- throw _iteratorError1;
6737
- }
6738
- }
6739
- }
6740
- return out.join('\n');
7661
+ return row;
7662
+ }
7663
+ function renderNestedFieldBlock(field, indent) {
7664
+ var nested = field.nestedFields;
7665
+ if (!nested || nested.length === 0) return [];
7666
+ var label = field.nestedIsArray ? 'array element' : 'sub-object';
7667
+ var plural = nested.length === 1 ? '' : 's';
7668
+ return [
7669
+ indentLines$1("↳ ".concat(field.name, " (").concat(label, ", ").concat(nested.length, " field").concat(plural, ")"), indent + 2),
7670
+ renderFieldsTree(nested, indent + 4)
7671
+ ];
6741
7672
  }
6742
7673
  function renderTable(rows) {
6743
7674
  if (rows.length === 0) return '';
@@ -7200,6 +8131,21 @@ function _ts_generator$6(thisArg, body) {
7200
8131
  })();
7201
8132
  };
7202
8133
  }
8134
+ /**
8135
+ * Test-only middleware that skips OIDC discovery, disk token loading, and token refresh, attaching
8136
+ * a pre-built {@link CliContext} directly via {@link setCliContext}.
8137
+ *
8138
+ * @internal Intended for use by `@dereekb/dbx-cli/test`. Not for production wiring.
8139
+ *
8140
+ * @param input - The pre-built context to attach on every invocation.
8141
+ * @param input.cliContext - The {@link CliContext} that will be attached via {@link setCliContext}.
8142
+ * @returns A yargs middleware function that always sets the provided context.
8143
+ * @__NO_SIDE_EFFECTS__
8144
+ */ function createPassthroughAuthMiddleware(input) {
8145
+ return function() {
8146
+ setCliContext(input.cliContext);
8147
+ };
8148
+ }
7203
8149
 
7204
8150
  function asyncGeneratorStep$5(gen, resolve, reject, _next, _throw, key, arg) {
7205
8151
  try {
@@ -8300,7 +9246,7 @@ function _ts_generator$2(thisArg, body) {
8300
9246
  * @returns The configured yargs `Argv` ready to be `.parse()`-d.
8301
9247
  * @__NO_SIDE_EFFECTS__
8302
9248
  */ function createCli(input) {
8303
- var _input_configCommands, _input_apiCommands, _input_argv;
9249
+ var _input_configCommands, _input_actionCommands, _input_apiCommands, _input_argv;
8304
9250
  var cliName = input.cliName;
8305
9251
  var defaultEnvs = input.defaultEnvs;
8306
9252
  var builtInConfigCommands = [
@@ -8334,10 +9280,19 @@ function _ts_generator$2(thisArg, body) {
8334
9280
  if (input.disableModelGet !== true) {
8335
9281
  builtInApiCommands.push(getCommand, getManyCommand);
8336
9282
  }
8337
- var allApiCommands = _to_consumable_array$1(builtInApiCommands).concat(_to_consumable_array$1((_input_apiCommands = input.apiCommands) !== null && _input_apiCommands !== void 0 ? _input_apiCommands : []));
9283
+ var actionCommands = buildActionCommands((_input_actionCommands = input.actionCommands) !== null && _input_actionCommands !== void 0 ? _input_actionCommands : []);
9284
+ var allApiCommands = _to_consumable_array$1(builtInApiCommands).concat(_to_consumable_array$1((_input_apiCommands = input.apiCommands) !== null && _input_apiCommands !== void 0 ? _input_apiCommands : []), _to_consumable_array$1(actionCommands));
8338
9285
  var skipCommandNames = new Set(allConfigCommands.map(function(c) {
8339
9286
  return commandName(c);
8340
9287
  }));
9288
+ var authMiddleware = input.testCliContext ? createPassthroughAuthMiddleware({
9289
+ cliContext: input.testCliContext
9290
+ }) : createAuthMiddleware({
9291
+ cliName: cliName,
9292
+ skipCommands: skipCommandNames,
9293
+ defaultEnvs: defaultEnvs,
9294
+ modelManifest: input.modelManifest
9295
+ });
8341
9296
  return yargs((_input_argv = input.argv) !== null && _input_argv !== void 0 ? _input_argv : hideBin(process.argv)).scriptName(cliName).usage('$0 <command> [options]').option('verbose', {
8342
9297
  alias: 'v',
8343
9298
  type: 'boolean',
@@ -8382,12 +9337,7 @@ function _ts_generator$2(thisArg, body) {
8382
9337
  global: true,
8383
9338
  describe: 'Show the full options table in --help even when --data-help is in focus mode'
8384
9339
  }).middleware([
8385
- createAuthMiddleware({
8386
- cliName: cliName,
8387
- skipCommands: skipCommandNames,
8388
- defaultEnvs: defaultEnvs,
8389
- modelManifest: input.modelManifest
8390
- }),
9340
+ authMiddleware,
8391
9341
  createOutputMiddleware({
8392
9342
  cliName: cliName,
8393
9343
  skipCommands: skipCommandNames
@@ -9013,7 +9963,8 @@ function buildModelCommand(model, entries, context) {
9013
9963
  var isRootModel = entry != null && !entry.parentIdentityConst;
9014
9964
  var positionalName = isRootModel ? 'idOrKey' : 'key';
9015
9965
  var placeholder = isRootModel ? '<id-or-key>' : '<key>';
9016
- var positionalDescribe = isRootModel ? "Firestore key for the ".concat(model, " document — bare doc id (resolved to `").concat(entry.collectionPrefix, "/<id>`) or full `prefix/id`.") : "Firestore key for the ".concat(model, " document (full `prefix/id` — bare doc id is not supported").concat(entry ? ' for this subcollection model' : '', ").");
9966
+ var subcollectionNote = entry ? ' for this subcollection model' : '';
9967
+ var positionalDescribe = isRootModel ? "Firestore key for the ".concat(model, " document — bare doc id (resolved to `").concat(entry.collectionPrefix, "/<id>`) or full `prefix/id`.") : "Firestore key for the ".concat(model, " document (full `prefix/id` — bare doc id is not supported").concat(subcollectionNote, ").");
9017
9968
  var commandDescribe = isRootModel ? "Read a single ".concat(model, " document by id or key.") : "Read a single ".concat(model, " document by key.");
9018
9969
  return {
9019
9970
  command: "get ".concat(placeholder),
@@ -9237,8 +10188,7 @@ function buildParamsSection(entry) {
9237
10188
  lines.push(indentLines(entry.paramsTypeDescription, ' '));
9238
10189
  }
9239
10190
  if (entry.paramsFields && entry.paramsFields.length > 0) {
9240
- lines.push('');
9241
- lines.push('Fields:');
10191
+ lines.push('', 'Fields:');
9242
10192
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
9243
10193
  try {
9244
10194
  for(var _iterator = entry.paramsFields[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
@@ -9278,8 +10228,7 @@ function buildResultSection(entry) {
9278
10228
  lines.push(indentLines(entry.resultTypeDescription, ' '));
9279
10229
  }
9280
10230
  if (entry.resultFields && entry.resultFields.length > 0) {
9281
- lines.push('');
9282
- lines.push('Fields:');
10231
+ lines.push('', 'Fields:');
9283
10232
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
9284
10233
  try {
9285
10234
  for(var _iterator = entry.resultFields[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
@@ -9375,6 +10324,7 @@ function renderJsonSchemaSection(entry) {
9375
10324
  // method that emits the bare JSON Schema value, e.g. `false`). Round-trip
9376
10325
  // through JSON to invoke those `toJSON()` callbacks before pruning;
9377
10326
  // `structuredClone` would not call them.
10327
+ // NOSONAR (typescript:S7784): structuredClone bypasses toJSON()
9378
10328
  var normalized = JSON.parse(JSON.stringify(raw));
9379
10329
  var pruned = pruneFalseUnionBranches(normalized);
9380
10330
  result = "Params Schema (JSON Schema):\n".concat(JSON.stringify(pruned, null, 2));
@@ -10016,4 +10966,4 @@ function printPaginatedOutput(input) {
10016
10966
  })();
10017
10967
  }
10018
10968
 
10019
- export { CALL_MODEL_API_PATH, CliError, DEFAULT_CLI_OIDC_SCOPES, DEFAULT_CLI_REDIRECT_URI, DEFAULT_CLI_SECRET_PATTERNS, DEFAULT_MANIFEST_HELP_DATA_FORMAT, DEFAULT_MANIFEST_HELP_MODE, DEFAULT_MANIFEST_MODEL_COMMAND_NAME, DEFAULT_MODEL_DECODE_COMMAND_NAME, DEFAULT_MODEL_INFO_COMMAND_NAME, DUMP_MERGE_MODES, DUMP_OUTPUT_MODES, MAX_MODEL_ACCESS_MULTI_READ_KEYS, MODEL_WRITE_OIDC_SCOPES, MULTIPLE_PAGES_OUTPUT_MODES, PROMPT_CANCELLED_ERROR_CODE, STANDARD_GLOBAL_OPTION_NAMES, applyEnvVarOverrides, buildAuthorizationUrl, buildCliPaths, buildDumpFilePath, buildErrorOutput, buildManifestCommands, buildModelDecodeCommand, buildModelInfoCommand, buildOidcDiscoveryCandidates, callModelOverHttp, callPassthroughCommand, configureCliErrorMapper, configureCliSecretPatterns, configureOutputOptions, createAuthCommand, createAuthMiddleware, createCallModelCommand, createCli, createCliContext, createCliTokenCacheStore, createContextSlot, createDoctorCommand, createEnvCommand, createOutputCommand, createOutputMiddleware, decodeFirestoreModelKey, defaultDoctorChecks, detectDataHelpFormat, detectHelpMode, discoverOidcMetadata, dumpTimestamp, exchangeAuthorizationCode, expandModelKeys, fetchUserInfo, filterReadOnlyModelScopes, findCliEnvDefault, findCliModelManifestEntry, generateOAuthState, generatePkceMaterial, getCliContext, getCommand, getManyCommand, getModelOverHttp, getMultipleModelsOverHttp, getOutputOptions, isCliEnvConfigComplete, isTokenExpired, loadCliConfig, maskSecret, mergeCliConfig, mergeCliEnvWithDefault, mergeOutputConfig, openStreamingDump, outputError, outputResult, parseGetArgs, parseGetManyArgs, parsePastedRedirect, pickFields, promptLine, refreshAccessToken, renderDecodedKey, renderModelManifestEntry, renderModelManifestFields, renderModelManifestList, requireCliContext, resolveActiveEnvName, resolveCliModel, resolveOutputConfig, resolvePerModelGetKey, revokeToken, runCli, runPaginatedList, sanitizeString, saveCliConfig, setCliContext, withCallModelArgs, withEnv, withMultiplePages, withOutput, wrapCommandHandler };
10969
+ export { CALL_MODEL_API_PATH, CliError, DEFAULT_ACTION_COMMAND_NAME, DEFAULT_CLI_OIDC_SCOPES, DEFAULT_CLI_REDIRECT_URI, DEFAULT_CLI_SECRET_PATTERNS, DEFAULT_MANIFEST_HELP_DATA_FORMAT, DEFAULT_MANIFEST_HELP_MODE, DEFAULT_MANIFEST_MODEL_COMMAND_NAME, DEFAULT_MODEL_DECODE_COMMAND_NAME, DEFAULT_MODEL_INFO_COMMAND_NAME, DUMP_MERGE_MODES, DUMP_OUTPUT_MODES, MAX_MODEL_ACCESS_MULTI_READ_KEYS, MODEL_WRITE_OIDC_SCOPES, MULTIPLE_PAGES_OUTPUT_MODES, PROMPT_CANCELLED_ERROR_CODE, STANDARD_GLOBAL_OPTION_NAMES, applyEnvVarOverrides, buildActionCommands, buildAuthorizationUrl, buildCliPaths, buildDumpFilePath, buildErrorOutput, buildManifestCommands, buildModelDecodeCommand, buildModelInfoCommand, buildOidcDiscoveryCandidates, callModelOverHttp, callPassthroughCommand, configureCliErrorMapper, configureCliSecretPatterns, configureOutputOptions, createActionCommand, createAuthCommand, createAuthMiddleware, createCallModelCommand, createCli, createCliContext, createCliTokenCacheStore, createContextSlot, createDoctorCommand, createEnvCommand, createOutputCommand, createOutputMiddleware, createPassthroughAuthMiddleware, decodeFirestoreModelKey, defaultDoctorChecks, detectDataHelpFormat, detectHelpMode, discoverOidcMetadata, dumpTimestamp, exchangeAuthorizationCode, expandModelKeys, fetchUserInfo, filterReadOnlyModelScopes, findCliEnvDefault, findCliModelManifestEntry, generateOAuthState, generatePkceMaterial, getCliContext, getCommand, getManyCommand, getModelOverHttp, getMultipleModelsOverHttp, getOutputOptions, isCliEnvConfigComplete, isTokenExpired, iterateDbxCliCallModel, loadCliConfig, maskSecret, mergeCliConfig, mergeCliEnvWithDefault, mergeOutputConfig, openStreamingDump, outputError, outputResult, parseGetArgs, parseGetManyArgs, parsePastedRedirect, pickFields, promptLine, refreshAccessToken, renderDecodedKey, renderModelManifestEntry, renderModelManifestFields, renderModelManifestList, requireCliContext, resolveActiveEnvName, resolveCliModel, resolveOutputConfig, resolvePerModelGetKey, revokeToken, runCli, runPaginatedList, sanitizeString, saveCliConfig, setCliContext, withCallModelArgs, withEnv, withMultiplePages, withOutput, wrapCommandHandler };