payload-live-preview 2.0.5 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +143 -39
  2. package/dist/adapters/astro/FragmentBridge.astro +25 -0
  3. package/dist/adapters/astro/PreviewBoundary.astro +2 -4
  4. package/dist/adapters/astro/RichText.astro +26 -5
  5. package/dist/adapters/astro/index.d.ts +41 -9
  6. package/dist/adapters/astro/index.js +1 -1
  7. package/dist/adapters/astro/index.js.map +1 -1
  8. package/dist/adapters/astro/middleware-entry.d.ts +3 -3
  9. package/dist/adapters/astro/middleware-entry.js +1 -1
  10. package/dist/adapters/astro/middleware-entry.js.map +1 -1
  11. package/dist/adapters/nextjs/index.d.ts +17 -12
  12. package/dist/adapters/nextjs/index.js +1 -1
  13. package/dist/adapters/nextjs/index.js.map +1 -1
  14. package/dist/adapters/nuxt/index.d.ts +11 -6
  15. package/dist/adapters/nuxt/index.js +1 -1
  16. package/dist/adapters/nuxt/index.js.map +1 -1
  17. package/dist/adapters/nuxt/module.d.ts +64 -13
  18. package/dist/adapters/nuxt/module.js +1 -1
  19. package/dist/adapters/nuxt/module.js.map +1 -1
  20. package/dist/adapters/react/index.d.ts +11 -7
  21. package/dist/adapters/react/index.js +1 -1
  22. package/dist/adapters/react/index.js.map +1 -1
  23. package/dist/adapters/sveltekit/index.d.ts +10 -5
  24. package/dist/adapters/sveltekit/index.js +1 -1
  25. package/dist/adapters/sveltekit/index.js.map +1 -1
  26. package/dist/adapters/vue/index.d.ts +10 -7
  27. package/dist/adapters/vue/index.js +1 -1
  28. package/dist/adapters/vue/index.js.map +1 -1
  29. package/dist/annotate.d.ts +15 -2
  30. package/dist/annotate.js.map +1 -1
  31. package/dist/client.cjs +1 -1
  32. package/dist/client.cjs.map +1 -1
  33. package/dist/client.d.cts +367 -266
  34. package/dist/client.d.ts +367 -266
  35. package/dist/client.js +1 -1
  36. package/dist/client.js.map +1 -1
  37. package/dist/codegen-cli.js.map +1 -1
  38. package/dist/codegen.cjs.map +1 -1
  39. package/dist/codegen.d.cts +7 -1
  40. package/dist/codegen.d.ts +7 -1
  41. package/dist/codegen.js.map +1 -1
  42. package/dist/core.cjs +1 -1
  43. package/dist/core.cjs.map +1 -1
  44. package/dist/core.d.cts +544 -392
  45. package/dist/core.d.ts +544 -392
  46. package/dist/core.js +1 -1
  47. package/dist/core.js.map +1 -1
  48. package/dist/doctor-cli.d.ts +1 -1
  49. package/dist/doctor-cli.js +1 -1
  50. package/dist/doctor-cli.js.map +1 -1
  51. package/dist/doctor.d.ts +2 -2
  52. package/dist/doctor.js +1 -1
  53. package/dist/doctor.js.map +1 -1
  54. package/dist/{document-session-BfBfLVpg.d.ts → document-session-DWi9H3Qk.d.ts} +7 -0
  55. package/dist/{fragment-endpoint-DATKU183.d.ts → fragment-endpoint-B2qcRw5T.d.ts} +22 -7
  56. package/dist/fragment.cjs +1 -1
  57. package/dist/fragment.cjs.map +1 -1
  58. package/dist/fragment.d.cts +37 -16
  59. package/dist/fragment.d.ts +37 -16
  60. package/dist/fragment.js +1 -1
  61. package/dist/fragment.js.map +1 -1
  62. package/dist/index.cjs +1 -1
  63. package/dist/index.cjs.map +1 -1
  64. package/dist/index.d.cts +598 -400
  65. package/dist/index.d.ts +598 -400
  66. package/dist/index.js +1 -1
  67. package/dist/index.js.map +1 -1
  68. package/dist/lean.cjs +1 -1
  69. package/dist/lean.cjs.map +1 -1
  70. package/dist/lean.d.cts +5 -2
  71. package/dist/lean.d.ts +5 -2
  72. package/dist/lean.js +1 -1
  73. package/dist/lean.js.map +1 -1
  74. package/dist/lexical.cjs +1 -1
  75. package/dist/lexical.cjs.map +1 -1
  76. package/dist/lexical.d.cts +32 -11
  77. package/dist/lexical.d.ts +32 -11
  78. package/dist/lexical.js +1 -1
  79. package/dist/lexical.js.map +1 -1
  80. package/dist/{locals-CNUGYbA_.d.ts → locals-B1mF3aTb.d.ts} +1 -1
  81. package/dist/{middleware-CWObDO37.d.ts → middleware-BGobLN9P.d.ts} +11 -5
  82. package/dist/migrate.js +1 -1
  83. package/dist/migrate.js.map +1 -1
  84. package/dist/{options-uHKrDM2U.d.ts → options-Cm8fC7dj.d.ts} +31 -1
  85. package/dist/payload.cjs +1 -1
  86. package/dist/payload.cjs.map +1 -1
  87. package/dist/payload.d.cts +18 -2
  88. package/dist/payload.d.ts +18 -2
  89. package/dist/payload.js +1 -1
  90. package/dist/payload.js.map +1 -1
  91. package/dist/plugin.cjs +2 -0
  92. package/dist/plugin.cjs.map +1 -0
  93. package/dist/plugin.d.cts +30 -0
  94. package/dist/plugin.d.ts +30 -0
  95. package/dist/plugin.js +2 -0
  96. package/dist/plugin.js.map +1 -0
  97. package/dist/plugins.cjs +1 -1
  98. package/dist/plugins.cjs.map +1 -1
  99. package/dist/plugins.d.cts +102 -29
  100. package/dist/plugins.d.ts +102 -29
  101. package/dist/plugins.js +1 -1
  102. package/dist/plugins.js.map +1 -1
  103. package/dist/{probe-Bzm4fYFL.d.ts → probe-DGPDsnbj.d.ts} +6 -2
  104. package/dist/server.cjs +1 -1
  105. package/dist/server.cjs.map +1 -1
  106. package/dist/server.d.cts +43 -4
  107. package/dist/server.d.ts +43 -4
  108. package/dist/server.js +1 -1
  109. package/dist/server.js.map +1 -1
  110. package/dist/structural.cjs +2 -2
  111. package/dist/structural.cjs.map +1 -1
  112. package/dist/structural.d.cts +61 -13
  113. package/dist/structural.d.ts +61 -13
  114. package/dist/structural.js +2 -2
  115. package/dist/structural.js.map +1 -1
  116. package/package.json +35 -4
@@ -77,13 +77,13 @@ declare const DIAGNOSTIC_CODES: Readonly<{
77
77
  readonly StartupFailed: "LP0605";
78
78
  /** Sending the ready handshake failed. */
79
79
  readonly ReadyFailed: "LP0606";
80
- /** The page declared hydration, but no React commit or Vue mount came within the cap; the runtime started without waiting. */
80
+ /** The page declared hydration, but no React commit, Vue mount or SvelteKit mount came within the cap; the runtime started without waiting. */
81
81
  readonly HydrationWaitTimedOut: "LP0607";
82
82
  /** The audit found no runtime in a response that carried preview intent. */
83
83
  readonly AuditRuntimeMissing: "LP0701";
84
84
  /** The preview response declares no `frame-ancestors`. */
85
85
  readonly AuditNoFrameAncestors: "LP0702";
86
- /** `X-Frame-Options` forbids framing, which no CSP can undo; `SAMEORIGIN` forbids it from another origin only. */
86
+ /** `X-Frame-Options` forbids framing on a response that declares no `frame-ancestors`; `SAMEORIGIN` forbids it from another origin only. */
87
87
  readonly AuditFrameOptionsBlocks: "LP0703";
88
88
  /** Binding attributes are served to anonymous visitors. */
89
89
  readonly AuditBindingsExposed: "LP0704";
@@ -111,6 +111,10 @@ declare const DIAGNOSTIC_CODES: Readonly<{
111
111
  readonly UnboundChangeRefresh: "LP0807";
112
112
  /** `onUnfaithfulPatch: 'escalate'` found no route or fragment strategy to hand an unfaithful patch to; the page keeps it. */
113
113
  readonly EscalationUnavailable: "LP0808";
114
+ /** A fragment inserted an Astro island the page cannot start: it never loaded the island element or that client directive. */
115
+ readonly IslandStartUnavailable: "LP0809";
116
+ /** The host's route refresh returned no promise, so the revision was re-applied before the host committed. */
117
+ readonly RouteRefreshUnconfirmed: "LP0810";
114
118
  /** A readiness row is not yet at its 2.0 value; `pll doctor --v2` reports it. */
115
119
  readonly V2ReadinessGap: "LP0709";
116
120
  /** The preview runtime is served to anonymous visitors, not only inside the admin frame. */
@@ -131,6 +135,8 @@ type DiagnosticCode = (typeof DIAGNOSTIC_CODES)[keyof typeof DIAGNOSTIC_CODES];
131
135
  type UpdateSource = 'patch' | 'fragment' | 'route';
132
136
  /** Marks a server-rendered boundary; the value is the registry id the server may render. @internal */
133
137
  declare const FRAGMENT_ATTRIBUTE = "data-payload-fragment";
138
+ /** Distinguishes several boundaries of one registry id; unique among siblings. @internal */
139
+ declare const FRAGMENT_KEY_ATTRIBUTE = "data-payload-fragment-key";
134
140
  /** One revision, as a strategy sees it, with the runtime capabilities it may use. */
135
141
  interface FragmentContext {
136
142
  readonly root: ParentNode;
@@ -144,9 +150,9 @@ interface FragmentContext {
144
150
  readonly signal: AbortSignal;
145
151
  /** Whether this revision is still the current one. */
146
152
  readonly isCurrent: () => boolean;
147
- /** Morph server-rendered HTML into a boundary (Trusted Types and the keyed morph apply). */
153
+ /** Morph server-rendered HTML into a boundary; no-op after supersession (Trusted Types and the keyed morph apply). */
148
154
  readonly morph: (boundary: Element, html: string) => void;
149
- /** Patch the boundary's own bindings from this revision — the deterministic fallback. */
155
+ /** Patch the boundary's owned bindings from this revision; no-op after supersession. */
150
156
  readonly patch: (boundary: Element) => void;
151
157
  /** Debug log through the runtime's logger, with the diagnostic code. */
152
158
  readonly log: (code: DiagnosticCode, detail: string) => void;
@@ -171,8 +177,13 @@ interface FragmentStrategy {
171
177
  interface RouteContext {
172
178
  readonly revision: number;
173
179
  readonly receivedAt: number;
174
- /** Aborted when a newer revision arrives or the runtime stops. */
180
+ /** Aborted when a newer revision asks for a refresh of its own, a navigation commits, or the runtime stops. */
175
181
  readonly signal: AbortSignal;
182
+ /**
183
+ * Whether the refresh may still land. A newer revision that asks for no
184
+ * refresh of its own does not end it: the route is the server's, so the
185
+ * refresh lands for that revision, which the runtime then re-applies.
186
+ */
176
187
  readonly isCurrent: () => boolean;
177
188
  readonly log: (code: DiagnosticCode, detail: string) => void;
178
189
  /**
@@ -185,18 +196,30 @@ interface RouteContext {
185
196
  readonly retryAfter?: (delayMs: number) => void;
186
197
  }
187
198
  /**
188
- * What one refresh did. `refused` is the strategy's own brake and not a
189
- * failure — it is counted separately, because a number that mixes a planned
190
- * pause with a broken request cannot be read.
199
+ * What one refresh did. `refreshed` asserts that the strategy rendered the
200
+ * current unsaved revision. `partial` completed a render whose data source was
201
+ * not proven current; the runtime still reapplies every binding it can reach.
202
+ * `refused` is the strategy's own brake and not a failure.
191
203
  */
192
- type RouteOutcome = 'refreshed' | 'failed' | 'refused' | 'superseded';
204
+ type RouteOutcome = 'refreshed' | 'partial' | 'failed' | 'refused' | 'superseded';
205
+ /** What the runtime tells a route planner about the update it plans for. */
206
+ interface RoutePlanContext {
207
+ /**
208
+ * Whether an element belongs to the update: always `true` without
209
+ * `scopeBindingsByOwner`, otherwise only inside the document the update
210
+ * names. A marker outside it asks for nothing.
211
+ */
212
+ readonly inScope: (element: Element) => boolean;
213
+ }
193
214
  /**
194
215
  * Whether a revision needs the whole route re-rendered, and how. After a
195
- * refresh the runtime rescans and re-applies the revision, so the unsaved
196
- * state lands on the fresh markup.
216
+ * refresh the runtime rescans and re-applies the revision, so reachable
217
+ * unsaved bindings land on the fresh markup. The runtime always passes
218
+ * `context`; a planner written before it existed still works, but plans for
219
+ * markers of every document.
197
220
  */
198
221
  interface RouteStrategy {
199
- readonly plan: (root: ParentNode, changedFields: ReadonlySet<string>) => boolean;
222
+ readonly plan: (root: ParentNode, changedFields: ReadonlySet<string>, context?: RoutePlanContext) => boolean;
200
223
  readonly refresh: (context: RouteContext) => Promise<RouteOutcome>;
201
224
  }
202
225
  interface StrategyHandlers {
@@ -213,8 +236,6 @@ declare function resolveStrategy(element: Element): UpdateSource | undefined;
213
236
 
214
237
  /** Fragment boundaries: how a `data-payload-fragment` element is read and which ones an update touches. */
215
238
 
216
- /** Distinguishes several boundaries of one registry id; unique among siblings. @internal */
217
- declare const FRAGMENT_KEY_ATTRIBUTE = "data-payload-fragment-key";
218
239
  /** @internal */
219
240
  interface FragmentBoundary {
220
241
  readonly element: Element;
@@ -361,7 +382,7 @@ interface FragmentResponseBody {
361
382
  };
362
383
  }
363
384
  /** Shape check for a request body; `null` when it is not one. @internal */
364
- declare function parseFragmentRequest(value: unknown): FragmentRequestBody | null;
385
+ declare function parseFragmentRequest(value: unknown, maxFieldDepth?: number): FragmentRequestBody | null;
365
386
  /** Shape check for a response body; `null` when it is not one. @internal */
366
387
  declare function parseFragmentResponse(value: unknown): FragmentResponseBody | null;
367
388
 
@@ -383,4 +404,4 @@ declare function fragmentStrategyFrom(handler: FragmentHandler): FragmentStrateg
383
404
  /** The strategy for a fragment endpoint: hand it to the runtime as `strategies.fragment`. */
384
405
  declare function createFragmentStrategy(options: FragmentStrategyOptions): FragmentStrategy;
385
406
 
386
- export { DIAGNOSTIC_CODES, type DiagnosticCode, FRAGMENT_ATTRIBUTE, FRAGMENT_KEY_ATTRIBUTE, FRAGMENT_PROTOCOL_VERSION, FRAGMENT_VERSION_HEADER, type FragmentBoundary, type FragmentContext, type FragmentHandler, type FragmentOutcome, type FragmentReport, type FragmentRequestBody, type FragmentResponseBody, type FragmentStrategy, type FragmentStrategyOptions, ROUTE_REFRESH_HEADER, type RouteContext, type RouteOutcome, type RouteStrategy, type RouteStrategyOptions, type StrategyHandlers, type StrategyRequest, type UpdateSource, collectFragmentBoundaries, createFragmentHandler, createFragmentStrategy, createRouteStrategy, describeBoundary, fragmentStrategyFrom, isRouteBound, parseFragmentRequest, parseFragmentResponse, resolveStrategy };
407
+ export { DIAGNOSTIC_CODES, type DiagnosticCode, FRAGMENT_ATTRIBUTE, FRAGMENT_KEY_ATTRIBUTE, FRAGMENT_PROTOCOL_VERSION, FRAGMENT_VERSION_HEADER, type FragmentBoundary, type FragmentContext, type FragmentHandler, type FragmentOutcome, type FragmentReport, type FragmentRequestBody, type FragmentResponseBody, type FragmentStrategy, type FragmentStrategyOptions, ROUTE_REFRESH_HEADER, type RouteContext, type RouteOutcome, type RoutePlanContext, type RouteStrategy, type RouteStrategyOptions, type StrategyHandlers, type StrategyRequest, type UpdateSource, collectFragmentBoundaries, createFragmentHandler, createFragmentStrategy, createRouteStrategy, describeBoundary, fragmentStrategyFrom, isRouteBound, parseFragmentRequest, parseFragmentResponse, resolveStrategy };
@@ -77,13 +77,13 @@ declare const DIAGNOSTIC_CODES: Readonly<{
77
77
  readonly StartupFailed: "LP0605";
78
78
  /** Sending the ready handshake failed. */
79
79
  readonly ReadyFailed: "LP0606";
80
- /** The page declared hydration, but no React commit or Vue mount came within the cap; the runtime started without waiting. */
80
+ /** The page declared hydration, but no React commit, Vue mount or SvelteKit mount came within the cap; the runtime started without waiting. */
81
81
  readonly HydrationWaitTimedOut: "LP0607";
82
82
  /** The audit found no runtime in a response that carried preview intent. */
83
83
  readonly AuditRuntimeMissing: "LP0701";
84
84
  /** The preview response declares no `frame-ancestors`. */
85
85
  readonly AuditNoFrameAncestors: "LP0702";
86
- /** `X-Frame-Options` forbids framing, which no CSP can undo; `SAMEORIGIN` forbids it from another origin only. */
86
+ /** `X-Frame-Options` forbids framing on a response that declares no `frame-ancestors`; `SAMEORIGIN` forbids it from another origin only. */
87
87
  readonly AuditFrameOptionsBlocks: "LP0703";
88
88
  /** Binding attributes are served to anonymous visitors. */
89
89
  readonly AuditBindingsExposed: "LP0704";
@@ -111,6 +111,10 @@ declare const DIAGNOSTIC_CODES: Readonly<{
111
111
  readonly UnboundChangeRefresh: "LP0807";
112
112
  /** `onUnfaithfulPatch: 'escalate'` found no route or fragment strategy to hand an unfaithful patch to; the page keeps it. */
113
113
  readonly EscalationUnavailable: "LP0808";
114
+ /** A fragment inserted an Astro island the page cannot start: it never loaded the island element or that client directive. */
115
+ readonly IslandStartUnavailable: "LP0809";
116
+ /** The host's route refresh returned no promise, so the revision was re-applied before the host committed. */
117
+ readonly RouteRefreshUnconfirmed: "LP0810";
114
118
  /** A readiness row is not yet at its 2.0 value; `pll doctor --v2` reports it. */
115
119
  readonly V2ReadinessGap: "LP0709";
116
120
  /** The preview runtime is served to anonymous visitors, not only inside the admin frame. */
@@ -131,6 +135,8 @@ type DiagnosticCode = (typeof DIAGNOSTIC_CODES)[keyof typeof DIAGNOSTIC_CODES];
131
135
  type UpdateSource = 'patch' | 'fragment' | 'route';
132
136
  /** Marks a server-rendered boundary; the value is the registry id the server may render. @internal */
133
137
  declare const FRAGMENT_ATTRIBUTE = "data-payload-fragment";
138
+ /** Distinguishes several boundaries of one registry id; unique among siblings. @internal */
139
+ declare const FRAGMENT_KEY_ATTRIBUTE = "data-payload-fragment-key";
134
140
  /** One revision, as a strategy sees it, with the runtime capabilities it may use. */
135
141
  interface FragmentContext {
136
142
  readonly root: ParentNode;
@@ -144,9 +150,9 @@ interface FragmentContext {
144
150
  readonly signal: AbortSignal;
145
151
  /** Whether this revision is still the current one. */
146
152
  readonly isCurrent: () => boolean;
147
- /** Morph server-rendered HTML into a boundary (Trusted Types and the keyed morph apply). */
153
+ /** Morph server-rendered HTML into a boundary; no-op after supersession (Trusted Types and the keyed morph apply). */
148
154
  readonly morph: (boundary: Element, html: string) => void;
149
- /** Patch the boundary's own bindings from this revision — the deterministic fallback. */
155
+ /** Patch the boundary's owned bindings from this revision; no-op after supersession. */
150
156
  readonly patch: (boundary: Element) => void;
151
157
  /** Debug log through the runtime's logger, with the diagnostic code. */
152
158
  readonly log: (code: DiagnosticCode, detail: string) => void;
@@ -171,8 +177,13 @@ interface FragmentStrategy {
171
177
  interface RouteContext {
172
178
  readonly revision: number;
173
179
  readonly receivedAt: number;
174
- /** Aborted when a newer revision arrives or the runtime stops. */
180
+ /** Aborted when a newer revision asks for a refresh of its own, a navigation commits, or the runtime stops. */
175
181
  readonly signal: AbortSignal;
182
+ /**
183
+ * Whether the refresh may still land. A newer revision that asks for no
184
+ * refresh of its own does not end it: the route is the server's, so the
185
+ * refresh lands for that revision, which the runtime then re-applies.
186
+ */
176
187
  readonly isCurrent: () => boolean;
177
188
  readonly log: (code: DiagnosticCode, detail: string) => void;
178
189
  /**
@@ -185,18 +196,30 @@ interface RouteContext {
185
196
  readonly retryAfter?: (delayMs: number) => void;
186
197
  }
187
198
  /**
188
- * What one refresh did. `refused` is the strategy's own brake and not a
189
- * failure — it is counted separately, because a number that mixes a planned
190
- * pause with a broken request cannot be read.
199
+ * What one refresh did. `refreshed` asserts that the strategy rendered the
200
+ * current unsaved revision. `partial` completed a render whose data source was
201
+ * not proven current; the runtime still reapplies every binding it can reach.
202
+ * `refused` is the strategy's own brake and not a failure.
191
203
  */
192
- type RouteOutcome = 'refreshed' | 'failed' | 'refused' | 'superseded';
204
+ type RouteOutcome = 'refreshed' | 'partial' | 'failed' | 'refused' | 'superseded';
205
+ /** What the runtime tells a route planner about the update it plans for. */
206
+ interface RoutePlanContext {
207
+ /**
208
+ * Whether an element belongs to the update: always `true` without
209
+ * `scopeBindingsByOwner`, otherwise only inside the document the update
210
+ * names. A marker outside it asks for nothing.
211
+ */
212
+ readonly inScope: (element: Element) => boolean;
213
+ }
193
214
  /**
194
215
  * Whether a revision needs the whole route re-rendered, and how. After a
195
- * refresh the runtime rescans and re-applies the revision, so the unsaved
196
- * state lands on the fresh markup.
216
+ * refresh the runtime rescans and re-applies the revision, so reachable
217
+ * unsaved bindings land on the fresh markup. The runtime always passes
218
+ * `context`; a planner written before it existed still works, but plans for
219
+ * markers of every document.
197
220
  */
198
221
  interface RouteStrategy {
199
- readonly plan: (root: ParentNode, changedFields: ReadonlySet<string>) => boolean;
222
+ readonly plan: (root: ParentNode, changedFields: ReadonlySet<string>, context?: RoutePlanContext) => boolean;
200
223
  readonly refresh: (context: RouteContext) => Promise<RouteOutcome>;
201
224
  }
202
225
  interface StrategyHandlers {
@@ -213,8 +236,6 @@ declare function resolveStrategy(element: Element): UpdateSource | undefined;
213
236
 
214
237
  /** Fragment boundaries: how a `data-payload-fragment` element is read and which ones an update touches. */
215
238
 
216
- /** Distinguishes several boundaries of one registry id; unique among siblings. @internal */
217
- declare const FRAGMENT_KEY_ATTRIBUTE = "data-payload-fragment-key";
218
239
  /** @internal */
219
240
  interface FragmentBoundary {
220
241
  readonly element: Element;
@@ -361,7 +382,7 @@ interface FragmentResponseBody {
361
382
  };
362
383
  }
363
384
  /** Shape check for a request body; `null` when it is not one. @internal */
364
- declare function parseFragmentRequest(value: unknown): FragmentRequestBody | null;
385
+ declare function parseFragmentRequest(value: unknown, maxFieldDepth?: number): FragmentRequestBody | null;
365
386
  /** Shape check for a response body; `null` when it is not one. @internal */
366
387
  declare function parseFragmentResponse(value: unknown): FragmentResponseBody | null;
367
388
 
@@ -383,4 +404,4 @@ declare function fragmentStrategyFrom(handler: FragmentHandler): FragmentStrateg
383
404
  /** The strategy for a fragment endpoint: hand it to the runtime as `strategies.fragment`. */
384
405
  declare function createFragmentStrategy(options: FragmentStrategyOptions): FragmentStrategy;
385
406
 
386
- export { DIAGNOSTIC_CODES, type DiagnosticCode, FRAGMENT_ATTRIBUTE, FRAGMENT_KEY_ATTRIBUTE, FRAGMENT_PROTOCOL_VERSION, FRAGMENT_VERSION_HEADER, type FragmentBoundary, type FragmentContext, type FragmentHandler, type FragmentOutcome, type FragmentReport, type FragmentRequestBody, type FragmentResponseBody, type FragmentStrategy, type FragmentStrategyOptions, ROUTE_REFRESH_HEADER, type RouteContext, type RouteOutcome, type RouteStrategy, type RouteStrategyOptions, type StrategyHandlers, type StrategyRequest, type UpdateSource, collectFragmentBoundaries, createFragmentHandler, createFragmentStrategy, createRouteStrategy, describeBoundary, fragmentStrategyFrom, isRouteBound, parseFragmentRequest, parseFragmentResponse, resolveStrategy };
407
+ export { DIAGNOSTIC_CODES, type DiagnosticCode, FRAGMENT_ATTRIBUTE, FRAGMENT_KEY_ATTRIBUTE, FRAGMENT_PROTOCOL_VERSION, FRAGMENT_VERSION_HEADER, type FragmentBoundary, type FragmentContext, type FragmentHandler, type FragmentOutcome, type FragmentReport, type FragmentRequestBody, type FragmentResponseBody, type FragmentStrategy, type FragmentStrategyOptions, ROUTE_REFRESH_HEADER, type RouteContext, type RouteOutcome, type RoutePlanContext, type RouteStrategy, type RouteStrategyOptions, type StrategyHandlers, type StrategyRequest, type UpdateSource, collectFragmentBoundaries, createFragmentHandler, createFragmentStrategy, createRouteStrategy, describeBoundary, fragmentStrategyFrom, isRouteBound, parseFragmentRequest, parseFragmentResponse, resolveStrategy };
package/dist/fragment.js CHANGED
@@ -1,2 +1,2 @@
1
- function e(e,t){const n=new AbortController;let r=!1;const o=()=>{n.abort()};e.addEventListener("abort",o,{once:!0});const i=setTimeout(()=>{r=!0,n.abort()},t);return{signal:n.signal,timedOut:()=>r,dispose:()=>{clearTimeout(i),e.removeEventListener("abort",o)}}}function t(e){return e instanceof Error?e.message:String(e)}var n="data-payload-island";function r(e){return function(e){return"astro-island"===e.tagName.toLowerCase()||e.hasAttribute(n)}(e)&&!("patch"===e.getAttribute(n))}function isInsideIsland(e){let t=e;for(;null!==t;){if(r(t))return!0;t=t.parentElement}return!1}function o(e){if(null==e)return[];const t=/* @__PURE__ */new Set,n=[];for(const r of e.split(/[\s,]+/)){const e=r.trim();0===e.length||t.has(e)||(t.add(e),n.push(e))}return n}var i="data-payload-fragment";function a(e){const t=e.getAttribute("data-payload-strategy");return null!==t&&t.length>0?"patch"===t||"fragment"===t||"route"===t?t:void 0:null!==function(e){return e.closest(`[${i}]`)}(e)?"fragment":null!==e.closest("head")?"route":"patch"}var s="data-payload-fragment-key";function l(e){const t=e.getAttribute(i);if(null===t||0===t.length)return null;const n=e.getAttribute(s);return{element:e,id:t,key:null===n||0===n.length?void 0:n,dependsOn:o(e.getAttribute("data-payload-depends"))}}function u(e,t){const n=[];for(const r of e.querySelectorAll(`[${i}]`)){const e=l(r);null===e||isInsideIsland(r)||e.dependsOn.length>0&&!e.dependsOn.some(e=>t.has(e))||n.push(e)}return n}var c=1,d="x-payload-fragment-version";function f(e,t){if(t>12||"object"!=typeof e||null===e)return t;let n=t;for(const r of Object.values(e))if(n=Math.max(n,f(r,t+1)),n>12)break;return n}function g(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function h(e){if(!g(e))return null;const t=e.fragment;if("string"!=typeof t||!/^[a-z][a-z0-9-]{0,63}$/iu.test(t))return null;const n=e.key;if(void 0!==n&&("string"!=typeof n||n.length>128))return null;const r=e.route;if("string"!=typeof r||!r.startsWith("/")||r.length>2048)return null;const o=e.search;if("string"!=typeof o||o.length>4096||""!==o&&!o.startsWith("?"))return null;const i=e.revision;if("number"!=typeof i||!Number.isInteger(i)||i<0)return null;const a=[];for(const t of["locale","collectionSlug","globalSlug"]){const n=e[t];if(void 0!==n){if("string"!=typeof n||n.length>128)return null;a.push(n)}else a.push(void 0)}const[s,l,u]=a,c=e.fields;return!g(c)||f(c,0)>12?null:{fragment:t,..."string"==typeof n?{key:n}:{},route:r,search:o,revision:i,...void 0!==s?{locale:s}:{},...void 0!==l?{collectionSlug:l}:{},...void 0!==u?{globalSlug:u}:{},fields:c}}function p(e){if(!g(e))return null;const{html:t,boundary:n,revision:r,metadata:o}=e;return"string"!=typeof t?null:g(n)&&"string"==typeof n.id?void 0!==n.key&&"string"!=typeof n.key||"number"!=typeof r?null:g(o)&&"string"==typeof o.renderedAt&&"string"==typeof o.renderer?e:null:null}var m={status:"superseded"};function y(e,t){return{status:"failed",code:e,reason:t}}function b(n){const r=function(e){const t=()=>{throw new TypeError('createFragmentStrategy: endpoint must be a same-origin path starting with "/"')};if(("string"!=typeof e||!e.startsWith("/")||e.startsWith("//")||e.includes("\\"))&&t(),"undefined"!=typeof location){let n;try{n=new URL(e,location.href)}catch{n=void 0}n?.origin!==location.origin&&t()}return e}(n.endpoint),o=n.timeoutMs??5e3,i=n.maxResponseBytes??524288,a=function(e){let t=0;const n=[];return async r=>{t<e?t+=1:await new Promise(e=>{n.push(e)});try{return await r()}finally{(()=>{const e=n.shift();void 0===e?t-=1:e()})()}}}(Math.max(1,n.maxConcurrent??4)),s=/* @__PURE__ */new Map;return(l,u)=>{const c=`${u.id} ${u.key??""} ${String(l.revision)}`,f=s.get(c);if(void 0!==f)return f;const g=a(()=>async function(a,s){const l=()=>a.signal.aborted;if(l())return m;const u=n.location??location,c=function(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(t[n]=r);return t}({fragment:s.id,key:s.key,route:u.pathname,search:u.search,revision:a.revision,locale:a.locale,collectionSlug:a.collectionSlug,globalSlug:a.globalSlug,fields:a.fields}),f=e(a.signal,o),g=e=>l()?m:f.timedOut()?y("LP0801",`timeout after ${String(o)} ms`):y("LP0801",t(e));try{let e;try{e=await(n.fetch??fetch)(r,{method:"POST",credentials:"same-origin",headers:{...n.headers,accept:"application/json","content-type":"application/json",[d]:String(1)},body:JSON.stringify(c),signal:f.signal})}catch(e){return g(e)}if(l())return m;if(401===e.status||403===e.status)return y("LP0803",`endpoint refused the preview (${String(e.status)})`);if(!e.ok)return y("LP0801",`endpoint answered ${String(e.status)}`);const t=e.headers.get("content-type")??"";if(!t.toLowerCase().startsWith("application/json"))return y("LP0802",`unexpected content type "${t}"`);if(Number(e.headers.get("content-length")??"0")>i)return y("LP0802","response exceeds the size limit");let u,h;try{u=await async function(e,t,n){const r=e.body;if("object"!=typeof(o=r)||null===o||"function"!=typeof o.getReader){const n=await e.text();return(new TextEncoder).encode(n).byteLength>t?null:n}var o;const i=r.getReader(),a=()=>{i.cancel().catch(()=>{})};n.addEventListener("abort",a,{once:!0});const s=new TextDecoder;let l="",u=0;try{for(;;){const{done:e,value:n}=await i.read();if(e)break;if(u+=n.byteLength,u>t)return a(),null;l+=s.decode(n,{stream:!0})}}finally{n.removeEventListener("abort",a)}return l+s.decode()}(e,i,f.signal)}catch(e){return g(e)}if(l())return m;if(f.timedOut())return y("LP0801",`timeout after ${String(o)} ms`);if(null===u)return y("LP0802","response exceeds the size limit");try{h=JSON.parse(u)}catch{return y("LP0802","response is not JSON")}const b=p(h);return null===b?y("LP0802","response has the wrong shape"):b.boundary.id!==s.id?y("LP0802","response is for another boundary"):b.revision!==a.revision?m:{status:"rendered",html:b.html,metadata:b.metadata}}finally{f.dispose()}}(l,u));s.set(c,g);const h=()=>{s.get(c)===g&&s.delete(c)};return g.then(h,h),g}}var v=Object.freeze({NoTrustedOrigin:"LP0101",ReferrerOnlyTrust:"LP0102",PluginIncompatible:"LP0103",ProfileFeatureOmitted:"LP0104",OrphanField:"LP0201",UnattributableUpdate:"LP0202",UnboundField:"LP0203",VisibilityGateDeferred:"LP0301",UnsafeAttributeWrite:"LP0401",TextTargetHasChildren:"LP0402",MissingArrayTemplate:"LP0403",StructuralItemUnkeyed:"LP0404",StructuralDuplicateKey:"LP0405",StructuralUnstableKeys:"LP0406",UnsupportedStrategy:"LP0407",UnknownValueFormat:"LP0408",SanitizerDroppedAttribute:"LP0409",UnrenderedBlockKept:"LP0410",UnfaithfulPatch:"LP0411",ServerFormatReplaced:"LP0412",UnrenderedBlockLost:"LP0413",MessageRejected:"LP0501",TokenRejected:"LP0502",ProtocolShapeUnknown:"LP0503",HandlerThrew:"LP0601",TransformThrew:"LP0602",RendererThrew:"LP0603",StartupFailed:"LP0605",ReadyFailed:"LP0606",HydrationWaitTimedOut:"LP0607",AuditRuntimeMissing:"LP0701",AuditNoFrameAncestors:"LP0702",AuditFrameOptionsBlocks:"LP0703",AuditBindingsExposed:"LP0704",AuditGateThresholdExceeded:"LP0705",AuditUnownedBindings:"LP0706",AuditNoBindings:"LP0707",AuditNotAPage:"LP0708",FragmentRequestFailed:"LP0801",FragmentResponseInvalid:"LP0802",FragmentUnauthorized:"LP0803",FragmentSuperseded:"LP0804",RouteRefreshLoop:"LP0805",FragmentStrategyUnavailable:"LP0806",UnboundChangeRefresh:"LP0807",EscalationUnavailable:"LP0808",V2ReadinessGap:"LP0709",RuntimeOnPublicPage:"LP0710"}),L="data-payload-owned",P=/* @__PURE__ */new Set(["open","value","checked","selected"]);function A(e,t){for(const n of t.keyAttributes){const t=e.getAttribute(n);if(null!==t&&t.length>0)return`${n}=${t}`}}function S(e){if(e.tagName.toLowerCase().includes("-"))return!0;if(e.hasAttribute(n)||e.hasAttribute(L))return!0;const t=e.getAttribute("contenteditable");return null!==t&&"false"!==t}function w(e,t,n){if(!function(e,t){return e.tagName===t.tagName&&e.namespaceURI===t.namespaceURI&&!S(e)&&!S(t)}(e,t))return t;const r=function(e){const t=e.ownerDocument.activeElement;if(!(t instanceof HTMLElement&&e.contains(t)))return null;return{element:t,selection:t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement?[t.selectionStart,t.selectionEnd]:null}}(e);return function(e,t){for(const n of Array.from(e.attributes))t.hasAttribute(n.name)||P.has(n.name.toLowerCase())||e.removeAttribute(n.name);for(const n of Array.from(t.attributes))e.getAttribute(n.name)!==n.value&&e.setAttribute(n.name,n.value)}(e,t),!0!==n.retainChildrenOf?.(e,t)&&function(e,t,n){const r=function(e,t){const n=/* @__PURE__ */new Map;let r;for(const o of Array.from(e.children)){const e=A(o,t);void 0!==e&&(n.has(e)?r??=e.slice(e.indexOf("=")+1):n.set(e,o))}return void 0!==r&&t.onDuplicateKey?.(e,r),n}(e,n),o=new Set(r.values()),i=Array.from(e.childNodes).filter(e=>!o.has(e)),a=/* @__PURE__ */new Set,s=/* @__PURE__ */new Set,l=Array.from(t.childNodes);let u=e.firstChild,c=0;for(let t=0;t<l.length;t+=1){const o=l[t];let d=null,f=o instanceof Element?A(o,n):void 0;if(void 0!==f&&s.has(f)&&(f=void 0),void 0!==f){s.add(f);const e=r.get(f);if(void 0!==e&&!a.has(e)&&(d=k(e,o,n)===e?e:null,null===d)){e.replaceWith(o),a.add(o),u=o.nextSibling;continue}}else{for(;c<i.length;){const r=i[c];if(c+=1,!a.has(r)){if(E(r,o)){d=k(r,o,n)===r?r:null,null===d&&(e.replaceChild(o,r),a.add(o),u=o.nextSibling);break}if(r instanceof Element){const n=l[t+1];if(!(o instanceof Element)||void 0!==n&&E(r,n)){c-=1;break}e.replaceChild(o,r),a.add(o),u=o.nextSibling;break}if(!(o instanceof Element)){e.replaceChild(o,r),a.add(o),u=o.nextSibling;break}}}if(null===d&&a.has(o))continue}const g=d??o;for(a.add(g);null!==u&&u!==g&&!a.has(u)&&T(u);)u=u.nextSibling;g!==u&&e.insertBefore(g,u),u=g.nextSibling}for(const t of Array.from(e.childNodes))a.has(t)||t.remove()}(e,t,n),function(e){if(null===e)return;const{element:t,selection:n}=e;if(t.ownerDocument.activeElement!==t&&t.isConnected)try{t.focus({preventScroll:!0});const[e,r]=n??[null,null];null!==e&&null!==r&&t.setSelectionRange(e,r)}catch{}}(r),e}function k(e,t,n){return e instanceof Element&&t instanceof Element?S(e)&&S(t)?e:w(e,t,n):(e.nodeValue!==t.nodeValue&&(e.nodeValue=t.nodeValue),e)}function T(e){return e.nodeType===Node.TEXT_NODE&&0===(e.nodeValue??"").trim().length}function E(e,t){return e.nodeType===t.nodeType&&(!(e instanceof Element&&t instanceof Element)||e.tagName===t.tagName&&e.namespaceURI===t.namespaceURI)}var x="data-payload-strategy",O="data-payload-field",R="x-payload-live-preview";function N(e){const t=e.getAttribute(x);return null!==t?"route"===t:null!==e.closest("head")}function $(e){const t=e.getAttribute(O),n=o(e.getAttribute("data-payload-depends"));return null===t||0===t.length?n:[t,...n]}function U(e){if("META"===e.tagName){const t=e.getAttribute("name")??e.getAttribute("property");return null===t?null:`meta:${t}`}return"LINK"===e.tagName&&"canonical"===e.getAttribute("rel")?"link:canonical":null}function C(n={}){const r=n.timeoutMs??8e3,o=n.minIntervalMs??1e3;let a=-1/0;return{plan(e,t){for(const n of e.querySelectorAll(`[${O}], [${x}="route"]`)){if(!N(n))continue;const e=$(n);if(0===e.length||e.some(e=>t.has(e)))return!0}return!1},async refresh(l){const u=Date.now(),c=o-(u-a);if(c>0)return l.retryAfter?.(c),l.log("LP0805",`route refresh for revision ${String(l.revision)} refused: the previous one was ${String(u-a)} ms ago`),"refused";a=u;const d=n.document??document,f=n.location??location,g=n.window??window,h=e(l.signal,r),p=e=>{if(l.signal.aborted)return"superseded";const n=h.timedOut()?`route refresh timed out after ${String(r)} ms`:t(e);return l.log("LP0801",n),"failed"};try{const e=("undefined"==typeof window?void 0:window)?.__livePreviewRouteRefresh;if(void 0!==e){try{await e()}catch(e){return p(e)}return l.isCurrent()?"refreshed":"superseded"}let t;try{t=await(n.fetch??fetch)(f.href,{method:"GET",credentials:"same-origin",cache:"no-store",headers:{accept:"text/html",[R]:"route"},signal:h.signal})}catch(e){return p(e)}if(l.signal.aborted)return"superseded";if(!t.ok||!(t.headers.get("content-type")??"").includes("text/html"))return l.log("LP0802",`route answered ${String(t.status)} ${t.headers.get("content-type")??""}`),"failed";try{const e=await t.text();if(!l.isCurrent())return"superseded";const n=(new DOMParser).parseFromString(e,"text/html"),r=g.scrollX,o=g.scrollY;return function(e,t){t.title!==e.title&&(e.title=t.title);const n=/* @__PURE__ */new Map;for(const t of e.head.querySelectorAll("meta, link")){const e=U(t);null===e||n.has(e)||n.set(e,t)}const r=/* @__PURE__ */new Set;for(const o of t.head.querySelectorAll("meta, link")){const t=U(o);if(null===t)continue;r.add(t);const i=n.get(t);if(void 0!==i){if(!i.hasAttribute(L))for(const e of Array.from(o.attributes))i.getAttribute(e.name)!==e.value&&i.setAttribute(e.name,e.value)}else e.head.append(e.importNode(o,!0))}for(const[e,t]of n)r.has(e)||t.hasAttribute(L)||t.remove()}(d,n),w(d.body,n.body,{keyAttributes:["data-payload-key",s,i],retainChildrenOf:e=>e.hasAttribute(i)}),g.scrollTo(r,o),"refreshed"}catch(e){return p(e)}}finally{h.dispose()}}}}function F(e){return{plan:(e,t)=>u(e,t).map(e=>e.element),async render(n,r){const o={rendered:0,failed:0,superseded:0},i={revision:n.revision,receivedAt:n.receivedAt,fields:n.fields,locale:n.locale,collectionSlug:n.collectionSlug,globalSlug:n.globalSlug,signal:n.signal};return await Promise.all(r.map(async r=>{const a=l(r);if(null===a)return;let s;try{s=await e(i,a)}catch(e){s={status:"failed",code:"LP0801",reason:t(e)}}return n.isCurrent()&&"superseded"!==s.status?"rendered"===s.status?(n.morph(r,s.html),n.rendered(r,a.id,a.key),void(o.rendered+=1)):(n.failed(r,a.id,a.key,s.code,s.reason),n.isCurrent()&&n.patch(r),void(o.failed+=1)):(o.superseded+=1,void n.log("LP0804",`fragment "${a.id}" for revision ${String(i.revision)} discarded as superseded`))})),o}}}function M(e){return F(b(e))}export{v as DIAGNOSTIC_CODES,i as FRAGMENT_ATTRIBUTE,s as FRAGMENT_KEY_ATTRIBUTE,c as FRAGMENT_PROTOCOL_VERSION,d as FRAGMENT_VERSION_HEADER,R as ROUTE_REFRESH_HEADER,u as collectFragmentBoundaries,b as createFragmentHandler,M as createFragmentStrategy,C as createRouteStrategy,l as describeBoundary,F as fragmentStrategyFrom,N as isRouteBound,h as parseFragmentRequest,p as parseFragmentResponse,a as resolveStrategy};
1
+ function e(e,t){const n=new AbortController;let r=!1;const o=()=>{n.abort()};e.addEventListener("abort",o,{once:!0});const i=setTimeout(()=>{r=!0,n.abort()},t);return{signal:n.signal,timedOut:()=>r,dispose:()=>{clearTimeout(i),e.removeEventListener("abort",o)}}}function t(e){return e instanceof Error?e.message:String(e)}var n="data-payload-island",r="data-payload-owned";function o(e){if(e.tagName.toLowerCase().includes("-")&&!e.hasAttribute("data-payload-morph"))return!0;if(i(e)||e.hasAttribute(r))return!0;const t=e.getAttribute("contenteditable");return null!==t&&"false"!==t}function i(e){return function(e){return"astro-island"===e.tagName.toLowerCase()||e.hasAttribute(n)}(e)&&!("patch"===e.getAttribute(n))}function isInsideIsland(e){let t=e;for(;null!==t;){if(i(t))return!0;t=t.parentElement}return!1}var a=["component-url","component-export","renderer-url","client","opts","before-hydration-url"],s=/* @__PURE__ */new WeakMap,l=/* @__PURE__ */new WeakSet;function u(e){return"astro-island"===e.tagName.toLowerCase()}function c(e){let t="";for(const n of e.querySelectorAll("astro-slot, template[data-astro-template]"))n.parentElement?.closest("astro-island")===e&&(t+=`${n.getAttribute("name")??n.getAttribute("data-astro-template")??""}\0${n.innerHTML}\0`);return t}function d(e,t){if(!u(e)||!u(t))return!0;const n=c(t);if(!a.every(n=>e.getAttribute(n)===t.getAttribute(n))||(s.get(e)??c(e))!==n||e.getAttribute("props")!==t.getAttribute("props")&&!function(e){const t=e.ownerDocument.defaultView?.customElements.get("astro-island");return void 0!==t&&e instanceof t&&Array.isArray(t.observedAttributes)&&t.observedAttributes.includes("props")}(e))return s.set(t,n),!1;s.set(e,n);const r=t.getAttribute("props");return r!==e.getAttribute("props")&&(e.setAttribute("ssr",""),null===r?e.removeAttribute("props"):e.setAttribute("props",r)),!0}function f(e){if(null==e)return[];const t=/* @__PURE__ */new Set,n=[];for(const r of e.split(/[\s,]+/)){const e=r.trim();0===e.length||t.has(e)||(t.add(e),n.push(e))}return n}var g="data-payload-fragment",p="data-payload-fragment-key";function h(e){const t=e.getAttribute("data-payload-strategy");return null!==t&&t.length>0?"patch"===t||"fragment"===t||"route"===t?t:void 0:null!==function(e){return e.closest(`[${g}]`)}(e)?"fragment":null!==e.closest("head")?"route":"patch"}function m(e){const t=e.getAttribute(g);if(null===t||0===t.length)return null;const n=e.getAttribute(p);return{element:e,id:t,key:null===n||0===n.length?void 0:n,dependsOn:f(e.getAttribute("data-payload-depends"))}}function y(e,t){const n=[];for(const r of e.querySelectorAll(`[${g}]`)){const e=m(r);null===e||isInsideIsland(r)||e.dependsOn.length>0&&!e.dependsOn.some(e=>t.has(e))||n.push(e)}return n}var b=1,v="x-payload-fragment-version";function L(e,t,n){if(t>n||"object"!=typeof e||null===e)return t;let r=t;for(const o of Object.values(e))if(r=Math.max(r,L(o,t+1,n)),r>n)break;return r}function A(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function P(e,t=64){const n=function(e,t=64){if(!Number.isInteger(t)||t<0||t>64)return null;if(!A(e))return null;const n=e.fragment;if("string"!=typeof n||!/^[a-z][a-z0-9-]{0,63}$/iu.test(n))return null;const r=e.key;if(void 0!==r&&("string"!=typeof r||r.length>128))return null;const o=e.route;if("string"!=typeof o||!o.startsWith("/")||o.length>2048)return null;const i=e.search;if("string"!=typeof i||i.length>4096||""!==i&&!i.startsWith("?"))return null;const a=e.revision;if("number"!=typeof a||!Number.isInteger(a)||a<0)return null;const s=[];for(const t of["locale","collectionSlug","globalSlug"]){const n=e[t];if(void 0!==n){if("string"!=typeof n||n.length>128)return null;s.push(n)}else s.push(void 0)}const[l,u,c]=s,d=e.fields;return A(d)?L(d,0,t)>t?"field-depth":{fragment:n,..."string"==typeof r?{key:r}:{},route:o,search:i,revision:a,...void 0!==l?{locale:l}:{},...void 0!==u?{collectionSlug:u}:{},...void 0!==c?{globalSlug:c}:{},fields:d}:null}(e,t);return"field-depth"===n?null:n}function w(e){if(!A(e))return null;const{html:t,boundary:n,revision:r,metadata:o}=e;return"string"!=typeof t?null:A(n)&&"string"==typeof n.id?void 0!==n.key&&"string"!=typeof n.key||"number"!=typeof r?null:A(o)&&"string"==typeof o.renderedAt&&"string"==typeof o.renderer?e:null:null}function S(e){return e.reason instanceof Error?e.reason:new DOMException("The operation was aborted.","AbortError")}function E(e){return!0===e?.aborted}var k={status:"superseded"};function T(e,t){return{status:"failed",code:e,reason:t}}function x(n){const r=function(e){const t=()=>{throw new TypeError('createFragmentStrategy: endpoint must be a same-origin path starting with "/"')};if(("string"!=typeof e||!e.startsWith("/")||e.startsWith("//")||e.includes("\\"))&&t(),"undefined"!=typeof location){let n;try{n=new URL(e,location.href)}catch{n=void 0}n?.origin!==location.origin&&t()}return e}(n.endpoint),o=n.timeoutMs??5e3,i=n.maxResponseBytes??524288,a=function(e){let t=0;const n=[],r=()=>{const e=n.shift();void 0===e?t-=1:e.resume()};return async(o,i)=>{if(void 0!==i&&E(i))throw S(i);if(t<e)t+=1;else if(await new Promise((e,t)=>{let r=()=>{};const o={resume:()=>{r(),e()}};if(n.push(o),void 0!==i){const e=()=>{const e=n.indexOf(o);-1!==e&&(n.splice(e,1),r(),t(S(i)))};r=()=>{i.removeEventListener("abort",e)},i.addEventListener("abort",e,{once:!0}),E(i)&&e()}}),void 0!==i&&E(i))throw r(),S(i);try{return await o()}finally{r()}}}(Math.max(1,n.maxConcurrent??4)),s=/* @__PURE__ */new Map,l=/* @__PURE__ */new WeakMap;let u=0;const c=e=>{const t=l.get(e);return void 0!==t?t:(u+=1,l.set(e,u),u)};return(l,u)=>{const d=JSON.stringify([c(l.signal),u.id,u.key,l.revision]),f=s.get(d);if(void 0!==f)return f;let g=!1;const p=a(()=>(g=!0,async function(a,s){const l=()=>a.signal.aborted;if(l())return k;const u=n.location??location,c=function(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(t[n]=r);return t}({fragment:s.id,key:s.key,route:u.pathname,search:u.search,revision:a.revision,locale:a.locale,collectionSlug:a.collectionSlug,globalSlug:a.globalSlug,fields:a.fields}),d=e(a.signal,o),f=e=>l()?k:d.timedOut()?T("LP0801",`timeout after ${String(o)} ms`):T("LP0801",t(e));let g,p=!1;try{try{g=await(n.fetch??fetch)(r,{method:"POST",credentials:"same-origin",headers:{...n.headers,accept:"application/json","content-type":"application/json",[v]:String(1)},body:JSON.stringify(c),signal:d.signal})}catch(e){return f(e)}if(l())return k;if(401===g.status||403===g.status)return T("LP0803",`endpoint refused the preview (${String(g.status)})`);if(!g.ok)return T("LP0801",`endpoint answered ${String(g.status)}`);const e=g.headers.get("content-type")??"";if(!e.toLowerCase().startsWith("application/json"))return T("LP0802",`unexpected content type "${e}"`);if(Number(g.headers.get("content-length")??"0")>i)return T("LP0802","response exceeds the size limit");if(d.signal.aborted)return f(d.signal.reason);let t,u;try{p=!0,t=await async function(e,t,n){const r=e.body;if("object"!=typeof(o=r)||null===o||"function"!=typeof o.getReader){const n=await e.text();return(new TextEncoder).encode(n).byteLength>t?null:n}var o;const i=r.getReader(),a=()=>{i.cancel().catch(()=>{})};n.addEventListener("abort",a,{once:!0});const s=new TextDecoder;let l="",u=0;try{for(;;){const{done:e,value:n}=await i.read();if(e)break;if(u+=n.byteLength,u>t)return a(),null;l+=s.decode(n,{stream:!0})}}finally{n.removeEventListener("abort",a),i.releaseLock()}return l+s.decode()}(g,i,d.signal)}catch(e){return f(e)}if(l())return k;if(d.timedOut())return T("LP0801",`timeout after ${String(o)} ms`);if(null===t)return T("LP0802","response exceeds the size limit");try{u=JSON.parse(t)}catch{return T("LP0802","response is not JSON")}const h=w(u);return null===h?T("LP0802","response has the wrong shape"):h.boundary.id!==s.id||h.boundary.key!==s.key?T("LP0802","response is for another boundary"):h.revision!==a.revision?k:{status:"rendered",html:h.html,metadata:h.metadata}}finally{if(d.dispose(),void 0!==g&&!p)try{g.body?.cancel().catch(()=>{})}catch{}}}(l,u)),l.signal).catch(e=>{if(!g&&l.signal.aborted)return k;throw e});s.set(d,p);const h=()=>{s.get(d)===p&&s.delete(d)};return p.then(h,h),p}}var N=Object.freeze({NoTrustedOrigin:"LP0101",ReferrerOnlyTrust:"LP0102",PluginIncompatible:"LP0103",ProfileFeatureOmitted:"LP0104",OrphanField:"LP0201",UnattributableUpdate:"LP0202",UnboundField:"LP0203",VisibilityGateDeferred:"LP0301",UnsafeAttributeWrite:"LP0401",TextTargetHasChildren:"LP0402",MissingArrayTemplate:"LP0403",StructuralItemUnkeyed:"LP0404",StructuralDuplicateKey:"LP0405",StructuralUnstableKeys:"LP0406",UnsupportedStrategy:"LP0407",UnknownValueFormat:"LP0408",SanitizerDroppedAttribute:"LP0409",UnrenderedBlockKept:"LP0410",UnfaithfulPatch:"LP0411",ServerFormatReplaced:"LP0412",UnrenderedBlockLost:"LP0413",MessageRejected:"LP0501",TokenRejected:"LP0502",ProtocolShapeUnknown:"LP0503",HandlerThrew:"LP0601",TransformThrew:"LP0602",RendererThrew:"LP0603",StartupFailed:"LP0605",ReadyFailed:"LP0606",HydrationWaitTimedOut:"LP0607",AuditRuntimeMissing:"LP0701",AuditNoFrameAncestors:"LP0702",AuditFrameOptionsBlocks:"LP0703",AuditBindingsExposed:"LP0704",AuditGateThresholdExceeded:"LP0705",AuditUnownedBindings:"LP0706",AuditNoBindings:"LP0707",AuditNotAPage:"LP0708",FragmentRequestFailed:"LP0801",FragmentResponseInvalid:"LP0802",FragmentUnauthorized:"LP0803",FragmentSuperseded:"LP0804",RouteRefreshLoop:"LP0805",FragmentStrategyUnavailable:"LP0806",UnboundChangeRefresh:"LP0807",EscalationUnavailable:"LP0808",IslandStartUnavailable:"LP0809",RouteRefreshUnconfirmed:"LP0810",V2ReadinessGap:"LP0709",RuntimeOnPublicPage:"LP0710"}),O=/* @__PURE__ */new Set(["open","value","checked","selected"]);function R(e,t){for(const n of t.keyAttributes){const t=e.getAttribute(n);if(null!==t&&t.length>0)return`${n}=${t}`}}function C(e,t,n){if(!M(e,t))return t;const r=n.boundary??o,i=r(e),a=r(t);if(i||a)return i&&a&&(n.retainBoundary?.(e,t)??1)?e:t;const s=function(e){const t=e.ownerDocument.activeElement;if(!(t instanceof HTMLElement&&e.contains(t)))return null;return{element:t,selection:t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement?[t.selectionStart,t.selectionEnd]:null}}(e);return function(e,t){for(const n of Array.from(e.attributes))t.hasAttribute(n.name)||O.has(n.name.toLowerCase())||e.removeAttribute(n.name);for(const n of Array.from(t.attributes))e.getAttribute(n.name)!==n.value&&e.setAttribute(n.name,n.value)}(e,t),!0!==n.retainChildrenOf?.(e,t)&&function(e,t,n){const r=function(e,t){const n=/* @__PURE__ */new Map;let r;for(const o of Array.from(e.children)){const e=R(o,t);void 0!==e&&(n.has(e)?r??=e.slice(e.indexOf("=")+1):n.set(e,o))}return void 0!==r&&t.onDuplicateKey?.(e,r),n}(e,n),o=new Set(r.values()),i=Array.from(e.childNodes).filter(e=>!o.has(e)),a=/* @__PURE__ */new Set,s=/* @__PURE__ */new Set,l=Array.from(t.childNodes);let u=e.firstChild,c=0;for(let t=0;t<l.length;t+=1){const o=l[t];let d=null,f=o instanceof Element?R(o,n):void 0;if(void 0!==f&&s.has(f)&&(f=void 0),void 0!==f){s.add(f);const e=r.get(f);if(void 0!==e&&!a.has(e)&&(d=U(e,o,n)===e?e:null,null===d)){e.replaceWith(o),a.add(o),u=o.nextSibling;continue}}else{for(;c<i.length;){const r=i[c];if(c+=1,!a.has(r)){if(M(r,o)){d=U(r,o,n)===r?r:null,null===d&&(e.replaceChild(o,r),a.add(o),u=o.nextSibling);break}if(r instanceof Element){const n=l[t+1];if(!(o instanceof Element)||void 0!==n&&M(r,n)){c-=1;break}e.replaceChild(o,r),a.add(o),u=o.nextSibling;break}if(!(o instanceof Element)){e.replaceChild(o,r),a.add(o),u=o.nextSibling;break}}}if(null===d&&a.has(o))continue}const g=d??o;for(a.add(g);null!==u&&u!==g&&!a.has(u)&&$(u);)u=u.nextSibling;g!==u&&e.insertBefore(g,u),u=g.nextSibling}for(const t of Array.from(e.childNodes))a.has(t)||t.remove()}(e,t,n),function(e){if(null===e)return;const{element:t,selection:n}=e;if(t.ownerDocument.activeElement!==t&&t.isConnected)try{t.focus({preventScroll:!0});const[e,r]=n??[null,null];null!==e&&null!==r&&t.setSelectionRange(e,r)}catch{}}(s),e}function U(e,t,n){return e instanceof Element&&t instanceof Element?C(e,t,n):(e.nodeValue!==t.nodeValue&&(e.nodeValue=t.nodeValue),e)}function $(e){return e.nodeType===Node.TEXT_NODE&&0===(e.nodeValue??"").trim().length}function M(e,t){return e.nodeType===t.nodeType&&(!(e instanceof Element&&t instanceof Element)||e.tagName===t.tagName&&e.namespaceURI===t.namespaceURI)}var F="data-payload-strategy",I="data-payload-field",D="x-payload-live-preview";function W(e){const t=e.getAttribute(F);return null!==t?"route"===t:null!==e.closest("head")}function j(e){const t=e.getAttribute(I),n=f(e.getAttribute("data-payload-depends"));return null===t||0===t.length?n:[t,...n]}function B(e){return!e.hasAttribute(r)&&("META"===e.tagName?e.hasAttribute("name")||e.hasAttribute("property"):"LINK"===e.tagName&&"canonical"===e.getAttribute("rel"))}function V(n={}){const i=n.timeoutMs??8e3,a=n.minIntervalMs??1e3;let s=-1/0,u=!1;return{plan(e,t,n){for(const r of e.querySelectorAll(`[${I}], [${F}="route"]`)){if(!W(r)||!1===n?.inScope(r))continue;const e=j(r);if(0===e.length||e.some(e=>t.has(e)))return!0}return!1},async refresh(c){const f=Date.now(),h=a-(f-s);if(h>0)return c.retryAfter?.(h),c.log("LP0805",`route refresh for revision ${String(c.revision)} refused: the previous one was ${String(f-s)} ms ago`),"refused";s=f;const m=n.document??document,y=n.location??location,b=n.window??window,v=e(c.signal,i),L=e=>{if(c.signal.aborted)return"superseded";const n=v.timedOut()?`route refresh timed out after ${String(i)} ms`:t(e);return c.log("LP0801",n),"failed"};try{const e=("undefined"==typeof window?void 0:window)?.__livePreviewRouteRefresh;if(void 0!==e){try{const t=e();"function"==typeof t?.then||u||(u=!0,c.log("LP0810","route refresh returned no promise; re-applied before the host committed (see LivePreviewRouteRefresh)")),await t}catch(e){return L(e)}return c.isCurrent()?"partial":"superseded"}let t;try{t=await(n.fetch??fetch)(y.href,{method:"GET",credentials:"same-origin",cache:"no-store",headers:{accept:"text/html",[D]:"route"},signal:v.signal})}catch(e){return L(e)}if(c.signal.aborted)return"superseded";if(!t.ok||!(t.headers.get("content-type")??"").includes("text/html"))return c.log("LP0802",`route answered ${String(t.status)} ${t.headers.get("content-type")??""}`),"failed";try{const e=await t.text();if(!c.isCurrent())return"superseded";const n=(new DOMParser).parseFromString(e,"text/html"),i=b.scrollX,a=b.scrollY;!function(e,t){const n=Array.from(e.head.children).find(e=>"TITLE"===e.tagName),o=Array.from(t.head.children).find(e=>"TITLE"===e.tagName);n?.hasAttribute(r)||o?.hasAttribute(r)||t.title===e.title||(e.title=t.title);const i=Array.from(e.head.children).filter(B),a=Array.from(t.head.children).filter(B),s=Math.min(i.length,a.length);i.slice(0,s).forEach((t,n)=>{const r=a[n];if(void 0===r)return;if(t.tagName===r.tagName){for(const e of Array.from(t.attributes))r.hasAttribute(e.name)||t.removeAttribute(e.name);for(const e of Array.from(r.attributes))t.getAttribute(e.name)!==e.value&&t.setAttribute(e.name,e.value);return}const o=e.importNode(r,!0);t.replaceWith(o),i[n]=o});let l=i.at(-1);for(const t of a.slice(i.length)){const n=e.importNode(t,!0);void 0===l?e.head.append(n):l.after(n),l=n}for(const e of i.slice(a.length))e.remove()}(m,n);const s=(A=m.body,Array.from(A.querySelectorAll("astro-island")));return C(m.body,n.body,{boundary:o,retainBoundary:d,keyAttributes:["data-payload-key",p,g],retainChildrenOf:e=>e.hasAttribute(g)}),function(e){for(const t of e)t.isConnected||l.has(t)||(l.add(t),t.dispatchEvent(new CustomEvent("astro:unmount")))}(s),b.scrollTo(i,a),"partial"}catch(e){return L(e)}}finally{v.dispose()}var A}}}function z(e){return{plan:(e,t)=>y(e,t).map(e=>e.element),async render(n,r){const o={rendered:0,failed:0,superseded:0},i={revision:n.revision,receivedAt:n.receivedAt,fields:n.fields,locale:n.locale,collectionSlug:n.collectionSlug,globalSlug:n.globalSlug,signal:n.signal};return await Promise.all(r.map(async r=>{const a=m(r);if(null===a)return;let s;try{s=await e(i,a)}catch(e){s={status:"failed",code:"LP0801",reason:t(e)}}return n.isCurrent()&&"superseded"!==s.status?"rendered"===s.status?(n.morph(r,s.html),n.rendered(r,a.id,a.key),void(o.rendered+=1)):(n.failed(r,a.id,a.key,s.code,s.reason),n.isCurrent()&&n.patch(r),void(o.failed+=1)):(o.superseded+=1,void n.log("LP0804",`fragment "${a.id}" for revision ${String(i.revision)} discarded as superseded`))})),o}}}function H(e){return z(x(e))}export{N as DIAGNOSTIC_CODES,g as FRAGMENT_ATTRIBUTE,p as FRAGMENT_KEY_ATTRIBUTE,b as FRAGMENT_PROTOCOL_VERSION,v as FRAGMENT_VERSION_HEADER,D as ROUTE_REFRESH_HEADER,y as collectFragmentBoundaries,x as createFragmentHandler,H as createFragmentStrategy,V as createRouteStrategy,m as describeBoundary,z as fragmentStrategyFrom,W as isRouteBound,P as parseFragmentRequest,w as parseFragmentResponse,h as resolveStrategy};
2
2
  //# sourceMappingURL=fragment.js.map