@uniformdev/next-app-router 20.7.1-alpha.118

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.
@@ -0,0 +1,3935 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __commonJS = (cb, mod) => function __require() {
8
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
19
+ // If the importer is in node compatibility mode or this is not an ESM
20
+ // file that has been converted to a CommonJS file using a Babel-
21
+ // compatible transform (i.e. "__esModule" has not been set), then set
22
+ // "default" to the CommonJS "module.exports" for node compatibility.
23
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
24
+ mod
25
+ ));
26
+
27
+ // ../../node_modules/.pnpm/yocto-queue@0.1.0/node_modules/yocto-queue/index.js
28
+ var require_yocto_queue = __commonJS({
29
+ "../../node_modules/.pnpm/yocto-queue@0.1.0/node_modules/yocto-queue/index.js"(exports, module) {
30
+ "use strict";
31
+ var Node = class {
32
+ /// value;
33
+ /// next;
34
+ constructor(value) {
35
+ this.value = value;
36
+ this.next = void 0;
37
+ }
38
+ };
39
+ var Queue = class {
40
+ // TODO: Use private class fields when targeting Node.js 12.
41
+ // #_head;
42
+ // #_tail;
43
+ // #_size;
44
+ constructor() {
45
+ this.clear();
46
+ }
47
+ enqueue(value) {
48
+ const node = new Node(value);
49
+ if (this._head) {
50
+ this._tail.next = node;
51
+ this._tail = node;
52
+ } else {
53
+ this._head = node;
54
+ this._tail = node;
55
+ }
56
+ this._size++;
57
+ }
58
+ dequeue() {
59
+ const current = this._head;
60
+ if (!current) {
61
+ return;
62
+ }
63
+ this._head = this._head.next;
64
+ this._size--;
65
+ return current.value;
66
+ }
67
+ clear() {
68
+ this._head = void 0;
69
+ this._tail = void 0;
70
+ this._size = 0;
71
+ }
72
+ get size() {
73
+ return this._size;
74
+ }
75
+ *[Symbol.iterator]() {
76
+ let current = this._head;
77
+ while (current) {
78
+ yield current.value;
79
+ current = current.next;
80
+ }
81
+ }
82
+ };
83
+ module.exports = Queue;
84
+ }
85
+ });
86
+
87
+ // ../../node_modules/.pnpm/p-limit@3.1.0/node_modules/p-limit/index.js
88
+ var require_p_limit = __commonJS({
89
+ "../../node_modules/.pnpm/p-limit@3.1.0/node_modules/p-limit/index.js"(exports, module) {
90
+ "use strict";
91
+ var Queue = require_yocto_queue();
92
+ var pLimit2 = (concurrency) => {
93
+ if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) {
94
+ throw new TypeError("Expected `concurrency` to be a number from 1 and up");
95
+ }
96
+ const queue = new Queue();
97
+ let activeCount = 0;
98
+ const next = () => {
99
+ activeCount--;
100
+ if (queue.size > 0) {
101
+ queue.dequeue()();
102
+ }
103
+ };
104
+ const run = async (fn, resolve, ...args) => {
105
+ activeCount++;
106
+ const result = (async () => fn(...args))();
107
+ resolve(result);
108
+ try {
109
+ await result;
110
+ } catch (e) {
111
+ }
112
+ next();
113
+ };
114
+ const enqueue = (fn, resolve, ...args) => {
115
+ queue.enqueue(run.bind(null, fn, resolve, ...args));
116
+ (async () => {
117
+ await Promise.resolve();
118
+ if (activeCount < concurrency && queue.size > 0) {
119
+ queue.dequeue()();
120
+ }
121
+ })();
122
+ };
123
+ const generator = (fn, ...args) => new Promise((resolve) => {
124
+ enqueue(fn, resolve, ...args);
125
+ });
126
+ Object.defineProperties(generator, {
127
+ activeCount: {
128
+ get: () => activeCount
129
+ },
130
+ pendingCount: {
131
+ get: () => queue.size
132
+ },
133
+ clearQueue: {
134
+ value: () => {
135
+ queue.clear();
136
+ }
137
+ }
138
+ });
139
+ return generator;
140
+ };
141
+ module.exports = pLimit2;
142
+ }
143
+ });
144
+
145
+ // src/index.ts
146
+ import "server-only";
147
+
148
+ // src/clients/canvas.ts
149
+ import "server-only";
150
+
151
+ // ../context/dist/api/api.mjs
152
+ var import_p_limit = __toESM(require_p_limit(), 1);
153
+ var __defProp2 = Object.defineProperty;
154
+ var __typeError = (msg) => {
155
+ throw TypeError(msg);
156
+ };
157
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
158
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
159
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
160
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
161
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
162
+ var defaultLimitPolicy = (0, import_p_limit.default)(6);
163
+ var ApiClientError = class _ApiClientError extends Error {
164
+ constructor(errorMessage, fetchMethod, fetchUri, statusCode, statusText, requestId) {
165
+ super(
166
+ `${errorMessage}
167
+ ${statusCode}${statusText ? " " + statusText : ""} (${fetchMethod} ${fetchUri}${requestId ? ` Request ID: ${requestId}` : ""})`
168
+ );
169
+ this.errorMessage = errorMessage;
170
+ this.fetchMethod = fetchMethod;
171
+ this.fetchUri = fetchUri;
172
+ this.statusCode = statusCode;
173
+ this.statusText = statusText;
174
+ this.requestId = requestId;
175
+ Object.setPrototypeOf(this, _ApiClientError.prototype);
176
+ }
177
+ };
178
+ var ApiClient = class _ApiClient {
179
+ constructor(options) {
180
+ __publicField(this, "options");
181
+ var _a, _b, _c, _d, _e;
182
+ if (!options.apiKey && !options.bearerToken) {
183
+ throw new Error("You must provide an API key or a bearer token");
184
+ }
185
+ let leFetch = options.fetch;
186
+ if (!leFetch) {
187
+ if (typeof window !== "undefined") {
188
+ leFetch = window.fetch.bind(window);
189
+ } else if (typeof fetch !== "undefined") {
190
+ leFetch = fetch;
191
+ } else {
192
+ throw new Error("You must provide or polyfill a fetch implementation when not in a browser");
193
+ }
194
+ }
195
+ this.options = {
196
+ ...options,
197
+ fetch: leFetch,
198
+ apiHost: this.ensureApiHost(options.apiHost),
199
+ apiKey: (_a = options.apiKey) != null ? _a : null,
200
+ projectId: (_b = options.projectId) != null ? _b : null,
201
+ bearerToken: (_c = options.bearerToken) != null ? _c : null,
202
+ limitPolicy: (_d = options.limitPolicy) != null ? _d : defaultLimitPolicy,
203
+ bypassCache: (_e = options.bypassCache) != null ? _e : false
204
+ };
205
+ }
206
+ async apiClient(fetchUri, options) {
207
+ return (await this.apiClientWithResponse(fetchUri, options)).body;
208
+ }
209
+ async apiClientWithResponse(fetchUri, options) {
210
+ return this.options.limitPolicy(async () => {
211
+ var _a;
212
+ const coreHeaders = this.options.apiKey ? {
213
+ "x-api-key": this.options.apiKey
214
+ } : {
215
+ Authorization: `Bearer ${this.options.bearerToken}`
216
+ };
217
+ if (this.options.bypassCache) {
218
+ coreHeaders["x-bypass-cache"] = "true";
219
+ }
220
+ const { fetch: fetch2, signal } = this.options;
221
+ const callApi = () => fetch2(fetchUri.toString(), {
222
+ ...options,
223
+ signal,
224
+ headers: {
225
+ ...options == null ? void 0 : options.headers,
226
+ ...coreHeaders
227
+ }
228
+ });
229
+ const apiResponse = await handleRateLimits(callApi);
230
+ if (!apiResponse.ok) {
231
+ let message = "";
232
+ try {
233
+ const responseText = await apiResponse.text();
234
+ try {
235
+ const parsed = JSON.parse(responseText);
236
+ if (parsed.errorMessage) {
237
+ message = Array.isArray(parsed.errorMessage) ? parsed.errorMessage.join(", ") : parsed.errorMessage;
238
+ } else {
239
+ message = responseText;
240
+ }
241
+ } catch (e) {
242
+ message = responseText;
243
+ }
244
+ } catch (e) {
245
+ message = `General error`;
246
+ }
247
+ throw new ApiClientError(
248
+ message,
249
+ (_a = options == null ? void 0 : options.method) != null ? _a : "GET",
250
+ fetchUri.toString(),
251
+ apiResponse.status,
252
+ apiResponse.statusText,
253
+ _ApiClient.getRequestId(apiResponse)
254
+ );
255
+ }
256
+ if (options == null ? void 0 : options.expectNoContent) {
257
+ return { response: apiResponse, body: null };
258
+ }
259
+ return {
260
+ response: apiResponse,
261
+ body: await apiResponse.json()
262
+ };
263
+ });
264
+ }
265
+ createUrl(path, queryParams, hostOverride) {
266
+ const url = new URL(`${hostOverride != null ? hostOverride : this.options.apiHost}${path}`);
267
+ Object.entries(queryParams != null ? queryParams : {}).forEach(([key, value]) => {
268
+ var _a;
269
+ if (typeof value !== "undefined" && value !== null) {
270
+ url.searchParams.append(key, Array.isArray(value) ? value.join(",") : (_a = value == null ? void 0 : value.toString()) != null ? _a : "");
271
+ }
272
+ });
273
+ return url;
274
+ }
275
+ ensureApiHost(apiHost) {
276
+ if (!apiHost) return "https://uniform.app";
277
+ if (!(apiHost == null ? void 0 : apiHost.startsWith("http"))) {
278
+ throw new Error('Your apiHost must start with "http"');
279
+ }
280
+ if (apiHost.indexOf("/", 8) > -1) {
281
+ throw new Error("Your apiHost must not contain a path element after the domain");
282
+ }
283
+ if (apiHost.indexOf("?") > -1) {
284
+ throw new Error("Your apiHost must not contain a query string");
285
+ }
286
+ if (apiHost == null ? void 0 : apiHost.endsWith("/")) {
287
+ apiHost = apiHost.substring(0, apiHost.length - 1);
288
+ }
289
+ return apiHost;
290
+ }
291
+ static getRequestId(response) {
292
+ const apigRequestId = response.headers.get("apigw-requestid");
293
+ if (apigRequestId) {
294
+ return apigRequestId;
295
+ }
296
+ return void 0;
297
+ }
298
+ };
299
+ async function handleRateLimits(callApi) {
300
+ var _a;
301
+ const backoffRetries = 5;
302
+ let backoffRetriesLeft = backoffRetries;
303
+ let response;
304
+ while (backoffRetriesLeft > 0) {
305
+ response = await callApi();
306
+ if (response.status !== 429) {
307
+ break;
308
+ }
309
+ let resetWait = 0;
310
+ try {
311
+ const responseClone = response.clone();
312
+ const dateHeader = responseClone.headers.get("date");
313
+ const serverTime = dateHeader ? new Date(dateHeader).getTime() : void 0;
314
+ const body = await responseClone.json();
315
+ const resetTime = (_a = body == null ? void 0 : body.info) == null ? void 0 : _a.reset;
316
+ if (typeof serverTime === "number" && typeof resetTime === "number") {
317
+ resetWait = Math.max(0, Math.min(Math.round(1.1 * (resetTime - serverTime)), 1e4));
318
+ }
319
+ } catch (e) {
320
+ }
321
+ const base = Math.pow(2, backoffRetries - backoffRetriesLeft) * 333;
322
+ const backoffWait = base + Math.round(Math.random() * (base / 2)) * (Math.random() > 0.5 ? 1 : -1);
323
+ await new Promise((resolve) => setTimeout(resolve, resetWait + backoffWait));
324
+ backoffRetriesLeft -= 1;
325
+ }
326
+ return response;
327
+ }
328
+ var _url;
329
+ var _AggregateClient = class _AggregateClient2 extends ApiClient {
330
+ constructor(options) {
331
+ super(options);
332
+ }
333
+ /** Fetches all aggregates for a project */
334
+ async get(options) {
335
+ const { projectId } = this.options;
336
+ const fetchUri = this.createUrl(__privateGet(_AggregateClient2, _url), { ...options, projectId });
337
+ return await this.apiClient(fetchUri);
338
+ }
339
+ /** Updates or creates (based on id) an Aggregate */
340
+ async upsert(body) {
341
+ const fetchUri = this.createUrl(__privateGet(_AggregateClient2, _url));
342
+ await this.apiClient(fetchUri, {
343
+ method: "PUT",
344
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
345
+ expectNoContent: true
346
+ });
347
+ }
348
+ /** Deletes an Aggregate */
349
+ async remove(body) {
350
+ const fetchUri = this.createUrl(__privateGet(_AggregateClient2, _url));
351
+ await this.apiClient(fetchUri, {
352
+ method: "DELETE",
353
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
354
+ expectNoContent: true
355
+ });
356
+ }
357
+ };
358
+ _url = /* @__PURE__ */ new WeakMap();
359
+ __privateAdd(_AggregateClient, _url, "/api/v2/aggregate");
360
+ var _url2;
361
+ var _DimensionClient = class _DimensionClient2 extends ApiClient {
362
+ constructor(options) {
363
+ super(options);
364
+ }
365
+ /** Fetches the known score dimensions for a project */
366
+ async get(options) {
367
+ const { projectId } = this.options;
368
+ const fetchUri = this.createUrl(__privateGet(_DimensionClient2, _url2), { ...options, projectId });
369
+ return await this.apiClient(fetchUri);
370
+ }
371
+ };
372
+ _url2 = /* @__PURE__ */ new WeakMap();
373
+ __privateAdd(_DimensionClient, _url2, "/api/v2/dimension");
374
+ var _url3;
375
+ var _valueUrl;
376
+ var _EnrichmentClient = class _EnrichmentClient2 extends ApiClient {
377
+ constructor(options) {
378
+ super(options);
379
+ }
380
+ /** Fetches all enrichments and values for a project, grouped by category */
381
+ async get(options) {
382
+ const { projectId } = this.options;
383
+ const fetchUri = this.createUrl(__privateGet(_EnrichmentClient2, _url3), { ...options, projectId });
384
+ return await this.apiClient(fetchUri);
385
+ }
386
+ /** Updates or creates (based on id) an enrichment category */
387
+ async upsertCategory(body) {
388
+ const fetchUri = this.createUrl(__privateGet(_EnrichmentClient2, _url3));
389
+ await this.apiClient(fetchUri, {
390
+ method: "PUT",
391
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
392
+ expectNoContent: true
393
+ });
394
+ }
395
+ /** Deletes an enrichment category */
396
+ async removeCategory(body) {
397
+ const fetchUri = this.createUrl(__privateGet(_EnrichmentClient2, _url3));
398
+ await this.apiClient(fetchUri, {
399
+ method: "DELETE",
400
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
401
+ expectNoContent: true
402
+ });
403
+ }
404
+ /** Updates or creates (based on id) an enrichment value within an enrichment category */
405
+ async upsertValue(body) {
406
+ const fetchUri = this.createUrl(__privateGet(_EnrichmentClient2, _valueUrl));
407
+ await this.apiClient(fetchUri, {
408
+ method: "PUT",
409
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
410
+ expectNoContent: true
411
+ });
412
+ }
413
+ /** Deletes an enrichment value within an enrichment category. The category is left alone. */
414
+ async removeValue(body) {
415
+ const fetchUri = this.createUrl(__privateGet(_EnrichmentClient2, _valueUrl));
416
+ await this.apiClient(fetchUri, {
417
+ method: "DELETE",
418
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
419
+ expectNoContent: true
420
+ });
421
+ }
422
+ };
423
+ _url3 = /* @__PURE__ */ new WeakMap();
424
+ _valueUrl = /* @__PURE__ */ new WeakMap();
425
+ __privateAdd(_EnrichmentClient, _url3, "/api/v1/enrichments");
426
+ __privateAdd(_EnrichmentClient, _valueUrl, "/api/v1/enrichment-values");
427
+ var _url4;
428
+ var _ManifestClient = class _ManifestClient2 extends ApiClient {
429
+ constructor(options) {
430
+ super(options);
431
+ }
432
+ /** Fetches the Context manifest for a project */
433
+ async get(options) {
434
+ const { projectId } = this.options;
435
+ const fetchUri = this.createUrl(__privateGet(_ManifestClient2, _url4), { ...options, projectId });
436
+ return await this.apiClient(fetchUri);
437
+ }
438
+ /** Publishes the Context manifest for a project */
439
+ async publish() {
440
+ const { projectId } = this.options;
441
+ const fetchUri = this.createUrl("/api/v1/publish", { siteId: projectId });
442
+ await this.apiClient(fetchUri, {
443
+ method: "POST",
444
+ expectNoContent: true
445
+ });
446
+ }
447
+ };
448
+ _url4 = /* @__PURE__ */ new WeakMap();
449
+ __privateAdd(_ManifestClient, _url4, "/api/v2/manifest");
450
+ var ManifestClient = _ManifestClient;
451
+ var _url5;
452
+ var _QuirkClient = class _QuirkClient2 extends ApiClient {
453
+ constructor(options) {
454
+ super(options);
455
+ }
456
+ /** Fetches all Quirks for a project */
457
+ async get(options) {
458
+ const { projectId } = this.options;
459
+ const fetchUri = this.createUrl(__privateGet(_QuirkClient2, _url5), { ...options, projectId });
460
+ return await this.apiClient(fetchUri);
461
+ }
462
+ /** Updates or creates (based on id) a Quirk */
463
+ async upsert(body) {
464
+ const fetchUri = this.createUrl(__privateGet(_QuirkClient2, _url5));
465
+ await this.apiClient(fetchUri, {
466
+ method: "PUT",
467
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
468
+ expectNoContent: true
469
+ });
470
+ }
471
+ /** Deletes a Quirk */
472
+ async remove(body) {
473
+ const fetchUri = this.createUrl(__privateGet(_QuirkClient2, _url5));
474
+ await this.apiClient(fetchUri, {
475
+ method: "DELETE",
476
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
477
+ expectNoContent: true
478
+ });
479
+ }
480
+ };
481
+ _url5 = /* @__PURE__ */ new WeakMap();
482
+ __privateAdd(_QuirkClient, _url5, "/api/v2/quirk");
483
+ var _url6;
484
+ var _SignalClient = class _SignalClient2 extends ApiClient {
485
+ constructor(options) {
486
+ super(options);
487
+ }
488
+ /** Fetches all Signals for a project */
489
+ async get(options) {
490
+ const { projectId } = this.options;
491
+ const fetchUri = this.createUrl(__privateGet(_SignalClient2, _url6), { ...options, projectId });
492
+ return await this.apiClient(fetchUri);
493
+ }
494
+ /** Updates or creates (based on id) a Signal */
495
+ async upsert(body) {
496
+ const fetchUri = this.createUrl(__privateGet(_SignalClient2, _url6));
497
+ await this.apiClient(fetchUri, {
498
+ method: "PUT",
499
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
500
+ expectNoContent: true
501
+ });
502
+ }
503
+ /** Deletes a Signal */
504
+ async remove(body) {
505
+ const fetchUri = this.createUrl(__privateGet(_SignalClient2, _url6));
506
+ await this.apiClient(fetchUri, {
507
+ method: "DELETE",
508
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
509
+ expectNoContent: true
510
+ });
511
+ }
512
+ };
513
+ _url6 = /* @__PURE__ */ new WeakMap();
514
+ __privateAdd(_SignalClient, _url6, "/api/v2/signal");
515
+ var _url7;
516
+ var _TestClient = class _TestClient2 extends ApiClient {
517
+ constructor(options) {
518
+ super(options);
519
+ }
520
+ /** Fetches all Tests for a project */
521
+ async get(options) {
522
+ const { projectId } = this.options;
523
+ const fetchUri = this.createUrl(__privateGet(_TestClient2, _url7), { ...options, projectId });
524
+ return await this.apiClient(fetchUri);
525
+ }
526
+ /** Updates or creates (based on id) a Test */
527
+ async upsert(body) {
528
+ const fetchUri = this.createUrl(__privateGet(_TestClient2, _url7));
529
+ await this.apiClient(fetchUri, {
530
+ method: "PUT",
531
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
532
+ expectNoContent: true
533
+ });
534
+ }
535
+ /** Deletes a Test */
536
+ async remove(body) {
537
+ const fetchUri = this.createUrl(__privateGet(_TestClient2, _url7));
538
+ await this.apiClient(fetchUri, {
539
+ method: "DELETE",
540
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
541
+ expectNoContent: true
542
+ });
543
+ }
544
+ };
545
+ _url7 = /* @__PURE__ */ new WeakMap();
546
+ __privateAdd(_TestClient, _url7, "/api/v2/test");
547
+
548
+ // ../canvas/dist/index.mjs
549
+ var __create2 = Object.create;
550
+ var __defProp3 = Object.defineProperty;
551
+ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
552
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
553
+ var __getProtoOf2 = Object.getPrototypeOf;
554
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
555
+ var __typeError2 = (msg) => {
556
+ throw TypeError(msg);
557
+ };
558
+ var __commonJS2 = (cb, mod) => function __require() {
559
+ return mod || (0, cb[__getOwnPropNames2(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
560
+ };
561
+ var __copyProps2 = (to, from, except, desc) => {
562
+ if (from && typeof from === "object" || typeof from === "function") {
563
+ for (let key of __getOwnPropNames2(from))
564
+ if (!__hasOwnProp2.call(to, key) && key !== except)
565
+ __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
566
+ }
567
+ return to;
568
+ };
569
+ var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2(
570
+ // If the importer is in node compatibility mode or this is not an ESM
571
+ // file that has been converted to a CommonJS file using a Babel-
572
+ // compatible transform (i.e. "__esModule" has not been set), then set
573
+ // "default" to the CommonJS "module.exports" for node compatibility.
574
+ isNodeMode || !mod || !mod.__esModule ? __defProp3(target, "default", { value: mod, enumerable: true }) : target,
575
+ mod
576
+ ));
577
+ var __accessCheck2 = (obj, member, msg) => member.has(obj) || __typeError2("Cannot " + msg);
578
+ var __privateGet2 = (obj, member, getter) => (__accessCheck2(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
579
+ var __privateAdd2 = (obj, member, value) => member.has(obj) ? __typeError2("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
580
+ var require_yocto_queue2 = __commonJS2({
581
+ "../../node_modules/.pnpm/yocto-queue@0.1.0/node_modules/yocto-queue/index.js"(exports, module) {
582
+ "use strict";
583
+ var Node = class {
584
+ /// value;
585
+ /// next;
586
+ constructor(value) {
587
+ this.value = value;
588
+ this.next = void 0;
589
+ }
590
+ };
591
+ var Queue = class {
592
+ // TODO: Use private class fields when targeting Node.js 12.
593
+ // #_head;
594
+ // #_tail;
595
+ // #_size;
596
+ constructor() {
597
+ this.clear();
598
+ }
599
+ enqueue(value) {
600
+ const node = new Node(value);
601
+ if (this._head) {
602
+ this._tail.next = node;
603
+ this._tail = node;
604
+ } else {
605
+ this._head = node;
606
+ this._tail = node;
607
+ }
608
+ this._size++;
609
+ }
610
+ dequeue() {
611
+ const current = this._head;
612
+ if (!current) {
613
+ return;
614
+ }
615
+ this._head = this._head.next;
616
+ this._size--;
617
+ return current.value;
618
+ }
619
+ clear() {
620
+ this._head = void 0;
621
+ this._tail = void 0;
622
+ this._size = 0;
623
+ }
624
+ get size() {
625
+ return this._size;
626
+ }
627
+ *[Symbol.iterator]() {
628
+ let current = this._head;
629
+ while (current) {
630
+ yield current.value;
631
+ current = current.next;
632
+ }
633
+ }
634
+ };
635
+ module.exports = Queue;
636
+ }
637
+ });
638
+ var require_p_limit2 = __commonJS2({
639
+ "../../node_modules/.pnpm/p-limit@3.1.0/node_modules/p-limit/index.js"(exports, module) {
640
+ "use strict";
641
+ var Queue = require_yocto_queue2();
642
+ var pLimit2 = (concurrency) => {
643
+ if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) {
644
+ throw new TypeError("Expected `concurrency` to be a number from 1 and up");
645
+ }
646
+ const queue = new Queue();
647
+ let activeCount = 0;
648
+ const next = () => {
649
+ activeCount--;
650
+ if (queue.size > 0) {
651
+ queue.dequeue()();
652
+ }
653
+ };
654
+ const run = async (fn, resolve, ...args) => {
655
+ activeCount++;
656
+ const result = (async () => fn(...args))();
657
+ resolve(result);
658
+ try {
659
+ await result;
660
+ } catch (e) {
661
+ }
662
+ next();
663
+ };
664
+ const enqueue = (fn, resolve, ...args) => {
665
+ queue.enqueue(run.bind(null, fn, resolve, ...args));
666
+ (async () => {
667
+ await Promise.resolve();
668
+ if (activeCount < concurrency && queue.size > 0) {
669
+ queue.dequeue()();
670
+ }
671
+ })();
672
+ };
673
+ const generator = (fn, ...args) => new Promise((resolve) => {
674
+ enqueue(fn, resolve, ...args);
675
+ });
676
+ Object.defineProperties(generator, {
677
+ activeCount: {
678
+ get: () => activeCount
679
+ },
680
+ pendingCount: {
681
+ get: () => queue.size
682
+ },
683
+ clearQueue: {
684
+ value: () => {
685
+ queue.clear();
686
+ }
687
+ }
688
+ });
689
+ return generator;
690
+ };
691
+ module.exports = pLimit2;
692
+ }
693
+ });
694
+ var require_retry_operation = __commonJS2({
695
+ "../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js"(exports, module) {
696
+ "use strict";
697
+ function RetryOperation(timeouts, options) {
698
+ if (typeof options === "boolean") {
699
+ options = { forever: options };
700
+ }
701
+ this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
702
+ this._timeouts = timeouts;
703
+ this._options = options || {};
704
+ this._maxRetryTime = options && options.maxRetryTime || Infinity;
705
+ this._fn = null;
706
+ this._errors = [];
707
+ this._attempts = 1;
708
+ this._operationTimeout = null;
709
+ this._operationTimeoutCb = null;
710
+ this._timeout = null;
711
+ this._operationStart = null;
712
+ this._timer = null;
713
+ if (this._options.forever) {
714
+ this._cachedTimeouts = this._timeouts.slice(0);
715
+ }
716
+ }
717
+ module.exports = RetryOperation;
718
+ RetryOperation.prototype.reset = function() {
719
+ this._attempts = 1;
720
+ this._timeouts = this._originalTimeouts.slice(0);
721
+ };
722
+ RetryOperation.prototype.stop = function() {
723
+ if (this._timeout) {
724
+ clearTimeout(this._timeout);
725
+ }
726
+ if (this._timer) {
727
+ clearTimeout(this._timer);
728
+ }
729
+ this._timeouts = [];
730
+ this._cachedTimeouts = null;
731
+ };
732
+ RetryOperation.prototype.retry = function(err) {
733
+ if (this._timeout) {
734
+ clearTimeout(this._timeout);
735
+ }
736
+ if (!err) {
737
+ return false;
738
+ }
739
+ var currentTime = (/* @__PURE__ */ new Date()).getTime();
740
+ if (err && currentTime - this._operationStart >= this._maxRetryTime) {
741
+ this._errors.push(err);
742
+ this._errors.unshift(new Error("RetryOperation timeout occurred"));
743
+ return false;
744
+ }
745
+ this._errors.push(err);
746
+ var timeout = this._timeouts.shift();
747
+ if (timeout === void 0) {
748
+ if (this._cachedTimeouts) {
749
+ this._errors.splice(0, this._errors.length - 1);
750
+ timeout = this._cachedTimeouts.slice(-1);
751
+ } else {
752
+ return false;
753
+ }
754
+ }
755
+ var self = this;
756
+ this._timer = setTimeout(function() {
757
+ self._attempts++;
758
+ if (self._operationTimeoutCb) {
759
+ self._timeout = setTimeout(function() {
760
+ self._operationTimeoutCb(self._attempts);
761
+ }, self._operationTimeout);
762
+ if (self._options.unref) {
763
+ self._timeout.unref();
764
+ }
765
+ }
766
+ self._fn(self._attempts);
767
+ }, timeout);
768
+ if (this._options.unref) {
769
+ this._timer.unref();
770
+ }
771
+ return true;
772
+ };
773
+ RetryOperation.prototype.attempt = function(fn, timeoutOps) {
774
+ this._fn = fn;
775
+ if (timeoutOps) {
776
+ if (timeoutOps.timeout) {
777
+ this._operationTimeout = timeoutOps.timeout;
778
+ }
779
+ if (timeoutOps.cb) {
780
+ this._operationTimeoutCb = timeoutOps.cb;
781
+ }
782
+ }
783
+ var self = this;
784
+ if (this._operationTimeoutCb) {
785
+ this._timeout = setTimeout(function() {
786
+ self._operationTimeoutCb();
787
+ }, self._operationTimeout);
788
+ }
789
+ this._operationStart = (/* @__PURE__ */ new Date()).getTime();
790
+ this._fn(this._attempts);
791
+ };
792
+ RetryOperation.prototype.try = function(fn) {
793
+ console.log("Using RetryOperation.try() is deprecated");
794
+ this.attempt(fn);
795
+ };
796
+ RetryOperation.prototype.start = function(fn) {
797
+ console.log("Using RetryOperation.start() is deprecated");
798
+ this.attempt(fn);
799
+ };
800
+ RetryOperation.prototype.start = RetryOperation.prototype.try;
801
+ RetryOperation.prototype.errors = function() {
802
+ return this._errors;
803
+ };
804
+ RetryOperation.prototype.attempts = function() {
805
+ return this._attempts;
806
+ };
807
+ RetryOperation.prototype.mainError = function() {
808
+ if (this._errors.length === 0) {
809
+ return null;
810
+ }
811
+ var counts = {};
812
+ var mainError = null;
813
+ var mainErrorCount = 0;
814
+ for (var i = 0; i < this._errors.length; i++) {
815
+ var error = this._errors[i];
816
+ var message = error.message;
817
+ var count = (counts[message] || 0) + 1;
818
+ counts[message] = count;
819
+ if (count >= mainErrorCount) {
820
+ mainError = error;
821
+ mainErrorCount = count;
822
+ }
823
+ }
824
+ return mainError;
825
+ };
826
+ }
827
+ });
828
+ var require_retry = __commonJS2({
829
+ "../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js"(exports) {
830
+ "use strict";
831
+ var RetryOperation = require_retry_operation();
832
+ exports.operation = function(options) {
833
+ var timeouts = exports.timeouts(options);
834
+ return new RetryOperation(timeouts, {
835
+ forever: options && (options.forever || options.retries === Infinity),
836
+ unref: options && options.unref,
837
+ maxRetryTime: options && options.maxRetryTime
838
+ });
839
+ };
840
+ exports.timeouts = function(options) {
841
+ if (options instanceof Array) {
842
+ return [].concat(options);
843
+ }
844
+ var opts = {
845
+ retries: 10,
846
+ factor: 2,
847
+ minTimeout: 1 * 1e3,
848
+ maxTimeout: Infinity,
849
+ randomize: false
850
+ };
851
+ for (var key in options) {
852
+ opts[key] = options[key];
853
+ }
854
+ if (opts.minTimeout > opts.maxTimeout) {
855
+ throw new Error("minTimeout is greater than maxTimeout");
856
+ }
857
+ var timeouts = [];
858
+ for (var i = 0; i < opts.retries; i++) {
859
+ timeouts.push(this.createTimeout(i, opts));
860
+ }
861
+ if (options && options.forever && !timeouts.length) {
862
+ timeouts.push(this.createTimeout(i, opts));
863
+ }
864
+ timeouts.sort(function(a, b) {
865
+ return a - b;
866
+ });
867
+ return timeouts;
868
+ };
869
+ exports.createTimeout = function(attempt, opts) {
870
+ var random = opts.randomize ? Math.random() + 1 : 1;
871
+ var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));
872
+ timeout = Math.min(timeout, opts.maxTimeout);
873
+ return timeout;
874
+ };
875
+ exports.wrap = function(obj, options, methods) {
876
+ if (options instanceof Array) {
877
+ methods = options;
878
+ options = null;
879
+ }
880
+ if (!methods) {
881
+ methods = [];
882
+ for (var key in obj) {
883
+ if (typeof obj[key] === "function") {
884
+ methods.push(key);
885
+ }
886
+ }
887
+ }
888
+ for (var i = 0; i < methods.length; i++) {
889
+ var method = methods[i];
890
+ var original = obj[method];
891
+ obj[method] = function retryWrapper(original2) {
892
+ var op = exports.operation(options);
893
+ var args = Array.prototype.slice.call(arguments, 1);
894
+ var callback = args.pop();
895
+ args.push(function(err) {
896
+ if (op.retry(err)) {
897
+ return;
898
+ }
899
+ if (err) {
900
+ arguments[0] = op.mainError();
901
+ }
902
+ callback.apply(this, arguments);
903
+ });
904
+ op.attempt(function() {
905
+ original2.apply(obj, args);
906
+ });
907
+ }.bind(obj, original);
908
+ obj[method].options = options;
909
+ }
910
+ };
911
+ }
912
+ });
913
+ var require_retry2 = __commonJS2({
914
+ "../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js"(exports, module) {
915
+ "use strict";
916
+ module.exports = require_retry();
917
+ }
918
+ });
919
+ var import_p_limit2 = __toESM2(require_p_limit2());
920
+ var import_retry = __toESM2(require_retry2(), 1);
921
+ var networkErrorMsgs = /* @__PURE__ */ new Set([
922
+ "Failed to fetch",
923
+ // Chrome
924
+ "NetworkError when attempting to fetch resource.",
925
+ // Firefox
926
+ "The Internet connection appears to be offline.",
927
+ // Safari
928
+ "Network request failed",
929
+ // `cross-fetch`
930
+ "fetch failed"
931
+ // Undici (Node.js)
932
+ ]);
933
+ var AbortError = class extends Error {
934
+ constructor(message) {
935
+ super();
936
+ if (message instanceof Error) {
937
+ this.originalError = message;
938
+ ({ message } = message);
939
+ } else {
940
+ this.originalError = new Error(message);
941
+ this.originalError.stack = this.stack;
942
+ }
943
+ this.name = "AbortError";
944
+ this.message = message;
945
+ }
946
+ };
947
+ var decorateErrorWithCounts = (error, attemptNumber, options) => {
948
+ const retriesLeft = options.retries - (attemptNumber - 1);
949
+ error.attemptNumber = attemptNumber;
950
+ error.retriesLeft = retriesLeft;
951
+ return error;
952
+ };
953
+ var isNetworkError = (errorMessage) => networkErrorMsgs.has(errorMessage);
954
+ var getDOMException = (errorMessage) => globalThis.DOMException === void 0 ? new Error(errorMessage) : new DOMException(errorMessage);
955
+ async function pRetry(input, options) {
956
+ return new Promise((resolve, reject) => {
957
+ options = {
958
+ onFailedAttempt() {
959
+ },
960
+ retries: 10,
961
+ ...options
962
+ };
963
+ const operation = import_retry.default.operation(options);
964
+ operation.attempt(async (attemptNumber) => {
965
+ try {
966
+ resolve(await input(attemptNumber));
967
+ } catch (error) {
968
+ if (!(error instanceof Error)) {
969
+ reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));
970
+ return;
971
+ }
972
+ if (error instanceof AbortError) {
973
+ operation.stop();
974
+ reject(error.originalError);
975
+ } else if (error instanceof TypeError && !isNetworkError(error.message)) {
976
+ operation.stop();
977
+ reject(error);
978
+ } else {
979
+ decorateErrorWithCounts(error, attemptNumber, options);
980
+ try {
981
+ await options.onFailedAttempt(error);
982
+ } catch (error2) {
983
+ reject(error2);
984
+ return;
985
+ }
986
+ if (!operation.retry(error)) {
987
+ reject(operation.mainError());
988
+ }
989
+ }
990
+ }
991
+ });
992
+ if (options.signal && !options.signal.aborted) {
993
+ options.signal.addEventListener("abort", () => {
994
+ operation.stop();
995
+ const reason = options.signal.reason === void 0 ? getDOMException("The operation was aborted.") : options.signal.reason;
996
+ reject(reason instanceof Error ? reason : getDOMException(reason));
997
+ }, {
998
+ once: true
999
+ });
1000
+ }
1001
+ });
1002
+ }
1003
+ var AbortError2 = class extends Error {
1004
+ constructor() {
1005
+ super("Throttled function aborted");
1006
+ this.name = "AbortError";
1007
+ }
1008
+ };
1009
+ function pThrottle({ limit, interval, strict }) {
1010
+ if (!Number.isFinite(limit)) {
1011
+ throw new TypeError("Expected `limit` to be a finite number");
1012
+ }
1013
+ if (!Number.isFinite(interval)) {
1014
+ throw new TypeError("Expected `interval` to be a finite number");
1015
+ }
1016
+ const queue = /* @__PURE__ */ new Map();
1017
+ let currentTick = 0;
1018
+ let activeCount = 0;
1019
+ function windowedDelay() {
1020
+ const now = Date.now();
1021
+ if (now - currentTick > interval) {
1022
+ activeCount = 1;
1023
+ currentTick = now;
1024
+ return 0;
1025
+ }
1026
+ if (activeCount < limit) {
1027
+ activeCount++;
1028
+ } else {
1029
+ currentTick += interval;
1030
+ activeCount = 1;
1031
+ }
1032
+ return currentTick - now;
1033
+ }
1034
+ const strictTicks = [];
1035
+ function strictDelay() {
1036
+ const now = Date.now();
1037
+ if (strictTicks.length < limit) {
1038
+ strictTicks.push(now);
1039
+ return 0;
1040
+ }
1041
+ const earliestTime = strictTicks.shift() + interval;
1042
+ if (now >= earliestTime) {
1043
+ strictTicks.push(now);
1044
+ return 0;
1045
+ }
1046
+ strictTicks.push(earliestTime);
1047
+ return earliestTime - now;
1048
+ }
1049
+ const getDelay = strict ? strictDelay : windowedDelay;
1050
+ return (function_) => {
1051
+ const throttled = function(...args) {
1052
+ if (!throttled.isEnabled) {
1053
+ return (async () => function_.apply(this, args))();
1054
+ }
1055
+ let timeout;
1056
+ return new Promise((resolve, reject) => {
1057
+ const execute = () => {
1058
+ resolve(function_.apply(this, args));
1059
+ queue.delete(timeout);
1060
+ };
1061
+ timeout = setTimeout(execute, getDelay());
1062
+ queue.set(timeout, reject);
1063
+ });
1064
+ };
1065
+ throttled.abort = () => {
1066
+ for (const timeout of queue.keys()) {
1067
+ clearTimeout(timeout);
1068
+ queue.get(timeout)(new AbortError2());
1069
+ }
1070
+ queue.clear();
1071
+ strictTicks.splice(0, strictTicks.length);
1072
+ };
1073
+ throttled.isEnabled = true;
1074
+ return throttled;
1075
+ };
1076
+ }
1077
+ function createLimitPolicy({
1078
+ throttle = { interval: 1e3, limit: 10 },
1079
+ retry: retry2 = { retries: 1, factor: 1.66 },
1080
+ limit = 10
1081
+ }) {
1082
+ const throttler = throttle ? pThrottle(throttle) : null;
1083
+ const limiter = limit ? (0, import_p_limit2.default)(limit) : null;
1084
+ return function limitPolicy(func) {
1085
+ let currentFunc = async () => await func();
1086
+ if (throttler) {
1087
+ const throttleFunc = currentFunc;
1088
+ currentFunc = throttler(throttleFunc);
1089
+ }
1090
+ if (limiter) {
1091
+ const limitFunc = currentFunc;
1092
+ currentFunc = () => limiter(limitFunc);
1093
+ }
1094
+ if (retry2) {
1095
+ const retryFunc = currentFunc;
1096
+ currentFunc = () => pRetry(retryFunc, {
1097
+ ...retry2,
1098
+ onFailedAttempt: async (error) => {
1099
+ if (retry2.onFailedAttempt) {
1100
+ await retry2.onFailedAttempt(error);
1101
+ }
1102
+ if (error instanceof ApiClientError && typeof error.statusCode === "number" && error.statusCode >= 400 && error.statusCode < 500 && error.statusCode !== 429 && error.statusCode !== 408) {
1103
+ throw error;
1104
+ }
1105
+ }
1106
+ });
1107
+ }
1108
+ return currentFunc();
1109
+ };
1110
+ }
1111
+ var isPlainObject = (obj) => typeof obj === "object" && obj !== null && !Array.isArray(obj);
1112
+ function rewriteFilters(filters) {
1113
+ return Object.entries(filters != null ? filters : {}).reduce(
1114
+ (acc, [key, value]) => {
1115
+ const lhs = `filters.${key}` + (isPlainObject(value) ? `[${Object.keys(value)[0]}]` : "");
1116
+ const rhs = isPlainObject(value) ? Object.values(value)[0] : value;
1117
+ return {
1118
+ ...acc,
1119
+ [lhs]: Array.isArray(rhs) ? rhs.map((v) => `${v}`.trim()).join(",") : `${rhs}`.trim()
1120
+ };
1121
+ },
1122
+ {}
1123
+ );
1124
+ }
1125
+ var CANVAS_URL = "/api/v1/canvas";
1126
+ var CanvasClient = class extends ApiClient {
1127
+ constructor(options) {
1128
+ var _a;
1129
+ if (!options.limitPolicy) {
1130
+ options.limitPolicy = createLimitPolicy({});
1131
+ }
1132
+ super(options);
1133
+ this.edgeApiHost = (_a = options.edgeApiHost) != null ? _a : "https://uniform.global";
1134
+ this.edgeApiRequestInit = options.disableSWR ? { headers: { "x-disable-swr": "true" } } : void 0;
1135
+ }
1136
+ /** Fetches lists of Canvas compositions, optionally by type */
1137
+ async getCompositionList(params = {}) {
1138
+ const { projectId } = this.options;
1139
+ const { resolveData, filters, ...originParams } = params;
1140
+ const rewrittenFilters = rewriteFilters(filters);
1141
+ if (!resolveData) {
1142
+ const fetchUri = this.createUrl(CANVAS_URL, { ...originParams, projectId, ...rewrittenFilters });
1143
+ return this.apiClient(fetchUri);
1144
+ }
1145
+ const edgeParams = {
1146
+ ...originParams,
1147
+ projectId,
1148
+ diagnostics: typeof params.diagnostics === "boolean" ? params.diagnostics : params.diagnostics === "no-data" ? "no-data" : void 0,
1149
+ ...rewrittenFilters
1150
+ };
1151
+ const edgeUrl = this.createUrl("/api/v1/compositions", edgeParams, this.edgeApiHost);
1152
+ return this.apiClient(edgeUrl, this.edgeApiRequestInit);
1153
+ }
1154
+ getCompositionByNodePath(options) {
1155
+ return this.getOneComposition(options);
1156
+ }
1157
+ getCompositionByNodeId(options) {
1158
+ return this.getOneComposition(options);
1159
+ }
1160
+ getCompositionBySlug(options) {
1161
+ return this.getOneComposition(options);
1162
+ }
1163
+ getCompositionById(options) {
1164
+ return this.getOneComposition(options);
1165
+ }
1166
+ getCompositionDefaults(options) {
1167
+ return this.getOneComposition(options);
1168
+ }
1169
+ /** Fetches historical versions of a composition or pattern */
1170
+ async getCompositionHistory(options) {
1171
+ const historyUrl = this.createUrl("/api/v1/canvas-history", {
1172
+ ...options,
1173
+ projectId: this.options.projectId
1174
+ });
1175
+ return this.apiClient(historyUrl);
1176
+ }
1177
+ getOneComposition({
1178
+ skipDataResolution,
1179
+ diagnostics,
1180
+ ...params
1181
+ }) {
1182
+ const { projectId } = this.options;
1183
+ if (skipDataResolution) {
1184
+ return this.apiClient(this.createUrl(CANVAS_URL, { ...params, projectId }));
1185
+ }
1186
+ const edgeParams = {
1187
+ ...params,
1188
+ projectId,
1189
+ diagnostics: typeof diagnostics === "boolean" ? diagnostics : diagnostics === "no-data" ? "no-data" : void 0
1190
+ };
1191
+ const edgeUrl = this.createUrl("/api/v1/composition", edgeParams, this.edgeApiHost);
1192
+ return this.apiClient(edgeUrl, this.edgeApiRequestInit);
1193
+ }
1194
+ /** Updates or creates a Canvas component definition */
1195
+ async updateComposition(body, options) {
1196
+ const fetchUri = this.createUrl(CANVAS_URL);
1197
+ const headers = {};
1198
+ if (options == null ? void 0 : options.ifUnmodifiedSince) {
1199
+ headers["x-if-unmodified-since"] = options.ifUnmodifiedSince;
1200
+ }
1201
+ const { response } = await this.apiClientWithResponse(fetchUri, {
1202
+ method: "PUT",
1203
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
1204
+ expectNoContent: true,
1205
+ headers
1206
+ });
1207
+ return { modified: response.headers.get("x-modified-at") };
1208
+ }
1209
+ /** Deletes a Canvas component definition */
1210
+ async removeComposition(body) {
1211
+ const fetchUri = this.createUrl(CANVAS_URL);
1212
+ const { projectId } = this.options;
1213
+ await this.apiClient(fetchUri, {
1214
+ method: "DELETE",
1215
+ body: JSON.stringify({ ...body, projectId }),
1216
+ expectNoContent: true
1217
+ });
1218
+ }
1219
+ /** Fetches all Canvas component definitions */
1220
+ async getComponentDefinitions(options) {
1221
+ const { projectId } = this.options;
1222
+ const fetchUri = this.createUrl("/api/v1/canvas-definitions", { ...options, projectId });
1223
+ return this.apiClient(fetchUri);
1224
+ }
1225
+ /** Updates or creates a Canvas component definition */
1226
+ async updateComponentDefinition(body) {
1227
+ const fetchUri = this.createUrl("/api/v1/canvas-definitions");
1228
+ await this.apiClient(fetchUri, {
1229
+ method: "PUT",
1230
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
1231
+ expectNoContent: true
1232
+ });
1233
+ }
1234
+ /** Deletes a Canvas component definition */
1235
+ async removeComponentDefinition(body) {
1236
+ const fetchUri = this.createUrl("/api/v1/canvas-definitions");
1237
+ await this.apiClient(fetchUri, {
1238
+ method: "DELETE",
1239
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
1240
+ expectNoContent: true
1241
+ });
1242
+ }
1243
+ };
1244
+ var _contentTypesUrl;
1245
+ var _entriesUrl;
1246
+ var _ContentClient = class _ContentClient2 extends ApiClient {
1247
+ constructor(options) {
1248
+ var _a;
1249
+ super(options);
1250
+ this.edgeApiHost = (_a = options.edgeApiHost) != null ? _a : "https://uniform.global";
1251
+ }
1252
+ getContentTypes(options) {
1253
+ const { projectId } = this.options;
1254
+ const fetchUri = this.createUrl(__privateGet2(_ContentClient2, _contentTypesUrl), { ...options, projectId });
1255
+ return this.apiClient(fetchUri);
1256
+ }
1257
+ getEntries(options) {
1258
+ const { projectId } = this.options;
1259
+ const { skipDataResolution, filters, ...params } = options;
1260
+ const rewrittenFilters = rewriteFilters(filters);
1261
+ if (skipDataResolution) {
1262
+ const url = this.createUrl(__privateGet2(_ContentClient2, _entriesUrl), { ...params, ...rewrittenFilters, projectId });
1263
+ return this.apiClient(url);
1264
+ }
1265
+ const edgeUrl = this.createUrl(
1266
+ __privateGet2(_ContentClient2, _entriesUrl),
1267
+ { ...this.getEdgeOptions(params), ...rewrittenFilters },
1268
+ this.edgeApiHost
1269
+ );
1270
+ return this.apiClient(
1271
+ edgeUrl,
1272
+ this.options.disableSWR ? { headers: { "x-disable-swr": "true" } } : void 0
1273
+ );
1274
+ }
1275
+ /** Fetches historical versions of an entry */
1276
+ async getEntryHistory(options) {
1277
+ const historyUrl = this.createUrl("/api/v1/entries-history", {
1278
+ ...options,
1279
+ projectId: this.options.projectId
1280
+ });
1281
+ return this.apiClient(historyUrl);
1282
+ }
1283
+ async upsertContentType(body, opts = {}) {
1284
+ const fetchUri = this.createUrl(__privateGet2(_ContentClient2, _contentTypesUrl));
1285
+ if (typeof body.contentType.slugSettings === "object" && body.contentType.slugSettings !== null && Object.keys(body.contentType.slugSettings).length === 0) {
1286
+ delete body.contentType.slugSettings;
1287
+ }
1288
+ await this.apiClient(fetchUri, {
1289
+ method: "PUT",
1290
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
1291
+ expectNoContent: true,
1292
+ headers: opts.autogenerateDataTypes ? { "x-uniform-autogenerate-data-types": "true" } : {}
1293
+ });
1294
+ }
1295
+ async upsertEntry(body, options) {
1296
+ const fetchUri = this.createUrl(__privateGet2(_ContentClient2, _entriesUrl));
1297
+ const headers = {};
1298
+ if (options == null ? void 0 : options.ifUnmodifiedSince) {
1299
+ headers["x-if-unmodified-since"] = options.ifUnmodifiedSince;
1300
+ }
1301
+ const { response } = await this.apiClientWithResponse(fetchUri, {
1302
+ method: "PUT",
1303
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
1304
+ expectNoContent: true,
1305
+ headers
1306
+ });
1307
+ return { modified: response.headers.get("x-modified-at") };
1308
+ }
1309
+ async deleteContentType(body) {
1310
+ const fetchUri = this.createUrl(__privateGet2(_ContentClient2, _contentTypesUrl));
1311
+ await this.apiClient(fetchUri, {
1312
+ method: "DELETE",
1313
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
1314
+ expectNoContent: true
1315
+ });
1316
+ }
1317
+ async deleteEntry(body) {
1318
+ const fetchUri = this.createUrl(__privateGet2(_ContentClient2, _entriesUrl));
1319
+ await this.apiClient(fetchUri, {
1320
+ method: "DELETE",
1321
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
1322
+ expectNoContent: true
1323
+ });
1324
+ }
1325
+ getEdgeOptions(options) {
1326
+ const { projectId } = this.options;
1327
+ const { skipDataResolution, ...params } = options;
1328
+ return {
1329
+ projectId,
1330
+ ...params,
1331
+ diagnostics: typeof options.diagnostics === "boolean" ? options.diagnostics : options.diagnostics === "no-data" ? "no-data" : void 0
1332
+ };
1333
+ }
1334
+ };
1335
+ _contentTypesUrl = /* @__PURE__ */ new WeakMap();
1336
+ _entriesUrl = /* @__PURE__ */ new WeakMap();
1337
+ __privateAdd2(_ContentClient, _contentTypesUrl, "/api/v1/content-types");
1338
+ __privateAdd2(_ContentClient, _entriesUrl, "/api/v1/entries");
1339
+ var _url8;
1340
+ var _DataTypeClient = class _DataTypeClient2 extends ApiClient {
1341
+ constructor(options) {
1342
+ super(options);
1343
+ }
1344
+ /** Fetches all DataTypes for a project */
1345
+ async get(options) {
1346
+ const { projectId } = this.options;
1347
+ const fetchUri = this.createUrl(__privateGet2(_DataTypeClient2, _url8), { ...options, projectId });
1348
+ return await this.apiClient(fetchUri);
1349
+ }
1350
+ /** Updates or creates (based on id) a DataType */
1351
+ async upsert(body) {
1352
+ const fetchUri = this.createUrl(__privateGet2(_DataTypeClient2, _url8));
1353
+ await this.apiClient(fetchUri, {
1354
+ method: "PUT",
1355
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
1356
+ expectNoContent: true
1357
+ });
1358
+ }
1359
+ /** Deletes a DataType */
1360
+ async remove(body) {
1361
+ const fetchUri = this.createUrl(__privateGet2(_DataTypeClient2, _url8));
1362
+ await this.apiClient(fetchUri, {
1363
+ method: "DELETE",
1364
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
1365
+ expectNoContent: true
1366
+ });
1367
+ }
1368
+ };
1369
+ _url8 = /* @__PURE__ */ new WeakMap();
1370
+ __privateAdd2(_DataTypeClient, _url8, "/api/v1/data-types");
1371
+ function getComponentPath(ancestorsAndSelf) {
1372
+ const path = [];
1373
+ for (let i = ancestorsAndSelf.length - 1; i >= 0; i--) {
1374
+ const currentLocation = ancestorsAndSelf[i];
1375
+ const parentLocation = ancestorsAndSelf[i + 1];
1376
+ if ("type" in currentLocation && currentLocation.type !== "slot") {
1377
+ if (currentLocation.type === "block") {
1378
+ const { fieldName, blockIndexFn } = currentLocation;
1379
+ const blockIndex = blockIndexFn();
1380
+ if (fieldName && blockIndex !== void 0) {
1381
+ const noun = parentLocation && "type" in parentLocation && parentLocation.type === "block" ? "fields" : "parameters";
1382
+ path.push(`${noun}.${fieldName}.value[${blockIndex}]`);
1383
+ }
1384
+ } else {
1385
+ }
1386
+ continue;
1387
+ }
1388
+ const parentSlotIndex = currentLocation.parentSlotIndexFn();
1389
+ const { parentSlot } = currentLocation;
1390
+ if (parentSlot && parentSlotIndex !== void 0) {
1391
+ path.push(`${parentSlot}[${parentSlotIndex}]`);
1392
+ }
1393
+ }
1394
+ return `.${path.join(".")}`;
1395
+ }
1396
+ var CANVAS_PERSONALIZE_TYPE = "$personalization";
1397
+ var CANVAS_TEST_TYPE = "$test";
1398
+ var CANVAS_BLOCK_PARAM_TYPE = "$block";
1399
+ var CANVAS_PERSONALIZE_SLOT = "pz";
1400
+ var CANVAS_TEST_SLOT = "test";
1401
+ var CANVAS_DRAFT_STATE = 0;
1402
+ var CANVAS_PUBLISHED_STATE = 64;
1403
+ var CANVAS_EDITOR_STATE = 63;
1404
+ var CANVAS_PERSONALIZATION_PARAM = "$pzCrit";
1405
+ var CANVAS_TEST_VARIANT_PARAM = "$tstVrnt";
1406
+ var CANVAS_ENRICHMENT_TAG_PARAM = "$enr";
1407
+ var CANVAS_CONTEXTUAL_EDITING_PARAM = "$contextualEditing";
1408
+ var IN_CONTEXT_EDITOR_QUERY_STRING_PARAM = "is_incontext_editing_mode";
1409
+ var PLACEHOLDER_ID = "placeholder";
1410
+ var EDGE_MAX_CACHE_TTL = 24 * 60 * 60;
1411
+ function isRootEntryReference(root) {
1412
+ return root.type === "root" && isEntryData(root.node);
1413
+ }
1414
+ function isEntryData(entryData) {
1415
+ return Boolean(entryData && typeof entryData === "object" && "fields" in entryData);
1416
+ }
1417
+ function getPropertiesValue(entity) {
1418
+ return "parameters" in entity && entity.parameters ? entity.parameters : "fields" in entity && entity.fields ? entity.fields : void 0;
1419
+ }
1420
+ var escapeCharacter = "\\";
1421
+ var variablePrefix = "${";
1422
+ var variableSuffix = "}";
1423
+ function parseVariableExpression(serialized, onToken) {
1424
+ if (typeof serialized !== "string") {
1425
+ throw new TypeError("Variable expression must be a string");
1426
+ }
1427
+ let bufferStartIndex = 0;
1428
+ let bufferEndIndex = 0;
1429
+ let tokenCount = 0;
1430
+ const handleToken = (token, type) => {
1431
+ tokenCount++;
1432
+ return onToken == null ? void 0 : onToken(token, type);
1433
+ };
1434
+ let state = "text";
1435
+ for (let index = 0; index < serialized.length; index++) {
1436
+ const char = serialized[index];
1437
+ if (bufferStartIndex > bufferEndIndex) {
1438
+ bufferEndIndex = bufferStartIndex;
1439
+ }
1440
+ if (char === variablePrefix[0] && serialized[index + 1] === variablePrefix[1]) {
1441
+ if (serialized[index - 1] === escapeCharacter) {
1442
+ bufferEndIndex -= escapeCharacter.length;
1443
+ if (handleToken(serialized.substring(bufferStartIndex, bufferEndIndex), "text") === false) {
1444
+ return tokenCount;
1445
+ }
1446
+ bufferStartIndex = index;
1447
+ bufferEndIndex = index + 1;
1448
+ continue;
1449
+ }
1450
+ state = "variable";
1451
+ if (bufferEndIndex > bufferStartIndex) {
1452
+ if (handleToken(serialized.substring(bufferStartIndex, bufferEndIndex), "text") === false) {
1453
+ return tokenCount;
1454
+ }
1455
+ bufferStartIndex = bufferEndIndex;
1456
+ }
1457
+ index += variablePrefix.length - 1;
1458
+ bufferStartIndex += variablePrefix.length;
1459
+ continue;
1460
+ }
1461
+ if (char === variableSuffix && state === "variable") {
1462
+ if (serialized[index - 1] === escapeCharacter) {
1463
+ bufferEndIndex++;
1464
+ continue;
1465
+ }
1466
+ state = "text";
1467
+ if (bufferEndIndex > bufferStartIndex) {
1468
+ const unescapedVariableName = serialized.substring(bufferStartIndex, bufferEndIndex).replace(/\\([${}])/g, "$1");
1469
+ if (handleToken(unescapedVariableName, "variable") === false) {
1470
+ return tokenCount;
1471
+ }
1472
+ bufferStartIndex = bufferEndIndex + variableSuffix.length;
1473
+ }
1474
+ continue;
1475
+ }
1476
+ bufferEndIndex++;
1477
+ }
1478
+ if (bufferEndIndex > bufferStartIndex) {
1479
+ if (state === "variable") {
1480
+ state = "text";
1481
+ bufferStartIndex -= variablePrefix.length;
1482
+ }
1483
+ handleToken(serialized.substring(bufferStartIndex), state);
1484
+ }
1485
+ return tokenCount;
1486
+ }
1487
+ function hasReferencedVariables(value) {
1488
+ if (value === void 0) {
1489
+ return 0;
1490
+ }
1491
+ let variableTokenCount = 0;
1492
+ parseVariableExpression(value, (_, tokenType) => {
1493
+ if (tokenType === "variable") {
1494
+ variableTokenCount++;
1495
+ }
1496
+ });
1497
+ return variableTokenCount;
1498
+ }
1499
+ function walkNodeTree(node, visitor, options) {
1500
+ var _a, _b;
1501
+ const componentQueue = [
1502
+ {
1503
+ ancestorsAndSelf: Array.isArray(node) ? node : [{ node, type: "root" }],
1504
+ context: options == null ? void 0 : options.initialContext
1505
+ }
1506
+ ];
1507
+ const childContexts = /* @__PURE__ */ new Map();
1508
+ do {
1509
+ const currentQueueEntry = componentQueue.pop();
1510
+ if (!currentQueueEntry) continue;
1511
+ const currentComponent = currentQueueEntry.ancestorsAndSelf[0];
1512
+ let visitDescendants = true;
1513
+ let descendantContext = (_a = childContexts.get(currentComponent.node)) != null ? _a : currentQueueEntry.context;
1514
+ let visitorInfo;
1515
+ if (currentComponent.type === "root" && isRootEntryReference(currentComponent) || currentComponent.type === "block") {
1516
+ visitorInfo = {
1517
+ type: "entry",
1518
+ node: currentComponent.node,
1519
+ ancestorsAndSelf: currentQueueEntry.ancestorsAndSelf,
1520
+ actions: {
1521
+ replace: (replacementNode) => {
1522
+ Object.assign(currentComponent.node, replacementNode);
1523
+ const propertiesToCheck = ["fields", "_dataResources", "_author"];
1524
+ propertiesToCheck.forEach((property) => {
1525
+ if (!replacementNode[property]) {
1526
+ delete currentComponent.node[property];
1527
+ }
1528
+ });
1529
+ },
1530
+ remove: () => {
1531
+ const currentComponentLocation = currentQueueEntry.ancestorsAndSelf[0];
1532
+ const parentComponent = currentQueueEntry.ancestorsAndSelf[1];
1533
+ if (currentComponentLocation.type === "block") {
1534
+ const { fieldName, blockIndexFn } = currentComponentLocation;
1535
+ const blockIndex = blockIndexFn();
1536
+ const blockValue = getBlockValue(parentComponent.node, fieldName);
1537
+ blockValue.splice(blockIndex, 1);
1538
+ if (blockValue.length === 0) {
1539
+ const properties2 = getPropertiesValue(parentComponent.node);
1540
+ delete properties2[fieldName];
1541
+ }
1542
+ } else {
1543
+ throw new Error("Unknown node type");
1544
+ }
1545
+ visitDescendants = false;
1546
+ },
1547
+ insertAfter: (nodes) => {
1548
+ const currentNodeInfo = currentQueueEntry.ancestorsAndSelf[0];
1549
+ if (currentNodeInfo.type !== "block") {
1550
+ throw new Error("Unknown type");
1551
+ }
1552
+ const { fieldName, blockIndexFn } = currentNodeInfo;
1553
+ const blockIndex = blockIndexFn();
1554
+ const parentComponent = currentQueueEntry.ancestorsAndSelf[1];
1555
+ const nodesToInsert = Array.isArray(nodes) ? nodes : [nodes];
1556
+ if (fieldName && typeof blockIndex !== "undefined") {
1557
+ getPropertiesValue(parentComponent.node)[fieldName].value.splice(
1558
+ blockIndex + 1,
1559
+ 0,
1560
+ ...nodesToInsert
1561
+ );
1562
+ componentQueue.unshift(
1563
+ ...nodesToInsert.map((enqueueingComponent) => {
1564
+ const blockIndexFn2 = () => {
1565
+ const parentArray = getPropertiesValue(parentComponent.node)[fieldName].value;
1566
+ return parentArray.findIndex((x) => x === enqueueingComponent);
1567
+ };
1568
+ return {
1569
+ ancestorsAndSelf: [
1570
+ {
1571
+ type: "block",
1572
+ node: enqueueingComponent,
1573
+ fieldName,
1574
+ blockIndexFn: blockIndexFn2
1575
+ },
1576
+ // slice removes 'self' since we are inserting a peer of self
1577
+ ...currentQueueEntry.ancestorsAndSelf.slice(1)
1578
+ ],
1579
+ context: descendantContext
1580
+ };
1581
+ })
1582
+ );
1583
+ }
1584
+ },
1585
+ stopProcessingDescendants() {
1586
+ visitDescendants = false;
1587
+ },
1588
+ setDescendantsContext(context) {
1589
+ descendantContext = context;
1590
+ },
1591
+ setChildContext(child, context) {
1592
+ childContexts.set(child, context);
1593
+ }
1594
+ },
1595
+ context: descendantContext
1596
+ };
1597
+ } else {
1598
+ visitorInfo = {
1599
+ type: "component",
1600
+ node: currentComponent.node,
1601
+ ancestorsAndSelf: currentQueueEntry.ancestorsAndSelf,
1602
+ actions: {
1603
+ replace: (replacementComponent) => {
1604
+ Object.assign(currentComponent.node, replacementComponent);
1605
+ const propertiesToCheck = [
1606
+ "parameters",
1607
+ "variant",
1608
+ "slots",
1609
+ "data",
1610
+ "_pattern",
1611
+ "_patternError",
1612
+ "_dataResources",
1613
+ "_overridability",
1614
+ "_overrides",
1615
+ "_patternDataResources"
1616
+ ];
1617
+ propertiesToCheck.forEach((property) => {
1618
+ if (!replacementComponent[property]) {
1619
+ delete currentComponent.node[property];
1620
+ }
1621
+ });
1622
+ },
1623
+ remove: () => {
1624
+ const currentComponentLocation = currentQueueEntry.ancestorsAndSelf[0];
1625
+ const parentComponent = currentQueueEntry.ancestorsAndSelf[1];
1626
+ if (currentComponentLocation.type === "root") {
1627
+ throw new Error("Unable to delete root node.");
1628
+ }
1629
+ if (currentComponentLocation.type === "slot") {
1630
+ const { parentSlot, parentSlotIndexFn } = currentComponentLocation;
1631
+ const parentSlotIndex = parentSlotIndexFn();
1632
+ parentComponent.node.slots[parentSlot].splice(parentSlotIndex, 1);
1633
+ } else {
1634
+ throw new Error("Unknown node type");
1635
+ }
1636
+ visitDescendants = false;
1637
+ },
1638
+ insertAfter: (nodes) => {
1639
+ const nodesToInsert = Array.isArray(nodes) ? nodes : [nodes];
1640
+ const currentNodeInfo = currentQueueEntry.ancestorsAndSelf[0];
1641
+ if (currentNodeInfo.type === "root") {
1642
+ throw new Error("Unable to insert after root node.");
1643
+ }
1644
+ if (currentNodeInfo.type === "slot") {
1645
+ const { parentSlot, parentSlotIndexFn } = currentNodeInfo;
1646
+ const parentSlotIndex = parentSlotIndexFn();
1647
+ const parentComponent = currentQueueEntry.ancestorsAndSelf[1];
1648
+ if (parentSlot && typeof parentSlotIndex !== "undefined") {
1649
+ parentComponent.node.slots[parentSlot].splice(
1650
+ parentSlotIndex + 1,
1651
+ 0,
1652
+ ...nodesToInsert
1653
+ );
1654
+ componentQueue.unshift(
1655
+ ...nodesToInsert.map((enqueueingComponent) => {
1656
+ const parentSlotIndexFn2 = () => {
1657
+ return parentComponent.node.slots[parentSlot].findIndex(
1658
+ (x) => x === enqueueingComponent
1659
+ );
1660
+ };
1661
+ return {
1662
+ type: "slot",
1663
+ ancestorsAndSelf: [
1664
+ {
1665
+ type: "slot",
1666
+ node: enqueueingComponent,
1667
+ parentSlot,
1668
+ parentSlotIndexFn: parentSlotIndexFn2
1669
+ },
1670
+ // slice removes 'self' since we are inserting a peer of self
1671
+ ...currentQueueEntry.ancestorsAndSelf.slice(1)
1672
+ ],
1673
+ context: descendantContext
1674
+ };
1675
+ })
1676
+ );
1677
+ }
1678
+ } else {
1679
+ throw new Error("Unknown type");
1680
+ }
1681
+ },
1682
+ stopProcessingDescendants() {
1683
+ visitDescendants = false;
1684
+ },
1685
+ setDescendantsContext(context) {
1686
+ descendantContext = context;
1687
+ },
1688
+ setChildContext(child, context) {
1689
+ childContexts.set(child, context);
1690
+ }
1691
+ },
1692
+ context: descendantContext
1693
+ };
1694
+ }
1695
+ visitor(visitorInfo);
1696
+ if (!visitDescendants) {
1697
+ continue;
1698
+ }
1699
+ const slots = "slots" in currentComponent.node && currentComponent.node.slots;
1700
+ if (slots) {
1701
+ const slotKeys = Object.keys(slots);
1702
+ for (let slotIndex = slotKeys.length - 1; slotIndex >= 0; slotIndex--) {
1703
+ const slotKey = slotKeys[slotIndex];
1704
+ const components = slots[slotKey];
1705
+ for (let componentIndex = components.length - 1; componentIndex >= 0; componentIndex--) {
1706
+ const enqueueingComponent = components[componentIndex];
1707
+ const parentSlotIndexFn = () => {
1708
+ const result = currentComponent.node.slots[slotKey].findIndex(
1709
+ (x) => x === enqueueingComponent
1710
+ );
1711
+ return result;
1712
+ };
1713
+ componentQueue.push({
1714
+ ancestorsAndSelf: [
1715
+ {
1716
+ type: "slot",
1717
+ node: enqueueingComponent,
1718
+ parentSlot: slotKey,
1719
+ parentSlotIndexFn
1720
+ },
1721
+ ...currentQueueEntry.ancestorsAndSelf
1722
+ ],
1723
+ context: descendantContext
1724
+ });
1725
+ }
1726
+ }
1727
+ }
1728
+ const properties = getPropertiesValue(currentComponent.node);
1729
+ if (properties) {
1730
+ const propertyEntries = Object.entries(properties);
1731
+ for (let propIndex = propertyEntries.length - 1; propIndex >= 0; propIndex--) {
1732
+ const [propKey, propObject] = propertyEntries[propIndex];
1733
+ if (!isNestedNodeType(propObject.type)) {
1734
+ continue;
1735
+ }
1736
+ if (typeof propObject.value === "string" && hasReferencedVariables(propObject.value) > 0) {
1737
+ continue;
1738
+ }
1739
+ if (!Array.isArray(propObject.value)) {
1740
+ const error = new BlockFormatError(
1741
+ `${getComponentPath(currentQueueEntry.ancestorsAndSelf)}`,
1742
+ propKey,
1743
+ propObject.value
1744
+ );
1745
+ if (options == null ? void 0 : options.throwForInvalidBlockValues) {
1746
+ throw error;
1747
+ } else {
1748
+ console.warn(`Skipped invalid block value: ${error.message}}`);
1749
+ continue;
1750
+ }
1751
+ }
1752
+ const blocks = (_b = propObject.value) != null ? _b : [];
1753
+ for (let blockIndex = blocks.length - 1; blockIndex >= 0; blockIndex--) {
1754
+ const enqueueingBlock = blocks[blockIndex];
1755
+ const blockIndexFn = () => {
1756
+ return getBlockValue(currentComponent.node, propKey).findIndex((x) => x === enqueueingBlock);
1757
+ };
1758
+ componentQueue.push({
1759
+ ancestorsAndSelf: [
1760
+ {
1761
+ type: "block",
1762
+ node: enqueueingBlock,
1763
+ fieldName: propKey,
1764
+ blockIndexFn
1765
+ },
1766
+ ...currentQueueEntry.ancestorsAndSelf
1767
+ ],
1768
+ context: descendantContext
1769
+ });
1770
+ }
1771
+ }
1772
+ }
1773
+ } while (componentQueue.length > 0);
1774
+ }
1775
+ function isNestedNodeType(type) {
1776
+ return type === CANVAS_BLOCK_PARAM_TYPE;
1777
+ }
1778
+ function getBlockValue(component, parameterName) {
1779
+ var _a;
1780
+ const parameter = (_a = getPropertiesValue(component)) == null ? void 0 : _a[parameterName];
1781
+ if ((parameter == null ? void 0 : parameter.value) && parameter.type === CANVAS_BLOCK_PARAM_TYPE && Array.isArray(parameter.value)) {
1782
+ return parameter.value;
1783
+ }
1784
+ return [];
1785
+ }
1786
+ var BlockFormatError = class _BlockFormatError extends Error {
1787
+ constructor(componentPath, propertyId, blockValue) {
1788
+ super(
1789
+ `${componentPath} has an invalid block property value on ${propertyId}. Block values must be arrays of blocks (BlockValue type), but received ${blockValue === null ? "null" : typeof blockValue}`
1790
+ );
1791
+ this.componentPath = componentPath;
1792
+ this.propertyId = propertyId;
1793
+ this.blockValue = blockValue;
1794
+ Object.setPrototypeOf(this, _BlockFormatError.prototype);
1795
+ }
1796
+ };
1797
+ function createVariableReference(variableName) {
1798
+ return `\${${variableName.replace(/([${}])/g, "\\$1")}}`;
1799
+ }
1800
+ var CANVAS_VIZ_CONTROL_PARAM = "$viz";
1801
+ var _baseUrl;
1802
+ var _IntegrationPropertyEditorsClient = class _IntegrationPropertyEditorsClient2 extends ApiClient {
1803
+ constructor(options) {
1804
+ super(options);
1805
+ this.teamId = options.teamId;
1806
+ }
1807
+ /**
1808
+ * Gets a list of property type and hook names for the current team, including public integrations' hooks.
1809
+ */
1810
+ get(options) {
1811
+ const fetchUri = this.createUrl(__privateGet2(_IntegrationPropertyEditorsClient2, _baseUrl), {
1812
+ ...options,
1813
+ teamId: this.teamId
1814
+ });
1815
+ return this.apiClient(fetchUri);
1816
+ }
1817
+ /**
1818
+ * Creates or updates a custom AI property editor on a Mesh app.
1819
+ */
1820
+ async deploy(body) {
1821
+ const fetchUri = this.createUrl(__privateGet2(_IntegrationPropertyEditorsClient2, _baseUrl));
1822
+ await this.apiClient(fetchUri, {
1823
+ method: "PUT",
1824
+ body: JSON.stringify({ ...body, teamId: this.teamId }),
1825
+ expectNoContent: true
1826
+ });
1827
+ }
1828
+ /**
1829
+ * Removes a custom AI property editor from a Mesh app.
1830
+ */
1831
+ async delete(body) {
1832
+ const fetchUri = this.createUrl(__privateGet2(_IntegrationPropertyEditorsClient2, _baseUrl));
1833
+ await this.apiClient(fetchUri, {
1834
+ method: "DELETE",
1835
+ body: JSON.stringify({ ...body, teamId: this.teamId }),
1836
+ expectNoContent: true
1837
+ });
1838
+ }
1839
+ };
1840
+ _baseUrl = /* @__PURE__ */ new WeakMap();
1841
+ __privateAdd2(_IntegrationPropertyEditorsClient, _baseUrl, "/api/v1/integration-property-editors");
1842
+ var _url22;
1843
+ var _ProjectClient = class _ProjectClient2 extends ApiClient {
1844
+ constructor(options) {
1845
+ super({ ...options, bypassCache: true });
1846
+ }
1847
+ /** Fetches single Project */
1848
+ async get(options) {
1849
+ const fetchUri = this.createUrl(__privateGet2(_ProjectClient2, _url22), { ...options });
1850
+ return await this.apiClient(fetchUri);
1851
+ }
1852
+ /** Updates or creates (based on id) a Project */
1853
+ async upsert(body) {
1854
+ const fetchUri = this.createUrl(__privateGet2(_ProjectClient2, _url22));
1855
+ return await this.apiClient(fetchUri, {
1856
+ method: "PUT",
1857
+ body: JSON.stringify({ ...body })
1858
+ });
1859
+ }
1860
+ /** Deletes a Project */
1861
+ async delete(body) {
1862
+ const fetchUri = this.createUrl(__privateGet2(_ProjectClient2, _url22));
1863
+ await this.apiClient(fetchUri, {
1864
+ method: "DELETE",
1865
+ body: JSON.stringify({ ...body }),
1866
+ expectNoContent: true
1867
+ });
1868
+ }
1869
+ };
1870
+ _url22 = /* @__PURE__ */ new WeakMap();
1871
+ __privateAdd2(_ProjectClient, _url22, "/api/v1/project");
1872
+ var ROUTE_URL = "/api/v1/route";
1873
+ var RouteClient = class extends ApiClient {
1874
+ constructor(options) {
1875
+ var _a;
1876
+ if (!options.limitPolicy) {
1877
+ options.limitPolicy = createLimitPolicy({});
1878
+ }
1879
+ super(options);
1880
+ this.edgeApiHost = (_a = options.edgeApiHost) != null ? _a : "https://uniform.global";
1881
+ }
1882
+ /** Fetches lists of Canvas compositions, optionally by type */
1883
+ async getRoute(options) {
1884
+ const { projectId } = this.options;
1885
+ const fetchUri = this.createUrl(ROUTE_URL, { ...options, projectId }, this.edgeApiHost);
1886
+ return await this.apiClient(
1887
+ fetchUri,
1888
+ this.options.disableSWR ? { headers: { "x-disable-swr": "true" } } : void 0
1889
+ );
1890
+ }
1891
+ };
1892
+ function mapSlotToPersonalizedVariations(slot) {
1893
+ if (!slot) return [];
1894
+ return slot.map((v, i) => {
1895
+ var _a, _b;
1896
+ const contextTag = (_b = (_a = v.parameters) == null ? void 0 : _a[CANVAS_PERSONALIZATION_PARAM]) == null ? void 0 : _b.value;
1897
+ const id = (contextTag == null ? void 0 : contextTag.name) || `pz-${i}-${v.type}`;
1898
+ return {
1899
+ ...v,
1900
+ id,
1901
+ pz: contextTag
1902
+ };
1903
+ });
1904
+ }
1905
+ function mapSlotToTestVariations(slot) {
1906
+ if (!slot) return [];
1907
+ return slot.map((v, i) => {
1908
+ var _a, _b, _c;
1909
+ const contextTag = (_b = (_a = v.parameters) == null ? void 0 : _a[CANVAS_TEST_VARIANT_PARAM]) == null ? void 0 : _b.value;
1910
+ const id = (_c = contextTag == null ? void 0 : contextTag.id) != null ? _c : "testId" in v ? v.testId : `ab-${i}-${v.type}`;
1911
+ return {
1912
+ ...v,
1913
+ id,
1914
+ testDistribution: contextTag == null ? void 0 : contextTag.testDistribution,
1915
+ control: contextTag == null ? void 0 : contextTag.control
1916
+ };
1917
+ });
1918
+ }
1919
+ var isComponentPlaceholderId = (id) => {
1920
+ if (id === PLACEHOLDER_ID) {
1921
+ return true;
1922
+ }
1923
+ if (typeof id !== "string") {
1924
+ return false;
1925
+ }
1926
+ return id == null ? void 0 : id.startsWith(PLACEHOLDER_ID);
1927
+ };
1928
+
1929
+ // src/utils/env.ts
1930
+ var env = {
1931
+ getProjectId: () => {
1932
+ return process.env.UNIFORM_PROJECT_ID;
1933
+ },
1934
+ getApiKey: () => {
1935
+ return process.env.UNIFORM_API_KEY;
1936
+ },
1937
+ getApiHost: () => {
1938
+ return process.env.UNIFORM_API_HOST || process.env.UNIFORM_CLI_BASE_URL;
1939
+ },
1940
+ getEdgeApiHost: () => {
1941
+ return process.env.UNIFORM_EDGE_API_HOST || process.env.UNIFORM_CLI_BASE_EDGE_URL;
1942
+ }
1943
+ };
1944
+
1945
+ // src/utils/tag.ts
1946
+ var buildPathTag = (path) => {
1947
+ const actualPath = path.startsWith("/") ? path : `/${path}`;
1948
+ return `path:${actualPath}`.toLowerCase();
1949
+ };
1950
+ var buildCompositionTag = (compositionId) => {
1951
+ return `composition:${compositionId}`.toLowerCase();
1952
+ };
1953
+
1954
+ // src/config/helpers.ts
1955
+ import serverConfig from "uniform.server.config";
1956
+ var getServerConfig = () => {
1957
+ return serverConfig;
1958
+ };
1959
+
1960
+ // src/utils/draft.ts
1961
+ var isDraftModeEnabled = ({
1962
+ draftModeEnabled
1963
+ }) => {
1964
+ return draftModeEnabled;
1965
+ };
1966
+ var isIncontextEditingEnabled = ({ searchParams }) => {
1967
+ const containsKey = searchParams.has(IN_CONTEXT_EDITOR_QUERY_STRING_PARAM);
1968
+ return containsKey;
1969
+ };
1970
+ var isDevelopmentEnvironment = () => {
1971
+ return process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test";
1972
+ };
1973
+
1974
+ // src/clients/cache.ts
1975
+ var isSpecificCacheMode = (options) => {
1976
+ return "cache" in options;
1977
+ };
1978
+ var isStateCacheMode = (options) => {
1979
+ return "state" in options;
1980
+ };
1981
+ var isDetectCacheMode = (options) => {
1982
+ return "searchParams" in options && "draftModeEnabled" in options;
1983
+ };
1984
+ var resolveManifestCache = (options) => {
1985
+ return resolveCache({
1986
+ options,
1987
+ defaultCache: getServerConfig().manifestCache
1988
+ });
1989
+ };
1990
+ var resolveCanvasCache = (options) => {
1991
+ return resolveCache({
1992
+ options,
1993
+ defaultCache: getServerConfig().canvasCache
1994
+ });
1995
+ };
1996
+ var resolveProjectMapCache = (options) => {
1997
+ return resolveCache({
1998
+ options,
1999
+ defaultCache: getServerConfig().projectMapCache
2000
+ });
2001
+ };
2002
+ var resolveCache = ({
2003
+ options,
2004
+ defaultCache
2005
+ }) => {
2006
+ let cache2 = defaultCache;
2007
+ if (options) {
2008
+ if (isSpecificCacheMode(options)) {
2009
+ cache2 = options.cache;
2010
+ } else if (isStateCacheMode(options)) {
2011
+ if (options.state === CANVAS_DRAFT_STATE || options.state === CANVAS_EDITOR_STATE) {
2012
+ cache2 = {
2013
+ type: "no-cache",
2014
+ bypassCache: true
2015
+ };
2016
+ }
2017
+ } else if (isDetectCacheMode(options)) {
2018
+ const { disabled } = shouldCacheBeDisabled(options);
2019
+ if (disabled) {
2020
+ cache2 = {
2021
+ type: "no-cache",
2022
+ bypassCache: true
2023
+ };
2024
+ }
2025
+ }
2026
+ }
2027
+ return cache2 || {
2028
+ type: "force-cache"
2029
+ };
2030
+ };
2031
+ var shouldCacheBeDisabled = (options) => {
2032
+ if (isDraftModeEnabled(options)) {
2033
+ return { disabled: true, reason: "DRAFT" };
2034
+ }
2035
+ if (isIncontextEditingEnabled(options)) {
2036
+ return { disabled: true, reason: "INCONTEXT" };
2037
+ }
2038
+ if (isDevelopmentEnvironment()) {
2039
+ return { disabled: true, reason: "DEV" };
2040
+ }
2041
+ return {
2042
+ disabled: false,
2043
+ reason: void 0
2044
+ };
2045
+ };
2046
+ var determineFetchCacheOptions = (mode) => {
2047
+ let cache2 = void 0;
2048
+ let revalidate = void 0;
2049
+ if (mode.type === "revalidate") {
2050
+ cache2 = void 0;
2051
+ revalidate = mode.interval;
2052
+ } else {
2053
+ cache2 = mode.type;
2054
+ }
2055
+ return {
2056
+ cache: cache2,
2057
+ revalidate
2058
+ };
2059
+ };
2060
+
2061
+ // src/clients/retry.ts
2062
+ function createThrottler(limit, interval) {
2063
+ let available = limit;
2064
+ let refillScheduled = false;
2065
+ const waiting = [];
2066
+ function scheduleRefill() {
2067
+ if (refillScheduled) return;
2068
+ refillScheduled = true;
2069
+ setTimeout(() => {
2070
+ refillScheduled = false;
2071
+ available = limit;
2072
+ while (available > 0 && waiting.length > 0) {
2073
+ available--;
2074
+ const next = waiting.shift();
2075
+ next();
2076
+ }
2077
+ if (waiting.length > 0) {
2078
+ scheduleRefill();
2079
+ }
2080
+ }, interval);
2081
+ }
2082
+ return async function throttle(fn) {
2083
+ if (available > 0) {
2084
+ available--;
2085
+ if (!refillScheduled) {
2086
+ scheduleRefill();
2087
+ }
2088
+ return fn();
2089
+ }
2090
+ return new Promise((resolve, reject) => {
2091
+ waiting.push(() => {
2092
+ fn().then(resolve, reject);
2093
+ });
2094
+ scheduleRefill();
2095
+ });
2096
+ };
2097
+ }
2098
+ function createLimiter(concurrency) {
2099
+ let active = 0;
2100
+ const queue = [];
2101
+ return async function limit(fn) {
2102
+ return new Promise((resolve, reject) => {
2103
+ const run = async () => {
2104
+ active++;
2105
+ try {
2106
+ const result = await fn();
2107
+ resolve(result);
2108
+ } catch (error) {
2109
+ reject(error);
2110
+ } finally {
2111
+ active--;
2112
+ if (queue.length > 0) {
2113
+ const next = queue.shift();
2114
+ next();
2115
+ }
2116
+ }
2117
+ };
2118
+ if (active < concurrency) {
2119
+ run();
2120
+ } else {
2121
+ queue.push(run);
2122
+ }
2123
+ });
2124
+ };
2125
+ }
2126
+ async function retry(fn, options) {
2127
+ let lastError;
2128
+ let delay = 1e3;
2129
+ for (let attempt = 1; attempt <= options.retries + 1; attempt++) {
2130
+ try {
2131
+ return await fn();
2132
+ } catch (error) {
2133
+ lastError = error;
2134
+ const attemptError = Object.assign(error, { attemptNumber: attempt });
2135
+ if (options.onFailedAttempt) {
2136
+ await options.onFailedAttempt(attemptError);
2137
+ }
2138
+ if (attempt > options.retries) {
2139
+ throw error;
2140
+ }
2141
+ await new Promise((resolve) => setTimeout(resolve, delay));
2142
+ delay *= options.factor;
2143
+ }
2144
+ }
2145
+ throw lastError;
2146
+ }
2147
+ function createLimitPolicy2({
2148
+ throttle = { interval: 1e3, limit: 10 },
2149
+ retry: retryOptions = { retries: 1, factor: 1.66 },
2150
+ limit = 10
2151
+ }) {
2152
+ const throttler = throttle ? createThrottler(throttle.limit, throttle.interval) : null;
2153
+ const limiter = limit ? createLimiter(limit) : null;
2154
+ return function limitPolicy(func) {
2155
+ let currentFunc = async () => await func();
2156
+ if (throttler) {
2157
+ const throttleFunc = currentFunc;
2158
+ currentFunc = () => throttler(throttleFunc);
2159
+ }
2160
+ if (limiter) {
2161
+ const limitFunc = currentFunc;
2162
+ currentFunc = () => limiter(limitFunc);
2163
+ }
2164
+ if (retryOptions) {
2165
+ const retryFunc = currentFunc;
2166
+ currentFunc = () => retry(retryFunc, {
2167
+ ...retryOptions,
2168
+ onFailedAttempt: async (error) => {
2169
+ if (retryOptions.onFailedAttempt) {
2170
+ await retryOptions.onFailedAttempt(error);
2171
+ }
2172
+ if (error instanceof ApiClientError && typeof error.statusCode === "number" && error.statusCode >= 400 && error.statusCode < 500 && error.statusCode !== 429 && error.statusCode !== 408) {
2173
+ throw error;
2174
+ }
2175
+ }
2176
+ });
2177
+ }
2178
+ return currentFunc();
2179
+ };
2180
+ }
2181
+
2182
+ // src/clients/canvas.ts
2183
+ var getCanvasClient = (options) => {
2184
+ const cache2 = resolveCanvasCache(options);
2185
+ return new CanvasClient({
2186
+ projectId: env.getProjectId(),
2187
+ apiHost: env.getApiHost(),
2188
+ apiKey: env.getApiKey(),
2189
+ edgeApiHost: env.getEdgeApiHost(),
2190
+ disableSWR: typeof cache2.disableSWR !== "undefined" ? cache2.disableSWR : true,
2191
+ limitPolicy: createLimitPolicy2({
2192
+ limit: 6
2193
+ }),
2194
+ fetch: (req, init) => {
2195
+ let requestedUrl;
2196
+ if (typeof req === "string") {
2197
+ requestedUrl = new URL(req);
2198
+ } else if (req instanceof URL) {
2199
+ requestedUrl = req;
2200
+ } else {
2201
+ requestedUrl = new URL(req.url);
2202
+ }
2203
+ const tags = [];
2204
+ if (requestedUrl) {
2205
+ const compositionIdKey = "compositionId";
2206
+ const compositionIdsKey = "compositionIDs";
2207
+ const compositionId = requestedUrl.searchParams.get(compositionIdKey);
2208
+ const compositionIds = requestedUrl.searchParams.get(compositionIdsKey);
2209
+ if (compositionId) {
2210
+ tags.push(buildCompositionTag(compositionId));
2211
+ }
2212
+ if (compositionIds) {
2213
+ const ids = compositionIds.split(",");
2214
+ for (let i = 0; i < ids.length; i++) {
2215
+ tags.push(buildCompositionTag(ids[i]));
2216
+ }
2217
+ }
2218
+ }
2219
+ const { cache: fetchCache, revalidate } = determineFetchCacheOptions(cache2);
2220
+ return fetch(req, {
2221
+ ...init,
2222
+ cache: fetchCache,
2223
+ headers: {
2224
+ ...init == null ? void 0 : init.headers,
2225
+ "x-bypass-cache": typeof cache2.bypassCache !== "undefined" ? cache2.bypassCache.toString() : "false"
2226
+ },
2227
+ next: {
2228
+ revalidate,
2229
+ tags: tags.length ? tags : void 0
2230
+ }
2231
+ });
2232
+ }
2233
+ });
2234
+ };
2235
+
2236
+ // src/clients/manifest.ts
2237
+ import "server-only";
2238
+
2239
+ // src/clients/tags.ts
2240
+ var generateRouteCacheTags = ({ path, old }) => {
2241
+ const tags = old ? ["route-old"] : ["route"];
2242
+ if (path) {
2243
+ const pathWithoutQuery = path.split("?")[0];
2244
+ const pieces = pathWithoutQuery.split("/");
2245
+ for (let i = 0; i < pieces.length; i++) {
2246
+ const segmentPieces = pieces.slice(0, i + 1);
2247
+ const segment = segmentPieces.join("/");
2248
+ tags.push(buildPathTag(segment));
2249
+ }
2250
+ }
2251
+ return tags;
2252
+ };
2253
+ var generateManifestCacheTags = () => {
2254
+ return ["manifest"];
2255
+ };
2256
+
2257
+ // src/clients/manifest.ts
2258
+ var getManifestClient = (options) => {
2259
+ const cache2 = resolveManifestCache(options);
2260
+ const manifestClient = new ManifestClient({
2261
+ apiHost: env.getApiHost(),
2262
+ apiKey: env.getApiKey(),
2263
+ projectId: env.getProjectId(),
2264
+ limitPolicy: createLimitPolicy2({
2265
+ limit: 6
2266
+ }),
2267
+ fetch: (req, init) => {
2268
+ const { cache: fetchCache, revalidate } = determineFetchCacheOptions(cache2);
2269
+ return fetch(req, {
2270
+ ...init,
2271
+ headers: {
2272
+ ...init == null ? void 0 : init.headers,
2273
+ "x-bypass-cache": typeof cache2.bypassCache !== "undefined" ? cache2.bypassCache.toString() : "false"
2274
+ },
2275
+ cache: fetchCache,
2276
+ next: {
2277
+ revalidate,
2278
+ tags: generateManifestCacheTags()
2279
+ }
2280
+ });
2281
+ }
2282
+ });
2283
+ return manifestClient;
2284
+ };
2285
+ var getManifest = async (options) => {
2286
+ let preview = false;
2287
+ if (options && isStateCacheMode(options)) {
2288
+ preview = options.state === CANVAS_DRAFT_STATE || options.state === CANVAS_EDITOR_STATE;
2289
+ }
2290
+ const manifestClient = getManifestClient(options);
2291
+ return manifestClient.get({
2292
+ preview
2293
+ });
2294
+ };
2295
+
2296
+ // src/clients/projectMap.ts
2297
+ import "server-only";
2298
+
2299
+ // ../project-map/dist/index.mjs
2300
+ var __typeError3 = (msg) => {
2301
+ throw TypeError(msg);
2302
+ };
2303
+ var __accessCheck3 = (obj, member, msg) => member.has(obj) || __typeError3("Cannot " + msg);
2304
+ var __privateGet3 = (obj, member, getter) => (__accessCheck3(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
2305
+ var __privateAdd3 = (obj, member, value) => member.has(obj) ? __typeError3("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2306
+ var __privateSet = (obj, member, value, setter) => (__accessCheck3(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
2307
+ var __privateMethod = (obj, member, method) => (__accessCheck3(obj, member, "access private method"), method);
2308
+ var ProjectMapClient = class extends ApiClient {
2309
+ constructor(options) {
2310
+ super(options);
2311
+ this.getProjectMapDefinitions = async () => {
2312
+ const { projectId } = this.options;
2313
+ const fetchUri = this.createUrl("/api/v1/project-map", { projectId });
2314
+ return await this.apiClient(fetchUri);
2315
+ };
2316
+ this.getProjectMapDefinition = async (options2) => {
2317
+ const { projectId } = this.options;
2318
+ const fetchUri = this.createUrl("/api/v1/project-map", {
2319
+ ...options2,
2320
+ projectId
2321
+ });
2322
+ return await this.apiClient(fetchUri);
2323
+ };
2324
+ this.upsertProjectMap = async (options2) => {
2325
+ const { projectId } = this.options;
2326
+ const fetchUri = this.createUrl("/api/v1/project-map");
2327
+ const result = await this.apiClient(fetchUri, {
2328
+ method: "PUT",
2329
+ body: JSON.stringify({ ...options2, projectId })
2330
+ });
2331
+ return result.projectMapId;
2332
+ };
2333
+ this.deleteProjectMap = async (options2) => {
2334
+ const { projectId } = this.options;
2335
+ const fetchUri = this.createUrl("/api/v1/project-map");
2336
+ await this.apiClient(fetchUri, {
2337
+ method: "DELETE",
2338
+ body: JSON.stringify({ ...options2, projectId }),
2339
+ expectNoContent: true
2340
+ });
2341
+ };
2342
+ this.upsertProjectMapNodes = async (options2) => {
2343
+ const { projectId } = this.options;
2344
+ const fetchUri = this.createUrl("/api/v1/project-map-nodes");
2345
+ await this.apiClient(fetchUri, {
2346
+ method: "PUT",
2347
+ body: JSON.stringify({
2348
+ ...options2,
2349
+ projectId,
2350
+ nodes: options2.nodes.map((n) => {
2351
+ return {
2352
+ ...n,
2353
+ node: { ...this.cleanProjectMapNode(n.node) }
2354
+ };
2355
+ })
2356
+ }),
2357
+ expectNoContent: true
2358
+ });
2359
+ };
2360
+ this.deleteProjectMapNode = async (options2) => {
2361
+ const { projectId } = this.options;
2362
+ const fetchUri = this.createUrl("/api/v1/project-map-nodes");
2363
+ await this.apiClient(fetchUri, {
2364
+ method: "DELETE",
2365
+ body: JSON.stringify({
2366
+ ...options2,
2367
+ projectId
2368
+ }),
2369
+ expectNoContent: true
2370
+ });
2371
+ };
2372
+ this.getSubtree = async (options2) => {
2373
+ var _a;
2374
+ const fetchOptions = this.setFetchOptions(options2);
2375
+ fetchOptions["tree"] = "true";
2376
+ const fetchUri = this.createUrl("/api/v1/project-map-nodes", fetchOptions);
2377
+ const result = await this.apiClient(fetchUri);
2378
+ const root = {
2379
+ ...result.tree
2380
+ };
2381
+ const nodes = [root];
2382
+ while (nodes && nodes.length > 0) {
2383
+ const currentNode = nodes.pop();
2384
+ let lastChild = void 0;
2385
+ (_a = currentNode == null ? void 0 : currentNode.children) == null ? void 0 : _a.forEach((child) => {
2386
+ child.parent = cutReferences(currentNode);
2387
+ child.previousSibling = cutReferences(lastChild);
2388
+ if (lastChild) {
2389
+ lastChild.nextSibling = cutReferences(child);
2390
+ }
2391
+ lastChild = child;
2392
+ nodes.push(child);
2393
+ });
2394
+ }
2395
+ return root;
2396
+ };
2397
+ this.getNodes = async (options2) => {
2398
+ const fetchOptions = this.setFetchOptions(options2);
2399
+ const fetchUri = this.createUrl("/api/v1/project-map-nodes", fetchOptions);
2400
+ return await this.apiClient(fetchUri);
2401
+ };
2402
+ }
2403
+ setFetchOptions(options) {
2404
+ const { projectId } = this.options;
2405
+ const fetchOptions = {
2406
+ projectId
2407
+ };
2408
+ Object.entries(options).forEach(([key, value]) => {
2409
+ if (value === void 0) {
2410
+ return;
2411
+ }
2412
+ if (typeof value === "boolean") {
2413
+ if (!value) {
2414
+ return;
2415
+ }
2416
+ fetchOptions[key] = "true";
2417
+ return;
2418
+ }
2419
+ if (typeof value === "number") {
2420
+ fetchOptions[key] = value.toString(10);
2421
+ return;
2422
+ }
2423
+ fetchOptions[key] = value;
2424
+ });
2425
+ return fetchOptions;
2426
+ }
2427
+ cleanProjectMapNode(node) {
2428
+ var _a, _b, _c;
2429
+ return {
2430
+ id: ((_c = (_b = (_a = node.id) == null ? void 0 : _a.match(/^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i)) == null ? void 0 : _b.length) != null ? _c : 0) == 1 ? node.id : void 0,
2431
+ path: node.path,
2432
+ name: node.name,
2433
+ type: node.type,
2434
+ order: node.order,
2435
+ data: node.data,
2436
+ compositionId: node.compositionId,
2437
+ description: node.description,
2438
+ locales: node.locales
2439
+ };
2440
+ }
2441
+ };
2442
+ var cutReferences = (node) => node ? {
2443
+ ...node,
2444
+ parent: void 0,
2445
+ children: void 0
2446
+ } : void 0;
2447
+ var _routeInfo;
2448
+ var _Route_static;
2449
+ var parseRouteOrPath_fn;
2450
+ var isDynamicRouteSegment_fn;
2451
+ var _Route = class _Route2 {
2452
+ constructor(route) {
2453
+ this.route = route;
2454
+ __privateAdd3(this, _routeInfo);
2455
+ var _a;
2456
+ __privateSet(this, _routeInfo, __privateMethod(_a = _Route2, _Route_static, parseRouteOrPath_fn).call(_a, this.route));
2457
+ }
2458
+ get dynamicSegmentCount() {
2459
+ return __privateGet3(this, _routeInfo).segments.reduce(
2460
+ (count, segment) => {
2461
+ var _a;
2462
+ return __privateMethod(_a = _Route2, _Route_static, isDynamicRouteSegment_fn).call(_a, segment) ? count + 1 : count;
2463
+ },
2464
+ 0
2465
+ );
2466
+ }
2467
+ /** Tests if an incoming path matches this route */
2468
+ matches(path) {
2469
+ var _a, _b;
2470
+ const { segments: pathSegments, queryParams: pathQuery } = __privateMethod(_a = _Route2, _Route_static, parseRouteOrPath_fn).call(_a, path);
2471
+ const { segments: routeSegments } = __privateGet3(this, _routeInfo);
2472
+ if (pathSegments.length !== routeSegments.length) {
2473
+ return { match: false };
2474
+ }
2475
+ const possibleMatch = {
2476
+ match: true,
2477
+ dynamicSegmentCount: 0,
2478
+ pathParams: {},
2479
+ queryParams: {}
2480
+ };
2481
+ for (let i = 0; i < routeSegments.length; i++) {
2482
+ const routeSegment = routeSegments[i];
2483
+ const pathSegment = pathSegments[i];
2484
+ if (__privateMethod(_b = _Route2, _Route_static, isDynamicRouteSegment_fn).call(_b, routeSegment)) {
2485
+ const key = routeSegment.slice(1);
2486
+ possibleMatch.pathParams[key] = pathSegment;
2487
+ possibleMatch.dynamicSegmentCount++;
2488
+ } else if (routeSegment !== pathSegment) {
2489
+ return { match: false };
2490
+ }
2491
+ }
2492
+ for (const [key, value] of __privateGet3(this, _routeInfo).queryParams) {
2493
+ possibleMatch.queryParams[key] = pathQuery.has(key) ? pathQuery.get(key) : value;
2494
+ }
2495
+ return possibleMatch;
2496
+ }
2497
+ /**
2498
+ * Creates an expanded path value for this route given dynamic input values and allowed query string values
2499
+ */
2500
+ expand(options) {
2501
+ const { dynamicInputValues = {}, allowedQueryParams = [], doNotEscapeVariables = false } = options != null ? options : {};
2502
+ const path = __privateGet3(this, _routeInfo).segments.map((segment) => {
2503
+ const dynamicSegmentName = _Route2.getDynamicRouteSegmentName(segment);
2504
+ if (!dynamicSegmentName) {
2505
+ return segment;
2506
+ }
2507
+ const dynamicSegmentValue = dynamicInputValues[dynamicSegmentName];
2508
+ if (!dynamicSegmentValue) {
2509
+ return segment;
2510
+ }
2511
+ return encodeRouteComponent(dynamicSegmentValue, doNotEscapeVariables);
2512
+ }).join("/");
2513
+ const queries = allowedQueryParams.filter((qs) => {
2514
+ const type = typeof dynamicInputValues[qs];
2515
+ return type === "string" || type === "number" || type === "boolean";
2516
+ }).map(
2517
+ (qs) => `${encodeRouteComponent(qs, doNotEscapeVariables)}=${encodeRouteComponent(
2518
+ dynamicInputValues[qs],
2519
+ doNotEscapeVariables
2520
+ )}`
2521
+ );
2522
+ const query = queries.length ? `?${queries.join("&")}` : "";
2523
+ return `/${path}${query}`;
2524
+ }
2525
+ static getDynamicRouteSegmentName(segment) {
2526
+ var _a;
2527
+ if (!__privateMethod(_a = _Route2, _Route_static, isDynamicRouteSegment_fn).call(_a, segment)) {
2528
+ return void 0;
2529
+ }
2530
+ return segment.slice(_Route2.dynamicSegmentPrefix.length);
2531
+ }
2532
+ };
2533
+ _routeInfo = /* @__PURE__ */ new WeakMap();
2534
+ _Route_static = /* @__PURE__ */ new WeakSet();
2535
+ parseRouteOrPath_fn = function(path) {
2536
+ if (!path.startsWith("/") || path === "") {
2537
+ throw new Error(`Path must start with a slash: ${path}`);
2538
+ }
2539
+ const [pathname, queryString] = path.split("?");
2540
+ const pathSegments = pathname.substring(1).split("/");
2541
+ if (pathSegments[pathSegments.length - 1] === "") {
2542
+ pathSegments.pop();
2543
+ }
2544
+ const queryParams = new URLSearchParams(queryString);
2545
+ return { segments: pathSegments, queryParams };
2546
+ };
2547
+ isDynamicRouteSegment_fn = function(segment) {
2548
+ if (!segment) {
2549
+ return false;
2550
+ }
2551
+ return segment.startsWith(_Route.dynamicSegmentPrefix);
2552
+ };
2553
+ __privateAdd3(_Route, _Route_static);
2554
+ _Route.dynamicSegmentPrefix = ":";
2555
+ function encodeRouteComponent(value, doNotEscapeVariables) {
2556
+ if (!doNotEscapeVariables) {
2557
+ return encodeURIComponent(value);
2558
+ }
2559
+ const result = [];
2560
+ parseVariableExpression(value.toString(10), (token, type) => {
2561
+ if (type === "variable") {
2562
+ result.push(createVariableReference(token));
2563
+ } else {
2564
+ result.push(encodeURIComponent(token));
2565
+ }
2566
+ });
2567
+ return result.join("");
2568
+ }
2569
+
2570
+ // src/clients/projectMap.ts
2571
+ var getProjectMapClient = (options) => {
2572
+ const cache2 = resolveProjectMapCache(options);
2573
+ const manifestClient = new ProjectMapClient({
2574
+ apiHost: env.getApiHost(),
2575
+ apiKey: env.getApiKey(),
2576
+ projectId: env.getProjectId(),
2577
+ limitPolicy: createLimitPolicy2({
2578
+ limit: 6
2579
+ }),
2580
+ fetch: (req, init) => {
2581
+ const { cache: fetchCache, revalidate } = determineFetchCacheOptions(cache2);
2582
+ return fetch(req, {
2583
+ ...init,
2584
+ headers: {
2585
+ ...init == null ? void 0 : init.headers,
2586
+ "x-bypass-cache": typeof cache2.bypassCache !== "undefined" ? cache2.bypassCache.toString() : "false"
2587
+ },
2588
+ cache: fetchCache,
2589
+ next: {
2590
+ revalidate
2591
+ }
2592
+ });
2593
+ }
2594
+ });
2595
+ return manifestClient;
2596
+ };
2597
+
2598
+ // src/clients/route.ts
2599
+ import "server-only";
2600
+ var getRouteCacheTags = (requestedUrl) => {
2601
+ const tags = ["route"];
2602
+ if (requestedUrl) {
2603
+ const pathKey = "path";
2604
+ const path = requestedUrl.searchParams.get(pathKey);
2605
+ if (path) {
2606
+ return generateRouteCacheTags({ path });
2607
+ }
2608
+ }
2609
+ return tags;
2610
+ };
2611
+ var getRouteClient = (options) => {
2612
+ const cache2 = resolveCanvasCache(options);
2613
+ const client = new RouteClient({
2614
+ projectId: env.getProjectId(),
2615
+ apiKey: env.getApiKey(),
2616
+ edgeApiHost: env.getEdgeApiHost(),
2617
+ disableSWR: typeof cache2.disableSWR !== "undefined" ? cache2.disableSWR : true,
2618
+ limitPolicy: createLimitPolicy2({
2619
+ limit: 6
2620
+ }),
2621
+ fetch: (req, init) => {
2622
+ let requestedUrl;
2623
+ if (typeof req === "string") {
2624
+ requestedUrl = new URL(req);
2625
+ } else if (req instanceof URL) {
2626
+ requestedUrl = req;
2627
+ } else {
2628
+ requestedUrl = new URL(req.url);
2629
+ }
2630
+ const tags = getRouteCacheTags(requestedUrl);
2631
+ const { cache: fetchCache, revalidate } = determineFetchCacheOptions(cache2);
2632
+ return fetch(req, {
2633
+ ...init,
2634
+ headers: {
2635
+ ...init == null ? void 0 : init.headers,
2636
+ "x-bypass-cache": typeof cache2.bypassCache !== "undefined" ? cache2.bypassCache.toString() : "false"
2637
+ },
2638
+ cache: fetchCache,
2639
+ next: {
2640
+ revalidate,
2641
+ tags: tags.length ? tags : void 0
2642
+ }
2643
+ });
2644
+ }
2645
+ });
2646
+ return client;
2647
+ };
2648
+
2649
+ // src/components/UniformComposition.tsx
2650
+ import { PureContextualEditingComponentWrapper } from "@uniformdev/canvas-react/core";
2651
+ import { ContextUpdateTransfer, Personalize, UniformScript } from "@uniformdev/next-app-router-client";
2652
+ import {
2653
+ resolveRuleFromPageState
2654
+ } from "@uniformdev/next-app-router-shared";
2655
+ import { notFound } from "next/navigation";
2656
+ import React5, { createElement as createElement2, Fragment as Fragment3, Suspense as Suspense2 } from "react";
2657
+
2658
+ // src/data/extract/extractTest.ts
2659
+ import { extractTestName } from "@uniformdev/next-app-router-shared";
2660
+ var extractTest = ({ component }) => {
2661
+ var _a;
2662
+ const testName = extractTestName({ component });
2663
+ const slot = ((_a = component.slots) == null ? void 0 : _a[CANVAS_TEST_SLOT]) || [];
2664
+ const componentVariations = mapSlotToTestVariations(slot).map((variation, index) => {
2665
+ const slotComponent = slot[index];
2666
+ if (!slotComponent) {
2667
+ throw new Error(`Slot component not found for index ${index}`);
2668
+ }
2669
+ return {
2670
+ ...variation,
2671
+ index,
2672
+ componentId: slotComponent._id
2673
+ };
2674
+ });
2675
+ return {
2676
+ name: testName,
2677
+ variations: componentVariations
2678
+ };
2679
+ };
2680
+
2681
+ // src/components/ComponentProps.ts
2682
+ import {
2683
+ resolveComponentFromPageState
2684
+ } from "@uniformdev/next-app-router-shared";
2685
+ var createComponentProps = ({
2686
+ component,
2687
+ parent,
2688
+ isRoot,
2689
+ slotName,
2690
+ slotIndex,
2691
+ slots,
2692
+ pageState,
2693
+ composition,
2694
+ compositionContext
2695
+ }) => {
2696
+ var _a, _b;
2697
+ const parameters = (_a = component.parameters) != null ? _a : {};
2698
+ const componentProps = {
2699
+ parameters: Object.keys(parameters).reduce((acc, cur) => {
2700
+ acc[cur] = {
2701
+ parameterId: cur,
2702
+ ...parameters[cur]
2703
+ };
2704
+ return acc;
2705
+ }, {}),
2706
+ component: {
2707
+ _id: component._id,
2708
+ _parentId: (_b = parent == null ? void 0 : parent._id) != null ? _b : null,
2709
+ slotName,
2710
+ slotIndex: isRoot ? void 0 : slotIndex
2711
+ },
2712
+ type: component.type,
2713
+ variant: component.variant,
2714
+ slots,
2715
+ context: {
2716
+ isContextualEditing: pageState.compositionState === CANVAS_EDITOR_STATE,
2717
+ _id: composition._id,
2718
+ state: pageState.compositionState,
2719
+ type: composition.type,
2720
+ pageState,
2721
+ matchedRoute: compositionContext.matchedRoute,
2722
+ dynamicInputs: compositionContext.dynamicInputs
2723
+ }
2724
+ };
2725
+ return componentProps;
2726
+ };
2727
+ var createPersonalizeComponentProps = ({
2728
+ common,
2729
+ componentId,
2730
+ pageState
2731
+ }) => {
2732
+ var _a;
2733
+ const component = resolveComponentFromPageState({
2734
+ pageState,
2735
+ componentId
2736
+ });
2737
+ return {
2738
+ ...common,
2739
+ indexes: (_a = component == null ? void 0 : component.indexes) != null ? _a : []
2740
+ };
2741
+ };
2742
+ var createTestComponentProps = ({
2743
+ common,
2744
+ componentId,
2745
+ pageState,
2746
+ test
2747
+ }) => {
2748
+ var _a;
2749
+ const component = resolveComponentFromPageState({
2750
+ pageState,
2751
+ componentId
2752
+ });
2753
+ const [testIndex] = (_a = component == null ? void 0 : component.indexes) != null ? _a : [];
2754
+ return {
2755
+ ...common,
2756
+ index: testIndex != null ? testIndex : 0,
2757
+ test
2758
+ };
2759
+ };
2760
+
2761
+ // src/components/helpers/applyEditableParameters.ts
2762
+ var applyEditableParameters = ({
2763
+ composition,
2764
+ state
2765
+ }) => {
2766
+ if (state === CANVAS_EDITOR_STATE) {
2767
+ walkNodeTree(composition, (node) => {
2768
+ var _a, _b;
2769
+ if (node.type === "component" && node.node.parameters) {
2770
+ const contextualEditing = node.node.parameters[CANVAS_CONTEXTUAL_EDITING_PARAM];
2771
+ const editableFields = (_b = (_a = contextualEditing == null ? void 0 : contextualEditing.value) == null ? void 0 : _a.editableParameters) != null ? _b : [];
2772
+ Object.keys(node.node.parameters).forEach((key) => {
2773
+ const parameter = node.node.parameters[key];
2774
+ if (parameter.type === "text") {
2775
+ const contextualParameter = parameter;
2776
+ contextualParameter._contextualEditing = {
2777
+ isEditable: editableFields.includes(key)
2778
+ };
2779
+ }
2780
+ });
2781
+ }
2782
+ });
2783
+ }
2784
+ };
2785
+
2786
+ // src/components/Test.tsx
2787
+ import { createElement, Fragment } from "react";
2788
+
2789
+ // src/components/ContextTestTransfer.tsx
2790
+ import { ClientContextTestTransfer } from "@uniformdev/next-app-router-client";
2791
+ import React from "react";
2792
+ var ContextTestTransfer = ({ event }) => {
2793
+ return /* @__PURE__ */ React.createElement(ClientContextTestTransfer, { event });
2794
+ };
2795
+
2796
+ // src/components/Test.tsx
2797
+ var Test = ({ index, slots, test, component, context: compositionContext }) => {
2798
+ var _a, _b, _c, _d, _e, _f;
2799
+ const indexToShow = typeof index === "number" ? (_b = (_a = slots == null ? void 0 : slots[CANVAS_TEST_SLOT]) == null ? void 0 : _a.items[index]) != null ? _b : null : null;
2800
+ const event = {
2801
+ name: test.name,
2802
+ // todo: add Control Group support
2803
+ control: (_d = (_c = test.variations[index]) == null ? void 0 : _c.control) != null ? _d : false,
2804
+ variantAssigned: true,
2805
+ variantId: (_f = (_e = test.variations[index]) == null ? void 0 : _e.id) != null ? _f : "NO_VARIANTS",
2806
+ compositionMetadata: {
2807
+ compositionId: compositionContext._id,
2808
+ matchedRoute: compositionContext.matchedRoute,
2809
+ dynamicInputs: compositionContext.dynamicInputs
2810
+ }
2811
+ };
2812
+ const eventElement = createElement(ContextTestTransfer, {
2813
+ event,
2814
+ key: `${component.slotName}-${component.slotIndex}-server-transfer`
2815
+ });
2816
+ return createElement(Fragment, void 0, [indexToShow == null ? void 0 : indexToShow.component, eventElement]);
2817
+ };
2818
+
2819
+ // src/components/UniformCompositionWrapper.tsx
2820
+ import { deserializeEvaluationResult } from "@uniformdev/next-app-router-shared";
2821
+ import React2, { Fragment as Fragment2, Suspense } from "react";
2822
+ var UniformCompositionWrapper = ({
2823
+ code,
2824
+ children
2825
+ }) => {
2826
+ const data = deserializeEvaluationResult({ input: code });
2827
+ const WrapperComponent = data.compositionState === CANVAS_EDITOR_STATE || data.compositionState === CANVAS_DRAFT_STATE ? Suspense : Fragment2;
2828
+ return /* @__PURE__ */ React2.createElement(WrapperComponent, null, children);
2829
+ };
2830
+
2831
+ // src/components/UniformContext.tsx
2832
+ import { DefaultUniformClientContext } from "@uniformdev/next-app-router-client";
2833
+ import React3 from "react";
2834
+ var UniformContext = async ({ clientContextComponent, result }) => {
2835
+ var _a, _b, _c, _d;
2836
+ const manifest = await getManifest({
2837
+ state: CANVAS_PUBLISHED_STATE
2838
+ });
2839
+ const { route } = result != null ? result : {};
2840
+ const compositionMetadata = route ? {
2841
+ compositionId: route.compositionApiResponse.composition._id,
2842
+ dynamicInputs: route.dynamicInputs,
2843
+ matchedRoute: route.matchedRoute
2844
+ } : void 0;
2845
+ const ContextComponent = clientContextComponent || DefaultUniformClientContext;
2846
+ const serverConfig2 = getServerConfig();
2847
+ const disableDevTools = ((_a = serverConfig2.context) == null ? void 0 : _a.disableDevTools) || false;
2848
+ const defaultConsent = (_c = (_b = result == null ? void 0 : result.pageState.defaultConsent) != null ? _b : serverConfig2.defaultConsent) != null ? _c : false;
2849
+ const experimentalQuirkSerialization = ((_d = serverConfig2.experimental) == null ? void 0 : _d.quirkSerialization) || false;
2850
+ return /* @__PURE__ */ React3.createElement(React3.Fragment, null, /* @__PURE__ */ React3.createElement(
2851
+ ContextComponent,
2852
+ {
2853
+ manifest,
2854
+ disableDevTools,
2855
+ defaultConsent,
2856
+ experimentalQuirkSerialization,
2857
+ compositionMetadata
2858
+ }
2859
+ ));
2860
+ };
2861
+
2862
+ // src/components/VisibilityRulesWrapper.tsx
2863
+ import { VisibilityRulesWrapperClient } from "@uniformdev/next-app-router-client";
2864
+ import React4 from "react";
2865
+ var VisibilityRulesWrapper = ({
2866
+ parameter,
2867
+ initialIsVisible,
2868
+ children
2869
+ }) => {
2870
+ return /* @__PURE__ */ React4.createElement(VisibilityRulesWrapperClient, { parameter, initialIsVisible }, children);
2871
+ };
2872
+
2873
+ // src/components/UniformComposition.tsx
2874
+ function UniformComposition({ code, ...props }) {
2875
+ return /* @__PURE__ */ React5.createElement(UniformCompositionWrapper, { code }, /* @__PURE__ */ React5.createElement(UniformCompositionInner, { code, ...props }));
2876
+ }
2877
+ async function UniformCompositionInner({
2878
+ code,
2879
+ resolveRoute,
2880
+ resolveComponent,
2881
+ resolveEmptyPlaceholder,
2882
+ compositionCache,
2883
+ clientContextComponent
2884
+ }) {
2885
+ var _a, _b;
2886
+ const result = await resolveRoute({
2887
+ params: Promise.resolve({ code })
2888
+ });
2889
+ if (!(result == null ? void 0 : result.route) || ((_a = result == null ? void 0 : result.route) == null ? void 0 : _a.type) !== "composition") {
2890
+ notFound();
2891
+ }
2892
+ const { pageState, route } = result;
2893
+ const composition = result.route.compositionApiResponse.composition;
2894
+ applyEditableParameters({
2895
+ composition,
2896
+ state: route.compositionApiResponse.state
2897
+ });
2898
+ compositionCache == null ? void 0 : compositionCache.setUniformComposition(composition);
2899
+ const compositionContext = {
2900
+ _id: composition._id,
2901
+ type: composition.type,
2902
+ state: pageState.compositionState,
2903
+ isContextualEditing: pageState.compositionState === CANVAS_EDITOR_STATE,
2904
+ matchedRoute: route.matchedRoute,
2905
+ dynamicInputs: (_b = route.dynamicInputs) != null ? _b : {},
2906
+ pageState
2907
+ };
2908
+ const [resolved] = resolveComponents({
2909
+ target: {
2910
+ type: "root",
2911
+ composition
2912
+ },
2913
+ pageState,
2914
+ slotName: void 0,
2915
+ slotIndex: void 0,
2916
+ resolveComponent,
2917
+ resolveEmptyPlaceholder,
2918
+ composition,
2919
+ compositionContext
2920
+ });
2921
+ return /* @__PURE__ */ React5.createElement(React5.Fragment, null, resolved, /* @__PURE__ */ React5.createElement(Suspense2, null, /* @__PURE__ */ React5.createElement(
2922
+ UniformContext,
2923
+ {
2924
+ clientContextComponent,
2925
+ result: {
2926
+ code,
2927
+ pageState,
2928
+ route
2929
+ }
2930
+ }
2931
+ )), (pageState.compositionState === CANVAS_EDITOR_STATE || pageState.compositionState === CANVAS_DRAFT_STATE) && /* @__PURE__ */ React5.createElement(UniformScript, null));
2932
+ }
2933
+ var resolveComponents = ({
2934
+ target,
2935
+ pageState,
2936
+ slotName,
2937
+ slotIndex,
2938
+ resolveComponent,
2939
+ resolveEmptyPlaceholder,
2940
+ composition,
2941
+ compositionContext
2942
+ }) => {
2943
+ const isRoot = !slotName && typeof slotIndex !== "number";
2944
+ let root;
2945
+ let parent = void 0;
2946
+ let components;
2947
+ if (target.type === "root") {
2948
+ root = target.composition;
2949
+ components = [target.composition];
2950
+ } else {
2951
+ root = target.root;
2952
+ components = target.components;
2953
+ parent = target.parent;
2954
+ }
2955
+ const resolved = components.map((component, componentIndex) => {
2956
+ var _a, _b, _c;
2957
+ const isPlaceholder = isComponentPlaceholderId(component == null ? void 0 : component._id);
2958
+ let resolveResult = null;
2959
+ if (isPlaceholder && resolveEmptyPlaceholder) {
2960
+ const resolvedPlaceholder = resolveEmptyPlaceholder({
2961
+ parentComponent: parent,
2962
+ component,
2963
+ slotName,
2964
+ slotIndex: componentIndex
2965
+ });
2966
+ if (resolvedPlaceholder) {
2967
+ resolveResult = {
2968
+ component: resolvedPlaceholder.component
2969
+ };
2970
+ }
2971
+ }
2972
+ if (!resolveResult) {
2973
+ resolveResult = resolveComponent({ component });
2974
+ }
2975
+ const { component: resolvedComponent, suspense: componentSuspense } = resolveResult || {
2976
+ component: null
2977
+ };
2978
+ const slots = resolveSlots({
2979
+ component,
2980
+ root,
2981
+ resolveComponent,
2982
+ resolveEmptyPlaceholder,
2983
+ pageState,
2984
+ composition,
2985
+ compositionContext
2986
+ });
2987
+ const wrapInSuspense = componentSuspense;
2988
+ const parameters = (_a = component.parameters) != null ? _a : {};
2989
+ const enrichmentTags = (_b = parameters[CANVAS_ENRICHMENT_TAG_PARAM]) == null ? void 0 : _b.value;
2990
+ const visibilityRules = (_c = parameters[CANVAS_VIZ_CONTROL_PARAM]) == null ? void 0 : _c.value;
2991
+ if (!component._id) {
2992
+ console.warn(`Component ${component.type} has no _id`);
2993
+ }
2994
+ const key = `${slotName}-${componentIndex}-component`;
2995
+ const componentProps = createComponentProps({
2996
+ component,
2997
+ parent: parent != null ? parent : null,
2998
+ isRoot,
2999
+ slotName,
3000
+ slotIndex: isRoot ? void 0 : componentIndex,
3001
+ slots,
3002
+ pageState,
3003
+ composition,
3004
+ compositionContext
3005
+ });
3006
+ let element = null;
3007
+ if (wrapInSuspense) {
3008
+ element = createElement2(
3009
+ Suspense2,
3010
+ {
3011
+ key,
3012
+ fallback: typeof wrapInSuspense === "boolean" || typeof (wrapInSuspense == null ? void 0 : wrapInSuspense.fallback) === "undefined" ? void 0 : createElement2(wrapInSuspense.fallback)
3013
+ },
3014
+ createResolvedComponent({ component, props: componentProps, resolvedComponent, pageState })
3015
+ );
3016
+ } else {
3017
+ element = createResolvedComponent({
3018
+ component,
3019
+ props: componentProps,
3020
+ resolvedComponent,
3021
+ pageState,
3022
+ key
3023
+ });
3024
+ }
3025
+ let tagElement = null;
3026
+ if (enrichmentTags == null ? void 0 : enrichmentTags.length) {
3027
+ tagElement = createElement2(ContextUpdateTransfer, {
3028
+ key: `${slotName}-${componentIndex}-tags`,
3029
+ update: {
3030
+ enrichments: enrichmentTags
3031
+ }
3032
+ });
3033
+ }
3034
+ let childNode;
3035
+ if (pageState.compositionState === CANVAS_EDITOR_STATE) {
3036
+ const elements = [element];
3037
+ if (tagElement) {
3038
+ elements.push(tagElement);
3039
+ }
3040
+ const isPlaceholder2 = isComponentPlaceholderId(component == null ? void 0 : component._id);
3041
+ if (!isPlaceholder2 || pageState.compositionState === CANVAS_EDITOR_STATE) {
3042
+ childNode = createElement2(
3043
+ PureContextualEditingComponentWrapper,
3044
+ {
3045
+ key: `${slotName}-${componentIndex}-wrapper`,
3046
+ isPlaceholder: isPlaceholder2,
3047
+ parentComponent: parent,
3048
+ component,
3049
+ slotName,
3050
+ indexInSlot: componentIndex,
3051
+ slotChildrenCount: components.length,
3052
+ isReadOnly: "false"
3053
+ },
3054
+ elements
3055
+ );
3056
+ }
3057
+ } else {
3058
+ const elements = [element];
3059
+ if (tagElement) {
3060
+ elements.push(tagElement);
3061
+ }
3062
+ childNode = elements;
3063
+ }
3064
+ if (visibilityRules) {
3065
+ const isVisible = resolveRuleFromPageState({
3066
+ pageState,
3067
+ rule: visibilityRules
3068
+ });
3069
+ childNode = createElement2(
3070
+ VisibilityRulesWrapper,
3071
+ {
3072
+ key: `${slotName}-${componentIndex}-visibility`,
3073
+ parameter: visibilityRules,
3074
+ initialIsVisible: isVisible != null ? isVisible : null
3075
+ },
3076
+ childNode
3077
+ );
3078
+ }
3079
+ return createElement2(
3080
+ Fragment3,
3081
+ {
3082
+ key: !isRoot ? `${slotName}-${componentIndex}` : void 0
3083
+ },
3084
+ childNode
3085
+ );
3086
+ });
3087
+ return resolved;
3088
+ };
3089
+ var createResolvedComponent = ({
3090
+ component,
3091
+ props,
3092
+ resolvedComponent,
3093
+ pageState,
3094
+ key
3095
+ }) => {
3096
+ if (component.type === CANVAS_PERSONALIZE_TYPE) {
3097
+ const personalizeProps = createPersonalizeComponentProps({
3098
+ common: props,
3099
+ componentId: component._id,
3100
+ pageState
3101
+ });
3102
+ return createElement2(Personalize, { ...personalizeProps, key });
3103
+ }
3104
+ if (component.type === CANVAS_TEST_TYPE) {
3105
+ const extractedTest = extractTest({
3106
+ component
3107
+ });
3108
+ const testProps = createTestComponentProps({
3109
+ common: props,
3110
+ componentId: component._id,
3111
+ pageState,
3112
+ test: extractedTest
3113
+ });
3114
+ return createElement2(Test, { ...testProps, key });
3115
+ }
3116
+ if (!resolvedComponent) {
3117
+ return null;
3118
+ }
3119
+ return createElement2(resolvedComponent, { ...props, key });
3120
+ };
3121
+ var resolveSlots = ({
3122
+ component,
3123
+ root,
3124
+ resolveComponent,
3125
+ resolveEmptyPlaceholder,
3126
+ pageState,
3127
+ composition,
3128
+ compositionContext
3129
+ }) => {
3130
+ const slots = {};
3131
+ if (component.slots) {
3132
+ Object.keys(component.slots).forEach((slotName, slotIndex) => {
3133
+ const components = component.slots[slotName];
3134
+ const resolved = resolveComponents({
3135
+ target: {
3136
+ type: "slot",
3137
+ components,
3138
+ root,
3139
+ parent: component
3140
+ },
3141
+ slotName,
3142
+ slotIndex,
3143
+ resolveComponent,
3144
+ resolveEmptyPlaceholder,
3145
+ pageState,
3146
+ composition,
3147
+ compositionContext
3148
+ });
3149
+ if (resolved) {
3150
+ let variantIds;
3151
+ if (component.type === CANVAS_PERSONALIZE_TYPE) {
3152
+ variantIds = mapSlotToPersonalizedVariations(components).map((v) => v.id);
3153
+ } else if (component.type === CANVAS_TEST_TYPE) {
3154
+ variantIds = mapSlotToTestVariations(components).map((v) => v.id);
3155
+ }
3156
+ slots[slotName] = {
3157
+ name: slotName,
3158
+ items: components.map((component2, index) => {
3159
+ var _a, _b;
3160
+ const item = resolved[index];
3161
+ if (!item) {
3162
+ return null;
3163
+ }
3164
+ const pzCriteria = (_b = (_a = component2.parameters) == null ? void 0 : _a[CANVAS_PERSONALIZATION_PARAM]) == null ? void 0 : _b.value;
3165
+ return {
3166
+ _id: component2._id,
3167
+ variantId: variantIds == null ? void 0 : variantIds[index],
3168
+ [CANVAS_PERSONALIZATION_PARAM]: pzCriteria,
3169
+ component: item
3170
+ };
3171
+ })
3172
+ };
3173
+ }
3174
+ });
3175
+ }
3176
+ return slots;
3177
+ };
3178
+
3179
+ // src/components/UniformPlayground.tsx
3180
+ import { draftMode } from "next/headers";
3181
+ import React6 from "react";
3182
+
3183
+ // src/data/resolvePlaygroundRoute.ts
3184
+ import { deserializeEvaluationResult as deserializeEvaluationResult2 } from "@uniformdev/next-app-router-shared";
3185
+ var resolvePlaygroundRoute = async ({
3186
+ params
3187
+ }) => {
3188
+ const { code } = await params;
3189
+ const pageState = deserializeEvaluationResult2({ input: code });
3190
+ const canvasClient = getCanvasClient({
3191
+ cache: {
3192
+ type: "no-cache"
3193
+ }
3194
+ });
3195
+ let composition = void 0;
3196
+ try {
3197
+ composition = await canvasClient.getCompositionById({
3198
+ compositionId: pageState.routePath,
3199
+ state: pageState.compositionState,
3200
+ withComponentIDs: true
3201
+ });
3202
+ } catch (e) {
3203
+ console.warn(
3204
+ `Failed to get composition ${pageState.routePath} with state ${pageState.compositionState}`,
3205
+ e
3206
+ );
3207
+ }
3208
+ if (!composition) {
3209
+ return {
3210
+ code,
3211
+ pageState,
3212
+ route: void 0
3213
+ };
3214
+ }
3215
+ return {
3216
+ code,
3217
+ pageState,
3218
+ route: {
3219
+ type: "composition",
3220
+ compositionApiResponse: composition,
3221
+ matchedRoute: "composition"
3222
+ }
3223
+ };
3224
+ };
3225
+
3226
+ // src/components/UniformPlayground.tsx
3227
+ var UniformPlayground = async ({ resolveRoute, ...rest }) => {
3228
+ const isDraftMode = (await draftMode()).isEnabled;
3229
+ if (!isDraftMode) {
3230
+ return /* @__PURE__ */ React6.createElement("div", null, /* @__PURE__ */ React6.createElement("h1", null, "Playground is only available in draft mode"));
3231
+ }
3232
+ return /* @__PURE__ */ React6.createElement(UniformComposition, { ...rest, resolveRoute: resolvePlaygroundRoute });
3233
+ };
3234
+
3235
+ // src/components/generateStaticParams.ts
3236
+ import { serializeEvaluationResult } from "@uniformdev/next-app-router-shared";
3237
+
3238
+ // src/data/extract/extractRunnables.ts
3239
+ import { getRuleId } from "@uniformdev/next-app-router-shared";
3240
+
3241
+ // src/data/extract/extractPersonalization.ts
3242
+ import {
3243
+ extractPersonalizationName
3244
+ } from "@uniformdev/next-app-router-shared";
3245
+ var extractPersonalization = ({
3246
+ component
3247
+ }) => {
3248
+ var _a, _b, _c;
3249
+ const trackingEventName = extractPersonalizationName({ component });
3250
+ const countParameter = (_a = component.parameters) == null ? void 0 : _a.count;
3251
+ const algorithmParameter = (_b = component.parameters) == null ? void 0 : _b.algorithm;
3252
+ const count = countParameter == null ? void 0 : countParameter.value;
3253
+ const algorithm = algorithmParameter == null ? void 0 : algorithmParameter.value;
3254
+ let parsedCount;
3255
+ if (typeof count === "string") {
3256
+ parsedCount = parseInt(count, 10);
3257
+ } else if (typeof count !== "number") {
3258
+ parsedCount = void 0;
3259
+ } else {
3260
+ parsedCount = count || 1;
3261
+ }
3262
+ const slot = ((_c = component.slots) == null ? void 0 : _c[CANVAS_PERSONALIZE_SLOT]) || [];
3263
+ const componentVariations = mapSlotToPersonalizedVariations(
3264
+ slot
3265
+ ).map((variant, index) => {
3266
+ const slotComponent = slot[index];
3267
+ if (!slotComponent) {
3268
+ throw new Error(`Slot component not found for index ${index}`);
3269
+ }
3270
+ return {
3271
+ ...variant,
3272
+ index,
3273
+ componentId: slotComponent._id
3274
+ };
3275
+ });
3276
+ return {
3277
+ name: trackingEventName,
3278
+ take: parsedCount,
3279
+ variations: componentVariations,
3280
+ algorithm
3281
+ };
3282
+ };
3283
+
3284
+ // src/data/extract/extractRunnables.ts
3285
+ var findAncestorVariant = (ancestorsAndSelf) => {
3286
+ let nodeIndex = -1;
3287
+ for (let i = 1; i < ancestorsAndSelf.length; i++) {
3288
+ const node = ancestorsAndSelf[i];
3289
+ if (node.type === "slot" && (node.parentSlot === CANVAS_PERSONALIZE_SLOT || node.parentSlot === CANVAS_TEST_SLOT)) {
3290
+ nodeIndex = i;
3291
+ break;
3292
+ }
3293
+ }
3294
+ if (nodeIndex !== -1) {
3295
+ const node = ancestorsAndSelf[nodeIndex];
3296
+ return node.node._id;
3297
+ }
3298
+ return void 0;
3299
+ };
3300
+ var extractRunnables = (composition) => {
3301
+ const runnable = [];
3302
+ walkNodeTree(composition, (node) => {
3303
+ var _a, _b;
3304
+ if (node.type === "component") {
3305
+ const component = node.node;
3306
+ const visibilityRules = (_b = (_a = component.parameters) == null ? void 0 : _a[CANVAS_VIZ_CONTROL_PARAM]) == null ? void 0 : _b.value;
3307
+ if (component.type === CANVAS_TEST_TYPE) {
3308
+ const test = extractTest({ component });
3309
+ runnable.push({
3310
+ _id: component._id,
3311
+ variantId: findAncestorVariant(node.ancestorsAndSelf),
3312
+ type: "test",
3313
+ result: test
3314
+ });
3315
+ } else if (component.type === CANVAS_PERSONALIZE_TYPE) {
3316
+ const personalize = extractPersonalization({ component });
3317
+ runnable.push({
3318
+ type: "personalization",
3319
+ variantId: findAncestorVariant(node.ancestorsAndSelf),
3320
+ _id: component._id,
3321
+ result: personalize
3322
+ });
3323
+ }
3324
+ if (visibilityRules) {
3325
+ runnable.push({
3326
+ type: "visibility",
3327
+ _id: getRuleId(visibilityRules),
3328
+ variantId: findAncestorVariant(node.ancestorsAndSelf),
3329
+ rules: visibilityRules
3330
+ });
3331
+ }
3332
+ }
3333
+ });
3334
+ return runnable;
3335
+ };
3336
+
3337
+ // src/components/generateStaticParams.ts
3338
+ var createUniformPlaygroundStaticParams = async (options) => {
3339
+ var _a;
3340
+ const { paths } = options;
3341
+ const [firstPath] = paths;
3342
+ if (!firstPath) {
3343
+ throw new Error("At least one path is required.");
3344
+ }
3345
+ const possibleStates = [CANVAS_EDITOR_STATE, CANVAS_DRAFT_STATE];
3346
+ let route = void 0;
3347
+ for (const state of possibleStates) {
3348
+ const routeClient = getRouteClient({
3349
+ state
3350
+ });
3351
+ route = await routeClient.getRoute({
3352
+ path: firstPath,
3353
+ withComponentIDs: true,
3354
+ state: CANVAS_DRAFT_STATE
3355
+ });
3356
+ if (route.type === "composition") {
3357
+ break;
3358
+ }
3359
+ }
3360
+ if ((route == null ? void 0 : route.type) !== "composition") {
3361
+ throw new Error("No route found for the given path.");
3362
+ }
3363
+ const runnables = extractRunnables(route.compositionApiResponse.composition);
3364
+ const choices = generatePossiblePageStates({
3365
+ runnables,
3366
+ path: route.compositionApiResponse.composition._id,
3367
+ keys: void 0,
3368
+ state: route.compositionApiResponse.state
3369
+ });
3370
+ return (_a = choices == null ? void 0 : choices.map((code) => {
3371
+ return {
3372
+ code
3373
+ };
3374
+ })) != null ? _a : [];
3375
+ };
3376
+ var createUniformStaticParams = async (options) => {
3377
+ var _a;
3378
+ const { paths, rewrite } = options;
3379
+ const codes = [];
3380
+ for (const path of paths) {
3381
+ const pageStates = await processRoutePath({ path, rewrite });
3382
+ if (pageStates) {
3383
+ codes.push(...pageStates);
3384
+ }
3385
+ }
3386
+ return (_a = codes == null ? void 0 : codes.map((code) => {
3387
+ return {
3388
+ code
3389
+ };
3390
+ })) != null ? _a : [];
3391
+ };
3392
+ async function processRoutePath({
3393
+ path,
3394
+ rewrite
3395
+ }) {
3396
+ var _a;
3397
+ const routeClient = getRouteClient({
3398
+ state: CANVAS_PUBLISHED_STATE
3399
+ });
3400
+ const rewrittenPath = await (rewrite == null ? void 0 : rewrite({ path }));
3401
+ const resolvedPath = (_a = rewrittenPath == null ? void 0 : rewrittenPath.path) != null ? _a : path;
3402
+ const route = await routeClient.getRoute({
3403
+ path: resolvedPath,
3404
+ withComponentIDs: true,
3405
+ state: CANVAS_PUBLISHED_STATE
3406
+ });
3407
+ if (route.type !== "composition") {
3408
+ return void 0;
3409
+ }
3410
+ const runnables = extractRunnables(route.compositionApiResponse.composition);
3411
+ const choices = generatePossiblePageStates({
3412
+ runnables,
3413
+ path: resolvedPath,
3414
+ keys: rewrittenPath == null ? void 0 : rewrittenPath.keys,
3415
+ state: CANVAS_PUBLISHED_STATE
3416
+ });
3417
+ return choices;
3418
+ }
3419
+ var buildDependencyMap = (runnables) => {
3420
+ var _a;
3421
+ const map = /* @__PURE__ */ new Map();
3422
+ for (const runnable of runnables) {
3423
+ const deps = (_a = map.get(runnable.variantId)) != null ? _a : [];
3424
+ deps.push(runnable);
3425
+ map.set(runnable.variantId, deps);
3426
+ }
3427
+ return map;
3428
+ };
3429
+ var runnablesToGroups = (runnables) => {
3430
+ var _a;
3431
+ const groups = [];
3432
+ for (const runnable of runnables) {
3433
+ if (runnable.type === "visibility") {
3434
+ groups.push({
3435
+ _id: runnable._id,
3436
+ optionType: "visibility",
3437
+ select: 1,
3438
+ options: [true, false]
3439
+ });
3440
+ } else if (runnable.type === "test") {
3441
+ groups.push({
3442
+ _id: runnable._id,
3443
+ optionType: "indexes",
3444
+ select: 1,
3445
+ options: runnable.result.variations.map((variation, index) => ({
3446
+ variantId: variation.componentId,
3447
+ index
3448
+ }))
3449
+ });
3450
+ } else if (runnable.type === "personalization") {
3451
+ const options = [];
3452
+ let index = 0;
3453
+ for (const variation of runnable.result.variations) {
3454
+ options.push({
3455
+ variantId: variation.componentId,
3456
+ index
3457
+ });
3458
+ index++;
3459
+ }
3460
+ groups.push({
3461
+ _id: runnable._id,
3462
+ optionType: "indexes",
3463
+ select: (_a = runnable.result.take) != null ? _a : 1,
3464
+ options
3465
+ });
3466
+ }
3467
+ }
3468
+ return groups;
3469
+ };
3470
+ var extractSelectedVariantIds = (groups, permutation) => {
3471
+ const variantIds = [];
3472
+ for (let i = 0; i < groups.length; i++) {
3473
+ const group = groups[i];
3474
+ const choices = permutation[i];
3475
+ if (group.optionType === "indexes") {
3476
+ for (const choice of choices) {
3477
+ variantIds.push(choice.variantId);
3478
+ }
3479
+ }
3480
+ }
3481
+ return variantIds;
3482
+ };
3483
+ var applyChoicesToPageState = (state, groups, permutation) => {
3484
+ var _a;
3485
+ const newState = {
3486
+ ...state,
3487
+ components: { ...state.components },
3488
+ rules: state.rules ? { ...state.rules } : void 0
3489
+ };
3490
+ for (let i = 0; i < permutation.length; i++) {
3491
+ const group = groups[i];
3492
+ const choices = permutation[i];
3493
+ if (group.optionType === "indexes") {
3494
+ newState.components[group._id] = {
3495
+ indexes: choices.map((v) => v.index)
3496
+ };
3497
+ } else if (group.optionType === "visibility" && typeof choices[0] === "boolean") {
3498
+ newState.rules = (_a = newState.rules) != null ? _a : {};
3499
+ newState.rules[group._id] = choices[0];
3500
+ }
3501
+ }
3502
+ return newState;
3503
+ };
3504
+ var generateStatesRecursively = (dependencyMap, parentVariantId, currentState) => {
3505
+ var _a;
3506
+ const runnables = (_a = dependencyMap.get(parentVariantId)) != null ? _a : [];
3507
+ if (runnables.length === 0) {
3508
+ return [currentState];
3509
+ }
3510
+ const groups = runnablesToGroups(runnables);
3511
+ const permutations = generateAllGroupPermutations(groups);
3512
+ const results = [];
3513
+ for (const permutation of permutations) {
3514
+ const mergedState = applyChoicesToPageState(currentState, groups, permutation);
3515
+ const selectedVariantIds = extractSelectedVariantIds(groups, permutation);
3516
+ let subResults = [mergedState];
3517
+ for (const variantId of selectedVariantIds) {
3518
+ if (dependencyMap.has(variantId)) {
3519
+ subResults = subResults.flatMap(
3520
+ (state) => generateStatesRecursively(dependencyMap, variantId, state)
3521
+ );
3522
+ }
3523
+ }
3524
+ results.push(...subResults);
3525
+ }
3526
+ return results;
3527
+ };
3528
+ var generatePossiblePageStates = ({
3529
+ runnables,
3530
+ path,
3531
+ keys,
3532
+ state
3533
+ }) => {
3534
+ const dependencyMap = buildDependencyMap(runnables);
3535
+ const initialState = {
3536
+ compositionState: state,
3537
+ keys,
3538
+ releaseId: void 0,
3539
+ routePath: path,
3540
+ components: {},
3541
+ defaultConsent: void 0,
3542
+ previewMode: void 0,
3543
+ rules: void 0
3544
+ };
3545
+ const allStates = generateStatesRecursively(dependencyMap, void 0, initialState);
3546
+ return allStates.map((payload) => serializeEvaluationResult({ payload }));
3547
+ };
3548
+ function permutationsWithoutRepetition(options, k) {
3549
+ if (k === 0) return [[]];
3550
+ if (k > options.length) return [];
3551
+ const results = [];
3552
+ const used = new Array(options.length).fill(false);
3553
+ const current = [];
3554
+ function backtrack() {
3555
+ if (current.length === k) {
3556
+ results.push(current.slice());
3557
+ return;
3558
+ }
3559
+ for (let i = 0; i < options.length; i++) {
3560
+ if (used[i]) continue;
3561
+ used[i] = true;
3562
+ current.push(options[i]);
3563
+ backtrack();
3564
+ current.pop();
3565
+ used[i] = false;
3566
+ }
3567
+ }
3568
+ backtrack();
3569
+ return results;
3570
+ }
3571
+ function combineAcrossGroups(perGroupSelections) {
3572
+ return perGroupSelections.reduce(
3573
+ (acc, group) => acc.flatMap((config) => group.map((selection) => [...config, selection])),
3574
+ [[]]
3575
+ );
3576
+ }
3577
+ function generateAllGroupPermutations(groups) {
3578
+ const perGroupSelections = groups.map((g) => permutationsWithoutRepetition(g.options, g.select));
3579
+ return combineAcrossGroups(perGroupSelections);
3580
+ }
3581
+
3582
+ // src/data/client.ts
3583
+ import { getCache, waitUntil } from "@vercel/functions";
3584
+ var MANIFEST_CACHE_KEY = "uniform-manifest";
3585
+ var DefaultDataClient = class {
3586
+ async getManifest(options) {
3587
+ var _a, _b;
3588
+ const cache2 = options.source === "middleware" && ((_b = (_a = getServerConfig().experimental) == null ? void 0 : _a.middlewareRuntimeCache) != null ? _b : false) ? getCache() : null;
3589
+ if (cache2) {
3590
+ const cachedManifest = await cache2.get(MANIFEST_CACHE_KEY);
3591
+ if (cachedManifest) {
3592
+ return cachedManifest;
3593
+ }
3594
+ }
3595
+ const manifest = await getManifest({
3596
+ cache: {
3597
+ type: "force-cache"
3598
+ }
3599
+ });
3600
+ if (cache2) {
3601
+ waitUntil(
3602
+ (async () => {
3603
+ await cache2.set(MANIFEST_CACHE_KEY, manifest, {
3604
+ tags: generateManifestCacheTags()
3605
+ });
3606
+ })()
3607
+ );
3608
+ }
3609
+ return manifest;
3610
+ }
3611
+ async getRouteFromApi({
3612
+ route,
3613
+ routeClient,
3614
+ enableRuntimeCache,
3615
+ disableSwrCache
3616
+ }) {
3617
+ const newCacheKey = `uniform-route-${route.state}-${route.releaseId}-${route.path}`;
3618
+ const oldCacheKey = `uniform-route-old-${route.state}-${route.releaseId}-${route.path}`;
3619
+ const cache2 = enableRuntimeCache ? getCache() : null;
3620
+ const cacheNewRoute = async (result2) => {
3621
+ if (cache2 && result2.type === "composition") {
3622
+ const tags = generateRouteCacheTags({ path: route.path });
3623
+ await cache2.set(newCacheKey, result2, {
3624
+ tags
3625
+ });
3626
+ }
3627
+ };
3628
+ const cacheOldRoute = async (result2) => {
3629
+ if (cache2 && result2.type === "composition" && !disableSwrCache) {
3630
+ const tags = generateRouteCacheTags({ path: route.path, old: true });
3631
+ await cache2.set(oldCacheKey, result2, {
3632
+ tags
3633
+ });
3634
+ }
3635
+ };
3636
+ if (cache2) {
3637
+ const [cachedRoute, oldCachedRoute] = await Promise.all([
3638
+ cache2.get(newCacheKey),
3639
+ disableSwrCache ? null : cache2.get(oldCacheKey)
3640
+ ]);
3641
+ if (cachedRoute) {
3642
+ return cachedRoute;
3643
+ }
3644
+ if (oldCachedRoute) {
3645
+ waitUntil(
3646
+ (async () => {
3647
+ const result2 = await routeClient.getRoute(route);
3648
+ await cacheNewRoute(result2);
3649
+ })()
3650
+ );
3651
+ return oldCachedRoute;
3652
+ }
3653
+ }
3654
+ const result = await routeClient.getRoute(route);
3655
+ waitUntil(
3656
+ (async () => {
3657
+ await Promise.all([
3658
+ cacheNewRoute(result),
3659
+ disableSwrCache ? Promise.resolve() : cacheOldRoute(result)
3660
+ ]);
3661
+ })()
3662
+ );
3663
+ return result;
3664
+ }
3665
+ async getRoute(options) {
3666
+ if (options.source === "middleware") {
3667
+ return this.getRouteMiddleware(options);
3668
+ }
3669
+ return this.getRoutePageState(options);
3670
+ }
3671
+ async enhanceRoute(_options) {
3672
+ }
3673
+ async getRouteMiddleware(options) {
3674
+ var _a, _b, _c, _d;
3675
+ const routeClient = getRouteClient({
3676
+ searchParams: options.searchParams,
3677
+ draftModeEnabled: options.draftModeEnabled
3678
+ });
3679
+ const config = getServerConfig();
3680
+ const resolvedRoute = await this.getRouteFromApi({
3681
+ source: "middleware",
3682
+ route: options.route,
3683
+ routeClient,
3684
+ enableRuntimeCache: options.route.state === CANVAS_PUBLISHED_STATE && ((_b = (_a = config.experimental) == null ? void 0 : _a.middlewareRuntimeCache) != null ? _b : false),
3685
+ disableSwrCache: (_d = (_c = config.experimental) == null ? void 0 : _c.disableSwrMiddlewareCache) != null ? _d : false
3686
+ });
3687
+ if (resolvedRoute.type === "composition") {
3688
+ await this.enhanceRoute({
3689
+ source: "middleware",
3690
+ parameters: options.route,
3691
+ route: resolvedRoute,
3692
+ routeClient,
3693
+ keys: void 0
3694
+ });
3695
+ }
3696
+ return {
3697
+ route: resolvedRoute
3698
+ };
3699
+ }
3700
+ async getRoutePageState(options) {
3701
+ var _a;
3702
+ const routeClient = getRouteClient({
3703
+ cache: options.pageState.compositionState === CANVAS_PUBLISHED_STATE ? (_a = getServerConfig().canvasCache) != null ? _a : {
3704
+ type: "force-cache"
3705
+ } : {
3706
+ type: "no-cache"
3707
+ }
3708
+ });
3709
+ const originalRoute = {
3710
+ path: options.pageState.routePath,
3711
+ state: options.pageState.compositionState,
3712
+ withComponentIDs: true,
3713
+ releaseId: options.pageState.releaseId
3714
+ };
3715
+ const resolvedRoute = await this.getRouteFromApi({
3716
+ source: "pageState",
3717
+ route: originalRoute,
3718
+ routeClient,
3719
+ enableRuntimeCache: false,
3720
+ disableSwrCache: false
3721
+ });
3722
+ if (resolvedRoute.type === "composition") {
3723
+ await this.enhanceRoute({
3724
+ source: "pageState",
3725
+ parameters: originalRoute,
3726
+ route: resolvedRoute,
3727
+ routeClient,
3728
+ keys: options.pageState.keys
3729
+ });
3730
+ }
3731
+ return {
3732
+ route: resolvedRoute
3733
+ };
3734
+ }
3735
+ };
3736
+ var expireMiddlewareCacheTag = async (tag) => {
3737
+ var _a;
3738
+ const cache2 = ((_a = getServerConfig().experimental) == null ? void 0 : _a.middlewareRuntimeCache) ? getCache() : null;
3739
+ if (cache2) {
3740
+ await cache2.expireTag(tag);
3741
+ } else {
3742
+ console.warn("Middleware cache is not enabled, cannot clear cache tag", tag);
3743
+ }
3744
+ };
3745
+
3746
+ // src/data/precomputeComposition.ts
3747
+ import {
3748
+ extractPersonalizationName as extractPersonalizationName2,
3749
+ extractTestName as extractTestName2,
3750
+ resolveComponentFromPageState as resolveComponentFromPageState2
3751
+ } from "@uniformdev/next-app-router-shared";
3752
+ var shouldEvaluateTest = (test, evaluateTests) => {
3753
+ return typeof evaluateTests === "function" ? evaluateTests({
3754
+ name: extractTestName2({ component: test }),
3755
+ component: test
3756
+ }) : evaluateTests;
3757
+ };
3758
+ var shouldEvaluatePersonalization = (personalization, evaluatePersonalizations) => {
3759
+ const result = typeof evaluatePersonalizations === "function" ? evaluatePersonalizations({
3760
+ name: extractPersonalizationName2({ component: personalization }),
3761
+ component: personalization
3762
+ }) : evaluatePersonalizations;
3763
+ return result;
3764
+ };
3765
+ var precomputeComposition = ({
3766
+ pageState,
3767
+ route,
3768
+ evaluatePersonalizations = true,
3769
+ evaluateTests = true
3770
+ }) => {
3771
+ if (!route) {
3772
+ return Promise.resolve();
3773
+ }
3774
+ walkNodeTree(route.compositionApiResponse.composition, (node) => {
3775
+ var _a, _b;
3776
+ if (node.type === "component") {
3777
+ const component = node.node;
3778
+ const pageStateComponent = resolveComponentFromPageState2({
3779
+ pageState,
3780
+ componentId: component._id
3781
+ });
3782
+ if (component.type === CANVAS_TEST_TYPE && shouldEvaluateTest(component, evaluateTests)) {
3783
+ const [testIndex] = (pageStateComponent == null ? void 0 : pageStateComponent.indexes) || [];
3784
+ if (typeof testIndex === "undefined") {
3785
+ node.actions.remove();
3786
+ return;
3787
+ }
3788
+ const slotComponents = ((_a = component.slots) == null ? void 0 : _a[CANVAS_TEST_SLOT]) || [];
3789
+ const visibileComponent = slotComponents[testIndex];
3790
+ if (typeof visibileComponent !== "undefined") {
3791
+ node.actions.replace(visibileComponent);
3792
+ } else {
3793
+ node.actions.remove();
3794
+ }
3795
+ } else if (component.type === CANVAS_PERSONALIZE_TYPE && shouldEvaluatePersonalization(component, evaluatePersonalizations)) {
3796
+ const personalizeIndexes = (pageStateComponent == null ? void 0 : pageStateComponent.indexes) || [];
3797
+ if (!(personalizeIndexes == null ? void 0 : personalizeIndexes.length)) {
3798
+ node.actions.remove();
3799
+ return;
3800
+ }
3801
+ const slotComponents = ((_b = component.slots) == null ? void 0 : _b[CANVAS_PERSONALIZE_SLOT]) || [];
3802
+ const visibileComponents = personalizeIndexes.map((index) => slotComponents[index]).filter(Boolean);
3803
+ if (visibileComponents.length) {
3804
+ const [first, ...rest] = visibileComponents;
3805
+ node.actions.replace(first);
3806
+ for (const component2 of rest) {
3807
+ node.actions.insertAfter(component2);
3808
+ }
3809
+ } else {
3810
+ node.actions.remove();
3811
+ }
3812
+ }
3813
+ }
3814
+ });
3815
+ return Promise.resolve();
3816
+ };
3817
+
3818
+ // src/data/resolveRouteFromCode.ts
3819
+ import { deserializeEvaluationResult as deserializeEvaluationResult3 } from "@uniformdev/next-app-router-shared";
3820
+ var resolveRouteFromCode = async ({
3821
+ params,
3822
+ dataClient: providedDataClient
3823
+ }) => {
3824
+ const { code } = await params;
3825
+ const pageState = deserializeEvaluationResult3({ input: code });
3826
+ const dataClient = providedDataClient != null ? providedDataClient : new DefaultDataClient();
3827
+ const { route } = await dataClient.getRoute({
3828
+ source: "pageState",
3829
+ pageState
3830
+ });
3831
+ return {
3832
+ pageState,
3833
+ // suppress the route if it's not a composition
3834
+ route: (route == null ? void 0 : route.type) === "composition" ? route : void 0,
3835
+ // the code that was used to resolve the route
3836
+ code
3837
+ };
3838
+ };
3839
+
3840
+ // src/data/routes.ts
3841
+ var findRouteMatch = (routes, path) => {
3842
+ const pieces = path.split("/").filter(Boolean);
3843
+ for (const route of routes) {
3844
+ const patternPieces = route.pattern.split("/").filter(Boolean);
3845
+ if (patternPieces.length !== pieces.length) {
3846
+ continue;
3847
+ }
3848
+ let match = true;
3849
+ const params = {};
3850
+ for (let i = 0; i < patternPieces.length; i++) {
3851
+ const patternPiece = patternPieces[i];
3852
+ const piece = pieces[i];
3853
+ if (patternPiece.startsWith(":")) {
3854
+ const paramName = patternPiece.slice(1);
3855
+ params[paramName] = piece;
3856
+ } else if (patternPiece !== piece) {
3857
+ match = false;
3858
+ break;
3859
+ }
3860
+ }
3861
+ if (match) {
3862
+ return {
3863
+ route,
3864
+ params
3865
+ };
3866
+ }
3867
+ }
3868
+ return void 0;
3869
+ };
3870
+
3871
+ // src/cache/helpers.ts
3872
+ import { cache } from "react";
3873
+ var serverContext = (defaultValue) => {
3874
+ const getRef = cache(() => ({ current: defaultValue }));
3875
+ const getValue = () => getRef().current;
3876
+ const setValue = (value) => {
3877
+ getRef().current = value;
3878
+ };
3879
+ return [getValue, setValue];
3880
+ };
3881
+
3882
+ // src/cache/composition.ts
3883
+ var createCompositionCache = () => {
3884
+ const [getCompositionInternal, setCompositionInternal] = serverContext({});
3885
+ const getUniformComposition = ({ id }) => {
3886
+ const compositions = getCompositionInternal();
3887
+ if (!compositions) {
3888
+ return null;
3889
+ }
3890
+ return compositions[id];
3891
+ };
3892
+ const setUniformComposition = (composition) => {
3893
+ const compositions = getCompositionInternal();
3894
+ compositions[composition._id] = composition;
3895
+ setCompositionInternal(compositions);
3896
+ };
3897
+ const getUniformComponent = ({ compositionId, componentId }) => {
3898
+ const composition = getUniformComposition({ id: compositionId });
3899
+ if (!composition) {
3900
+ return null;
3901
+ }
3902
+ let component;
3903
+ walkNodeTree(composition, ({ node, actions }) => {
3904
+ if (node._id === componentId) {
3905
+ component = node;
3906
+ actions.stopProcessingDescendants();
3907
+ }
3908
+ });
3909
+ return component != null ? component : null;
3910
+ };
3911
+ return {
3912
+ getUniformComposition,
3913
+ setUniformComposition,
3914
+ getUniformComponent
3915
+ };
3916
+ };
3917
+ export {
3918
+ DefaultDataClient,
3919
+ UniformComposition,
3920
+ UniformPlayground,
3921
+ createCompositionCache,
3922
+ createUniformPlaygroundStaticParams,
3923
+ createUniformStaticParams,
3924
+ expireMiddlewareCacheTag,
3925
+ findRouteMatch,
3926
+ getCanvasClient,
3927
+ getManifest,
3928
+ getManifestClient,
3929
+ getProjectMapClient,
3930
+ getRouteClient,
3931
+ precomputeComposition,
3932
+ resolvePlaygroundRoute,
3933
+ resolveRouteFromCode,
3934
+ serverContext
3935
+ };