@sanity/cli 3.36.4 → 3.36.5-canary.34

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 (116) hide show
  1. package/lib/_chunks-cjs/cli.js +1779 -1317
  2. package/lib/_chunks-cjs/cli.js.map +1 -1
  3. package/lib/_chunks-cjs/journeyConfig.js +11 -11
  4. package/lib/_chunks-cjs/journeyConfig.js.map +1 -1
  5. package/lib/_chunks-cjs/loadEnv.js +105 -2719
  6. package/lib/_chunks-cjs/loadEnv.js.map +1 -1
  7. package/lib/cli.d.ts +10 -0
  8. package/lib/index.d.ts +448 -0
  9. package/lib/index.esm.js +449 -5
  10. package/lib/index.esm.js.map +1 -1
  11. package/lib/index.js +3 -3
  12. package/lib/index.js.map +1 -1
  13. package/lib/index.mjs +452 -0
  14. package/lib/index.mjs.map +1 -0
  15. package/lib/run.d.ts +1 -0
  16. package/lib/workers/getAndWriteJourneySchema.d.ts +1 -0
  17. package/lib/workers/getCliConfig.d.ts +1 -0
  18. package/lib/workers/typegenGenerate.d.ts +37 -0
  19. package/lib/workers/typegenGenerate.js +6 -2
  20. package/lib/workers/typegenGenerate.js.map +1 -1
  21. package/package.json +18 -21
  22. package/src/actions/init-project/templates/shopify.ts +7 -0
  23. package/src/util/journeyConfig.ts +5 -5
  24. package/templates/ecommerce/plugins/barcode-input/BarcodeInput.js +1 -1
  25. package/templates/get-started/plugins/sanity-plugin-tutorial/GetStartedTutorial.tsx +1 -1
  26. package/templates/shared/tsconfig.json +2 -4
  27. package/templates/shopify/README.md +3 -3
  28. package/templates/shopify/components/hotspots/ProductTooltip.tsx +1 -1
  29. package/templates/shopify/components/icons/Shopify.tsx +1 -1
  30. package/templates/shopify/components/inputs/CollectionHidden.tsx +1 -1
  31. package/templates/shopify/components/media/ColorTheme.tsx +1 -1
  32. package/templates/shopify/components/studio/Navbar.tsx +29 -0
  33. package/templates/shopify/constants.ts +31 -1
  34. package/templates/shopify/docs/features.md +6 -7
  35. package/templates/shopify/schemaTypes/documents/collection.tsx +11 -47
  36. package/templates/shopify/schemaTypes/documents/colorTheme.tsx +2 -17
  37. package/templates/shopify/schemaTypes/documents/page.ts +10 -37
  38. package/templates/shopify/schemaTypes/documents/product.tsx +4 -27
  39. package/templates/shopify/schemaTypes/documents/productVariant.tsx +4 -13
  40. package/templates/shopify/schemaTypes/index.ts +97 -126
  41. package/templates/shopify/schemaTypes/objects/collection/{group.ts → collectionGroupType.ts} +7 -10
  42. package/templates/shopify/schemaTypes/objects/collection/{links.ts → collectionLinksType.ts} +4 -4
  43. package/templates/shopify/schemaTypes/objects/customProductOption/{colorObject.tsx → customProductOptionColorObjectType.tsx} +3 -6
  44. package/templates/shopify/schemaTypes/objects/customProductOption/{color.tsx → customProductOptionColorType.tsx} +2 -10
  45. package/templates/shopify/schemaTypes/objects/customProductOption/{sizeObject.ts → customProductOptionSizeObjectType.ts} +3 -7
  46. package/templates/shopify/schemaTypes/objects/customProductOption/{size.ts → customProductOptionSizeType.ts} +3 -12
  47. package/templates/shopify/schemaTypes/objects/global/footerType.ts +22 -0
  48. package/templates/shopify/schemaTypes/objects/global/menuLinksType.ts +21 -0
  49. package/templates/shopify/schemaTypes/objects/global/{menu.ts → menuType.ts} +2 -4
  50. package/templates/shopify/schemaTypes/objects/global/{notFoundPage.ts → notFoundPageType.ts} +1 -6
  51. package/templates/shopify/schemaTypes/objects/hotspot/{imageWithProductHotspots.ts → imageWithProductHotspotsType.ts} +4 -6
  52. package/templates/shopify/schemaTypes/objects/hotspot/{productHotspots.tsx → productHotspotsType.tsx} +3 -5
  53. package/templates/shopify/schemaTypes/objects/hotspot/{spot.tsx → spotType.tsx} +1 -3
  54. package/templates/shopify/schemaTypes/{annotations/linkEmail.tsx → objects/link/linkEmailType.tsx} +5 -13
  55. package/templates/shopify/schemaTypes/{annotations/linkExternal.tsx → objects/link/linkExternalType.tsx} +6 -13
  56. package/templates/shopify/schemaTypes/{annotations/linkInternal.tsx → objects/link/linkInternalType.tsx} +5 -12
  57. package/templates/shopify/schemaTypes/{annotations/product.tsx → objects/link/linkProductType.tsx} +4 -16
  58. package/templates/shopify/schemaTypes/objects/module/{accordionGroup.ts → accordionGroupType.ts} +6 -9
  59. package/templates/shopify/schemaTypes/objects/module/{accordion.ts → accordionType.ts} +4 -11
  60. package/templates/shopify/schemaTypes/objects/module/{callToAction.tsx → callToActionType.tsx} +10 -23
  61. package/templates/shopify/schemaTypes/objects/module/{callout.ts → calloutType.ts} +4 -10
  62. package/templates/shopify/schemaTypes/objects/module/{collection.tsx → collectionReferenceType.tsx} +4 -9
  63. package/templates/shopify/schemaTypes/objects/module/gridItemType.ts +41 -0
  64. package/templates/shopify/schemaTypes/objects/module/{grid.ts → gridType.ts} +7 -15
  65. package/templates/shopify/schemaTypes/objects/{hero/home.tsx → module/heroType.tsx} +14 -17
  66. package/templates/shopify/schemaTypes/objects/module/{imageCallToAction.tsx → imageCallToActionType.tsx} +6 -10
  67. package/templates/shopify/schemaTypes/objects/module/{image.ts → imageFeatureType.ts} +6 -18
  68. package/templates/shopify/schemaTypes/objects/module/{images.tsx → imageFeaturesType.tsx} +7 -25
  69. package/templates/shopify/schemaTypes/objects/module/{instagram.ts → instagramType.ts} +2 -2
  70. package/templates/shopify/schemaTypes/objects/module/{products.tsx → productFeaturesType.tsx} +6 -11
  71. package/templates/shopify/schemaTypes/objects/module/{product.tsx → productReferenceType.tsx} +6 -8
  72. package/templates/shopify/schemaTypes/objects/{seo/seo.ts → seoType.ts} +7 -6
  73. package/templates/shopify/schemaTypes/objects/shopify/{shopifyCollectionRule.tsx → collectionRuleType.tsx} +2 -10
  74. package/templates/shopify/schemaTypes/objects/shopify/{inventory.ts → inventoryType.ts} +7 -12
  75. package/templates/shopify/schemaTypes/objects/shopify/{option.tsx → optionType.tsx} +6 -12
  76. package/templates/shopify/schemaTypes/objects/shopify/{placeholderString.ts → placeholderStringType.ts} +3 -1
  77. package/templates/shopify/schemaTypes/objects/shopify/{priceRange.ts → priceRangeType.ts} +5 -7
  78. package/templates/shopify/schemaTypes/objects/shopify/{productWithVariant.tsx → productWithVariantType.tsx} +2 -2
  79. package/templates/shopify/schemaTypes/objects/shopify/{proxyString.ts → proxyStringType.ts} +1 -1
  80. package/templates/shopify/schemaTypes/objects/shopify/{shopifyCollection.ts → shopifyCollectionType.ts} +4 -25
  81. package/templates/shopify/schemaTypes/objects/shopify/{shopifyProduct.ts → shopifyProductType.ts} +5 -35
  82. package/templates/shopify/schemaTypes/objects/shopify/{shopifyProductVariant.ts → shopifyProductVariantType.ts} +1 -27
  83. package/templates/shopify/schemaTypes/portableText/portableTextSimpleType.tsx +45 -0
  84. package/templates/shopify/schemaTypes/portableText/portableTextType.tsx +52 -0
  85. package/templates/shopify/schemaTypes/singletons/homeType.ts +49 -0
  86. package/templates/shopify/schemaTypes/singletons/{settings.ts → settingsType.ts} +7 -9
  87. package/templates/shopify/utils/shopifyUrls.ts +3 -3
  88. package/templates/shopify/utils/validateSlug.ts +3 -7
  89. package/lib/_chunks-cjs/index.js +0 -547
  90. package/lib/_chunks-cjs/index.js.map +0 -1
  91. package/lib/_chunks-cjs/node.js +0 -213
  92. package/lib/_chunks-cjs/node.js.map +0 -1
  93. package/lib/_chunks-cjs/stegaEncodeSourceMap.js +0 -357
  94. package/lib/_chunks-cjs/stegaEncodeSourceMap.js.map +0 -1
  95. package/lib/_chunks-es/index.js +0 -3336
  96. package/lib/_chunks-es/index.js.map +0 -1
  97. package/lib/_chunks-es/node.js +0 -216
  98. package/lib/_chunks-es/node.js.map +0 -1
  99. package/lib/_chunks-es/stegaEncodeSourceMap.js +0 -358
  100. package/lib/_chunks-es/stegaEncodeSourceMap.js.map +0 -1
  101. package/lib/index.cjs.mjs +0 -7
  102. package/templates/shopify/schemaTypes/blocks/body.tsx +0 -70
  103. package/templates/shopify/schemaTypes/objects/global/footer.ts +0 -57
  104. package/templates/shopify/schemaTypes/objects/global/linkExternal.ts +0 -52
  105. package/templates/shopify/schemaTypes/objects/global/linkInternal.ts +0 -65
  106. package/templates/shopify/schemaTypes/objects/global/links.ts +0 -16
  107. package/templates/shopify/schemaTypes/objects/hero/collection.tsx +0 -42
  108. package/templates/shopify/schemaTypes/objects/hero/page.tsx +0 -35
  109. package/templates/shopify/schemaTypes/objects/module/accordionBody.ts +0 -45
  110. package/templates/shopify/schemaTypes/objects/module/gridItem.ts +0 -91
  111. package/templates/shopify/schemaTypes/objects/seo/description.tsx +0 -10
  112. package/templates/shopify/schemaTypes/objects/seo/home.tsx +0 -31
  113. package/templates/shopify/schemaTypes/objects/seo/page.tsx +0 -37
  114. package/templates/shopify/schemaTypes/objects/seo/shopify.tsx +0 -40
  115. package/templates/shopify/schemaTypes/singletons/home.ts +0 -62
  116. /package/lib/{dts/src/index.d.ts → index.d.mts} +0 -0
@@ -1,2688 +1,10 @@
1
1
  "use strict";
2
- var require$$1 = require("get-it"), require$$2 = require("get-it/middleware"), require$$0 = require("fs"), path$1 = require("path"), index = require("./index.js"), fs$1 = require("node:fs"), path$2 = require("node:path"), require$$0$1 = require("os"), require$$3 = require("crypto");
2
+ var require$$0 = require("fs"), path$1 = require("path"), debugIt = require("debug"), fs$1 = require("node:fs"), path$2 = require("node:path"), os$1 = require("os"), require$$3 = require("crypto");
3
3
  function _interopDefaultCompat(e) {
4
4
  return e && typeof e == "object" && "default" in e ? e : { default: e };
5
5
  }
6
- var require$$0__default = /* @__PURE__ */ _interopDefaultCompat(require$$0), path__default = /* @__PURE__ */ _interopDefaultCompat(path$1), fs__default = /* @__PURE__ */ _interopDefaultCompat(fs$1), path__default$1 = /* @__PURE__ */ _interopDefaultCompat(path$2), require$$0__default$1 = /* @__PURE__ */ _interopDefaultCompat(require$$0$1), require$$3__default = /* @__PURE__ */ _interopDefaultCompat(require$$3), extendStatics = function(d, b) {
7
- return extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
8
- d2.__proto__ = b2;
9
- } || function(d2, b2) {
10
- for (var p in b2)
11
- Object.prototype.hasOwnProperty.call(b2, p) && (d2[p] = b2[p]);
12
- }, extendStatics(d, b);
13
- };
14
- function __extends(d, b) {
15
- if (typeof b != "function" && b !== null)
16
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
17
- extendStatics(d, b);
18
- function __() {
19
- this.constructor = d;
20
- }
21
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22
- }
23
- var __assign = function() {
24
- return __assign = Object.assign || function(t) {
25
- for (var s2, i = 1, n = arguments.length; i < n; i++) {
26
- s2 = arguments[i];
27
- for (var p in s2)
28
- Object.prototype.hasOwnProperty.call(s2, p) && (t[p] = s2[p]);
29
- }
30
- return t;
31
- }, __assign.apply(this, arguments);
32
- };
33
- function __rest(s2, e) {
34
- var t = {};
35
- for (var p in s2)
36
- Object.prototype.hasOwnProperty.call(s2, p) && e.indexOf(p) < 0 && (t[p] = s2[p]);
37
- if (s2 != null && typeof Object.getOwnPropertySymbols == "function")
38
- for (var i = 0, p = Object.getOwnPropertySymbols(s2); i < p.length; i++)
39
- e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s2, p[i]) && (t[p[i]] = s2[p[i]]);
40
- return t;
41
- }
42
- function __decorate(decorators, target, key, desc) {
43
- var c2 = arguments.length, r = c2 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
44
- if (typeof Reflect == "object" && typeof Reflect.decorate == "function")
45
- r = Reflect.decorate(decorators, target, key, desc);
46
- else
47
- for (var i = decorators.length - 1; i >= 0; i--)
48
- (d = decorators[i]) && (r = (c2 < 3 ? d(r) : c2 > 3 ? d(target, key, r) : d(target, key)) || r);
49
- return c2 > 3 && r && Object.defineProperty(target, key, r), r;
50
- }
51
- function __param(paramIndex, decorator) {
52
- return function(target, key) {
53
- decorator(target, key, paramIndex);
54
- };
55
- }
56
- function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
57
- function accept(f2) {
58
- if (f2 !== void 0 && typeof f2 != "function")
59
- throw new TypeError("Function expected");
60
- return f2;
61
- }
62
- for (var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value", target = !descriptorIn && ctor ? contextIn.static ? ctor : ctor.prototype : null, descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}), _, done = !1, i = decorators.length - 1; i >= 0; i--) {
63
- var context = {};
64
- for (var p in contextIn)
65
- context[p] = p === "access" ? {} : contextIn[p];
66
- for (var p in contextIn.access)
67
- context.access[p] = contextIn.access[p];
68
- context.addInitializer = function(f2) {
69
- if (done)
70
- throw new TypeError("Cannot add initializers after decoration has completed");
71
- extraInitializers.push(accept(f2 || null));
72
- };
73
- var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
74
- if (kind === "accessor") {
75
- if (result === void 0)
76
- continue;
77
- if (result === null || typeof result != "object")
78
- throw new TypeError("Object expected");
79
- (_ = accept(result.get)) && (descriptor.get = _), (_ = accept(result.set)) && (descriptor.set = _), (_ = accept(result.init)) && initializers.unshift(_);
80
- } else
81
- (_ = accept(result)) && (kind === "field" ? initializers.unshift(_) : descriptor[key] = _);
82
- }
83
- target && Object.defineProperty(target, contextIn.name, descriptor), done = !0;
84
- }
85
- function __runInitializers(thisArg, initializers, value) {
86
- for (var useValue = arguments.length > 2, i = 0; i < initializers.length; i++)
87
- value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
88
- return useValue ? value : void 0;
89
- }
90
- function __propKey(x) {
91
- return typeof x == "symbol" ? x : "".concat(x);
92
- }
93
- function __setFunctionName(f2, name2, prefix) {
94
- return typeof name2 == "symbol" && (name2 = name2.description ? "[".concat(name2.description, "]") : ""), Object.defineProperty(f2, "name", { configurable: !0, value: prefix ? "".concat(prefix, " ", name2) : name2 });
95
- }
96
- function __metadata(metadataKey, metadataValue) {
97
- if (typeof Reflect == "object" && typeof Reflect.metadata == "function")
98
- return Reflect.metadata(metadataKey, metadataValue);
99
- }
100
- function __awaiter(thisArg, _arguments, P, generator) {
101
- function adopt(value) {
102
- return value instanceof P ? value : new P(function(resolve) {
103
- resolve(value);
104
- });
105
- }
106
- return new (P || (P = Promise))(function(resolve, reject) {
107
- function fulfilled(value) {
108
- try {
109
- step(generator.next(value));
110
- } catch (e) {
111
- reject(e);
112
- }
113
- }
114
- function rejected(value) {
115
- try {
116
- step(generator.throw(value));
117
- } catch (e) {
118
- reject(e);
119
- }
120
- }
121
- function step(result) {
122
- result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
123
- }
124
- step((generator = generator.apply(thisArg, _arguments || [])).next());
125
- });
126
- }
127
- function __generator(thisArg, body) {
128
- var _ = { label: 0, sent: function() {
129
- if (t[0] & 1)
130
- throw t[1];
131
- return t[1];
132
- }, trys: [], ops: [] }, f2, y, t, g;
133
- return g = { next: verb(0), throw: verb(1), return: verb(2) }, typeof Symbol == "function" && (g[Symbol.iterator] = function() {
134
- return this;
135
- }), g;
136
- function verb(n) {
137
- return function(v) {
138
- return step([n, v]);
139
- };
140
- }
141
- function step(op) {
142
- if (f2)
143
- throw new TypeError("Generator is already executing.");
144
- for (; g && (g = 0, op[0] && (_ = 0)), _; )
145
- try {
146
- if (f2 = 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)
147
- return t;
148
- switch (y = 0, t && (op = [op[0] & 2, t.value]), op[0]) {
149
- case 0:
150
- case 1:
151
- t = op;
152
- break;
153
- case 4:
154
- return _.label++, { value: op[1], done: !1 };
155
- case 5:
156
- _.label++, y = op[1], op = [0];
157
- continue;
158
- case 7:
159
- op = _.ops.pop(), _.trys.pop();
160
- continue;
161
- default:
162
- if (t = _.trys, !(t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
163
- _ = 0;
164
- continue;
165
- }
166
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
167
- _.label = op[1];
168
- break;
169
- }
170
- if (op[0] === 6 && _.label < t[1]) {
171
- _.label = t[1], t = op;
172
- break;
173
- }
174
- if (t && _.label < t[2]) {
175
- _.label = t[2], _.ops.push(op);
176
- break;
177
- }
178
- t[2] && _.ops.pop(), _.trys.pop();
179
- continue;
180
- }
181
- op = body.call(thisArg, _);
182
- } catch (e) {
183
- op = [6, e], y = 0;
184
- } finally {
185
- f2 = t = 0;
186
- }
187
- if (op[0] & 5)
188
- throw op[1];
189
- return { value: op[0] ? op[1] : void 0, done: !0 };
190
- }
191
- }
192
- var __createBinding = Object.create ? function(o, m, k, k2) {
193
- k2 === void 0 && (k2 = k);
194
- var desc = Object.getOwnPropertyDescriptor(m, k);
195
- (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) && (desc = { enumerable: !0, get: function() {
196
- return m[k];
197
- } }), Object.defineProperty(o, k2, desc);
198
- } : function(o, m, k, k2) {
199
- k2 === void 0 && (k2 = k), o[k2] = m[k];
200
- };
201
- function __exportStar(m, o) {
202
- for (var p in m)
203
- p !== "default" && !Object.prototype.hasOwnProperty.call(o, p) && __createBinding(o, m, p);
204
- }
205
- function __values(o) {
206
- var s2 = typeof Symbol == "function" && Symbol.iterator, m = s2 && o[s2], i = 0;
207
- if (m)
208
- return m.call(o);
209
- if (o && typeof o.length == "number")
210
- return {
211
- next: function() {
212
- return o && i >= o.length && (o = void 0), { value: o && o[i++], done: !o };
213
- }
214
- };
215
- throw new TypeError(s2 ? "Object is not iterable." : "Symbol.iterator is not defined.");
216
- }
217
- function __read(o, n) {
218
- var m = typeof Symbol == "function" && o[Symbol.iterator];
219
- if (!m)
220
- return o;
221
- var i = m.call(o), r, ar = [], e;
222
- try {
223
- for (; (n === void 0 || n-- > 0) && !(r = i.next()).done; )
224
- ar.push(r.value);
225
- } catch (error) {
226
- e = { error };
227
- } finally {
228
- try {
229
- r && !r.done && (m = i.return) && m.call(i);
230
- } finally {
231
- if (e)
232
- throw e.error;
233
- }
234
- }
235
- return ar;
236
- }
237
- function __spread() {
238
- for (var ar = [], i = 0; i < arguments.length; i++)
239
- ar = ar.concat(__read(arguments[i]));
240
- return ar;
241
- }
242
- function __spreadArrays() {
243
- for (var s2 = 0, i = 0, il = arguments.length; i < il; i++)
244
- s2 += arguments[i].length;
245
- for (var r = Array(s2), k = 0, i = 0; i < il; i++)
246
- for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
247
- r[k] = a[j];
248
- return r;
249
- }
250
- function __spreadArray(to, from2, pack) {
251
- if (pack || arguments.length === 2)
252
- for (var i = 0, l = from2.length, ar; i < l; i++)
253
- (ar || !(i in from2)) && (ar || (ar = Array.prototype.slice.call(from2, 0, i)), ar[i] = from2[i]);
254
- return to.concat(ar || Array.prototype.slice.call(from2));
255
- }
256
- function __await(v) {
257
- return this instanceof __await ? (this.v = v, this) : new __await(v);
258
- }
259
- function __asyncGenerator(thisArg, _arguments, generator) {
260
- if (!Symbol.asyncIterator)
261
- throw new TypeError("Symbol.asyncIterator is not defined.");
262
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
263
- return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
264
- return this;
265
- }, i;
266
- function verb(n) {
267
- g[n] && (i[n] = function(v) {
268
- return new Promise(function(a, b) {
269
- q.push([n, v, a, b]) > 1 || resume(n, v);
270
- });
271
- });
272
- }
273
- function resume(n, v) {
274
- try {
275
- step(g[n](v));
276
- } catch (e) {
277
- settle(q[0][3], e);
278
- }
279
- }
280
- function step(r) {
281
- r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
282
- }
283
- function fulfill(value) {
284
- resume("next", value);
285
- }
286
- function reject(value) {
287
- resume("throw", value);
288
- }
289
- function settle(f2, v) {
290
- f2(v), q.shift(), q.length && resume(q[0][0], q[0][1]);
291
- }
292
- }
293
- function __asyncDelegator(o) {
294
- var i, p;
295
- return i = {}, verb("next"), verb("throw", function(e) {
296
- throw e;
297
- }), verb("return"), i[Symbol.iterator] = function() {
298
- return this;
299
- }, i;
300
- function verb(n, f2) {
301
- i[n] = o[n] ? function(v) {
302
- return (p = !p) ? { value: __await(o[n](v)), done: !1 } : f2 ? f2(v) : v;
303
- } : f2;
304
- }
305
- }
306
- function __asyncValues(o) {
307
- if (!Symbol.asyncIterator)
308
- throw new TypeError("Symbol.asyncIterator is not defined.");
309
- var m = o[Symbol.asyncIterator], i;
310
- return m ? m.call(o) : (o = typeof __values == "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
311
- return this;
312
- }, i);
313
- function verb(n) {
314
- i[n] = o[n] && function(v) {
315
- return new Promise(function(resolve, reject) {
316
- v = o[n](v), settle(resolve, reject, v.done, v.value);
317
- });
318
- };
319
- }
320
- function settle(resolve, reject, d, v) {
321
- Promise.resolve(v).then(function(v2) {
322
- resolve({ value: v2, done: d });
323
- }, reject);
324
- }
325
- }
326
- function __makeTemplateObject(cooked, raw) {
327
- return Object.defineProperty ? Object.defineProperty(cooked, "raw", { value: raw }) : cooked.raw = raw, cooked;
328
- }
329
- var __setModuleDefault = Object.create ? function(o, v) {
330
- Object.defineProperty(o, "default", { enumerable: !0, value: v });
331
- } : function(o, v) {
332
- o.default = v;
333
- };
334
- function __importStar(mod) {
335
- if (mod && mod.__esModule)
336
- return mod;
337
- var result = {};
338
- if (mod != null)
339
- for (var k in mod)
340
- k !== "default" && Object.prototype.hasOwnProperty.call(mod, k) && __createBinding(result, mod, k);
341
- return __setModuleDefault(result, mod), result;
342
- }
343
- function __importDefault(mod) {
344
- return mod && mod.__esModule ? mod : { default: mod };
345
- }
346
- function __classPrivateFieldGet(receiver, state, kind, f2) {
347
- if (kind === "a" && !f2)
348
- throw new TypeError("Private accessor was defined without a getter");
349
- if (typeof state == "function" ? receiver !== state || !f2 : !state.has(receiver))
350
- throw new TypeError("Cannot read private member from an object whose class did not declare it");
351
- return kind === "m" ? f2 : kind === "a" ? f2.call(receiver) : f2 ? f2.value : state.get(receiver);
352
- }
353
- function __classPrivateFieldSet(receiver, state, value, kind, f2) {
354
- if (kind === "m")
355
- throw new TypeError("Private method is not writable");
356
- if (kind === "a" && !f2)
357
- throw new TypeError("Private accessor was defined without a setter");
358
- if (typeof state == "function" ? receiver !== state || !f2 : !state.has(receiver))
359
- throw new TypeError("Cannot write private member to an object whose class did not declare it");
360
- return kind === "a" ? f2.call(receiver, value) : f2 ? f2.value = value : state.set(receiver, value), value;
361
- }
362
- function __classPrivateFieldIn(state, receiver) {
363
- if (receiver === null || typeof receiver != "object" && typeof receiver != "function")
364
- throw new TypeError("Cannot use 'in' operator on non-object");
365
- return typeof state == "function" ? receiver === state : state.has(receiver);
366
- }
367
- function __addDisposableResource(env, value, async) {
368
- if (value != null) {
369
- if (typeof value != "object" && typeof value != "function")
370
- throw new TypeError("Object expected.");
371
- var dispose;
372
- if (async) {
373
- if (!Symbol.asyncDispose)
374
- throw new TypeError("Symbol.asyncDispose is not defined.");
375
- dispose = value[Symbol.asyncDispose];
376
- }
377
- if (dispose === void 0) {
378
- if (!Symbol.dispose)
379
- throw new TypeError("Symbol.dispose is not defined.");
380
- dispose = value[Symbol.dispose];
381
- }
382
- if (typeof dispose != "function")
383
- throw new TypeError("Object not disposable.");
384
- env.stack.push({ value, dispose, async });
385
- } else
386
- async && env.stack.push({ async: !0 });
387
- return value;
388
- }
389
- var _SuppressedError = typeof SuppressedError == "function" ? SuppressedError : function(error, suppressed, message) {
390
- var e = new Error(message);
391
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
392
- };
393
- function __disposeResources(env) {
394
- function fail(e) {
395
- env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e, env.hasError = !0;
396
- }
397
- function next() {
398
- for (; env.stack.length; ) {
399
- var rec = env.stack.pop();
400
- try {
401
- var result = rec.dispose && rec.dispose.call(rec.value);
402
- if (rec.async)
403
- return Promise.resolve(result).then(next, function(e) {
404
- return fail(e), next();
405
- });
406
- } catch (e) {
407
- fail(e);
408
- }
409
- }
410
- if (env.hasError)
411
- throw env.error;
412
- }
413
- return next();
414
- }
415
- var tslib_es6 = {
416
- __extends,
417
- __assign,
418
- __rest,
419
- __decorate,
420
- __param,
421
- __metadata,
422
- __awaiter,
423
- __generator,
424
- __createBinding,
425
- __exportStar,
426
- __values,
427
- __read,
428
- __spread,
429
- __spreadArrays,
430
- __spreadArray,
431
- __await,
432
- __asyncGenerator,
433
- __asyncDelegator,
434
- __asyncValues,
435
- __makeTemplateObject,
436
- __importStar,
437
- __importDefault,
438
- __classPrivateFieldGet,
439
- __classPrivateFieldSet,
440
- __classPrivateFieldIn,
441
- __addDisposableResource,
442
- __disposeResources
443
- }, tslib_es6$1 = /* @__PURE__ */ Object.freeze({
444
- __proto__: null,
445
- __addDisposableResource,
446
- get __assign() {
447
- return __assign;
448
- },
449
- __asyncDelegator,
450
- __asyncGenerator,
451
- __asyncValues,
452
- __await,
453
- __awaiter,
454
- __classPrivateFieldGet,
455
- __classPrivateFieldIn,
456
- __classPrivateFieldSet,
457
- __createBinding,
458
- __decorate,
459
- __disposeResources,
460
- __esDecorate,
461
- __exportStar,
462
- __extends,
463
- __generator,
464
- __importDefault,
465
- __importStar,
466
- __makeTemplateObject,
467
- __metadata,
468
- __param,
469
- __propKey,
470
- __read,
471
- __rest,
472
- __runInitializers,
473
- __setFunctionName,
474
- __spread,
475
- __spreadArray,
476
- __spreadArrays,
477
- __values,
478
- default: tslib_es6
479
- });
480
- function isFunction(value) {
481
- return typeof value == "function";
482
- }
483
- function createErrorClass(createImpl) {
484
- var _super = function(instance) {
485
- Error.call(instance), instance.stack = new Error().stack;
486
- }, ctorFunc = createImpl(_super);
487
- return ctorFunc.prototype = Object.create(Error.prototype), ctorFunc.prototype.constructor = ctorFunc, ctorFunc;
488
- }
489
- var UnsubscriptionError = createErrorClass(function(_super) {
490
- return function(errors) {
491
- _super(this), this.message = errors ? errors.length + ` errors occurred during unsubscription:
492
- ` + errors.map(function(err, i) {
493
- return i + 1 + ") " + err.toString();
494
- }).join(`
495
- `) : "", this.name = "UnsubscriptionError", this.errors = errors;
496
- };
497
- });
498
- function arrRemove(arr, item) {
499
- if (arr) {
500
- var index2 = arr.indexOf(item);
501
- 0 <= index2 && arr.splice(index2, 1);
502
- }
503
- }
504
- var Subscription = function() {
505
- function Subscription2(initialTeardown) {
506
- this.initialTeardown = initialTeardown, this.closed = !1, this._parentage = null, this._finalizers = null;
507
- }
508
- return Subscription2.prototype.unsubscribe = function() {
509
- var e_1, _a, e_2, _b, errors;
510
- if (!this.closed) {
511
- this.closed = !0;
512
- var _parentage = this._parentage;
513
- if (_parentage)
514
- if (this._parentage = null, Array.isArray(_parentage))
515
- try {
516
- for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
517
- var parent_1 = _parentage_1_1.value;
518
- parent_1.remove(this);
519
- }
520
- } catch (e_1_1) {
521
- e_1 = { error: e_1_1 };
522
- } finally {
523
- try {
524
- _parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return) && _a.call(_parentage_1);
525
- } finally {
526
- if (e_1)
527
- throw e_1.error;
528
- }
529
- }
530
- else
531
- _parentage.remove(this);
532
- var initialFinalizer = this.initialTeardown;
533
- if (isFunction(initialFinalizer))
534
- try {
535
- initialFinalizer();
536
- } catch (e) {
537
- errors = e instanceof UnsubscriptionError ? e.errors : [e];
538
- }
539
- var _finalizers = this._finalizers;
540
- if (_finalizers) {
541
- this._finalizers = null;
542
- try {
543
- for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
544
- var finalizer = _finalizers_1_1.value;
545
- try {
546
- execFinalizer(finalizer);
547
- } catch (err) {
548
- errors = errors ?? [], err instanceof UnsubscriptionError ? errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors)) : errors.push(err);
549
- }
550
- }
551
- } catch (e_2_1) {
552
- e_2 = { error: e_2_1 };
553
- } finally {
554
- try {
555
- _finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return) && _b.call(_finalizers_1);
556
- } finally {
557
- if (e_2)
558
- throw e_2.error;
559
- }
560
- }
561
- }
562
- if (errors)
563
- throw new UnsubscriptionError(errors);
564
- }
565
- }, Subscription2.prototype.add = function(teardown) {
566
- var _a;
567
- if (teardown && teardown !== this)
568
- if (this.closed)
569
- execFinalizer(teardown);
570
- else {
571
- if (teardown instanceof Subscription2) {
572
- if (teardown.closed || teardown._hasParent(this))
573
- return;
574
- teardown._addParent(this);
575
- }
576
- (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
577
- }
578
- }, Subscription2.prototype._hasParent = function(parent) {
579
- var _parentage = this._parentage;
580
- return _parentage === parent || Array.isArray(_parentage) && _parentage.includes(parent);
581
- }, Subscription2.prototype._addParent = function(parent) {
582
- var _parentage = this._parentage;
583
- this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
584
- }, Subscription2.prototype._removeParent = function(parent) {
585
- var _parentage = this._parentage;
586
- _parentage === parent ? this._parentage = null : Array.isArray(_parentage) && arrRemove(_parentage, parent);
587
- }, Subscription2.prototype.remove = function(teardown) {
588
- var _finalizers = this._finalizers;
589
- _finalizers && arrRemove(_finalizers, teardown), teardown instanceof Subscription2 && teardown._removeParent(this);
590
- }, Subscription2.EMPTY = function() {
591
- var empty = new Subscription2();
592
- return empty.closed = !0, empty;
593
- }(), Subscription2;
594
- }();
595
- function isSubscription(value) {
596
- return value instanceof Subscription || value && "closed" in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe);
597
- }
598
- function execFinalizer(finalizer) {
599
- isFunction(finalizer) ? finalizer() : finalizer.unsubscribe();
600
- }
601
- var config$1 = {
602
- onUnhandledError: null,
603
- onStoppedNotification: null,
604
- Promise: void 0,
605
- useDeprecatedSynchronousErrorHandling: !1,
606
- useDeprecatedNextContext: !1
607
- }, timeoutProvider = {
608
- setTimeout: function(handler, timeout) {
609
- for (var args = [], _i = 2; _i < arguments.length; _i++)
610
- args[_i - 2] = arguments[_i];
611
- return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));
612
- },
613
- clearTimeout: function(handle) {
614
- return clearTimeout(handle);
615
- },
616
- delegate: void 0
617
- };
618
- function reportUnhandledError(err) {
619
- timeoutProvider.setTimeout(function() {
620
- throw err;
621
- });
622
- }
623
- function noop() {
624
- }
625
- function errorContext(cb) {
626
- cb();
627
- }
628
- var Subscriber = function(_super) {
629
- __extends(Subscriber2, _super);
630
- function Subscriber2(destination) {
631
- var _this = _super.call(this) || this;
632
- return _this.isStopped = !1, destination ? (_this.destination = destination, isSubscription(destination) && destination.add(_this)) : _this.destination = EMPTY_OBSERVER, _this;
633
- }
634
- return Subscriber2.create = function(next, error, complete) {
635
- return new SafeSubscriber(next, error, complete);
636
- }, Subscriber2.prototype.next = function(value) {
637
- this.isStopped || this._next(value);
638
- }, Subscriber2.prototype.error = function(err) {
639
- this.isStopped || (this.isStopped = !0, this._error(err));
640
- }, Subscriber2.prototype.complete = function() {
641
- this.isStopped || (this.isStopped = !0, this._complete());
642
- }, Subscriber2.prototype.unsubscribe = function() {
643
- this.closed || (this.isStopped = !0, _super.prototype.unsubscribe.call(this), this.destination = null);
644
- }, Subscriber2.prototype._next = function(value) {
645
- this.destination.next(value);
646
- }, Subscriber2.prototype._error = function(err) {
647
- try {
648
- this.destination.error(err);
649
- } finally {
650
- this.unsubscribe();
651
- }
652
- }, Subscriber2.prototype._complete = function() {
653
- try {
654
- this.destination.complete();
655
- } finally {
656
- this.unsubscribe();
657
- }
658
- }, Subscriber2;
659
- }(Subscription), _bind = Function.prototype.bind;
660
- function bind(fn, thisArg) {
661
- return _bind.call(fn, thisArg);
662
- }
663
- var ConsumerObserver = function() {
664
- function ConsumerObserver2(partialObserver) {
665
- this.partialObserver = partialObserver;
666
- }
667
- return ConsumerObserver2.prototype.next = function(value) {
668
- var partialObserver = this.partialObserver;
669
- if (partialObserver.next)
670
- try {
671
- partialObserver.next(value);
672
- } catch (error) {
673
- handleUnhandledError(error);
674
- }
675
- }, ConsumerObserver2.prototype.error = function(err) {
676
- var partialObserver = this.partialObserver;
677
- if (partialObserver.error)
678
- try {
679
- partialObserver.error(err);
680
- } catch (error) {
681
- handleUnhandledError(error);
682
- }
683
- else
684
- handleUnhandledError(err);
685
- }, ConsumerObserver2.prototype.complete = function() {
686
- var partialObserver = this.partialObserver;
687
- if (partialObserver.complete)
688
- try {
689
- partialObserver.complete();
690
- } catch (error) {
691
- handleUnhandledError(error);
692
- }
693
- }, ConsumerObserver2;
694
- }(), SafeSubscriber = function(_super) {
695
- __extends(SafeSubscriber2, _super);
696
- function SafeSubscriber2(observerOrNext, error, complete) {
697
- var _this = _super.call(this) || this, partialObserver;
698
- if (isFunction(observerOrNext) || !observerOrNext)
699
- partialObserver = {
700
- next: observerOrNext ?? void 0,
701
- error: error ?? void 0,
702
- complete: complete ?? void 0
703
- };
704
- else {
705
- var context_1;
706
- _this && config$1.useDeprecatedNextContext ? (context_1 = Object.create(observerOrNext), context_1.unsubscribe = function() {
707
- return _this.unsubscribe();
708
- }, partialObserver = {
709
- next: observerOrNext.next && bind(observerOrNext.next, context_1),
710
- error: observerOrNext.error && bind(observerOrNext.error, context_1),
711
- complete: observerOrNext.complete && bind(observerOrNext.complete, context_1)
712
- }) : partialObserver = observerOrNext;
713
- }
714
- return _this.destination = new ConsumerObserver(partialObserver), _this;
715
- }
716
- return SafeSubscriber2;
717
- }(Subscriber);
718
- function handleUnhandledError(error) {
719
- reportUnhandledError(error);
720
- }
721
- function defaultErrorHandler(err) {
722
- throw err;
723
- }
724
- var EMPTY_OBSERVER = {
725
- closed: !0,
726
- next: noop,
727
- error: defaultErrorHandler,
728
- complete: noop
729
- }, observable = function() {
730
- return typeof Symbol == "function" && Symbol.observable || "@@observable";
731
- }();
732
- function identity(x) {
733
- return x;
734
- }
735
- function pipe() {
736
- for (var fns = [], _i = 0; _i < arguments.length; _i++)
737
- fns[_i] = arguments[_i];
738
- return pipeFromArray(fns);
739
- }
740
- function pipeFromArray(fns) {
741
- return fns.length === 0 ? identity : fns.length === 1 ? fns[0] : function(input) {
742
- return fns.reduce(function(prev, fn) {
743
- return fn(prev);
744
- }, input);
745
- };
746
- }
747
- var Observable = function() {
748
- function Observable2(subscribe) {
749
- subscribe && (this._subscribe = subscribe);
750
- }
751
- return Observable2.prototype.lift = function(operator) {
752
- var observable2 = new Observable2();
753
- return observable2.source = this, observable2.operator = operator, observable2;
754
- }, Observable2.prototype.subscribe = function(observerOrNext, error, complete) {
755
- var _this = this, subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
756
- return errorContext(function() {
757
- var _a = _this, operator = _a.operator, source = _a.source;
758
- subscriber.add(operator ? operator.call(subscriber, source) : source ? _this._subscribe(subscriber) : _this._trySubscribe(subscriber));
759
- }), subscriber;
760
- }, Observable2.prototype._trySubscribe = function(sink) {
761
- try {
762
- return this._subscribe(sink);
763
- } catch (err) {
764
- sink.error(err);
765
- }
766
- }, Observable2.prototype.forEach = function(next, promiseCtor) {
767
- var _this = this;
768
- return promiseCtor = getPromiseCtor(promiseCtor), new promiseCtor(function(resolve, reject) {
769
- var subscriber = new SafeSubscriber({
770
- next: function(value) {
771
- try {
772
- next(value);
773
- } catch (err) {
774
- reject(err), subscriber.unsubscribe();
775
- }
776
- },
777
- error: reject,
778
- complete: resolve
779
- });
780
- _this.subscribe(subscriber);
781
- });
782
- }, Observable2.prototype._subscribe = function(subscriber) {
783
- var _a;
784
- return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);
785
- }, Observable2.prototype[observable] = function() {
786
- return this;
787
- }, Observable2.prototype.pipe = function() {
788
- for (var operations = [], _i = 0; _i < arguments.length; _i++)
789
- operations[_i] = arguments[_i];
790
- return pipeFromArray(operations)(this);
791
- }, Observable2.prototype.toPromise = function(promiseCtor) {
792
- var _this = this;
793
- return promiseCtor = getPromiseCtor(promiseCtor), new promiseCtor(function(resolve, reject) {
794
- var value;
795
- _this.subscribe(function(x) {
796
- return value = x;
797
- }, function(err) {
798
- return reject(err);
799
- }, function() {
800
- return resolve(value);
801
- });
802
- });
803
- }, Observable2.create = function(subscribe) {
804
- return new Observable2(subscribe);
805
- }, Observable2;
806
- }();
807
- function getPromiseCtor(promiseCtor) {
808
- var _a;
809
- return (_a = promiseCtor ?? config$1.Promise) !== null && _a !== void 0 ? _a : Promise;
810
- }
811
- function isObserver(value) {
812
- return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);
813
- }
814
- function isSubscriber(value) {
815
- return value && value instanceof Subscriber || isObserver(value) && isSubscription(value);
816
- }
817
- function hasLift(source) {
818
- return isFunction(source?.lift);
819
- }
820
- function operate(init) {
821
- return function(source) {
822
- if (hasLift(source))
823
- return source.lift(function(liftedSource) {
824
- try {
825
- return init(liftedSource, this);
826
- } catch (err) {
827
- this.error(err);
828
- }
829
- });
830
- throw new TypeError("Unable to lift unknown Observable type");
831
- };
832
- }
833
- function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
834
- return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
835
- }
836
- var OperatorSubscriber = function(_super) {
837
- __extends(OperatorSubscriber2, _super);
838
- function OperatorSubscriber2(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
839
- var _this = _super.call(this, destination) || this;
840
- return _this.onFinalize = onFinalize, _this.shouldUnsubscribe = shouldUnsubscribe, _this._next = onNext ? function(value) {
841
- try {
842
- onNext(value);
843
- } catch (err) {
844
- destination.error(err);
845
- }
846
- } : _super.prototype._next, _this._error = onError ? function(err) {
847
- try {
848
- onError(err);
849
- } catch (err2) {
850
- destination.error(err2);
851
- } finally {
852
- this.unsubscribe();
853
- }
854
- } : _super.prototype._error, _this._complete = onComplete ? function() {
855
- try {
856
- onComplete();
857
- } catch (err) {
858
- destination.error(err);
859
- } finally {
860
- this.unsubscribe();
861
- }
862
- } : _super.prototype._complete, _this;
863
- }
864
- return OperatorSubscriber2.prototype.unsubscribe = function() {
865
- var _a;
866
- if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
867
- var closed_1 = this.closed;
868
- _super.prototype.unsubscribe.call(this), !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 || _a.call(this));
869
- }
870
- }, OperatorSubscriber2;
871
- }(Subscriber);
872
- function last(arr) {
873
- return arr[arr.length - 1];
874
- }
875
- function popResultSelector(args) {
876
- return isFunction(last(args)) ? args.pop() : void 0;
877
- }
878
- var isArrayLike = function(x) {
879
- return x && typeof x.length == "number" && typeof x != "function";
880
- };
881
- function isPromise(value) {
882
- return isFunction(value?.then);
883
- }
884
- function isInteropObservable(input) {
885
- return isFunction(input[observable]);
886
- }
887
- function isAsyncIterable(obj) {
888
- return Symbol.asyncIterator && isFunction(obj?.[Symbol.asyncIterator]);
889
- }
890
- function createInvalidObservableTypeError(input) {
891
- return new TypeError("You provided " + (input !== null && typeof input == "object" ? "an invalid object" : "'" + input + "'") + " where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.");
892
- }
893
- function getSymbolIterator() {
894
- return typeof Symbol != "function" || !Symbol.iterator ? "@@iterator" : Symbol.iterator;
895
- }
896
- var iterator = getSymbolIterator();
897
- function isIterable(input) {
898
- return isFunction(input?.[iterator]);
899
- }
900
- function readableStreamLikeToAsyncGenerator(readableStream) {
901
- return __asyncGenerator(this, arguments, function() {
902
- var reader, _a, value, done;
903
- return __generator(this, function(_b) {
904
- switch (_b.label) {
905
- case 0:
906
- reader = readableStream.getReader(), _b.label = 1;
907
- case 1:
908
- _b.trys.push([1, , 9, 10]), _b.label = 2;
909
- case 2:
910
- return [4, __await(reader.read())];
911
- case 3:
912
- return _a = _b.sent(), value = _a.value, done = _a.done, done ? [4, __await(void 0)] : [3, 5];
913
- case 4:
914
- return [2, _b.sent()];
915
- case 5:
916
- return [4, __await(value)];
917
- case 6:
918
- return [4, _b.sent()];
919
- case 7:
920
- return _b.sent(), [3, 2];
921
- case 8:
922
- return [3, 10];
923
- case 9:
924
- return reader.releaseLock(), [7];
925
- case 10:
926
- return [2];
927
- }
928
- });
929
- });
930
- }
931
- function isReadableStreamLike(obj) {
932
- return isFunction(obj?.getReader);
933
- }
934
- function innerFrom(input) {
935
- if (input instanceof Observable)
936
- return input;
937
- if (input != null) {
938
- if (isInteropObservable(input))
939
- return fromInteropObservable(input);
940
- if (isArrayLike(input))
941
- return fromArrayLike(input);
942
- if (isPromise(input))
943
- return fromPromise(input);
944
- if (isAsyncIterable(input))
945
- return fromAsyncIterable(input);
946
- if (isIterable(input))
947
- return fromIterable(input);
948
- if (isReadableStreamLike(input))
949
- return fromReadableStreamLike(input);
950
- }
951
- throw createInvalidObservableTypeError(input);
952
- }
953
- function fromInteropObservable(obj) {
954
- return new Observable(function(subscriber) {
955
- var obs = obj[observable]();
956
- if (isFunction(obs.subscribe))
957
- return obs.subscribe(subscriber);
958
- throw new TypeError("Provided object does not correctly implement Symbol.observable");
959
- });
960
- }
961
- function fromArrayLike(array) {
962
- return new Observable(function(subscriber) {
963
- for (var i = 0; i < array.length && !subscriber.closed; i++)
964
- subscriber.next(array[i]);
965
- subscriber.complete();
966
- });
967
- }
968
- function fromPromise(promise) {
969
- return new Observable(function(subscriber) {
970
- promise.then(function(value) {
971
- subscriber.closed || (subscriber.next(value), subscriber.complete());
972
- }, function(err) {
973
- return subscriber.error(err);
974
- }).then(null, reportUnhandledError);
975
- });
976
- }
977
- function fromIterable(iterable) {
978
- return new Observable(function(subscriber) {
979
- var e_1, _a;
980
- try {
981
- for (var iterable_1 = __values(iterable), iterable_1_1 = iterable_1.next(); !iterable_1_1.done; iterable_1_1 = iterable_1.next()) {
982
- var value = iterable_1_1.value;
983
- if (subscriber.next(value), subscriber.closed)
984
- return;
985
- }
986
- } catch (e_1_1) {
987
- e_1 = { error: e_1_1 };
988
- } finally {
989
- try {
990
- iterable_1_1 && !iterable_1_1.done && (_a = iterable_1.return) && _a.call(iterable_1);
991
- } finally {
992
- if (e_1)
993
- throw e_1.error;
994
- }
995
- }
996
- subscriber.complete();
997
- });
998
- }
999
- function fromAsyncIterable(asyncIterable) {
1000
- return new Observable(function(subscriber) {
1001
- process$1(asyncIterable, subscriber).catch(function(err) {
1002
- return subscriber.error(err);
1003
- });
1004
- });
1005
- }
1006
- function fromReadableStreamLike(readableStream) {
1007
- return fromAsyncIterable(readableStreamLikeToAsyncGenerator(readableStream));
1008
- }
1009
- function process$1(asyncIterable, subscriber) {
1010
- var asyncIterable_1, asyncIterable_1_1, e_2, _a;
1011
- return __awaiter(this, void 0, void 0, function() {
1012
- var value, e_2_1;
1013
- return __generator(this, function(_b) {
1014
- switch (_b.label) {
1015
- case 0:
1016
- _b.trys.push([0, 5, 6, 11]), asyncIterable_1 = __asyncValues(asyncIterable), _b.label = 1;
1017
- case 1:
1018
- return [4, asyncIterable_1.next()];
1019
- case 2:
1020
- if (asyncIterable_1_1 = _b.sent(), !!asyncIterable_1_1.done)
1021
- return [3, 4];
1022
- if (value = asyncIterable_1_1.value, subscriber.next(value), subscriber.closed)
1023
- return [2];
1024
- _b.label = 3;
1025
- case 3:
1026
- return [3, 1];
1027
- case 4:
1028
- return [3, 11];
1029
- case 5:
1030
- return e_2_1 = _b.sent(), e_2 = { error: e_2_1 }, [3, 11];
1031
- case 6:
1032
- return _b.trys.push([6, , 9, 10]), asyncIterable_1_1 && !asyncIterable_1_1.done && (_a = asyncIterable_1.return) ? [4, _a.call(asyncIterable_1)] : [3, 8];
1033
- case 7:
1034
- _b.sent(), _b.label = 8;
1035
- case 8:
1036
- return [3, 10];
1037
- case 9:
1038
- if (e_2)
1039
- throw e_2.error;
1040
- return [7];
1041
- case 10:
1042
- return [7];
1043
- case 11:
1044
- return subscriber.complete(), [2];
1045
- }
1046
- });
1047
- });
1048
- }
1049
- function executeSchedule(parentSubscription, scheduler, work, delay, repeat) {
1050
- delay === void 0 && (delay = 0), repeat === void 0 && (repeat = !1);
1051
- var scheduleSubscription = scheduler.schedule(function() {
1052
- work(), repeat ? parentSubscription.add(this.schedule(null, delay)) : this.unsubscribe();
1053
- }, delay);
1054
- if (parentSubscription.add(scheduleSubscription), !repeat)
1055
- return scheduleSubscription;
1056
- }
1057
- function observeOn(scheduler, delay) {
1058
- return delay === void 0 && (delay = 0), operate(function(source, subscriber) {
1059
- source.subscribe(createOperatorSubscriber(subscriber, function(value) {
1060
- return executeSchedule(subscriber, scheduler, function() {
1061
- return subscriber.next(value);
1062
- }, delay);
1063
- }, function() {
1064
- return executeSchedule(subscriber, scheduler, function() {
1065
- return subscriber.complete();
1066
- }, delay);
1067
- }, function(err) {
1068
- return executeSchedule(subscriber, scheduler, function() {
1069
- return subscriber.error(err);
1070
- }, delay);
1071
- }));
1072
- });
1073
- }
1074
- function subscribeOn(scheduler, delay) {
1075
- return delay === void 0 && (delay = 0), operate(function(source, subscriber) {
1076
- subscriber.add(scheduler.schedule(function() {
1077
- return source.subscribe(subscriber);
1078
- }, delay));
1079
- });
1080
- }
1081
- function scheduleObservable(input, scheduler) {
1082
- return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));
1083
- }
1084
- function schedulePromise(input, scheduler) {
1085
- return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));
1086
- }
1087
- function scheduleArray(input, scheduler) {
1088
- return new Observable(function(subscriber) {
1089
- var i = 0;
1090
- return scheduler.schedule(function() {
1091
- i === input.length ? subscriber.complete() : (subscriber.next(input[i++]), subscriber.closed || this.schedule());
1092
- });
1093
- });
1094
- }
1095
- function scheduleIterable(input, scheduler) {
1096
- return new Observable(function(subscriber) {
1097
- var iterator$1;
1098
- return executeSchedule(subscriber, scheduler, function() {
1099
- iterator$1 = input[iterator](), executeSchedule(subscriber, scheduler, function() {
1100
- var _a, value, done;
1101
- try {
1102
- _a = iterator$1.next(), value = _a.value, done = _a.done;
1103
- } catch (err) {
1104
- subscriber.error(err);
1105
- return;
1106
- }
1107
- done ? subscriber.complete() : subscriber.next(value);
1108
- }, 0, !0);
1109
- }), function() {
1110
- return isFunction(iterator$1?.return) && iterator$1.return();
1111
- };
1112
- });
1113
- }
1114
- function scheduleAsyncIterable(input, scheduler) {
1115
- if (!input)
1116
- throw new Error("Iterable cannot be null");
1117
- return new Observable(function(subscriber) {
1118
- executeSchedule(subscriber, scheduler, function() {
1119
- var iterator2 = input[Symbol.asyncIterator]();
1120
- executeSchedule(subscriber, scheduler, function() {
1121
- iterator2.next().then(function(result) {
1122
- result.done ? subscriber.complete() : subscriber.next(result.value);
1123
- });
1124
- }, 0, !0);
1125
- });
1126
- });
1127
- }
1128
- function scheduleReadableStreamLike(input, scheduler) {
1129
- return scheduleAsyncIterable(readableStreamLikeToAsyncGenerator(input), scheduler);
1130
- }
1131
- function scheduled(input, scheduler) {
1132
- if (input != null) {
1133
- if (isInteropObservable(input))
1134
- return scheduleObservable(input, scheduler);
1135
- if (isArrayLike(input))
1136
- return scheduleArray(input, scheduler);
1137
- if (isPromise(input))
1138
- return schedulePromise(input, scheduler);
1139
- if (isAsyncIterable(input))
1140
- return scheduleAsyncIterable(input, scheduler);
1141
- if (isIterable(input))
1142
- return scheduleIterable(input, scheduler);
1143
- if (isReadableStreamLike(input))
1144
- return scheduleReadableStreamLike(input, scheduler);
1145
- }
1146
- throw createInvalidObservableTypeError(input);
1147
- }
1148
- function from(input, scheduler) {
1149
- return scheduler ? scheduled(input, scheduler) : innerFrom(input);
1150
- }
1151
- var EmptyError = createErrorClass(function(_super) {
1152
- return function() {
1153
- _super(this), this.name = "EmptyError", this.message = "no elements in sequence";
1154
- };
1155
- });
1156
- function lastValueFrom(source, config2) {
1157
- var hasConfig = typeof config2 == "object";
1158
- return new Promise(function(resolve, reject) {
1159
- var _hasValue = !1, _value;
1160
- source.subscribe({
1161
- next: function(value) {
1162
- _value = value, _hasValue = !0;
1163
- },
1164
- error: reject,
1165
- complete: function() {
1166
- _hasValue ? resolve(_value) : hasConfig ? resolve(config2.defaultValue) : reject(new EmptyError());
1167
- }
1168
- });
1169
- });
1170
- }
1171
- function map(project, thisArg) {
1172
- return operate(function(source, subscriber) {
1173
- var index2 = 0;
1174
- source.subscribe(createOperatorSubscriber(subscriber, function(value) {
1175
- subscriber.next(project.call(thisArg, value, index2++));
1176
- }));
1177
- });
1178
- }
1179
- var isArray$1 = Array.isArray;
1180
- function callOrApply(fn, args) {
1181
- return isArray$1(args) ? fn.apply(void 0, __spreadArray([], __read(args))) : fn(args);
1182
- }
1183
- function mapOneOrManyArgs(fn) {
1184
- return map(function(args) {
1185
- return callOrApply(fn, args);
1186
- });
1187
- }
1188
- function combineLatestInit(observables, scheduler, valueTransform) {
1189
- return valueTransform === void 0 && (valueTransform = identity), function(subscriber) {
1190
- maybeSchedule(scheduler, function() {
1191
- for (var length = observables.length, values = new Array(length), active = length, remainingFirstValues = length, _loop_1 = function(i2) {
1192
- maybeSchedule(scheduler, function() {
1193
- var source = from(observables[i2], scheduler), hasFirstValue = !1;
1194
- source.subscribe(createOperatorSubscriber(subscriber, function(value) {
1195
- values[i2] = value, hasFirstValue || (hasFirstValue = !0, remainingFirstValues--), remainingFirstValues || subscriber.next(valueTransform(values.slice()));
1196
- }, function() {
1197
- --active || subscriber.complete();
1198
- }));
1199
- }, subscriber);
1200
- }, i = 0; i < length; i++)
1201
- _loop_1(i);
1202
- }, subscriber);
1203
- };
1204
- }
1205
- function maybeSchedule(scheduler, execute, subscription) {
1206
- scheduler ? executeSchedule(subscription, scheduler, execute) : execute();
1207
- }
1208
- var isArray = Array.isArray;
1209
- function argsOrArgArray(args) {
1210
- return args.length === 1 && isArray(args[0]) ? args[0] : args;
1211
- }
1212
- function filter(predicate, thisArg) {
1213
- return operate(function(source, subscriber) {
1214
- var index2 = 0;
1215
- source.subscribe(createOperatorSubscriber(subscriber, function(value) {
1216
- return predicate.call(thisArg, value, index2++) && subscriber.next(value);
1217
- }));
1218
- });
1219
- }
1220
- function combineLatest() {
1221
- for (var args = [], _i = 0; _i < arguments.length; _i++)
1222
- args[_i] = arguments[_i];
1223
- var resultSelector = popResultSelector(args);
1224
- return resultSelector ? pipe(combineLatest.apply(void 0, __spreadArray([], __read(args))), mapOneOrManyArgs(resultSelector)) : operate(function(source, subscriber) {
1225
- combineLatestInit(__spreadArray([source], __read(argsOrArgArray(args))))(subscriber);
1226
- });
1227
- }
1228
- function combineLatestWith() {
1229
- for (var otherSources = [], _i = 0; _i < arguments.length; _i++)
1230
- otherSources[_i] = arguments[_i];
1231
- return combineLatest.apply(void 0, __spreadArray([], __read(otherSources)));
1232
- }
1233
- class ClientError extends Error {
1234
- constructor(res) {
1235
- const props = extractErrorProps(res);
1236
- super(props.message), this.statusCode = 400, Object.assign(this, props);
1237
- }
1238
- }
1239
- class ServerError extends Error {
1240
- constructor(res) {
1241
- const props = extractErrorProps(res);
1242
- super(props.message), this.statusCode = 500, Object.assign(this, props);
1243
- }
1244
- }
1245
- function extractErrorProps(res) {
1246
- const body = res.body, props = {
1247
- response: res,
1248
- statusCode: res.statusCode,
1249
- responseBody: stringifyBody(body, res),
1250
- message: "",
1251
- details: void 0
1252
- };
1253
- if (body.error && body.message)
1254
- return props.message = `${body.error} - ${body.message}`, props;
1255
- if (isMutationError(body)) {
1256
- const allItems = body.error.items || [], items = allItems.slice(0, 5).map((item) => {
1257
- var _a;
1258
- return (_a = item.error) == null ? void 0 : _a.description;
1259
- }).filter(Boolean);
1260
- let itemsStr = items.length ? `:
1261
- - ${items.join(`
1262
- - `)}` : "";
1263
- return allItems.length > 5 && (itemsStr += `
1264
- ...and ${allItems.length - 5} more`), props.message = `${body.error.description}${itemsStr}`, props.details = body.error, props;
1265
- }
1266
- return body.error && body.error.description ? (props.message = body.error.description, props.details = body.error, props) : (props.message = body.error || body.message || httpErrorMessage(res), props);
1267
- }
1268
- function isMutationError(body) {
1269
- return isPlainObject(body) && isPlainObject(body.error) && body.error.type === "mutationError" && typeof body.error.description == "string";
1270
- }
1271
- function isPlainObject(obj) {
1272
- return typeof obj == "object" && obj !== null && !Array.isArray(obj);
1273
- }
1274
- function httpErrorMessage(res) {
1275
- const statusMessage = res.statusMessage ? ` ${res.statusMessage}` : "";
1276
- return `${res.method}-request to ${res.url} resulted in HTTP ${res.statusCode}${statusMessage}`;
1277
- }
1278
- function stringifyBody(body, res) {
1279
- return (res.headers["content-type"] || "").toLowerCase().indexOf("application/json") !== -1 ? JSON.stringify(body, null, 2) : body;
1280
- }
1281
- const httpError = {
1282
- onResponse: (res) => {
1283
- if (res.statusCode >= 500)
1284
- throw new ServerError(res);
1285
- if (res.statusCode >= 400)
1286
- throw new ClientError(res);
1287
- return res;
1288
- }
1289
- }, printWarnings = {
1290
- onResponse: (res) => {
1291
- const warn = res.headers["x-sanity-warning"];
1292
- return (Array.isArray(warn) ? warn : [warn]).filter(Boolean).forEach((msg) => console.warn(msg)), res;
1293
- }
1294
- };
1295
- function defineHttpRequest(envMiddleware, {
1296
- maxRetries = 5,
1297
- retryDelay
1298
- }) {
1299
- const request = require$$1.getIt([
1300
- maxRetries > 0 ? require$$2.retry({
1301
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1302
- retryDelay,
1303
- // This option is typed incorrectly in get-it.
1304
- maxRetries,
1305
- shouldRetry
1306
- }) : {},
1307
- ...envMiddleware,
1308
- printWarnings,
1309
- require$$2.jsonRequest(),
1310
- require$$2.jsonResponse(),
1311
- require$$2.progress(),
1312
- httpError,
1313
- require$$2.observable({ implementation: Observable })
1314
- ]);
1315
- function httpRequest(options, requester2 = request) {
1316
- return requester2({ maxRedirects: 0, ...options });
1317
- }
1318
- return httpRequest.defaultRequester = request, httpRequest;
1319
- }
1320
- function shouldRetry(err, attempt, options) {
1321
- const isSafe = options.method === "GET" || options.method === "HEAD", isQuery = (options.uri || options.url).startsWith("/data/query"), isRetriableResponse = err.response && (err.response.statusCode === 429 || err.response.statusCode === 502 || err.response.statusCode === 503);
1322
- return (isSafe || isQuery) && isRetriableResponse ? !0 : require$$2.retry.shouldRetry(err, attempt, options);
1323
- }
1324
- function getSelection(sel) {
1325
- if (typeof sel == "string")
1326
- return { id: sel };
1327
- if (Array.isArray(sel))
1328
- return { query: "*[_id in $ids]", params: { ids: sel } };
1329
- if (typeof sel == "object" && sel !== null && "query" in sel && typeof sel.query == "string")
1330
- return "params" in sel && typeof sel.params == "object" && sel.params !== null ? { query: sel.query, params: sel.params } : { query: sel.query };
1331
- const selectionOpts = [
1332
- "* Document ID (<docId>)",
1333
- "* Array of document IDs",
1334
- "* Object containing `query`"
1335
- ].join(`
1336
- `);
1337
- throw new Error(`Unknown selection - must be one of:
1338
-
1339
- ${selectionOpts}`);
1340
- }
1341
- const VALID_ASSET_TYPES = ["image", "file"], VALID_INSERT_LOCATIONS = ["before", "after", "replace"], dataset = (name2) => {
1342
- if (!/^(~[a-z0-9]{1}[-\w]{0,63}|[a-z0-9]{1}[-\w]{0,63})$/.test(name2))
1343
- throw new Error(
1344
- "Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters"
1345
- );
1346
- }, projectId = (id) => {
1347
- if (!/^[-a-z0-9]+$/i.test(id))
1348
- throw new Error("`projectId` can only contain only a-z, 0-9 and dashes");
1349
- }, validateAssetType = (type) => {
1350
- if (VALID_ASSET_TYPES.indexOf(type) === -1)
1351
- throw new Error(`Invalid asset type: ${type}. Must be one of ${VALID_ASSET_TYPES.join(", ")}`);
1352
- }, validateObject = (op, val) => {
1353
- if (val === null || typeof val != "object" || Array.isArray(val))
1354
- throw new Error(`${op}() takes an object of properties`);
1355
- }, validateDocumentId = (op, id) => {
1356
- if (typeof id != "string" || !/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(id) || id.includes(".."))
1357
- throw new Error(`${op}(): "${id}" is not a valid document ID`);
1358
- }, requireDocumentId = (op, doc) => {
1359
- if (!doc._id)
1360
- throw new Error(`${op}() requires that the document contains an ID ("_id" property)`);
1361
- validateDocumentId(op, doc._id);
1362
- }, validateInsert = (at, selector, items) => {
1363
- const signature = "insert(at, selector, items)";
1364
- if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {
1365
- const valid = VALID_INSERT_LOCATIONS.map((loc) => `"${loc}"`).join(", ");
1366
- throw new Error(`${signature} takes an "at"-argument which is one of: ${valid}`);
1367
- }
1368
- if (typeof selector != "string")
1369
- throw new Error(`${signature} takes a "selector"-argument which must be a string`);
1370
- if (!Array.isArray(items))
1371
- throw new Error(`${signature} takes an "items"-argument which must be an array`);
1372
- }, hasDataset = (config2) => {
1373
- if (!config2.dataset)
1374
- throw new Error("`dataset` must be provided to perform queries");
1375
- return config2.dataset || "";
1376
- }, requestTag = (tag) => {
1377
- if (typeof tag != "string" || !/^[a-z0-9._-]{1,75}$/i.test(tag))
1378
- throw new Error(
1379
- "Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long."
1380
- );
1381
- return tag;
1382
- };
1383
- var __accessCheck$6 = (obj, member, msg) => {
1384
- if (!member.has(obj))
1385
- throw TypeError("Cannot " + msg);
1386
- }, __privateGet$6 = (obj, member, getter) => (__accessCheck$6(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)), __privateAdd$6 = (obj, member, value) => {
1387
- if (member.has(obj))
1388
- throw TypeError("Cannot add the same private member more than once");
1389
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1390
- }, __privateSet$6 = (obj, member, value, setter) => (__accessCheck$6(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
1391
- class BasePatch {
1392
- constructor(selection, operations = {}) {
1393
- this.selection = selection, this.operations = operations;
1394
- }
1395
- /**
1396
- * Sets the given attributes to the document. Does NOT merge objects.
1397
- * The operation is added to the current patch, ready to be commited by `commit()`
1398
- *
1399
- * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "value"\}
1400
- */
1401
- set(attrs) {
1402
- return this._assign("set", attrs);
1403
- }
1404
- /**
1405
- * Sets the given attributes to the document if they are not currently set. Does NOT merge objects.
1406
- * The operation is added to the current patch, ready to be commited by `commit()`
1407
- *
1408
- * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "value"\}
1409
- */
1410
- setIfMissing(attrs) {
1411
- return this._assign("setIfMissing", attrs);
1412
- }
1413
- /**
1414
- * Performs a "diff-match-patch" operation on the string attributes provided.
1415
- * The operation is added to the current patch, ready to be commited by `commit()`
1416
- *
1417
- * @param attrs - Attributes to perform operation on. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "dmp"\}
1418
- */
1419
- diffMatchPatch(attrs) {
1420
- return validateObject("diffMatchPatch", attrs), this._assign("diffMatchPatch", attrs);
1421
- }
1422
- /**
1423
- * Unsets the attribute paths provided.
1424
- * The operation is added to the current patch, ready to be commited by `commit()`
1425
- *
1426
- * @param attrs - Attribute paths to unset.
1427
- */
1428
- unset(attrs) {
1429
- if (!Array.isArray(attrs))
1430
- throw new Error("unset(attrs) takes an array of attributes to unset, non-array given");
1431
- return this.operations = Object.assign({}, this.operations, { unset: attrs }), this;
1432
- }
1433
- /**
1434
- * Increment a numeric value. Each entry in the argument is either an attribute or a JSON path. The value may be a positive or negative integer or floating-point value. The operation will fail if target value is not a numeric value, or doesn't exist.
1435
- *
1436
- * @param attrs - Object of attribute paths to increment, values representing the number to increment by.
1437
- */
1438
- inc(attrs) {
1439
- return this._assign("inc", attrs);
1440
- }
1441
- /**
1442
- * Decrement a numeric value. Each entry in the argument is either an attribute or a JSON path. The value may be a positive or negative integer or floating-point value. The operation will fail if target value is not a numeric value, or doesn't exist.
1443
- *
1444
- * @param attrs - Object of attribute paths to decrement, values representing the number to decrement by.
1445
- */
1446
- dec(attrs) {
1447
- return this._assign("dec", attrs);
1448
- }
1449
- /**
1450
- * Provides methods for modifying arrays, by inserting, appending and replacing elements via a JSONPath expression.
1451
- *
1452
- * @param at - Location to insert at, relative to the given selector, or 'replace' the matched path
1453
- * @param selector - JSONPath expression, eg `comments[-1]` or `blocks[_key=="abc123"]`
1454
- * @param items - Array of items to insert/replace
1455
- */
1456
- insert(at, selector, items) {
1457
- return validateInsert(at, selector, items), this._assign("insert", { [at]: selector, items });
1458
- }
1459
- /**
1460
- * Append the given items to the array at the given JSONPath
1461
- *
1462
- * @param selector - Attribute/path to append to, eg `comments` or `person.hobbies`
1463
- * @param items - Array of items to append to the array
1464
- */
1465
- append(selector, items) {
1466
- return this.insert("after", `${selector}[-1]`, items);
1467
- }
1468
- /**
1469
- * Prepend the given items to the array at the given JSONPath
1470
- *
1471
- * @param selector - Attribute/path to prepend to, eg `comments` or `person.hobbies`
1472
- * @param items - Array of items to prepend to the array
1473
- */
1474
- prepend(selector, items) {
1475
- return this.insert("before", `${selector}[0]`, items);
1476
- }
1477
- /**
1478
- * Change the contents of an array by removing existing elements and/or adding new elements.
1479
- *
1480
- * @param selector - Attribute or JSONPath expression for array
1481
- * @param start - Index at which to start changing the array (with origin 0). If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end of the array (with origin -1) and will be set to 0 if absolute value is greater than the length of the array.x
1482
- * @param deleteCount - An integer indicating the number of old array elements to remove.
1483
- * @param items - The elements to add to the array, beginning at the start index. If you don't specify any elements, splice() will only remove elements from the array.
1484
- */
1485
- splice(selector, start, deleteCount, items) {
1486
- const delAll = typeof deleteCount > "u" || deleteCount === -1, startIndex = start < 0 ? start - 1 : start, delCount = delAll ? -1 : Math.max(0, start + deleteCount), delRange = startIndex < 0 && delCount >= 0 ? "" : delCount, rangeSelector = `${selector}[${startIndex}:${delRange}]`;
1487
- return this.insert("replace", rangeSelector, items || []);
1488
- }
1489
- /**
1490
- * Adds a revision clause, preventing the document from being patched if the `_rev` property does not match the given value
1491
- *
1492
- * @param rev - Revision to lock the patch to
1493
- */
1494
- ifRevisionId(rev) {
1495
- return this.operations.ifRevisionID = rev, this;
1496
- }
1497
- /**
1498
- * Return a plain JSON representation of the patch
1499
- */
1500
- serialize() {
1501
- return { ...getSelection(this.selection), ...this.operations };
1502
- }
1503
- /**
1504
- * Return a plain JSON representation of the patch
1505
- */
1506
- toJSON() {
1507
- return this.serialize();
1508
- }
1509
- /**
1510
- * Clears the patch of all operations
1511
- */
1512
- reset() {
1513
- return this.operations = {}, this;
1514
- }
1515
- _assign(op, props, merge = !0) {
1516
- return validateObject(op, props), this.operations = Object.assign({}, this.operations, {
1517
- [op]: Object.assign({}, merge && this.operations[op] || {}, props)
1518
- }), this;
1519
- }
1520
- _set(op, props) {
1521
- return this._assign(op, props, !1);
1522
- }
1523
- }
1524
- var _client$5;
1525
- const _ObservablePatch = class _ObservablePatch2 extends BasePatch {
1526
- constructor(selection, operations, client) {
1527
- super(selection, operations), __privateAdd$6(this, _client$5, void 0), __privateSet$6(this, _client$5, client);
1528
- }
1529
- /**
1530
- * Clones the patch
1531
- */
1532
- clone() {
1533
- return new _ObservablePatch2(this.selection, { ...this.operations }, __privateGet$6(this, _client$5));
1534
- }
1535
- commit(options) {
1536
- if (!__privateGet$6(this, _client$5))
1537
- throw new Error(
1538
- "No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method"
1539
- );
1540
- const returnFirst = typeof this.selection == "string", opts = Object.assign({ returnFirst, returnDocuments: !0 }, options);
1541
- return __privateGet$6(this, _client$5).mutate({ patch: this.serialize() }, opts);
1542
- }
1543
- };
1544
- _client$5 = /* @__PURE__ */ new WeakMap();
1545
- let ObservablePatch = _ObservablePatch;
1546
- var _client2$5;
1547
- const _Patch = class _Patch2 extends BasePatch {
1548
- constructor(selection, operations, client) {
1549
- super(selection, operations), __privateAdd$6(this, _client2$5, void 0), __privateSet$6(this, _client2$5, client);
1550
- }
1551
- /**
1552
- * Clones the patch
1553
- */
1554
- clone() {
1555
- return new _Patch2(this.selection, { ...this.operations }, __privateGet$6(this, _client2$5));
1556
- }
1557
- commit(options) {
1558
- if (!__privateGet$6(this, _client2$5))
1559
- throw new Error(
1560
- "No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method"
1561
- );
1562
- const returnFirst = typeof this.selection == "string", opts = Object.assign({ returnFirst, returnDocuments: !0 }, options);
1563
- return __privateGet$6(this, _client2$5).mutate({ patch: this.serialize() }, opts);
1564
- }
1565
- };
1566
- _client2$5 = /* @__PURE__ */ new WeakMap();
1567
- let Patch = _Patch;
1568
- var __accessCheck$5 = (obj, member, msg) => {
1569
- if (!member.has(obj))
1570
- throw TypeError("Cannot " + msg);
1571
- }, __privateGet$5 = (obj, member, getter) => (__accessCheck$5(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)), __privateAdd$5 = (obj, member, value) => {
1572
- if (member.has(obj))
1573
- throw TypeError("Cannot add the same private member more than once");
1574
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1575
- }, __privateSet$5 = (obj, member, value, setter) => (__accessCheck$5(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
1576
- const defaultMutateOptions = { returnDocuments: !1 };
1577
- class BaseTransaction {
1578
- constructor(operations = [], transactionId) {
1579
- this.operations = operations, this.trxId = transactionId;
1580
- }
1581
- /**
1582
- * Creates a new Sanity document. If `_id` is provided and already exists, the mutation will fail. If no `_id` is given, one will automatically be generated by the database.
1583
- * The operation is added to the current transaction, ready to be commited by `commit()`
1584
- *
1585
- * @param doc - Document to create. Requires a `_type` property.
1586
- */
1587
- create(doc) {
1588
- return validateObject("create", doc), this._add({ create: doc });
1589
- }
1590
- /**
1591
- * Creates a new Sanity document. If a document with the same `_id` already exists, the create operation will be ignored.
1592
- * The operation is added to the current transaction, ready to be commited by `commit()`
1593
- *
1594
- * @param doc - Document to create if it does not already exist. Requires `_id` and `_type` properties.
1595
- */
1596
- createIfNotExists(doc) {
1597
- const op = "createIfNotExists";
1598
- return validateObject(op, doc), requireDocumentId(op, doc), this._add({ [op]: doc });
1599
- }
1600
- /**
1601
- * Creates a new Sanity document, or replaces an existing one if the same `_id` is already used.
1602
- * The operation is added to the current transaction, ready to be commited by `commit()`
1603
- *
1604
- * @param doc - Document to create or replace. Requires `_id` and `_type` properties.
1605
- */
1606
- createOrReplace(doc) {
1607
- const op = "createOrReplace";
1608
- return validateObject(op, doc), requireDocumentId(op, doc), this._add({ [op]: doc });
1609
- }
1610
- /**
1611
- * Deletes the document with the given document ID
1612
- * The operation is added to the current transaction, ready to be commited by `commit()`
1613
- *
1614
- * @param documentId - Document ID to delete
1615
- */
1616
- delete(documentId) {
1617
- return validateDocumentId("delete", documentId), this._add({ delete: { id: documentId } });
1618
- }
1619
- transactionId(id) {
1620
- return id ? (this.trxId = id, this) : this.trxId;
1621
- }
1622
- /**
1623
- * Return a plain JSON representation of the transaction
1624
- */
1625
- serialize() {
1626
- return [...this.operations];
1627
- }
1628
- /**
1629
- * Return a plain JSON representation of the transaction
1630
- */
1631
- toJSON() {
1632
- return this.serialize();
1633
- }
1634
- /**
1635
- * Clears the transaction of all operations
1636
- */
1637
- reset() {
1638
- return this.operations = [], this;
1639
- }
1640
- _add(mut) {
1641
- return this.operations.push(mut), this;
1642
- }
1643
- }
1644
- var _client$4;
1645
- const _Transaction = class _Transaction2 extends BaseTransaction {
1646
- constructor(operations, client, transactionId) {
1647
- super(operations, transactionId), __privateAdd$5(this, _client$4, void 0), __privateSet$5(this, _client$4, client);
1648
- }
1649
- /**
1650
- * Clones the transaction
1651
- */
1652
- clone() {
1653
- return new _Transaction2([...this.operations], __privateGet$5(this, _client$4), this.trxId);
1654
- }
1655
- commit(options) {
1656
- if (!__privateGet$5(this, _client$4))
1657
- throw new Error(
1658
- "No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method"
1659
- );
1660
- return __privateGet$5(this, _client$4).mutate(
1661
- this.serialize(),
1662
- Object.assign({ transactionId: this.trxId }, defaultMutateOptions, options || {})
1663
- );
1664
- }
1665
- patch(patchOrDocumentId, patchOps) {
1666
- const isBuilder = typeof patchOps == "function";
1667
- if (typeof patchOrDocumentId != "string" && patchOrDocumentId instanceof Patch)
1668
- return this._add({ patch: patchOrDocumentId.serialize() });
1669
- if (isBuilder) {
1670
- const patch = patchOps(new Patch(patchOrDocumentId, {}, __privateGet$5(this, _client$4)));
1671
- if (!(patch instanceof Patch))
1672
- throw new Error("function passed to `patch()` must return the patch");
1673
- return this._add({ patch: patch.serialize() });
1674
- }
1675
- return this._add({ patch: { id: patchOrDocumentId, ...patchOps } });
1676
- }
1677
- };
1678
- _client$4 = /* @__PURE__ */ new WeakMap();
1679
- let Transaction = _Transaction;
1680
- var _client2$4;
1681
- const _ObservableTransaction = class _ObservableTransaction2 extends BaseTransaction {
1682
- constructor(operations, client, transactionId) {
1683
- super(operations, transactionId), __privateAdd$5(this, _client2$4, void 0), __privateSet$5(this, _client2$4, client);
1684
- }
1685
- /**
1686
- * Clones the transaction
1687
- */
1688
- clone() {
1689
- return new _ObservableTransaction2([...this.operations], __privateGet$5(this, _client2$4), this.trxId);
1690
- }
1691
- commit(options) {
1692
- if (!__privateGet$5(this, _client2$4))
1693
- throw new Error(
1694
- "No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method"
1695
- );
1696
- return __privateGet$5(this, _client2$4).mutate(
1697
- this.serialize(),
1698
- Object.assign({ transactionId: this.trxId }, defaultMutateOptions, options || {})
1699
- );
1700
- }
1701
- patch(patchOrDocumentId, patchOps) {
1702
- const isBuilder = typeof patchOps == "function";
1703
- if (typeof patchOrDocumentId != "string" && patchOrDocumentId instanceof ObservablePatch)
1704
- return this._add({ patch: patchOrDocumentId.serialize() });
1705
- if (isBuilder) {
1706
- const patch = patchOps(new ObservablePatch(patchOrDocumentId, {}, __privateGet$5(this, _client2$4)));
1707
- if (!(patch instanceof ObservablePatch))
1708
- throw new Error("function passed to `patch()` must return the patch");
1709
- return this._add({ patch: patch.serialize() });
1710
- }
1711
- return this._add({ patch: { id: patchOrDocumentId, ...patchOps } });
1712
- }
1713
- };
1714
- _client2$4 = /* @__PURE__ */ new WeakMap();
1715
- let ObservableTransaction = _ObservableTransaction;
1716
- const BASE_URL = "https://www.sanity.io/help/";
1717
- function generateHelpUrl(slug) {
1718
- return BASE_URL + slug;
1719
- }
1720
- function once(fn) {
1721
- let didCall = !1, returnValue;
1722
- return (...args) => (didCall || (returnValue = fn(...args), didCall = !0), returnValue);
1723
- }
1724
- const createWarningPrinter = (message) => (
1725
- // eslint-disable-next-line no-console
1726
- once((...args) => console.warn(message.join(" "), ...args))
1727
- ), printCdnWarning = createWarningPrinter([
1728
- "Since you haven't set a value for `useCdn`, we will deliver content using our",
1729
- "global, edge-cached API-CDN. If you wish to have content delivered faster, set",
1730
- "`useCdn: false` to use the Live API. Note: You may incur higher costs using the live API."
1731
- ]), printCdnPreviewDraftsWarning = createWarningPrinter([
1732
- "The Sanity client is configured with the `perspective` set to `previewDrafts`, which doesn't support the API-CDN.",
1733
- "The Live API will be used instead. Set `useCdn: false` in your configuration to hide this warning."
1734
- ]), printBrowserTokenWarning = createWarningPrinter([
1735
- "You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.",
1736
- `See ${generateHelpUrl(
1737
- "js-client-browser-token"
1738
- )} for more information and how to hide this warning.`
1739
- ]), printNoApiVersionSpecifiedWarning = createWarningPrinter([
1740
- "Using the Sanity client without specifying an API version is deprecated.",
1741
- `See ${generateHelpUrl("js-client-api-version")}`
1742
- ]), defaultCdnHost = "apicdn.sanity.io", defaultConfig = {
1743
- apiHost: "https://api.sanity.io",
1744
- apiVersion: "1",
1745
- useProjectHostname: !0,
1746
- stega: { enabled: !1 }
1747
- }, LOCALHOSTS = ["localhost", "127.0.0.1", "0.0.0.0"], isLocal = (host) => LOCALHOSTS.indexOf(host) !== -1;
1748
- function validateApiVersion(apiVersion) {
1749
- if (apiVersion === "1" || apiVersion === "X")
1750
- return;
1751
- const apiDate = new Date(apiVersion);
1752
- if (!(/^\d{4}-\d{2}-\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0))
1753
- throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`");
1754
- }
1755
- const validateApiPerspective = function(perspective) {
1756
- switch (perspective) {
1757
- case "previewDrafts":
1758
- case "published":
1759
- case "raw":
1760
- return;
1761
- default:
1762
- throw new TypeError(
1763
- "Invalid API perspective string, expected `published`, `previewDrafts` or `raw`"
1764
- );
1765
- }
1766
- }, initConfig = (config2, prevConfig) => {
1767
- const specifiedConfig = {
1768
- ...prevConfig,
1769
- ...config2,
1770
- stega: {
1771
- ...typeof prevConfig.stega == "boolean" ? { enabled: prevConfig.stega } : prevConfig.stega || defaultConfig.stega,
1772
- ...typeof config2.stega == "boolean" ? { enabled: config2.stega } : config2.stega || {}
1773
- }
1774
- };
1775
- specifiedConfig.apiVersion || printNoApiVersionSpecifiedWarning();
1776
- const newConfig = {
1777
- ...defaultConfig,
1778
- ...specifiedConfig
1779
- }, projectBased = newConfig.useProjectHostname;
1780
- if (typeof Promise > "u") {
1781
- const helpUrl = generateHelpUrl("js-client-promise-polyfill");
1782
- throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`);
1783
- }
1784
- if (projectBased && !newConfig.projectId)
1785
- throw new Error("Configuration must contain `projectId`");
1786
- if (typeof newConfig.perspective == "string" && validateApiPerspective(newConfig.perspective), "encodeSourceMap" in newConfig)
1787
- throw new Error(
1788
- "It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMap' is not supported in '@sanity/client'. Did you mean 'stega.enabled'?"
1789
- );
1790
- if ("encodeSourceMapAtPath" in newConfig)
1791
- throw new Error(
1792
- "It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMapAtPath' is not supported in '@sanity/client'. Did you mean 'stega.filter'?"
1793
- );
1794
- if (typeof newConfig.stega.enabled != "boolean")
1795
- throw new Error(`stega.enabled must be a boolean, received ${newConfig.stega.enabled}`);
1796
- if (newConfig.stega.enabled && newConfig.stega.studioUrl === void 0)
1797
- throw new Error("stega.studioUrl must be defined when stega.enabled is true");
1798
- if (newConfig.stega.enabled && typeof newConfig.stega.studioUrl != "string" && typeof newConfig.stega.studioUrl != "function")
1799
- throw new Error(
1800
- `stega.studioUrl must be a string or a function, received ${newConfig.stega.studioUrl}`
1801
- );
1802
- const isBrowser = typeof window < "u" && window.location && window.location.hostname, isLocalhost = isBrowser && isLocal(window.location.hostname);
1803
- isBrowser && isLocalhost && newConfig.token && newConfig.ignoreBrowserTokenWarning !== !0 ? printBrowserTokenWarning() : typeof newConfig.useCdn > "u" && printCdnWarning(), projectBased && projectId(newConfig.projectId), newConfig.dataset && dataset(newConfig.dataset), "requestTagPrefix" in newConfig && (newConfig.requestTagPrefix = newConfig.requestTagPrefix ? requestTag(newConfig.requestTagPrefix).replace(/\.+$/, "") : void 0), newConfig.apiVersion = `${newConfig.apiVersion}`.replace(/^v/, ""), newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost, newConfig.useCdn = newConfig.useCdn !== !1 && !newConfig.withCredentials, validateApiVersion(newConfig.apiVersion);
1804
- const hostParts = newConfig.apiHost.split("://", 2), protocol = hostParts[0], host = hostParts[1], cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host;
1805
- return newConfig.useProjectHostname ? (newConfig.url = `${protocol}://${newConfig.projectId}.${host}/v${newConfig.apiVersion}`, newConfig.cdnUrl = `${protocol}://${newConfig.projectId}.${cdnHost}/v${newConfig.apiVersion}`) : (newConfig.url = `${newConfig.apiHost}/v${newConfig.apiVersion}`, newConfig.cdnUrl = newConfig.url), newConfig;
1806
- }, projectHeader = "X-Sanity-Project-ID";
1807
- function requestOptions(config2, overrides = {}) {
1808
- const headers2 = {}, token = overrides.token || config2.token;
1809
- token && (headers2.Authorization = `Bearer ${token}`), !overrides.useGlobalApi && !config2.useProjectHostname && config2.projectId && (headers2[projectHeader] = config2.projectId);
1810
- const withCredentials = !!(typeof overrides.withCredentials > "u" ? config2.token || config2.withCredentials : overrides.withCredentials), timeout = typeof overrides.timeout > "u" ? config2.timeout : overrides.timeout;
1811
- return Object.assign({}, overrides, {
1812
- headers: Object.assign({}, headers2, overrides.headers || {}),
1813
- timeout: typeof timeout > "u" ? 5 * 60 * 1e3 : timeout,
1814
- proxy: overrides.proxy || config2.proxy,
1815
- json: !0,
1816
- withCredentials,
1817
- fetch: typeof overrides.fetch == "object" && typeof config2.fetch == "object" ? { ...config2.fetch, ...overrides.fetch } : overrides.fetch || config2.fetch
1818
- });
1819
- }
1820
- var s = { 0: 8203, 1: 8204, 2: 8205, 3: 8290, 4: 8291, 5: 8288, 6: 65279, 7: 8289, 8: 119155, 9: 119156, a: 119157, b: 119158, c: 119159, d: 119160, e: 119161, f: 119162 }, c = { 0: 8203, 1: 8204, 2: 8205, 3: 65279 };
1821
- new Array(4).fill(String.fromCodePoint(c[0])).join("");
1822
- Object.fromEntries(Object.entries(c).map((t) => t.reverse()));
1823
- Object.fromEntries(Object.entries(s).map((t) => t.reverse()));
1824
- var S = `${Object.values(s).map((t) => `\\u{${t.toString(16)}}`).join("")}`, f = new RegExp(`[${S}]{4,}`, "gu");
1825
- function X(t) {
1826
- var e;
1827
- return { cleaned: t.replace(f, ""), encoded: ((e = t.match(f)) == null ? void 0 : e[0]) || "" };
1828
- }
1829
- function vercelStegaCleanAll(result) {
1830
- try {
1831
- return JSON.parse(
1832
- JSON.stringify(result, (key, value) => typeof value != "string" ? value : X(value).cleaned)
1833
- );
1834
- } catch {
1835
- return result;
1836
- }
1837
- }
1838
- const encodeQueryString = ({
1839
- query,
1840
- params = {},
1841
- options = {}
1842
- }) => {
1843
- const searchParams = new URLSearchParams(), { tag, returnQuery, ...opts } = options;
1844
- tag && searchParams.append("tag", tag), searchParams.append("query", query);
1845
- for (const [key, value] of Object.entries(params))
1846
- searchParams.append(`$${key}`, JSON.stringify(value));
1847
- for (const [key, value] of Object.entries(opts))
1848
- value && searchParams.append(key, `${value}`);
1849
- return returnQuery === !1 && searchParams.append("returnQuery", "false"), `?${searchParams}`;
1850
- }, excludeFalsey = (param, defValue) => param === !1 ? void 0 : typeof param > "u" ? defValue : param, getMutationQuery = (options = {}) => ({
1851
- dryRun: options.dryRun,
1852
- returnIds: !0,
1853
- returnDocuments: excludeFalsey(options.returnDocuments, !0),
1854
- visibility: options.visibility || "sync",
1855
- autoGenerateArrayKeys: options.autoGenerateArrayKeys,
1856
- skipCrossDatasetReferenceValidation: options.skipCrossDatasetReferenceValidation
1857
- }), isResponse = (event) => event.type === "response", getBody = (event) => event.body, indexBy = (docs, attr) => docs.reduce((indexed, doc) => (indexed[attr(doc)] = doc, indexed), /* @__PURE__ */ Object.create(null)), getQuerySizeLimit = 11264;
1858
- function _fetch(client, httpRequest, _stega, query, _params = {}, options = {}) {
1859
- const stega = "stega" in options ? {
1860
- ..._stega || {},
1861
- ...typeof options.stega == "boolean" ? { enabled: options.stega } : options.stega || {}
1862
- } : _stega, params = stega.enabled ? vercelStegaCleanAll(_params) : _params, mapResponse = options.filterResponse === !1 ? (res) => res : (res) => res.result, { cache, next, ...opts } = {
1863
- // Opt out of setting a `signal` on an internal `fetch` if one isn't provided.
1864
- // This is necessary in React Server Components to avoid opting out of Request Memoization.
1865
- useAbortSignal: typeof options.signal < "u",
1866
- // Set `resultSourceMap' when stega is enabled, as it's required for encoding.
1867
- resultSourceMap: stega.enabled ? "withKeyArraySelector" : options.resultSourceMap,
1868
- ...options,
1869
- // Default to not returning the query, unless `filterResponse` is `false`,
1870
- // or `returnQuery` is explicitly set. `true` is the default in Content Lake, so skip if truthy
1871
- returnQuery: options.filterResponse === !1 && options.returnQuery !== !1
1872
- }, reqOpts = typeof cache < "u" || typeof next < "u" ? { ...opts, fetch: { cache, next } } : opts, $request = _dataRequest(client, httpRequest, "query", { query, params }, reqOpts);
1873
- return stega.enabled ? $request.pipe(
1874
- combineLatestWith(
1875
- from(
1876
- Promise.resolve().then(function() {
1877
- return require("./stegaEncodeSourceMap.js");
1878
- }).then(function(n) {
1879
- return n.a;
1880
- }).then(
1881
- ({ stegaEncodeSourceMap }) => stegaEncodeSourceMap
1882
- )
1883
- )
1884
- ),
1885
- map(
1886
- ([res, stegaEncodeSourceMap]) => {
1887
- const result = stegaEncodeSourceMap(res.result, res.resultSourceMap, stega);
1888
- return mapResponse({ ...res, result });
1889
- }
1890
- )
1891
- ) : $request.pipe(map(mapResponse));
1892
- }
1893
- function _getDocument(client, httpRequest, id, opts = {}) {
1894
- const options = { uri: _getDataUrl(client, "doc", id), json: !0, tag: opts.tag };
1895
- return _requestObservable(client, httpRequest, options).pipe(
1896
- filter(isResponse),
1897
- map((event) => event.body.documents && event.body.documents[0])
1898
- );
1899
- }
1900
- function _getDocuments(client, httpRequest, ids, opts = {}) {
1901
- const options = { uri: _getDataUrl(client, "doc", ids.join(",")), json: !0, tag: opts.tag };
1902
- return _requestObservable(client, httpRequest, options).pipe(
1903
- filter(isResponse),
1904
- map((event) => {
1905
- const indexed = indexBy(event.body.documents || [], (doc) => doc._id);
1906
- return ids.map((id) => indexed[id] || null);
1907
- })
1908
- );
1909
- }
1910
- function _createIfNotExists(client, httpRequest, doc, options) {
1911
- return requireDocumentId("createIfNotExists", doc), _create(client, httpRequest, doc, "createIfNotExists", options);
1912
- }
1913
- function _createOrReplace(client, httpRequest, doc, options) {
1914
- return requireDocumentId("createOrReplace", doc), _create(client, httpRequest, doc, "createOrReplace", options);
1915
- }
1916
- function _delete(client, httpRequest, selection, options) {
1917
- return _dataRequest(
1918
- client,
1919
- httpRequest,
1920
- "mutate",
1921
- { mutations: [{ delete: getSelection(selection) }] },
1922
- options
1923
- );
1924
- }
1925
- function _mutate(client, httpRequest, mutations, options) {
1926
- let mut;
1927
- mutations instanceof Patch || mutations instanceof ObservablePatch ? mut = { patch: mutations.serialize() } : mutations instanceof Transaction || mutations instanceof ObservableTransaction ? mut = mutations.serialize() : mut = mutations;
1928
- const muts = Array.isArray(mut) ? mut : [mut], transactionId = options && options.transactionId || void 0;
1929
- return _dataRequest(client, httpRequest, "mutate", { mutations: muts, transactionId }, options);
1930
- }
1931
- function _dataRequest(client, httpRequest, endpoint, body, options = {}) {
1932
- const isMutation = endpoint === "mutate", isQuery = endpoint === "query", strQuery = isMutation ? "" : encodeQueryString(body), useGet = !isMutation && strQuery.length < getQuerySizeLimit, stringQuery = useGet ? strQuery : "", returnFirst = options.returnFirst, { timeout, token, tag, headers: headers2, returnQuery } = options, uri = _getDataUrl(client, endpoint, stringQuery), reqOptions = {
1933
- method: useGet ? "GET" : "POST",
1934
- uri,
1935
- json: !0,
1936
- body: useGet ? void 0 : body,
1937
- query: isMutation && getMutationQuery(options),
1938
- timeout,
1939
- headers: headers2,
1940
- token,
1941
- tag,
1942
- returnQuery,
1943
- perspective: options.perspective,
1944
- resultSourceMap: options.resultSourceMap,
1945
- canUseCdn: isQuery,
1946
- signal: options.signal,
1947
- fetch: options.fetch,
1948
- useAbortSignal: options.useAbortSignal,
1949
- useCdn: options.useCdn
1950
- };
1951
- return _requestObservable(client, httpRequest, reqOptions).pipe(
1952
- filter(isResponse),
1953
- map(getBody),
1954
- map((res) => {
1955
- if (!isMutation)
1956
- return res;
1957
- const results = res.results || [];
1958
- if (options.returnDocuments)
1959
- return returnFirst ? results[0] && results[0].document : results.map((mut) => mut.document);
1960
- const key = returnFirst ? "documentId" : "documentIds", ids = returnFirst ? results[0] && results[0].id : results.map((mut) => mut.id);
1961
- return {
1962
- transactionId: res.transactionId,
1963
- results,
1964
- [key]: ids
1965
- };
1966
- })
1967
- );
1968
- }
1969
- function _create(client, httpRequest, doc, op, options = {}) {
1970
- const mutation = { [op]: doc }, opts = Object.assign({ returnFirst: !0, returnDocuments: !0 }, options);
1971
- return _dataRequest(client, httpRequest, "mutate", { mutations: [mutation] }, opts);
1972
- }
1973
- function _requestObservable(client, httpRequest, options) {
1974
- var _a, _b;
1975
- const uri = options.url || options.uri, config2 = client.config(), canUseCdn = typeof options.canUseCdn > "u" ? ["GET", "HEAD"].indexOf(options.method || "GET") >= 0 && uri.indexOf("/data/") === 0 : options.canUseCdn;
1976
- let useCdn = ((_a = options.useCdn) != null ? _a : config2.useCdn) && canUseCdn;
1977
- const tag = options.tag && config2.requestTagPrefix ? [config2.requestTagPrefix, options.tag].join(".") : options.tag || config2.requestTagPrefix;
1978
- if (tag && options.tag !== null && (options.query = { tag: requestTag(tag), ...options.query }), ["GET", "HEAD", "POST"].indexOf(options.method || "GET") >= 0 && uri.indexOf("/data/query/") === 0) {
1979
- const resultSourceMap = (_b = options.resultSourceMap) != null ? _b : config2.resultSourceMap;
1980
- resultSourceMap !== void 0 && resultSourceMap !== !1 && (options.query = { resultSourceMap, ...options.query });
1981
- const perspective = options.perspective || config2.perspective;
1982
- typeof perspective == "string" && perspective !== "raw" && (validateApiPerspective(perspective), options.query = { perspective, ...options.query }, perspective === "previewDrafts" && useCdn && (useCdn = !1, printCdnPreviewDraftsWarning())), options.returnQuery === !1 && (options.query = { returnQuery: "false", ...options.query });
1983
- }
1984
- const reqOptions = requestOptions(
1985
- config2,
1986
- Object.assign({}, options, {
1987
- url: _getUrl(client, uri, useCdn)
1988
- })
1989
- ), request = new Observable(
1990
- (subscriber) => httpRequest(reqOptions, config2.requester).subscribe(subscriber)
1991
- );
1992
- return options.signal ? request.pipe(_withAbortSignal(options.signal)) : request;
1993
- }
1994
- function _request(client, httpRequest, options) {
1995
- return _requestObservable(client, httpRequest, options).pipe(
1996
- filter((event) => event.type === "response"),
1997
- map((event) => event.body)
1998
- );
1999
- }
2000
- function _getDataUrl(client, operation, path2) {
2001
- const config2 = client.config(), catalog = hasDataset(config2), baseUri = `/${operation}/${catalog}`;
2002
- return `/data${path2 ? `${baseUri}/${path2}` : baseUri}`.replace(/\/($|\?)/, "$1");
2003
- }
2004
- function _getUrl(client, uri, canUseCdn = !1) {
2005
- const { url, cdnUrl } = client.config();
2006
- return `${canUseCdn ? cdnUrl : url}/${uri.replace(/^\//, "")}`;
2007
- }
2008
- function _withAbortSignal(signal) {
2009
- return (input) => new Observable((observer) => {
2010
- const abort = () => observer.error(_createAbortError(signal));
2011
- if (signal && signal.aborted) {
2012
- abort();
2013
- return;
2014
- }
2015
- const subscription = input.subscribe(observer);
2016
- return signal.addEventListener("abort", abort), () => {
2017
- signal.removeEventListener("abort", abort), subscription.unsubscribe();
2018
- };
2019
- });
2020
- }
2021
- const isDomExceptionSupported = !!globalThis.DOMException;
2022
- function _createAbortError(signal) {
2023
- var _a, _b;
2024
- if (isDomExceptionSupported)
2025
- return new DOMException((_a = signal?.reason) != null ? _a : "The operation was aborted.", "AbortError");
2026
- const error = new Error((_b = signal?.reason) != null ? _b : "The operation was aborted.");
2027
- return error.name = "AbortError", error;
2028
- }
2029
- var __accessCheck$4 = (obj, member, msg) => {
2030
- if (!member.has(obj))
2031
- throw TypeError("Cannot " + msg);
2032
- }, __privateGet$4 = (obj, member, getter) => (__accessCheck$4(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)), __privateAdd$4 = (obj, member, value) => {
2033
- if (member.has(obj))
2034
- throw TypeError("Cannot add the same private member more than once");
2035
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2036
- }, __privateSet$4 = (obj, member, value, setter) => (__accessCheck$4(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value), _client$3, _httpRequest$4;
2037
- class ObservableAssetsClient {
2038
- constructor(client, httpRequest) {
2039
- __privateAdd$4(this, _client$3, void 0), __privateAdd$4(this, _httpRequest$4, void 0), __privateSet$4(this, _client$3, client), __privateSet$4(this, _httpRequest$4, httpRequest);
2040
- }
2041
- upload(assetType, body, options) {
2042
- return _upload(__privateGet$4(this, _client$3), __privateGet$4(this, _httpRequest$4), assetType, body, options);
2043
- }
2044
- }
2045
- _client$3 = /* @__PURE__ */ new WeakMap(), _httpRequest$4 = /* @__PURE__ */ new WeakMap();
2046
- var _client2$3, _httpRequest2$4;
2047
- class AssetsClient {
2048
- constructor(client, httpRequest) {
2049
- __privateAdd$4(this, _client2$3, void 0), __privateAdd$4(this, _httpRequest2$4, void 0), __privateSet$4(this, _client2$3, client), __privateSet$4(this, _httpRequest2$4, httpRequest);
2050
- }
2051
- upload(assetType, body, options) {
2052
- const observable2 = _upload(__privateGet$4(this, _client2$3), __privateGet$4(this, _httpRequest2$4), assetType, body, options);
2053
- return lastValueFrom(
2054
- observable2.pipe(
2055
- filter((event) => event.type === "response"),
2056
- map(
2057
- (event) => event.body.document
2058
- )
2059
- )
2060
- );
2061
- }
2062
- }
2063
- _client2$3 = /* @__PURE__ */ new WeakMap(), _httpRequest2$4 = /* @__PURE__ */ new WeakMap();
2064
- function _upload(client, httpRequest, assetType, body, opts = {}) {
2065
- validateAssetType(assetType);
2066
- let meta = opts.extract || void 0;
2067
- meta && !meta.length && (meta = ["none"]);
2068
- const dataset2 = hasDataset(client.config()), assetEndpoint = assetType === "image" ? "images" : "files", options = optionsFromFile(opts, body), { tag, label, title, description: description2, creditLine, filename, source } = options, query = {
2069
- label,
2070
- title,
2071
- description: description2,
2072
- filename,
2073
- meta,
2074
- creditLine
2075
- };
2076
- return source && (query.sourceId = source.id, query.sourceName = source.name, query.sourceUrl = source.url), _requestObservable(client, httpRequest, {
2077
- tag,
2078
- method: "POST",
2079
- timeout: options.timeout || 0,
2080
- uri: `/assets/${assetEndpoint}/${dataset2}`,
2081
- headers: options.contentType ? { "Content-Type": options.contentType } : {},
2082
- query,
2083
- body
2084
- });
2085
- }
2086
- function optionsFromFile(opts, file) {
2087
- return typeof File > "u" || !(file instanceof File) ? opts : Object.assign(
2088
- {
2089
- filename: opts.preserveFilename === !1 ? void 0 : file.name,
2090
- contentType: file.type
2091
- },
2092
- opts
2093
- );
2094
- }
2095
- var defaults = (obj, defaults2) => Object.keys(defaults2).concat(Object.keys(obj)).reduce((target, prop) => (target[prop] = typeof obj[prop] > "u" ? defaults2[prop] : obj[prop], target), {});
2096
- const pick = (obj, props) => props.reduce((selection, prop) => (typeof obj[prop] > "u" || (selection[prop] = obj[prop]), selection), {}), MAX_URL_LENGTH = 14800, possibleOptions = [
2097
- "includePreviousRevision",
2098
- "includeResult",
2099
- "visibility",
2100
- "effectFormat",
2101
- "tag"
2102
- ], defaultOptions = {
2103
- includeResult: !0
2104
- };
2105
- function _listen(query, params, opts = {}) {
2106
- const { url, token, withCredentials, requestTagPrefix } = this.config(), tag = opts.tag && requestTagPrefix ? [requestTagPrefix, opts.tag].join(".") : opts.tag, options = { ...defaults(opts, defaultOptions), tag }, listenOpts = pick(options, possibleOptions), qs = encodeQueryString({ query, params, options: { tag, ...listenOpts } }), uri = `${url}${_getDataUrl(this, "listen", qs)}`;
2107
- if (uri.length > MAX_URL_LENGTH)
2108
- return new Observable((observer) => observer.error(new Error("Query too large for listener")));
2109
- const listenFor = options.events ? options.events : ["mutation"], shouldEmitReconnect = listenFor.indexOf("reconnect") !== -1, esOptions = {};
2110
- return (token || withCredentials) && (esOptions.withCredentials = !0), token && (esOptions.headers = {
2111
- Authorization: `Bearer ${token}`
2112
- }), new Observable((observer) => {
2113
- let es;
2114
- getEventSource().then((eventSource) => {
2115
- es = eventSource;
2116
- }).catch((reason) => {
2117
- observer.error(reason), stop();
2118
- });
2119
- let reconnectTimer, stopped = !1;
2120
- function onError() {
2121
- stopped || (emitReconnect(), !stopped && es.readyState === es.CLOSED && (unsubscribe(), clearTimeout(reconnectTimer), reconnectTimer = setTimeout(open, 100)));
2122
- }
2123
- function onChannelError(err) {
2124
- observer.error(cooerceError(err));
2125
- }
2126
- function onMessage(evt) {
2127
- const event = parseEvent(evt);
2128
- return event instanceof Error ? observer.error(event) : observer.next(event);
2129
- }
2130
- function onDisconnect() {
2131
- stopped = !0, unsubscribe(), observer.complete();
2132
- }
2133
- function unsubscribe() {
2134
- es && (es.removeEventListener("error", onError), es.removeEventListener("channelError", onChannelError), es.removeEventListener("disconnect", onDisconnect), listenFor.forEach((type) => es.removeEventListener(type, onMessage)), es.close());
2135
- }
2136
- function emitReconnect() {
2137
- shouldEmitReconnect && observer.next({ type: "reconnect" });
2138
- }
2139
- async function getEventSource() {
2140
- const { default: EventSource } = await Promise.resolve().then(function() {
2141
- return require("./node.js");
2142
- }).then(function(n) {
2143
- return n.node;
2144
- }), evs = new EventSource(uri, esOptions);
2145
- return evs.addEventListener("error", onError), evs.addEventListener("channelError", onChannelError), evs.addEventListener("disconnect", onDisconnect), listenFor.forEach((type) => evs.addEventListener(type, onMessage)), evs;
2146
- }
2147
- function open() {
2148
- getEventSource().then((eventSource) => {
2149
- es = eventSource;
2150
- }).catch((reason) => {
2151
- observer.error(reason), stop();
2152
- });
2153
- }
2154
- function stop() {
2155
- stopped = !0, unsubscribe();
2156
- }
2157
- return stop;
2158
- });
2159
- }
2160
- function parseEvent(event) {
2161
- try {
2162
- const data = event.data && JSON.parse(event.data) || {};
2163
- return Object.assign({ type: event.type }, data);
2164
- } catch (err) {
2165
- return err;
2166
- }
2167
- }
2168
- function cooerceError(err) {
2169
- if (err instanceof Error)
2170
- return err;
2171
- const evt = parseEvent(err);
2172
- return evt instanceof Error ? evt : new Error(extractErrorMessage(evt));
2173
- }
2174
- function extractErrorMessage(err) {
2175
- return err.error ? err.error.description ? err.error.description : typeof err.error == "string" ? err.error : JSON.stringify(err.error, null, 2) : err.message || "Unknown listener error";
2176
- }
2177
- var __accessCheck$3 = (obj, member, msg) => {
2178
- if (!member.has(obj))
2179
- throw TypeError("Cannot " + msg);
2180
- }, __privateGet$3 = (obj, member, getter) => (__accessCheck$3(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)), __privateAdd$3 = (obj, member, value) => {
2181
- if (member.has(obj))
2182
- throw TypeError("Cannot add the same private member more than once");
2183
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2184
- }, __privateSet$3 = (obj, member, value, setter) => (__accessCheck$3(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value), _client$2, _httpRequest$3;
2185
- class ObservableDatasetsClient {
2186
- constructor(client, httpRequest) {
2187
- __privateAdd$3(this, _client$2, void 0), __privateAdd$3(this, _httpRequest$3, void 0), __privateSet$3(this, _client$2, client), __privateSet$3(this, _httpRequest$3, httpRequest);
2188
- }
2189
- /**
2190
- * Create a new dataset with the given name
2191
- *
2192
- * @param name - Name of the dataset to create
2193
- * @param options - Options for the dataset
2194
- */
2195
- create(name2, options) {
2196
- return _modify(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), "PUT", name2, options);
2197
- }
2198
- /**
2199
- * Edit a dataset with the given name
2200
- *
2201
- * @param name - Name of the dataset to edit
2202
- * @param options - New options for the dataset
2203
- */
2204
- edit(name2, options) {
2205
- return _modify(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), "PATCH", name2, options);
2206
- }
2207
- /**
2208
- * Delete a dataset with the given name
2209
- *
2210
- * @param name - Name of the dataset to delete
2211
- */
2212
- delete(name2) {
2213
- return _modify(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), "DELETE", name2);
2214
- }
2215
- /**
2216
- * Fetch a list of datasets for the configured project
2217
- */
2218
- list() {
2219
- return _request(__privateGet$3(this, _client$2), __privateGet$3(this, _httpRequest$3), {
2220
- uri: "/datasets",
2221
- tag: null
2222
- });
2223
- }
2224
- }
2225
- _client$2 = /* @__PURE__ */ new WeakMap(), _httpRequest$3 = /* @__PURE__ */ new WeakMap();
2226
- var _client2$2, _httpRequest2$3;
2227
- class DatasetsClient {
2228
- constructor(client, httpRequest) {
2229
- __privateAdd$3(this, _client2$2, void 0), __privateAdd$3(this, _httpRequest2$3, void 0), __privateSet$3(this, _client2$2, client), __privateSet$3(this, _httpRequest2$3, httpRequest);
2230
- }
2231
- /**
2232
- * Create a new dataset with the given name
2233
- *
2234
- * @param name - Name of the dataset to create
2235
- * @param options - Options for the dataset
2236
- */
2237
- create(name2, options) {
2238
- return lastValueFrom(
2239
- _modify(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), "PUT", name2, options)
2240
- );
2241
- }
2242
- /**
2243
- * Edit a dataset with the given name
2244
- *
2245
- * @param name - Name of the dataset to edit
2246
- * @param options - New options for the dataset
2247
- */
2248
- edit(name2, options) {
2249
- return lastValueFrom(
2250
- _modify(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), "PATCH", name2, options)
2251
- );
2252
- }
2253
- /**
2254
- * Delete a dataset with the given name
2255
- *
2256
- * @param name - Name of the dataset to delete
2257
- */
2258
- delete(name2) {
2259
- return lastValueFrom(_modify(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), "DELETE", name2));
2260
- }
2261
- /**
2262
- * Fetch a list of datasets for the configured project
2263
- */
2264
- list() {
2265
- return lastValueFrom(
2266
- _request(__privateGet$3(this, _client2$2), __privateGet$3(this, _httpRequest2$3), { uri: "/datasets", tag: null })
2267
- );
2268
- }
2269
- }
2270
- _client2$2 = /* @__PURE__ */ new WeakMap(), _httpRequest2$3 = /* @__PURE__ */ new WeakMap();
2271
- function _modify(client, httpRequest, method, name2, options) {
2272
- return dataset(name2), _request(client, httpRequest, {
2273
- method,
2274
- uri: `/datasets/${name2}`,
2275
- body: options,
2276
- tag: null
2277
- });
2278
- }
2279
- var __accessCheck$2 = (obj, member, msg) => {
2280
- if (!member.has(obj))
2281
- throw TypeError("Cannot " + msg);
2282
- }, __privateGet$2 = (obj, member, getter) => (__accessCheck$2(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)), __privateAdd$2 = (obj, member, value) => {
2283
- if (member.has(obj))
2284
- throw TypeError("Cannot add the same private member more than once");
2285
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2286
- }, __privateSet$2 = (obj, member, value, setter) => (__accessCheck$2(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value), _client$1, _httpRequest$2;
2287
- class ObservableProjectsClient {
2288
- constructor(client, httpRequest) {
2289
- __privateAdd$2(this, _client$1, void 0), __privateAdd$2(this, _httpRequest$2, void 0), __privateSet$2(this, _client$1, client), __privateSet$2(this, _httpRequest$2, httpRequest);
2290
- }
2291
- list(options) {
2292
- const uri = options?.includeMembers === !1 ? "/projects?includeMembers=false" : "/projects";
2293
- return _request(__privateGet$2(this, _client$1), __privateGet$2(this, _httpRequest$2), { uri });
2294
- }
2295
- /**
2296
- * Fetch a project by project ID
2297
- *
2298
- * @param projectId - ID of the project to fetch
2299
- */
2300
- getById(projectId2) {
2301
- return _request(__privateGet$2(this, _client$1), __privateGet$2(this, _httpRequest$2), { uri: `/projects/${projectId2}` });
2302
- }
2303
- }
2304
- _client$1 = /* @__PURE__ */ new WeakMap(), _httpRequest$2 = /* @__PURE__ */ new WeakMap();
2305
- var _client2$1, _httpRequest2$2;
2306
- class ProjectsClient {
2307
- constructor(client, httpRequest) {
2308
- __privateAdd$2(this, _client2$1, void 0), __privateAdd$2(this, _httpRequest2$2, void 0), __privateSet$2(this, _client2$1, client), __privateSet$2(this, _httpRequest2$2, httpRequest);
2309
- }
2310
- list(options) {
2311
- const uri = options?.includeMembers === !1 ? "/projects?includeMembers=false" : "/projects";
2312
- return lastValueFrom(_request(__privateGet$2(this, _client2$1), __privateGet$2(this, _httpRequest2$2), { uri }));
2313
- }
2314
- /**
2315
- * Fetch a project by project ID
2316
- *
2317
- * @param projectId - ID of the project to fetch
2318
- */
2319
- getById(projectId2) {
2320
- return lastValueFrom(
2321
- _request(__privateGet$2(this, _client2$1), __privateGet$2(this, _httpRequest2$2), { uri: `/projects/${projectId2}` })
2322
- );
2323
- }
2324
- }
2325
- _client2$1 = /* @__PURE__ */ new WeakMap(), _httpRequest2$2 = /* @__PURE__ */ new WeakMap();
2326
- var __accessCheck$1 = (obj, member, msg) => {
2327
- if (!member.has(obj))
2328
- throw TypeError("Cannot " + msg);
2329
- }, __privateGet$1 = (obj, member, getter) => (__accessCheck$1(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)), __privateAdd$1 = (obj, member, value) => {
2330
- if (member.has(obj))
2331
- throw TypeError("Cannot add the same private member more than once");
2332
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2333
- }, __privateSet$1 = (obj, member, value, setter) => (__accessCheck$1(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value), _client, _httpRequest$1;
2334
- class ObservableUsersClient {
2335
- constructor(client, httpRequest) {
2336
- __privateAdd$1(this, _client, void 0), __privateAdd$1(this, _httpRequest$1, void 0), __privateSet$1(this, _client, client), __privateSet$1(this, _httpRequest$1, httpRequest);
2337
- }
2338
- /**
2339
- * Fetch a user by user ID
2340
- *
2341
- * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
2342
- */
2343
- getById(id) {
2344
- return _request(
2345
- __privateGet$1(this, _client),
2346
- __privateGet$1(this, _httpRequest$1),
2347
- { uri: `/users/${id}` }
2348
- );
2349
- }
2350
- }
2351
- _client = /* @__PURE__ */ new WeakMap(), _httpRequest$1 = /* @__PURE__ */ new WeakMap();
2352
- var _client2, _httpRequest2$1;
2353
- class UsersClient {
2354
- constructor(client, httpRequest) {
2355
- __privateAdd$1(this, _client2, void 0), __privateAdd$1(this, _httpRequest2$1, void 0), __privateSet$1(this, _client2, client), __privateSet$1(this, _httpRequest2$1, httpRequest);
2356
- }
2357
- /**
2358
- * Fetch a user by user ID
2359
- *
2360
- * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
2361
- */
2362
- getById(id) {
2363
- return lastValueFrom(
2364
- _request(__privateGet$1(this, _client2), __privateGet$1(this, _httpRequest2$1), {
2365
- uri: `/users/${id}`
2366
- })
2367
- );
2368
- }
2369
- }
2370
- _client2 = /* @__PURE__ */ new WeakMap(), _httpRequest2$1 = /* @__PURE__ */ new WeakMap();
2371
- var __accessCheck = (obj, member, msg) => {
2372
- if (!member.has(obj))
2373
- throw TypeError("Cannot " + msg);
2374
- }, __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)), __privateAdd = (obj, member, value) => {
2375
- if (member.has(obj))
2376
- throw TypeError("Cannot add the same private member more than once");
2377
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2378
- }, __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value), _clientConfig, _httpRequest;
2379
- const _ObservableSanityClient = class _ObservableSanityClient2 {
2380
- constructor(httpRequest, config2 = defaultConfig) {
2381
- __privateAdd(this, _clientConfig, void 0), __privateAdd(this, _httpRequest, void 0), this.listen = _listen, this.config(config2), __privateSet(this, _httpRequest, httpRequest), this.assets = new ObservableAssetsClient(this, __privateGet(this, _httpRequest)), this.datasets = new ObservableDatasetsClient(this, __privateGet(this, _httpRequest)), this.projects = new ObservableProjectsClient(this, __privateGet(this, _httpRequest)), this.users = new ObservableUsersClient(this, __privateGet(this, _httpRequest));
2382
- }
2383
- /**
2384
- * Clone the client - returns a new instance
2385
- */
2386
- clone() {
2387
- return new _ObservableSanityClient2(__privateGet(this, _httpRequest), this.config());
2388
- }
2389
- config(newConfig) {
2390
- if (newConfig === void 0)
2391
- return { ...__privateGet(this, _clientConfig) };
2392
- if (__privateGet(this, _clientConfig) && __privateGet(this, _clientConfig).allowReconfigure === !1)
2393
- throw new Error(
2394
- "Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client"
2395
- );
2396
- return __privateSet(this, _clientConfig, initConfig(newConfig, __privateGet(this, _clientConfig) || {})), this;
2397
- }
2398
- /**
2399
- * Clone the client with a new (partial) configuration.
2400
- *
2401
- * @param newConfig - New client configuration properties, shallowly merged with existing configuration
2402
- */
2403
- withConfig(newConfig) {
2404
- const thisConfig = this.config();
2405
- return new _ObservableSanityClient2(__privateGet(this, _httpRequest), {
2406
- ...thisConfig,
2407
- ...newConfig,
2408
- stega: {
2409
- ...thisConfig.stega || {},
2410
- ...typeof newConfig?.stega == "boolean" ? { enabled: newConfig.stega } : newConfig?.stega || {}
2411
- }
2412
- });
2413
- }
2414
- fetch(query, params, options) {
2415
- return _fetch(
2416
- this,
2417
- __privateGet(this, _httpRequest),
2418
- __privateGet(this, _clientConfig).stega,
2419
- query,
2420
- params,
2421
- options
2422
- );
2423
- }
2424
- /**
2425
- * Fetch a single document with the given ID.
2426
- *
2427
- * @param id - Document ID to fetch
2428
- * @param options - Request options
2429
- */
2430
- getDocument(id, options) {
2431
- return _getDocument(this, __privateGet(this, _httpRequest), id, options);
2432
- }
2433
- /**
2434
- * Fetch multiple documents in one request.
2435
- * Should be used sparingly - performing a query is usually a better option.
2436
- * The order/position of documents is preserved based on the original array of IDs.
2437
- * If any of the documents are missing, they will be replaced by a `null` entry in the returned array
2438
- *
2439
- * @param ids - Document IDs to fetch
2440
- * @param options - Request options
2441
- */
2442
- getDocuments(ids, options) {
2443
- return _getDocuments(this, __privateGet(this, _httpRequest), ids, options);
2444
- }
2445
- create(document, options) {
2446
- return _create(this, __privateGet(this, _httpRequest), document, "create", options);
2447
- }
2448
- createIfNotExists(document, options) {
2449
- return _createIfNotExists(this, __privateGet(this, _httpRequest), document, options);
2450
- }
2451
- createOrReplace(document, options) {
2452
- return _createOrReplace(this, __privateGet(this, _httpRequest), document, options);
2453
- }
2454
- delete(selection, options) {
2455
- return _delete(this, __privateGet(this, _httpRequest), selection, options);
2456
- }
2457
- mutate(operations, options) {
2458
- return _mutate(this, __privateGet(this, _httpRequest), operations, options);
2459
- }
2460
- /**
2461
- * Create a new buildable patch of operations to perform
2462
- *
2463
- * @param selection - Document ID, an array of document IDs, or an object with `query` and optional `params`, defining which document(s) to patch
2464
- * @param operations - Optional object of patch operations to initialize the patch instance with
2465
- * @returns Patch instance - call `.commit()` to perform the operations defined
2466
- */
2467
- patch(selection, operations) {
2468
- return new ObservablePatch(selection, operations, this);
2469
- }
2470
- /**
2471
- * Create a new transaction of mutations
2472
- *
2473
- * @param operations - Optional array of mutation operations to initialize the transaction instance with
2474
- */
2475
- transaction(operations) {
2476
- return new ObservableTransaction(operations, this);
2477
- }
2478
- /**
2479
- * Perform an HTTP request against the Sanity API
2480
- *
2481
- * @param options - Request options
2482
- */
2483
- request(options) {
2484
- return _request(this, __privateGet(this, _httpRequest), options);
2485
- }
2486
- /**
2487
- * Get a Sanity API URL for the URI provided
2488
- *
2489
- * @param uri - URI/path to build URL for
2490
- * @param canUseCdn - Whether or not to allow using the API CDN for this route
2491
- */
2492
- getUrl(uri, canUseCdn) {
2493
- return _getUrl(this, uri, canUseCdn);
2494
- }
2495
- /**
2496
- * Get a Sanity API URL for the data operation and path provided
2497
- *
2498
- * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
2499
- * @param path - Path to append after the operation
2500
- */
2501
- getDataUrl(operation, path2) {
2502
- return _getDataUrl(this, operation, path2);
2503
- }
2504
- };
2505
- _clientConfig = /* @__PURE__ */ new WeakMap(), _httpRequest = /* @__PURE__ */ new WeakMap();
2506
- let ObservableSanityClient = _ObservableSanityClient;
2507
- var _clientConfig2, _httpRequest2;
2508
- const _SanityClient = class _SanityClient2 {
2509
- constructor(httpRequest, config2 = defaultConfig) {
2510
- __privateAdd(this, _clientConfig2, void 0), __privateAdd(this, _httpRequest2, void 0), this.listen = _listen, this.config(config2), __privateSet(this, _httpRequest2, httpRequest), this.assets = new AssetsClient(this, __privateGet(this, _httpRequest2)), this.datasets = new DatasetsClient(this, __privateGet(this, _httpRequest2)), this.projects = new ProjectsClient(this, __privateGet(this, _httpRequest2)), this.users = new UsersClient(this, __privateGet(this, _httpRequest2)), this.observable = new ObservableSanityClient(httpRequest, config2);
2511
- }
2512
- /**
2513
- * Clone the client - returns a new instance
2514
- */
2515
- clone() {
2516
- return new _SanityClient2(__privateGet(this, _httpRequest2), this.config());
2517
- }
2518
- config(newConfig) {
2519
- if (newConfig === void 0)
2520
- return { ...__privateGet(this, _clientConfig2) };
2521
- if (__privateGet(this, _clientConfig2) && __privateGet(this, _clientConfig2).allowReconfigure === !1)
2522
- throw new Error(
2523
- "Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client"
2524
- );
2525
- return this.observable && this.observable.config(newConfig), __privateSet(this, _clientConfig2, initConfig(newConfig, __privateGet(this, _clientConfig2) || {})), this;
2526
- }
2527
- /**
2528
- * Clone the client with a new (partial) configuration.
2529
- *
2530
- * @param newConfig - New client configuration properties, shallowly merged with existing configuration
2531
- */
2532
- withConfig(newConfig) {
2533
- const thisConfig = this.config();
2534
- return new _SanityClient2(__privateGet(this, _httpRequest2), {
2535
- ...thisConfig,
2536
- ...newConfig,
2537
- stega: {
2538
- ...thisConfig.stega || {},
2539
- ...typeof newConfig?.stega == "boolean" ? { enabled: newConfig.stega } : newConfig?.stega || {}
2540
- }
2541
- });
2542
- }
2543
- fetch(query, params, options) {
2544
- return lastValueFrom(
2545
- _fetch(
2546
- this,
2547
- __privateGet(this, _httpRequest2),
2548
- __privateGet(this, _clientConfig2).stega,
2549
- query,
2550
- params,
2551
- options
2552
- )
2553
- );
2554
- }
2555
- /**
2556
- * Fetch a single document with the given ID.
2557
- *
2558
- * @param id - Document ID to fetch
2559
- * @param options - Request options
2560
- */
2561
- getDocument(id, options) {
2562
- return lastValueFrom(_getDocument(this, __privateGet(this, _httpRequest2), id, options));
2563
- }
2564
- /**
2565
- * Fetch multiple documents in one request.
2566
- * Should be used sparingly - performing a query is usually a better option.
2567
- * The order/position of documents is preserved based on the original array of IDs.
2568
- * If any of the documents are missing, they will be replaced by a `null` entry in the returned array
2569
- *
2570
- * @param ids - Document IDs to fetch
2571
- * @param options - Request options
2572
- */
2573
- getDocuments(ids, options) {
2574
- return lastValueFrom(_getDocuments(this, __privateGet(this, _httpRequest2), ids, options));
2575
- }
2576
- create(document, options) {
2577
- return lastValueFrom(
2578
- _create(this, __privateGet(this, _httpRequest2), document, "create", options)
2579
- );
2580
- }
2581
- createIfNotExists(document, options) {
2582
- return lastValueFrom(
2583
- _createIfNotExists(this, __privateGet(this, _httpRequest2), document, options)
2584
- );
2585
- }
2586
- createOrReplace(document, options) {
2587
- return lastValueFrom(
2588
- _createOrReplace(this, __privateGet(this, _httpRequest2), document, options)
2589
- );
2590
- }
2591
- delete(selection, options) {
2592
- return lastValueFrom(_delete(this, __privateGet(this, _httpRequest2), selection, options));
2593
- }
2594
- mutate(operations, options) {
2595
- return lastValueFrom(_mutate(this, __privateGet(this, _httpRequest2), operations, options));
2596
- }
2597
- /**
2598
- * Create a new buildable patch of operations to perform
2599
- *
2600
- * @param selection - Document ID, an array of document IDs, or an object with `query` and optional `params`, defining which document(s) to patch
2601
- * @param operations - Optional object of patch operations to initialize the patch instance with
2602
- * @returns Patch instance - call `.commit()` to perform the operations defined
2603
- */
2604
- patch(documentId, operations) {
2605
- return new Patch(documentId, operations, this);
2606
- }
2607
- /**
2608
- * Create a new transaction of mutations
2609
- *
2610
- * @param operations - Optional array of mutation operations to initialize the transaction instance with
2611
- */
2612
- transaction(operations) {
2613
- return new Transaction(operations, this);
2614
- }
2615
- /**
2616
- * Perform a request against the Sanity API
2617
- * NOTE: Only use this for Sanity API endpoints, not for your own APIs!
2618
- *
2619
- * @param options - Request options
2620
- * @returns Promise resolving to the response body
2621
- */
2622
- request(options) {
2623
- return lastValueFrom(_request(this, __privateGet(this, _httpRequest2), options));
2624
- }
2625
- /**
2626
- * Perform an HTTP request a `/data` sub-endpoint
2627
- * NOTE: Considered internal, thus marked as deprecated. Use `request` instead.
2628
- *
2629
- * @deprecated - Use `request()` or your own HTTP library instead
2630
- * @param endpoint - Endpoint to hit (mutate, query etc)
2631
- * @param body - Request body
2632
- * @param options - Request options
2633
- * @internal
2634
- */
2635
- dataRequest(endpoint, body, options) {
2636
- return lastValueFrom(_dataRequest(this, __privateGet(this, _httpRequest2), endpoint, body, options));
2637
- }
2638
- /**
2639
- * Get a Sanity API URL for the URI provided
2640
- *
2641
- * @param uri - URI/path to build URL for
2642
- * @param canUseCdn - Whether or not to allow using the API CDN for this route
2643
- */
2644
- getUrl(uri, canUseCdn) {
2645
- return _getUrl(this, uri, canUseCdn);
2646
- }
2647
- /**
2648
- * Get a Sanity API URL for the data operation and path provided
2649
- *
2650
- * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
2651
- * @param path - Path to append after the operation
2652
- */
2653
- getDataUrl(operation, path2) {
2654
- return _getDataUrl(this, operation, path2);
2655
- }
2656
- };
2657
- _clientConfig2 = /* @__PURE__ */ new WeakMap(), _httpRequest2 = /* @__PURE__ */ new WeakMap();
2658
- let SanityClient = _SanityClient;
2659
- function defineCreateClientExports(envMiddleware, ClassConstructor) {
2660
- return { requester: defineHttpRequest(envMiddleware, {}).defaultRequester, createClient: (config2) => new ClassConstructor(
2661
- defineHttpRequest(envMiddleware, {
2662
- maxRetries: config2.maxRetries,
2663
- retryDelay: config2.retryDelay
2664
- }),
2665
- config2
2666
- ) };
2667
- }
2668
- var name$1 = "@sanity/client", version$2 = "6.15.7";
2669
- const middleware = [
2670
- require$$2.debug({ verbose: !0, namespace: "sanity:client" }),
2671
- require$$2.headers({ "User-Agent": `${name$1} ${version$2}` }),
2672
- // Enable keep-alive, and in addition limit the number of sockets that can be opened.
2673
- // This avoids opening too many connections to the server if someone tries to execute
2674
- // a bunch of requests in parallel. It's recommended to have a concurrency limit
2675
- // at a "higher limit" (i.e. you shouldn't actually execute hundreds of requests in parallel),
2676
- // and this is mainly to minimize the impact for the network and server.
2677
- //
2678
- // We're currently matching the same defaults as browsers:
2679
- // https://stackoverflow.com/questions/26003756/is-there-a-limit-practical-or-otherwise-to-the-number-of-web-sockets-a-page-op
2680
- require$$2.agent({
2681
- keepAlive: !0,
2682
- maxSockets: 30,
2683
- maxTotalSockets: 256
2684
- })
2685
- ], exp = defineCreateClientExports(middleware, SanityClient), requester = exp.requester, createClient = exp.createClient, debug = index.createDebug("sanity:cli");
6
+ var require$$0__default = /* @__PURE__ */ _interopDefaultCompat(require$$0), path__default = /* @__PURE__ */ _interopDefaultCompat(path$1), debugIt__default = /* @__PURE__ */ _interopDefaultCompat(debugIt), fs__default = /* @__PURE__ */ _interopDefaultCompat(fs$1), path__default$1 = /* @__PURE__ */ _interopDefaultCompat(path$2), os__default = /* @__PURE__ */ _interopDefaultCompat(os$1), require$$3__default = /* @__PURE__ */ _interopDefaultCompat(require$$3);
7
+ const debug = debugIt__default.default("sanity:cli");
2686
8
  function resolveRootDir(cwd) {
2687
9
  try {
2688
10
  return resolveProjectRoot(cwd) || cwd;
@@ -2715,7 +37,32 @@ function isSanityV2StudioRoot(basePath) {
2715
37
  function fileExists(filePath) {
2716
38
  return require$$0__default.default.existsSync(filePath);
2717
39
  }
2718
- var main$1 = { exports: {} }, name = "dotenv", version$1 = "16.3.2", description = "Loads environment variables from .env file", main = "lib/main.js", types = "lib/main.d.ts", exports$1 = {
40
+ var commonjsGlobal = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {};
41
+ function getDefaultExportFromCjs(x) {
42
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x.default : x;
43
+ }
44
+ function getAugmentedNamespace(n) {
45
+ if (n.__esModule)
46
+ return n;
47
+ var f = n.default;
48
+ if (typeof f == "function") {
49
+ var a = function a2() {
50
+ return this instanceof a2 ? Reflect.construct(f, arguments, this.constructor) : f.apply(this, arguments);
51
+ };
52
+ a.prototype = f.prototype;
53
+ } else
54
+ a = {};
55
+ return Object.defineProperty(a, "__esModule", { value: !0 }), Object.keys(n).forEach(function(k) {
56
+ var d = Object.getOwnPropertyDescriptor(n, k);
57
+ Object.defineProperty(a, k, d.get ? d : {
58
+ enumerable: !0,
59
+ get: function() {
60
+ return n[k];
61
+ }
62
+ });
63
+ }), a;
64
+ }
65
+ var main$1 = { exports: {} }, name = "dotenv", version$1 = "16.4.5", description = "Loads environment variables from .env file", main = "lib/main.js", types = "lib/main.d.ts", exports$1 = {
2719
66
  ".": {
2720
67
  types: "./lib/main.d.ts",
2721
68
  require: "./lib/main.js",
@@ -2734,12 +81,13 @@ var main$1 = { exports: {} }, name = "dotenv", version$1 = "16.3.2", description
2734
81
  "lint-readme": "standard-markdown",
2735
82
  pretest: "npm run lint && npm run dts-check",
2736
83
  test: "tap tests/*.js --100 -Rspec",
84
+ "test:coverage": "tap --coverage-report=lcov",
2737
85
  prerelease: "npm test",
2738
86
  release: "standard-version"
2739
87
  }, repository = {
2740
88
  type: "git",
2741
89
  url: "git://github.com/motdotla/dotenv.git"
2742
- }, funding = "https://github.com/motdotla/dotenv?sponsor=1", keywords = [
90
+ }, funding = "https://dotenvx.com", keywords = [
2743
91
  "dotenv",
2744
92
  "env",
2745
93
  ".env",
@@ -2779,7 +127,7 @@ var main$1 = { exports: {} }, name = "dotenv", version$1 = "16.3.2", description
2779
127
  engines,
2780
128
  browser
2781
129
  };
2782
- const fs = require$$0__default.default, path = path__default.default, os = require$$0__default$1.default, crypto = require$$3__default.default, packageJson = require$$4, version = packageJson.version, LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
130
+ const fs = require$$0__default.default, path = path__default.default, os = os__default.default, crypto = require$$3__default.default, packageJson = require$$4, version = packageJson.version, LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
2783
131
  function parse(src) {
2784
132
  const obj = {};
2785
133
  let lines = src.toString();
@@ -2798,8 +146,10 @@ function parse(src) {
2798
146
  }
2799
147
  function _parseVault(options) {
2800
148
  const vaultPath = _vaultPath(options), result = DotenvModule.configDotenv({ path: vaultPath });
2801
- if (!result.parsed)
2802
- throw new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
149
+ if (!result.parsed) {
150
+ const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
151
+ throw err.code = "MISSING_DATA", err;
152
+ }
2803
153
  const keys = _dotenvKey(options).split(","), length = keys.length;
2804
154
  let decrypted;
2805
155
  for (let i = 0; i < length; i++)
@@ -2830,22 +180,40 @@ function _instructions(result, dotenvKey) {
2830
180
  try {
2831
181
  uri = new URL(dotenvKey);
2832
182
  } catch (error) {
2833
- throw error.code === "ERR_INVALID_URL" ? new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenv.org/vault/.env.vault?environment=development") : error;
183
+ if (error.code === "ERR_INVALID_URL") {
184
+ const err = new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
185
+ throw err.code = "INVALID_DOTENV_KEY", err;
186
+ }
187
+ throw error;
2834
188
  }
2835
189
  const key = uri.password;
2836
- if (!key)
2837
- throw new Error("INVALID_DOTENV_KEY: Missing key part");
190
+ if (!key) {
191
+ const err = new Error("INVALID_DOTENV_KEY: Missing key part");
192
+ throw err.code = "INVALID_DOTENV_KEY", err;
193
+ }
2838
194
  const environment = uri.searchParams.get("environment");
2839
- if (!environment)
2840
- throw new Error("INVALID_DOTENV_KEY: Missing environment part");
195
+ if (!environment) {
196
+ const err = new Error("INVALID_DOTENV_KEY: Missing environment part");
197
+ throw err.code = "INVALID_DOTENV_KEY", err;
198
+ }
2841
199
  const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`, ciphertext = result.parsed[environmentKey];
2842
- if (!ciphertext)
2843
- throw new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
200
+ if (!ciphertext) {
201
+ const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
202
+ throw err.code = "NOT_FOUND_DOTENV_ENVIRONMENT", err;
203
+ }
2844
204
  return { ciphertext, key };
2845
205
  }
2846
206
  function _vaultPath(options) {
2847
- let dotenvPath = path.resolve(process.cwd(), ".env");
2848
- return options && options.path && options.path.length > 0 && (dotenvPath = options.path), dotenvPath.endsWith(".vault") ? dotenvPath : `${dotenvPath}.vault`;
207
+ let possibleVaultPath = null;
208
+ if (options && options.path && options.path.length > 0)
209
+ if (Array.isArray(options.path))
210
+ for (const filepath of options.path)
211
+ fs.existsSync(filepath) && (possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`);
212
+ else
213
+ possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
214
+ else
215
+ possibleVaultPath = path.resolve(process.cwd(), ".env.vault");
216
+ return fs.existsSync(possibleVaultPath) ? possibleVaultPath : null;
2849
217
  }
2850
218
  function _resolveHome(envPath) {
2851
219
  return envPath[0] === "~" ? path.join(os.homedir(), envPath.slice(1)) : envPath;
@@ -2857,20 +225,36 @@ function _configVault(options) {
2857
225
  return options && options.processEnv != null && (processEnv = options.processEnv), DotenvModule.populate(processEnv, parsed, options), { parsed };
2858
226
  }
2859
227
  function configDotenv(options) {
2860
- let dotenvPath = path.resolve(process.cwd(), ".env"), encoding = "utf8";
228
+ const dotenvPath = path.resolve(process.cwd(), ".env");
229
+ let encoding = "utf8";
2861
230
  const debug2 = !!(options && options.debug);
2862
- options && (options.path != null && (dotenvPath = _resolveHome(options.path)), options.encoding != null ? encoding = options.encoding : debug2 && _debug("No encoding is specified. UTF-8 is used by default"));
2863
- try {
2864
- const parsed = DotenvModule.parse(fs.readFileSync(dotenvPath, { encoding }));
2865
- let processEnv = process.env;
2866
- return options && options.processEnv != null && (processEnv = options.processEnv), DotenvModule.populate(processEnv, parsed, options), { parsed };
2867
- } catch (e) {
2868
- return debug2 && _debug(`Failed to load ${dotenvPath} ${e.message}`), { error: e };
2869
- }
231
+ options && options.encoding ? encoding = options.encoding : debug2 && _debug("No encoding is specified. UTF-8 is used by default");
232
+ let optionPaths = [dotenvPath];
233
+ if (options && options.path)
234
+ if (!Array.isArray(options.path))
235
+ optionPaths = [_resolveHome(options.path)];
236
+ else {
237
+ optionPaths = [];
238
+ for (const filepath of options.path)
239
+ optionPaths.push(_resolveHome(filepath));
240
+ }
241
+ let lastError;
242
+ const parsedAll = {};
243
+ for (const path2 of optionPaths)
244
+ try {
245
+ const parsed = DotenvModule.parse(fs.readFileSync(path2, { encoding }));
246
+ DotenvModule.populate(parsedAll, parsed, options);
247
+ } catch (e) {
248
+ debug2 && _debug(`Failed to load ${path2} ${e.message}`), lastError = e;
249
+ }
250
+ let processEnv = process.env;
251
+ return options && options.processEnv != null && (processEnv = options.processEnv), DotenvModule.populate(processEnv, parsedAll, options), lastError ? { parsed: parsedAll, error: lastError } : { parsed: parsedAll };
2870
252
  }
2871
253
  function config(options) {
254
+ if (_dotenvKey(options).length === 0)
255
+ return DotenvModule.configDotenv(options);
2872
256
  const vaultPath = _vaultPath(options);
2873
- return _dotenvKey(options).length === 0 ? DotenvModule.configDotenv(options) : fs.existsSync(vaultPath) ? DotenvModule._configVault(options) : (_warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`), DotenvModule.configDotenv(options));
257
+ return vaultPath ? DotenvModule._configVault(options) : (_warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`), DotenvModule.configDotenv(options));
2874
258
  }
2875
259
  function decrypt(encrypted, keyStr) {
2876
260
  const key = Buffer.from(keyStr.slice(-64), "hex");
@@ -2883,19 +267,21 @@ function decrypt(encrypted, keyStr) {
2883
267
  } catch (error) {
2884
268
  const isRange = error instanceof RangeError, invalidKeyLength = error.message === "Invalid key length", decryptionFailed = error.message === "Unsupported state or unable to authenticate data";
2885
269
  if (isRange || invalidKeyLength) {
2886
- const msg = "INVALID_DOTENV_KEY: It must be 64 characters long (or more)";
2887
- throw new Error(msg);
270
+ const err = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
271
+ throw err.code = "INVALID_DOTENV_KEY", err;
2888
272
  } else if (decryptionFailed) {
2889
- const msg = "DECRYPTION_FAILED: Please check your DOTENV_KEY";
2890
- throw new Error(msg);
273
+ const err = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
274
+ throw err.code = "DECRYPTION_FAILED", err;
2891
275
  } else
2892
- throw console.error("Error: ", error.code), console.error("Error: ", error.message), error;
276
+ throw error;
2893
277
  }
2894
278
  }
2895
279
  function populate(processEnv, parsed, options = {}) {
2896
280
  const debug2 = !!(options && options.debug), override = !!(options && options.override);
2897
- if (typeof parsed != "object")
2898
- throw new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
281
+ if (typeof parsed != "object") {
282
+ const err = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
283
+ throw err.code = "OBJECT_REQUIRED", err;
284
+ }
2899
285
  for (const key of Object.keys(parsed))
2900
286
  Object.prototype.hasOwnProperty.call(processEnv, key) ? (override === !0 && (processEnv[key] = parsed[key]), debug2 && _debug(override === !0 ? `"${key}" is already defined and WAS overwritten` : `"${key}" is already defined and was NOT overwritten`)) : processEnv[key] = parsed[key];
2901
287
  }
@@ -2916,10 +302,10 @@ main$1.exports.decrypt = DotenvModule.decrypt;
2916
302
  var parse_1 = main$1.exports.parse = DotenvModule.parse;
2917
303
  main$1.exports.populate = DotenvModule.populate;
2918
304
  main$1.exports = DotenvModule;
2919
- var mainExports = main$1.exports, dotenv = /* @__PURE__ */ index.getDefaultExportFromCjs(mainExports);
305
+ var mainExports = main$1.exports, dotenv = /* @__PURE__ */ getDefaultExportFromCjs(mainExports);
2920
306
  function _interpolate(envValue, environment, config2) {
2921
307
  const matches = envValue.match(/(.?\${*[\w]*(?::-[\w/]*)?}*)/g) || [];
2922
- return matches.reduce(function(newEnv, match, index2) {
308
+ return matches.reduce(function(newEnv, match, index) {
2923
309
  const parts = /(.?)\${*([\w]*(?::-[\w/]*)?)?}*/g.exec(match);
2924
310
  if (!parts || parts.length === 0)
2925
311
  return newEnv;
@@ -2930,8 +316,8 @@ function _interpolate(envValue, environment, config2) {
2930
316
  else {
2931
317
  const keyParts = parts[2].split(":-"), key = keyParts[0];
2932
318
  if (replacePart = parts[0].substring(prefix.length), value = Object.prototype.hasOwnProperty.call(environment, key) ? environment[key] : config2.parsed[key] || keyParts[1] || "", keyParts.length > 1 && value) {
2933
- const replaceNested = matches[index2 + 1];
2934
- matches[index2 + 1] = "", newEnv = newEnv.replace(replaceNested, "");
319
+ const replaceNested = matches[index + 1];
320
+ matches[index + 1] = "", newEnv = newEnv.replace(replaceNested, "");
2935
321
  }
2936
322
  value = _interpolate(value, environment, config2);
2937
323
  }
@@ -2993,11 +379,11 @@ function lookupFile(dir, formats, options) {
2993
379
  if (parentDir !== dir && (!options?.rootDir || parentDir.startsWith(options?.rootDir)))
2994
380
  return lookupFile(parentDir, formats, options);
2995
381
  }
2996
- exports.createClient = createClient;
382
+ exports.commonjsGlobal = commonjsGlobal;
2997
383
  exports.debug = debug;
2998
384
  exports.dotenv = dotenv;
385
+ exports.getAugmentedNamespace = getAugmentedNamespace;
386
+ exports.getDefaultExportFromCjs = getDefaultExportFromCjs;
2999
387
  exports.loadEnv = loadEnv;
3000
- exports.requester = requester;
3001
388
  exports.resolveRootDir = resolveRootDir;
3002
- exports.tslib_es6 = tslib_es6$1;
3003
389
  //# sourceMappingURL=loadEnv.js.map