@screenbook/ui 0.0.1

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 (101) hide show
  1. package/.astro/content-assets.mjs +1 -0
  2. package/.astro/content-modules.mjs +1 -0
  3. package/.astro/content.d.ts +199 -0
  4. package/.astro/data-store.json +1 -0
  5. package/.astro/settings.json +5 -0
  6. package/.astro/types.d.ts +2 -0
  7. package/.prettierrc +15 -0
  8. package/.screenbook/coverage.json +37 -0
  9. package/.screenbook/screens.json +90 -0
  10. package/LICENSE +21 -0
  11. package/astro.config.mjs +18 -0
  12. package/dist/client/_astro/_baseUniq.BGai4mcc.js +1 -0
  13. package/dist/client/_astro/arc.DUp0dfXj.js +1 -0
  14. package/dist/client/_astro/architectureDiagram-VXUJARFQ.De_Gt-YC.js +36 -0
  15. package/dist/client/_astro/blockDiagram-VD42YOAC.BBt_VNhR.js +122 -0
  16. package/dist/client/_astro/c4Diagram-YG6GDRKO.DfgUlHvt.js +10 -0
  17. package/dist/client/_astro/channel.CNyr52v1.js +1 -0
  18. package/dist/client/_astro/chunk-4BX2VUAB.BL0ar6du.js +1 -0
  19. package/dist/client/_astro/chunk-55IACEB6.CI6SkZkY.js +1 -0
  20. package/dist/client/_astro/chunk-B4BG7PRW.Z25N80K6.js +165 -0
  21. package/dist/client/_astro/chunk-DI55MBZ5.BqjPVmi1.js +220 -0
  22. package/dist/client/_astro/chunk-FMBD7UC4.bZ9DWnFm.js +15 -0
  23. package/dist/client/_astro/chunk-QN33PNHL.BkzuUgWB.js +1 -0
  24. package/dist/client/_astro/chunk-QZHKN3VN.C__d68N_.js +1 -0
  25. package/dist/client/_astro/chunk-TZMSLE5B.BIpu8bMn.js +1 -0
  26. package/dist/client/_astro/classDiagram-2ON5EDUG.CxT3aW-h.js +1 -0
  27. package/dist/client/_astro/classDiagram-v2-WZHVMYZB.CxT3aW-h.js +1 -0
  28. package/dist/client/_astro/clone.U_lSZ6fe.js +1 -0
  29. package/dist/client/_astro/cose-bilkent-S5V4N54A.D48yfMll.js +1 -0
  30. package/dist/client/_astro/coverage.CKIVg4LY.css +1 -0
  31. package/dist/client/_astro/coverage.DDJMzKCq.css +1 -0
  32. package/dist/client/_astro/cytoscape.esm.DtBltrT8.js +331 -0
  33. package/dist/client/_astro/dagre-6UL2VRFP.LKVH7b30.js +4 -0
  34. package/dist/client/_astro/defaultLocale.C4B-KCzX.js +1 -0
  35. package/dist/client/_astro/diagram-PSM6KHXK.AHgUjH56.js +24 -0
  36. package/dist/client/_astro/diagram-QEK2KX5R.DvS33xWZ.js +43 -0
  37. package/dist/client/_astro/diagram-S2PKOQOG.BWisaYrQ.js +24 -0
  38. package/dist/client/_astro/erDiagram-Q2GNP2WA.B7oID6oT.js +60 -0
  39. package/dist/client/_astro/flowDiagram-NV44I4VS.Bb1qJLxr.js +162 -0
  40. package/dist/client/_astro/ganttDiagram-JELNMOA3.3vGHETyo.js +267 -0
  41. package/dist/client/_astro/gitGraphDiagram-NY62KEGX.Co2SKcif.js +65 -0
  42. package/dist/client/_astro/graph.B5fevUwB.js +1 -0
  43. package/dist/client/_astro/graph.astro_astro_type_script_index_0_lang.1HlATQ1g.js +1 -0
  44. package/dist/client/_astro/impact.Cvhl64u1.css +1 -0
  45. package/dist/client/_astro/impact.astro_astro_type_script_index_0_lang.D4cAR9AL.js +6 -0
  46. package/dist/client/_astro/infoDiagram-WHAUD3N6.B6ULtps1.js +2 -0
  47. package/dist/client/_astro/init.Gi6I4Gst.js +1 -0
  48. package/dist/client/_astro/journeyDiagram-XKPGCS4Q.BSOCzWmw.js +139 -0
  49. package/dist/client/_astro/kanban-definition-3W4ZIXB7.D8KKGc1o.js +89 -0
  50. package/dist/client/_astro/katex.XbL3y5x-.js +261 -0
  51. package/dist/client/_astro/layout.8vv24qEg.js +1 -0
  52. package/dist/client/_astro/linear.B6O9ymuK.js +1 -0
  53. package/dist/client/_astro/mermaid.core.CReXU7YN.js +256 -0
  54. package/dist/client/_astro/min.CdGMGVU0.js +1 -0
  55. package/dist/client/_astro/mindmap-definition-VGOIOE7T.G14HgtDw.js +68 -0
  56. package/dist/client/_astro/ordinal.BYWQX77i.js +1 -0
  57. package/dist/client/_astro/pieDiagram-ADFJNKIX.bC2VkyoW.js +30 -0
  58. package/dist/client/_astro/quadrantDiagram-AYHSOK5B.BlLaQQxO.js +7 -0
  59. package/dist/client/_astro/requirementDiagram-UZGBJVZJ.DHRnMofO.js +64 -0
  60. package/dist/client/_astro/sankeyDiagram-TZEHDZUN.BMuaJBmt.js +10 -0
  61. package/dist/client/_astro/sequenceDiagram-WL72ISMW.CnU62wqy.js +145 -0
  62. package/dist/client/_astro/stateDiagram-FKZM4ZOC.CewI55YO.js +1 -0
  63. package/dist/client/_astro/stateDiagram-v2-4FDKWEC3.7xUQqoNr.js +1 -0
  64. package/dist/client/_astro/timeline-definition-IT6M3QCI.D1PLRwss.js +61 -0
  65. package/dist/client/_astro/treemap-KMMF4GRG.D3VNVvXF.js +128 -0
  66. package/dist/client/_astro/xychartDiagram-PRI3JC2R.CQex0-ul.js +7 -0
  67. package/dist/client/logo.svg +5 -0
  68. package/dist/server/_@astrojs-ssr-adapter.mjs +1 -0
  69. package/dist/server/_noop-middleware.mjs +3 -0
  70. package/dist/server/chunks/_@astrojs-ssr-adapter_DgsYudHz.mjs +4385 -0
  71. package/dist/server/chunks/astro/server_m7yT4wCr.mjs +2787 -0
  72. package/dist/server/chunks/astro-designed-error-pages_BvPhMmw0.mjs +364 -0
  73. package/dist/server/chunks/fs-lite_COtHaKzy.mjs +157 -0
  74. package/dist/server/chunks/impactAnalysis_Bz5lMdmy.mjs +188 -0
  75. package/dist/server/chunks/loadScreens_DJf-tycc.mjs +39 -0
  76. package/dist/server/chunks/node_DoTkMCOi.mjs +1673 -0
  77. package/dist/server/chunks/remote_B3W5fv4r.mjs +188 -0
  78. package/dist/server/chunks/sharp_DHNfMLYY.mjs +99 -0
  79. package/dist/server/entry.mjs +47 -0
  80. package/dist/server/manifest_-V1HEnR8.mjs +101 -0
  81. package/dist/server/noop-entrypoint.mjs +3 -0
  82. package/dist/server/pages/_image.astro.mjs +2 -0
  83. package/dist/server/pages/coverage.astro.mjs +65 -0
  84. package/dist/server/pages/graph.astro.mjs +107 -0
  85. package/dist/server/pages/impact.astro.mjs +52 -0
  86. package/dist/server/pages/index.astro.mjs +28 -0
  87. package/dist/server/pages/screen/_id_.astro.mjs +52 -0
  88. package/dist/server/renderers.mjs +3 -0
  89. package/package.json +42 -0
  90. package/public/logo.svg +5 -0
  91. package/src/layouts/Layout.astro +60 -0
  92. package/src/pages/coverage.astro +399 -0
  93. package/src/pages/graph.astro +330 -0
  94. package/src/pages/impact.astro +459 -0
  95. package/src/pages/index.astro +167 -0
  96. package/src/pages/screen/[id].astro +186 -0
  97. package/src/styles/global.css +862 -0
  98. package/src/utils/impactAnalysis.ts +297 -0
  99. package/src/utils/loadCoverage.ts +30 -0
  100. package/src/utils/loadScreens.ts +18 -0
  101. package/tsconfig.json +9 -0
@@ -0,0 +1,2787 @@
1
+ import colors from 'piccolore';
2
+ import { clsx } from 'clsx';
3
+ import { escape } from 'html-escaper';
4
+ import { decodeBase64, encodeBase64, encodeHexUpperCase, decodeHex } from '@oslojs/encoding';
5
+ import { z } from 'zod';
6
+ import 'cssesc';
7
+
8
+ const ASTRO_VERSION = "5.16.6";
9
+ const REROUTE_DIRECTIVE_HEADER = "X-Astro-Reroute";
10
+ const REWRITE_DIRECTIVE_HEADER_KEY = "X-Astro-Rewrite";
11
+ const REWRITE_DIRECTIVE_HEADER_VALUE = "yes";
12
+ const NOOP_MIDDLEWARE_HEADER = "X-Astro-Noop";
13
+ const ROUTE_TYPE_HEADER = "X-Astro-Route-Type";
14
+ const DEFAULT_404_COMPONENT = "astro-default-404.astro";
15
+ const REDIRECT_STATUS_CODES = [301, 302, 303, 307, 308, 300, 304];
16
+ const REROUTABLE_STATUS_CODES = [404, 500];
17
+ const clientAddressSymbol = Symbol.for("astro.clientAddress");
18
+ const originPathnameSymbol = Symbol.for("astro.originPathname");
19
+ const nodeRequestAbortControllerCleanupSymbol = Symbol.for(
20
+ "astro.nodeRequestAbortControllerCleanup"
21
+ );
22
+ const responseSentSymbol = Symbol.for("astro.responseSent");
23
+
24
+ const ClientAddressNotAvailable = {
25
+ name: "ClientAddressNotAvailable",
26
+ title: "`Astro.clientAddress` is not available in current adapter.",
27
+ message: (adapterName) => `\`Astro.clientAddress\` is not available in the \`${adapterName}\` adapter. File an issue with the adapter to add support.`
28
+ };
29
+ const PrerenderClientAddressNotAvailable = {
30
+ name: "PrerenderClientAddressNotAvailable",
31
+ title: "`Astro.clientAddress` cannot be used inside prerendered routes.",
32
+ message: (name) => `\`Astro.clientAddress\` cannot be used inside prerendered route ${name}`
33
+ };
34
+ const StaticClientAddressNotAvailable = {
35
+ name: "StaticClientAddressNotAvailable",
36
+ title: "`Astro.clientAddress` is not available in prerendered pages.",
37
+ message: "`Astro.clientAddress` is only available on pages that are server-rendered.",
38
+ hint: "See https://docs.astro.build/en/guides/on-demand-rendering/ for more information on how to enable SSR."
39
+ };
40
+ const NoMatchingStaticPathFound = {
41
+ name: "NoMatchingStaticPathFound",
42
+ title: "No static path found for requested path.",
43
+ message: (pathName) => `A \`getStaticPaths()\` route pattern was matched, but no matching static path was found for requested path \`${pathName}\`.`,
44
+ hint: (possibleRoutes) => `Possible dynamic routes being matched: ${possibleRoutes.join(", ")}.`
45
+ };
46
+ const OnlyResponseCanBeReturned = {
47
+ name: "OnlyResponseCanBeReturned",
48
+ title: "Invalid type returned by Astro page.",
49
+ message: (route, returnedValue) => `Route \`${route ? route : ""}\` returned a \`${returnedValue}\`. Only a [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) can be returned from Astro files.`,
50
+ hint: "See https://docs.astro.build/en/guides/on-demand-rendering/#response for more information."
51
+ };
52
+ const MissingMediaQueryDirective = {
53
+ name: "MissingMediaQueryDirective",
54
+ title: "Missing value for `client:media` directive.",
55
+ message: 'Media query not provided for `client:media` directive. A media query similar to `client:media="(max-width: 600px)"` must be provided'
56
+ };
57
+ const NoMatchingRenderer = {
58
+ name: "NoMatchingRenderer",
59
+ title: "No matching renderer found.",
60
+ message: (componentName, componentExtension, plural, validRenderersCount) => `Unable to render \`${componentName}\`.
61
+
62
+ ${validRenderersCount > 0 ? `There ${plural ? "are" : "is"} ${validRenderersCount} renderer${plural ? "s" : ""} configured in your \`astro.config.mjs\` file,
63
+ but ${plural ? "none were" : "it was not"} able to server-side render \`${componentName}\`.` : `No valid renderer was found ${componentExtension ? `for the \`.${componentExtension}\` file extension.` : `for this file extension.`}`}`,
64
+ hint: (probableRenderers) => `Did you mean to enable the ${probableRenderers} integration?
65
+
66
+ See https://docs.astro.build/en/guides/framework-components/ for more information on how to install and configure integrations.`
67
+ };
68
+ const NoClientOnlyHint = {
69
+ name: "NoClientOnlyHint",
70
+ title: "Missing hint on client:only directive.",
71
+ message: (componentName) => `Unable to render \`${componentName}\`. When using the \`client:only\` hydration strategy, Astro needs a hint to use the correct renderer.`,
72
+ hint: (probableRenderers) => `Did you mean to pass \`client:only="${probableRenderers}"\`? See https://docs.astro.build/en/reference/directives-reference/#clientonly for more information on client:only`
73
+ };
74
+ const InvalidGetStaticPathsEntry = {
75
+ name: "InvalidGetStaticPathsEntry",
76
+ title: "Invalid entry inside getStaticPath's return value",
77
+ message: (entryType) => `Invalid entry returned by getStaticPaths. Expected an object, got \`${entryType}\``,
78
+ hint: "If you're using a `.map` call, you might be looking for `.flatMap()` instead. See https://docs.astro.build/en/reference/routing-reference/#getstaticpaths for more information on getStaticPaths."
79
+ };
80
+ const InvalidGetStaticPathsReturn = {
81
+ name: "InvalidGetStaticPathsReturn",
82
+ title: "Invalid value returned by getStaticPaths.",
83
+ message: (returnType) => `Invalid type returned by \`getStaticPaths\`. Expected an \`array\`, got \`${returnType}\``,
84
+ hint: "See https://docs.astro.build/en/reference/routing-reference/#getstaticpaths for more information on getStaticPaths."
85
+ };
86
+ const GetStaticPathsExpectedParams = {
87
+ name: "GetStaticPathsExpectedParams",
88
+ title: "Missing params property on `getStaticPaths` route.",
89
+ message: "Missing or empty required `params` property on `getStaticPaths` route.",
90
+ hint: "See https://docs.astro.build/en/reference/routing-reference/#getstaticpaths for more information on getStaticPaths."
91
+ };
92
+ const GetStaticPathsInvalidRouteParam = {
93
+ name: "GetStaticPathsInvalidRouteParam",
94
+ title: "Invalid value for `getStaticPaths` route parameter.",
95
+ message: (key, value, valueType) => `Invalid getStaticPaths route parameter for \`${key}\`. Expected undefined, a string or a number, received \`${valueType}\` (\`${value}\`)`,
96
+ hint: "See https://docs.astro.build/en/reference/routing-reference/#getstaticpaths for more information on getStaticPaths."
97
+ };
98
+ const GetStaticPathsRequired = {
99
+ name: "GetStaticPathsRequired",
100
+ title: "`getStaticPaths()` function required for dynamic routes.",
101
+ message: "`getStaticPaths()` function is required for dynamic routes. Make sure that you `export` a `getStaticPaths` function from your dynamic route.",
102
+ hint: `See https://docs.astro.build/en/guides/routing/#dynamic-routes for more information on dynamic routes.
103
+
104
+ If you meant for this route to be server-rendered, set \`export const prerender = false;\` in the page.`
105
+ };
106
+ const ReservedSlotName = {
107
+ name: "ReservedSlotName",
108
+ title: "Invalid slot name.",
109
+ message: (slotName) => `Unable to create a slot named \`${slotName}\`. \`${slotName}\` is a reserved slot name. Please update the name of this slot.`
110
+ };
111
+ const NoMatchingImport = {
112
+ name: "NoMatchingImport",
113
+ title: "No import found for component.",
114
+ message: (componentName) => `Could not render \`${componentName}\`. No matching import has been found for \`${componentName}\`.`,
115
+ hint: "Please make sure the component is properly imported."
116
+ };
117
+ const InvalidComponentArgs = {
118
+ name: "InvalidComponentArgs",
119
+ title: "Invalid component arguments.",
120
+ message: (name) => `Invalid arguments passed to${name ? ` <${name}>` : ""} component.`,
121
+ hint: "Astro components cannot be rendered directly via function call, such as `Component()` or `{items.map(Component)}`."
122
+ };
123
+ const PageNumberParamNotFound = {
124
+ name: "PageNumberParamNotFound",
125
+ title: "Page number param not found.",
126
+ message: (paramName) => `[paginate()] page number param \`${paramName}\` not found in your filepath.`,
127
+ hint: "Rename your file to `[page].astro` or `[...page].astro`."
128
+ };
129
+ const ImageMissingAlt = {
130
+ name: "ImageMissingAlt",
131
+ title: 'Image missing required "alt" property.',
132
+ message: 'Image missing "alt" property. "alt" text is required to describe important images on the page.',
133
+ hint: 'Use an empty string ("") for decorative images.'
134
+ };
135
+ const InvalidImageService = {
136
+ name: "InvalidImageService",
137
+ title: "Error while loading image service.",
138
+ message: "There was an error loading the configured image service. Please see the stack trace for more information."
139
+ };
140
+ const MissingImageDimension = {
141
+ name: "MissingImageDimension",
142
+ title: "Missing image dimensions",
143
+ message: (missingDimension, imageURL) => `Missing ${missingDimension === "both" ? "width and height attributes" : `${missingDimension} attribute`} for ${imageURL}. When using remote images, both dimensions are required in order to avoid CLS.`,
144
+ hint: "If your image is inside your `src` folder, you probably meant to import it instead. See [the Imports guide for more information](https://docs.astro.build/en/guides/imports/#other-assets). You can also use `inferSize={true}` for remote images to get the original dimensions."
145
+ };
146
+ const FailedToFetchRemoteImageDimensions = {
147
+ name: "FailedToFetchRemoteImageDimensions",
148
+ title: "Failed to retrieve remote image dimensions",
149
+ message: (imageURL) => `Failed to get the dimensions for ${imageURL}.`,
150
+ hint: "Verify your remote image URL is accurate, and that you are not using `inferSize` with a file located in your `public/` folder."
151
+ };
152
+ const UnsupportedImageFormat = {
153
+ name: "UnsupportedImageFormat",
154
+ title: "Unsupported image format",
155
+ message: (format, imagePath, supportedFormats) => `Received unsupported format \`${format}\` from \`${imagePath}\`. Currently only ${supportedFormats.join(
156
+ ", "
157
+ )} are supported by our image services.`,
158
+ hint: "Using an `img` tag directly instead of the `Image` component might be what you're looking for."
159
+ };
160
+ const UnsupportedImageConversion = {
161
+ name: "UnsupportedImageConversion",
162
+ title: "Unsupported image conversion",
163
+ message: "Converting between vector (such as SVGs) and raster (such as PNGs and JPEGs) images is not currently supported."
164
+ };
165
+ const PrerenderDynamicEndpointPathCollide = {
166
+ name: "PrerenderDynamicEndpointPathCollide",
167
+ title: "Prerendered dynamic endpoint has path collision.",
168
+ message: (pathname) => `Could not render \`${pathname}\` with an \`undefined\` param as the generated path will collide during prerendering. Prevent passing \`undefined\` as \`params\` for the endpoint's \`getStaticPaths()\` function, or add an additional extension to the endpoint's filename.`,
169
+ hint: (filename) => `Rename \`${filename}\` to \`${filename.replace(/\.(?:js|ts)/, (m) => `.json` + m)}\``
170
+ };
171
+ const ExpectedImage = {
172
+ name: "ExpectedImage",
173
+ title: "Expected src to be an image.",
174
+ message: (src, typeofOptions, fullOptions) => `Expected \`src\` property for \`getImage\` or \`<Image />\` to be either an ESM imported image or a string with the path of a remote image. Received \`${src}\` (type: \`${typeofOptions}\`).
175
+
176
+ Full serialized options received: \`${fullOptions}\`.`,
177
+ hint: "This error can often happen because of a wrong path. Make sure the path to your image is correct. If you're passing an async function, make sure to call and await it."
178
+ };
179
+ const ExpectedImageOptions = {
180
+ name: "ExpectedImageOptions",
181
+ title: "Expected image options.",
182
+ message: (options) => `Expected getImage() parameter to be an object. Received \`${options}\`.`
183
+ };
184
+ const ExpectedNotESMImage = {
185
+ name: "ExpectedNotESMImage",
186
+ title: "Expected image options, not an ESM-imported image.",
187
+ message: "An ESM-imported image cannot be passed directly to `getImage()`. Instead, pass an object with the image in the `src` property.",
188
+ hint: "Try changing `getImage(myImage)` to `getImage({ src: myImage })`"
189
+ };
190
+ const IncompatibleDescriptorOptions = {
191
+ name: "IncompatibleDescriptorOptions",
192
+ title: "Cannot set both `densities` and `widths`",
193
+ message: "Only one of `densities` or `widths` can be specified. In most cases, you'll probably want to use only `widths` if you require specific widths.",
194
+ hint: "Those attributes are used to construct a `srcset` attribute, which cannot have both `x` and `w` descriptors."
195
+ };
196
+ const NoImageMetadata = {
197
+ name: "NoImageMetadata",
198
+ title: "Could not process image metadata.",
199
+ message: (imagePath) => `Could not process image metadata${imagePath ? ` for \`${imagePath}\`` : ""}.`,
200
+ hint: "This is often caused by a corrupted or malformed image. Re-exporting the image from your image editor may fix this issue."
201
+ };
202
+ const ResponseSentError = {
203
+ name: "ResponseSentError",
204
+ title: "Unable to set response.",
205
+ message: "The response has already been sent to the browser and cannot be altered."
206
+ };
207
+ const MiddlewareNoDataOrNextCalled = {
208
+ name: "MiddlewareNoDataOrNextCalled",
209
+ title: "The middleware didn't return a `Response`.",
210
+ message: "Make sure your middleware returns a `Response` object, either directly or by returning the `Response` from calling the `next` function."
211
+ };
212
+ const MiddlewareNotAResponse = {
213
+ name: "MiddlewareNotAResponse",
214
+ title: "The middleware returned something that is not a `Response` object.",
215
+ message: "Any data returned from middleware must be a valid `Response` object."
216
+ };
217
+ const EndpointDidNotReturnAResponse = {
218
+ name: "EndpointDidNotReturnAResponse",
219
+ title: "The endpoint did not return a `Response`.",
220
+ message: "An endpoint must return either a `Response`, or a `Promise` that resolves with a `Response`."
221
+ };
222
+ const LocalsNotAnObject = {
223
+ name: "LocalsNotAnObject",
224
+ title: "Value assigned to `locals` is not accepted.",
225
+ message: "`locals` can only be assigned to an object. Other values like numbers, strings, etc. are not accepted.",
226
+ hint: "If you tried to remove some information from the `locals` object, try to use `delete` or set the property to `undefined`."
227
+ };
228
+ const LocalsReassigned = {
229
+ name: "LocalsReassigned",
230
+ title: "`locals` must not be reassigned.",
231
+ message: "`locals` can not be assigned directly.",
232
+ hint: "Set a `locals` property instead."
233
+ };
234
+ const AstroResponseHeadersReassigned = {
235
+ name: "AstroResponseHeadersReassigned",
236
+ title: "`Astro.response.headers` must not be reassigned.",
237
+ message: "Individual headers can be added to and removed from `Astro.response.headers`, but it must not be replaced with another instance of `Headers` altogether.",
238
+ hint: "Consider using `Astro.response.headers.add()`, and `Astro.response.headers.delete()`."
239
+ };
240
+ const LocalImageUsedWrongly = {
241
+ name: "LocalImageUsedWrongly",
242
+ title: "Local images must be imported.",
243
+ message: (imageFilePath) => `\`Image\`'s and \`getImage\`'s \`src\` parameter must be an imported image or an URL, it cannot be a string filepath. Received \`${imageFilePath}\`.`,
244
+ hint: "If you want to use an image from your `src` folder, you need to either import it or if the image is coming from a content collection, use the [image() schema helper](https://docs.astro.build/en/guides/images/#images-in-content-collections). See https://docs.astro.build/en/guides/images/#src-required for more information on the `src` property."
245
+ };
246
+ const AstroGlobUsedOutside = {
247
+ name: "AstroGlobUsedOutside",
248
+ title: "Astro.glob() used outside of an Astro file.",
249
+ message: (globStr) => `\`Astro.glob(${globStr})\` can only be used in \`.astro\` files. \`import.meta.glob(${globStr})\` can be used instead to achieve a similar result.`,
250
+ hint: "See Vite's documentation on `import.meta.glob` for more information: https://vite.dev/guide/features.html#glob-import"
251
+ };
252
+ const AstroGlobNoMatch = {
253
+ name: "AstroGlobNoMatch",
254
+ title: "Astro.glob() did not match any files.",
255
+ message: (globStr) => `\`Astro.glob(${globStr})\` did not return any matching files.`,
256
+ hint: "Check the pattern for typos."
257
+ };
258
+ const MissingSharp = {
259
+ name: "MissingSharp",
260
+ title: "Could not find Sharp.",
261
+ message: "Could not find Sharp. Please install Sharp (`sharp`) manually into your project or migrate to another image service.",
262
+ hint: "See Sharp's installation instructions for more information: https://sharp.pixelplumbing.com/install. If you are not relying on `astro:assets` to optimize, transform, or process any images, you can configure a passthrough image service instead of installing Sharp. See https://docs.astro.build/en/reference/errors/missing-sharp for more information.\n\nSee https://docs.astro.build/en/guides/images/#default-image-service for more information on how to migrate to another image service."
263
+ };
264
+ const i18nNoLocaleFoundInPath = {
265
+ name: "i18nNoLocaleFoundInPath",
266
+ title: "The path doesn't contain any locale",
267
+ message: "You tried to use an i18n utility on a path that doesn't contain any locale. You can use `pathHasLocale` first to determine if the path has a locale."
268
+ };
269
+ const RewriteWithBodyUsed = {
270
+ name: "RewriteWithBodyUsed",
271
+ title: "Cannot use Astro.rewrite after the request body has been read",
272
+ message: "Astro.rewrite() cannot be used if the request body has already been read. If you need to read the body, first clone the request."
273
+ };
274
+ const ForbiddenRewrite = {
275
+ name: "ForbiddenRewrite",
276
+ title: "Forbidden rewrite to a static route.",
277
+ message: (from, to, component) => `You tried to rewrite the on-demand route '${from}' with the static route '${to}', when using the 'server' output.
278
+
279
+ The static route '${to}' is rendered by the component
280
+ '${component}', which is marked as prerendered. This is a forbidden operation because during the build the component '${component}' is compiled to an
281
+ HTML file, which can't be retrieved at runtime by Astro.`,
282
+ hint: (component) => `Add \`export const prerender = false\` to the component '${component}', or use a Astro.redirect().`
283
+ };
284
+ const ExperimentalFontsNotEnabled = {
285
+ name: "ExperimentalFontsNotEnabled",
286
+ title: "Experimental fonts are not enabled",
287
+ message: "The Font component is used but experimental fonts have not been registered in the config.",
288
+ hint: "Check that you have enabled experimental fonts and also configured your preferred fonts."
289
+ };
290
+ const FontFamilyNotFound = {
291
+ name: "FontFamilyNotFound",
292
+ title: "Font family not found",
293
+ message: (family) => `No data was found for the \`"${family}"\` family passed to the \`<Font>\` component.`,
294
+ hint: "This is often caused by a typo. Check that the `<Font />` component or `getFontData()` function are using a `cssVariable` specified in your config."
295
+ };
296
+ const CspNotEnabled = {
297
+ name: "CspNotEnabled",
298
+ title: "CSP feature isn't enabled",
299
+ message: "The `experimental.csp` configuration isn't enabled."
300
+ };
301
+ const ActionsReturnedInvalidDataError = {
302
+ name: "ActionsReturnedInvalidDataError",
303
+ title: "Action handler returned invalid data.",
304
+ message: (error) => `Action handler returned invalid data. Handlers should return serializable data types like objects, arrays, strings, and numbers. Parse error: ${error}`,
305
+ hint: "See the devalue library for all supported types: https://github.com/rich-harris/devalue"
306
+ };
307
+ const ActionNotFoundError = {
308
+ name: "ActionNotFoundError",
309
+ title: "Action not found.",
310
+ message: (actionName) => `The server received a request for an action named \`${actionName}\` but could not find a match. If you renamed an action, check that you've updated your \`actions/index\` file and your calling code to match.`,
311
+ hint: "You can run `astro check` to detect type errors caused by mismatched action names."
312
+ };
313
+ const SessionStorageInitError = {
314
+ name: "SessionStorageInitError",
315
+ title: "Session storage could not be initialized.",
316
+ message: (error, driver) => `Error when initializing session storage${driver ? ` with driver \`${driver}\`` : ""}. \`${error ?? ""}\``,
317
+ hint: "For more information, see https://docs.astro.build/en/guides/sessions/"
318
+ };
319
+ const SessionStorageSaveError = {
320
+ name: "SessionStorageSaveError",
321
+ title: "Session data could not be saved.",
322
+ message: (error, driver) => `Error when saving session data${driver ? ` with driver \`${driver}\`` : ""}. \`${error ?? ""}\``,
323
+ hint: "For more information, see https://docs.astro.build/en/guides/sessions/"
324
+ };
325
+
326
+ function normalizeLF(code) {
327
+ return code.replace(/\r\n|\r(?!\n)|\n/g, "\n");
328
+ }
329
+
330
+ function codeFrame(src, loc) {
331
+ if (!loc || loc.line === void 0 || loc.column === void 0) {
332
+ return "";
333
+ }
334
+ const lines = normalizeLF(src).split("\n").map((ln) => ln.replace(/\t/g, " "));
335
+ const visibleLines = [];
336
+ for (let n = -2; n <= 2; n++) {
337
+ if (lines[loc.line + n]) visibleLines.push(loc.line + n);
338
+ }
339
+ let gutterWidth = 0;
340
+ for (const lineNo of visibleLines) {
341
+ let w = `> ${lineNo}`;
342
+ if (w.length > gutterWidth) gutterWidth = w.length;
343
+ }
344
+ let output = "";
345
+ for (const lineNo of visibleLines) {
346
+ const isFocusedLine = lineNo === loc.line - 1;
347
+ output += isFocusedLine ? "> " : " ";
348
+ output += `${lineNo + 1} | ${lines[lineNo]}
349
+ `;
350
+ if (isFocusedLine)
351
+ output += `${Array.from({ length: gutterWidth }).join(" ")} | ${Array.from({
352
+ length: loc.column
353
+ }).join(" ")}^
354
+ `;
355
+ }
356
+ return output;
357
+ }
358
+
359
+ class AstroError extends Error {
360
+ loc;
361
+ title;
362
+ hint;
363
+ frame;
364
+ type = "AstroError";
365
+ constructor(props, options) {
366
+ const { name, title, message, stack, location, hint, frame } = props;
367
+ super(message, options);
368
+ this.title = title;
369
+ this.name = name;
370
+ if (message) this.message = message;
371
+ this.stack = stack ? stack : this.stack;
372
+ this.loc = location;
373
+ this.hint = hint;
374
+ this.frame = frame;
375
+ }
376
+ setLocation(location) {
377
+ this.loc = location;
378
+ }
379
+ setName(name) {
380
+ this.name = name;
381
+ }
382
+ setMessage(message) {
383
+ this.message = message;
384
+ }
385
+ setHint(hint) {
386
+ this.hint = hint;
387
+ }
388
+ setFrame(source, location) {
389
+ this.frame = codeFrame(source, location);
390
+ }
391
+ static is(err) {
392
+ return err?.type === "AstroError";
393
+ }
394
+ }
395
+
396
+ function validateArgs(args) {
397
+ if (args.length !== 3) return false;
398
+ if (!args[0] || typeof args[0] !== "object") return false;
399
+ return true;
400
+ }
401
+ function baseCreateComponent(cb, moduleId, propagation) {
402
+ const name = moduleId?.split("/").pop()?.replace(".astro", "") ?? "";
403
+ const fn = (...args) => {
404
+ if (!validateArgs(args)) {
405
+ throw new AstroError({
406
+ ...InvalidComponentArgs,
407
+ message: InvalidComponentArgs.message(name)
408
+ });
409
+ }
410
+ return cb(...args);
411
+ };
412
+ Object.defineProperty(fn, "name", { value: name, writable: false });
413
+ fn.isAstroComponentFactory = true;
414
+ fn.moduleId = moduleId;
415
+ fn.propagation = propagation;
416
+ return fn;
417
+ }
418
+ function createComponentWithOptions(opts) {
419
+ const cb = baseCreateComponent(opts.factory, opts.moduleId, opts.propagation);
420
+ return cb;
421
+ }
422
+ function createComponent(arg1, moduleId, propagation) {
423
+ if (typeof arg1 === "function") {
424
+ return baseCreateComponent(arg1, moduleId, propagation);
425
+ } else {
426
+ return createComponentWithOptions(arg1);
427
+ }
428
+ }
429
+
430
+ function createAstroGlobFn() {
431
+ const globHandler = (importMetaGlobResult) => {
432
+ console.warn(`Astro.glob is deprecated and will be removed in a future major version of Astro.
433
+ Use import.meta.glob instead: https://vitejs.dev/guide/features.html#glob-import`);
434
+ if (typeof importMetaGlobResult === "string") {
435
+ throw new AstroError({
436
+ ...AstroGlobUsedOutside,
437
+ message: AstroGlobUsedOutside.message(JSON.stringify(importMetaGlobResult))
438
+ });
439
+ }
440
+ let allEntries = [...Object.values(importMetaGlobResult)];
441
+ if (allEntries.length === 0) {
442
+ throw new AstroError({
443
+ ...AstroGlobNoMatch,
444
+ message: AstroGlobNoMatch.message(JSON.stringify(importMetaGlobResult))
445
+ });
446
+ }
447
+ return Promise.all(allEntries.map((fn) => fn()));
448
+ };
449
+ return globHandler;
450
+ }
451
+ function createAstro(site) {
452
+ return {
453
+ site: void 0,
454
+ generator: `Astro v${ASTRO_VERSION}`,
455
+ glob: createAstroGlobFn()
456
+ };
457
+ }
458
+
459
+ async function renderEndpoint(mod, context, isPrerendered, logger) {
460
+ const { request, url } = context;
461
+ const method = request.method.toUpperCase();
462
+ let handler = mod[method] ?? mod["ALL"];
463
+ if (!handler && method === "HEAD" && mod["GET"]) {
464
+ handler = mod["GET"];
465
+ }
466
+ if (isPrerendered && !["GET", "HEAD"].includes(method)) {
467
+ logger.warn(
468
+ "router",
469
+ `${url.pathname} ${colors.bold(
470
+ method
471
+ )} requests are not available in static endpoints. Mark this page as server-rendered (\`export const prerender = false;\`) or update your config to \`output: 'server'\` to make all your pages server-rendered by default.`
472
+ );
473
+ }
474
+ if (handler === void 0) {
475
+ logger.warn(
476
+ "router",
477
+ `No API Route handler exists for the method "${method}" for the route "${url.pathname}".
478
+ Found handlers: ${Object.keys(mod).map((exp) => JSON.stringify(exp)).join(", ")}
479
+ ` + ("all" in mod ? `One of the exported handlers is "all" (lowercase), did you mean to export 'ALL'?
480
+ ` : "")
481
+ );
482
+ return new Response(null, { status: 404 });
483
+ }
484
+ if (typeof handler !== "function") {
485
+ logger.error(
486
+ "router",
487
+ `The route "${url.pathname}" exports a value for the method "${method}", but it is of the type ${typeof handler} instead of a function.`
488
+ );
489
+ return new Response(null, { status: 500 });
490
+ }
491
+ let response = await handler.call(mod, context);
492
+ if (!response || response instanceof Response === false) {
493
+ throw new AstroError(EndpointDidNotReturnAResponse);
494
+ }
495
+ if (REROUTABLE_STATUS_CODES.includes(response.status)) {
496
+ try {
497
+ response.headers.set(REROUTE_DIRECTIVE_HEADER, "no");
498
+ } catch (err) {
499
+ if (err.message?.includes("immutable")) {
500
+ response = new Response(response.body, response);
501
+ response.headers.set(REROUTE_DIRECTIVE_HEADER, "no");
502
+ } else {
503
+ throw err;
504
+ }
505
+ }
506
+ }
507
+ if (method === "HEAD") {
508
+ return new Response(null, response);
509
+ }
510
+ return response;
511
+ }
512
+
513
+ function isPromise(value) {
514
+ return !!value && typeof value === "object" && "then" in value && typeof value.then === "function";
515
+ }
516
+ async function* streamAsyncIterator(stream) {
517
+ const reader = stream.getReader();
518
+ try {
519
+ while (true) {
520
+ const { done, value } = await reader.read();
521
+ if (done) return;
522
+ yield value;
523
+ }
524
+ } finally {
525
+ reader.releaseLock();
526
+ }
527
+ }
528
+
529
+ const escapeHTML = escape;
530
+ class HTMLBytes extends Uint8Array {
531
+ }
532
+ Object.defineProperty(HTMLBytes.prototype, Symbol.toStringTag, {
533
+ get() {
534
+ return "HTMLBytes";
535
+ }
536
+ });
537
+ class HTMLString extends String {
538
+ get [Symbol.toStringTag]() {
539
+ return "HTMLString";
540
+ }
541
+ }
542
+ const markHTMLString = (value) => {
543
+ if (value instanceof HTMLString) {
544
+ return value;
545
+ }
546
+ if (typeof value === "string") {
547
+ return new HTMLString(value);
548
+ }
549
+ return value;
550
+ };
551
+ function isHTMLString(value) {
552
+ return Object.prototype.toString.call(value) === "[object HTMLString]";
553
+ }
554
+ function markHTMLBytes(bytes) {
555
+ return new HTMLBytes(bytes);
556
+ }
557
+ function hasGetReader(obj) {
558
+ return typeof obj.getReader === "function";
559
+ }
560
+ async function* unescapeChunksAsync(iterable) {
561
+ if (hasGetReader(iterable)) {
562
+ for await (const chunk of streamAsyncIterator(iterable)) {
563
+ yield unescapeHTML(chunk);
564
+ }
565
+ } else {
566
+ for await (const chunk of iterable) {
567
+ yield unescapeHTML(chunk);
568
+ }
569
+ }
570
+ }
571
+ function* unescapeChunks(iterable) {
572
+ for (const chunk of iterable) {
573
+ yield unescapeHTML(chunk);
574
+ }
575
+ }
576
+ function unescapeHTML(str) {
577
+ if (!!str && typeof str === "object") {
578
+ if (str instanceof Uint8Array) {
579
+ return markHTMLBytes(str);
580
+ } else if (str instanceof Response && str.body) {
581
+ const body = str.body;
582
+ return unescapeChunksAsync(body);
583
+ } else if (typeof str.then === "function") {
584
+ return Promise.resolve(str).then((value) => {
585
+ return unescapeHTML(value);
586
+ });
587
+ } else if (str[Symbol.for("astro:slot-string")]) {
588
+ return str;
589
+ } else if (Symbol.iterator in str) {
590
+ return unescapeChunks(str);
591
+ } else if (Symbol.asyncIterator in str || hasGetReader(str)) {
592
+ return unescapeChunksAsync(str);
593
+ }
594
+ }
595
+ return markHTMLString(str);
596
+ }
597
+
598
+ const AstroJSX = "astro:jsx";
599
+ function isVNode(vnode) {
600
+ return vnode && typeof vnode === "object" && vnode[AstroJSX];
601
+ }
602
+
603
+ function isAstroComponentFactory(obj) {
604
+ return obj == null ? false : obj.isAstroComponentFactory === true;
605
+ }
606
+ function isAPropagatingComponent(result, factory) {
607
+ const hint = getPropagationHint(result, factory);
608
+ return hint === "in-tree" || hint === "self";
609
+ }
610
+ function getPropagationHint(result, factory) {
611
+ let hint = factory.propagation || "none";
612
+ if (factory.moduleId && result.componentMetadata.has(factory.moduleId) && hint === "none") {
613
+ hint = result.componentMetadata.get(factory.moduleId).propagation;
614
+ }
615
+ return hint;
616
+ }
617
+
618
+ const PROP_TYPE = {
619
+ Value: 0,
620
+ JSON: 1,
621
+ // Actually means Array
622
+ RegExp: 2,
623
+ Date: 3,
624
+ Map: 4,
625
+ Set: 5,
626
+ BigInt: 6,
627
+ URL: 7,
628
+ Uint8Array: 8,
629
+ Uint16Array: 9,
630
+ Uint32Array: 10,
631
+ Infinity: 11
632
+ };
633
+ function serializeArray(value, metadata = {}, parents = /* @__PURE__ */ new WeakSet()) {
634
+ if (parents.has(value)) {
635
+ throw new Error(`Cyclic reference detected while serializing props for <${metadata.displayName} client:${metadata.hydrate}>!
636
+
637
+ Cyclic references cannot be safely serialized for client-side usage. Please remove the cyclic reference.`);
638
+ }
639
+ parents.add(value);
640
+ const serialized = value.map((v) => {
641
+ return convertToSerializedForm(v, metadata, parents);
642
+ });
643
+ parents.delete(value);
644
+ return serialized;
645
+ }
646
+ function serializeObject(value, metadata = {}, parents = /* @__PURE__ */ new WeakSet()) {
647
+ if (parents.has(value)) {
648
+ throw new Error(`Cyclic reference detected while serializing props for <${metadata.displayName} client:${metadata.hydrate}>!
649
+
650
+ Cyclic references cannot be safely serialized for client-side usage. Please remove the cyclic reference.`);
651
+ }
652
+ parents.add(value);
653
+ const serialized = Object.fromEntries(
654
+ Object.entries(value).map(([k, v]) => {
655
+ return [k, convertToSerializedForm(v, metadata, parents)];
656
+ })
657
+ );
658
+ parents.delete(value);
659
+ return serialized;
660
+ }
661
+ function convertToSerializedForm(value, metadata = {}, parents = /* @__PURE__ */ new WeakSet()) {
662
+ const tag = Object.prototype.toString.call(value);
663
+ switch (tag) {
664
+ case "[object Date]": {
665
+ return [PROP_TYPE.Date, value.toISOString()];
666
+ }
667
+ case "[object RegExp]": {
668
+ return [PROP_TYPE.RegExp, value.source];
669
+ }
670
+ case "[object Map]": {
671
+ return [PROP_TYPE.Map, serializeArray(Array.from(value), metadata, parents)];
672
+ }
673
+ case "[object Set]": {
674
+ return [PROP_TYPE.Set, serializeArray(Array.from(value), metadata, parents)];
675
+ }
676
+ case "[object BigInt]": {
677
+ return [PROP_TYPE.BigInt, value.toString()];
678
+ }
679
+ case "[object URL]": {
680
+ return [PROP_TYPE.URL, value.toString()];
681
+ }
682
+ case "[object Array]": {
683
+ return [PROP_TYPE.JSON, serializeArray(value, metadata, parents)];
684
+ }
685
+ case "[object Uint8Array]": {
686
+ return [PROP_TYPE.Uint8Array, Array.from(value)];
687
+ }
688
+ case "[object Uint16Array]": {
689
+ return [PROP_TYPE.Uint16Array, Array.from(value)];
690
+ }
691
+ case "[object Uint32Array]": {
692
+ return [PROP_TYPE.Uint32Array, Array.from(value)];
693
+ }
694
+ default: {
695
+ if (value !== null && typeof value === "object") {
696
+ return [PROP_TYPE.Value, serializeObject(value, metadata, parents)];
697
+ }
698
+ if (value === Infinity) {
699
+ return [PROP_TYPE.Infinity, 1];
700
+ }
701
+ if (value === -Infinity) {
702
+ return [PROP_TYPE.Infinity, -1];
703
+ }
704
+ if (value === void 0) {
705
+ return [PROP_TYPE.Value];
706
+ }
707
+ return [PROP_TYPE.Value, value];
708
+ }
709
+ }
710
+ }
711
+ function serializeProps(props, metadata) {
712
+ const serialized = JSON.stringify(serializeObject(props, metadata));
713
+ return serialized;
714
+ }
715
+
716
+ const transitionDirectivesToCopyOnIsland = Object.freeze([
717
+ "data-astro-transition-scope",
718
+ "data-astro-transition-persist",
719
+ "data-astro-transition-persist-props"
720
+ ]);
721
+ function extractDirectives(inputProps, clientDirectives) {
722
+ let extracted = {
723
+ isPage: false,
724
+ hydration: null,
725
+ props: {},
726
+ propsWithoutTransitionAttributes: {}
727
+ };
728
+ for (const [key, value] of Object.entries(inputProps)) {
729
+ if (key.startsWith("server:")) {
730
+ if (key === "server:root") {
731
+ extracted.isPage = true;
732
+ }
733
+ }
734
+ if (key.startsWith("client:")) {
735
+ if (!extracted.hydration) {
736
+ extracted.hydration = {
737
+ directive: "",
738
+ value: "",
739
+ componentUrl: "",
740
+ componentExport: { value: "" }
741
+ };
742
+ }
743
+ switch (key) {
744
+ case "client:component-path": {
745
+ extracted.hydration.componentUrl = value;
746
+ break;
747
+ }
748
+ case "client:component-export": {
749
+ extracted.hydration.componentExport.value = value;
750
+ break;
751
+ }
752
+ // This is a special prop added to prove that the client hydration method
753
+ // was added statically.
754
+ case "client:component-hydration": {
755
+ break;
756
+ }
757
+ case "client:display-name": {
758
+ break;
759
+ }
760
+ default: {
761
+ extracted.hydration.directive = key.split(":")[1];
762
+ extracted.hydration.value = value;
763
+ if (!clientDirectives.has(extracted.hydration.directive)) {
764
+ const hydrationMethods = Array.from(clientDirectives.keys()).map((d) => `client:${d}`).join(", ");
765
+ throw new Error(
766
+ `Error: invalid hydration directive "${key}". Supported hydration methods: ${hydrationMethods}`
767
+ );
768
+ }
769
+ if (extracted.hydration.directive === "media" && typeof extracted.hydration.value !== "string") {
770
+ throw new AstroError(MissingMediaQueryDirective);
771
+ }
772
+ break;
773
+ }
774
+ }
775
+ } else {
776
+ extracted.props[key] = value;
777
+ if (!transitionDirectivesToCopyOnIsland.includes(key)) {
778
+ extracted.propsWithoutTransitionAttributes[key] = value;
779
+ }
780
+ }
781
+ }
782
+ for (const sym of Object.getOwnPropertySymbols(inputProps)) {
783
+ extracted.props[sym] = inputProps[sym];
784
+ extracted.propsWithoutTransitionAttributes[sym] = inputProps[sym];
785
+ }
786
+ return extracted;
787
+ }
788
+ async function generateHydrateScript(scriptOptions, metadata) {
789
+ const { renderer, result, astroId, props, attrs } = scriptOptions;
790
+ const { hydrate, componentUrl, componentExport } = metadata;
791
+ if (!componentExport.value) {
792
+ throw new AstroError({
793
+ ...NoMatchingImport,
794
+ message: NoMatchingImport.message(metadata.displayName)
795
+ });
796
+ }
797
+ const island = {
798
+ children: "",
799
+ props: {
800
+ // This is for HMR, probably can avoid it in prod
801
+ uid: astroId
802
+ }
803
+ };
804
+ if (attrs) {
805
+ for (const [key, value] of Object.entries(attrs)) {
806
+ island.props[key] = escapeHTML(value);
807
+ }
808
+ }
809
+ island.props["component-url"] = await result.resolve(decodeURI(componentUrl));
810
+ if (renderer.clientEntrypoint) {
811
+ island.props["component-export"] = componentExport.value;
812
+ island.props["renderer-url"] = await result.resolve(
813
+ decodeURI(renderer.clientEntrypoint.toString())
814
+ );
815
+ island.props["props"] = escapeHTML(serializeProps(props, metadata));
816
+ }
817
+ island.props["ssr"] = "";
818
+ island.props["client"] = hydrate;
819
+ let beforeHydrationUrl = await result.resolve("astro:scripts/before-hydration.js");
820
+ if (beforeHydrationUrl.length) {
821
+ island.props["before-hydration-url"] = beforeHydrationUrl;
822
+ }
823
+ island.props["opts"] = escapeHTML(
824
+ JSON.stringify({
825
+ name: metadata.displayName,
826
+ value: metadata.hydrateArgs || ""
827
+ })
828
+ );
829
+ transitionDirectivesToCopyOnIsland.forEach((name) => {
830
+ if (typeof props[name] !== "undefined") {
831
+ island.props[name] = props[name];
832
+ }
833
+ });
834
+ return island;
835
+ }
836
+
837
+ /**
838
+ * shortdash - https://github.com/bibig/node-shorthash
839
+ *
840
+ * @license
841
+ *
842
+ * (The MIT License)
843
+ *
844
+ * Copyright (c) 2013 Bibig <bibig@me.com>
845
+ *
846
+ * Permission is hereby granted, free of charge, to any person
847
+ * obtaining a copy of this software and associated documentation
848
+ * files (the "Software"), to deal in the Software without
849
+ * restriction, including without limitation the rights to use,
850
+ * copy, modify, merge, publish, distribute, sublicense, and/or sell
851
+ * copies of the Software, and to permit persons to whom the
852
+ * Software is furnished to do so, subject to the following
853
+ * conditions:
854
+ *
855
+ * The above copyright notice and this permission notice shall be
856
+ * included in all copies or substantial portions of the Software.
857
+ *
858
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
859
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
860
+ * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
861
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
862
+ * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
863
+ * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
864
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
865
+ * OTHER DEALINGS IN THE SOFTWARE.
866
+ */
867
+ const dictionary = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXY";
868
+ const binary = dictionary.length;
869
+ function bitwise(str) {
870
+ let hash = 0;
871
+ if (str.length === 0) return hash;
872
+ for (let i = 0; i < str.length; i++) {
873
+ const ch = str.charCodeAt(i);
874
+ hash = (hash << 5) - hash + ch;
875
+ hash = hash & hash;
876
+ }
877
+ return hash;
878
+ }
879
+ function shorthash(text) {
880
+ let num;
881
+ let result = "";
882
+ let integer = bitwise(text);
883
+ const sign = integer < 0 ? "Z" : "";
884
+ integer = Math.abs(integer);
885
+ while (integer >= binary) {
886
+ num = integer % binary;
887
+ integer = Math.floor(integer / binary);
888
+ result = dictionary[num] + result;
889
+ }
890
+ if (integer > 0) {
891
+ result = dictionary[integer] + result;
892
+ }
893
+ return sign + result;
894
+ }
895
+
896
+ const headAndContentSym = Symbol.for("astro.headAndContent");
897
+ function isHeadAndContent(obj) {
898
+ return typeof obj === "object" && obj !== null && !!obj[headAndContentSym];
899
+ }
900
+ function createThinHead() {
901
+ return {
902
+ [headAndContentSym]: true
903
+ };
904
+ }
905
+
906
+ var astro_island_prebuilt_default = `(()=>{var A=Object.defineProperty;var g=(i,o,a)=>o in i?A(i,o,{enumerable:!0,configurable:!0,writable:!0,value:a}):i[o]=a;var d=(i,o,a)=>g(i,typeof o!="symbol"?o+"":o,a);{let i={0:t=>m(t),1:t=>a(t),2:t=>new RegExp(t),3:t=>new Date(t),4:t=>new Map(a(t)),5:t=>new Set(a(t)),6:t=>BigInt(t),7:t=>new URL(t),8:t=>new Uint8Array(t),9:t=>new Uint16Array(t),10:t=>new Uint32Array(t),11:t=>1/0*t},o=t=>{let[l,e]=t;return l in i?i[l](e):void 0},a=t=>t.map(o),m=t=>typeof t!="object"||t===null?t:Object.fromEntries(Object.entries(t).map(([l,e])=>[l,o(e)]));class y extends HTMLElement{constructor(){super(...arguments);d(this,"Component");d(this,"hydrator");d(this,"hydrate",async()=>{var b;if(!this.hydrator||!this.isConnected)return;let e=(b=this.parentElement)==null?void 0:b.closest("astro-island[ssr]");if(e){e.addEventListener("astro:hydrate",this.hydrate,{once:!0});return}let c=this.querySelectorAll("astro-slot"),n={},h=this.querySelectorAll("template[data-astro-template]");for(let r of h){let s=r.closest(this.tagName);s!=null&&s.isSameNode(this)&&(n[r.getAttribute("data-astro-template")||"default"]=r.innerHTML,r.remove())}for(let r of c){let s=r.closest(this.tagName);s!=null&&s.isSameNode(this)&&(n[r.getAttribute("name")||"default"]=r.innerHTML)}let p;try{p=this.hasAttribute("props")?m(JSON.parse(this.getAttribute("props"))):{}}catch(r){let s=this.getAttribute("component-url")||"<unknown>",v=this.getAttribute("component-export");throw v&&(s+=\` (export \${v})\`),console.error(\`[hydrate] Error parsing props for component \${s}\`,this.getAttribute("props"),r),r}let u;await this.hydrator(this)(this.Component,p,n,{client:this.getAttribute("client")}),this.removeAttribute("ssr"),this.dispatchEvent(new CustomEvent("astro:hydrate"))});d(this,"unmount",()=>{this.isConnected||this.dispatchEvent(new CustomEvent("astro:unmount"))})}disconnectedCallback(){document.removeEventListener("astro:after-swap",this.unmount),document.addEventListener("astro:after-swap",this.unmount,{once:!0})}connectedCallback(){if(!this.hasAttribute("await-children")||document.readyState==="interactive"||document.readyState==="complete")this.childrenConnectedCallback();else{let e=()=>{document.removeEventListener("DOMContentLoaded",e),c.disconnect(),this.childrenConnectedCallback()},c=new MutationObserver(()=>{var n;((n=this.lastChild)==null?void 0:n.nodeType)===Node.COMMENT_NODE&&this.lastChild.nodeValue==="astro:end"&&(this.lastChild.remove(),e())});c.observe(this,{childList:!0}),document.addEventListener("DOMContentLoaded",e)}}async childrenConnectedCallback(){let e=this.getAttribute("before-hydration-url");e&&await import(e),this.start()}async start(){let e=JSON.parse(this.getAttribute("opts")),c=this.getAttribute("client");if(Astro[c]===void 0){window.addEventListener(\`astro:\${c}\`,()=>this.start(),{once:!0});return}try{await Astro[c](async()=>{let n=this.getAttribute("renderer-url"),[h,{default:p}]=await Promise.all([import(this.getAttribute("component-url")),n?import(n):()=>()=>{}]),u=this.getAttribute("component-export")||"default";if(!u.includes("."))this.Component=h[u];else{this.Component=h;for(let f of u.split("."))this.Component=this.Component[f]}return this.hydrator=p,this.hydrate},e,this)}catch(n){console.error(\`[astro-island] Error hydrating \${this.getAttribute("component-url")}\`,n)}}attributeChangedCallback(){this.hydrate()}}d(y,"observedAttributes",["props"]),customElements.get("astro-island")||customElements.define("astro-island",y)}})();`;
907
+
908
+ var astro_island_prebuilt_dev_default = `(()=>{var A=Object.defineProperty;var g=(i,o,a)=>o in i?A(i,o,{enumerable:!0,configurable:!0,writable:!0,value:a}):i[o]=a;var l=(i,o,a)=>g(i,typeof o!="symbol"?o+"":o,a);{let i={0:t=>y(t),1:t=>a(t),2:t=>new RegExp(t),3:t=>new Date(t),4:t=>new Map(a(t)),5:t=>new Set(a(t)),6:t=>BigInt(t),7:t=>new URL(t),8:t=>new Uint8Array(t),9:t=>new Uint16Array(t),10:t=>new Uint32Array(t),11:t=>1/0*t},o=t=>{let[h,e]=t;return h in i?i[h](e):void 0},a=t=>t.map(o),y=t=>typeof t!="object"||t===null?t:Object.fromEntries(Object.entries(t).map(([h,e])=>[h,o(e)]));class f extends HTMLElement{constructor(){super(...arguments);l(this,"Component");l(this,"hydrator");l(this,"hydrate",async()=>{var b;if(!this.hydrator||!this.isConnected)return;let e=(b=this.parentElement)==null?void 0:b.closest("astro-island[ssr]");if(e){e.addEventListener("astro:hydrate",this.hydrate,{once:!0});return}let c=this.querySelectorAll("astro-slot"),n={},p=this.querySelectorAll("template[data-astro-template]");for(let r of p){let s=r.closest(this.tagName);s!=null&&s.isSameNode(this)&&(n[r.getAttribute("data-astro-template")||"default"]=r.innerHTML,r.remove())}for(let r of c){let s=r.closest(this.tagName);s!=null&&s.isSameNode(this)&&(n[r.getAttribute("name")||"default"]=r.innerHTML)}let u;try{u=this.hasAttribute("props")?y(JSON.parse(this.getAttribute("props"))):{}}catch(r){let s=this.getAttribute("component-url")||"<unknown>",v=this.getAttribute("component-export");throw v&&(s+=\` (export \${v})\`),console.error(\`[hydrate] Error parsing props for component \${s}\`,this.getAttribute("props"),r),r}let d,m=this.hydrator(this);d=performance.now(),await m(this.Component,u,n,{client:this.getAttribute("client")}),d&&this.setAttribute("client-render-time",(performance.now()-d).toString()),this.removeAttribute("ssr"),this.dispatchEvent(new CustomEvent("astro:hydrate"))});l(this,"unmount",()=>{this.isConnected||this.dispatchEvent(new CustomEvent("astro:unmount"))})}disconnectedCallback(){document.removeEventListener("astro:after-swap",this.unmount),document.addEventListener("astro:after-swap",this.unmount,{once:!0})}connectedCallback(){if(!this.hasAttribute("await-children")||document.readyState==="interactive"||document.readyState==="complete")this.childrenConnectedCallback();else{let e=()=>{document.removeEventListener("DOMContentLoaded",e),c.disconnect(),this.childrenConnectedCallback()},c=new MutationObserver(()=>{var n;((n=this.lastChild)==null?void 0:n.nodeType)===Node.COMMENT_NODE&&this.lastChild.nodeValue==="astro:end"&&(this.lastChild.remove(),e())});c.observe(this,{childList:!0}),document.addEventListener("DOMContentLoaded",e)}}async childrenConnectedCallback(){let e=this.getAttribute("before-hydration-url");e&&await import(e),this.start()}async start(){let e=JSON.parse(this.getAttribute("opts")),c=this.getAttribute("client");if(Astro[c]===void 0){window.addEventListener(\`astro:\${c}\`,()=>this.start(),{once:!0});return}try{await Astro[c](async()=>{let n=this.getAttribute("renderer-url"),[p,{default:u}]=await Promise.all([import(this.getAttribute("component-url")),n?import(n):()=>()=>{}]),d=this.getAttribute("component-export")||"default";if(!d.includes("."))this.Component=p[d];else{this.Component=p;for(let m of d.split("."))this.Component=this.Component[m]}return this.hydrator=u,this.hydrate},e,this)}catch(n){console.error(\`[astro-island] Error hydrating \${this.getAttribute("component-url")}\`,n)}}attributeChangedCallback(){this.hydrate()}}l(f,"observedAttributes",["props"]),customElements.get("astro-island")||customElements.define("astro-island",f)}})();`;
909
+
910
+ const ISLAND_STYLES = "astro-island,astro-slot,astro-static-slot{display:contents}";
911
+
912
+ function determineIfNeedsHydrationScript(result) {
913
+ if (result._metadata.hasHydrationScript) {
914
+ return false;
915
+ }
916
+ return result._metadata.hasHydrationScript = true;
917
+ }
918
+ function determinesIfNeedsDirectiveScript(result, directive) {
919
+ if (result._metadata.hasDirectives.has(directive)) {
920
+ return false;
921
+ }
922
+ result._metadata.hasDirectives.add(directive);
923
+ return true;
924
+ }
925
+ function getDirectiveScriptText(result, directive) {
926
+ const clientDirectives = result.clientDirectives;
927
+ const clientDirective = clientDirectives.get(directive);
928
+ if (!clientDirective) {
929
+ throw new Error(`Unknown directive: ${directive}`);
930
+ }
931
+ return clientDirective;
932
+ }
933
+ function getPrescripts(result, type, directive) {
934
+ switch (type) {
935
+ case "both":
936
+ return `<style>${ISLAND_STYLES}</style><script>${getDirectiveScriptText(result, directive)}</script><script>${process.env.NODE_ENV === "development" ? astro_island_prebuilt_dev_default : astro_island_prebuilt_default}</script>`;
937
+ case "directive":
938
+ return `<script>${getDirectiveScriptText(result, directive)}</script>`;
939
+ }
940
+ }
941
+
942
+ function renderCspContent(result) {
943
+ const finalScriptHashes = /* @__PURE__ */ new Set();
944
+ const finalStyleHashes = /* @__PURE__ */ new Set();
945
+ for (const scriptHash of result.scriptHashes) {
946
+ finalScriptHashes.add(`'${scriptHash}'`);
947
+ }
948
+ for (const styleHash of result.styleHashes) {
949
+ finalStyleHashes.add(`'${styleHash}'`);
950
+ }
951
+ for (const styleHash of result._metadata.extraStyleHashes) {
952
+ finalStyleHashes.add(`'${styleHash}'`);
953
+ }
954
+ for (const scriptHash of result._metadata.extraScriptHashes) {
955
+ finalScriptHashes.add(`'${scriptHash}'`);
956
+ }
957
+ let directives;
958
+ if (result.directives.length > 0) {
959
+ directives = result.directives.join(";") + ";";
960
+ }
961
+ let scriptResources = "'self'";
962
+ if (result.scriptResources.length > 0) {
963
+ scriptResources = result.scriptResources.map((r) => `${r}`).join(" ");
964
+ }
965
+ let styleResources = "'self'";
966
+ if (result.styleResources.length > 0) {
967
+ styleResources = result.styleResources.map((r) => `${r}`).join(" ");
968
+ }
969
+ const strictDynamic = result.isStrictDynamic ? ` 'strict-dynamic'` : "";
970
+ const scriptSrc = `script-src ${scriptResources} ${Array.from(finalScriptHashes).join(" ")}${strictDynamic};`;
971
+ const styleSrc = `style-src ${styleResources} ${Array.from(finalStyleHashes).join(" ")};`;
972
+ return [directives, scriptSrc, styleSrc].filter(Boolean).join(" ");
973
+ }
974
+
975
+ const RenderInstructionSymbol = Symbol.for("astro:render");
976
+ function createRenderInstruction(instruction) {
977
+ return Object.defineProperty(instruction, RenderInstructionSymbol, {
978
+ value: true
979
+ });
980
+ }
981
+ function isRenderInstruction(chunk) {
982
+ return chunk && typeof chunk === "object" && chunk[RenderInstructionSymbol];
983
+ }
984
+
985
+ const voidElementNames = /^(area|base|br|col|command|embed|hr|img|input|keygen|link|meta|param|source|track|wbr)$/i;
986
+ const htmlBooleanAttributes = /^(?:allowfullscreen|async|autofocus|autoplay|checked|controls|default|defer|disabled|disablepictureinpicture|disableremoteplayback|formnovalidate|hidden|inert|loop|muted|nomodule|novalidate|open|playsinline|readonly|required|reversed|scoped|seamless|selected|itemscope)$/i;
987
+ const AMPERSAND_REGEX = /&/g;
988
+ const DOUBLE_QUOTE_REGEX = /"/g;
989
+ const STATIC_DIRECTIVES = /* @__PURE__ */ new Set(["set:html", "set:text"]);
990
+ const toIdent = (k) => k.trim().replace(/(?!^)\b\w|\s+|\W+/g, (match, index) => {
991
+ if (/\W/.test(match)) return "";
992
+ return index === 0 ? match : match.toUpperCase();
993
+ });
994
+ const toAttributeString = (value, shouldEscape = true) => shouldEscape ? String(value).replace(AMPERSAND_REGEX, "&#38;").replace(DOUBLE_QUOTE_REGEX, "&#34;") : value;
995
+ const kebab = (k) => k.toLowerCase() === k ? k : k.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`);
996
+ const toStyleString = (obj) => Object.entries(obj).filter(([_, v]) => typeof v === "string" && v.trim() || typeof v === "number").map(([k, v]) => {
997
+ if (k[0] !== "-" && k[1] !== "-") return `${kebab(k)}:${v}`;
998
+ return `${k}:${v}`;
999
+ }).join(";");
1000
+ function defineScriptVars(vars) {
1001
+ let output = "";
1002
+ for (const [key, value] of Object.entries(vars)) {
1003
+ output += `const ${toIdent(key)} = ${JSON.stringify(value)?.replace(
1004
+ /<\/script>/g,
1005
+ "\\x3C/script>"
1006
+ )};
1007
+ `;
1008
+ }
1009
+ return markHTMLString(output);
1010
+ }
1011
+ function formatList(values) {
1012
+ if (values.length === 1) {
1013
+ return values[0];
1014
+ }
1015
+ return `${values.slice(0, -1).join(", ")} or ${values[values.length - 1]}`;
1016
+ }
1017
+ function isCustomElement(tagName) {
1018
+ return tagName.includes("-");
1019
+ }
1020
+ function handleBooleanAttribute(key, value, shouldEscape, tagName) {
1021
+ if (tagName && isCustomElement(tagName)) {
1022
+ return markHTMLString(` ${key}="${toAttributeString(value, shouldEscape)}"`);
1023
+ }
1024
+ return markHTMLString(value ? ` ${key}` : "");
1025
+ }
1026
+ function addAttribute(value, key, shouldEscape = true, tagName = "") {
1027
+ if (value == null) {
1028
+ return "";
1029
+ }
1030
+ if (STATIC_DIRECTIVES.has(key)) {
1031
+ console.warn(`[astro] The "${key}" directive cannot be applied dynamically at runtime. It will not be rendered as an attribute.
1032
+
1033
+ Make sure to use the static attribute syntax (\`${key}={value}\`) instead of the dynamic spread syntax (\`{...{ "${key}": value }}\`).`);
1034
+ return "";
1035
+ }
1036
+ if (key === "class:list") {
1037
+ const listValue = toAttributeString(clsx(value), shouldEscape);
1038
+ if (listValue === "") {
1039
+ return "";
1040
+ }
1041
+ return markHTMLString(` ${key.slice(0, -5)}="${listValue}"`);
1042
+ }
1043
+ if (key === "style" && !(value instanceof HTMLString)) {
1044
+ if (Array.isArray(value) && value.length === 2) {
1045
+ return markHTMLString(
1046
+ ` ${key}="${toAttributeString(`${toStyleString(value[0])};${value[1]}`, shouldEscape)}"`
1047
+ );
1048
+ }
1049
+ if (typeof value === "object") {
1050
+ return markHTMLString(` ${key}="${toAttributeString(toStyleString(value), shouldEscape)}"`);
1051
+ }
1052
+ }
1053
+ if (key === "className") {
1054
+ return markHTMLString(` class="${toAttributeString(value, shouldEscape)}"`);
1055
+ }
1056
+ if (typeof value === "string" && value.includes("&") && isHttpUrl(value)) {
1057
+ return markHTMLString(` ${key}="${toAttributeString(value, false)}"`);
1058
+ }
1059
+ if (htmlBooleanAttributes.test(key)) {
1060
+ return handleBooleanAttribute(key, value, shouldEscape, tagName);
1061
+ }
1062
+ if (value === "") {
1063
+ return markHTMLString(` ${key}`);
1064
+ }
1065
+ if (key === "popover" && typeof value === "boolean") {
1066
+ return handleBooleanAttribute(key, value, shouldEscape, tagName);
1067
+ }
1068
+ if (key === "download" && typeof value === "boolean") {
1069
+ return handleBooleanAttribute(key, value, shouldEscape, tagName);
1070
+ }
1071
+ return markHTMLString(` ${key}="${toAttributeString(value, shouldEscape)}"`);
1072
+ }
1073
+ function internalSpreadAttributes(values, shouldEscape = true, tagName) {
1074
+ let output = "";
1075
+ for (const [key, value] of Object.entries(values)) {
1076
+ output += addAttribute(value, key, shouldEscape, tagName);
1077
+ }
1078
+ return markHTMLString(output);
1079
+ }
1080
+ function renderElement$1(name, { props: _props, children = "" }, shouldEscape = true) {
1081
+ const { lang: _, "data-astro-id": astroId, "define:vars": defineVars, ...props } = _props;
1082
+ if (defineVars) {
1083
+ if (name === "style") {
1084
+ delete props["is:global"];
1085
+ delete props["is:scoped"];
1086
+ }
1087
+ if (name === "script") {
1088
+ delete props.hoist;
1089
+ children = defineScriptVars(defineVars) + "\n" + children;
1090
+ }
1091
+ }
1092
+ if ((children == null || children == "") && voidElementNames.test(name)) {
1093
+ return `<${name}${internalSpreadAttributes(props, shouldEscape, name)}>`;
1094
+ }
1095
+ return `<${name}${internalSpreadAttributes(props, shouldEscape, name)}>${children}</${name}>`;
1096
+ }
1097
+ const noop = () => {
1098
+ };
1099
+ class BufferedRenderer {
1100
+ chunks = [];
1101
+ renderPromise;
1102
+ destination;
1103
+ /**
1104
+ * Determines whether buffer has been flushed
1105
+ * to the final destination.
1106
+ */
1107
+ flushed = false;
1108
+ constructor(destination, renderFunction) {
1109
+ this.destination = destination;
1110
+ this.renderPromise = renderFunction(this);
1111
+ if (isPromise(this.renderPromise)) {
1112
+ Promise.resolve(this.renderPromise).catch(noop);
1113
+ }
1114
+ }
1115
+ write(chunk) {
1116
+ if (this.flushed) {
1117
+ this.destination.write(chunk);
1118
+ } else {
1119
+ this.chunks.push(chunk);
1120
+ }
1121
+ }
1122
+ flush() {
1123
+ if (this.flushed) {
1124
+ throw new Error("The render buffer has already been flushed.");
1125
+ }
1126
+ this.flushed = true;
1127
+ for (const chunk of this.chunks) {
1128
+ this.destination.write(chunk);
1129
+ }
1130
+ return this.renderPromise;
1131
+ }
1132
+ }
1133
+ function createBufferedRenderer(destination, renderFunction) {
1134
+ return new BufferedRenderer(destination, renderFunction);
1135
+ }
1136
+ const isNode = typeof process !== "undefined" && Object.prototype.toString.call(process) === "[object process]";
1137
+ const isDeno = typeof Deno !== "undefined";
1138
+ function promiseWithResolvers() {
1139
+ let resolve, reject;
1140
+ const promise = new Promise((_resolve, _reject) => {
1141
+ resolve = _resolve;
1142
+ reject = _reject;
1143
+ });
1144
+ return {
1145
+ promise,
1146
+ resolve,
1147
+ reject
1148
+ };
1149
+ }
1150
+ const VALID_PROTOCOLS = ["http:", "https:"];
1151
+ function isHttpUrl(url) {
1152
+ try {
1153
+ const parsedUrl = new URL(url);
1154
+ return VALID_PROTOCOLS.includes(parsedUrl.protocol);
1155
+ } catch {
1156
+ return false;
1157
+ }
1158
+ }
1159
+
1160
+ const uniqueElements = (item, index, all) => {
1161
+ const props = JSON.stringify(item.props);
1162
+ const children = item.children;
1163
+ return index === all.findIndex((i) => JSON.stringify(i.props) === props && i.children == children);
1164
+ };
1165
+ function renderAllHeadContent(result) {
1166
+ result._metadata.hasRenderedHead = true;
1167
+ let content = "";
1168
+ if (result.shouldInjectCspMetaTags && result.cspDestination === "meta") {
1169
+ content += renderElement$1(
1170
+ "meta",
1171
+ {
1172
+ props: {
1173
+ "http-equiv": "content-security-policy",
1174
+ content: renderCspContent(result)
1175
+ },
1176
+ children: ""
1177
+ },
1178
+ false
1179
+ );
1180
+ }
1181
+ const styles = Array.from(result.styles).filter(uniqueElements).map(
1182
+ (style) => style.props.rel === "stylesheet" ? renderElement$1("link", style) : renderElement$1("style", style)
1183
+ );
1184
+ result.styles.clear();
1185
+ const scripts = Array.from(result.scripts).filter(uniqueElements).map((script) => {
1186
+ if (result.userAssetsBase) {
1187
+ script.props.src = (result.base === "/" ? "" : result.base) + result.userAssetsBase + script.props.src;
1188
+ }
1189
+ return renderElement$1("script", script, false);
1190
+ });
1191
+ const links = Array.from(result.links).filter(uniqueElements).map((link) => renderElement$1("link", link, false));
1192
+ content += styles.join("\n") + links.join("\n") + scripts.join("\n");
1193
+ if (result._metadata.extraHead.length > 0) {
1194
+ for (const part of result._metadata.extraHead) {
1195
+ content += part;
1196
+ }
1197
+ }
1198
+ return markHTMLString(content);
1199
+ }
1200
+ function renderHead() {
1201
+ return createRenderInstruction({ type: "head" });
1202
+ }
1203
+ function maybeRenderHead() {
1204
+ return createRenderInstruction({ type: "maybe-head" });
1205
+ }
1206
+
1207
+ const ALGORITHMS = {
1208
+ "SHA-256": "sha256-",
1209
+ "SHA-384": "sha384-",
1210
+ "SHA-512": "sha512-"
1211
+ };
1212
+ const ALGORITHM_VALUES = Object.values(ALGORITHMS);
1213
+ z.enum(Object.keys(ALGORITHMS)).optional().default("SHA-256");
1214
+ z.custom((value) => {
1215
+ if (typeof value !== "string") {
1216
+ return false;
1217
+ }
1218
+ return ALGORITHM_VALUES.some((allowedValue) => {
1219
+ return value.startsWith(allowedValue);
1220
+ });
1221
+ });
1222
+ const ALLOWED_DIRECTIVES = [
1223
+ "base-uri",
1224
+ "child-src",
1225
+ "connect-src",
1226
+ "default-src",
1227
+ "fenced-frame-src",
1228
+ "font-src",
1229
+ "form-action",
1230
+ "frame-ancestors",
1231
+ "frame-src",
1232
+ "img-src",
1233
+ "manifest-src",
1234
+ "media-src",
1235
+ "object-src",
1236
+ "referrer",
1237
+ "report-to",
1238
+ "report-uri",
1239
+ "require-trusted-types-for",
1240
+ "sandbox",
1241
+ "trusted-types",
1242
+ "upgrade-insecure-requests",
1243
+ "worker-src"
1244
+ ];
1245
+ z.custom((value) => {
1246
+ if (typeof value !== "string") {
1247
+ return false;
1248
+ }
1249
+ return ALLOWED_DIRECTIVES.some((allowedValue) => {
1250
+ return value.startsWith(allowedValue);
1251
+ });
1252
+ });
1253
+
1254
+ const ALGORITHM = "AES-GCM";
1255
+ async function decodeKey(encoded) {
1256
+ const bytes = decodeBase64(encoded);
1257
+ return crypto.subtle.importKey("raw", bytes.buffer, ALGORITHM, true, [
1258
+ "encrypt",
1259
+ "decrypt"
1260
+ ]);
1261
+ }
1262
+ const encoder$1 = new TextEncoder();
1263
+ const decoder$1 = new TextDecoder();
1264
+ const IV_LENGTH = 24;
1265
+ async function encryptString(key, raw) {
1266
+ const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH / 2));
1267
+ const data = encoder$1.encode(raw);
1268
+ const buffer = await crypto.subtle.encrypt(
1269
+ {
1270
+ name: ALGORITHM,
1271
+ iv
1272
+ },
1273
+ key,
1274
+ data
1275
+ );
1276
+ return encodeHexUpperCase(iv) + encodeBase64(new Uint8Array(buffer));
1277
+ }
1278
+ async function decryptString(key, encoded) {
1279
+ const iv = decodeHex(encoded.slice(0, IV_LENGTH));
1280
+ const dataArray = decodeBase64(encoded.slice(IV_LENGTH));
1281
+ const decryptedBuffer = await crypto.subtle.decrypt(
1282
+ {
1283
+ name: ALGORITHM,
1284
+ iv
1285
+ },
1286
+ key,
1287
+ dataArray
1288
+ );
1289
+ const decryptedString = decoder$1.decode(decryptedBuffer);
1290
+ return decryptedString;
1291
+ }
1292
+ async function generateCspDigest(data, algorithm) {
1293
+ const hashBuffer = await crypto.subtle.digest(algorithm, encoder$1.encode(data));
1294
+ const hash = encodeBase64(new Uint8Array(hashBuffer));
1295
+ return `${ALGORITHMS[algorithm]}${hash}`;
1296
+ }
1297
+
1298
+ const renderTemplateResultSym = Symbol.for("astro.renderTemplateResult");
1299
+ class RenderTemplateResult {
1300
+ [renderTemplateResultSym] = true;
1301
+ htmlParts;
1302
+ expressions;
1303
+ error;
1304
+ constructor(htmlParts, expressions) {
1305
+ this.htmlParts = htmlParts;
1306
+ this.error = void 0;
1307
+ this.expressions = expressions.map((expression) => {
1308
+ if (isPromise(expression)) {
1309
+ return Promise.resolve(expression).catch((err) => {
1310
+ if (!this.error) {
1311
+ this.error = err;
1312
+ throw err;
1313
+ }
1314
+ });
1315
+ }
1316
+ return expression;
1317
+ });
1318
+ }
1319
+ render(destination) {
1320
+ const flushers = this.expressions.map((exp) => {
1321
+ return createBufferedRenderer(destination, (bufferDestination) => {
1322
+ if (exp || exp === 0) {
1323
+ return renderChild(bufferDestination, exp);
1324
+ }
1325
+ });
1326
+ });
1327
+ let i = 0;
1328
+ const iterate = () => {
1329
+ while (i < this.htmlParts.length) {
1330
+ const html = this.htmlParts[i];
1331
+ const flusher = flushers[i];
1332
+ i++;
1333
+ if (html) {
1334
+ destination.write(markHTMLString(html));
1335
+ }
1336
+ if (flusher) {
1337
+ const result = flusher.flush();
1338
+ if (isPromise(result)) {
1339
+ return result.then(iterate);
1340
+ }
1341
+ }
1342
+ }
1343
+ };
1344
+ return iterate();
1345
+ }
1346
+ }
1347
+ function isRenderTemplateResult(obj) {
1348
+ return typeof obj === "object" && obj !== null && !!obj[renderTemplateResultSym];
1349
+ }
1350
+ function renderTemplate(htmlParts, ...expressions) {
1351
+ return new RenderTemplateResult(htmlParts, expressions);
1352
+ }
1353
+
1354
+ const slotString = Symbol.for("astro:slot-string");
1355
+ class SlotString extends HTMLString {
1356
+ instructions;
1357
+ [slotString];
1358
+ constructor(content, instructions) {
1359
+ super(content);
1360
+ this.instructions = instructions;
1361
+ this[slotString] = true;
1362
+ }
1363
+ }
1364
+ function isSlotString(str) {
1365
+ return !!str[slotString];
1366
+ }
1367
+ function renderSlot(result, slotted, fallback) {
1368
+ if (!slotted && fallback) {
1369
+ return renderSlot(result, fallback);
1370
+ }
1371
+ return {
1372
+ async render(destination) {
1373
+ await renderChild(destination, typeof slotted === "function" ? slotted(result) : slotted);
1374
+ }
1375
+ };
1376
+ }
1377
+ async function renderSlotToString(result, slotted, fallback) {
1378
+ let content = "";
1379
+ let instructions = null;
1380
+ const temporaryDestination = {
1381
+ write(chunk) {
1382
+ if (chunk instanceof SlotString) {
1383
+ content += chunk;
1384
+ if (chunk.instructions) {
1385
+ instructions ??= [];
1386
+ instructions.push(...chunk.instructions);
1387
+ }
1388
+ } else if (chunk instanceof Response) return;
1389
+ else if (typeof chunk === "object" && "type" in chunk && typeof chunk.type === "string") {
1390
+ if (instructions === null) {
1391
+ instructions = [];
1392
+ }
1393
+ instructions.push(chunk);
1394
+ } else {
1395
+ content += chunkToString(result, chunk);
1396
+ }
1397
+ }
1398
+ };
1399
+ const renderInstance = renderSlot(result, slotted, fallback);
1400
+ await renderInstance.render(temporaryDestination);
1401
+ return markHTMLString(new SlotString(content, instructions));
1402
+ }
1403
+ async function renderSlots(result, slots = {}) {
1404
+ let slotInstructions = null;
1405
+ let children = {};
1406
+ if (slots) {
1407
+ await Promise.all(
1408
+ Object.entries(slots).map(
1409
+ ([key, value]) => renderSlotToString(result, value).then((output) => {
1410
+ if (output.instructions) {
1411
+ if (slotInstructions === null) {
1412
+ slotInstructions = [];
1413
+ }
1414
+ slotInstructions.push(...output.instructions);
1415
+ }
1416
+ children[key] = output;
1417
+ })
1418
+ )
1419
+ );
1420
+ }
1421
+ return { slotInstructions, children };
1422
+ }
1423
+ function createSlotValueFromString(content) {
1424
+ return function() {
1425
+ return renderTemplate`${unescapeHTML(content)}`;
1426
+ };
1427
+ }
1428
+
1429
+ const internalProps = /* @__PURE__ */ new Set([
1430
+ "server:component-path",
1431
+ "server:component-export",
1432
+ "server:component-directive",
1433
+ "server:defer"
1434
+ ]);
1435
+ function containsServerDirective(props) {
1436
+ return "server:component-directive" in props;
1437
+ }
1438
+ const SCRIPT_RE = /<\/script/giu;
1439
+ const COMMENT_RE = /<!--/gu;
1440
+ const SCRIPT_REPLACER = "<\\/script";
1441
+ const COMMENT_REPLACER = "\\u003C!--";
1442
+ function safeJsonStringify(obj) {
1443
+ return JSON.stringify(obj).replace(SCRIPT_RE, SCRIPT_REPLACER).replace(COMMENT_RE, COMMENT_REPLACER);
1444
+ }
1445
+ function createSearchParams(componentExport, encryptedProps, slots) {
1446
+ const params = new URLSearchParams();
1447
+ params.set("e", componentExport);
1448
+ params.set("p", encryptedProps);
1449
+ params.set("s", slots);
1450
+ return params;
1451
+ }
1452
+ function isWithinURLLimit(pathname, params) {
1453
+ const url = pathname + "?" + params.toString();
1454
+ const chars = url.length;
1455
+ return chars < 2048;
1456
+ }
1457
+ class ServerIslandComponent {
1458
+ result;
1459
+ props;
1460
+ slots;
1461
+ displayName;
1462
+ hostId;
1463
+ islandContent;
1464
+ componentPath;
1465
+ componentExport;
1466
+ componentId;
1467
+ constructor(result, props, slots, displayName) {
1468
+ this.result = result;
1469
+ this.props = props;
1470
+ this.slots = slots;
1471
+ this.displayName = displayName;
1472
+ }
1473
+ async init() {
1474
+ const content = await this.getIslandContent();
1475
+ if (this.result.cspDestination) {
1476
+ this.result._metadata.extraScriptHashes.push(
1477
+ await generateCspDigest(SERVER_ISLAND_REPLACER, this.result.cspAlgorithm)
1478
+ );
1479
+ const contentDigest = await generateCspDigest(content, this.result.cspAlgorithm);
1480
+ this.result._metadata.extraScriptHashes.push(contentDigest);
1481
+ }
1482
+ return createThinHead();
1483
+ }
1484
+ async render(destination) {
1485
+ const hostId = await this.getHostId();
1486
+ const islandContent = await this.getIslandContent();
1487
+ destination.write(createRenderInstruction({ type: "server-island-runtime" }));
1488
+ destination.write("<!--[if astro]>server-island-start<![endif]-->");
1489
+ for (const name in this.slots) {
1490
+ if (name === "fallback") {
1491
+ await renderChild(destination, this.slots.fallback(this.result));
1492
+ }
1493
+ }
1494
+ destination.write(
1495
+ `<script type="module" data-astro-rerun data-island-id="${hostId}">${islandContent}</script>`
1496
+ );
1497
+ }
1498
+ getComponentPath() {
1499
+ if (this.componentPath) {
1500
+ return this.componentPath;
1501
+ }
1502
+ const componentPath = this.props["server:component-path"];
1503
+ if (!componentPath) {
1504
+ throw new Error(`Could not find server component path`);
1505
+ }
1506
+ this.componentPath = componentPath;
1507
+ return componentPath;
1508
+ }
1509
+ getComponentExport() {
1510
+ if (this.componentExport) {
1511
+ return this.componentExport;
1512
+ }
1513
+ const componentExport = this.props["server:component-export"];
1514
+ if (!componentExport) {
1515
+ throw new Error(`Could not find server component export`);
1516
+ }
1517
+ this.componentExport = componentExport;
1518
+ return componentExport;
1519
+ }
1520
+ async getHostId() {
1521
+ if (!this.hostId) {
1522
+ this.hostId = await crypto.randomUUID();
1523
+ }
1524
+ return this.hostId;
1525
+ }
1526
+ async getIslandContent() {
1527
+ if (this.islandContent) {
1528
+ return this.islandContent;
1529
+ }
1530
+ const componentPath = this.getComponentPath();
1531
+ const componentExport = this.getComponentExport();
1532
+ const componentId = this.result.serverIslandNameMap.get(componentPath);
1533
+ if (!componentId) {
1534
+ throw new Error(`Could not find server component name`);
1535
+ }
1536
+ for (const key2 of Object.keys(this.props)) {
1537
+ if (internalProps.has(key2)) {
1538
+ delete this.props[key2];
1539
+ }
1540
+ }
1541
+ const renderedSlots = {};
1542
+ for (const name in this.slots) {
1543
+ if (name !== "fallback") {
1544
+ const content = await renderSlotToString(this.result, this.slots[name]);
1545
+ renderedSlots[name] = content.toString();
1546
+ }
1547
+ }
1548
+ const key = await this.result.key;
1549
+ const propsEncrypted = Object.keys(this.props).length === 0 ? "" : await encryptString(key, JSON.stringify(this.props));
1550
+ const slotsEncrypted = Object.keys(renderedSlots).length === 0 ? "" : await encryptString(key, JSON.stringify(renderedSlots));
1551
+ const hostId = await this.getHostId();
1552
+ const slash = this.result.base.endsWith("/") ? "" : "/";
1553
+ let serverIslandUrl = `${this.result.base}${slash}_server-islands/${componentId}${this.result.trailingSlash === "always" ? "/" : ""}`;
1554
+ const potentialSearchParams = createSearchParams(
1555
+ componentExport,
1556
+ propsEncrypted,
1557
+ slotsEncrypted
1558
+ );
1559
+ const useGETRequest = isWithinURLLimit(serverIslandUrl, potentialSearchParams);
1560
+ if (useGETRequest) {
1561
+ serverIslandUrl += "?" + potentialSearchParams.toString();
1562
+ this.result._metadata.extraHead.push(
1563
+ markHTMLString(
1564
+ `<link rel="preload" as="fetch" href="${serverIslandUrl}" crossorigin="anonymous">`
1565
+ )
1566
+ );
1567
+ }
1568
+ const adapterHeaders = this.result.internalFetchHeaders || {};
1569
+ const headersJson = safeJsonStringify(adapterHeaders);
1570
+ const method = useGETRequest ? (
1571
+ // GET request
1572
+ `const headers = new Headers(${headersJson});
1573
+ let response = await fetch('${serverIslandUrl}', { headers });`
1574
+ ) : (
1575
+ // POST request
1576
+ `let data = {
1577
+ componentExport: ${safeJsonStringify(componentExport)},
1578
+ encryptedProps: ${safeJsonStringify(propsEncrypted)},
1579
+ encryptedSlots: ${safeJsonStringify(slotsEncrypted)},
1580
+ };
1581
+ const headers = new Headers({ 'Content-Type': 'application/json', ...${headersJson} });
1582
+ let response = await fetch('${serverIslandUrl}', {
1583
+ method: 'POST',
1584
+ body: JSON.stringify(data),
1585
+ headers,
1586
+ });`
1587
+ );
1588
+ this.islandContent = `${method}replaceServerIsland('${hostId}', response);`;
1589
+ return this.islandContent;
1590
+ }
1591
+ }
1592
+ const renderServerIslandRuntime = () => {
1593
+ return `<script>${SERVER_ISLAND_REPLACER}</script>`;
1594
+ };
1595
+ const SERVER_ISLAND_REPLACER = markHTMLString(
1596
+ `async function replaceServerIsland(id, r) {
1597
+ let s = document.querySelector(\`script[data-island-id="\${id}"]\`);
1598
+ // If there's no matching script, or the request fails then return
1599
+ if (!s || r.status !== 200 || r.headers.get('content-type')?.split(';')[0].trim() !== 'text/html') return;
1600
+ // Load the HTML before modifying the DOM in case of errors
1601
+ let html = await r.text();
1602
+ // Remove any placeholder content before the island script
1603
+ while (s.previousSibling && s.previousSibling.nodeType !== 8 && s.previousSibling.data !== '[if astro]>server-island-start<![endif]')
1604
+ s.previousSibling.remove();
1605
+ s.previousSibling?.remove();
1606
+ // Insert the new HTML
1607
+ s.before(document.createRange().createContextualFragment(html));
1608
+ // Remove the script. Prior to v5.4.2, this was the trick to force rerun of scripts. Keeping it to minimize change to the existing behavior.
1609
+ s.remove();
1610
+ }`.split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("//")).join(" ")
1611
+ );
1612
+
1613
+ const Fragment = Symbol.for("astro:fragment");
1614
+ const Renderer = Symbol.for("astro:renderer");
1615
+ const encoder = new TextEncoder();
1616
+ const decoder = new TextDecoder();
1617
+ function stringifyChunk(result, chunk) {
1618
+ if (isRenderInstruction(chunk)) {
1619
+ const instruction = chunk;
1620
+ switch (instruction.type) {
1621
+ case "directive": {
1622
+ const { hydration } = instruction;
1623
+ let needsHydrationScript = hydration && determineIfNeedsHydrationScript(result);
1624
+ let needsDirectiveScript = hydration && determinesIfNeedsDirectiveScript(result, hydration.directive);
1625
+ if (needsHydrationScript) {
1626
+ let prescripts = getPrescripts(result, "both", hydration.directive);
1627
+ return markHTMLString(prescripts);
1628
+ } else if (needsDirectiveScript) {
1629
+ let prescripts = getPrescripts(result, "directive", hydration.directive);
1630
+ return markHTMLString(prescripts);
1631
+ } else {
1632
+ return "";
1633
+ }
1634
+ }
1635
+ case "head": {
1636
+ if (result._metadata.hasRenderedHead || result.partial) {
1637
+ return "";
1638
+ }
1639
+ return renderAllHeadContent(result);
1640
+ }
1641
+ case "maybe-head": {
1642
+ if (result._metadata.hasRenderedHead || result._metadata.headInTree || result.partial) {
1643
+ return "";
1644
+ }
1645
+ return renderAllHeadContent(result);
1646
+ }
1647
+ case "renderer-hydration-script": {
1648
+ const { rendererSpecificHydrationScripts } = result._metadata;
1649
+ const { rendererName } = instruction;
1650
+ if (!rendererSpecificHydrationScripts.has(rendererName)) {
1651
+ rendererSpecificHydrationScripts.add(rendererName);
1652
+ return instruction.render();
1653
+ }
1654
+ return "";
1655
+ }
1656
+ case "server-island-runtime": {
1657
+ if (result._metadata.hasRenderedServerIslandRuntime) {
1658
+ return "";
1659
+ }
1660
+ result._metadata.hasRenderedServerIslandRuntime = true;
1661
+ return renderServerIslandRuntime();
1662
+ }
1663
+ default: {
1664
+ throw new Error(`Unknown chunk type: ${chunk.type}`);
1665
+ }
1666
+ }
1667
+ } else if (chunk instanceof Response) {
1668
+ return "";
1669
+ } else if (isSlotString(chunk)) {
1670
+ let out = "";
1671
+ const c = chunk;
1672
+ if (c.instructions) {
1673
+ for (const instr of c.instructions) {
1674
+ out += stringifyChunk(result, instr);
1675
+ }
1676
+ }
1677
+ out += chunk.toString();
1678
+ return out;
1679
+ }
1680
+ return chunk.toString();
1681
+ }
1682
+ function chunkToString(result, chunk) {
1683
+ if (ArrayBuffer.isView(chunk)) {
1684
+ return decoder.decode(chunk);
1685
+ } else {
1686
+ return stringifyChunk(result, chunk);
1687
+ }
1688
+ }
1689
+ function chunkToByteArray(result, chunk) {
1690
+ if (ArrayBuffer.isView(chunk)) {
1691
+ return chunk;
1692
+ } else {
1693
+ const stringified = stringifyChunk(result, chunk);
1694
+ return encoder.encode(stringified.toString());
1695
+ }
1696
+ }
1697
+ function isRenderInstance(obj) {
1698
+ return !!obj && typeof obj === "object" && "render" in obj && typeof obj.render === "function";
1699
+ }
1700
+
1701
+ function renderChild(destination, child) {
1702
+ if (isPromise(child)) {
1703
+ return child.then((x) => renderChild(destination, x));
1704
+ }
1705
+ if (child instanceof SlotString) {
1706
+ destination.write(child);
1707
+ return;
1708
+ }
1709
+ if (isHTMLString(child)) {
1710
+ destination.write(child);
1711
+ return;
1712
+ }
1713
+ if (Array.isArray(child)) {
1714
+ return renderArray(destination, child);
1715
+ }
1716
+ if (typeof child === "function") {
1717
+ return renderChild(destination, child());
1718
+ }
1719
+ if (!child && child !== 0) {
1720
+ return;
1721
+ }
1722
+ if (typeof child === "string") {
1723
+ destination.write(markHTMLString(escapeHTML(child)));
1724
+ return;
1725
+ }
1726
+ if (isRenderInstance(child)) {
1727
+ return child.render(destination);
1728
+ }
1729
+ if (isRenderTemplateResult(child)) {
1730
+ return child.render(destination);
1731
+ }
1732
+ if (isAstroComponentInstance(child)) {
1733
+ return child.render(destination);
1734
+ }
1735
+ if (ArrayBuffer.isView(child)) {
1736
+ destination.write(child);
1737
+ return;
1738
+ }
1739
+ if (typeof child === "object" && (Symbol.asyncIterator in child || Symbol.iterator in child)) {
1740
+ if (Symbol.asyncIterator in child) {
1741
+ return renderAsyncIterable(destination, child);
1742
+ }
1743
+ return renderIterable(destination, child);
1744
+ }
1745
+ destination.write(child);
1746
+ }
1747
+ function renderArray(destination, children) {
1748
+ const flushers = children.map((c) => {
1749
+ return createBufferedRenderer(destination, (bufferDestination) => {
1750
+ return renderChild(bufferDestination, c);
1751
+ });
1752
+ });
1753
+ const iterator = flushers[Symbol.iterator]();
1754
+ const iterate = () => {
1755
+ for (; ; ) {
1756
+ const { value: flusher, done } = iterator.next();
1757
+ if (done) {
1758
+ break;
1759
+ }
1760
+ const result = flusher.flush();
1761
+ if (isPromise(result)) {
1762
+ return result.then(iterate);
1763
+ }
1764
+ }
1765
+ };
1766
+ return iterate();
1767
+ }
1768
+ function renderIterable(destination, children) {
1769
+ const iterator = children[Symbol.iterator]();
1770
+ const iterate = () => {
1771
+ for (; ; ) {
1772
+ const { value, done } = iterator.next();
1773
+ if (done) {
1774
+ break;
1775
+ }
1776
+ const result = renderChild(destination, value);
1777
+ if (isPromise(result)) {
1778
+ return result.then(iterate);
1779
+ }
1780
+ }
1781
+ };
1782
+ return iterate();
1783
+ }
1784
+ async function renderAsyncIterable(destination, children) {
1785
+ for await (const value of children) {
1786
+ await renderChild(destination, value);
1787
+ }
1788
+ }
1789
+
1790
+ const astroComponentInstanceSym = Symbol.for("astro.componentInstance");
1791
+ class AstroComponentInstance {
1792
+ [astroComponentInstanceSym] = true;
1793
+ result;
1794
+ props;
1795
+ slotValues;
1796
+ factory;
1797
+ returnValue;
1798
+ constructor(result, props, slots, factory) {
1799
+ this.result = result;
1800
+ this.props = props;
1801
+ this.factory = factory;
1802
+ this.slotValues = {};
1803
+ for (const name in slots) {
1804
+ let didRender = false;
1805
+ let value = slots[name](result);
1806
+ this.slotValues[name] = () => {
1807
+ if (!didRender) {
1808
+ didRender = true;
1809
+ return value;
1810
+ }
1811
+ return slots[name](result);
1812
+ };
1813
+ }
1814
+ }
1815
+ init(result) {
1816
+ if (this.returnValue !== void 0) {
1817
+ return this.returnValue;
1818
+ }
1819
+ this.returnValue = this.factory(result, this.props, this.slotValues);
1820
+ if (isPromise(this.returnValue)) {
1821
+ this.returnValue.then((resolved) => {
1822
+ this.returnValue = resolved;
1823
+ }).catch(() => {
1824
+ });
1825
+ }
1826
+ return this.returnValue;
1827
+ }
1828
+ render(destination) {
1829
+ const returnValue = this.init(this.result);
1830
+ if (isPromise(returnValue)) {
1831
+ return returnValue.then((x) => this.renderImpl(destination, x));
1832
+ }
1833
+ return this.renderImpl(destination, returnValue);
1834
+ }
1835
+ renderImpl(destination, returnValue) {
1836
+ if (isHeadAndContent(returnValue)) {
1837
+ return returnValue.content.render(destination);
1838
+ } else {
1839
+ return renderChild(destination, returnValue);
1840
+ }
1841
+ }
1842
+ }
1843
+ function validateComponentProps(props, clientDirectives, displayName) {
1844
+ if (props != null) {
1845
+ const directives = [...clientDirectives.keys()].map((directive) => `client:${directive}`);
1846
+ for (const prop of Object.keys(props)) {
1847
+ if (directives.includes(prop)) {
1848
+ console.warn(
1849
+ `You are attempting to render <${displayName} ${prop} />, but ${displayName} is an Astro component. Astro components do not render in the client and should not have a hydration directive. Please use a framework component for client rendering.`
1850
+ );
1851
+ }
1852
+ }
1853
+ }
1854
+ }
1855
+ function createAstroComponentInstance(result, displayName, factory, props, slots = {}) {
1856
+ validateComponentProps(props, result.clientDirectives, displayName);
1857
+ const instance = new AstroComponentInstance(result, props, slots, factory);
1858
+ if (isAPropagatingComponent(result, factory)) {
1859
+ result._metadata.propagators.add(instance);
1860
+ }
1861
+ return instance;
1862
+ }
1863
+ function isAstroComponentInstance(obj) {
1864
+ return typeof obj === "object" && obj !== null && !!obj[astroComponentInstanceSym];
1865
+ }
1866
+
1867
+ const DOCTYPE_EXP = /<!doctype html/i;
1868
+ async function renderToString(result, componentFactory, props, children, isPage = false, route) {
1869
+ const templateResult = await callComponentAsTemplateResultOrResponse(
1870
+ result,
1871
+ componentFactory,
1872
+ props,
1873
+ children,
1874
+ route
1875
+ );
1876
+ if (templateResult instanceof Response) return templateResult;
1877
+ let str = "";
1878
+ let renderedFirstPageChunk = false;
1879
+ if (isPage) {
1880
+ await bufferHeadContent(result);
1881
+ }
1882
+ const destination = {
1883
+ write(chunk) {
1884
+ if (isPage && !renderedFirstPageChunk) {
1885
+ renderedFirstPageChunk = true;
1886
+ if (!result.partial && !DOCTYPE_EXP.test(String(chunk))) {
1887
+ const doctype = result.compressHTML ? "<!DOCTYPE html>" : "<!DOCTYPE html>\n";
1888
+ str += doctype;
1889
+ }
1890
+ }
1891
+ if (chunk instanceof Response) return;
1892
+ str += chunkToString(result, chunk);
1893
+ }
1894
+ };
1895
+ await templateResult.render(destination);
1896
+ return str;
1897
+ }
1898
+ async function renderToReadableStream(result, componentFactory, props, children, isPage = false, route) {
1899
+ const templateResult = await callComponentAsTemplateResultOrResponse(
1900
+ result,
1901
+ componentFactory,
1902
+ props,
1903
+ children,
1904
+ route
1905
+ );
1906
+ if (templateResult instanceof Response) return templateResult;
1907
+ let renderedFirstPageChunk = false;
1908
+ if (isPage) {
1909
+ await bufferHeadContent(result);
1910
+ }
1911
+ return new ReadableStream({
1912
+ start(controller) {
1913
+ const destination = {
1914
+ write(chunk) {
1915
+ if (isPage && !renderedFirstPageChunk) {
1916
+ renderedFirstPageChunk = true;
1917
+ if (!result.partial && !DOCTYPE_EXP.test(String(chunk))) {
1918
+ const doctype = result.compressHTML ? "<!DOCTYPE html>" : "<!DOCTYPE html>\n";
1919
+ controller.enqueue(encoder.encode(doctype));
1920
+ }
1921
+ }
1922
+ if (chunk instanceof Response) {
1923
+ throw new AstroError({
1924
+ ...ResponseSentError
1925
+ });
1926
+ }
1927
+ const bytes = chunkToByteArray(result, chunk);
1928
+ controller.enqueue(bytes);
1929
+ }
1930
+ };
1931
+ (async () => {
1932
+ try {
1933
+ await templateResult.render(destination);
1934
+ controller.close();
1935
+ } catch (e) {
1936
+ if (AstroError.is(e) && !e.loc) {
1937
+ e.setLocation({
1938
+ file: route?.component
1939
+ });
1940
+ }
1941
+ setTimeout(() => controller.error(e), 0);
1942
+ }
1943
+ })();
1944
+ },
1945
+ cancel() {
1946
+ result.cancelled = true;
1947
+ }
1948
+ });
1949
+ }
1950
+ async function callComponentAsTemplateResultOrResponse(result, componentFactory, props, children, route) {
1951
+ const factoryResult = await componentFactory(result, props, children);
1952
+ if (factoryResult instanceof Response) {
1953
+ return factoryResult;
1954
+ } else if (isHeadAndContent(factoryResult)) {
1955
+ if (!isRenderTemplateResult(factoryResult.content)) {
1956
+ throw new AstroError({
1957
+ ...OnlyResponseCanBeReturned,
1958
+ message: OnlyResponseCanBeReturned.message(
1959
+ route?.route,
1960
+ typeof factoryResult
1961
+ ),
1962
+ location: {
1963
+ file: route?.component
1964
+ }
1965
+ });
1966
+ }
1967
+ return factoryResult.content;
1968
+ } else if (!isRenderTemplateResult(factoryResult)) {
1969
+ throw new AstroError({
1970
+ ...OnlyResponseCanBeReturned,
1971
+ message: OnlyResponseCanBeReturned.message(route?.route, typeof factoryResult),
1972
+ location: {
1973
+ file: route?.component
1974
+ }
1975
+ });
1976
+ }
1977
+ return factoryResult;
1978
+ }
1979
+ async function bufferHeadContent(result) {
1980
+ const iterator = result._metadata.propagators.values();
1981
+ while (true) {
1982
+ const { value, done } = iterator.next();
1983
+ if (done) {
1984
+ break;
1985
+ }
1986
+ const returnValue = await value.init(result);
1987
+ if (isHeadAndContent(returnValue) && returnValue.head) {
1988
+ result._metadata.extraHead.push(returnValue.head);
1989
+ }
1990
+ }
1991
+ }
1992
+ async function renderToAsyncIterable(result, componentFactory, props, children, isPage = false, route) {
1993
+ const templateResult = await callComponentAsTemplateResultOrResponse(
1994
+ result,
1995
+ componentFactory,
1996
+ props,
1997
+ children,
1998
+ route
1999
+ );
2000
+ if (templateResult instanceof Response) return templateResult;
2001
+ let renderedFirstPageChunk = false;
2002
+ if (isPage) {
2003
+ await bufferHeadContent(result);
2004
+ }
2005
+ let error = null;
2006
+ let next = null;
2007
+ const buffer = [];
2008
+ let renderingComplete = false;
2009
+ const iterator = {
2010
+ async next() {
2011
+ if (result.cancelled) return { done: true, value: void 0 };
2012
+ if (next !== null) {
2013
+ await next.promise;
2014
+ } else if (!renderingComplete && !buffer.length) {
2015
+ next = promiseWithResolvers();
2016
+ await next.promise;
2017
+ }
2018
+ if (!renderingComplete) {
2019
+ next = promiseWithResolvers();
2020
+ }
2021
+ if (error) {
2022
+ throw error;
2023
+ }
2024
+ let length = 0;
2025
+ for (let i = 0, len = buffer.length; i < len; i++) {
2026
+ length += buffer[i].length;
2027
+ }
2028
+ let mergedArray = new Uint8Array(length);
2029
+ let offset = 0;
2030
+ for (let i = 0, len = buffer.length; i < len; i++) {
2031
+ const item = buffer[i];
2032
+ mergedArray.set(item, offset);
2033
+ offset += item.length;
2034
+ }
2035
+ buffer.length = 0;
2036
+ const returnValue = {
2037
+ // The iterator is done when rendering has finished
2038
+ // and there are no more chunks to return.
2039
+ done: length === 0 && renderingComplete,
2040
+ value: mergedArray
2041
+ };
2042
+ return returnValue;
2043
+ },
2044
+ async return() {
2045
+ result.cancelled = true;
2046
+ return { done: true, value: void 0 };
2047
+ }
2048
+ };
2049
+ const destination = {
2050
+ write(chunk) {
2051
+ if (isPage && !renderedFirstPageChunk) {
2052
+ renderedFirstPageChunk = true;
2053
+ if (!result.partial && !DOCTYPE_EXP.test(String(chunk))) {
2054
+ const doctype = result.compressHTML ? "<!DOCTYPE html>" : "<!DOCTYPE html>\n";
2055
+ buffer.push(encoder.encode(doctype));
2056
+ }
2057
+ }
2058
+ if (chunk instanceof Response) {
2059
+ throw new AstroError(ResponseSentError);
2060
+ }
2061
+ const bytes = chunkToByteArray(result, chunk);
2062
+ if (bytes.length > 0) {
2063
+ buffer.push(bytes);
2064
+ next?.resolve();
2065
+ } else if (buffer.length > 0) {
2066
+ next?.resolve();
2067
+ }
2068
+ }
2069
+ };
2070
+ const renderResult = toPromise(() => templateResult.render(destination));
2071
+ renderResult.catch((err) => {
2072
+ error = err;
2073
+ }).finally(() => {
2074
+ renderingComplete = true;
2075
+ next?.resolve();
2076
+ });
2077
+ return {
2078
+ [Symbol.asyncIterator]() {
2079
+ return iterator;
2080
+ }
2081
+ };
2082
+ }
2083
+ function toPromise(fn) {
2084
+ try {
2085
+ const result = fn();
2086
+ return isPromise(result) ? result : Promise.resolve(result);
2087
+ } catch (err) {
2088
+ return Promise.reject(err);
2089
+ }
2090
+ }
2091
+
2092
+ function componentIsHTMLElement(Component) {
2093
+ return typeof HTMLElement !== "undefined" && HTMLElement.isPrototypeOf(Component);
2094
+ }
2095
+ async function renderHTMLElement(result, constructor, props, slots) {
2096
+ const name = getHTMLElementName(constructor);
2097
+ let attrHTML = "";
2098
+ for (const attr in props) {
2099
+ attrHTML += ` ${attr}="${toAttributeString(await props[attr])}"`;
2100
+ }
2101
+ return markHTMLString(
2102
+ `<${name}${attrHTML}>${await renderSlotToString(result, slots?.default)}</${name}>`
2103
+ );
2104
+ }
2105
+ function getHTMLElementName(constructor) {
2106
+ const definedName = customElements.getName(constructor);
2107
+ if (definedName) return definedName;
2108
+ const assignedName = constructor.name.replace(/^HTML|Element$/g, "").replace(/[A-Z]/g, "-$&").toLowerCase().replace(/^-/, "html-");
2109
+ return assignedName;
2110
+ }
2111
+
2112
+ const needsHeadRenderingSymbol = Symbol.for("astro.needsHeadRendering");
2113
+ const rendererAliases = /* @__PURE__ */ new Map([["solid", "solid-js"]]);
2114
+ const clientOnlyValues = /* @__PURE__ */ new Set(["solid-js", "react", "preact", "vue", "svelte"]);
2115
+ function guessRenderers(componentUrl) {
2116
+ const extname = componentUrl?.split(".").pop();
2117
+ switch (extname) {
2118
+ case "svelte":
2119
+ return ["@astrojs/svelte"];
2120
+ case "vue":
2121
+ return ["@astrojs/vue"];
2122
+ case "jsx":
2123
+ case "tsx":
2124
+ return ["@astrojs/react", "@astrojs/preact", "@astrojs/solid-js", "@astrojs/vue (jsx)"];
2125
+ case void 0:
2126
+ default:
2127
+ return [
2128
+ "@astrojs/react",
2129
+ "@astrojs/preact",
2130
+ "@astrojs/solid-js",
2131
+ "@astrojs/vue",
2132
+ "@astrojs/svelte"
2133
+ ];
2134
+ }
2135
+ }
2136
+ function isFragmentComponent(Component) {
2137
+ return Component === Fragment;
2138
+ }
2139
+ function isHTMLComponent(Component) {
2140
+ return Component && Component["astro:html"] === true;
2141
+ }
2142
+ const ASTRO_SLOT_EXP = /<\/?astro-slot\b[^>]*>/g;
2143
+ const ASTRO_STATIC_SLOT_EXP = /<\/?astro-static-slot\b[^>]*>/g;
2144
+ function removeStaticAstroSlot(html, supportsAstroStaticSlot = true) {
2145
+ const exp = supportsAstroStaticSlot ? ASTRO_STATIC_SLOT_EXP : ASTRO_SLOT_EXP;
2146
+ return html.replace(exp, "");
2147
+ }
2148
+ async function renderFrameworkComponent(result, displayName, Component, _props, slots = {}) {
2149
+ if (!Component && "client:only" in _props === false) {
2150
+ throw new Error(
2151
+ `Unable to render ${displayName} because it is ${Component}!
2152
+ Did you forget to import the component or is it possible there is a typo?`
2153
+ );
2154
+ }
2155
+ const { renderers, clientDirectives } = result;
2156
+ const metadata = {
2157
+ astroStaticSlot: true,
2158
+ displayName
2159
+ };
2160
+ const { hydration, isPage, props, propsWithoutTransitionAttributes } = extractDirectives(
2161
+ _props,
2162
+ clientDirectives
2163
+ );
2164
+ let html = "";
2165
+ let attrs = void 0;
2166
+ if (hydration) {
2167
+ metadata.hydrate = hydration.directive;
2168
+ metadata.hydrateArgs = hydration.value;
2169
+ metadata.componentExport = hydration.componentExport;
2170
+ metadata.componentUrl = hydration.componentUrl;
2171
+ }
2172
+ const probableRendererNames = guessRenderers(metadata.componentUrl);
2173
+ const validRenderers = renderers.filter((r) => r.name !== "astro:jsx");
2174
+ const { children, slotInstructions } = await renderSlots(result, slots);
2175
+ let renderer;
2176
+ if (metadata.hydrate !== "only") {
2177
+ let isTagged = false;
2178
+ try {
2179
+ isTagged = Component && Component[Renderer];
2180
+ } catch {
2181
+ }
2182
+ if (isTagged) {
2183
+ const rendererName = Component[Renderer];
2184
+ renderer = renderers.find(({ name }) => name === rendererName);
2185
+ }
2186
+ if (!renderer) {
2187
+ let error;
2188
+ for (const r of renderers) {
2189
+ try {
2190
+ if (await r.ssr.check.call({ result }, Component, props, children)) {
2191
+ renderer = r;
2192
+ break;
2193
+ }
2194
+ } catch (e) {
2195
+ error ??= e;
2196
+ }
2197
+ }
2198
+ if (!renderer && error) {
2199
+ throw error;
2200
+ }
2201
+ }
2202
+ if (!renderer && typeof HTMLElement === "function" && componentIsHTMLElement(Component)) {
2203
+ const output = await renderHTMLElement(
2204
+ result,
2205
+ Component,
2206
+ _props,
2207
+ slots
2208
+ );
2209
+ return {
2210
+ render(destination) {
2211
+ destination.write(output);
2212
+ }
2213
+ };
2214
+ }
2215
+ } else {
2216
+ if (metadata.hydrateArgs) {
2217
+ const rendererName = rendererAliases.has(metadata.hydrateArgs) ? rendererAliases.get(metadata.hydrateArgs) : metadata.hydrateArgs;
2218
+ if (clientOnlyValues.has(rendererName)) {
2219
+ renderer = renderers.find(
2220
+ ({ name }) => name === `@astrojs/${rendererName}` || name === rendererName
2221
+ );
2222
+ }
2223
+ }
2224
+ if (!renderer && validRenderers.length === 1) {
2225
+ renderer = validRenderers[0];
2226
+ }
2227
+ if (!renderer) {
2228
+ const extname = metadata.componentUrl?.split(".").pop();
2229
+ renderer = renderers.find(({ name }) => name === `@astrojs/${extname}` || name === extname);
2230
+ }
2231
+ }
2232
+ let componentServerRenderEndTime;
2233
+ if (!renderer) {
2234
+ if (metadata.hydrate === "only") {
2235
+ const rendererName = rendererAliases.has(metadata.hydrateArgs) ? rendererAliases.get(metadata.hydrateArgs) : metadata.hydrateArgs;
2236
+ if (clientOnlyValues.has(rendererName)) {
2237
+ const plural = validRenderers.length > 1;
2238
+ throw new AstroError({
2239
+ ...NoMatchingRenderer,
2240
+ message: NoMatchingRenderer.message(
2241
+ metadata.displayName,
2242
+ metadata?.componentUrl?.split(".").pop(),
2243
+ plural,
2244
+ validRenderers.length
2245
+ ),
2246
+ hint: NoMatchingRenderer.hint(
2247
+ formatList(probableRendererNames.map((r) => "`" + r + "`"))
2248
+ )
2249
+ });
2250
+ } else {
2251
+ throw new AstroError({
2252
+ ...NoClientOnlyHint,
2253
+ message: NoClientOnlyHint.message(metadata.displayName),
2254
+ hint: NoClientOnlyHint.hint(
2255
+ probableRendererNames.map((r) => r.replace("@astrojs/", "")).join("|")
2256
+ )
2257
+ });
2258
+ }
2259
+ } else if (typeof Component !== "string") {
2260
+ const matchingRenderers = validRenderers.filter(
2261
+ (r) => probableRendererNames.includes(r.name)
2262
+ );
2263
+ const plural = validRenderers.length > 1;
2264
+ if (matchingRenderers.length === 0) {
2265
+ throw new AstroError({
2266
+ ...NoMatchingRenderer,
2267
+ message: NoMatchingRenderer.message(
2268
+ metadata.displayName,
2269
+ metadata?.componentUrl?.split(".").pop(),
2270
+ plural,
2271
+ validRenderers.length
2272
+ ),
2273
+ hint: NoMatchingRenderer.hint(
2274
+ formatList(probableRendererNames.map((r) => "`" + r + "`"))
2275
+ )
2276
+ });
2277
+ } else if (matchingRenderers.length === 1) {
2278
+ renderer = matchingRenderers[0];
2279
+ ({ html, attrs } = await renderer.ssr.renderToStaticMarkup.call(
2280
+ { result },
2281
+ Component,
2282
+ propsWithoutTransitionAttributes,
2283
+ children,
2284
+ metadata
2285
+ ));
2286
+ } else {
2287
+ throw new Error(`Unable to render ${metadata.displayName}!
2288
+
2289
+ This component likely uses ${formatList(probableRendererNames)},
2290
+ but Astro encountered an error during server-side rendering.
2291
+
2292
+ Please ensure that ${metadata.displayName}:
2293
+ 1. Does not unconditionally access browser-specific globals like \`window\` or \`document\`.
2294
+ If this is unavoidable, use the \`client:only\` hydration directive.
2295
+ 2. Does not conditionally return \`null\` or \`undefined\` when rendered on the server.
2296
+
2297
+ If you're still stuck, please open an issue on GitHub or join us at https://astro.build/chat.`);
2298
+ }
2299
+ }
2300
+ } else {
2301
+ if (metadata.hydrate === "only") {
2302
+ html = await renderSlotToString(result, slots?.fallback);
2303
+ } else {
2304
+ const componentRenderStartTime = performance.now();
2305
+ ({ html, attrs } = await renderer.ssr.renderToStaticMarkup.call(
2306
+ { result },
2307
+ Component,
2308
+ propsWithoutTransitionAttributes,
2309
+ children,
2310
+ metadata
2311
+ ));
2312
+ if (process.env.NODE_ENV === "development")
2313
+ componentServerRenderEndTime = performance.now() - componentRenderStartTime;
2314
+ }
2315
+ }
2316
+ if (!html && typeof Component === "string") {
2317
+ const Tag = sanitizeElementName(Component);
2318
+ const childSlots = Object.values(children).join("");
2319
+ const renderTemplateResult = renderTemplate`<${Tag}${internalSpreadAttributes(
2320
+ props,
2321
+ true,
2322
+ Tag
2323
+ )}${markHTMLString(
2324
+ childSlots === "" && voidElementNames.test(Tag) ? `/>` : `>${childSlots}</${Tag}>`
2325
+ )}`;
2326
+ html = "";
2327
+ const destination = {
2328
+ write(chunk) {
2329
+ if (chunk instanceof Response) return;
2330
+ html += chunkToString(result, chunk);
2331
+ }
2332
+ };
2333
+ await renderTemplateResult.render(destination);
2334
+ }
2335
+ if (!hydration) {
2336
+ return {
2337
+ render(destination) {
2338
+ if (slotInstructions) {
2339
+ for (const instruction of slotInstructions) {
2340
+ destination.write(instruction);
2341
+ }
2342
+ }
2343
+ if (isPage || renderer?.name === "astro:jsx") {
2344
+ destination.write(html);
2345
+ } else if (html && html.length > 0) {
2346
+ destination.write(
2347
+ markHTMLString(removeStaticAstroSlot(html, renderer?.ssr?.supportsAstroStaticSlot))
2348
+ );
2349
+ }
2350
+ }
2351
+ };
2352
+ }
2353
+ const astroId = shorthash(
2354
+ `<!--${metadata.componentExport.value}:${metadata.componentUrl}-->
2355
+ ${html}
2356
+ ${serializeProps(
2357
+ props,
2358
+ metadata
2359
+ )}`
2360
+ );
2361
+ const island = await generateHydrateScript(
2362
+ { renderer, result, astroId, props, attrs },
2363
+ metadata
2364
+ );
2365
+ if (componentServerRenderEndTime && process.env.NODE_ENV === "development")
2366
+ island.props["server-render-time"] = componentServerRenderEndTime;
2367
+ let unrenderedSlots = [];
2368
+ if (html) {
2369
+ if (Object.keys(children).length > 0) {
2370
+ for (const key of Object.keys(children)) {
2371
+ let tagName = renderer?.ssr?.supportsAstroStaticSlot ? !!metadata.hydrate ? "astro-slot" : "astro-static-slot" : "astro-slot";
2372
+ let expectedHTML = key === "default" ? `<${tagName}>` : `<${tagName} name="${key}">`;
2373
+ if (!html.includes(expectedHTML)) {
2374
+ unrenderedSlots.push(key);
2375
+ }
2376
+ }
2377
+ }
2378
+ } else {
2379
+ unrenderedSlots = Object.keys(children);
2380
+ }
2381
+ const template = unrenderedSlots.length > 0 ? unrenderedSlots.map(
2382
+ (key) => `<template data-astro-template${key !== "default" ? `="${key}"` : ""}>${children[key]}</template>`
2383
+ ).join("") : "";
2384
+ island.children = `${html ?? ""}${template}`;
2385
+ if (island.children) {
2386
+ island.props["await-children"] = "";
2387
+ island.children += `<!--astro:end-->`;
2388
+ }
2389
+ return {
2390
+ render(destination) {
2391
+ if (slotInstructions) {
2392
+ for (const instruction of slotInstructions) {
2393
+ destination.write(instruction);
2394
+ }
2395
+ }
2396
+ destination.write(createRenderInstruction({ type: "directive", hydration }));
2397
+ if (hydration.directive !== "only" && renderer?.ssr.renderHydrationScript) {
2398
+ destination.write(
2399
+ createRenderInstruction({
2400
+ type: "renderer-hydration-script",
2401
+ rendererName: renderer.name,
2402
+ render: renderer.ssr.renderHydrationScript
2403
+ })
2404
+ );
2405
+ }
2406
+ const renderedElement = renderElement$1("astro-island", island, false);
2407
+ destination.write(markHTMLString(renderedElement));
2408
+ }
2409
+ };
2410
+ }
2411
+ function sanitizeElementName(tag) {
2412
+ const unsafe = /[&<>'"\s]+/;
2413
+ if (!unsafe.test(tag)) return tag;
2414
+ return tag.trim().split(unsafe)[0].trim();
2415
+ }
2416
+ async function renderFragmentComponent(result, slots = {}) {
2417
+ const children = await renderSlotToString(result, slots?.default);
2418
+ return {
2419
+ render(destination) {
2420
+ if (children == null) return;
2421
+ destination.write(children);
2422
+ }
2423
+ };
2424
+ }
2425
+ async function renderHTMLComponent(result, Component, _props, slots = {}) {
2426
+ const { slotInstructions, children } = await renderSlots(result, slots);
2427
+ const html = Component({ slots: children });
2428
+ const hydrationHtml = slotInstructions ? slotInstructions.map((instr) => chunkToString(result, instr)).join("") : "";
2429
+ return {
2430
+ render(destination) {
2431
+ destination.write(markHTMLString(hydrationHtml + html));
2432
+ }
2433
+ };
2434
+ }
2435
+ function renderAstroComponent(result, displayName, Component, props, slots = {}) {
2436
+ if (containsServerDirective(props)) {
2437
+ const serverIslandComponent = new ServerIslandComponent(result, props, slots, displayName);
2438
+ result._metadata.propagators.add(serverIslandComponent);
2439
+ return serverIslandComponent;
2440
+ }
2441
+ const instance = createAstroComponentInstance(result, displayName, Component, props, slots);
2442
+ return {
2443
+ render(destination) {
2444
+ return instance.render(destination);
2445
+ }
2446
+ };
2447
+ }
2448
+ function renderComponent(result, displayName, Component, props, slots = {}) {
2449
+ if (isPromise(Component)) {
2450
+ return Component.catch(handleCancellation).then((x) => {
2451
+ return renderComponent(result, displayName, x, props, slots);
2452
+ });
2453
+ }
2454
+ if (isFragmentComponent(Component)) {
2455
+ return renderFragmentComponent(result, slots).catch(handleCancellation);
2456
+ }
2457
+ props = normalizeProps(props);
2458
+ if (isHTMLComponent(Component)) {
2459
+ return renderHTMLComponent(result, Component, props, slots).catch(handleCancellation);
2460
+ }
2461
+ if (isAstroComponentFactory(Component)) {
2462
+ return renderAstroComponent(result, displayName, Component, props, slots);
2463
+ }
2464
+ return renderFrameworkComponent(result, displayName, Component, props, slots).catch(
2465
+ handleCancellation
2466
+ );
2467
+ function handleCancellation(e) {
2468
+ if (result.cancelled)
2469
+ return {
2470
+ render() {
2471
+ }
2472
+ };
2473
+ throw e;
2474
+ }
2475
+ }
2476
+ function normalizeProps(props) {
2477
+ if (props["class:list"] !== void 0) {
2478
+ const value = props["class:list"];
2479
+ delete props["class:list"];
2480
+ props["class"] = clsx(props["class"], value);
2481
+ if (props["class"] === "") {
2482
+ delete props["class"];
2483
+ }
2484
+ }
2485
+ return props;
2486
+ }
2487
+ async function renderComponentToString(result, displayName, Component, props, slots = {}, isPage = false, route) {
2488
+ let str = "";
2489
+ let renderedFirstPageChunk = false;
2490
+ let head = "";
2491
+ if (isPage && !result.partial && nonAstroPageNeedsHeadInjection(Component)) {
2492
+ head += chunkToString(result, maybeRenderHead());
2493
+ }
2494
+ try {
2495
+ const destination = {
2496
+ write(chunk) {
2497
+ if (isPage && !result.partial && !renderedFirstPageChunk) {
2498
+ renderedFirstPageChunk = true;
2499
+ if (!/<!doctype html/i.test(String(chunk))) {
2500
+ const doctype = result.compressHTML ? "<!DOCTYPE html>" : "<!DOCTYPE html>\n";
2501
+ str += doctype + head;
2502
+ }
2503
+ }
2504
+ if (chunk instanceof Response) return;
2505
+ str += chunkToString(result, chunk);
2506
+ }
2507
+ };
2508
+ const renderInstance = await renderComponent(result, displayName, Component, props, slots);
2509
+ if (containsServerDirective(props)) {
2510
+ await bufferHeadContent(result);
2511
+ }
2512
+ await renderInstance.render(destination);
2513
+ } catch (e) {
2514
+ if (AstroError.is(e) && !e.loc) {
2515
+ e.setLocation({
2516
+ file: route?.component
2517
+ });
2518
+ }
2519
+ throw e;
2520
+ }
2521
+ return str;
2522
+ }
2523
+ function nonAstroPageNeedsHeadInjection(pageComponent) {
2524
+ return !!pageComponent?.[needsHeadRenderingSymbol];
2525
+ }
2526
+
2527
+ const ClientOnlyPlaceholder = "astro-client-only";
2528
+ const hasTriedRenderComponentSymbol = Symbol("hasTriedRenderComponent");
2529
+ async function renderJSX(result, vnode) {
2530
+ switch (true) {
2531
+ case vnode instanceof HTMLString:
2532
+ if (vnode.toString().trim() === "") {
2533
+ return "";
2534
+ }
2535
+ return vnode;
2536
+ case typeof vnode === "string":
2537
+ return markHTMLString(escapeHTML(vnode));
2538
+ case typeof vnode === "function":
2539
+ return vnode;
2540
+ case (!vnode && vnode !== 0):
2541
+ return "";
2542
+ case Array.isArray(vnode):
2543
+ return markHTMLString(
2544
+ (await Promise.all(vnode.map((v) => renderJSX(result, v)))).join("")
2545
+ );
2546
+ }
2547
+ return renderJSXVNode(result, vnode);
2548
+ }
2549
+ async function renderJSXVNode(result, vnode) {
2550
+ if (isVNode(vnode)) {
2551
+ switch (true) {
2552
+ case !vnode.type: {
2553
+ throw new Error(`Unable to render ${result.pathname} because it contains an undefined Component!
2554
+ Did you forget to import the component or is it possible there is a typo?`);
2555
+ }
2556
+ case vnode.type === Symbol.for("astro:fragment"):
2557
+ return renderJSX(result, vnode.props.children);
2558
+ case isAstroComponentFactory(vnode.type): {
2559
+ let props = {};
2560
+ let slots = {};
2561
+ for (const [key, value] of Object.entries(vnode.props ?? {})) {
2562
+ if (key === "children" || value && typeof value === "object" && value["$$slot"]) {
2563
+ slots[key === "children" ? "default" : key] = () => renderJSX(result, value);
2564
+ } else {
2565
+ props[key] = value;
2566
+ }
2567
+ }
2568
+ const str = await renderComponentToString(
2569
+ result,
2570
+ vnode.type.name,
2571
+ vnode.type,
2572
+ props,
2573
+ slots
2574
+ );
2575
+ const html = markHTMLString(str);
2576
+ return html;
2577
+ }
2578
+ case (!vnode.type && vnode.type !== 0):
2579
+ return "";
2580
+ case (typeof vnode.type === "string" && vnode.type !== ClientOnlyPlaceholder):
2581
+ return markHTMLString(await renderElement(result, vnode.type, vnode.props ?? {}));
2582
+ }
2583
+ if (vnode.type) {
2584
+ let extractSlots2 = function(child) {
2585
+ if (Array.isArray(child)) {
2586
+ return child.map((c) => extractSlots2(c));
2587
+ }
2588
+ if (!isVNode(child)) {
2589
+ _slots.default.push(child);
2590
+ return;
2591
+ }
2592
+ if ("slot" in child.props) {
2593
+ _slots[child.props.slot] = [..._slots[child.props.slot] ?? [], child];
2594
+ delete child.props.slot;
2595
+ return;
2596
+ }
2597
+ _slots.default.push(child);
2598
+ };
2599
+ if (typeof vnode.type === "function" && vnode.props["server:root"]) {
2600
+ const output2 = await vnode.type(vnode.props ?? {});
2601
+ return await renderJSX(result, output2);
2602
+ }
2603
+ if (typeof vnode.type === "function") {
2604
+ if (vnode.props[hasTriedRenderComponentSymbol]) {
2605
+ delete vnode.props[hasTriedRenderComponentSymbol];
2606
+ const output2 = await vnode.type(vnode.props ?? {});
2607
+ if (output2?.[AstroJSX] || !output2) {
2608
+ return await renderJSXVNode(result, output2);
2609
+ } else {
2610
+ return;
2611
+ }
2612
+ } else {
2613
+ vnode.props[hasTriedRenderComponentSymbol] = true;
2614
+ }
2615
+ }
2616
+ const { children = null, ...props } = vnode.props ?? {};
2617
+ const _slots = {
2618
+ default: []
2619
+ };
2620
+ extractSlots2(children);
2621
+ for (const [key, value] of Object.entries(props)) {
2622
+ if (value?.["$$slot"]) {
2623
+ _slots[key] = value;
2624
+ delete props[key];
2625
+ }
2626
+ }
2627
+ const slotPromises = [];
2628
+ const slots = {};
2629
+ for (const [key, value] of Object.entries(_slots)) {
2630
+ slotPromises.push(
2631
+ renderJSX(result, value).then((output2) => {
2632
+ if (output2.toString().trim().length === 0) return;
2633
+ slots[key] = () => output2;
2634
+ })
2635
+ );
2636
+ }
2637
+ await Promise.all(slotPromises);
2638
+ let output;
2639
+ if (vnode.type === ClientOnlyPlaceholder && vnode.props["client:only"]) {
2640
+ output = await renderComponentToString(
2641
+ result,
2642
+ vnode.props["client:display-name"] ?? "",
2643
+ null,
2644
+ props,
2645
+ slots
2646
+ );
2647
+ } else {
2648
+ output = await renderComponentToString(
2649
+ result,
2650
+ typeof vnode.type === "function" ? vnode.type.name : vnode.type,
2651
+ vnode.type,
2652
+ props,
2653
+ slots
2654
+ );
2655
+ }
2656
+ return markHTMLString(output);
2657
+ }
2658
+ }
2659
+ return markHTMLString(`${vnode}`);
2660
+ }
2661
+ async function renderElement(result, tag, { children, ...props }) {
2662
+ return markHTMLString(
2663
+ `<${tag}${spreadAttributes(props)}${markHTMLString(
2664
+ (children == null || children == "") && voidElementNames.test(tag) ? `/>` : `>${children == null ? "" : await renderJSX(result, prerenderElementChildren(tag, children))}</${tag}>`
2665
+ )}`
2666
+ );
2667
+ }
2668
+ function prerenderElementChildren(tag, children) {
2669
+ if (typeof children === "string" && (tag === "style" || tag === "script")) {
2670
+ return markHTMLString(children);
2671
+ } else {
2672
+ return children;
2673
+ }
2674
+ }
2675
+
2676
+ async function renderPage(result, componentFactory, props, children, streaming, route) {
2677
+ if (!isAstroComponentFactory(componentFactory)) {
2678
+ result._metadata.headInTree = result.componentMetadata.get(componentFactory.moduleId)?.containsHead ?? false;
2679
+ const pageProps = { ...props ?? {}, "server:root": true };
2680
+ const str = await renderComponentToString(
2681
+ result,
2682
+ componentFactory.name,
2683
+ componentFactory,
2684
+ pageProps,
2685
+ {},
2686
+ true,
2687
+ route
2688
+ );
2689
+ const bytes = encoder.encode(str);
2690
+ const headers2 = new Headers([
2691
+ ["Content-Type", "text/html"],
2692
+ ["Content-Length", bytes.byteLength.toString()]
2693
+ ]);
2694
+ if (result.shouldInjectCspMetaTags && (result.cspDestination === "header" || result.cspDestination === "adapter")) {
2695
+ headers2.set("content-security-policy", renderCspContent(result));
2696
+ }
2697
+ return new Response(bytes, {
2698
+ headers: headers2
2699
+ });
2700
+ }
2701
+ result._metadata.headInTree = result.componentMetadata.get(componentFactory.moduleId)?.containsHead ?? false;
2702
+ let body;
2703
+ if (streaming) {
2704
+ if (isNode && !isDeno) {
2705
+ const nodeBody = await renderToAsyncIterable(
2706
+ result,
2707
+ componentFactory,
2708
+ props,
2709
+ children,
2710
+ true,
2711
+ route
2712
+ );
2713
+ body = nodeBody;
2714
+ } else {
2715
+ body = await renderToReadableStream(result, componentFactory, props, children, true, route);
2716
+ }
2717
+ } else {
2718
+ body = await renderToString(result, componentFactory, props, children, true, route);
2719
+ }
2720
+ if (body instanceof Response) return body;
2721
+ const init = result.response;
2722
+ const headers = new Headers(init.headers);
2723
+ if (result.shouldInjectCspMetaTags && result.cspDestination === "header" || result.cspDestination === "adapter") {
2724
+ headers.set("content-security-policy", renderCspContent(result));
2725
+ }
2726
+ if (!streaming && typeof body === "string") {
2727
+ body = encoder.encode(body);
2728
+ headers.set("Content-Length", body.byteLength.toString());
2729
+ }
2730
+ let status = init.status;
2731
+ let statusText = init.statusText;
2732
+ if (route?.route === "/404") {
2733
+ status = 404;
2734
+ if (statusText === "OK") {
2735
+ statusText = "Not Found";
2736
+ }
2737
+ } else if (route?.route === "/500") {
2738
+ status = 500;
2739
+ if (statusText === "OK") {
2740
+ statusText = "Internal Server Error";
2741
+ }
2742
+ }
2743
+ if (status) {
2744
+ return new Response(body, { ...init, headers, status, statusText });
2745
+ } else {
2746
+ return new Response(body, { ...init, headers });
2747
+ }
2748
+ }
2749
+
2750
+ async function renderScript(result, id) {
2751
+ if (result._metadata.renderedScripts.has(id)) return;
2752
+ result._metadata.renderedScripts.add(id);
2753
+ const inlined = result.inlinedScripts.get(id);
2754
+ if (inlined != null) {
2755
+ if (inlined) {
2756
+ return markHTMLString(`<script type="module">${inlined}</script>`);
2757
+ } else {
2758
+ return "";
2759
+ }
2760
+ }
2761
+ const resolved = await result.resolve(id);
2762
+ return markHTMLString(
2763
+ `<script type="module" src="${result.userAssetsBase ? (result.base === "/" ? "" : result.base) + result.userAssetsBase : ""}${resolved}"></script>`
2764
+ );
2765
+ }
2766
+
2767
+ "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_".split("").reduce((v, c) => (v[c.charCodeAt(0)] = c, v), []);
2768
+ "-0123456789_".split("").reduce((v, c) => (v[c.charCodeAt(0)] = c, v), []);
2769
+
2770
+ function spreadAttributes(values = {}, _name, { class: scopedClassName } = {}) {
2771
+ let output = "";
2772
+ if (scopedClassName) {
2773
+ if (typeof values.class !== "undefined") {
2774
+ values.class += ` ${scopedClassName}`;
2775
+ } else if (typeof values["class:list"] !== "undefined") {
2776
+ values["class:list"] = [values["class:list"], scopedClassName];
2777
+ } else {
2778
+ values.class = scopedClassName;
2779
+ }
2780
+ }
2781
+ for (const [key, value] of Object.entries(values)) {
2782
+ output += addAttribute(value, key, true, _name);
2783
+ }
2784
+ return markHTMLString(output);
2785
+ }
2786
+
2787
+ export { chunkToString as $, AstroError as A, ResponseSentError as B, ActionNotFoundError as C, MiddlewareNoDataOrNextCalled as D, ExpectedImage as E, FailedToFetchRemoteImageDimensions as F, MiddlewareNotAResponse as G, originPathnameSymbol as H, IncompatibleDescriptorOptions as I, RewriteWithBodyUsed as J, GetStaticPathsRequired as K, LocalImageUsedWrongly as L, MissingImageDimension as M, NoImageMetadata as N, InvalidGetStaticPathsReturn as O, InvalidGetStaticPathsEntry as P, GetStaticPathsExpectedParams as Q, ROUTE_TYPE_HEADER as R, GetStaticPathsInvalidRouteParam as S, PageNumberParamNotFound as T, UnsupportedImageFormat as U, DEFAULT_404_COMPONENT as V, NoMatchingStaticPathFound as W, PrerenderDynamicEndpointPathCollide as X, ReservedSlotName as Y, renderSlotToString as Z, renderJSX as _, UnsupportedImageConversion as a, isRenderInstruction as a0, ForbiddenRewrite as a1, SessionStorageInitError as a2, SessionStorageSaveError as a3, ASTRO_VERSION as a4, CspNotEnabled as a5, LocalsReassigned as a6, generateCspDigest as a7, PrerenderClientAddressNotAvailable as a8, clientAddressSymbol as a9, ClientAddressNotAvailable as aa, StaticClientAddressNotAvailable as ab, AstroResponseHeadersReassigned as ac, responseSentSymbol as ad, renderPage as ae, REWRITE_DIRECTIVE_HEADER_KEY as af, REWRITE_DIRECTIVE_HEADER_VALUE as ag, renderEndpoint as ah, LocalsNotAnObject as ai, REROUTABLE_STATUS_CODES as aj, nodeRequestAbortControllerCleanupSymbol as ak, NOOP_MIDDLEWARE_HEADER as al, REDIRECT_STATUS_CODES as am, ActionsReturnedInvalidDataError as an, MissingSharp as ao, ExpectedImageOptions as b, ExpectedNotESMImage as c, InvalidImageService as d, createComponent as e, createAstro as f, ImageMissingAlt as g, addAttribute as h, ExperimentalFontsNotEnabled as i, FontFamilyNotFound as j, renderComponent as k, Fragment as l, maybeRenderHead as m, renderScript as n, renderHead as o, renderSlot as p, decodeKey as q, renderTemplate as r, spreadAttributes as s, toStyleString as t, unescapeHTML as u, decryptString as v, createSlotValueFromString as w, isAstroComponentFactory as x, REROUTE_DIRECTIVE_HEADER as y, i18nNoLocaleFoundInPath as z };