@uniformdev/next-app-router 20.81.0 → 20.81.1-alpha.7.sha-91a5b13e0c

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/{UniformComposition-DBO-oo7J.d.ts → UniformComposition-C00_YDOg.d.ts} +11 -31
  2. package/dist/{UniformComposition-le6UEB_r.d.mts → UniformComposition-DiArCpVQ.d.mts} +11 -31
  3. package/dist/cache.d.mts +24 -6
  4. package/dist/cache.d.ts +24 -6
  5. package/dist/cache.js +410 -831
  6. package/dist/cache.mjs +405 -829
  7. package/dist/compat.d.mts +2 -4
  8. package/dist/compat.d.ts +2 -4
  9. package/dist/component.d.mts +10 -1
  10. package/dist/component.d.ts +10 -1
  11. package/dist/component.js +113 -617
  12. package/dist/component.mjs +112 -640
  13. package/dist/composition-BvOM-LIW.d.mts +28 -0
  14. package/dist/composition-BvOM-LIW.d.ts +28 -0
  15. package/dist/config/default.js +0 -1
  16. package/dist/config/default.mjs +0 -1
  17. package/dist/createCachedManifestProvider-C7faGJJ8.d.mts +69 -0
  18. package/dist/createCachedManifestProvider-C7faGJJ8.d.ts +69 -0
  19. package/dist/edge.d.mts +57 -0
  20. package/dist/edge.d.ts +57 -0
  21. package/dist/edge.js +1105 -0
  22. package/dist/edge.mjs +1073 -0
  23. package/dist/handler.d.mts +15 -2
  24. package/dist/handler.d.ts +15 -2
  25. package/dist/handler.js +134 -628
  26. package/dist/handler.mjs +132 -626
  27. package/dist/index.d.mts +73 -42
  28. package/dist/index.d.ts +73 -42
  29. package/dist/index.esm.js +2032 -5629
  30. package/dist/index.js +2068 -5661
  31. package/dist/index.mjs +2032 -5629
  32. package/dist/middleware.d.mts +52 -13
  33. package/dist/middleware.d.ts +52 -13
  34. package/dist/middleware.js +410 -5746
  35. package/dist/middleware.mjs +417 -5776
  36. package/dist/resolveRouteFromPath-BHJGOpBN.d.ts +82 -0
  37. package/dist/resolveRouteFromPath-BsZUVkRX.d.mts +82 -0
  38. package/dist/vercel.d.mts +24 -0
  39. package/dist/vercel.d.ts +24 -0
  40. package/dist/vercel.js +703 -0
  41. package/dist/vercel.mjs +675 -0
  42. package/package.json +37 -9
  43. package/dist/client-BElN_CWD.d.mts +0 -786
  44. package/dist/client-BElN_CWD.d.ts +0 -786
  45. package/dist/resolveRouteFromCode-BOvjIvM2.d.ts +0 -18
  46. package/dist/resolveRouteFromCode-CuJ4JHeb.d.mts +0 -18
package/dist/edge.js ADDED
@@ -0,0 +1,1105 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/edge.ts
31
+ var edge_exports = {};
32
+ __export(edge_exports, {
33
+ UNIFORM_EDGE_ORIGIN_HEADER: () => UNIFORM_EDGE_ORIGIN_HEADER,
34
+ createCachedManifestProvider: () => createCachedManifestProvider,
35
+ handleUniformEdgeRoute: () => handleUniformEdgeRoute,
36
+ uniformEdgeMiddleware: () => uniformEdgeMiddleware
37
+ });
38
+ module.exports = __toCommonJS(edge_exports);
39
+
40
+ // src/edge/uniformEdgeMiddleware.ts
41
+ var import_context_edge = require("@uniformdev/context-edge");
42
+ var import_server2 = require("next/server");
43
+
44
+ // ../canvas/dist/index.mjs
45
+ var import_api = require("@uniformdev/context/api");
46
+ var import_api2 = require("@uniformdev/context/api");
47
+ var import_api3 = require("@uniformdev/context/api");
48
+ var import_api4 = require("@uniformdev/context/api");
49
+ var import_api5 = require("@uniformdev/context/api");
50
+ var import_api6 = require("@uniformdev/context/api");
51
+ var import_api7 = require("@uniformdev/context/api");
52
+ var import_api8 = require("@uniformdev/context/api");
53
+ var import_api9 = require("@uniformdev/context/api");
54
+ var import_api10 = require("@uniformdev/context/api");
55
+ var import_api11 = require("@uniformdev/context/api");
56
+ var import_api12 = require("@uniformdev/context/api");
57
+ var import_api13 = require("@uniformdev/context/api");
58
+ var import_api14 = require("@uniformdev/context/api");
59
+ var import_api15 = require("@uniformdev/context/api");
60
+ var import_api16 = require("@uniformdev/context/api");
61
+ var import_api17 = require("@uniformdev/context/api");
62
+ var import_api18 = require("@uniformdev/context/api");
63
+ var import_api19 = require("@uniformdev/context/api");
64
+ var import_api20 = require("@uniformdev/context/api");
65
+ var import_api21 = require("@uniformdev/context/api");
66
+ var import_api22 = require("@uniformdev/context/api");
67
+ var import_api23 = require("@uniformdev/context/api");
68
+ var import_api24 = require("@uniformdev/context/api");
69
+ var import_api25 = require("@uniformdev/context/api");
70
+ var import_api26 = require("@uniformdev/context/api");
71
+ var import_api27 = require("@uniformdev/context/api");
72
+ var __typeError = (msg) => {
73
+ throw TypeError(msg);
74
+ };
75
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
76
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
77
+ 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);
78
+ var SELECT_QUERY_PREFIX = "select.";
79
+ function appendCsv(out, key, values) {
80
+ if (values === void 0) {
81
+ return;
82
+ }
83
+ out[key] = values.join(",");
84
+ }
85
+ function projectionToQuery(spec) {
86
+ const out = {};
87
+ if (!spec) {
88
+ return out;
89
+ }
90
+ const { fields, fieldTypes, slots } = spec;
91
+ const p = SELECT_QUERY_PREFIX;
92
+ if (fields) {
93
+ appendCsv(out, `${p}fields[only]`, fields.only);
94
+ appendCsv(out, `${p}fields[except]`, fields.except);
95
+ appendCsv(out, `${p}fields[locales]`, fields.locales);
96
+ if (fields.blockDepth === "preserveAll" || typeof fields.blockDepth === "number") {
97
+ out[`${p}fields[blockDepth]`] = String(fields.blockDepth);
98
+ }
99
+ }
100
+ if (fieldTypes) {
101
+ appendCsv(out, `${p}fieldTypes[only]`, fieldTypes.only);
102
+ appendCsv(out, `${p}fieldTypes[except]`, fieldTypes.except);
103
+ }
104
+ if (slots) {
105
+ appendCsv(out, `${p}slots[only]`, slots.only);
106
+ appendCsv(out, `${p}slots[except]`, slots.except);
107
+ if (typeof slots.depth === "number") {
108
+ out[`${p}slots[depth]`] = String(slots.depth);
109
+ }
110
+ if (slots.named) {
111
+ const slotNames = Object.keys(slots.named).sort();
112
+ for (const slotName of slotNames) {
113
+ const named = slots.named[slotName];
114
+ if (named && typeof named.depth === "number") {
115
+ out[`${p}slots.${slotName}[depth]`] = String(named.depth);
116
+ }
117
+ }
118
+ }
119
+ }
120
+ return out;
121
+ }
122
+ var CANVAS_DRAFT_STATE = 0;
123
+ var CANVAS_PUBLISHED_STATE = 64;
124
+ var CANVAS_EDITOR_STATE = 63;
125
+ var CANVAS_INTERNAL_PARAM_PREFIX = "$internal_";
126
+ var CANVAS_COMPONENT_DISPLAY_NAME_PARAM = `${CANVAS_INTERNAL_PARAM_PREFIX}displayName`;
127
+ var CANVAS_HYPOTHESIS_PARAM = `${CANVAS_INTERNAL_PARAM_PREFIX}hypothesis`;
128
+ var IN_CONTEXT_EDITOR_QUERY_STRING_PARAM = "is_incontext_editing_mode";
129
+ var IN_CONTEXT_EDITOR_FORCED_SETTINGS_QUERY_STRING_PARAM = "is_incontext_editing_forced_settings";
130
+ var EDGE_MAX_CACHE_TTL = 24 * 60 * 60;
131
+ var _contentTypesUrl;
132
+ var _entriesUrl;
133
+ var _ContentClient = class _ContentClient2 extends import_api12.ApiClient {
134
+ constructor(options) {
135
+ var _a;
136
+ super(options);
137
+ this.edgeApiHost = (_a = options.edgeApiHost) != null ? _a : "https://uniform.global";
138
+ }
139
+ getContentTypes(options) {
140
+ const { projectId } = this.options;
141
+ const fetchUri = this.createUrl(__privateGet(_ContentClient2, _contentTypesUrl), { ...options, projectId });
142
+ return this.apiClient(fetchUri);
143
+ }
144
+ getEntries(options) {
145
+ const { projectId } = this.options;
146
+ const { skipDataResolution, filters, select, ...params } = options;
147
+ const rewrittenFilters = (0, import_api12.rewriteFiltersForApi)(filters);
148
+ const rewrittenSelect = projectionToQuery(select);
149
+ if (skipDataResolution) {
150
+ const url = this.createUrl(__privateGet(_ContentClient2, _entriesUrl), {
151
+ ...params,
152
+ ...rewrittenFilters,
153
+ ...rewrittenSelect,
154
+ projectId
155
+ });
156
+ return this.apiClient(url);
157
+ }
158
+ const edgeUrl = this.createUrl(
159
+ __privateGet(_ContentClient2, _entriesUrl),
160
+ { ...this.getEdgeOptions(params), ...rewrittenFilters, ...rewrittenSelect },
161
+ this.edgeApiHost
162
+ );
163
+ return this.apiClient(
164
+ edgeUrl,
165
+ this.options.disableSWR ? { headers: { "x-disable-swr": "true" } } : void 0
166
+ );
167
+ }
168
+ /** Fetches historical versions of an entry */
169
+ async getEntryHistory(options) {
170
+ const historyUrl = this.createUrl("/api/v1/entries-history", {
171
+ ...options,
172
+ projectId: this.options.projectId
173
+ });
174
+ return this.apiClient(historyUrl);
175
+ }
176
+ async upsertContentType(body, opts = {}) {
177
+ const fetchUri = this.createUrl(__privateGet(_ContentClient2, _contentTypesUrl));
178
+ if (typeof body.contentType.slugSettings === "object" && body.contentType.slugSettings !== null && Object.keys(body.contentType.slugSettings).length === 0) {
179
+ delete body.contentType.slugSettings;
180
+ }
181
+ await this.apiClient(fetchUri, {
182
+ method: "PUT",
183
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
184
+ expectNoContent: true,
185
+ headers: opts.autogenerateDataTypes ? { "x-uniform-autogenerate-data-types": "true" } : {}
186
+ });
187
+ }
188
+ async upsertEntry(body, options) {
189
+ const fetchUri = this.createUrl(__privateGet(_ContentClient2, _entriesUrl));
190
+ const headers = {};
191
+ if (options == null ? void 0 : options.ifUnmodifiedSince) {
192
+ headers["x-if-unmodified-since"] = options.ifUnmodifiedSince;
193
+ }
194
+ const { response } = await this.apiClientWithResponse(fetchUri, {
195
+ method: "PUT",
196
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
197
+ expectNoContent: true,
198
+ headers
199
+ });
200
+ return { modified: response.headers.get("x-modified-at") };
201
+ }
202
+ async deleteContentType(body) {
203
+ const fetchUri = this.createUrl(__privateGet(_ContentClient2, _contentTypesUrl));
204
+ await this.apiClient(fetchUri, {
205
+ method: "DELETE",
206
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
207
+ expectNoContent: true
208
+ });
209
+ }
210
+ async deleteEntry(body) {
211
+ const fetchUri = this.createUrl(__privateGet(_ContentClient2, _entriesUrl));
212
+ await this.apiClient(fetchUri, {
213
+ method: "DELETE",
214
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
215
+ expectNoContent: true
216
+ });
217
+ }
218
+ getEdgeOptions(options) {
219
+ const { projectId } = this.options;
220
+ const { skipDataResolution, ...params } = options;
221
+ return {
222
+ projectId,
223
+ ...params,
224
+ diagnostics: typeof options.diagnostics === "boolean" ? options.diagnostics : options.diagnostics === "no-data" ? "no-data" : void 0
225
+ };
226
+ }
227
+ };
228
+ _contentTypesUrl = /* @__PURE__ */ new WeakMap();
229
+ _entriesUrl = /* @__PURE__ */ new WeakMap();
230
+ __privateAdd(_ContentClient, _contentTypesUrl, "/api/v1/content-types");
231
+ __privateAdd(_ContentClient, _entriesUrl, "/api/v1/entries");
232
+ var _url;
233
+ var _DataTypeClient = class _DataTypeClient2 extends import_api14.ApiClient {
234
+ constructor(options) {
235
+ super(options);
236
+ }
237
+ /** Fetches a list of DataTypes for a project */
238
+ async list(options) {
239
+ const { projectId } = this.options;
240
+ const fetchUri = this.createUrl(__privateGet(_DataTypeClient2, _url), { ...options, projectId });
241
+ return await this.apiClient(fetchUri);
242
+ }
243
+ /** @deprecated Use {@link list} instead. */
244
+ async get(options) {
245
+ return this.list(options);
246
+ }
247
+ /** Updates or creates (based on id) a DataType */
248
+ async save(body) {
249
+ const fetchUri = this.createUrl(__privateGet(_DataTypeClient2, _url));
250
+ await this.apiClient(fetchUri, {
251
+ method: "PUT",
252
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
253
+ expectNoContent: true
254
+ });
255
+ }
256
+ /** @deprecated Use {@link save} instead. */
257
+ async upsert(body) {
258
+ return this.save(body);
259
+ }
260
+ /** Deletes a DataType */
261
+ async remove(body) {
262
+ const fetchUri = this.createUrl(__privateGet(_DataTypeClient2, _url));
263
+ await this.apiClient(fetchUri, {
264
+ method: "DELETE",
265
+ body: JSON.stringify({ ...body, projectId: this.options.projectId }),
266
+ expectNoContent: true
267
+ });
268
+ }
269
+ };
270
+ _url = /* @__PURE__ */ new WeakMap();
271
+ __privateAdd(_DataTypeClient, _url, "/api/v1/data-types");
272
+ var _baseUrl;
273
+ var _IntegrationPropertyEditorsClient = class _IntegrationPropertyEditorsClient2 extends import_api16.ApiClient {
274
+ constructor(options) {
275
+ super(options);
276
+ this.teamId = options.teamId;
277
+ }
278
+ /**
279
+ * Gets a list of property type and hook names for the current team, including public integrations' hooks.
280
+ */
281
+ get(options) {
282
+ const fetchUri = this.createUrl(__privateGet(_IntegrationPropertyEditorsClient2, _baseUrl), {
283
+ ...options,
284
+ teamId: this.teamId
285
+ });
286
+ return this.apiClient(fetchUri);
287
+ }
288
+ /**
289
+ * Creates or updates a custom AI property editor on a Mesh app.
290
+ */
291
+ async deploy(body) {
292
+ const fetchUri = this.createUrl(__privateGet(_IntegrationPropertyEditorsClient2, _baseUrl));
293
+ await this.apiClient(fetchUri, {
294
+ method: "PUT",
295
+ body: JSON.stringify({ ...body, teamId: this.teamId }),
296
+ expectNoContent: true
297
+ });
298
+ }
299
+ /**
300
+ * Removes a custom AI property editor from a Mesh app.
301
+ */
302
+ async delete(body) {
303
+ const fetchUri = this.createUrl(__privateGet(_IntegrationPropertyEditorsClient2, _baseUrl));
304
+ await this.apiClient(fetchUri, {
305
+ method: "DELETE",
306
+ body: JSON.stringify({ ...body, teamId: this.teamId }),
307
+ expectNoContent: true
308
+ });
309
+ }
310
+ };
311
+ _baseUrl = /* @__PURE__ */ new WeakMap();
312
+ __privateAdd(_IntegrationPropertyEditorsClient, _baseUrl, "/api/v1/integration-property-editors");
313
+ var _url2;
314
+ var _projectsUrl;
315
+ var _ProjectClient = class _ProjectClient2 extends import_api20.ApiClient {
316
+ constructor(options) {
317
+ super({ ...options, bypassCache: true });
318
+ }
319
+ /** Fetches single Project */
320
+ async get(options) {
321
+ const fetchUri = this.createUrl(__privateGet(_ProjectClient2, _url2), { ...options });
322
+ return await this.apiClient(fetchUri);
323
+ }
324
+ /**
325
+ * Fetches projects grouped by team.
326
+ * When teamId is provided, returns a single team with its projects.
327
+ * When omitted, returns all accessible teams and their projects.
328
+ */
329
+ async list(options) {
330
+ const fetchUri = this.createUrl(__privateGet(_ProjectClient2, _projectsUrl), options ? { ...options } : {});
331
+ return await this.apiClient(fetchUri);
332
+ }
333
+ /** @deprecated Use {@link list} instead. */
334
+ async getProjects(options) {
335
+ return this.list(options);
336
+ }
337
+ /** Updates or creates (based on id) a Project */
338
+ async save(body) {
339
+ const fetchUri = this.createUrl(__privateGet(_ProjectClient2, _url2));
340
+ return await this.apiClient(fetchUri, {
341
+ method: "PUT",
342
+ body: JSON.stringify({ ...body })
343
+ });
344
+ }
345
+ /** @deprecated Use {@link save} instead. */
346
+ async upsert(body) {
347
+ return this.save(body);
348
+ }
349
+ /** Deletes a Project */
350
+ async remove(body) {
351
+ const fetchUri = this.createUrl(__privateGet(_ProjectClient2, _url2));
352
+ await this.apiClient(fetchUri, {
353
+ method: "DELETE",
354
+ body: JSON.stringify({ ...body }),
355
+ expectNoContent: true
356
+ });
357
+ }
358
+ /** @deprecated Use {@link remove} instead. */
359
+ async delete(body) {
360
+ return this.remove(body);
361
+ }
362
+ };
363
+ _url2 = /* @__PURE__ */ new WeakMap();
364
+ _projectsUrl = /* @__PURE__ */ new WeakMap();
365
+ __privateAdd(_ProjectClient, _url2, "/api/v1/project");
366
+ __privateAdd(_ProjectClient, _projectsUrl, "/api/v1/projects");
367
+
368
+ // src/middleware.ts
369
+ var import_context = require("@uniformdev/context");
370
+ var import_next_app_router_shared = require("@uniformdev/next-app-router-shared");
371
+ var import_headers = require("next/headers");
372
+ var import_server = require("next/server");
373
+
374
+ // src/config/helpers.ts
375
+ var import_resolved = __toESM(require("@uniformdev/next-app-router/config/resolved"));
376
+ var getServerConfig = () => {
377
+ return import_resolved.default;
378
+ };
379
+ var getDefaultConsent = () => {
380
+ if (typeof import_resolved.default.defaultConsent === "boolean") {
381
+ return import_resolved.default.defaultConsent;
382
+ }
383
+ return false;
384
+ };
385
+ var getQuirkSerialization = () => {
386
+ if (typeof import_resolved.default.quirkSerialization === "boolean") {
387
+ return import_resolved.default.quirkSerialization;
388
+ }
389
+ return true;
390
+ };
391
+ var getPlaygroundPath = () => {
392
+ if (typeof import_resolved.default.playgroundPath === "string") {
393
+ return import_resolved.default.playgroundPath;
394
+ }
395
+ return "/uniform/playground";
396
+ };
397
+
398
+ // src/data/routes.ts
399
+ var findRouteMatch = (routes, path) => {
400
+ const pieces = path.split("/").filter(Boolean);
401
+ for (const route of routes) {
402
+ const patternPieces = route.pattern.split("/").filter(Boolean);
403
+ if (patternPieces.length !== pieces.length) {
404
+ continue;
405
+ }
406
+ let match = true;
407
+ const params = {};
408
+ for (let i = 0; i < patternPieces.length; i++) {
409
+ const patternPiece = patternPieces[i];
410
+ const piece = pieces[i];
411
+ if (patternPiece.startsWith(":")) {
412
+ const paramName = patternPiece.slice(1);
413
+ params[paramName] = piece;
414
+ } else if (patternPiece !== piece) {
415
+ match = false;
416
+ break;
417
+ }
418
+ }
419
+ if (match) {
420
+ return {
421
+ route,
422
+ params
423
+ };
424
+ }
425
+ }
426
+ return void 0;
427
+ };
428
+
429
+ // src/utils/draft.ts
430
+ var isDraftModeEnabled = ({
431
+ draftModeEnabled
432
+ }) => {
433
+ return draftModeEnabled;
434
+ };
435
+ var isIncontextEditingEnabled = ({
436
+ isDraftModeEnabled: isDraftModeEnabled2,
437
+ searchParams
438
+ }) => {
439
+ if (!isDraftModeEnabled2) {
440
+ return false;
441
+ }
442
+ const containsKey = searchParams.has(IN_CONTEXT_EDITOR_QUERY_STRING_PARAM);
443
+ return containsKey;
444
+ };
445
+ var isDevelopmentEnvironment = () => {
446
+ return process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test";
447
+ };
448
+
449
+ // src/utils/quirks.ts
450
+ var buildQuirksFromHeaders = (headers) => {
451
+ const headerToQuirkKey = {
452
+ "x-vercel-ip-country": "vc-country",
453
+ "x-vercel-ip-country-region": "vc-region",
454
+ "x-vercel-ip-city": "vc-city"
455
+ };
456
+ return Object.entries(headerToQuirkKey).reduce((acc, [headerName, quirkKey]) => {
457
+ const value = headers.get(headerName);
458
+ if (value) {
459
+ acc[quirkKey] = value;
460
+ }
461
+ return acc;
462
+ }, {});
463
+ };
464
+
465
+ // src/middleware.ts
466
+ var resolveUniformRequest = async ({
467
+ request,
468
+ ...options
469
+ }) => {
470
+ const draftModeEnabled = (await (0, import_headers.draftMode)()).isEnabled;
471
+ if (draftModeEnabled && isPlaygroundPath(request.nextUrl.pathname)) {
472
+ return handlePlaygroundRequest({ request, options });
473
+ }
474
+ return resolveRouteRequest({ request, draftModeEnabled, options });
475
+ };
476
+ var isPlaygroundPath = (path) => {
477
+ const { playgroundPath } = getServerConfig();
478
+ if (!playgroundPath) {
479
+ return false;
480
+ }
481
+ const PLAYGROUND_ID = "playground";
482
+ const match = findRouteMatch(
483
+ [
484
+ {
485
+ id: PLAYGROUND_ID,
486
+ pattern: playgroundPath
487
+ }
488
+ ],
489
+ path
490
+ );
491
+ return (match == null ? void 0 : match.route.id) === PLAYGROUND_ID;
492
+ };
493
+ var handlePlaygroundRequest = async ({
494
+ request,
495
+ options
496
+ }) => {
497
+ var _a, _b;
498
+ const id = request.nextUrl.searchParams.get("id");
499
+ if (!id) {
500
+ return {
501
+ type: "response",
502
+ response: import_server.NextResponse.json({ error: "No id provided" }, { status: 400 })
503
+ };
504
+ }
505
+ const playgroundPath = getPlaygroundPath();
506
+ const pageState = {
507
+ routePath: id,
508
+ compositionState: CANVAS_EDITOR_STATE,
509
+ keys: void 0,
510
+ releaseId: (_a = options.release) == null ? void 0 : _a.id,
511
+ defaultConsent: determineDefaultConsent({
512
+ serverConfig: getServerConfig(),
513
+ defaultConsent: options.defaultConsent
514
+ }),
515
+ previewMode: determinePreviewMode({
516
+ searchParams: request.nextUrl.searchParams,
517
+ isDraftModeEnabled: true
518
+ }),
519
+ locale: options.locale
520
+ };
521
+ const code = (0, import_next_app_router_shared.serializeEvaluationResult)({ payload: pageState });
522
+ const destination = await ((_b = options.rewriteDestinationPath) == null ? void 0 : _b.call(options, { code, pageState, source: "playground" })) || `${playgroundPath}${playgroundPath.endsWith("/") ? "" : "/"}${code}`;
523
+ return {
524
+ type: "response",
525
+ response: import_server.NextResponse.rewrite(new URL(destination, request.nextUrl.origin))
526
+ };
527
+ };
528
+ var resolveRouteRequest = async ({
529
+ request,
530
+ draftModeEnabled,
531
+ options
532
+ }) => {
533
+ var _a, _b, _c, _d, _e;
534
+ const releaseId = (_b = (_a = options.release) == null ? void 0 : _a.id) != null ? _b : draftModeEnabled ? request.nextUrl.searchParams.get("releaseId") || void 0 : void 0;
535
+ const requestPath = (_d = await ((_c = options.rewriteRequestPath) == null ? void 0 : _c.call(options, {
536
+ request,
537
+ url: new URL(request.url)
538
+ }))) != null ? _d : {
539
+ path: `${request.nextUrl.pathname}${request.nextUrl.search}`
540
+ };
541
+ const defaultConsent = determineDefaultConsent({
542
+ serverConfig: getServerConfig(),
543
+ defaultConsent: options.defaultConsent
544
+ });
545
+ const pageState = {
546
+ routePath: buildRoutePath({ path: requestPath.path, queryStrings: options.queryStrings }),
547
+ compositionState: determineCompositionState({
548
+ searchParams: request.nextUrl.searchParams,
549
+ draftModeEnabled
550
+ }),
551
+ keys: requestPath.keys,
552
+ releaseId,
553
+ defaultConsent,
554
+ previewMode: determinePreviewMode({
555
+ searchParams: request.nextUrl.searchParams,
556
+ isDraftModeEnabled: draftModeEnabled
557
+ }),
558
+ locale: options.locale
559
+ };
560
+ const code = (0, import_next_app_router_shared.serializeEvaluationResult)({ payload: pageState });
561
+ const destination = await ((_e = options.rewriteDestinationPath) == null ? void 0 : _e.call(options, { code, pageState, source: "route" })) || `/uniform/${code}`;
562
+ const quirks = {
563
+ ...buildQuirksFromHeaders(request.headers),
564
+ ...options.quirks
565
+ };
566
+ const headers = new Headers();
567
+ if (Object.keys(quirks).length > 0) {
568
+ headers.append(
569
+ "Set-Cookie",
570
+ `${import_next_app_router_shared.UNIFORM_MIDDLEWARE_QUIRK_COOKIE_NAME}=${JSON.stringify(quirks)}; Path=/; SameSite=Lax; Max-Age=10`
571
+ );
572
+ }
573
+ const createContext = async ({ manifest }) => {
574
+ var _a2, _b2, _c2, _d2;
575
+ const context = new import_context.Context({
576
+ manifest,
577
+ defaultConsent: defaultConsent != null ? defaultConsent : getDefaultConsent(),
578
+ transitionStore: new import_context.CookieTransitionDataStore({
579
+ serverCookieValue: (_b2 = (_a2 = request.cookies.get(import_context.UNIFORM_DEFAULT_COOKIE_NAME)) == null ? void 0 : _a2.value) != null ? _b2 : "",
580
+ experimental_quirksEnabled: getQuirkSerialization(),
581
+ quirkCookieValue: (_d2 = (_c2 = request.cookies.get(import_context.UNIFORM_DEFAULT_QUIRK_COOKIE_NAME)) == null ? void 0 : _c2.value) != null ? _d2 : ""
582
+ })
583
+ });
584
+ await context.update({
585
+ url: new URL(request.nextUrl.href),
586
+ cookies: Object.fromEntries(request.cookies.getAll().map((cookie) => [cookie.name, cookie.value])),
587
+ quirks
588
+ });
589
+ return context;
590
+ };
591
+ return {
592
+ type: "rewrite",
593
+ destination,
594
+ pageState,
595
+ code,
596
+ headers,
597
+ draftModeEnabled,
598
+ createContext
599
+ };
600
+ };
601
+ var buildRoutePath = ({
602
+ path,
603
+ queryStrings
604
+ }) => {
605
+ const [pathname = "", search] = path.split("?");
606
+ if (!search || !queryStrings) {
607
+ return pathname;
608
+ }
609
+ const patterns = Object.keys(queryStrings);
610
+ const match = findRouteMatch(
611
+ patterns.map((pattern) => ({ id: pattern, pattern })),
612
+ pathname
613
+ );
614
+ const allowed = match ? queryStrings[match.route.id] : void 0;
615
+ if (!(allowed == null ? void 0 : allowed.length)) {
616
+ return pathname;
617
+ }
618
+ const requestSearchParams = new URLSearchParams(search);
619
+ const searchParams = new URLSearchParams();
620
+ [...allowed].sort().forEach((name) => {
621
+ const value = requestSearchParams.get(name);
622
+ if (value !== null) {
623
+ searchParams.set(name, value);
624
+ }
625
+ });
626
+ return searchParams.size ? `${pathname}?${searchParams.toString()}` : pathname;
627
+ };
628
+ var determineCompositionState = ({
629
+ searchParams,
630
+ draftModeEnabled
631
+ }) => {
632
+ if (!draftModeEnabled) {
633
+ return CANVAS_PUBLISHED_STATE;
634
+ }
635
+ return isIncontextEditingEnabled({ isDraftModeEnabled: draftModeEnabled, searchParams }) ? CANVAS_EDITOR_STATE : CANVAS_DRAFT_STATE;
636
+ };
637
+ var determineDefaultConsent = ({
638
+ serverConfig,
639
+ defaultConsent
640
+ }) => {
641
+ return defaultConsent !== serverConfig.defaultConsent ? defaultConsent : void 0;
642
+ };
643
+ var determinePreviewMode = ({
644
+ searchParams,
645
+ isDraftModeEnabled: isDraftModeEnabled2
646
+ }) => {
647
+ if (!isDraftModeEnabled2) {
648
+ return void 0;
649
+ }
650
+ const queryStringSettings = searchParams.get(IN_CONTEXT_EDITOR_FORCED_SETTINGS_QUERY_STRING_PARAM);
651
+ let previewSettings = void 0;
652
+ if (queryStringSettings) {
653
+ try {
654
+ previewSettings = JSON.parse(queryStringSettings);
655
+ } catch (e) {
656
+ }
657
+ }
658
+ if (previewSettings == null ? void 0 : previewSettings.isVisualEditingDisabled) {
659
+ return "preview";
660
+ }
661
+ const isInContextEditingEnabled = isIncontextEditingEnabled({ isDraftModeEnabled: isDraftModeEnabled2, searchParams });
662
+ if (isInContextEditingEnabled) {
663
+ return "editor";
664
+ }
665
+ return void 0;
666
+ };
667
+
668
+ // src/edge/uniformEdgeMiddleware.ts
669
+ var UNIFORM_EDGE_ORIGIN_HEADER = "x-uniform-edge-origin";
670
+ var uniformEdgeMiddleware = (options) => {
671
+ return async (request, event) => {
672
+ return handleUniformEdgeRoute({
673
+ request,
674
+ waitUntil: event ? (promise) => event.waitUntil(promise) : void 0,
675
+ ...options
676
+ });
677
+ };
678
+ };
679
+ var handleUniformEdgeRoute = async ({
680
+ request,
681
+ manifest,
682
+ onError,
683
+ waitUntil = ignorePromise,
684
+ ...options
685
+ }) => {
686
+ var _a;
687
+ if (request.headers.has(UNIFORM_EDGE_ORIGIN_HEADER)) {
688
+ return import_server2.NextResponse.next();
689
+ }
690
+ const result = await resolveUniformRequest({ request, ...options });
691
+ if (result.type === "response") {
692
+ return result.response;
693
+ }
694
+ const destination = new URL(result.destination, request.nextUrl.origin);
695
+ if (result.draftModeEnabled || !isDocumentRequest(request)) {
696
+ return import_server2.NextResponse.rewrite(destination, { headers: result.headers });
697
+ }
698
+ const [originResponse, context] = await Promise.all([
699
+ fetch(destination, {
700
+ // A page that calls `redirect()` answers with a redirect, which belongs to the visitor.
701
+ redirect: "manual",
702
+ headers: {
703
+ cookie: (_a = request.headers.get("cookie")) != null ? _a : "",
704
+ accept: "text/html",
705
+ // Node's fetch decompresses the body but keeps the header, so ask for plain HTML.
706
+ "accept-encoding": "identity",
707
+ [UNIFORM_EDGE_ORIGIN_HEADER]: "1"
708
+ }
709
+ }),
710
+ resolveManifest({ manifest, waitUntil, onError }).then(
711
+ (resolved) => result.createContext({ manifest: resolved })
712
+ )
713
+ ]);
714
+ const headers = new Headers(originResponse.headers);
715
+ result.headers.forEach((value, key) => {
716
+ headers.append(key, value);
717
+ });
718
+ if (originResponse.status >= 300 && originResponse.status < 400) {
719
+ return new Response(originResponse.body, {
720
+ status: originResponse.status,
721
+ statusText: originResponse.statusText,
722
+ headers
723
+ });
724
+ }
725
+ headers.delete("content-length");
726
+ headers.delete("content-encoding");
727
+ headers.set("cache-control", "private, no-store");
728
+ return new Response(transformBody({ body: originResponse.body, context, onError }), {
729
+ status: originResponse.status,
730
+ statusText: originResponse.statusText,
731
+ headers
732
+ });
733
+ };
734
+ var ignorePromise = (promise) => {
735
+ promise.catch(() => {
736
+ });
737
+ };
738
+ var EMPTY_MANIFEST = { project: {} };
739
+ var resolveManifest = async ({
740
+ manifest,
741
+ waitUntil,
742
+ onError
743
+ }) => {
744
+ if (typeof manifest !== "function") {
745
+ return manifest;
746
+ }
747
+ try {
748
+ return await manifest({ waitUntil });
749
+ } catch (error) {
750
+ onError == null ? void 0 : onError({ error });
751
+ return EMPTY_MANIFEST;
752
+ }
753
+ };
754
+ var isDocumentRequest = (request) => {
755
+ const accept = request.headers.get("accept");
756
+ return request.method === "GET" && !request.headers.has("rsc") && !request.headers.has("next-router-prefetch") && (!accept || accept.includes("text/html") || accept.includes("*/*"));
757
+ };
758
+ var transformBody = ({
759
+ body,
760
+ context,
761
+ onError
762
+ }) => {
763
+ if (!body) {
764
+ return null;
765
+ }
766
+ const reader = body.getReader();
767
+ const { readable, writable } = new TransformStream();
768
+ const writer = writable.getWriter();
769
+ writer.closed.catch(() => reader.cancel()).catch(() => {
770
+ });
771
+ void (0, import_context_edge.transformEdgeStream)({
772
+ context,
773
+ decoder: new TextDecoder(),
774
+ encoder: new TextEncoder(),
775
+ reader: {
776
+ read: async () => {
777
+ await writer.ready.catch(() => {
778
+ });
779
+ const { done, value } = await reader.read();
780
+ return { done, value };
781
+ }
782
+ },
783
+ writer: {
784
+ // Write and close fail only after the visitor disconnects, which `writer.closed` handles.
785
+ write: (value) => {
786
+ writer.write(value).catch(() => {
787
+ });
788
+ },
789
+ close: () => {
790
+ return writer.close().catch(() => {
791
+ });
792
+ }
793
+ },
794
+ onError
795
+ });
796
+ return readable;
797
+ };
798
+
799
+ // src/clients/manifest.ts
800
+ var import_server_only = require("server-only");
801
+ var import_api29 = require("@uniformdev/context/api");
802
+
803
+ // src/utils/env.ts
804
+ var env = {
805
+ getProjectId: () => {
806
+ return process.env.UNIFORM_PROJECT_ID;
807
+ },
808
+ getApiKey: () => {
809
+ return process.env.UNIFORM_API_KEY;
810
+ },
811
+ getApiHost: () => {
812
+ return process.env.UNIFORM_API_HOST || process.env.UNIFORM_CLI_BASE_URL;
813
+ },
814
+ getEdgeApiHost: () => {
815
+ return process.env.UNIFORM_EDGE_API_HOST || process.env.UNIFORM_CLI_BASE_EDGE_URL;
816
+ }
817
+ };
818
+
819
+ // src/clients/cache.ts
820
+ var isSpecificCacheMode = (options) => {
821
+ return "cache" in options;
822
+ };
823
+ var isStateCacheMode = (options) => {
824
+ return "state" in options;
825
+ };
826
+ var isDetectCacheMode = (options) => {
827
+ return "searchParams" in options && "draftModeEnabled" in options;
828
+ };
829
+ var resolveManifestCache = (options) => {
830
+ return resolveCache({
831
+ options
832
+ });
833
+ };
834
+ var resolveCache = ({
835
+ options
836
+ }) => {
837
+ let cache = void 0;
838
+ if (options) {
839
+ if (isSpecificCacheMode(options)) {
840
+ cache = options.cache;
841
+ } else if (isStateCacheMode(options)) {
842
+ if (options.state === CANVAS_DRAFT_STATE || options.state === CANVAS_EDITOR_STATE) {
843
+ cache = {
844
+ type: "no-cache",
845
+ bypassCache: true
846
+ };
847
+ }
848
+ } else if (isDetectCacheMode(options)) {
849
+ const { disabled } = shouldCacheBeDisabled(options);
850
+ if (disabled) {
851
+ cache = {
852
+ type: "no-cache",
853
+ bypassCache: true
854
+ };
855
+ }
856
+ }
857
+ }
858
+ return cache || {
859
+ type: "force-cache"
860
+ };
861
+ };
862
+ var shouldCacheBeDisabled = (options) => {
863
+ if (isDraftModeEnabled(options)) {
864
+ return { disabled: true, reason: "DRAFT" };
865
+ }
866
+ if (isIncontextEditingEnabled({
867
+ isDraftModeEnabled: options.draftModeEnabled,
868
+ searchParams: options.searchParams
869
+ })) {
870
+ return { disabled: true, reason: "INCONTEXT" };
871
+ }
872
+ if (isDevelopmentEnvironment()) {
873
+ return { disabled: true, reason: "DEV" };
874
+ }
875
+ return {
876
+ disabled: false,
877
+ reason: void 0
878
+ };
879
+ };
880
+ var determineFetchCacheOptions = (mode) => {
881
+ let cache = void 0;
882
+ let revalidate = void 0;
883
+ if (mode.type === "revalidate") {
884
+ cache = void 0;
885
+ revalidate = mode.interval;
886
+ } else {
887
+ cache = mode.type;
888
+ }
889
+ return {
890
+ cache,
891
+ revalidate
892
+ };
893
+ };
894
+
895
+ // src/clients/retry.ts
896
+ var import_api28 = require("@uniformdev/context/api");
897
+ function createThrottler(limit, interval) {
898
+ let available = limit;
899
+ let refillScheduled = false;
900
+ const waiting = [];
901
+ function scheduleRefill() {
902
+ if (refillScheduled) return;
903
+ refillScheduled = true;
904
+ setTimeout(() => {
905
+ refillScheduled = false;
906
+ available = limit;
907
+ while (available > 0 && waiting.length > 0) {
908
+ available--;
909
+ const next = waiting.shift();
910
+ next();
911
+ }
912
+ if (waiting.length > 0) {
913
+ scheduleRefill();
914
+ }
915
+ }, interval);
916
+ }
917
+ return async function throttle(fn) {
918
+ if (available > 0) {
919
+ available--;
920
+ if (!refillScheduled) {
921
+ scheduleRefill();
922
+ }
923
+ return fn();
924
+ }
925
+ return new Promise((resolve, reject) => {
926
+ waiting.push(() => {
927
+ fn().then(resolve, reject);
928
+ });
929
+ scheduleRefill();
930
+ });
931
+ };
932
+ }
933
+ function createLimiter(concurrency) {
934
+ let active = 0;
935
+ const queue = [];
936
+ return async function limit(fn) {
937
+ return new Promise((resolve, reject) => {
938
+ const run = async () => {
939
+ active++;
940
+ try {
941
+ const result = await fn();
942
+ resolve(result);
943
+ } catch (error) {
944
+ reject(error);
945
+ } finally {
946
+ active--;
947
+ if (queue.length > 0) {
948
+ const next = queue.shift();
949
+ next();
950
+ }
951
+ }
952
+ };
953
+ if (active < concurrency) {
954
+ run();
955
+ } else {
956
+ queue.push(run);
957
+ }
958
+ });
959
+ };
960
+ }
961
+ async function retry(fn, options) {
962
+ let lastError;
963
+ let delay = 1e3;
964
+ for (let attempt = 1; attempt <= options.retries + 1; attempt++) {
965
+ try {
966
+ return await fn();
967
+ } catch (error) {
968
+ lastError = error;
969
+ const attemptError = Object.assign(error, { attemptNumber: attempt });
970
+ if (options.onFailedAttempt) {
971
+ await options.onFailedAttempt(attemptError);
972
+ }
973
+ if (attempt > options.retries) {
974
+ throw error;
975
+ }
976
+ await new Promise((resolve) => setTimeout(resolve, delay));
977
+ delay *= options.factor;
978
+ }
979
+ }
980
+ throw lastError;
981
+ }
982
+ function createLimitPolicy({
983
+ throttle = { interval: 1e3, limit: 10 },
984
+ retry: retryOptions = { retries: 1, factor: 1.66 },
985
+ limit = 10
986
+ }) {
987
+ const throttler = throttle ? createThrottler(throttle.limit, throttle.interval) : null;
988
+ const limiter = limit ? createLimiter(limit) : null;
989
+ return function limitPolicy(func) {
990
+ let currentFunc = async () => await func();
991
+ if (throttler) {
992
+ const throttleFunc = currentFunc;
993
+ currentFunc = () => throttler(throttleFunc);
994
+ }
995
+ if (limiter) {
996
+ const limitFunc = currentFunc;
997
+ currentFunc = () => limiter(limitFunc);
998
+ }
999
+ if (retryOptions) {
1000
+ const retryFunc = currentFunc;
1001
+ currentFunc = () => retry(retryFunc, {
1002
+ ...retryOptions,
1003
+ onFailedAttempt: async (error) => {
1004
+ if (retryOptions.onFailedAttempt) {
1005
+ await retryOptions.onFailedAttempt(error);
1006
+ }
1007
+ if (error instanceof import_api28.ApiClientError && typeof error.statusCode === "number" && error.statusCode >= 400 && error.statusCode < 500 && error.statusCode !== 429 && error.statusCode !== 408) {
1008
+ throw error;
1009
+ }
1010
+ }
1011
+ });
1012
+ }
1013
+ return currentFunc();
1014
+ };
1015
+ }
1016
+
1017
+ // src/clients/tags.ts
1018
+ var generateManifestCacheTags = () => {
1019
+ return ["manifest"];
1020
+ };
1021
+
1022
+ // src/clients/manifest.ts
1023
+ var getManifestClient = (options) => {
1024
+ const cache = resolveManifestCache(options);
1025
+ const manifestClient = new import_api29.ManifestClient({
1026
+ apiHost: env.getApiHost(),
1027
+ apiKey: env.getApiKey(),
1028
+ projectId: env.getProjectId(),
1029
+ limitPolicy: createLimitPolicy({
1030
+ limit: 6
1031
+ }),
1032
+ fetch: (req, init) => {
1033
+ const { cache: fetchCache, revalidate } = determineFetchCacheOptions(cache);
1034
+ return fetch(req, {
1035
+ ...init,
1036
+ headers: {
1037
+ ...init == null ? void 0 : init.headers,
1038
+ "x-bypass-cache": typeof cache.bypassCache !== "undefined" ? cache.bypassCache.toString() : "false"
1039
+ },
1040
+ cache: fetchCache,
1041
+ next: {
1042
+ revalidate,
1043
+ tags: generateManifestCacheTags()
1044
+ }
1045
+ });
1046
+ }
1047
+ });
1048
+ return manifestClient;
1049
+ };
1050
+
1051
+ // src/manifest/createCachedManifestProvider.ts
1052
+ var createCachedManifestProvider = ({
1053
+ cache,
1054
+ fallback,
1055
+ ttl = 3600,
1056
+ maxAge = 10,
1057
+ fetchManifest = fetchPublishedManifest
1058
+ } = {}) => {
1059
+ let current;
1060
+ let pending;
1061
+ const load = async ({ waitUntil }) => {
1062
+ var _a;
1063
+ const key = `uniform-manifest-${(_a = env.getProjectId()) != null ? _a : ""}`;
1064
+ const cached = await (cache == null ? void 0 : cache.get(key).catch(() => void 0));
1065
+ if (isManifest(cached)) {
1066
+ return cached;
1067
+ }
1068
+ const manifest = await fetchManifest();
1069
+ if (cache) {
1070
+ waitUntil(cache.set(key, manifest, { ttl, tags: generateManifestCacheTags() }).catch(() => {
1071
+ }));
1072
+ }
1073
+ return manifest;
1074
+ };
1075
+ return async (options) => {
1076
+ var _a;
1077
+ if (current && Date.now() - current.loadedAt < maxAge * 1e3) {
1078
+ return current.manifest;
1079
+ }
1080
+ pending != null ? pending : pending = load(options).then((manifest) => {
1081
+ current = { manifest, loadedAt: Date.now() };
1082
+ return manifest;
1083
+ }).finally(() => {
1084
+ pending = void 0;
1085
+ });
1086
+ try {
1087
+ return await pending;
1088
+ } catch (error) {
1089
+ const known = (_a = current == null ? void 0 : current.manifest) != null ? _a : fallback;
1090
+ if (known) {
1091
+ return known;
1092
+ }
1093
+ throw error;
1094
+ }
1095
+ };
1096
+ };
1097
+ var fetchPublishedManifest = () => getManifestClient({ cache: { type: "no-store" } }).get({ preview: false });
1098
+ var isManifest = (value) => typeof value === "object" && value !== null && "project" in value;
1099
+ // Annotate the CommonJS export names for ESM import in node:
1100
+ 0 && (module.exports = {
1101
+ UNIFORM_EDGE_ORIGIN_HEADER,
1102
+ createCachedManifestProvider,
1103
+ handleUniformEdgeRoute,
1104
+ uniformEdgeMiddleware
1105
+ });