@absolutejs/absolute 0.19.0-beta.808 → 0.19.0-beta.809

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 (260) hide show
  1. package/dist/angular/browser.js +9801 -57
  2. package/dist/angular/browser.js.map +246 -4
  3. package/dist/angular/components/core/streamingSlotRegistrar.js +1 -1
  4. package/dist/angular/components/core/streamingSlotRegistry.js +2 -2
  5. package/dist/angular/index.js +14877 -60
  6. package/dist/angular/index.js.map +281 -4
  7. package/dist/angular/server.js +5610 -45
  8. package/dist/angular/server.js.map +51 -3
  9. package/dist/build.js +18092 -45
  10. package/dist/build.js.map +99 -3
  11. package/dist/cli/index.js +317 -86
  12. package/dist/client/index.js +1100 -40
  13. package/dist/client/index.js.map +24 -4
  14. package/dist/core/streamingSlotRegistrar.js +108 -11
  15. package/dist/core/streamingSlotRegistrar.js.map +4 -3
  16. package/dist/core/streamingSlotRegistry.js +169 -7
  17. package/dist/core/streamingSlotRegistry.js.map +5 -3
  18. package/dist/index.js +19957 -547
  19. package/dist/index.js.map +116 -3
  20. package/dist/islands/browser.js +228 -9
  21. package/dist/islands/browser.js.map +9 -4
  22. package/dist/islands/index.js +1908 -17
  23. package/dist/islands/index.js.map +27 -3
  24. package/dist/react/browser.js +328 -12
  25. package/dist/react/browser.js.map +12 -4
  26. package/dist/react/components/index.js +167 -16
  27. package/dist/react/components/index.js.map +6 -3
  28. package/dist/react/hooks/index.js +183 -8
  29. package/dist/react/hooks/index.js.map +7 -3
  30. package/dist/react/index.js +3627 -36
  31. package/dist/react/index.js.map +45 -4
  32. package/dist/react/jsxDevRuntimeCompat.js +61 -2
  33. package/dist/react/jsxDevRuntimeCompat.js.map +2 -2
  34. package/dist/react/server.js +1789 -18
  35. package/dist/react/server.js.map +21 -3
  36. package/dist/src/angular/injectorPatch.d.ts +1 -0
  37. package/dist/src/index.d.ts +1 -0
  38. package/dist/svelte/browser.js +247 -12
  39. package/dist/svelte/browser.js.map +10 -3
  40. package/dist/svelte/index.js +3732 -37
  41. package/dist/svelte/index.js.map +47 -4
  42. package/dist/svelte/server.js +2794 -21
  43. package/dist/svelte/server.js.map +27 -3
  44. package/dist/vue/browser.js +348 -12
  45. package/dist/vue/browser.js.map +12 -4
  46. package/dist/vue/components/Image.js +240 -7
  47. package/dist/vue/components/Image.js.map +6 -3
  48. package/dist/vue/components/index.js +544 -11
  49. package/dist/vue/components/index.js.map +9 -3
  50. package/dist/vue/index.js +4212 -52
  51. package/dist/vue/index.js.map +50 -4
  52. package/dist/vue/server.js +1849 -18
  53. package/dist/vue/server.js.map +21 -3
  54. package/package.json +1 -1
  55. package/dist/chunk-0867j0r0.js +0 -136
  56. package/dist/chunk-0867j0r0.js.map +0 -10
  57. package/dist/chunk-0kdc6r16.js +0 -20
  58. package/dist/chunk-0kdc6r16.js.map +0 -10
  59. package/dist/chunk-102fp7xe.js +0 -63
  60. package/dist/chunk-102fp7xe.js.map +0 -10
  61. package/dist/chunk-11zpfqz6.js +0 -19
  62. package/dist/chunk-11zpfqz6.js.map +0 -10
  63. package/dist/chunk-1rfh7hw9.js +0 -319
  64. package/dist/chunk-1rfh7hw9.js.map +0 -11
  65. package/dist/chunk-25v9t56f.js +0 -29
  66. package/dist/chunk-25v9t56f.js.map +0 -11
  67. package/dist/chunk-2f21eenc.js +0 -21
  68. package/dist/chunk-2f21eenc.js.map +0 -10
  69. package/dist/chunk-2ga2znex.js +0 -13
  70. package/dist/chunk-2ga2znex.js.map +0 -9
  71. package/dist/chunk-30yrw0f6.js +0 -33
  72. package/dist/chunk-30yrw0f6.js.map +0 -10
  73. package/dist/chunk-38jwhqcw.js +0 -4410
  74. package/dist/chunk-38jwhqcw.js.map +0 -28
  75. package/dist/chunk-3g91wb4f.js +0 -358
  76. package/dist/chunk-3g91wb4f.js.map +0 -10
  77. package/dist/chunk-3yjzpcne.js +0 -34
  78. package/dist/chunk-3yjzpcne.js.map +0 -10
  79. package/dist/chunk-41bf6aqt.js +0 -17
  80. package/dist/chunk-41bf6aqt.js.map +0 -9
  81. package/dist/chunk-4d39r92n.js +0 -81
  82. package/dist/chunk-4d39r92n.js.map +0 -10
  83. package/dist/chunk-5003emhv.js +0 -17
  84. package/dist/chunk-5003emhv.js.map +0 -10
  85. package/dist/chunk-5f67rsed.js +0 -466
  86. package/dist/chunk-5f67rsed.js.map +0 -10
  87. package/dist/chunk-5fhp1jap.js +0 -9169
  88. package/dist/chunk-5fhp1jap.js.map +0 -236
  89. package/dist/chunk-6pdj08z3.js +0 -73
  90. package/dist/chunk-6pdj08z3.js.map +0 -12
  91. package/dist/chunk-6qjbrt0k.js +0 -13
  92. package/dist/chunk-6qjbrt0k.js.map +0 -9
  93. package/dist/chunk-6sccb4jr.js +0 -14
  94. package/dist/chunk-6sccb4jr.js.map +0 -9
  95. package/dist/chunk-798spvzv.js +0 -50
  96. package/dist/chunk-798spvzv.js.map +0 -10
  97. package/dist/chunk-7fw6x3js.js +0 -131
  98. package/dist/chunk-7fw6x3js.js.map +0 -11
  99. package/dist/chunk-7kjj42xm.js +0 -11
  100. package/dist/chunk-7kjj42xm.js.map +0 -10
  101. package/dist/chunk-7mtstdqn.js +0 -90
  102. package/dist/chunk-7mtstdqn.js.map +0 -10
  103. package/dist/chunk-851whwc7.js +0 -17
  104. package/dist/chunk-851whwc7.js.map +0 -10
  105. package/dist/chunk-85n68sy6.js +0 -103
  106. package/dist/chunk-85n68sy6.js.map +0 -10
  107. package/dist/chunk-8kcfffry.js +0 -35
  108. package/dist/chunk-8kcfffry.js.map +0 -10
  109. package/dist/chunk-8qqxc1h2.js +0 -426
  110. package/dist/chunk-8qqxc1h2.js.map +0 -14
  111. package/dist/chunk-92fsjfpp.js +0 -1731
  112. package/dist/chunk-92fsjfpp.js.map +0 -11
  113. package/dist/chunk-93sqk7be.js +0 -139
  114. package/dist/chunk-93sqk7be.js.map +0 -12
  115. package/dist/chunk-94gvx0hg.js +0 -28
  116. package/dist/chunk-94gvx0hg.js.map +0 -10
  117. package/dist/chunk-9c5tj4k3.js +0 -130
  118. package/dist/chunk-9c5tj4k3.js.map +0 -10
  119. package/dist/chunk-9ve9jq72.js +0 -203
  120. package/dist/chunk-9ve9jq72.js.map +0 -10
  121. package/dist/chunk-9xrsjeem.js +0 -12
  122. package/dist/chunk-9xrsjeem.js.map +0 -9
  123. package/dist/chunk-a9mvyp04.js +0 -87
  124. package/dist/chunk-a9mvyp04.js.map +0 -10
  125. package/dist/chunk-b3gbnrwe.js +0 -21
  126. package/dist/chunk-b3gbnrwe.js.map +0 -10
  127. package/dist/chunk-bmgqm774.js +0 -65
  128. package/dist/chunk-bmgqm774.js.map +0 -9
  129. package/dist/chunk-bxfghpma.js +0 -69
  130. package/dist/chunk-bxfghpma.js.map +0 -10
  131. package/dist/chunk-c1jfjnka.js +0 -74
  132. package/dist/chunk-c1jfjnka.js.map +0 -10
  133. package/dist/chunk-cbkrwmvh.js +0 -80
  134. package/dist/chunk-cbkrwmvh.js.map +0 -10
  135. package/dist/chunk-cdxd7sy2.js +0 -71
  136. package/dist/chunk-cdxd7sy2.js.map +0 -10
  137. package/dist/chunk-cg95827x.js +0 -21
  138. package/dist/chunk-cg95827x.js.map +0 -10
  139. package/dist/chunk-cm0g4q6w.js +0 -149
  140. package/dist/chunk-cm0g4q6w.js.map +0 -10
  141. package/dist/chunk-cwfy538a.js +0 -51
  142. package/dist/chunk-cwfy538a.js.map +0 -9
  143. package/dist/chunk-d7mwkzry.js +0 -261
  144. package/dist/chunk-d7mwkzry.js.map +0 -10
  145. package/dist/chunk-d8w0qm28.js +0 -184
  146. package/dist/chunk-d8w0qm28.js.map +0 -11
  147. package/dist/chunk-d9c0am65.js +0 -12
  148. package/dist/chunk-d9c0am65.js.map +0 -10
  149. package/dist/chunk-daqghmg8.js +0 -12
  150. package/dist/chunk-daqghmg8.js.map +0 -9
  151. package/dist/chunk-e3r9fxaa.js +0 -149
  152. package/dist/chunk-e3r9fxaa.js.map +0 -10
  153. package/dist/chunk-e8eecyrq.js +0 -244
  154. package/dist/chunk-e8eecyrq.js.map +0 -10
  155. package/dist/chunk-ex2hxe0v.js +0 -160
  156. package/dist/chunk-ex2hxe0v.js.map +0 -11
  157. package/dist/chunk-fak944et.js +0 -91
  158. package/dist/chunk-fak944et.js.map +0 -10
  159. package/dist/chunk-ff70rnhd.js +0 -672
  160. package/dist/chunk-ff70rnhd.js.map +0 -15
  161. package/dist/chunk-fygx2ymm.js +0 -118
  162. package/dist/chunk-fygx2ymm.js.map +0 -12
  163. package/dist/chunk-g15qj669.js +0 -271
  164. package/dist/chunk-g15qj669.js.map +0 -11
  165. package/dist/chunk-gd6wmknh.js +0 -121
  166. package/dist/chunk-gd6wmknh.js.map +0 -11
  167. package/dist/chunk-gf0ygptk.js +0 -85
  168. package/dist/chunk-gf0ygptk.js.map +0 -11
  169. package/dist/chunk-gytkmthr.js +0 -220
  170. package/dist/chunk-gytkmthr.js.map +0 -10
  171. package/dist/chunk-h5bbfn3n.js +0 -28
  172. package/dist/chunk-h5bbfn3n.js.map +0 -11
  173. package/dist/chunk-h6mye9r3.js +0 -93
  174. package/dist/chunk-h6mye9r3.js.map +0 -10
  175. package/dist/chunk-hcsmxw1v.js +0 -85
  176. package/dist/chunk-hcsmxw1v.js.map +0 -10
  177. package/dist/chunk-hyjs4bqs.js +0 -8
  178. package/dist/chunk-hyjs4bqs.js.map +0 -10
  179. package/dist/chunk-j88z31ep.js +0 -25
  180. package/dist/chunk-j88z31ep.js.map +0 -10
  181. package/dist/chunk-jn91vzkh.js +0 -66
  182. package/dist/chunk-jn91vzkh.js.map +0 -10
  183. package/dist/chunk-jpkjdgsk.js +0 -167
  184. package/dist/chunk-jpkjdgsk.js.map +0 -11
  185. package/dist/chunk-jwxt8gnp.js +0 -13
  186. package/dist/chunk-jwxt8gnp.js.map +0 -9
  187. package/dist/chunk-kk8w9rh5.js +0 -195
  188. package/dist/chunk-kk8w9rh5.js.map +0 -10
  189. package/dist/chunk-m97ze5hz.js +0 -46
  190. package/dist/chunk-m97ze5hz.js.map +0 -10
  191. package/dist/chunk-mbazhahf.js +0 -60
  192. package/dist/chunk-mbazhahf.js.map +0 -10
  193. package/dist/chunk-mgfwq18r.js +0 -15
  194. package/dist/chunk-mgfwq18r.js.map +0 -9
  195. package/dist/chunk-mtgf69xn.js +0 -88
  196. package/dist/chunk-mtgf69xn.js.map +0 -10
  197. package/dist/chunk-mtxzyxpg.js +0 -102
  198. package/dist/chunk-mtxzyxpg.js.map +0 -10
  199. package/dist/chunk-nehhtthw.js +0 -225
  200. package/dist/chunk-nehhtthw.js.map +0 -10
  201. package/dist/chunk-p5504p14.js +0 -16
  202. package/dist/chunk-p5504p14.js.map +0 -10
  203. package/dist/chunk-pnscgw95.js +0 -90
  204. package/dist/chunk-pnscgw95.js.map +0 -10
  205. package/dist/chunk-pvpp4pvs.js +0 -17
  206. package/dist/chunk-pvpp4pvs.js.map +0 -10
  207. package/dist/chunk-qh75agse.js +0 -95
  208. package/dist/chunk-qh75agse.js.map +0 -10
  209. package/dist/chunk-qxq2zcty.js +0 -52
  210. package/dist/chunk-qxq2zcty.js.map +0 -10
  211. package/dist/chunk-r6e8pytx.js +0 -22
  212. package/dist/chunk-r6e8pytx.js.map +0 -9
  213. package/dist/chunk-r7jmgqnw.js +0 -114
  214. package/dist/chunk-r7jmgqnw.js.map +0 -10
  215. package/dist/chunk-s6defjk2.js +0 -116
  216. package/dist/chunk-s6defjk2.js.map +0 -10
  217. package/dist/chunk-sd39p726.js +0 -619
  218. package/dist/chunk-sd39p726.js.map +0 -10
  219. package/dist/chunk-swrnzs4c.js +0 -63
  220. package/dist/chunk-swrnzs4c.js.map +0 -10
  221. package/dist/chunk-tfe3sb44.js +0 -33
  222. package/dist/chunk-tfe3sb44.js.map +0 -10
  223. package/dist/chunk-tjr0kcev.js +0 -41
  224. package/dist/chunk-tjr0kcev.js.map +0 -9
  225. package/dist/chunk-tx9edm1x.js +0 -34
  226. package/dist/chunk-tx9edm1x.js.map +0 -10
  227. package/dist/chunk-txhm2vb5.js +0 -18
  228. package/dist/chunk-txhm2vb5.js.map +0 -9
  229. package/dist/chunk-v5vmsxmy.js +0 -526
  230. package/dist/chunk-v5vmsxmy.js.map +0 -12
  231. package/dist/chunk-vjhxm8n2.js +0 -29
  232. package/dist/chunk-vjhxm8n2.js.map +0 -9
  233. package/dist/chunk-vkrpm7kc.js +0 -247
  234. package/dist/chunk-vkrpm7kc.js.map +0 -12
  235. package/dist/chunk-w3m4m5we.js +0 -4925
  236. package/dist/chunk-w3m4m5we.js.map +0 -12
  237. package/dist/chunk-wrxtn9ve.js +0 -18
  238. package/dist/chunk-wrxtn9ve.js.map +0 -10
  239. package/dist/chunk-wwzvp0zn.js +0 -192
  240. package/dist/chunk-wwzvp0zn.js.map +0 -10
  241. package/dist/chunk-x09cskqd.js +0 -377
  242. package/dist/chunk-x09cskqd.js.map +0 -10
  243. package/dist/chunk-xnt8c6h2.js +0 -576
  244. package/dist/chunk-xnt8c6h2.js.map +0 -10
  245. package/dist/chunk-xw0tx842.js +0 -13
  246. package/dist/chunk-xw0tx842.js.map +0 -9
  247. package/dist/chunk-xx5b6b9m.js +0 -69
  248. package/dist/chunk-xx5b6b9m.js.map +0 -10
  249. package/dist/chunk-xz1kdswj.js +0 -21
  250. package/dist/chunk-xz1kdswj.js.map +0 -9
  251. package/dist/chunk-y84qnsd3.js +0 -32
  252. package/dist/chunk-y84qnsd3.js.map +0 -10
  253. package/dist/chunk-ywjn0rad.js +0 -14
  254. package/dist/chunk-ywjn0rad.js.map +0 -9
  255. package/dist/chunk-z9nvhm6r.js +0 -13
  256. package/dist/chunk-z9nvhm6r.js.map +0 -9
  257. package/dist/chunk-zhmvdpk6.js +0 -15
  258. package/dist/chunk-zhmvdpk6.js.map +0 -9
  259. package/dist/chunk-zrg9d4zw.js +0 -784
  260. package/dist/chunk-zrg9d4zw.js.map +0 -10
@@ -1,41 +1,3510 @@
1
1
  // @bun
2
+ var __create = Object.create;
3
+ var __getProtoOf = Object.getPrototypeOf;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ function __accessProp(key) {
8
+ return this[key];
9
+ }
10
+ var __toESMCache_node;
11
+ var __toESMCache_esm;
12
+ var __toESM = (mod, isNodeMode, target) => {
13
+ var canCache = mod != null && typeof mod === "object";
14
+ if (canCache) {
15
+ var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
16
+ var cached = cache.get(mod);
17
+ if (cached)
18
+ return cached;
19
+ }
20
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
21
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
22
+ for (let key of __getOwnPropNames(mod))
23
+ if (!__hasOwnProp.call(to, key))
24
+ __defProp(to, key, {
25
+ get: __accessProp.bind(mod, key),
26
+ enumerable: true
27
+ });
28
+ if (canCache)
29
+ cache.set(mod, to);
30
+ return to;
31
+ };
32
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
33
+ var __returnValue = (v) => v;
34
+ function __exportSetter(name, newValue) {
35
+ this[name] = __returnValue.bind(null, newValue);
36
+ }
37
+ var __export = (target, all) => {
38
+ for (var name in all)
39
+ __defProp(target, name, {
40
+ get: all[name],
41
+ enumerable: true,
42
+ configurable: true,
43
+ set: __exportSetter.bind(all, name)
44
+ });
45
+ };
46
+ var __legacyDecorateClassTS = function(decorators, target, key, desc) {
47
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
48
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
49
+ r = Reflect.decorate(decorators, target, key, desc);
50
+ else
51
+ for (var i = decorators.length - 1;i >= 0; i--)
52
+ if (d = decorators[i])
53
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
54
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
55
+ };
56
+ var __legacyMetadataTS = (k, v) => {
57
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
58
+ return Reflect.metadata(k, v);
59
+ };
60
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
61
+ var __require = import.meta.require;
62
+
63
+ // src/constants.ts
64
+ var ANGULAR_INIT_TIMEOUT_MS = 500, ANSI_ESCAPE_CODE = 27, ANSI_ESCAPE_LENGTH = 3, ASCII_SPACE = 32, BASE_36_RADIX = 36, BUN_BUILD_WARNING_SUPPRESSION = "wildcard sideEffects are not supported yet", BODY_SLICE_LENGTH = 2000, BYTES_PER_KILOBYTE = 1024, CLI_ARGS_OFFSET = 3, CSS_ERROR_RESOLVE_DELAY_MS = 50, CSS_MAX_CHECK_ATTEMPTS = 10, CSS_MAX_PARSE_TIMEOUT_MS = 500, CSS_SHEET_READY_TIMEOUT_MS = 100, DEFAULT_CHUNK_SIZE = 16384, DEFAULT_DEBOUNCE_MS = 15, DEFAULT_PORT = 3000, DEV_SERVER_RESTART_DEBOUNCE_MS = 100, DOM_UPDATE_DELAY_MS = 50, FILE_PROTOCOL_PREFIX_LENGTH = 7, FOCUS_ID_PREFIX_LENGTH = 3, FOCUS_IDX_PREFIX_LENGTH = 4, FOCUS_NAME_PREFIX_LENGTH = 5, HMR_UPDATE_TIMEOUT_MS = 2000, HOOK_SIGNATURE_LENGTH = 12, EXCLUDE_LAST_OFFSET = -1, HTTP_STATUS_OK = 200, HTTP_STATUS_BAD_REQUEST = 400, HTTP_STATUS_NOT_FOUND = 404, HOURS_IN_DAY = 24, HOURS_IN_HALF_DAY = 12, IMAGE_DEFAULT_DEVICE_SIZES, IMAGE_DEFAULT_IMAGE_SIZES, IMAGE_DEFAULT_QUALITY = 75, IMAGE_GLOB_SUFFIX_LENGTH = 2, MAX_ERROR_LENGTH = 200, MAX_RECONNECT_ATTEMPTS = 60, MILLISECONDS_IN_A_SECOND = 1000, MINUTES_IN_AN_HOUR = 60, SECONDS_IN_A_MINUTE = 60, MILLISECONDS_IN_A_MINUTE, MILLISECONDS_IN_A_DAY, OVERLAY_FADE_DURATION_MS = 150, PING_INTERVAL_MS = 30000, RAF_BATCH_COUNT = 3, RANDOM_ID_END_INDEX = 11, REBUILD_BATCH_DELAY_MS = 10, REBUILD_RELOAD_DELAY_MS = 200, RECONNECT_INITIAL_DELAY_MS = 500, RECONNECT_POLL_INTERVAL_MS = 300, REACT_STREAM_SLOT_FAST_DELAY_MS = 5, REACT_STREAM_SLOT_SLOW_DELAY_MS = 20, SIGINT_EXIT_CODE = 130, SIGTERM_EXIT_CODE = 143, SVELTE_CSS_LOAD_TIMEOUT_MS = 500, TIME_PRECISION = 2, TWO_THIRDS, UNFOUND_INDEX = -1, WEBSOCKET_NORMAL_CLOSURE = 1000, WORKSPACE_COMMAND_ARGS_OFFSET = 3, WORKSPACE_FAILURE_LOG_PRINT_LIMIT = 30, WORKSPACE_FAILURE_RECENT_LOG_LIMIT = 60, WORKSPACE_READY_ATTEMPT_TIMEOUT_MS = 5000, WORKSPACE_READY_PROBE_INTERVAL_MS = 250, WORKSPACE_READY_TIMEOUT_MS = 30000, WORKSPACE_SHUTDOWN_TIMEOUT_MS = 1e4, WORKSPACE_TUI_DEFAULT_HEIGHT = 28, WORKSPACE_TUI_DEFAULT_WIDTH = 100, WORKSPACE_TUI_ESCAPE_SEQUENCE_TIMEOUT_MS = 30, WORKSPACE_TUI_FOOTER_LINE_COUNT = 3, WORKSPACE_TUI_MIN_LOG_HEIGHT = 3, WORKSPACE_TUI_MIN_SERVICE_NAME_WIDTH = 7, WORKSPACE_TUI_MIN_TARGET_WIDTH = 8, WORKSPACE_TUI_MIN_WRAP_WIDTH = 12, WORKSPACE_TUI_PROMPT_CURSOR_OFFSET = 3, WORKSPACE_TUI_RECENT_LOG_LIMIT = 40, WORKSPACE_TUI_RENDER_DEBOUNCE_MS = 16, WORKSPACE_TUI_STATUS_WIDTH = 10, WORKSPACE_TUI_TARGET_PADDING_WIDTH = 6, WORKSPACE_TUI_VISIBILITY_WIDTH = 8;
65
+ var init_constants = __esm(() => {
66
+ IMAGE_DEFAULT_DEVICE_SIZES = [
67
+ 640,
68
+ 750,
69
+ 828,
70
+ 1080,
71
+ 1200,
72
+ 1920,
73
+ 2048,
74
+ 3840
75
+ ];
76
+ IMAGE_DEFAULT_IMAGE_SIZES = [16, 32, 48, 64, 96, 128, 256, 384];
77
+ MILLISECONDS_IN_A_MINUTE = MILLISECONDS_IN_A_SECOND * SECONDS_IN_A_MINUTE;
78
+ MILLISECONDS_IN_A_DAY = MILLISECONDS_IN_A_SECOND * SECONDS_IN_A_MINUTE * MINUTES_IN_AN_HOUR * HOURS_IN_DAY;
79
+ TWO_THIRDS = 2 / 3;
80
+ });
81
+
82
+ // src/core/devRouteRegistrationCallsite.ts
83
+ var exports_devRouteRegistrationCallsite = {};
84
+ __export(exports_devRouteRegistrationCallsite, {
85
+ patchElysiaRouteRegistrationCallsites: () => patchElysiaRouteRegistrationCallsites,
86
+ getCurrentRouteRegistrationCallsite: () => getCurrentRouteRegistrationCallsite
87
+ });
88
+ import { AsyncLocalStorage } from "async_hooks";
89
+ import { Elysia } from "elysia";
90
+ var ROUTE_CALLSITE_STORAGE_KEY, ROUTE_CALLSITE_PATCHED_KEY, ROUTE_METHOD_NAMES, isObjectRecord3 = (value) => Boolean(value) && typeof value === "object", isAsyncLocalStorage2 = (value) => isObjectRecord3(value) && ("getStore" in value) && typeof value.getStore === "function" && ("run" in value) && typeof value.run === "function", isRouteMethod = (value) => typeof value === "function", getRouteCallsiteStorage = () => {
91
+ const value = Reflect.get(globalThis, ROUTE_CALLSITE_STORAGE_KEY);
92
+ if (value === null || typeof value === "undefined") {
93
+ return;
94
+ }
95
+ return isAsyncLocalStorage2(value) ? value : undefined;
96
+ }, ensureRouteCallsiteStorage = () => {
97
+ const existing = getRouteCallsiteStorage();
98
+ if (existing) {
99
+ return existing;
100
+ }
101
+ const storage = new AsyncLocalStorage;
102
+ Reflect.set(globalThis, ROUTE_CALLSITE_STORAGE_KEY, storage);
103
+ return storage;
104
+ }, normalizeCallsitePath = (value) => value.replace(`${process.cwd()}/`, "").replace(process.cwd(), "").replace(/^\.\/+/, ""), shouldIgnoreRouteCallsiteFrame = (frame) => frame.includes("/node_modules/") || frame.includes("/dist/") || frame.includes("/src/core/devRouteRegistrationCallsite."), getRouteCallsiteLocation = (frame) => frame.match(/\((\/[^)]+:\d+:\d+)\)$/)?.[1] ?? frame.match(/at (\/[^ ]+:\d+:\d+)$/)?.[1], extractRouteRegistrationCallsite = (stack) => {
105
+ const location = stack.split(`
106
+ `).slice(1).map((line) => line.trim()).filter((frame) => !shouldIgnoreRouteCallsiteFrame(frame)).map((frame) => getRouteCallsiteLocation(frame)).find((frameLocation) => frameLocation !== undefined);
107
+ return location ? normalizeCallsitePath(location) : undefined;
108
+ }, captureRouteRegistrationCallsite = () => {
109
+ const { stack } = new Error;
110
+ if (!stack) {
111
+ return;
112
+ }
113
+ return extractRouteRegistrationCallsite(stack);
114
+ }, wrapRouteHandlerWithCallsite = (handler, callsite) => {
115
+ if (typeof handler !== "function" || !callsite) {
116
+ return handler;
117
+ }
118
+ const storage = ensureRouteCallsiteStorage();
119
+ const routeHandler = handler;
120
+ return function wrappedRouteHandler(...args) {
121
+ return storage.run({ callsite }, () => Reflect.apply(routeHandler, this, args));
122
+ };
123
+ }, createPatchedRouteMethod = (originalMethod) => function patchedRouteMethod(path, handler, ...rest) {
124
+ const callsite = captureRouteRegistrationCallsite();
125
+ return Reflect.apply(originalMethod, this, [
126
+ path,
127
+ wrapRouteHandlerWithCallsite(handler, callsite),
128
+ ...rest
129
+ ]);
130
+ }, getCurrentRouteRegistrationCallsite = () => getRouteCallsiteStorage()?.getStore()?.callsite, patchElysiaRouteRegistrationCallsites = () => {
131
+ if (false) {}
132
+ if (Reflect.get(globalThis, ROUTE_CALLSITE_PATCHED_KEY) === true) {
133
+ return;
134
+ }
135
+ const { prototype } = Elysia;
136
+ ROUTE_METHOD_NAMES.forEach((methodName) => {
137
+ const originalMethod = Reflect.get(prototype, methodName);
138
+ if (!isRouteMethod(originalMethod))
139
+ return;
140
+ Reflect.set(prototype, methodName, createPatchedRouteMethod(originalMethod));
141
+ });
142
+ Reflect.set(globalThis, ROUTE_CALLSITE_PATCHED_KEY, true);
143
+ };
144
+ var init_devRouteRegistrationCallsite = __esm(() => {
145
+ ROUTE_CALLSITE_STORAGE_KEY = Symbol.for("absolutejs.devRouteRegistrationCallsiteStorage");
146
+ ROUTE_CALLSITE_PATCHED_KEY = Symbol.for("absolutejs.devRouteRegistrationCallsitePatched");
147
+ ROUTE_METHOD_NAMES = [
148
+ "all",
149
+ "delete",
150
+ "get",
151
+ "head",
152
+ "options",
153
+ "patch",
154
+ "post",
155
+ "put"
156
+ ];
157
+ });
158
+
159
+ // src/client/streamSwap.ts
160
+ var streamSwapRuntime = () => {
161
+ const absoluteWindow = window;
162
+ const SLOT_PATCH_EVENT = "absolutejs:slot-patch";
163
+ if (absoluteWindow.__ABS_SLOT_RUNTIME__ === true)
164
+ return;
165
+ absoluteWindow.__ABS_SLOT_RUNTIME__ = true;
166
+ absoluteWindow.__ABS_SLOT_CONSUMERS__ = absoluteWindow.__ABS_SLOT_CONSUMERS__ ?? {};
167
+ absoluteWindow.__ABS_SLOT_PENDING__ = absoluteWindow.__ABS_SLOT_PENDING__ ?? {};
168
+ const consumers = absoluteWindow.__ABS_SLOT_CONSUMERS__;
169
+ const pending = absoluteWindow.__ABS_SLOT_PENDING__;
170
+ const isObjectRecord4 = (value) => Boolean(value) && typeof value === "object";
171
+ const isPatchedPendingEntry = (value) => {
172
+ if (!isObjectRecord4(value))
173
+ return false;
174
+ return value.domPatched === true && "payload" in value;
175
+ };
176
+ const unwrapPendingPayload = (value) => isPatchedPendingEntry(value) ? value.payload : value;
177
+ const canApplyImmediately = () => absoluteWindow.__ABS_SLOT_HYDRATION_PENDING__ !== true;
178
+ const isAngularDeferPayload = (payload) => {
179
+ if (!isObjectRecord4(payload))
180
+ return false;
181
+ return payload.kind === "angular-defer";
182
+ };
183
+ const isVueSuspensePayload = (payload) => {
184
+ if (!isObjectRecord4(payload))
185
+ return false;
186
+ return payload.kind === "vue-suspense";
187
+ };
188
+ const resolveHtml = (payload) => {
189
+ if (!isObjectRecord4(payload)) {
190
+ return typeof payload === "string" ? payload : "";
191
+ }
192
+ if (typeof payload.html === "string") {
193
+ return payload.html;
194
+ }
195
+ return "";
196
+ };
197
+ const apply = (id, pendingEntry) => {
198
+ const payload = unwrapPendingPayload(pendingEntry);
199
+ if (!canApplyImmediately()) {
200
+ pending[id] = payload;
201
+ return;
202
+ }
203
+ const consumer = consumers[id];
204
+ if (typeof consumer !== "function") {
205
+ applyToDom(id, payload, pendingEntry);
206
+ return;
207
+ }
208
+ const handled = consumer(payload);
209
+ if (handled !== false) {
210
+ delete pending[id];
211
+ return;
212
+ }
213
+ applyToDom(id, payload, pendingEntry);
214
+ };
215
+ const applyToDom = (id, payload, pendingEntry) => {
216
+ if (isAngularDeferPayload(payload)) {
217
+ pending[id] = payload;
218
+ return;
219
+ }
220
+ const node = document.getElementById(id);
221
+ if (!node) {
222
+ pending[id] = payload;
223
+ return;
224
+ }
225
+ const html = resolveHtml(payload);
226
+ if (isVueSuspensePayload(payload) && isPatchedPendingEntry(pendingEntry)) {
227
+ return;
228
+ }
229
+ node.innerHTML = html;
230
+ node.setAttribute("data-absolute-slot-state", "resolved");
231
+ window.dispatchEvent(new CustomEvent(SLOT_PATCH_EVENT, {
232
+ detail: { html, id, payload }
233
+ }));
234
+ if (isVueSuspensePayload(payload)) {
235
+ pending[id] = { domPatched: true, payload };
236
+ return;
237
+ }
238
+ delete pending[id];
239
+ };
240
+ const flush = () => {
241
+ for (const id in pending) {
242
+ if (!Object.prototype.hasOwnProperty.call(pending, id))
243
+ continue;
244
+ apply(id, pending[id] ?? "");
245
+ }
246
+ };
247
+ absoluteWindow.__ABS_SLOT_FLUSH__ = flush;
248
+ absoluteWindow.__ABS_SLOT_ENQUEUE__ = (id, payload) => {
249
+ apply(id, payload);
250
+ };
251
+ if (typeof MutationObserver === "function") {
252
+ const observer = new MutationObserver(flush);
253
+ const root = document.documentElement ?? document.body ?? document;
254
+ observer.observe(root, { childList: true, subtree: true });
255
+ }
256
+ if (document.readyState === "loading") {
257
+ document.addEventListener("DOMContentLoaded", flush, { once: true });
258
+ }
259
+ flush();
260
+ }, stripFunctionWrapper = (value) => {
261
+ const start = value.indexOf("{");
262
+ const end = value.lastIndexOf("}");
263
+ if (start < 0 || end <= start)
264
+ return "";
265
+ return value.slice(start + 1, end);
266
+ }, getStreamSwapRuntimeScript = () => `(function(){${stripFunctionWrapper(streamSwapRuntime.toString())}})();`;
267
+
268
+ // src/utils/escapeScriptContent.ts
269
+ var ESCAPE_LOOKUP, ESCAPE_REGEX, escapeScriptContent = (content) => content.replace(ESCAPE_REGEX, (char) => {
270
+ const escaped = ESCAPE_LOOKUP[char];
271
+ return escaped !== undefined ? escaped : char;
272
+ });
273
+ var init_escapeScriptContent = __esm(() => {
274
+ ESCAPE_LOOKUP = {
275
+ "\u2028": "\\u2028",
276
+ "\u2029": "\\u2029",
277
+ "<": "\\u003C"
278
+ };
279
+ ESCAPE_REGEX = /[<\u2028\u2029]/g;
280
+ });
281
+
282
+ // src/utils/streamingSlots.ts
283
+ var SLOT_ID_PREFIX = "abs-slot-", CLOSING_BODY_TAG = "</body>", CLOSING_HEAD_TAG2 = "</head>", CLOSING_BODY_TAG_LENGTH, CLOSING_HEAD_TAG_LENGTH, CLOSING_PAGE_TAG_REGEX, STREAMING_RUNTIME_GLOBAL = "__ABS_SLOT_ENQUEUE__", STREAMING_PENDING_GLOBAL = "__ABS_SLOT_PENDING__", STREAM_TAIL_LOOKBEHIND = 128, STREAMING_SLOT_TIMEOUT_MS = 5000, STREAMING_SLOT_MAX_PER_RESPONSE = 128, STREAMING_SLOT_MAX_HTML_BYTES = 64000, createSlotPatchStatement = (id, payload) => `(window.${STREAMING_RUNTIME_GLOBAL}||function(i,p){window.${STREAMING_PENDING_GLOBAL}=window.${STREAMING_PENDING_GLOBAL}||{};window.${STREAMING_PENDING_GLOBAL}[i]=p;})(${JSON.stringify(id)},${JSON.stringify(payload)});`, createNonceAttr = (nonce) => nonce ? ` nonce="${nonce}"` : "", createStreamingSlotId = () => `${SLOT_ID_PREFIX}${Math.random().toString(BASE_36_RADIX).slice(2, RANDOM_ID_END_INDEX)}`, getStreamingSlotsRuntimeScript = () => getStreamSwapRuntimeScript(), injectHtmlIntoBody = (html, injection) => {
284
+ const closingBodyIndex = html.indexOf(CLOSING_BODY_TAG);
285
+ if (closingBodyIndex >= 0) {
286
+ return `${html.slice(0, closingBodyIndex)}${injection}${html.slice(closingBodyIndex)}`;
287
+ }
288
+ return `${html}${injection}`;
289
+ }, injectHtmlIntoHead = (html, injection) => {
290
+ const closingHeadIndex = html.indexOf(CLOSING_HEAD_TAG2);
291
+ if (closingHeadIndex >= 0) {
292
+ return `${html.slice(0, closingHeadIndex)}${injection}${html.slice(closingHeadIndex)}`;
293
+ }
294
+ return `${html}${injection}`;
295
+ }, renderStreamingSlotPatchTag = (id, payload, nonce) => `<script${createNonceAttr(nonce)}>${escapeScriptContent(createSlotPatchStatement(id, payload))}</script>`, renderStreamingSlotPlaceholder = (id, fallbackHtml = "") => `<div id="${id}" data-absolute-slot="true" data-absolute-slot-state="fallback">${fallbackHtml}</div>`, renderStreamingSlotsRuntimeTag = (nonce, runtimePreludeScript) => {
296
+ const runtimeBody = [
297
+ runtimePreludeScript?.trim() ? runtimePreludeScript.trim() : "",
298
+ getStreamingSlotsRuntimeScript()
299
+ ].filter(Boolean).join(";");
300
+ return `<script${createNonceAttr(nonce)}>${escapeScriptContent(runtimeBody)}</script>`;
301
+ }, toUint8 = (value, encoder) => encoder.encode(value), isRecord = (value) => Boolean(value) && typeof value === "object", isSafeHtmlLike = (value) => isRecord(value) && typeof value.changingThisBreaksApplicationSecurity === "string", normalizeSafeHtml = (value) => {
302
+ if (isSafeHtmlLike(value)) {
303
+ return value.changingThisBreaksApplicationSecurity;
304
+ }
305
+ return value;
306
+ }, currentStreamingSlotPolicy, clonePolicy = (policy) => ({
307
+ ...policy
308
+ }), normalizeSlotBytes = (value, fallback) => {
309
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
310
+ return Math.floor(value);
311
+ }
312
+ return fallback;
313
+ }, normalizeSlotText = (value, fallback) => {
314
+ const normalizedValue = normalizeSafeHtml(value);
315
+ return typeof normalizedValue === "string" ? normalizedValue : fallback;
316
+ }, normalizeSlotError = (value, fallback = undefined) => {
317
+ const safeValue = normalizeSafeHtml(value);
318
+ if (typeof safeValue === "string")
319
+ return safeValue;
320
+ return fallback;
321
+ }, hasPolicyValue = (policy, key) => Object.prototype.hasOwnProperty.call(policy, key), applyStreamingSlotPolicyOverrides = (base, overridePolicy = {}) => ({
322
+ errorHtml: hasPolicyValue(overridePolicy, "errorHtml") ? normalizeSlotError(overridePolicy.errorHtml) : base.errorHtml,
323
+ fallbackHtml: hasPolicyValue(overridePolicy, "fallbackHtml") ? normalizeSlotText(overridePolicy.fallbackHtml, "") : base.fallbackHtml,
324
+ maxSlotHtmlSizeBytes: hasPolicyValue(overridePolicy, "maxSlotHtmlSizeBytes") ? normalizeSlotBytes(overridePolicy.maxSlotHtmlSizeBytes, base.maxSlotHtmlSizeBytes) : base.maxSlotHtmlSizeBytes,
325
+ maxSlotsPerResponse: hasPolicyValue(overridePolicy, "maxSlotsPerResponse") ? normalizeSlotBytes(overridePolicy.maxSlotsPerResponse, base.maxSlotsPerResponse) : base.maxSlotsPerResponse,
326
+ onError: hasPolicyValue(overridePolicy, "onError") ? overridePolicy.onError : base.onError,
327
+ onSlotMetric: hasPolicyValue(overridePolicy, "onSlotMetric") ? overridePolicy.onSlotMetric : base.onSlotMetric,
328
+ timeoutMs: hasPolicyValue(overridePolicy, "timeoutMs") ? normalizeSlotBytes(overridePolicy.timeoutMs, base.timeoutMs) : base.timeoutMs
329
+ }), createCombinedSlotErrorHandler = (policyOnError, enhancerOnError) => {
330
+ if (!policyOnError && !enhancerOnError)
331
+ return;
332
+ return (error, slot) => {
333
+ policyOnError?.(error, slot);
334
+ enhancerOnError?.(error, slot);
335
+ };
336
+ }, createCombinedSlotMetricHandler = (policyOnSlotMetric, callOnSlotMetric) => {
337
+ if (!policyOnSlotMetric && !callOnSlotMetric)
338
+ return;
339
+ return (metric) => {
340
+ policyOnSlotMetric?.(metric);
341
+ callOnSlotMetric?.(metric);
342
+ };
343
+ }, resolveStreamingSlotPolicy = (overridePolicy = {}) => {
344
+ const base = getStreamingSlotPolicy();
345
+ return applyStreamingSlotPolicyOverrides(base, overridePolicy);
346
+ }, getStreamingSlotPolicy = () => clonePolicy(currentStreamingSlotPolicy), setStreamingSlotPolicy = (policy = {}) => {
347
+ const base = getStreamingSlotPolicy();
348
+ currentStreamingSlotPolicy = applyStreamingSlotPolicyOverrides(base, policy);
349
+ }, withStreamingSlotPolicy = async (policy, callback) => {
350
+ const previous = getStreamingSlotPolicy();
351
+ setStreamingSlotPolicy(policy);
352
+ try {
353
+ return await callback();
354
+ } finally {
355
+ currentStreamingSlotPolicy = previous;
356
+ }
357
+ }, emitSlotMetric = (metric, onSlotMetric) => {
358
+ onSlotMetric?.(metric);
359
+ }, createTimeoutError = (slot, timeoutMs) => {
360
+ const error = Object.assign(new Error(`Streaming slot "${slot.id}" timed out after ${timeoutMs}ms`), { __absTimeout: true });
361
+ return error;
362
+ }, isSlotPatchPayloadObject = (value) => isRecord(value) && ("html" in value), isTimeoutError = (error) => isRecord(error) && error.__absTimeout === true, toStreamingSlot = (slot, policy) => ({
363
+ errorHtml: slot.errorHtml === undefined ? policy.errorHtml : slot.errorHtml,
364
+ fallbackHtml: normalizeSlotText(slot.fallbackHtml, policy.fallbackHtml),
365
+ id: slot.id ?? createStreamingSlotId(),
366
+ resolve: slot.resolve,
367
+ timeoutMs: normalizeSlotBytes(slot.timeoutMs, policy.timeoutMs)
368
+ }), prepareSlots = ({
369
+ policy,
370
+ slots,
371
+ onError,
372
+ onSlotMetric
373
+ }) => {
374
+ const preparedSlots = slots.map((slot) => toStreamingSlot(slot, policy));
375
+ const emitPreparedSlotMetric = (slot) => {
376
+ emitSlotMetric({
377
+ slotId: slot.id,
378
+ type: "prepared"
379
+ }, onSlotMetric);
380
+ };
381
+ const dropPreparedSlot = (slot, reason) => {
382
+ onError?.(new Error(reason), slot);
383
+ emitSlotMetric({
384
+ reason,
385
+ slotId: slot.id,
386
+ type: "dropped"
387
+ }, onSlotMetric);
388
+ };
389
+ const { maxSlotsPerResponse } = policy;
390
+ if (maxSlotsPerResponse === 0) {
391
+ preparedSlots.forEach((slot) => dropPreparedSlot(slot, "maxSlotsPerResponse is 0"));
392
+ return [];
393
+ }
394
+ if (preparedSlots.length <= maxSlotsPerResponse) {
395
+ preparedSlots.forEach(emitPreparedSlotMetric);
396
+ return preparedSlots;
397
+ }
398
+ const keptSlots = preparedSlots.slice(0, maxSlotsPerResponse);
399
+ const droppedSlots = preparedSlots.slice(maxSlotsPerResponse);
400
+ droppedSlots.forEach((slot) => {
401
+ dropPreparedSlot(slot, `Streaming slot "${slot.id}" dropped because ${maxSlotsPerResponse} slots is the configured maximum`);
402
+ });
403
+ keptSlots.forEach(emitPreparedSlotMetric);
404
+ return keptSlots;
405
+ }, htmlByteLength = (value, encoder) => encoder.encode(value).length, normalizeSlotPatchPayload = (value) => {
406
+ const safeValue = normalizeSafeHtml(value);
407
+ if (isSlotPatchPayloadObject(safeValue) && typeof safeValue.html === "string") {
408
+ return {
409
+ ...safeValue,
410
+ html: normalizeSlotText(safeValue.html, "")
411
+ };
412
+ }
413
+ return typeof safeValue === "string" ? safeValue : `${safeValue}`;
414
+ }, getPayloadHtml = (payload) => typeof payload === "string" ? payload : payload.html, enqueueEncodedText = (controller, encoder, value) => {
415
+ if (value.length === 0) {
416
+ return;
417
+ }
418
+ controller.enqueue(encoder.encode(value));
419
+ }, readStreamingRuntimeChunk = async (reader) => {
420
+ const { done, value } = await reader.read();
421
+ if (done || !value) {
422
+ return { done, value: undefined };
423
+ }
424
+ return { done, value };
425
+ }, applyBaseWinnerState = (state, winner, handleResolved) => {
426
+ if (!state.handled && winner.kind === "slot") {
427
+ handleResolved(winner);
428
+ }
429
+ return state;
430
+ }, resolveOversizedSlotPayload = (input) => {
431
+ const {
432
+ encoder,
433
+ html,
434
+ maxSlotHtmlSizeBytes,
435
+ onError,
436
+ onSlotMetric,
437
+ slot,
438
+ start
439
+ } = input;
440
+ const bytes = htmlByteLength(html, encoder);
441
+ if (bytes <= maxSlotHtmlSizeBytes) {
442
+ return null;
443
+ }
444
+ const error = new Error(`Streaming slot "${slot.id}" exceeded max payload size of ${maxSlotHtmlSizeBytes} bytes`);
445
+ const durationMs = Date.now() - start;
446
+ onError?.(error, slot);
447
+ emitSlotMetric({
448
+ bytes,
449
+ durationMs,
450
+ error,
451
+ slotId: slot.id,
452
+ type: "size_exceeded"
453
+ }, onSlotMetric);
454
+ const fallbackHtml = normalizeSlotError(slot.errorHtml, undefined);
455
+ return {
456
+ bytes: fallbackHtml === undefined ? 0 : htmlByteLength(fallbackHtml, encoder),
457
+ durationMs,
458
+ id: slot.id,
459
+ payload: fallbackHtml === undefined ? null : fallbackHtml
460
+ };
461
+ }, raceWithTimeout = (promise, slot) => {
462
+ const { timeoutMs } = slot;
463
+ if (typeof timeoutMs !== "number" || timeoutMs <= 0) {
464
+ return promise;
465
+ }
466
+ const { promise: timeoutPromise, reject } = Promise.withResolvers();
467
+ setTimeout(() => {
468
+ reject(createTimeoutError(slot, timeoutMs));
469
+ }, timeoutMs);
470
+ return Promise.race([promise, timeoutPromise]);
471
+ }, resolveSlot = async (slot, onError, policy, onSlotMetric) => {
472
+ const safePolicy = policy ?? getStreamingSlotPolicy();
473
+ const encoder = new TextEncoder;
474
+ const start = Date.now();
475
+ try {
476
+ const maybeAsyncValue = Promise.resolve(slot.resolve());
477
+ const resolved = await raceWithTimeout(maybeAsyncValue, slot);
478
+ const payload = normalizeSlotPatchPayload(resolved);
479
+ const html = getPayloadHtml(payload);
480
+ const oversizedResult = safePolicy.maxSlotHtmlSizeBytes > 0 ? resolveOversizedSlotPayload({
481
+ encoder,
482
+ html,
483
+ maxSlotHtmlSizeBytes: safePolicy.maxSlotHtmlSizeBytes,
484
+ onError,
485
+ onSlotMetric,
486
+ slot,
487
+ start
488
+ }) : null;
489
+ if (oversizedResult) {
490
+ return oversizedResult;
491
+ }
492
+ const durationMs = Date.now() - start;
493
+ const bytes = htmlByteLength(html, encoder);
494
+ emitSlotMetric({
495
+ bytes,
496
+ durationMs,
497
+ slotId: slot.id,
498
+ type: "resolved"
499
+ }, onSlotMetric);
500
+ return {
501
+ bytes,
502
+ durationMs,
503
+ id: slot.id,
504
+ payload
505
+ };
506
+ } catch (error) {
507
+ const durationMs = Date.now() - start;
508
+ onError?.(error, slot);
509
+ emitSlotMetric({
510
+ durationMs,
511
+ error,
512
+ slotId: slot.id,
513
+ type: isTimeoutError(error) ? "timeout" : "error"
514
+ }, onSlotMetric);
515
+ const html = normalizeSlotError(slot.errorHtml, undefined);
516
+ if (html) {
517
+ return {
518
+ bytes: htmlByteLength(html, encoder),
519
+ durationMs,
520
+ id: slot.id,
521
+ payload: html
522
+ };
523
+ }
524
+ return {
525
+ bytes: 0,
526
+ durationMs,
527
+ id: slot.id,
528
+ payload: null
529
+ };
530
+ }
531
+ }, nextResolvedSlot = async (pending) => {
532
+ const wrapped = pending.map((promise) => promise.then((result) => ({
533
+ original: promise,
534
+ result
535
+ })));
536
+ return Promise.race(wrapped);
537
+ }, streamChunkToString2 = (value, decoder) => typeof value === "string" ? value : decoder.decode(value, { stream: true }), appendStreamingSlotPatchesToStream = (stream, slots = [], {
538
+ injectRuntime = true,
539
+ nonce,
540
+ onError,
541
+ onSlotMetric,
542
+ policy,
543
+ runtimePreludeScript,
544
+ runtimePlacement = "head"
545
+ } = {}) => {
546
+ const resolvedPolicy = resolveStreamingSlotPolicy(policy);
547
+ const combinedOnError = createCombinedSlotErrorHandler(resolvedPolicy.onError, onError);
548
+ const combinedOnSlotMetric = createCombinedSlotMetricHandler(resolvedPolicy.onSlotMetric, onSlotMetric);
549
+ const effectivePolicy = {
550
+ ...resolvedPolicy,
551
+ onSlotMetric: combinedOnSlotMetric
552
+ };
553
+ const preparedSlots = prepareSlots({
554
+ onError: combinedOnError,
555
+ onSlotMetric: combinedOnSlotMetric,
556
+ policy: effectivePolicy,
557
+ slots
558
+ });
559
+ if (preparedSlots.length === 0)
560
+ return stream;
561
+ const source = injectRuntime ? injectStreamingRuntimeIntoStream(stream, nonce, runtimePlacement, runtimePreludeScript) : stream;
562
+ const encoder = new TextEncoder;
563
+ const decoder = new TextDecoder;
564
+ const reader = source.getReader();
565
+ const pending = preparedSlots.map((slot) => resolveSlot(slot, combinedOnError, effectivePolicy, combinedOnSlotMetric));
566
+ const createRaceCandidates = (baseDone, baseRead) => {
567
+ const racers = [];
568
+ if (!baseDone) {
569
+ racers.push(baseRead.then(({ done, value }) => ({
570
+ done,
571
+ kind: "base",
572
+ value
573
+ })));
574
+ }
575
+ if (pending.length > 0) {
576
+ racers.push(nextResolvedSlot(pending).then((resolved) => ({
577
+ kind: "slot",
578
+ ...resolved
579
+ })));
580
+ }
581
+ return racers;
582
+ };
583
+ const flushTailLookbehind = (controller, tail) => {
584
+ if (tail.length <= STREAM_TAIL_LOOKBEHIND) {
585
+ return tail;
586
+ }
587
+ const content = tail.slice(0, tail.length - STREAM_TAIL_LOOKBEHIND);
588
+ controller.enqueue(encoder.encode(content));
589
+ return tail.slice(-STREAM_TAIL_LOOKBEHIND);
590
+ };
591
+ const finalizeCompletedBaseWinner = (controller, decodedTail, baseRead) => {
592
+ const footerStart = decodedTail.search(CLOSING_PAGE_TAG_REGEX);
593
+ if (footerStart < 0) {
594
+ enqueueEncodedText(controller, encoder, decodedTail);
595
+ return {
596
+ baseDone: true,
597
+ baseRead,
598
+ footer: "",
599
+ handled: true,
600
+ tail: ""
601
+ };
602
+ }
603
+ const content = decodedTail.slice(0, footerStart);
604
+ const nextFooter = decodedTail.slice(footerStart);
605
+ enqueueEncodedText(controller, encoder, content);
606
+ return {
607
+ baseDone: true,
608
+ baseRead,
609
+ footer: nextFooter,
610
+ handled: true,
611
+ tail: ""
612
+ };
613
+ };
614
+ const handleBaseWinner = (controller, winner, baseRead, tail, footer) => {
615
+ if (winner.kind !== "base") {
616
+ return { baseDone: false, baseRead, footer, handled: false, tail };
617
+ }
618
+ if (winner.done) {
619
+ return finalizeCompletedBaseWinner(controller, tail + decoder.decode(), baseRead);
620
+ }
621
+ if (!winner.value) {
622
+ return { baseDone: false, baseRead, footer, handled: true, tail };
623
+ }
624
+ const nextTail = flushTailLookbehind(controller, tail + streamChunkToString2(winner.value, decoder));
625
+ return {
626
+ baseDone: false,
627
+ baseRead: reader.read(),
628
+ footer,
629
+ handled: true,
630
+ tail: nextTail
631
+ };
632
+ };
633
+ const handleResolvedSlot = (controller, winner) => {
634
+ const index = pending.indexOf(winner.original);
635
+ if (index >= 0)
636
+ pending.splice(index, 1);
637
+ if (winner.result.payload === null) {
638
+ return;
639
+ }
640
+ emitSlotMetric({
641
+ bytes: winner.result.bytes,
642
+ durationMs: winner.result.durationMs,
643
+ slotId: winner.result.id,
644
+ type: "patched"
645
+ }, combinedOnSlotMetric);
646
+ controller.enqueue(encoder.encode(renderStreamingSlotPatchTag(winner.result.id, winner.result.payload, nonce)));
647
+ };
648
+ const runPatchedStreamLoop = async (controller) => {
649
+ let baseDone = false;
650
+ let baseRead = reader.read();
651
+ let tail = "";
652
+ let footer = "";
653
+ const readNextRaceWinner = async () => {
654
+ const racers = createRaceCandidates(baseDone, baseRead);
655
+ if (racers.length === 0) {
656
+ return footer;
657
+ }
658
+ const winner = await Promise.race(racers);
659
+ const baseWinnerState = applyBaseWinnerState(handleBaseWinner(controller, winner, baseRead, tail, footer), winner, (slotWinner) => {
660
+ handleResolvedSlot(controller, slotWinner);
661
+ });
662
+ ({ baseDone, baseRead, footer, tail } = baseWinnerState);
663
+ if (baseDone && pending.length === 0) {
664
+ return footer;
665
+ }
666
+ return readNextRaceWinner();
667
+ };
668
+ return readNextRaceWinner();
669
+ };
670
+ return new ReadableStream({
671
+ async start(controller) {
672
+ try {
673
+ const footer = await runPatchedStreamLoop(controller);
674
+ enqueueEncodedText(controller, encoder, footer);
675
+ controller.close();
676
+ } catch (error) {
677
+ controller.error(error);
678
+ }
679
+ }
680
+ });
681
+ }, injectStreamingRuntimeIntoStream = (stream, nonce, runtimePlacement = "head", runtimePreludeScript) => {
682
+ const runtimeTag = renderStreamingSlotsRuntimeTag(nonce, runtimePreludeScript);
683
+ const encoder = new TextEncoder;
684
+ const decoder = new TextDecoder;
685
+ const closingTag = runtimePlacement === "body" ? CLOSING_BODY_TAG : CLOSING_HEAD_TAG2;
686
+ const lookbehind = (runtimePlacement === "body" ? CLOSING_BODY_TAG_LENGTH : CLOSING_HEAD_TAG_LENGTH) - 1;
687
+ const flushRuntimeLookbehind = (controller, pending) => {
688
+ if (pending.length <= lookbehind) {
689
+ return pending;
690
+ }
691
+ const safeText = pending.slice(0, pending.length - lookbehind);
692
+ controller.enqueue(encoder.encode(safeText));
693
+ return pending.slice(-lookbehind);
694
+ };
695
+ const injectRuntimeIntoPending = (pending) => runtimePlacement === "body" ? injectHtmlIntoBody(pending, runtimeTag) : injectHtmlIntoHead(pending, runtimeTag);
696
+ const processRuntimePending = (controller, pending, injected) => {
697
+ if (injected) {
698
+ controller.enqueue(encoder.encode(pending));
699
+ return { injected, pending: "" };
700
+ }
701
+ const closingTagIndex = pending.indexOf(closingTag);
702
+ if (closingTagIndex >= 0) {
703
+ const withRuntime = `${pending.slice(0, closingTagIndex)}${runtimeTag}${pending.slice(closingTagIndex)}`;
704
+ controller.enqueue(encoder.encode(withRuntime));
705
+ return { injected: true, pending: "" };
706
+ }
707
+ return {
708
+ injected,
709
+ pending: flushRuntimeLookbehind(controller, pending)
710
+ };
711
+ };
712
+ return new ReadableStream({
713
+ async start(controller) {
714
+ const reader = stream.getReader();
715
+ let injected = false;
716
+ let pending = "";
717
+ const enqueuePending = () => enqueueEncodedText(controller, encoder, pending);
718
+ const consumeRuntimeChunk = async () => {
719
+ const { done, value } = await readStreamingRuntimeChunk(reader);
720
+ if (done || !value) {
721
+ return done;
722
+ }
723
+ pending += streamChunkToString2(value, decoder);
724
+ ({ injected, pending } = processRuntimePending(controller, pending, injected));
725
+ return false;
726
+ };
727
+ const runRuntimeInjectionLoop = async () => {
728
+ const done = await consumeRuntimeChunk();
729
+ if (done) {
730
+ return;
731
+ }
732
+ await runRuntimeInjectionLoop();
733
+ };
734
+ try {
735
+ await runRuntimeInjectionLoop();
736
+ pending += decoder.decode();
737
+ pending = injected ? pending : injectRuntimeIntoPending(pending);
738
+ enqueuePending();
739
+ controller.close();
740
+ } catch (error) {
741
+ controller.error(error);
742
+ }
743
+ }
744
+ });
745
+ }, streamOutOfOrderSlots = ({
746
+ footerHtml = "",
747
+ headerHtml = "",
748
+ nonce,
749
+ policy,
750
+ onSlotMetric,
751
+ onError,
752
+ slots
753
+ }) => {
754
+ const resolvedPolicy = resolveStreamingSlotPolicy(policy);
755
+ const combinedOnError = createCombinedSlotErrorHandler(resolvedPolicy.onError, onError);
756
+ const combinedOnSlotMetric = createCombinedSlotMetricHandler(resolvedPolicy.onSlotMetric, onSlotMetric);
757
+ const effectivePolicy = {
758
+ ...resolvedPolicy,
759
+ onSlotMetric: combinedOnSlotMetric
760
+ };
761
+ const preparedSlots = prepareSlots({
762
+ onError: combinedOnError,
763
+ onSlotMetric: combinedOnSlotMetric,
764
+ policy: effectivePolicy,
765
+ slots
766
+ });
767
+ const encoder = new TextEncoder;
768
+ const createPendingSlots = (controller) => preparedSlots.map((slot) => {
769
+ const fallback = renderStreamingSlotPlaceholder(slot.id, normalizeSlotText(slot.fallbackHtml, ""));
770
+ controller.enqueue(toUint8(fallback, encoder));
771
+ return resolveSlot(slot, combinedOnError, effectivePolicy, combinedOnSlotMetric);
772
+ });
773
+ const handleResolvedPreparedSlot = async (controller, pending) => {
774
+ const { original, result } = await nextResolvedSlot(pending);
775
+ const index = pending.indexOf(original);
776
+ if (index >= 0)
777
+ pending.splice(index, 1);
778
+ if (result.payload === null) {
779
+ return;
780
+ }
781
+ emitSlotMetric({
782
+ bytes: result.bytes,
783
+ durationMs: result.durationMs,
784
+ slotId: result.id,
785
+ type: "patched"
786
+ }, combinedOnSlotMetric);
787
+ controller.enqueue(toUint8(renderStreamingSlotPatchTag(result.id, result.payload, nonce), encoder));
788
+ };
789
+ const streamPreparedSlots = async (controller) => {
790
+ const pending = createPendingSlots(controller);
791
+ const streamNextPreparedSlot = async () => {
792
+ if (pending.length === 0) {
793
+ return;
794
+ }
795
+ await handleResolvedPreparedSlot(controller, pending);
796
+ await streamNextPreparedSlot();
797
+ };
798
+ await streamNextPreparedSlot();
799
+ };
800
+ const resolveHeaderHtml = () => {
801
+ const needsRuntimeTag = preparedSlots.length > 0 && !headerHtml.includes(STREAMING_RUNTIME_GLOBAL);
802
+ if (!needsRuntimeTag) {
803
+ return headerHtml;
804
+ }
805
+ return injectHtmlIntoHead(headerHtml, renderStreamingSlotsRuntimeTag(nonce));
806
+ };
807
+ return new ReadableStream({
808
+ async start(controller) {
809
+ try {
810
+ const header = resolveHeaderHtml();
811
+ controller.enqueue(toUint8(header, encoder));
812
+ await streamPreparedSlots(controller);
813
+ enqueueEncodedText(controller, encoder, footerHtml);
814
+ controller.close();
815
+ } catch (error) {
816
+ controller.error(error);
817
+ }
818
+ }
819
+ });
820
+ };
821
+ var init_streamingSlots = __esm(() => {
822
+ init_constants();
823
+ init_escapeScriptContent();
824
+ CLOSING_BODY_TAG_LENGTH = CLOSING_BODY_TAG.length;
825
+ CLOSING_HEAD_TAG_LENGTH = CLOSING_HEAD_TAG2.length;
826
+ CLOSING_PAGE_TAG_REGEX = /<\/body>\s*<\/html>\s*$/i;
827
+ currentStreamingSlotPolicy = {
828
+ errorHtml: undefined,
829
+ fallbackHtml: "",
830
+ maxSlotHtmlSizeBytes: STREAMING_SLOT_MAX_HTML_BYTES,
831
+ maxSlotsPerResponse: STREAMING_SLOT_MAX_PER_RESPONSE,
832
+ timeoutMs: STREAMING_SLOT_TIMEOUT_MS
833
+ };
834
+ });
835
+
836
+ // src/utils/getDurationString.ts
837
+ var getDurationString = (duration) => {
838
+ let durationString;
839
+ if (duration < MILLISECONDS_IN_A_SECOND) {
840
+ durationString = `${duration.toFixed(TIME_PRECISION)}ms`;
841
+ } else if (duration < MILLISECONDS_IN_A_MINUTE) {
842
+ durationString = `${(duration / MILLISECONDS_IN_A_SECOND).toFixed(TIME_PRECISION)}s`;
843
+ } else {
844
+ const totalSeconds = Math.round(duration / MILLISECONDS_IN_A_SECOND);
845
+ const minutes = Math.floor(totalSeconds / 60);
846
+ const seconds = totalSeconds % 60;
847
+ durationString = seconds === 0 ? `${minutes}m` : `${minutes}m ${seconds}s`;
848
+ }
849
+ return durationString;
850
+ };
851
+ var init_getDurationString = __esm(() => {
852
+ init_constants();
853
+ });
854
+
855
+ // src/utils/startupBanner.ts
856
+ var colors, MONTHS, formatTimestamp = () => {
857
+ const now = new Date;
858
+ const month = MONTHS[now.getMonth()];
859
+ const day = now.getDate().toString().padStart(2, "0");
860
+ let hours = now.getHours();
861
+ const minutes = now.getMinutes().toString().padStart(2, "0");
862
+ const seconds = now.getSeconds().toString().padStart(2, "0");
863
+ const ampm = hours >= HOURS_IN_HALF_DAY ? "PM" : "AM";
864
+ hours = hours % HOURS_IN_HALF_DAY || HOURS_IN_HALF_DAY;
865
+ return `${month} ${day} ${hours}:${minutes}:${seconds} ${ampm}`;
866
+ }, startupBanner = (options) => {
867
+ const {
868
+ version,
869
+ readyDuration,
870
+ buildDuration,
871
+ port,
872
+ host,
873
+ networkUrl,
874
+ protocol = "http"
875
+ } = options;
876
+ const name = `${colors.cyan}${colors.bold}ABSOLUTEJS${colors.reset}`;
877
+ const ver = `${colors.dim}v${version}${colors.reset}`;
878
+ const time = `${colors.dim}ready in${colors.reset} ${colors.bold}${getDurationString(readyDuration)}${colors.reset}`;
879
+ const build = typeof buildDuration === "number" && Number.isFinite(buildDuration) ? ` ${colors.dim}(build ${getDurationString(buildDuration)})${colors.reset}` : "";
880
+ console.log("");
881
+ console.log(` ${name} ${ver} ${time}${build}`);
882
+ console.log("");
883
+ console.log(` ${colors.green}\u279C${colors.reset} ${colors.bold}Local:${colors.reset} ${protocol}://${host === "0.0.0.0" ? "localhost" : host}:${port}/`);
884
+ if (networkUrl) {
885
+ console.log(` ${colors.green}\u279C${colors.reset} ${colors.bold}Network:${colors.reset} ${networkUrl}`);
886
+ }
887
+ console.log("");
888
+ };
889
+ var init_startupBanner = __esm(() => {
890
+ init_constants();
891
+ init_getDurationString();
892
+ colors = {
893
+ bold: "\x1B[1m",
894
+ cyan: "\x1B[36m",
895
+ dim: "\x1B[2m",
896
+ green: "\x1B[32m",
897
+ reset: "\x1B[0m"
898
+ };
899
+ MONTHS = [
900
+ "Jan",
901
+ "Feb",
902
+ "Mar",
903
+ "Apr",
904
+ "May",
905
+ "Jun",
906
+ "Jul",
907
+ "Aug",
908
+ "Sep",
909
+ "Oct",
910
+ "Nov",
911
+ "Dec"
912
+ ];
913
+ });
914
+
915
+ // src/utils/logger.ts
916
+ var colors2, frameworkColors, formatPath = (filePath) => {
917
+ const cwd = process.cwd();
918
+ let relative = filePath.startsWith(cwd) ? filePath.slice(cwd.length + 1) : filePath;
919
+ relative = relative.replace(/\\/g, "/");
920
+ if (!relative.startsWith("/")) {
921
+ relative = `/${relative}`;
922
+ }
923
+ return relative;
924
+ }, getFrameworkColor = (framework) => frameworkColors[framework] || colors2.white, log = (action, options) => {
925
+ const timestamp = `${colors2.dim}${formatTimestamp()}${colors2.reset}`;
926
+ const tag = `${colors2.cyan}[hmr]${colors2.reset}`;
927
+ let message = action;
928
+ if (options?.path) {
929
+ const pathColor = options.framework ? getFrameworkColor(options.framework) : colors2.white;
930
+ message += ` ${pathColor}${formatPath(options.path)}${colors2.reset}`;
931
+ }
932
+ if (options?.duration !== undefined) {
933
+ message += ` ${colors2.dim}(${options.duration}ms)${colors2.reset}`;
934
+ }
935
+ console.log(`${timestamp} ${tag} ${message}`);
936
+ }, logCssUpdate = (path, framework, duration) => {
937
+ log("css update", { duration, framework: framework ?? "css", path });
938
+ }, logError = (message, error) => {
939
+ const timestamp = `${colors2.dim}${formatTimestamp()}${colors2.reset}`;
940
+ const tag = `${colors2.red}[hmr]${colors2.reset}`;
941
+ const errorMsg = error instanceof Error ? error.message : error;
942
+ const fullMessage = `${colors2.red}error${colors2.reset} ${message}${errorMsg ? `: ${errorMsg}` : ""}`;
943
+ console.error(`${timestamp} ${tag} ${fullMessage}`);
944
+ }, logHmrUpdate = (path, framework, duration) => {
945
+ log("hmr update", { duration, framework, path });
946
+ }, logScriptUpdate = (path, framework, duration) => {
947
+ log("script update", { duration, framework, path });
948
+ }, logServerReload = () => {
949
+ log(`${colors2.cyan}server module reloaded${colors2.reset}`);
950
+ }, logWarn = (message) => {
951
+ const timestamp = `${colors2.dim}${formatTimestamp()}${colors2.reset}`;
952
+ const tag = `${colors2.yellow}[hmr]${colors2.reset}`;
953
+ console.log(`${timestamp} ${tag} ${colors2.yellow}warning ${message}${colors2.reset}`);
954
+ };
955
+ var init_logger = __esm(() => {
956
+ init_startupBanner();
957
+ colors2 = {
958
+ blue: "\x1B[34m",
959
+ bold: "\x1B[1m",
960
+ cyan: "\x1B[36m",
961
+ dim: "\x1B[2m",
962
+ green: "\x1B[32m",
963
+ magenta: "\x1B[35m",
964
+ red: "\x1B[31m",
965
+ reset: "\x1B[0m",
966
+ white: "\x1B[37m",
967
+ yellow: "\x1B[33m"
968
+ };
969
+ frameworkColors = {
970
+ angular: colors2.magenta,
971
+ assets: colors2.dim,
972
+ css: colors2.cyan,
973
+ html: colors2.white,
974
+ htmx: colors2.white,
975
+ react: colors2.blue,
976
+ svelte: colors2.yellow,
977
+ vue: colors2.green
978
+ };
979
+ });
980
+
981
+ // src/core/ssrCache.ts
982
+ var dirtyFrameworks, isSsrCacheDirty = (framework) => dirtyFrameworks.has(framework), markSsrCacheDirty = (framework) => {
983
+ dirtyFrameworks.add(framework);
984
+ };
985
+ var init_ssrCache = __esm(() => {
986
+ dirtyFrameworks = new Set;
987
+ });
988
+
989
+ // src/utils/stringModifiers.ts
990
+ var normalizeSlug = (str) => str.trim().replace(/\s+/g, "-").replace(/[^A-Za-z0-9\-_]+/g, "").replace(/[-_]{2,}/g, "-"), toKebab = (str) => normalizeSlug(str).replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase(), toPascal = (str) => {
991
+ if (!str.includes("-") && !str.includes("_")) {
992
+ return str.charAt(0).toUpperCase() + str.slice(1);
993
+ }
994
+ return normalizeSlug(str).split(/[-_]/).filter(Boolean).map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1).toLowerCase()).join("");
995
+ }, toScreamingSnake = (str) => str.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toUpperCase();
996
+
997
+ // src/core/islandManifest.ts
998
+ var toIslandFrameworkSegment = (framework) => framework[0]?.toUpperCase() + framework.slice(1), collectFrameworkIslands = (manifest, prefix) => {
999
+ const entries = {};
1000
+ let found = false;
1001
+ for (const [key, value] of Object.entries(manifest)) {
1002
+ if (!key.startsWith(prefix))
1003
+ continue;
1004
+ const component = key.slice(prefix.length);
1005
+ if (!component)
1006
+ continue;
1007
+ entries[component] = value;
1008
+ found = true;
1009
+ }
1010
+ return found ? entries : undefined;
1011
+ }, getIslandManifestEntries = (manifest) => {
1012
+ const islands = {};
1013
+ const frameworks = ["react", "svelte", "vue", "angular"];
1014
+ for (const framework of frameworks) {
1015
+ const prefix = `Island${toIslandFrameworkSegment(framework)}`;
1016
+ const entries = collectFrameworkIslands(manifest, prefix);
1017
+ if (entries)
1018
+ islands[framework] = entries;
1019
+ }
1020
+ return islands;
1021
+ }, getIslandManifestKey = (framework, component) => `Island${toIslandFrameworkSegment(framework)}${component}`;
1022
+
1023
+ // src/core/islands.ts
1024
+ function getIslandComponent(component) {
1025
+ if (isIslandComponentDefinition(component)) {
1026
+ return component.component;
1027
+ }
1028
+ return component;
1029
+ }
1030
+ var defineIslandComponent = (component, options) => ({
1031
+ component,
1032
+ export: options.export,
1033
+ source: options.source
1034
+ }), defineIslandRegistry = (registry) => registry, isRecord2 = (value) => typeof value === "object" && value !== null, getIslandBuildReference = (component) => {
1035
+ if (!isIslandComponentDefinition(component))
1036
+ return null;
1037
+ return {
1038
+ export: component.export,
1039
+ source: component.source
1040
+ };
1041
+ }, isIslandComponentDefinition = (value) => isRecord2(value) && ("component" in value) && ("source" in value) && typeof value.source === "string", parseIslandProps = (rawProps) => {
1042
+ if (!rawProps)
1043
+ return {};
1044
+ return JSON.parse(rawProps);
1045
+ }, serializeIslandProps = (props) => JSON.stringify(props ?? {});
1046
+ var init_islands = () => {};
1047
+
1048
+ // src/core/islandMarkupAttributes.ts
1049
+ var getIslandMarkerAttributes = (props, islandId) => ({
1050
+ "data-component": props.component,
1051
+ "data-framework": props.framework,
1052
+ "data-hydrate": props.hydrate ?? "load",
1053
+ "data-island": "true",
1054
+ ...islandId ? { "data-island-id": islandId } : {},
1055
+ "data-props": serializeIslandProps(props.props)
1056
+ }), escapeHtmlAttribute = (value) => value.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"), serializeIslandAttributes = (attributes) => Object.entries(attributes).map(([key, value]) => `${key}="${escapeHtmlAttribute(value)}"`).join(" ");
1057
+ var init_islandMarkupAttributes = __esm(() => {
1058
+ init_islands();
1059
+ });
1060
+
1061
+ // src/core/currentIslandRegistry.ts
1062
+ var requireCurrentIslandRegistry = () => {
1063
+ const registry = globalThis.__absoluteIslandRegistry;
1064
+ if (!registry) {
1065
+ throw new Error("No island registry is active. Configure `islands.registry` in absolute.config.ts before rendering <Island />.");
1066
+ }
1067
+ return registry;
1068
+ }, setCurrentIslandRegistry = (registry) => {
1069
+ globalThis.__absoluteIslandRegistry = registry;
1070
+ };
1071
+
1072
+ // src/angular/resolveAngularPackage.ts
1073
+ import { existsSync, readFileSync } from "fs";
1074
+ import { join, resolve } from "path";
1075
+ var resolveAngularPackageDir = (specifier) => {
1076
+ const fromCompiledRuntime = process.env.ABSOLUTE_BUILD_DIR ? resolve(process.env.ABSOLUTE_BUILD_DIR, "node_modules", specifier) : null;
1077
+ if (fromCompiledRuntime && existsSync(fromCompiledRuntime)) {
1078
+ return fromCompiledRuntime;
1079
+ }
1080
+ const fromProject = resolve(process.cwd(), "node_modules", specifier);
1081
+ if (existsSync(fromProject)) {
1082
+ return fromProject;
1083
+ }
1084
+ return null;
1085
+ }, resolvePackageEntry = (packageDir) => {
1086
+ try {
1087
+ const pkg = JSON.parse(readFileSync(join(packageDir, "package.json"), "utf-8"));
1088
+ const rootExport = pkg.exports?.["."];
1089
+ const entry = (typeof rootExport === "string" ? rootExport : rootExport?.default) ?? pkg.module ?? pkg.main ?? "index.js";
1090
+ return join(packageDir, entry);
1091
+ } catch {
1092
+ return packageDir;
1093
+ }
1094
+ }, resolveAngularPackage = (specifier) => {
1095
+ const packageDir = resolveAngularPackageDir(specifier);
1096
+ if (packageDir)
1097
+ return resolvePackageEntry(packageDir);
1098
+ return specifier;
1099
+ }, toSafeVendorName = (specifier) => specifier.replace(/^@/, "").replace(/\//g, "_"), resolveAngularRuntimePath = (specifier) => {
1100
+ const buildDir = process.env.ABSOLUTE_BUILD_DIR;
1101
+ if (buildDir) {
1102
+ const vendorPath = join(buildDir, "angular", "vendor", "server", `${toSafeVendorName(specifier)}.js`);
1103
+ if (existsSync(vendorPath))
1104
+ return vendorPath;
1105
+ }
1106
+ return resolveAngularPackage(specifier);
1107
+ };
1108
+ var init_resolveAngularPackage = () => {};
1109
+
1110
+ // src/angular/angularPatch.ts
1111
+ var exports_angularPatch = {};
1112
+ __export(exports_angularPatch, {
1113
+ applyPatches: () => applyPatches
1114
+ });
1115
+ var ensureHead = (doc) => {
1116
+ if (!doc || doc.head || !doc.documentElement) {
1117
+ return;
1118
+ }
1119
+ const head = doc.createElement("head");
1120
+ doc.documentElement.insertBefore(head, doc.documentElement.firstChild);
1121
+ }, SSR_LAYOUT_RECT, layoutPatchApplied = false, collectPrototypeChain = (instance) => {
1122
+ const protos = [];
1123
+ let current = instance ? Object.getPrototypeOf(instance) : null;
1124
+ while (current && current !== Object.prototype) {
1125
+ protos.push(current);
1126
+ current = Object.getPrototypeOf(current);
1127
+ }
1128
+ return protos;
1129
+ }, patchElementLayout = (doc) => {
1130
+ if (layoutPatchApplied || !doc) {
1131
+ return;
1132
+ }
1133
+ let element;
1134
+ try {
1135
+ element = doc.createElement("div");
1136
+ } catch {
1137
+ return;
1138
+ }
1139
+ const protos = collectPrototypeChain(element);
1140
+ if (protos.length === 0)
1141
+ return;
1142
+ const copyLayoutRect = (rect) => ({ ...rect });
1143
+ const createLayoutRect = () => copyLayoutRect(SSR_LAYOUT_RECT);
1144
+ const getClientRects = () => [];
1145
+ const noop = () => {
1146
+ return;
1147
+ };
1148
+ const numericProps = [
1149
+ "clientWidth",
1150
+ "clientHeight",
1151
+ "clientLeft",
1152
+ "clientTop",
1153
+ "offsetWidth",
1154
+ "offsetHeight",
1155
+ "offsetLeft",
1156
+ "offsetTop",
1157
+ "scrollWidth",
1158
+ "scrollHeight",
1159
+ "scrollLeft",
1160
+ "scrollTop"
1161
+ ];
1162
+ for (const proto of protos) {
1163
+ const define = (name, value) => {
1164
+ const descriptor = Object.getOwnPropertyDescriptor(proto, name);
1165
+ if (typeof descriptor?.value === "function")
1166
+ return;
1167
+ Object.defineProperty(proto, name, {
1168
+ configurable: true,
1169
+ value,
1170
+ writable: true
1171
+ });
1172
+ };
1173
+ define("getBoundingClientRect", createLayoutRect);
1174
+ define("getClientRects", getClientRects);
1175
+ define("scrollTo", noop);
1176
+ define("scrollBy", noop);
1177
+ define("scrollIntoView", noop);
1178
+ define("focus", noop);
1179
+ define("blur", noop);
1180
+ for (const prop of numericProps) {
1181
+ const desc = Object.getOwnPropertyDescriptor(proto, prop);
1182
+ if (desc)
1183
+ continue;
1184
+ Object.defineProperty(proto, prop, {
1185
+ configurable: true,
1186
+ get: () => 0
1187
+ });
1188
+ }
1189
+ }
1190
+ layoutPatchApplied = true;
1191
+ }, applyPatches = async () => {
1192
+ const { \u{275}DominoAdapter } = await import(resolveAngularRuntimePath("@angular/platform-server"));
1193
+ if (!\u{275}DominoAdapter?.prototype) {
1194
+ console.warn("[Angular Patch] \u0275DominoAdapter not found, skipping patches");
1195
+ return false;
1196
+ }
1197
+ try {
1198
+ const adapter = new \u{275}DominoAdapter;
1199
+ const seedDoc = typeof adapter.createHtmlDocument === "function" ? adapter.createHtmlDocument() : typeof adapter.getDefaultDocument === "function" ? adapter.getDefaultDocument() : null;
1200
+ if (seedDoc) {
1201
+ patchElementLayout(seedDoc);
1202
+ const probe = seedDoc.createElement("div");
1203
+ if (typeof probe.getBoundingClientRect !== "function") {
1204
+ console.warn("[Angular Patch] Layout shim did not stick on probe element prototype chain");
1205
+ }
1206
+ }
1207
+ } catch (error) {
1208
+ console.warn("[Angular Patch] Could not eagerly patch Element prototypes:", error);
1209
+ }
1210
+ const proto = \u{275}DominoAdapter.prototype;
1211
+ const origGetBaseHref = proto.getBaseHref;
1212
+ proto.getBaseHref = function(doc) {
1213
+ if (!doc || !doc.head || typeof doc.head.children === "undefined") {
1214
+ return "";
1215
+ }
1216
+ return origGetBaseHref.call(this, doc);
1217
+ };
1218
+ const origCreateHtmlDocument = proto.createHtmlDocument;
1219
+ proto.createHtmlDocument = function() {
1220
+ const doc = origCreateHtmlDocument.call(this);
1221
+ ensureHead(doc);
1222
+ patchElementLayout(doc);
1223
+ return doc;
1224
+ };
1225
+ const origGetDefaultDocument = proto.getDefaultDocument;
1226
+ proto.getDefaultDocument = function() {
1227
+ const doc = origGetDefaultDocument.call(this);
1228
+ ensureHead(doc);
1229
+ patchElementLayout(doc);
1230
+ return doc;
1231
+ };
1232
+ return true;
1233
+ };
1234
+ var init_angularPatch = __esm(() => {
1235
+ init_resolveAngularPackage();
1236
+ SSR_LAYOUT_RECT = Object.freeze({
1237
+ bottom: 0,
1238
+ height: 0,
1239
+ left: 0,
1240
+ right: 0,
1241
+ top: 0,
1242
+ width: 0,
1243
+ x: 0,
1244
+ y: 0,
1245
+ toJSON() {
1246
+ return this;
1247
+ }
1248
+ });
1249
+ });
1250
+
1251
+ // src/angular/angularDeps.ts
1252
+ var initDominoAdapter = (platformServer) => {
1253
+ try {
1254
+ platformServer.\u{275}DominoAdapter?.makeCurrent?.();
1255
+ } catch (err) {
1256
+ console.error("Failed to initialize DominoAdapter:", err);
1257
+ }
1258
+ }, loadAngularDeps = async () => {
1259
+ if (true) {
1260
+ await import(resolveAngularRuntimePath("@angular/compiler"));
1261
+ }
1262
+ const { applyPatches: applyPatches2 } = await Promise.resolve().then(() => (init_angularPatch(), exports_angularPatch));
1263
+ await applyPatches2();
1264
+ const [platformBrowser, platformServer, common, core] = await Promise.all([
1265
+ import(resolveAngularRuntimePath("@angular/platform-browser")),
1266
+ import(resolveAngularRuntimePath("@angular/platform-server")),
1267
+ import(resolveAngularRuntimePath("@angular/common")),
1268
+ import(resolveAngularRuntimePath("@angular/core"))
1269
+ ]);
1270
+ if (false) {}
1271
+ initDominoAdapter(platformServer);
1272
+ return {
1273
+ APP_BASE_HREF: common.APP_BASE_HREF,
1274
+ bootstrapApplication: platformBrowser.bootstrapApplication,
1275
+ DomSanitizer: platformBrowser.DomSanitizer,
1276
+ ENVIRONMENT_INITIALIZER: core.ENVIRONMENT_INITIALIZER,
1277
+ inject: core.inject,
1278
+ provideClientHydration: platformBrowser.provideClientHydration,
1279
+ provideServerRendering: platformServer.provideServerRendering,
1280
+ provideZonelessChangeDetection: core.provideZonelessChangeDetection,
1281
+ reflectComponentType: core.reflectComponentType,
1282
+ renderApplication: platformServer.renderApplication,
1283
+ REQUEST: core.REQUEST,
1284
+ REQUEST_CONTEXT: core.REQUEST_CONTEXT,
1285
+ RESPONSE_INIT: core.RESPONSE_INIT,
1286
+ Sanitizer: core.Sanitizer,
1287
+ SecurityContext: core.SecurityContext,
1288
+ withHttpTransferCacheOptions: platformBrowser.withHttpTransferCacheOptions
1289
+ };
1290
+ }, angularDeps = null, getAngularDeps = () => {
1291
+ if (!angularDeps) {
1292
+ angularDeps = loadAngularDeps();
1293
+ }
1294
+ return angularDeps;
1295
+ };
1296
+ var init_angularDeps = __esm(() => {
1297
+ init_resolveAngularPackage();
1298
+ });
1299
+
1300
+ // src/utils/registerClientScript.ts
1301
+ var scriptRegistry, requestCounter = 0, getRequestId = () => `req_${Date.now()}_${++requestCounter}`, ssrContextGetter = null, getSsrContextId = () => ssrContextGetter?.() || Object.getOwnPropertyDescriptor(globalThis, "__absolutejs_requestId")?.value, registerClientScript = (script, requestId) => {
1302
+ const id = requestId || getSsrContextId() || getRequestId();
1303
+ if (!scriptRegistry.has(id)) {
1304
+ scriptRegistry.set(id, new Set);
1305
+ }
1306
+ scriptRegistry.get(id)?.add(script);
1307
+ return id;
1308
+ }, setSsrContextGetter = (getter) => {
1309
+ ssrContextGetter = getter;
1310
+ }, clearAllClientScripts = () => {
1311
+ scriptRegistry.clear();
1312
+ }, generateClientScriptCode = (scripts) => {
1313
+ if (scripts.length === 0) {
1314
+ return "";
1315
+ }
1316
+ const scriptCode = scripts.map((script, index) => {
1317
+ const funcString = script.toString();
1318
+ const bodyMatch = funcString.match(/\{([\s\S]*)\}/);
1319
+ if (!bodyMatch || !bodyMatch[1]) {
1320
+ return "";
1321
+ }
1322
+ const body = bodyMatch[1].trim();
1323
+ return `
1324
+ (function() {
1325
+ var executed = false;
1326
+ function executeScript_${index}() {
1327
+ if (executed) return;
1328
+ executed = true;
1329
+ ${body}
1330
+ }
1331
+
1332
+ if (document.readyState === 'complete' || document.readyState === 'interactive') {
1333
+ executeScript_${index}();
1334
+ } else {
1335
+ document.addEventListener('DOMContentLoaded', executeScript_${index});
1336
+ }
1337
+
1338
+ // Watch for hydration-added elements
1339
+ var observer = new MutationObserver(function() {
1340
+ executeScript_${index}();
1341
+ if (executed) observer.disconnect();
1342
+ });
1343
+ if (!executed) {
1344
+ observer.observe(document.body || document.documentElement, { childList: true, subtree: true });
1345
+ }
1346
+
1347
+ // Single fallback timeout
1348
+ setTimeout(function() {
1349
+ executeScript_${index}();
1350
+ observer.disconnect();
1351
+ }, 1000);
1352
+ })();`;
1353
+ }).join(`
1354
+ `);
1355
+ return `<script>
1356
+ (function() {
1357
+ ${scriptCode}
1358
+ })();
1359
+ </script>`;
1360
+ }, getAndClearClientScripts = (requestId) => {
1361
+ const id = requestId || ssrContextGetter?.();
1362
+ if (!id)
1363
+ return [];
1364
+ const scripts = scriptRegistry.get(id);
1365
+ if (!scripts) {
1366
+ return [];
1367
+ }
1368
+ const scriptArray = Array.from(scripts);
1369
+ scriptRegistry.delete(id);
1370
+ return scriptArray;
1371
+ };
1372
+ var init_registerClientScript = __esm(() => {
1373
+ scriptRegistry = new Map;
1374
+ if (typeof globalThis !== "undefined") {
1375
+ Object.assign(globalThis, { registerClientScript });
1376
+ }
1377
+ });
1378
+
1379
+ // src/angular/httpTransferCache.ts
1380
+ var ABSOLUTE_HTTP_TRANSFER_CACHE_SKIP_HEADER = "x-skip-transfer-cache", buildAbsoluteHttpTransferCacheOptions = (options = {}) => {
1381
+ const {
1382
+ filter: userFilter,
1383
+ skipHeader = ABSOLUTE_HTTP_TRANSFER_CACHE_SKIP_HEADER,
1384
+ ...angularOptions
1385
+ } = options;
1386
+ return {
1387
+ includePostRequests: false,
1388
+ includeRequestsWithAuthHeaders: false,
1389
+ ...angularOptions,
1390
+ filter: (request) => !request.headers.has(skipHeader) && (userFilter?.(request) ?? true)
1391
+ };
1392
+ };
1393
+
1394
+ // src/angular/requestProviders.ts
1395
+ import { REQUEST, REQUEST_CONTEXT, RESPONSE_INIT } from "@angular/core";
1396
+ var buildRequestProviders = (deps, request, requestContext, responseInit) => [
1397
+ { provide: deps.REQUEST, useValue: request ?? null },
1398
+ { provide: deps.REQUEST_CONTEXT, useValue: requestContext ?? null },
1399
+ { provide: deps.RESPONSE_INIT, useValue: responseInit ?? null }
1400
+ ];
1401
+ var init_requestProviders = () => {};
1402
+
1403
+ // src/angular/ssrRender.ts
1404
+ var routePropsCache, cacheRouteData = (pagePath, data) => {
1405
+ const cacheKey = pagePath.split("?")[0] ?? pagePath;
1406
+ routePropsCache.set(cacheKey, data);
1407
+ }, getCachedRouteData = (pagePath) => routePropsCache.get(pagePath), selectorCache, buildProviders = (deps, sanitizer, maybeProps, tokenMap, request, requestContext, responseInit, userProviders = []) => {
1408
+ const providers = [
1409
+ deps.provideServerRendering(),
1410
+ deps.provideClientHydration(deps.withHttpTransferCacheOptions(buildAbsoluteHttpTransferCacheOptions())),
1411
+ deps.provideZonelessChangeDetection(),
1412
+ { provide: deps.APP_BASE_HREF, useValue: "/" },
1413
+ {
1414
+ provide: deps.DomSanitizer,
1415
+ useValue: sanitizer
1416
+ },
1417
+ { provide: deps.Sanitizer, useValue: sanitizer },
1418
+ ...buildRequestProviders(deps, request, requestContext, responseInit),
1419
+ ...userProviders
1420
+ ];
1421
+ if (!maybeProps) {
1422
+ return providers;
1423
+ }
1424
+ const propProviders = Object.entries(maybeProps).map(([propName, propValue]) => ({
1425
+ token: tokenMap.get(toScreamingSnake(propName)),
1426
+ value: propValue
1427
+ })).filter((entry) => entry.token).map((entry) => ({ provide: entry.token, useValue: entry.value }));
1428
+ return [...providers, ...propProviders];
1429
+ }, clearSelectorCache = () => selectorCache.clear(), isInjectionToken = (value) => {
1430
+ if (!value || typeof value !== "object") {
1431
+ return false;
1432
+ }
1433
+ return "ngMetadataName" in value && value.ngMetadataName === "InjectionToken";
1434
+ }, discoverTokens = (pageModule) => new Map(Object.entries(pageModule).filter(([, value]) => isInjectionToken(value))), resolveSelector = (deps, pagePath, PageComponent) => {
1435
+ const cached = selectorCache.get(pagePath);
1436
+ if (cached) {
1437
+ return cached;
1438
+ }
1439
+ const selector = deps.reflectComponentType(PageComponent)?.selector ?? "ng-app";
1440
+ selectorCache.set(pagePath, selector);
1441
+ return selector;
1442
+ }, injectBeforeClose = (html, snippet) => {
1443
+ if (html.includes("</body>")) {
1444
+ return html.replace("</body>", `${snippet}</body>`);
1445
+ }
1446
+ if (html.includes("</html>")) {
1447
+ return html.replace("</html>", `${snippet}</html>`);
1448
+ }
1449
+ return html + snippet;
1450
+ }, injectSsrScripts = (html, requestId, indexPath, props) => {
1451
+ let result = html;
1452
+ const registeredScripts = getAndClearClientScripts(requestId);
1453
+ if (registeredScripts.length > 0) {
1454
+ result = injectBeforeClose(result, generateClientScriptCode(registeredScripts));
1455
+ }
1456
+ if (props) {
1457
+ result = injectBeforeClose(result, `<script>window.__ABS_ANGULAR_PAGE_PROPS__ = ${JSON.stringify(props)};</script>`);
1458
+ }
1459
+ if (indexPath) {
1460
+ const escapedIndexPath = JSON.stringify(indexPath);
1461
+ result = injectBeforeClose(result, `<script>import(${escapedIndexPath});</script>`);
1462
+ }
1463
+ return result;
1464
+ }, renderAngularApp = async (deps, PageComponent, providers, document2, url = "/") => {
1465
+ const bootstrap = (context) => deps.bootstrapApplication(PageComponent, { providers }, context);
1466
+ return withSuppressedAngularDevLogs(() => deps.renderApplication(bootstrap, {
1467
+ document: document2,
1468
+ platformProviders: [],
1469
+ url
1470
+ }));
1471
+ }, withSuppressedAngularDevLogs = async (render) => {
1472
+ const origLog = console.log;
1473
+ console.log = (...args) => {
1474
+ if (typeof args[0] === "string" && args[0].includes("development mode")) {
1475
+ return;
1476
+ }
1477
+ origLog.apply(console, args);
1478
+ };
1479
+ try {
1480
+ return await render();
1481
+ } finally {
1482
+ console.log = origLog;
1483
+ }
1484
+ };
1485
+ var init_ssrRender = __esm(() => {
1486
+ init_registerClientScript();
1487
+ init_requestProviders();
1488
+ routePropsCache = new Map;
1489
+ selectorCache = new Map;
1490
+ });
1491
+
1492
+ // src/angular/islands.ts
1493
+ var exports_islands = {};
1494
+ __export(exports_islands, {
1495
+ renderAngularIslandToHtml: () => renderAngularIslandToHtml,
1496
+ mountAngularIsland: () => mountAngularIsland,
1497
+ isAngularComponent: () => isAngularComponent,
1498
+ getAngularIslandSelector: () => getAngularIslandSelector
1499
+ });
1500
+ var angularIslandSelector = "abs-angular-island", isAngularComponent = (value) => typeof value === "function", getAngularIslandSelector = (_islandId) => angularIslandSelector, getSelectorFromRenderedIsland = (rootElement) => {
1501
+ const firstChild = rootElement.firstElementChild;
1502
+ if (!(firstChild instanceof HTMLElement)) {
1503
+ return null;
1504
+ }
1505
+ const selector = firstChild.tagName.toLowerCase();
1506
+ return selector.length > 0 ? selector : null;
1507
+ }, getClientAngularComponentSelector = (component) => {
1508
+ const maybeDef = Reflect.get(component, "\u0275cmp");
1509
+ if (typeof maybeDef !== "object" || maybeDef === null) {
1510
+ return null;
1511
+ }
1512
+ const maybeSelectors = Reflect.get(maybeDef, "selectors");
1513
+ if (!Array.isArray(maybeSelectors)) {
1514
+ return null;
1515
+ }
1516
+ const [firstSelectorGroup] = maybeSelectors;
1517
+ if (!Array.isArray(firstSelectorGroup)) {
1518
+ return null;
1519
+ }
1520
+ const [selector] = firstSelectorGroup;
1521
+ return typeof selector === "string" && selector.length > 0 ? selector : null;
1522
+ }, createAngularIslandApp = async () => {
1523
+ const { EnvironmentInjector, provideZonelessChangeDetection } = await import("@angular/core");
1524
+ const { createApplication } = await import("@angular/platform-browser");
1525
+ const app = await createApplication({
1526
+ providers: [provideZonelessChangeDetection()]
1527
+ });
1528
+ const environmentInjector = app.injector.get(EnvironmentInjector);
1529
+ return { app, environmentInjector };
1530
+ }, angularIslandAppPromise = null, getAngularIslandApp = async () => {
1531
+ if (!angularIslandAppPromise) {
1532
+ angularIslandAppPromise = createAngularIslandApp();
1533
+ }
1534
+ return angularIslandAppPromise;
1535
+ }, wrapperMetadataCache, requestRenderCache, getRequestRenderCache = () => {
1536
+ const requestId = getSsrContextId();
1537
+ if (!requestId) {
1538
+ return null;
1539
+ }
1540
+ const cached = requestRenderCache.get(requestId);
1541
+ if (cached) {
1542
+ return cached;
1543
+ }
1544
+ const renderCache = new Map;
1545
+ requestRenderCache.set(requestId, renderCache);
1546
+ return renderCache;
1547
+ }, getAngularIslandWrapperKey = (component, _islandId) => {
1548
+ const componentName = typeof component.name === "string" && component.name.length > 0 ? component.name : "AngularIsland";
1549
+ return `${componentName}:${angularIslandSelector}`;
1550
+ }, getIslandRenderCacheKey = (component, props) => {
1551
+ const componentName = typeof component.name === "string" && component.name.length > 0 ? component.name : "AngularIsland";
1552
+ return `${componentName}:${JSON.stringify(props)}`;
1553
+ }, buildAngularIslandWrapperMetadata = async (component, islandId, wrapperKey) => {
1554
+ const { Component, InjectionToken, inject } = await import("@angular/core");
1555
+ const { NgComponentOutlet } = await import("@angular/common");
1556
+ const deps = await getAngularDeps();
1557
+ const selector = getAngularIslandSelector(islandId);
1558
+ const propsToken = new InjectionToken(`${wrapperKey}:props`);
1559
+
1560
+ class AngularIslandWrapperComponent {
1561
+ component = component;
1562
+ props = inject(propsToken);
1563
+ }
1564
+ return {
1565
+ deps,
1566
+ propsToken,
1567
+ selector,
1568
+ WrapperComponent: Component({
1569
+ imports: [NgComponentOutlet, component],
1570
+ selector,
1571
+ standalone: true,
1572
+ template: '<ng-container *ngComponentOutlet="component; inputs: props"></ng-container>'
1573
+ })(AngularIslandWrapperComponent)
1574
+ };
1575
+ }, createAngularIslandWrapper = async (component, islandId) => {
1576
+ const wrapperKey = getAngularIslandWrapperKey(component, islandId);
1577
+ const cached = wrapperMetadataCache.get(wrapperKey);
1578
+ if (cached) {
1579
+ return cached;
1580
+ }
1581
+ const metadataPromise = buildAngularIslandWrapperMetadata(component, islandId, wrapperKey);
1582
+ wrapperMetadataCache.set(wrapperKey, metadataPromise);
1583
+ return metadataPromise;
1584
+ }, extractAngularIslandRoot = (html, selector) => {
1585
+ const openTag = `<${selector}`;
1586
+ const start = html.indexOf(openTag);
1587
+ if (start < 0) {
1588
+ throw new Error(`Could not find Angular island root "${selector}".`);
1589
+ }
1590
+ const endTag = `</${selector}>`;
1591
+ const end = html.indexOf(endTag, start);
1592
+ if (end < 0) {
1593
+ throw new Error(`Could not close Angular island root "${selector}".`);
1594
+ }
1595
+ return html.slice(start, end + endTag.length);
1596
+ }, mountAngularIsland = async (component, element, props, islandId) => {
1597
+ await import("@angular/compiler");
1598
+ const { createComponent, inputBinding } = await import("@angular/core");
1599
+ const selector = getAngularIslandSelector(islandId);
1600
+ const { app, environmentInjector } = await getAngularIslandApp();
1601
+ let rootElement = element.querySelector(selector);
1602
+ if (!(rootElement instanceof HTMLElement)) {
1603
+ element.innerHTML = `<${selector}></${selector}>`;
1604
+ rootElement = element.querySelector(selector);
1605
+ }
1606
+ if (!(rootElement instanceof HTMLElement))
1607
+ return app;
1608
+ const componentSelector = getClientAngularComponentSelector(component) ?? getSelectorFromRenderedIsland(rootElement);
1609
+ if (!componentSelector)
1610
+ return app;
1611
+ rootElement.innerHTML = `<${componentSelector}></${componentSelector}>`;
1612
+ const hostElement = rootElement.querySelector(componentSelector);
1613
+ if (!(hostElement instanceof HTMLElement))
1614
+ return app;
1615
+ const bindings = Object.entries(props).map(([key, value]) => inputBinding(key, () => value));
1616
+ const componentRef = createComponent(component, {
1617
+ bindings,
1618
+ environmentInjector,
1619
+ hostElement
1620
+ });
1621
+ app.attachView(componentRef.hostView);
1622
+ componentRef.changeDetectorRef.detectChanges();
1623
+ window.__ABS_ANGULAR_ISLAND_APPS__ ??= [];
1624
+ window.__ABS_ANGULAR_ISLAND_APPS__.push(app);
1625
+ return app;
1626
+ }, renderAngularIslandToHtml = async (component, props, islandId) => {
1627
+ const requestCache = getRequestRenderCache();
1628
+ const renderCacheKey = getIslandRenderCacheKey(component, props);
1629
+ const cachedHtml = requestCache?.get(renderCacheKey);
1630
+ if (cachedHtml) {
1631
+ return cachedHtml;
1632
+ }
1633
+ const { deps, propsToken, selector, WrapperComponent } = await createAngularIslandWrapper(component, islandId);
1634
+ const providers = [
1635
+ deps.provideServerRendering(),
1636
+ deps.provideZonelessChangeDetection(),
1637
+ { provide: deps.APP_BASE_HREF, useValue: "/" },
1638
+ { provide: propsToken, useValue: props }
1639
+ ];
1640
+ const document2 = `<!DOCTYPE html><html><body><${selector}></${selector}></body></html>`;
1641
+ const html = await withSuppressedAngularDevLogs(() => deps.renderApplication((context) => deps.bootstrapApplication(WrapperComponent, { providers }, context), {
1642
+ document: document2,
1643
+ platformProviders: [],
1644
+ url: "/"
1645
+ }));
1646
+ const islandHtml = extractAngularIslandRoot(html, selector);
1647
+ requestCache?.set(renderCacheKey, islandHtml);
1648
+ return islandHtml;
1649
+ };
1650
+ var init_islands2 = __esm(() => {
1651
+ init_angularDeps();
1652
+ init_ssrRender();
1653
+ init_registerClientScript();
1654
+ wrapperMetadataCache = new Map;
1655
+ requestRenderCache = new Map;
1656
+ });
1657
+
1658
+ // src/core/islandSsr.ts
1659
+ var renderAngularIslandToHtmlInternal = async (component, props, islandId) => {
1660
+ const { renderAngularIslandToHtml: renderAngularIslandToHtml2 } = await Promise.resolve().then(() => (init_islands2(), exports_islands));
1661
+ return renderAngularIslandToHtml2(component, props, islandId);
1662
+ }, renderAngularIslandToHtml2, renderReactIslandToHtml = (component, props) => import("react").then(({ createElement }) => import("react-dom/server").then(({ renderToStaticMarkup }) => renderToStaticMarkup(createElement(component, props)))), renderSvelteIslandToHtml = (component, props) => import("svelte/server").then(({ render }) => {
1663
+ const { body } = render(component, { props });
1664
+ return body;
1665
+ }), renderVueIslandToHtml = (component, props) => import("vue").then(({ createSSRApp, h: createVueVNode }) => {
1666
+ const app = createSSRApp({
1667
+ render: () => createVueVNode(component, props)
1668
+ });
1669
+ return import("vue/server-renderer").then(({ renderToString }) => renderToString(app));
1670
+ });
1671
+ var init_islandSsr = __esm(() => {
1672
+ renderAngularIslandToHtml2 = renderAngularIslandToHtmlInternal;
1673
+ });
1674
+
1675
+ // src/build/resolvePackageImport.ts
1676
+ import { resolve as resolve2, join as join2 } from "path";
1677
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
1678
+ var resolveExportPath = (entry, conditions) => {
1679
+ if (typeof entry === "string")
1680
+ return entry;
1681
+ if (!entry || typeof entry !== "object")
1682
+ return null;
1683
+ for (const condition of conditions) {
1684
+ const target = Reflect.get(entry, condition);
1685
+ if (typeof target === "string") {
1686
+ return target;
1687
+ }
1688
+ }
1689
+ return null;
1690
+ }, resolvePackageImport = (specifier, conditions = ["import"]) => {
1691
+ if (specifier.startsWith(".") || specifier.startsWith("/"))
1692
+ return null;
1693
+ const parts = specifier.split("/");
1694
+ const isScoped = specifier.startsWith("@");
1695
+ const packageName = isScoped ? `${parts[0]}/${parts[1]}` : parts[0];
1696
+ const subpath = isScoped ? parts.slice(2).join("/") : parts.slice(1).join("/");
1697
+ const exportKey = subpath ? `./${subpath}` : ".";
1698
+ const currentPackageJsonPath = resolve2(process.cwd(), "package.json");
1699
+ const currentPackageJson = existsSync2(currentPackageJsonPath) ? JSON.parse(readFileSync2(currentPackageJsonPath, "utf-8")) : null;
1700
+ const currentPackageDir = currentPackageJson?.name === packageName ? process.cwd() : null;
1701
+ const packageDir = currentPackageDir ?? resolve2(process.cwd(), "node_modules", packageName ?? "");
1702
+ const packageJsonPath = join2(packageDir, "package.json");
1703
+ if (!existsSync2(packageJsonPath))
1704
+ return null;
1705
+ try {
1706
+ const packageJson = currentPackageDir && currentPackageJson ? currentPackageJson : JSON.parse(readFileSync2(packageJsonPath, "utf-8"));
1707
+ const { exports } = packageJson;
1708
+ if (!exports)
1709
+ return null;
1710
+ const entry = exports[exportKey];
1711
+ if (!entry)
1712
+ return null;
1713
+ const importPath = resolveExportPath(entry, conditions);
1714
+ if (!importPath)
1715
+ return null;
1716
+ if (currentPackageDir && importPath.startsWith("./dist/")) {
1717
+ const sourceCandidate = resolve2(packageDir, importPath.replace(/^\.\/dist\//, "./src/"));
1718
+ if (existsSync2(sourceCandidate)) {
1719
+ return sourceCandidate;
1720
+ }
1721
+ }
1722
+ const resolved = resolve2(packageDir, importPath);
1723
+ return existsSync2(resolved) ? resolved : null;
1724
+ } catch {
1725
+ return null;
1726
+ }
1727
+ };
1728
+ var init_resolvePackageImport = () => {};
1729
+
1730
+ // src/svelte/lowerIslandSyntax.ts
1731
+ var ISLAND_TAG_RE, extractBracedExpression = (text, braceStart) => {
1732
+ let depth = 0;
1733
+ for (let index = braceStart;index < text.length; index += 1) {
1734
+ const char = text[index];
1735
+ if (char === "{")
1736
+ depth += 1;
1737
+ if (char === "}")
1738
+ depth -= 1;
1739
+ if (depth === 0) {
1740
+ return text.slice(braceStart + 1, index).trim();
1741
+ }
1742
+ }
1743
+ return null;
1744
+ }, extractIslandAttribute = (attributeString, name) => {
1745
+ const quotedMatch = attributeString.match(new RegExp(`\\b${name}\\s*=\\s*["']([^"']+)["']`));
1746
+ if (quotedMatch?.[1]) {
1747
+ return { expression: JSON.stringify(quotedMatch[1]), found: true };
1748
+ }
1749
+ const attributeIndex = attributeString.search(new RegExp(`\\b${name}\\s*=\\s*\\{`));
1750
+ if (attributeIndex < 0) {
1751
+ return { expression: "", found: false };
1752
+ }
1753
+ const braceStart = attributeString.indexOf("{", attributeIndex);
1754
+ if (braceStart < 0) {
1755
+ return { expression: "", found: false };
1756
+ }
1757
+ const expression = extractBracedExpression(attributeString, braceStart);
1758
+ if (expression === null) {
1759
+ return { expression: "", found: false };
1760
+ }
1761
+ return { expression, found: true };
1762
+ }, lowerSvelteIslandSyntax = (source, _mode = "server") => {
1763
+ if (!source.includes("<Island")) {
1764
+ return { code: source, transformed: false };
1765
+ }
1766
+ let islandIndex = 0;
1767
+ const transformedMarkup = source.replace(ISLAND_TAG_RE, (fullMatch, attributeString) => {
1768
+ const framework = extractIslandAttribute(attributeString, "framework");
1769
+ const component = extractIslandAttribute(attributeString, "component");
1770
+ if (!framework.found || !component.found) {
1771
+ return fullMatch;
1772
+ }
1773
+ const hydrate = extractIslandAttribute(attributeString, "hydrate");
1774
+ const props = extractIslandAttribute(attributeString, "props");
1775
+ const slotId = `absolute-svelte-island-${islandIndex.toString(BASE_36_RADIX)}`;
1776
+ islandIndex += 1;
1777
+ const resolveExpression = `await __absoluteResolveIslandHtml(${JSON.stringify(slotId)}, { component: ${component.expression}, framework: ${framework.expression}, hydrate: ${hydrate.found ? hydrate.expression : JSON.stringify("load")}, props: ${props.found ? props.expression : "{}"} })`;
1778
+ return `<div data-absolute-island-slot="${slotId}" style="display: contents">{@html ${resolveExpression}}</div>`;
1779
+ });
1780
+ const importLine = 'import { resolveIslandHtml as __absoluteResolveIslandHtml } from "@absolutejs/absolute/svelte";';
1781
+ if (transformedMarkup.includes("<script")) {
1782
+ return {
1783
+ code: transformedMarkup.replace(/<script(\s[^>]*)?>/, (match) => `${match}
1784
+ ${importLine}
1785
+ `),
1786
+ transformed: true
1787
+ };
1788
+ }
1789
+ return {
1790
+ code: `<script lang="ts">
1791
+ ${importLine}
1792
+ </script>
1793
+ ${transformedMarkup}`,
1794
+ transformed: true
1795
+ };
1796
+ };
1797
+ var init_lowerIslandSyntax = __esm(() => {
1798
+ init_constants();
1799
+ ISLAND_TAG_RE = /<Island\b([\s\S]*?)\/>/g;
1800
+ });
1801
+
1802
+ // src/svelte/lowerAwaitSlotSyntax.ts
1803
+ var AWAIT_BLOCK_RE, escapeTemplateLiteral = (value) => value.replaceAll("\\", "\\\\").replaceAll("`", "\\`").replaceAll("${", "\\${"), markupToTemplateLiteral = (markup) => {
1804
+ const escaped = escapeTemplateLiteral(markup.trim());
1805
+ const withExpressions = escaped.replace(/\{([^{}]+)\}/g, (_, expression) => `\${${String(expression).trim()}}`);
1806
+ return `\`${withExpressions}\``;
1807
+ }, lowerSvelteAwaitSlotSyntax = (source) => {
1808
+ if (!source.includes("{#await")) {
1809
+ return { code: source, transformed: false };
1810
+ }
1811
+ let awaitIndex = 0;
1812
+ let transformed = false;
1813
+ const lowered = source.replace(AWAIT_BLOCK_RE, (fullMatch, awaitExpression, pendingMarkup, thenIdentifier, thenMarkup, catchIdentifier, catchMarkup) => {
1814
+ const trimmedAwaitExpression = awaitExpression.trim();
1815
+ if (!trimmedAwaitExpression) {
1816
+ return fullMatch;
1817
+ }
1818
+ const slotId = `absolute-svelte-await-${awaitIndex.toString(BASE_36_RADIX)}`;
1819
+ awaitIndex += 1;
1820
+ transformed = true;
1821
+ const thenValueIdentifier = thenIdentifier?.trim() || "__awaitValue";
1822
+ const catchValueIdentifier = catchIdentifier?.trim() || "__awaitError";
1823
+ const fallbackHtml = markupToTemplateLiteral(pendingMarkup);
1824
+ const resolvedHtml = markupToTemplateLiteral(thenMarkup);
1825
+ const rejectedHtml = typeof catchMarkup === "string" ? markupToTemplateLiteral(catchMarkup) : null;
1826
+ const catchBranch = rejectedHtml ? `catch (${catchValueIdentifier}) { return ${rejectedHtml}; }` : "catch (_absoluteAwaitError) { throw _absoluteAwaitError; }";
1827
+ return `<AbsoluteAwaitSlot id="${slotId}" fallbackHtml={${fallbackHtml}} resolve={async () => { try { const ${thenValueIdentifier} = await (${trimmedAwaitExpression}); return ${resolvedHtml}; } ${catchBranch} }} />`;
1828
+ });
1829
+ if (!transformed) {
1830
+ return { code: source, transformed: false };
1831
+ }
1832
+ const importLine = 'import AbsoluteAwaitSlot from "@absolutejs/absolute/svelte/components/AwaitSlot.svelte";';
1833
+ if (lowered.includes("<script")) {
1834
+ return {
1835
+ code: lowered.replace(/<script(\s[^>]*)?>/, (match) => `${match}
1836
+ ${importLine}
1837
+ `),
1838
+ transformed: true
1839
+ };
1840
+ }
1841
+ return {
1842
+ code: `<script lang="ts">
1843
+ ${importLine}
1844
+ </script>
1845
+ ${lowered}`,
1846
+ transformed: true
1847
+ };
1848
+ };
1849
+ var init_lowerAwaitSlotSyntax = __esm(() => {
1850
+ init_constants();
1851
+ AWAIT_BLOCK_RE = /\{#await\s+([^}]+)\}([\s\S]*?)\{:then(?:\s+([A-Za-z_$][\w$]*))?\}([\s\S]*?)(?:\{:catch(?:\s+([A-Za-z_$][\w$]*))?\}([\s\S]*?))?\{\/await\}/g;
1852
+ });
1853
+
1854
+ // src/build/stylePreprocessor.ts
1855
+ var exports_stylePreprocessor = {};
1856
+ __export(exports_stylePreprocessor, {
1857
+ stylePreprocessorPlugin: () => stylePreprocessorPlugin,
1858
+ recordStyleOutput: () => recordStyleOutput,
1859
+ isStylePath: () => isStylePath,
1860
+ isStyleModulePath: () => isStyleModulePath,
1861
+ isPreprocessableStylePath: () => isPreprocessableStylePath,
1862
+ getStyleBaseName: () => getStyleBaseName,
1863
+ getCssOutputExtension: () => getCssOutputExtension,
1864
+ forgetStyleEntry: () => forgetStyleEntry,
1865
+ findStyleEntriesImporting: () => findStyleEntriesImporting,
1866
+ createSvelteStylePreprocessor: () => createSvelteStylePreprocessor,
1867
+ createStyleTransformConfig: () => createStyleTransformConfig,
1868
+ createStylePreprocessorPlugin: () => createStylePreprocessorPlugin,
1869
+ compileStyleSource: () => compileStyleSource,
1870
+ compileStyleFileIfNeededSync: () => compileStyleFileIfNeededSync,
1871
+ compileStyleFileIfNeeded: () => compileStyleFileIfNeeded,
1872
+ addStyleImporter: () => addStyleImporter
1873
+ });
1874
+ import { createHash } from "crypto";
1875
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
1876
+ import { readFile } from "fs/promises";
1877
+ import { createRequire } from "module";
2
1878
  import {
3
- handleReactPageRequest
4
- } from "../chunk-7mtstdqn.js";
5
- import {
6
- useIslandStore
7
- } from "../chunk-pvpp4pvs.js";
8
- import"../chunk-gd6wmknh.js";
9
- import"../chunk-mtgf69xn.js";
10
- import"../chunk-v5vmsxmy.js";
11
- import"../chunk-c1jfjnka.js";
12
- import"../chunk-d9c0am65.js";
13
- import"../chunk-cbkrwmvh.js";
14
- import {
15
- requireCurrentIslandRegistry
16
- } from "../chunk-5003emhv.js";
17
- import"../chunk-sd39p726.js";
18
- import"../chunk-gf0ygptk.js";
19
- import"../chunk-851whwc7.js";
20
- import"../chunk-p5504p14.js";
21
- import"../chunk-qxq2zcty.js";
22
- import"../chunk-s6defjk2.js";
23
- import {
24
- renderIslandResult
25
- } from "../chunk-d8w0qm28.js";
26
- import"../chunk-9ve9jq72.js";
27
- import"../chunk-7fw6x3js.js";
28
- import"../chunk-mbazhahf.js";
29
- import"../chunk-xnt8c6h2.js";
30
- import"../chunk-qh75agse.js";
31
- import {
32
- getIslandMarkerAttributes
33
- } from "../chunk-2f21eenc.js";
34
- import"../chunk-fygx2ymm.js";
35
- import"../chunk-8kcfffry.js";
36
- import"../chunk-3yjzpcne.js";
37
- import"../chunk-bmgqm774.js";
1879
+ dirname,
1880
+ extname,
1881
+ isAbsolute,
1882
+ join as join3,
1883
+ relative,
1884
+ resolve as resolve3
1885
+ } from "path";
1886
+ import { fileURLToPath } from "url";
1887
+ var CSS_EXTENSION_PATTERN, STYLE_EXTENSION_PATTERN, STYLE_MODULE_EXTENSION_PATTERN, STYLE_LANGUAGE_PATTERN, importOptionalPeer, requireOptionalPeer, requireFromCwd, isPreprocessableStylePath = (filePath) => STYLE_EXTENSION_PATTERN.test(filePath), isStyleModulePath = (filePath) => STYLE_MODULE_EXTENSION_PATTERN.test(filePath), isStylePath = (filePath) => /\.(css|s[ac]ss|less|styl(?:us)?)$/i.test(filePath), getStyleBaseName = (filePath) => filePath.replace(/\.(css|s[ac]ss|less|styl(?:us)?)$/i, ""), getStyleLanguage = (filePathOrLanguage) => {
1888
+ const normalized = filePathOrLanguage.toLowerCase();
1889
+ if (normalized === "scss" || normalized.endsWith(".scss"))
1890
+ return "scss";
1891
+ if (normalized === "sass" || normalized.endsWith(".sass"))
1892
+ return "sass";
1893
+ if (normalized === "less" || normalized.endsWith(".less"))
1894
+ return "less";
1895
+ if (normalized === "styl" || normalized === "stylus" || normalized.endsWith(".styl") || normalized.endsWith(".stylus"))
1896
+ return "stylus";
1897
+ return null;
1898
+ }, missingDependencyError = (name, filePath) => new Error(`Unable to compile ${filePath}: install optional dependency "${name}" to use this stylesheet preprocessor.`), throwPreprocessorError = (error, filePath, language) => {
1899
+ if (!(error instanceof Error)) {
1900
+ throw new Error(`${language} compile failed in ${filePath}: ${String(error)}`);
1901
+ }
1902
+ const detail = error;
1903
+ const sassLine = detail.span?.start?.line;
1904
+ const sassCol = detail.span?.start?.column;
1905
+ const line = detail.line ?? sassLine;
1906
+ const column = detail.column ?? sassCol;
1907
+ const location = typeof line === "number" ? `:${line}${typeof column === "number" ? `:${column}` : ""}` : "";
1908
+ const message = detail.formatted ?? detail.message;
1909
+ const wrapped = new Error(`${language} compile failed in ${filePath}${location}
1910
+ ${message}`);
1911
+ wrapped.cause = error;
1912
+ throw wrapped;
1913
+ }, requireOptionalPeerSync = (specifier) => {
1914
+ try {
1915
+ return requireFromCwd(specifier);
1916
+ } catch {
1917
+ return requireOptionalPeer(specifier);
1918
+ }
1919
+ }, normalizeLoadPaths = (filePath, paths = []) => [
1920
+ dirname(filePath),
1921
+ process.cwd(),
1922
+ ...paths.map((path) => resolve3(process.cwd(), path))
1923
+ ], tsconfigAliasCache, stripJsonComments = (source) => source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1"), normalizeAliasEntries = (aliases) => Object.entries(aliases ?? {}).map(([pattern, value]) => ({
1924
+ pattern,
1925
+ replacements: Array.isArray(value) ? value : [value]
1926
+ })), readTsconfigAliases = () => {
1927
+ const cwd = process.cwd();
1928
+ if (tsconfigAliasCache?.cwd === cwd)
1929
+ return tsconfigAliasCache;
1930
+ const tsconfigPath = resolve3(cwd, "tsconfig.json");
1931
+ const empty = { aliases: [], baseUrl: cwd, cwd };
1932
+ if (!existsSync3(tsconfigPath)) {
1933
+ tsconfigAliasCache = empty;
1934
+ return empty;
1935
+ }
1936
+ try {
1937
+ const parsed = JSON.parse(stripJsonComments(readFileSync3(tsconfigPath, "utf-8")));
1938
+ const compilerOptions = parsed.compilerOptions ?? {};
1939
+ const baseUrl = resolve3(cwd, compilerOptions.baseUrl ?? ".");
1940
+ tsconfigAliasCache = {
1941
+ aliases: normalizeAliasEntries(compilerOptions.paths),
1942
+ baseUrl,
1943
+ cwd
1944
+ };
1945
+ } catch {
1946
+ tsconfigAliasCache = empty;
1947
+ }
1948
+ return tsconfigAliasCache;
1949
+ }, getAliasEntries = (config) => {
1950
+ const tsconfig = readTsconfigAliases();
1951
+ return {
1952
+ aliases: [
1953
+ ...normalizeAliasEntries(config?.aliases),
1954
+ ...tsconfig.aliases
1955
+ ],
1956
+ baseUrl: tsconfig.baseUrl
1957
+ };
1958
+ }, aliasPatternToRegExp = (pattern) => new RegExp(`^${pattern.split("*").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("(.+)")}$`), resolveAliasTargets = (specifier, config) => {
1959
+ const { aliases, baseUrl } = getAliasEntries(config);
1960
+ const targets = [];
1961
+ for (const alias of aliases) {
1962
+ const match = specifier.match(aliasPatternToRegExp(alias.pattern));
1963
+ if (!match)
1964
+ continue;
1965
+ const wildcard = match[1] ?? "";
1966
+ for (const replacement of alias.replacements) {
1967
+ targets.push(resolve3(baseUrl, replacement.replace("*", wildcard)));
1968
+ }
1969
+ }
1970
+ return targets;
1971
+ }, getLanguageExtensions = (language) => {
1972
+ if (language === "less")
1973
+ return [".less", ".css"];
1974
+ if (language === "stylus")
1975
+ return [".styl", ".stylus", ".css"];
1976
+ return [".scss", ".sass", ".css"];
1977
+ }, getCandidatePaths = (basePath, language) => {
1978
+ const ext = extname(basePath);
1979
+ const paths = ext ? [basePath] : getLanguageExtensions(language).flatMap((extension) => [
1980
+ `${basePath}${extension}`,
1981
+ join3(basePath, `index${extension}`)
1982
+ ]);
1983
+ if (language === "scss" || language === "sass") {
1984
+ return paths.flatMap((path) => {
1985
+ const dir = dirname(path);
1986
+ const base = path.slice(dir.length + 1);
1987
+ return [path, join3(dir, `_${base}`)];
1988
+ });
1989
+ }
1990
+ return paths;
1991
+ }, resolveImportPath = (specifier, fromDirectory, loadPaths, language, config) => {
1992
+ const rawCandidates = [
1993
+ ...resolveAliasTargets(specifier, config),
1994
+ isAbsolute(specifier) ? specifier : resolve3(fromDirectory, specifier),
1995
+ ...loadPaths.map((path) => resolve3(path, specifier))
1996
+ ];
1997
+ for (const candidate of rawCandidates.flatMap((path) => getCandidatePaths(path, language))) {
1998
+ if (existsSync3(candidate))
1999
+ return candidate;
2000
+ }
2001
+ return null;
2002
+ }, isExternalCssUrl = (url) => /^(?:[a-z][a-z0-9+.-]*:|\/\/|#|\/)/i.test(url), splitCssUrl = (url) => {
2003
+ const markerIndex = url.search(/[?#]/);
2004
+ if (markerIndex === -1)
2005
+ return { marker: "", path: url };
2006
+ return {
2007
+ marker: url.slice(markerIndex),
2008
+ path: url.slice(0, markerIndex)
2009
+ };
2010
+ }, rebaseCssUrls = (contents, sourceFile, entryFile) => {
2011
+ const sourceDir = dirname(sourceFile);
2012
+ const entryDir = dirname(entryFile);
2013
+ if (sourceDir === entryDir)
2014
+ return contents;
2015
+ return contents.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/gi, (match, quote, rawUrl) => {
2016
+ const trimmedUrl = rawUrl.trim();
2017
+ if (!trimmedUrl || isExternalCssUrl(trimmedUrl))
2018
+ return match;
2019
+ const { marker, path } = splitCssUrl(trimmedUrl);
2020
+ const rebased = relative(entryDir, resolve3(sourceDir, path)).replace(/\\/g, "/");
2021
+ const normalized = rebased.startsWith(".") ? rebased : `./${rebased}`;
2022
+ const nextQuote = quote || '"';
2023
+ return `url(${nextQuote}${normalized}${marker}${nextQuote})`;
2024
+ });
2025
+ }, rewriteAliasedStyleImports = (contents, sourceFile, loadPaths, language, config) => contents.replace(/(@(?:use|forward|import|require)\s+)(["'])([^"']+)\2/g, (match, prefix, quote, specifier) => {
2026
+ if (specifier.startsWith(".") || isAbsolute(specifier) || isExternalCssUrl(specifier))
2027
+ return match;
2028
+ const resolved = resolveImportPath(specifier, dirname(sourceFile), loadPaths, language, config);
2029
+ return resolved ? `${prefix}${quote}${resolved}${quote}` : match;
2030
+ }), preprocessLoadedStyle = (contents, sourceFile, entryFile, loadPaths = [], language, config) => {
2031
+ const rebased = rebaseCssUrls(contents, sourceFile, entryFile);
2032
+ return language ? rewriteAliasedStyleImports(rebased, sourceFile, loadPaths, language, config) : rebased;
2033
+ }, extractCssModuleExports = (css) => {
2034
+ const exports = {};
2035
+ const nextCss = css.replace(/:export\s*\{([^}]*)\}/g, (_, body) => {
2036
+ for (const declaration of body.split(";")) {
2037
+ const separator = declaration.indexOf(":");
2038
+ if (separator === -1)
2039
+ continue;
2040
+ const key = declaration.slice(0, separator).trim();
2041
+ const value = declaration.slice(separator + 1).trim();
2042
+ if (key && value)
2043
+ exports[key] = value;
2044
+ }
2045
+ return "";
2046
+ });
2047
+ return { css: nextCss, exports };
2048
+ }, getSassOptions = (config, language) => ({
2049
+ ...config?.sass ?? {},
2050
+ ...language === "scss" ? config?.scss ?? {} : {}
2051
+ }), getLessOptions = (config) => config?.less ?? {}, getStylusOptions = (config) => config?.stylus ?? {}, createStyleTransformConfig = (stylePreprocessors, postcss) => postcss === undefined ? stylePreprocessors : { ...stylePreprocessors ?? {}, postcss }, withAdditionalData = (contents, additionalData) => additionalData ? `${additionalData}
2052
+ ${contents}` : contents, normalizePostcssModule = (mod) => {
2053
+ if (mod && typeof mod === "object" && "default" in mod) {
2054
+ return mod.default ?? mod;
2055
+ }
2056
+ return mod;
2057
+ }, loadPostcssConfigFile = async (configPath) => {
2058
+ const resolved = resolve3(process.cwd(), configPath);
2059
+ const loaded = resolved.endsWith(".cjs") || resolved.endsWith(".cts") ? requireOptionalPeerSync(resolved) : await importOptionalPeer(`${new URL(`file://${resolved}`).href}?t=${Date.now()}`);
2060
+ const config = normalizePostcssModule(loaded);
2061
+ const value = typeof config === "function" ? await config({
2062
+ cwd: process.cwd(),
2063
+ env: "development"
2064
+ }) : config;
2065
+ return normalizePostcssModule(value) ?? {};
2066
+ }, normalizePostcssPlugins = (plugins) => {
2067
+ if (!plugins)
2068
+ return [];
2069
+ if (Array.isArray(plugins))
2070
+ return plugins.filter(Boolean);
2071
+ const resolved = [];
2072
+ for (const [specifier, options] of Object.entries(plugins)) {
2073
+ if (options === false)
2074
+ continue;
2075
+ const mod = normalizePostcssModule(requireOptionalPeerSync(specifier));
2076
+ const plugin = typeof mod === "function" ? mod(options === true ? undefined : options) : mod;
2077
+ if (plugin)
2078
+ resolved.push(plugin);
2079
+ }
2080
+ return resolved;
2081
+ }, resolvePostcssConfig = async (config) => {
2082
+ const inlineConfig = config?.postcss;
2083
+ if (!inlineConfig)
2084
+ return null;
2085
+ const fileConfig = inlineConfig.config ? await loadPostcssConfigFile(inlineConfig.config) : {};
2086
+ const plugins = [
2087
+ ...normalizePostcssPlugins(fileConfig.plugins),
2088
+ ...normalizePostcssPlugins(inlineConfig.plugins)
2089
+ ];
2090
+ if (plugins.length === 0)
2091
+ return null;
2092
+ return {
2093
+ options: {
2094
+ ...fileConfig.options ?? {},
2095
+ ...inlineConfig.options ?? {}
2096
+ },
2097
+ plugins
2098
+ };
2099
+ }, runPostcss = async (css, filePath, config) => {
2100
+ const postcssConfig = await resolvePostcssConfig(config);
2101
+ if (!postcssConfig)
2102
+ return css;
2103
+ let postcssModule;
2104
+ try {
2105
+ postcssModule = await importOptionalPeer("postcss");
2106
+ } catch {
2107
+ throw missingDependencyError("postcss", filePath);
2108
+ }
2109
+ const postcss = postcssModule.default ?? postcssModule;
2110
+ const result = await postcss(postcssConfig.plugins).process(css, {
2111
+ from: filePath,
2112
+ map: false,
2113
+ ...postcssConfig.options
2114
+ });
2115
+ return result.css;
2116
+ }, createSassImporter = (entryFile, loadPaths, language, config, deps) => ({
2117
+ canonicalize(specifier, options) {
2118
+ const fromDirectory = options.containingUrl ? dirname(fileURLToPath(options.containingUrl)) : dirname(entryFile);
2119
+ const resolved = resolveImportPath(specifier, fromDirectory, loadPaths, language, config);
2120
+ return resolved ? new URL(`file://${resolved}`) : null;
2121
+ },
2122
+ load(canonicalUrl) {
2123
+ const filePath = fileURLToPath(canonicalUrl);
2124
+ deps?.add(filePath);
2125
+ const fileLanguage = getStyleLanguage(filePath);
2126
+ if (fileLanguage !== "scss" && fileLanguage !== "sass" && fileLanguage !== null)
2127
+ return null;
2128
+ return {
2129
+ contents: preprocessLoadedStyle(readFileSync3(filePath, "utf-8"), filePath, entryFile, loadPaths, language, config),
2130
+ syntax: filePath.endsWith(".sass") ? "indented" : "scss"
2131
+ };
2132
+ }
2133
+ }), createLessFileManager = (entryFile, loadPaths, config, deps) => ({
2134
+ install(less, pluginManager) {
2135
+ const baseManager = new less.FileManager;
2136
+ const manager = Object.create(baseManager);
2137
+ manager.supports = (filename, currentDirectory) => Boolean(resolveImportPath(filename, resolve3(currentDirectory), loadPaths, "less", config));
2138
+ manager.loadFile = async (filename, currentDirectory) => {
2139
+ const resolved = resolveImportPath(filename, resolve3(currentDirectory), loadPaths, "less", config);
2140
+ if (!resolved) {
2141
+ throw new Error(`Unable to resolve Less import "${filename}"`);
2142
+ }
2143
+ deps?.add(resolved);
2144
+ return {
2145
+ contents: preprocessLoadedStyle(await readFile(resolved, "utf-8"), resolved, entryFile, loadPaths, "less", config),
2146
+ filename: resolved
2147
+ };
2148
+ };
2149
+ pluginManager.addFileManager(manager);
2150
+ }
2151
+ }), renderStylus = async (contents, filePath, loadPaths, options, deps) => {
2152
+ let stylus;
2153
+ try {
2154
+ const stylusModule = await importOptionalPeer("stylus");
2155
+ stylus = stylusModule.default ?? stylusModule;
2156
+ } catch {
2157
+ throw missingDependencyError("stylus", filePath);
2158
+ }
2159
+ return new Promise((resolveCss, reject) => {
2160
+ const renderer = stylus(contents);
2161
+ renderer.set("filename", filePath);
2162
+ for (const [key, value] of Object.entries(options.options ?? {})) {
2163
+ renderer.set(key, value);
2164
+ }
2165
+ for (const path of loadPaths)
2166
+ renderer.include(path);
2167
+ renderer.render((error, css) => {
2168
+ if (error) {
2169
+ reject(error);
2170
+ return;
2171
+ }
2172
+ if (deps) {
2173
+ const stylusDeps = renderer.deps?.();
2174
+ if (Array.isArray(stylusDeps)) {
2175
+ for (const dep of stylusDeps)
2176
+ deps.add(resolve3(dep));
2177
+ }
2178
+ }
2179
+ resolveCss(css ?? "");
2180
+ });
2181
+ });
2182
+ }, styleDependencyGraph, styleOutputHashes, recordStyleDeps = (entry, deps) => {
2183
+ const key = resolve3(entry);
2184
+ const stripped = new Set;
2185
+ for (const dep of deps) {
2186
+ const resolved = resolve3(dep);
2187
+ if (resolved !== key)
2188
+ stripped.add(resolved);
2189
+ }
2190
+ styleDependencyGraph.set(key, stripped);
2191
+ }, addStyleImporter = (importerPath, stylePath) => {
2192
+ const key = resolve3(importerPath);
2193
+ const target = resolve3(stylePath);
2194
+ const deps = styleDependencyGraph.get(key) ?? new Set;
2195
+ deps.add(target);
2196
+ styleDependencyGraph.set(key, deps);
2197
+ }, findStyleEntriesImporting = (changedPath) => {
2198
+ const target = resolve3(changedPath);
2199
+ const importers = [];
2200
+ for (const [entry, deps] of styleDependencyGraph) {
2201
+ if (deps.has(target))
2202
+ importers.push(entry);
2203
+ }
2204
+ return importers;
2205
+ }, recordStyleOutput = (entry, css) => {
2206
+ const key = resolve3(entry);
2207
+ const hash = createHash("sha1").update(css).digest("hex");
2208
+ const previous = styleOutputHashes.get(key);
2209
+ styleOutputHashes.set(key, hash);
2210
+ return previous !== hash;
2211
+ }, forgetStyleEntry = (entry) => {
2212
+ const key = resolve3(entry);
2213
+ styleDependencyGraph.delete(key);
2214
+ styleOutputHashes.delete(key);
2215
+ }, compileStyleSource = async (filePath, source, languageHint, config) => {
2216
+ const language = getStyleLanguage(languageHint ?? filePath);
2217
+ const rawContents = source ?? await readFile(filePath, "utf-8");
2218
+ const deps = new Set;
2219
+ if (language === "scss" || language === "sass") {
2220
+ const options = getSassOptions(config, language);
2221
+ const packageName = options.implementation ?? "sass";
2222
+ let sass;
2223
+ try {
2224
+ sass = await importOptionalPeer(packageName);
2225
+ } catch {
2226
+ throw missingDependencyError(packageName, filePath);
2227
+ }
2228
+ const contents = withAdditionalData(rawContents, options.additionalData);
2229
+ const loadPaths = normalizeLoadPaths(filePath, options.loadPaths);
2230
+ try {
2231
+ const result = sass.compileString(contents, {
2232
+ importers: [
2233
+ createSassImporter(filePath, loadPaths, language, config, deps)
2234
+ ],
2235
+ loadPaths,
2236
+ style: "expanded",
2237
+ syntax: language === "sass" ? "indented" : "scss",
2238
+ url: new URL(`file://${filePath}`)
2239
+ });
2240
+ const css = await runPostcss(result.css, filePath, config);
2241
+ recordStyleDeps(filePath, deps);
2242
+ return css;
2243
+ } catch (error) {
2244
+ throwPreprocessorError(error, filePath, language);
2245
+ }
2246
+ }
2247
+ if (language === "less") {
2248
+ const options = getLessOptions(config);
2249
+ let lessModule;
2250
+ try {
2251
+ lessModule = await importOptionalPeer("less");
2252
+ } catch {
2253
+ throw missingDependencyError("less", filePath);
2254
+ }
2255
+ const less = lessModule.render ? lessModule : lessModule.default;
2256
+ const render = less?.render;
2257
+ if (!render)
2258
+ throw missingDependencyError("less", filePath);
2259
+ const contents = withAdditionalData(rawContents, options.additionalData);
2260
+ const loadPaths = normalizeLoadPaths(filePath, options.paths);
2261
+ try {
2262
+ const result = await render(contents, {
2263
+ ...options.options ?? {},
2264
+ filename: filePath,
2265
+ paths: loadPaths,
2266
+ plugins: [
2267
+ ...options.options?.plugins ?? [],
2268
+ createLessFileManager(filePath, loadPaths, config, deps)
2269
+ ]
2270
+ });
2271
+ const css = await runPostcss(result.css, filePath, config);
2272
+ recordStyleDeps(filePath, deps);
2273
+ return css;
2274
+ } catch (error) {
2275
+ throwPreprocessorError(error, filePath, "less");
2276
+ }
2277
+ }
2278
+ if (language === "stylus") {
2279
+ const options = getStylusOptions(config);
2280
+ const loadPaths = normalizeLoadPaths(filePath, options.paths);
2281
+ const contents = withAdditionalData(preprocessLoadedStyle(rawContents, filePath, filePath, loadPaths, "stylus", config), options.additionalData);
2282
+ try {
2283
+ const css = await runPostcss(await renderStylus(contents, filePath, loadPaths, options, deps), filePath, config);
2284
+ recordStyleDeps(filePath, deps);
2285
+ return css;
2286
+ } catch (error) {
2287
+ throwPreprocessorError(error, filePath, "stylus");
2288
+ }
2289
+ }
2290
+ return runPostcss(rawContents, filePath, config);
2291
+ }, createStylePreprocessorPlugin = (config) => ({
2292
+ name: "absolute-style-preprocessor",
2293
+ setup(build) {
2294
+ const cssModuleSources = new Map;
2295
+ build.onResolve({ filter: /^absolute-style-module:/ }, ({ path }) => ({
2296
+ namespace: "absolute-style-module",
2297
+ path: path.slice("absolute-style-module:".length)
2298
+ }));
2299
+ build.onLoad({ filter: /\.module\.css$/i, namespace: "absolute-style-module" }, async ({ path }) => {
2300
+ const source = cssModuleSources.get(path);
2301
+ if (!source) {
2302
+ throw new Error(`Unable to resolve CSS module source for ${path}`);
2303
+ }
2304
+ return {
2305
+ contents: source.css,
2306
+ loader: "css"
2307
+ };
2308
+ });
2309
+ build.onLoad({ filter: STYLE_EXTENSION_PATTERN }, async ({ path }) => {
2310
+ if (isStyleModulePath(path)) {
2311
+ const cssModulePath = path.replace(STYLE_EXTENSION_PATTERN, ".css");
2312
+ const compiled = await compileStyleSource(path, undefined, undefined, config);
2313
+ const { css, exports } = extractCssModuleExports(compiled);
2314
+ cssModuleSources.set(cssModulePath, { css, exports });
2315
+ const exportSource = Object.keys(exports).length > 0 ? `import styles from ${JSON.stringify(`absolute-style-module:${cssModulePath}`)}; export default Object.assign({}, styles, ${JSON.stringify(exports)});` : `export { default } from ${JSON.stringify(`absolute-style-module:${cssModulePath}`)};`;
2316
+ return {
2317
+ contents: exportSource,
2318
+ loader: "js"
2319
+ };
2320
+ }
2321
+ return {
2322
+ contents: await compileStyleSource(path, undefined, undefined, config),
2323
+ loader: "css"
2324
+ };
2325
+ });
2326
+ build.onLoad({ filter: CSS_EXTENSION_PATTERN }, async ({ path }) => ({
2327
+ contents: await compileStyleSource(path, undefined, undefined, config),
2328
+ loader: "css"
2329
+ }));
2330
+ }
2331
+ }), stylePreprocessorPlugin, createSvelteStylePreprocessor = (config) => ({
2332
+ style: async ({
2333
+ attributes,
2334
+ content,
2335
+ filename
2336
+ }) => {
2337
+ const language = typeof attributes.lang === "string" ? attributes.lang : typeof attributes.type === "string" ? attributes.type.replace(/^text\//, "") : null;
2338
+ if (!language || !STYLE_LANGUAGE_PATTERN.test(language))
2339
+ return;
2340
+ const path = filename ?? `style.${language}`;
2341
+ return {
2342
+ code: await compileStyleSource(path, content, language, config)
2343
+ };
2344
+ }
2345
+ }), compileStyleFileIfNeeded = async (filePath, config) => {
2346
+ if (!isPreprocessableStylePath(filePath)) {
2347
+ return runPostcss(await readFile(filePath, "utf-8"), filePath, config);
2348
+ }
2349
+ return compileStyleSource(filePath, undefined, undefined, config);
2350
+ }, compileStyleFileIfNeededSync = (filePath, config) => {
2351
+ const rawContents = readFileSync3(filePath, "utf-8");
2352
+ const language = getStyleLanguage(filePath);
2353
+ if (config?.postcss) {
2354
+ throw new Error(`Unable to compile ${filePath}: PostCSS preprocessing is async-only.`);
2355
+ }
2356
+ if (language === "scss" || language === "sass") {
2357
+ const options = getSassOptions(config, language);
2358
+ const packageName = options.implementation ?? "sass";
2359
+ let sass;
2360
+ try {
2361
+ sass = requireOptionalPeerSync(packageName);
2362
+ } catch {
2363
+ throw missingDependencyError(packageName, filePath);
2364
+ }
2365
+ const contents = withAdditionalData(rawContents, options.additionalData);
2366
+ const loadPaths = normalizeLoadPaths(filePath, options.loadPaths);
2367
+ return sass.compileString(contents, {
2368
+ importers: [
2369
+ createSassImporter(filePath, loadPaths, language, config)
2370
+ ],
2371
+ loadPaths,
2372
+ style: "expanded",
2373
+ syntax: language === "sass" ? "indented" : "scss",
2374
+ url: new URL(`file://${filePath}`)
2375
+ }).css;
2376
+ }
2377
+ if (language === "less") {
2378
+ throw new Error(`Unable to compile ${filePath}: Less styleUrl preprocessing is async-only. Import the Less file from a bundled entrypoint or use SCSS/CSS for Angular styleUrl.`);
2379
+ }
2380
+ if (language === "stylus") {
2381
+ throw new Error(`Unable to compile ${filePath}: Stylus styleUrl preprocessing is async-only. Import the Stylus file from a bundled entrypoint or use SCSS/CSS for Angular styleUrl.`);
2382
+ }
2383
+ return rawContents;
2384
+ }, getCssOutputExtension = (filePath) => isPreprocessableStylePath(filePath) ? ".css" : extname(filePath);
2385
+ var init_stylePreprocessor = __esm(() => {
2386
+ CSS_EXTENSION_PATTERN = /\.css$/i;
2387
+ STYLE_EXTENSION_PATTERN = /\.(s[ac]ss|less|styl(?:us)?)$/i;
2388
+ STYLE_MODULE_EXTENSION_PATTERN = /\.module\.(s[ac]ss|less|styl(?:us)?)$/i;
2389
+ STYLE_LANGUAGE_PATTERN = /^(s[ac]ss|less|styl(?:us)?)$/i;
2390
+ importOptionalPeer = new Function("specifier", "return import(specifier)");
2391
+ requireOptionalPeer = new Function("specifier", "return require(specifier)");
2392
+ requireFromCwd = createRequire(join3(process.cwd(), "package.json"));
2393
+ styleDependencyGraph = new Map;
2394
+ styleOutputHashes = new Map;
2395
+ stylePreprocessorPlugin = createStylePreprocessorPlugin();
2396
+ });
2397
+
2398
+ // src/core/svelteServerModule.ts
2399
+ import { mkdir, readdir } from "fs/promises";
2400
+ import { basename as basename2, dirname as dirname2, extname as extname2, join as join4, relative as relative2, resolve as resolve4 } from "path";
2401
+ var serverCacheRoot, compiledModuleCache, originalSourcePathCache, transpiler, ensureRelativeImportPath = (from, target) => {
2402
+ const importPath = relative2(dirname2(from), target).replace(/\\/g, "/");
2403
+ return importPath.startsWith(".") ? importPath : `./${importPath}`;
2404
+ }, processDirectoryEntries = (entries, dir, targetFileName, stack) => {
2405
+ for (const entry of entries) {
2406
+ const entryPath = join4(dir, entry.name);
2407
+ if (entry.isDirectory())
2408
+ stack.push(entryPath);
2409
+ if (entry.isFile() && entry.name === targetFileName) {
2410
+ return entryPath;
2411
+ }
2412
+ }
2413
+ return null;
2414
+ }, searchDirectoryLevel = async (dirs, targetFileName) => {
2415
+ if (dirs.length === 0)
2416
+ return null;
2417
+ const nextStack = [];
2418
+ const dirEntries = await Promise.all(dirs.map(async (dir) => ({
2419
+ dir,
2420
+ entries: await readdir(dir, {
2421
+ encoding: "utf-8",
2422
+ withFileTypes: true
2423
+ })
2424
+ })));
2425
+ for (const { dir, entries } of dirEntries) {
2426
+ const found = processDirectoryEntries(entries, dir, targetFileName, nextStack);
2427
+ if (found)
2428
+ return found;
2429
+ }
2430
+ return searchDirectoryLevel(nextStack, targetFileName);
2431
+ }, findSourceFileByBasename = async (searchRoot, targetFileName) => searchDirectoryLevel([searchRoot], targetFileName), normalizeBuiltSvelteFileName = (sourcePath) => basename2(sourcePath).replace(/-[a-z0-9]{6,}(?=\.svelte$)/i, ""), resolveOriginalSourcePath = async (sourcePath) => {
2432
+ const cachedPath = originalSourcePathCache.get(sourcePath);
2433
+ if (cachedPath !== undefined) {
2434
+ return cachedPath;
2435
+ }
2436
+ if (!sourcePath.includes(`${join4(process.cwd(), "build")}${process.platform === "win32" ? "" : "/"}`) && !sourcePath.includes("/build/")) {
2437
+ originalSourcePathCache.set(sourcePath, sourcePath);
2438
+ return sourcePath;
2439
+ }
2440
+ const resolvedSourcePath = await findSourceFileByBasename(join4(process.cwd(), "src"), normalizeBuiltSvelteFileName(sourcePath));
2441
+ const nextPath = resolvedSourcePath ?? sourcePath;
2442
+ originalSourcePathCache.set(sourcePath, nextPath);
2443
+ return nextPath;
2444
+ }, resolveRelativeModule = async (spec, from) => {
2445
+ if (!spec.startsWith(".")) {
2446
+ return null;
2447
+ }
2448
+ const basePath = resolve4(dirname2(from), spec);
2449
+ const candidates = [
2450
+ basePath,
2451
+ `${basePath}.ts`,
2452
+ `${basePath}.js`,
2453
+ `${basePath}.mjs`,
2454
+ `${basePath}.cjs`,
2455
+ `${basePath}.json`,
2456
+ join4(basePath, "index.ts"),
2457
+ join4(basePath, "index.js"),
2458
+ join4(basePath, "index.mjs"),
2459
+ join4(basePath, "index.cjs"),
2460
+ join4(basePath, "index.json")
2461
+ ];
2462
+ const existResults = await Promise.all(candidates.map((candidate) => Bun.file(candidate).exists()));
2463
+ const foundIndex = existResults.indexOf(true);
2464
+ return foundIndex >= 0 ? candidates[foundIndex] ?? null : null;
2465
+ }, getCachedModulePath = (sourcePath) => {
2466
+ const relativeSourcePath = relative2(process.cwd(), sourcePath).replace(/\\/g, "/");
2467
+ const normalizedSourcePath = relativeSourcePath.startsWith("..") ? sourcePath.replace(/[:\\/]/g, "_") : relativeSourcePath;
2468
+ return join4(serverCacheRoot, `${normalizedSourcePath}.server.js`);
2469
+ }, resolveSvelteImport = async (spec, from) => {
2470
+ if (!spec.startsWith(".") && !spec.startsWith("/")) {
2471
+ const resolved = resolvePackageImport(spec);
2472
+ return resolved && resolved.endsWith(".svelte") ? resolved : null;
2473
+ }
2474
+ if (spec.startsWith("/")) {
2475
+ return spec;
2476
+ }
2477
+ if (!spec.startsWith(".")) {
2478
+ return null;
2479
+ }
2480
+ const explicitPath = resolve4(dirname2(from), spec);
2481
+ if (extname2(explicitPath) === ".svelte") {
2482
+ return explicitPath;
2483
+ }
2484
+ const candidate = `${explicitPath}.svelte`;
2485
+ if (await Bun.file(candidate).exists() === true) {
2486
+ return candidate;
2487
+ }
2488
+ return null;
2489
+ }, writeIfChanged = async (path, content) => {
2490
+ const targetFile = Bun.file(path);
2491
+ const exists = await targetFile.exists();
2492
+ if (exists) {
2493
+ const currentContent = await targetFile.text();
2494
+ if (currentContent === content) {
2495
+ return;
2496
+ }
2497
+ }
2498
+ await Bun.write(path, content);
2499
+ }, compileSvelteServerModule = async (sourcePath) => {
2500
+ const cachedModulePath = compiledModuleCache.get(sourcePath);
2501
+ if (cachedModulePath) {
2502
+ return cachedModulePath;
2503
+ }
2504
+ const resolutionSourcePath = await resolveOriginalSourcePath(sourcePath);
2505
+ const source = await Bun.file(sourcePath).text();
2506
+ const { compile, preprocess } = await import("svelte/compiler");
2507
+ const loweredAwaitSource = lowerSvelteAwaitSlotSyntax(source);
2508
+ const loweredSource = lowerSvelteIslandSyntax(loweredAwaitSource.code, "server");
2509
+ const preprocessed = await preprocess(loweredSource.code, createSvelteStylePreprocessor());
2510
+ let transpiled = sourcePath.endsWith(".ts") || sourcePath.endsWith(".svelte.ts") ? transpiler.transformSync(preprocessed.code) : preprocessed.code;
2511
+ const childImportSpecs = Array.from(transpiled.matchAll(/from\s+['"]([^'"]+)['"]/g)).map((match) => match[1]).filter((value) => value !== undefined);
2512
+ const resolvedChildModules = await Promise.all(childImportSpecs.map((spec) => resolveSvelteImport(spec, resolutionSourcePath)));
2513
+ const resolvedModuleImports = await Promise.all(childImportSpecs.map((spec) => resolveRelativeModule(spec, resolutionSourcePath)));
2514
+ const childModulePaths = new Map;
2515
+ const rewrittenModulePaths = new Map;
2516
+ const compiledChildren = await Promise.all(childImportSpecs.map(async (spec, index) => {
2517
+ const resolvedChild = resolvedChildModules[index];
2518
+ if (!spec || !resolvedChild)
2519
+ return null;
2520
+ return {
2521
+ compiledPath: await compileSvelteServerModule(resolvedChild),
2522
+ resolvedChild,
2523
+ spec
2524
+ };
2525
+ }));
2526
+ for (const result of compiledChildren) {
2527
+ if (!result)
2528
+ continue;
2529
+ childModulePaths.set(result.spec, result.compiledPath);
2530
+ childModulePaths.set(result.resolvedChild, result.compiledPath);
2531
+ }
2532
+ for (let index = 0;index < childImportSpecs.length; index += 1) {
2533
+ const spec = childImportSpecs[index];
2534
+ const resolvedModuleImport = resolvedModuleImports[index];
2535
+ if (!spec || !resolvedModuleImport)
2536
+ continue;
2537
+ if (resolvedChildModules[index])
2538
+ continue;
2539
+ rewrittenModulePaths.set(spec, ensureRelativeImportPath(getCachedModulePath(sourcePath), resolvedModuleImport));
2540
+ }
2541
+ for (const [spec, resolvedModuleImport] of rewrittenModulePaths) {
2542
+ transpiled = transpiled.replaceAll(spec, resolvedModuleImport);
2543
+ }
2544
+ let compiledCode = compile(transpiled, {
2545
+ css: "injected",
2546
+ experimental: {
2547
+ async: loweredAwaitSource.transformed || loweredSource.transformed
2548
+ },
2549
+ filename: resolutionSourcePath,
2550
+ generate: "server"
2551
+ }).js.code;
2552
+ for (const [spec, compiledChildPath] of childModulePaths) {
2553
+ compiledCode = compiledCode.replaceAll(spec, ensureRelativeImportPath(getCachedModulePath(sourcePath), compiledChildPath));
2554
+ }
2555
+ for (const [spec, resolvedModuleImport] of rewrittenModulePaths) {
2556
+ compiledCode = compiledCode.replaceAll(spec, resolvedModuleImport);
2557
+ }
2558
+ const compiledModulePath = getCachedModulePath(sourcePath);
2559
+ await mkdir(dirname2(compiledModulePath), { recursive: true });
2560
+ await writeIfChanged(compiledModulePath, compiledCode);
2561
+ compiledModuleCache.set(sourcePath, compiledModulePath);
2562
+ return compiledModulePath;
2563
+ };
2564
+ var init_svelteServerModule = __esm(() => {
2565
+ init_resolvePackageImport();
2566
+ init_lowerIslandSyntax();
2567
+ init_lowerAwaitSlotSyntax();
2568
+ init_stylePreprocessor();
2569
+ serverCacheRoot = join4(process.cwd(), ".absolutejs", "islands", "svelte");
2570
+ compiledModuleCache = new Map;
2571
+ originalSourcePathCache = new Map;
2572
+ transpiler = new Bun.Transpiler({
2573
+ loader: "ts",
2574
+ target: "browser"
2575
+ });
2576
+ });
2577
+
2578
+ // src/core/renderIslandMarkup.ts
2579
+ var islandSequence = 0, resolvedServerComponentCache, resolvedServerBuildComponentCache, nextIslandId = () => {
2580
+ islandSequence += 1;
2581
+ return `island-${islandSequence}`;
2582
+ }, isRecord3 = (value) => typeof value === "object" && value !== null, isReactServerIslandComponent = (value) => typeof value === "function", isSvelteServerIslandComponent = (value) => typeof value === "function", isVueServerIslandComponent = (value) => typeof value === "function" || isRecord3(value), isAngularServerIslandComponent = (value) => typeof value === "function", resolveBuildReferencePath = (source, registryPath) => {
2583
+ if (source.startsWith("file://"))
2584
+ return new URL(source).pathname;
2585
+ if (source.startsWith("."))
2586
+ return new URL(source, registryPath).pathname;
2587
+ return source;
2588
+ }, loadAndCompileServerBuildComponent = async (buildReferencePath) => {
2589
+ const compiledModulePath = await compileSvelteServerModule(buildReferencePath);
2590
+ const loadedModule = await import(compiledModulePath);
2591
+ return "default" in loadedModule ? loadedModule.default : loadedModule;
2592
+ }, loadServerBuildComponent = async (buildReferencePath) => {
2593
+ const cachedBuildComponent = resolvedServerBuildComponentCache.get(buildReferencePath);
2594
+ if (cachedBuildComponent) {
2595
+ return cachedBuildComponent;
2596
+ }
2597
+ const loadPromise = loadAndCompileServerBuildComponent(buildReferencePath);
2598
+ resolvedServerBuildComponentCache.set(buildReferencePath, loadPromise);
2599
+ return loadPromise;
2600
+ }, loadServerImportComponent = async (resolvedComponent, exportName) => {
2601
+ const resolvedModulePath = resolvedComponent.startsWith(".") ? new URL(resolvedComponent, import.meta.url).pathname : resolvedComponent;
2602
+ const importTarget = resolvedModulePath.endsWith(".svelte") ? await compileSvelteServerModule(resolvedModulePath) : resolvedModulePath;
2603
+ const loadedModule = await import(importTarget);
2604
+ if (exportName && exportName !== "default" && exportName in loadedModule) {
2605
+ return loadedModule[exportName];
2606
+ }
2607
+ return "default" in loadedModule ? loadedModule.default : loadedModule;
2608
+ }, resolveIslandComponent = async (component) => {
2609
+ const buildReference = getIslandBuildReference(component);
2610
+ const buildReferencePath = buildReference?.source ? resolveBuildReferencePath(buildReference.source, import.meta.url) : null;
2611
+ if (buildReferencePath?.endsWith(".svelte")) {
2612
+ return loadServerBuildComponent(buildReferencePath);
2613
+ }
2614
+ if (buildReferencePath) {
2615
+ return loadServerImportComponent(buildReferencePath, buildReference?.export);
2616
+ }
2617
+ const resolvedComponent = getIslandComponent(component);
2618
+ if (typeof resolvedComponent !== "string") {
2619
+ return resolvedComponent;
2620
+ }
2621
+ return loadServerImportComponent(resolvedComponent);
2622
+ }, resolveServerIslandComponent = async (component) => {
2623
+ const cachedResolvedComponent = resolvedServerComponentCache.get(component);
2624
+ if (cachedResolvedComponent) {
2625
+ return cachedResolvedComponent;
2626
+ }
2627
+ const resolutionPromise = resolveIslandComponent(component);
2628
+ resolvedServerComponentCache.set(component, resolutionPromise);
2629
+ return resolutionPromise;
2630
+ }, resolveReactServerIslandComponent = async (component) => {
2631
+ const resolvedComponent = await resolveServerIslandComponent(component);
2632
+ if (!isReactServerIslandComponent(resolvedComponent)) {
2633
+ throw new Error("Resolved React island is not a valid React component.");
2634
+ }
2635
+ return resolvedComponent;
2636
+ }, resolveSvelteServerIslandComponent = async (component) => {
2637
+ const resolvedComponent = await resolveServerIslandComponent(component);
2638
+ if (!isSvelteServerIslandComponent(resolvedComponent)) {
2639
+ throw new Error("Resolved Svelte island is not a valid Svelte component.");
2640
+ }
2641
+ return resolvedComponent;
2642
+ }, resolveVueServerIslandComponent = async (component) => {
2643
+ const resolvedComponent = await resolveServerIslandComponent(component);
2644
+ if (!isVueServerIslandComponent(resolvedComponent)) {
2645
+ throw new Error("Resolved Vue island is not a valid Vue component.");
2646
+ }
2647
+ return resolvedComponent;
2648
+ }, resolveAngularServerIslandComponent = async (component) => {
2649
+ const resolvedComponent = await resolveServerIslandComponent(component);
2650
+ if (!isAngularServerIslandComponent(resolvedComponent)) {
2651
+ throw new Error("Resolved Angular island is not a valid Angular component.");
2652
+ }
2653
+ return resolvedComponent;
2654
+ }, renderIslandMarkup = async (registry, props) => {
2655
+ const result = await renderIslandResult(registry, props);
2656
+ return `<div ${serializeIslandAttributes(result.attributes)}>${result.html}</div>`;
2657
+ }, renderIslandResult = async (registry, props) => {
2658
+ const islandId = nextIslandId();
2659
+ const attributes = getIslandMarkerAttributes(props);
2660
+ if (props.framework === "react") {
2661
+ const entry = registry.react?.[props.component];
2662
+ if (!entry) {
2663
+ throw new Error(`Island component "${props.component}" is not registered for framework "react".`);
2664
+ }
2665
+ const component = await resolveReactServerIslandComponent(entry);
2666
+ const html = await renderReactIslandToHtml(component, props.props);
2667
+ return { attributes, html };
2668
+ }
2669
+ if (props.framework === "svelte") {
2670
+ const entry = registry.svelte?.[props.component];
2671
+ if (!entry) {
2672
+ throw new Error(`Island component "${props.component}" is not registered for framework "svelte".`);
2673
+ }
2674
+ const component = await resolveSvelteServerIslandComponent(entry);
2675
+ const html = await renderSvelteIslandToHtml(component, props.props);
2676
+ return { attributes, html };
2677
+ }
2678
+ if (props.framework === "vue") {
2679
+ const entry = registry.vue?.[props.component];
2680
+ if (!entry) {
2681
+ throw new Error(`Island component "${props.component}" is not registered for framework "vue".`);
2682
+ }
2683
+ const component = await resolveVueServerIslandComponent(entry);
2684
+ const html = await renderVueIslandToHtml(component, props.props);
2685
+ return { attributes, html };
2686
+ }
2687
+ if (props.framework === "angular") {
2688
+ const entry = registry.angular?.[props.component];
2689
+ if (!entry) {
2690
+ throw new Error(`Island component "${props.component}" is not registered for framework "angular".`);
2691
+ }
2692
+ const component = await resolveAngularServerIslandComponent(entry);
2693
+ const html = await renderAngularIslandToHtml2(component, props.props, islandId);
2694
+ return {
2695
+ attributes: {
2696
+ ...getIslandMarkerAttributes(props, islandId)
2697
+ },
2698
+ html
2699
+ };
2700
+ }
2701
+ throw new Error(`Framework "${props.framework}" is not implemented in this prototype.`);
2702
+ };
2703
+ var init_renderIslandMarkup = __esm(() => {
2704
+ init_islandSsr();
2705
+ init_svelteServerModule();
2706
+ init_islandMarkupAttributes();
2707
+ init_islands();
2708
+ resolvedServerComponentCache = new Map;
2709
+ resolvedServerBuildComponentCache = new Map;
2710
+ });
2711
+
2712
+ // src/core/streamingSlotRegistrar.ts
2713
+ var STREAMING_SLOT_REGISTRAR_KEY = Symbol.for("absolutejs.streamingSlotRegistrar");
2714
+ var STREAMING_SLOT_WARNING_STORAGE_KEY = Symbol.for("absolutejs.streamingSlotWarningController");
2715
+ var STREAMING_SLOT_COLLECTION_STORAGE_KEY = Symbol.for("absolutejs.streamingSlotCollectionController");
2716
+ var getRegisteredStreamingSlotRegistrar = () => {
2717
+ const value = Reflect.get(globalThis, STREAMING_SLOT_REGISTRAR_KEY);
2718
+ if (typeof value === "function" || value === null) {
2719
+ return value;
2720
+ }
2721
+ return;
2722
+ };
2723
+ var isObjectRecord = (value) => Boolean(value) && typeof value === "object";
2724
+ var isStreamingSlotWarningController = (value) => isObjectRecord(value) && ("maybeWarn" in value) && typeof value.maybeWarn === "function";
2725
+ var isStreamingSlotCollectionController = (value) => isObjectRecord(value) && ("isCollecting" in value) && typeof value.isCollecting === "function";
2726
+ var getWarningController = () => {
2727
+ const value = Reflect.get(globalThis, STREAMING_SLOT_WARNING_STORAGE_KEY);
2728
+ if (value === null || typeof value === "undefined")
2729
+ return;
2730
+ return isStreamingSlotWarningController(value) ? value : undefined;
2731
+ };
2732
+ var getCollectionController = () => {
2733
+ const value = Reflect.get(globalThis, STREAMING_SLOT_COLLECTION_STORAGE_KEY);
2734
+ if (value === null || typeof value === "undefined")
2735
+ return;
2736
+ return isStreamingSlotCollectionController(value) ? value : undefined;
2737
+ };
2738
+ var hasRegisteredStreamingSlotRegistrar = () => typeof getRegisteredStreamingSlotRegistrar() === "function";
2739
+ var isStreamingSlotCollectionActive = () => getCollectionController()?.isCollecting() === true;
2740
+ var registerStreamingSlot = (slot) => {
2741
+ getRegisteredStreamingSlotRegistrar()?.(slot);
2742
+ };
2743
+ var setStreamingSlotCollectionController = (controller) => {
2744
+ Reflect.set(globalThis, STREAMING_SLOT_COLLECTION_STORAGE_KEY, controller);
2745
+ };
2746
+ var setStreamingSlotRegistrar = (nextRegistrar) => {
2747
+ Reflect.set(globalThis, STREAMING_SLOT_REGISTRAR_KEY, nextRegistrar);
2748
+ };
2749
+ var setStreamingSlotWarningController = (controller) => {
2750
+ Reflect.set(globalThis, STREAMING_SLOT_WARNING_STORAGE_KEY, controller);
2751
+ };
2752
+ var warnMissingStreamingSlotCollector = (primitiveName) => {
2753
+ if (isStreamingSlotCollectionActive()) {
2754
+ return;
2755
+ }
2756
+ getWarningController()?.maybeWarn(primitiveName);
2757
+ };
2758
+
2759
+ // src/core/streamingSlotRegistry.ts
2760
+ var STREAMING_SLOT_STORAGE_KEY = Symbol.for("absolutejs.streamingSlotAsyncLocalStorage");
2761
+ var isObjectRecord2 = (value) => Boolean(value) && typeof value === "object";
2762
+ var isAsyncLocalStorage = (value) => isObjectRecord2(value) && ("getStore" in value) && typeof value.getStore === "function" && ("run" in value) && typeof value.run === "function";
2763
+ var getStorageGlobal = () => {
2764
+ const value = Reflect.get(globalThis, STREAMING_SLOT_STORAGE_KEY);
2765
+ if (value === null || typeof value === "undefined") {
2766
+ return value;
2767
+ }
2768
+ return isAsyncLocalStorage(value) ? value : undefined;
2769
+ };
2770
+ var isServerRuntime = () => typeof process !== "undefined" && typeof process.versions?.node === "string";
2771
+ var ensureAsyncLocalStorage = async () => {
2772
+ const storage = getStorageGlobal();
2773
+ if (typeof storage !== "undefined") {
2774
+ return storage;
2775
+ }
2776
+ if (!isServerRuntime()) {
2777
+ Reflect.set(globalThis, STREAMING_SLOT_STORAGE_KEY, null);
2778
+ return getStorageGlobal();
2779
+ }
2780
+ const mod = await import("async_hooks");
2781
+ Reflect.set(globalThis, STREAMING_SLOT_STORAGE_KEY, new mod.AsyncLocalStorage);
2782
+ return getStorageGlobal();
2783
+ };
2784
+ var getActiveSlotStore = () => {
2785
+ const storage = getStorageGlobal();
2786
+ if (!storage)
2787
+ return;
2788
+ return storage.getStore();
2789
+ };
2790
+ var registerStreamingSlot2 = (slot) => {
2791
+ const store = getActiveSlotStore();
2792
+ if (!store)
2793
+ return;
2794
+ store.set(slot.id, slot);
2795
+ };
2796
+ setStreamingSlotRegistrar(registerStreamingSlot2);
2797
+ setStreamingSlotCollectionController({
2798
+ isCollecting: () => getActiveSlotStore() !== undefined
2799
+ });
2800
+ var hasActiveStreamingSlotRegistry = () => getActiveSlotStore() !== undefined;
2801
+ var runWithStreamingSlotRegistry = async (task) => {
2802
+ const storage = await ensureAsyncLocalStorage();
2803
+ if (!storage) {
2804
+ const slots = [];
2805
+ return {
2806
+ result: await task(),
2807
+ slots
2808
+ };
2809
+ }
2810
+ return storage.run(new Map, async () => {
2811
+ const result = await task();
2812
+ const store = storage.getStore();
2813
+ return {
2814
+ result,
2815
+ slots: store ? [...store.values()] : []
2816
+ };
2817
+ });
2818
+ };
2819
+
2820
+ // src/core/islandPageContext.ts
2821
+ init_constants();
2822
+ var BOOTSTRAP_MANIFEST_KEY = "BootstrapClient";
2823
+ var ISLAND_MARKER = 'data-island="true"';
2824
+ var MANIFEST_MARKER = "__ABSOLUTE_MANIFEST__";
2825
+ var ISLAND_STATE_MARKER = "__ABS_ISLAND_STATE__";
2826
+ var CLOSING_HEAD_TAG = "</head>";
2827
+ var buildIslandsHeadMarkup = (manifest) => {
2828
+ const manifestScript = `<script>window.__ABSOLUTE_MANIFEST__ = ${JSON.stringify(manifest)}</script>`;
2829
+ const islandStateScript = `<script>window.__ABS_ISLAND_STATE__ = ${JSON.stringify(globalThis.__ABS_ISLAND_STATE__ ?? {})}</script>`;
2830
+ const bootstrapPath = manifest[BOOTSTRAP_MANIFEST_KEY];
2831
+ const bootstrapScript = bootstrapPath ? `<script type="module" src="${bootstrapPath}"></script>` : "";
2832
+ return `${manifestScript}${islandStateScript}${bootstrapScript}`;
2833
+ };
2834
+ var injectHeadMarkup = (html, markup) => {
2835
+ const closingHeadIndex = html.indexOf("</head>");
2836
+ if (closingHeadIndex >= 0) {
2837
+ return `${html.slice(0, closingHeadIndex)}${markup}${html.slice(closingHeadIndex)}`;
2838
+ }
2839
+ const openingBodyIndex = html.indexOf("<body");
2840
+ if (openingBodyIndex >= 0) {
2841
+ const bodyStart = html.indexOf(">", openingBodyIndex);
2842
+ if (bodyStart >= 0) {
2843
+ return `${html.slice(0, openingBodyIndex)}<head>${markup}</head>${html.slice(openingBodyIndex)}`;
2844
+ }
2845
+ }
2846
+ return `<!DOCTYPE html><html><head>${markup}</head><body>${html}</body></html>`;
2847
+ };
2848
+ var streamChunkToString = (value, decoder) => typeof value === "string" ? value : decoder.decode(value, { stream: true });
2849
+ var flushSafePendingText = (controller, encoder, pending, lookbehind) => {
2850
+ if (pending.length <= lookbehind) {
2851
+ return pending;
2852
+ }
2853
+ const safeText = pending.slice(0, pending.length - lookbehind);
2854
+ controller.enqueue(encoder.encode(safeText));
2855
+ return pending.slice(-lookbehind);
2856
+ };
2857
+ var updateInjectedState = (consumed, injected, pending) => {
2858
+ if (consumed.done) {
2859
+ return { done: true, injected, pending };
2860
+ }
2861
+ return {
2862
+ done: false,
2863
+ injected: consumed.injected,
2864
+ pending: consumed.pending
2865
+ };
2866
+ };
2867
+ var readStreamChunk = async (reader) => {
2868
+ const { done, value } = await reader.read();
2869
+ if (done || !value) {
2870
+ return { done, value: undefined };
2871
+ }
2872
+ return { done, value };
2873
+ };
2874
+ var pipeStreamWithHeadInjection = (stream, markup) => {
2875
+ const encoder = new TextEncoder;
2876
+ const decoder = new TextDecoder;
2877
+ const lookbehind = CLOSING_HEAD_TAG.length - 1;
2878
+ const processPending = (controller, pending, injected) => {
2879
+ if (injected) {
2880
+ controller.enqueue(encoder.encode(pending));
2881
+ return { injected, pending: "" };
2882
+ }
2883
+ const headIndex = pending.indexOf(CLOSING_HEAD_TAG);
2884
+ if (headIndex >= 0) {
2885
+ const next = `${pending.slice(0, headIndex)}${markup}${pending.slice(headIndex)}`;
2886
+ controller.enqueue(encoder.encode(next));
2887
+ return { injected: true, pending: "" };
2888
+ }
2889
+ return {
2890
+ injected,
2891
+ pending: flushSafePendingText(controller, encoder, pending, lookbehind)
2892
+ };
2893
+ };
2894
+ const finishHeadInjectionStream = (controller, pending, injected) => {
2895
+ let finalPending = pending + decoder.decode();
2896
+ if (!injected) {
2897
+ finalPending = injectHeadMarkup(finalPending, markup);
2898
+ }
2899
+ if (finalPending.length > 0) {
2900
+ controller.enqueue(encoder.encode(finalPending));
2901
+ }
2902
+ controller.close();
2903
+ };
2904
+ const consumeHeadChunk = async (controller, reader, pending, injected) => {
2905
+ const { done, value } = await readStreamChunk(reader);
2906
+ if (done || !value) {
2907
+ return { done, injected, pending };
2908
+ }
2909
+ const processed = processPending(controller, pending + streamChunkToString(value, decoder), injected);
2910
+ return {
2911
+ done,
2912
+ injected: processed.injected,
2913
+ pending: processed.pending
2914
+ };
2915
+ };
2916
+ const runHeadInjectionLoop = async (controller, reader) => {
2917
+ const consumeNextHeadChunk = async (injected, pending) => {
2918
+ const consumed = await consumeHeadChunk(controller, reader, pending, injected);
2919
+ const nextState = updateInjectedState(consumed, injected, pending);
2920
+ if (nextState.done) {
2921
+ return { injected, pending };
2922
+ }
2923
+ return consumeNextHeadChunk(nextState.injected, nextState.pending);
2924
+ };
2925
+ return consumeNextHeadChunk(false, "");
2926
+ };
2927
+ return new ReadableStream({
2928
+ async start(controller) {
2929
+ const reader = stream.getReader();
2930
+ try {
2931
+ const { injected, pending } = await runHeadInjectionLoop(controller, reader);
2932
+ finishHeadInjectionStream(controller, pending, injected);
2933
+ } catch (error) {
2934
+ controller.error(error);
2935
+ }
2936
+ }
2937
+ });
2938
+ };
2939
+ var pipeStreamWithIslandMarkerDetection = (stream, markup) => {
2940
+ const encoder = new TextEncoder;
2941
+ const decoder = new TextDecoder;
2942
+ const lookbehind = Math.max(ISLAND_MARKER.length, BYTES_PER_KILOBYTE);
2943
+ const processPending = (controller, pending, injected) => {
2944
+ if (injected) {
2945
+ controller.enqueue(encoder.encode(pending));
2946
+ return { injected, pending: "" };
2947
+ }
2948
+ const markerIndex = pending.indexOf(ISLAND_MARKER);
2949
+ if (markerIndex >= 0) {
2950
+ const tagStart = pending.lastIndexOf("<", markerIndex);
2951
+ const injectAt = tagStart >= 0 ? tagStart : markerIndex;
2952
+ const next = `${pending.slice(0, injectAt)}${markup}${pending.slice(injectAt)}`;
2953
+ controller.enqueue(encoder.encode(next));
2954
+ return { injected: true, pending: "" };
2955
+ }
2956
+ return {
2957
+ injected,
2958
+ pending: flushSafePendingText(controller, encoder, pending, lookbehind)
2959
+ };
2960
+ };
2961
+ const finishIslandMarkerStream = (controller, pending) => {
2962
+ const finalPending = pending + decoder.decode();
2963
+ if (finalPending.length > 0) {
2964
+ controller.enqueue(encoder.encode(finalPending));
2965
+ }
2966
+ controller.close();
2967
+ };
2968
+ const consumeIslandChunk = async (controller, reader, pending, injected) => {
2969
+ const { done, value } = await readStreamChunk(reader);
2970
+ if (done || !value) {
2971
+ return { done, injected, pending };
2972
+ }
2973
+ const processed = processPending(controller, pending + streamChunkToString(value, decoder), injected);
2974
+ return {
2975
+ done,
2976
+ injected: processed.injected,
2977
+ pending: processed.pending
2978
+ };
2979
+ };
2980
+ const runIslandMarkerLoop = async (controller, reader) => {
2981
+ const consumeNextIslandChunk = async (injected, pending) => {
2982
+ const consumed = await consumeIslandChunk(controller, reader, pending, injected);
2983
+ const nextState = updateInjectedState(consumed, injected, pending);
2984
+ if (nextState.done) {
2985
+ return { injected, pending };
2986
+ }
2987
+ return consumeNextIslandChunk(nextState.injected, nextState.pending);
2988
+ };
2989
+ return consumeNextIslandChunk(false, "");
2990
+ };
2991
+ return new ReadableStream({
2992
+ async start(controller) {
2993
+ const reader = stream.getReader();
2994
+ try {
2995
+ const { pending } = await runIslandMarkerLoop(controller, reader);
2996
+ finishIslandMarkerStream(controller, pending);
2997
+ } catch (error) {
2998
+ controller.error(error);
2999
+ }
3000
+ }
3001
+ });
3002
+ };
3003
+ var htmlContainsIslands = (html) => html.includes(ISLAND_MARKER);
3004
+ var injectIslandPageContext = (html, options) => {
3005
+ const manifest = globalThis.__absoluteManifest;
3006
+ const hasIslands = options?.hasIslands ?? htmlContainsIslands(html);
3007
+ if (!manifest || !hasIslands) {
3008
+ return html;
3009
+ }
3010
+ if (html.includes(MANIFEST_MARKER) || html.includes(ISLAND_STATE_MARKER)) {
3011
+ return html;
3012
+ }
3013
+ return injectHeadMarkup(html, buildIslandsHeadMarkup(manifest));
3014
+ };
3015
+ var injectIslandPageContextStream = (stream, options) => {
3016
+ const manifest = globalThis.__absoluteManifest;
3017
+ if (!manifest)
3018
+ return stream;
3019
+ const markup = buildIslandsHeadMarkup(manifest);
3020
+ if (options?.hasIslands === true) {
3021
+ return pipeStreamWithHeadInjection(stream, markup);
3022
+ }
3023
+ if (options?.hasIslands === false) {
3024
+ return stream;
3025
+ }
3026
+ return pipeStreamWithIslandMarkerDetection(stream, markup);
3027
+ };
3028
+ var setCurrentIslandManifest = (manifest) => {
3029
+ globalThis.__absoluteManifest = manifest;
3030
+ };
3031
+
3032
+ // src/react/pageHandler.ts
3033
+ init_devRouteRegistrationCallsite();
3034
+
3035
+ // src/core/responseEnhancers.ts
3036
+ init_streamingSlots();
3037
+ var toResponse = async (responseLike) => responseLike;
3038
+ var cloneHeaders = (response) => {
3039
+ const headers = new Headers(response.headers);
3040
+ return headers;
3041
+ };
3042
+ var enhanceHtmlResponseWithStreamingSlots = (response, {
3043
+ nonce,
3044
+ onError,
3045
+ runtimePlacement,
3046
+ runtimePreludeScript,
3047
+ streamingSlots = [],
3048
+ policy
3049
+ } = {}) => {
3050
+ if (!response.body || streamingSlots.length === 0) {
3051
+ return response;
3052
+ }
3053
+ const body = appendStreamingSlotPatchesToStream(response.body, streamingSlots, {
3054
+ nonce,
3055
+ onError,
3056
+ policy,
3057
+ runtimePlacement,
3058
+ runtimePreludeScript
3059
+ });
3060
+ return new Response(body, {
3061
+ headers: cloneHeaders(response),
3062
+ status: response.status,
3063
+ statusText: response.statusText
3064
+ });
3065
+ };
3066
+ var withStreamingSlots = async (responseLike, options = {}) => enhanceHtmlResponseWithStreamingSlots(await toResponse(responseLike), options);
3067
+ var mergeStreamingSlots = (registered, explicit) => {
3068
+ const merged = new Map;
3069
+ for (const slot of registered)
3070
+ merged.set(slot.id, slot);
3071
+ for (const slot of explicit)
3072
+ merged.set(slot.id, slot);
3073
+ return [...merged.values()];
3074
+ };
3075
+ var withRegisteredStreamingSlots = async (renderResponse, options = {}) => {
3076
+ const { result, slots } = await runWithStreamingSlotRegistry(renderResponse);
3077
+ const explicit = options.streamingSlots ?? [];
3078
+ return withStreamingSlots(result, {
3079
+ ...options,
3080
+ streamingSlots: mergeStreamingSlots(slots, explicit)
3081
+ });
3082
+ };
3083
+
3084
+ // src/core/streamingSlotWarningScope.ts
3085
+ init_logger();
3086
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
3087
+ var STREAMING_SLOT_WARNING_STORAGE_KEY2 = Symbol.for("absolutejs.streamingSlotWarningAsyncLocalStorage");
3088
+ var isObjectRecord4 = (value) => Boolean(value) && typeof value === "object";
3089
+ var isAsyncLocalStorage3 = (value) => isObjectRecord4(value) && ("getStore" in value) && typeof value.getStore === "function" && ("run" in value) && typeof value.run === "function";
3090
+ var getWarningStorage = () => {
3091
+ const value = Reflect.get(globalThis, STREAMING_SLOT_WARNING_STORAGE_KEY2);
3092
+ if (value === null || typeof value === "undefined") {
3093
+ return;
3094
+ }
3095
+ return isAsyncLocalStorage3(value) ? value : undefined;
3096
+ };
3097
+ var ensureWarningStorage = () => {
3098
+ const existing = getWarningStorage();
3099
+ if (existing) {
3100
+ return existing;
3101
+ }
3102
+ const storage = new AsyncLocalStorage2;
3103
+ Reflect.set(globalThis, STREAMING_SLOT_WARNING_STORAGE_KEY2, storage);
3104
+ return storage;
3105
+ };
3106
+ var normalizeCallsitePath2 = (value) => value.replace(`${process.cwd()}/`, "").replace(process.cwd(), "").replace(/^\.\/+/, "");
3107
+ var formatWarningCallsite = (callsite) => {
3108
+ const match = callsite.match(/^(.*?)(:\d+:\d+)$/);
3109
+ if (!match) {
3110
+ return `\x1B[36m${callsite}\x1B[0m`;
3111
+ }
3112
+ return `\x1B[36m${match[1]}\x1B[33m${match[2]}\x1B[0m`;
3113
+ };
3114
+ var shouldIgnoreWarningFrame = (frame) => frame.includes("/node_modules/") || frame.includes("/dist/") || frame.includes("/src/react/pageHandler.") || frame.includes("/src/vue/pageHandler.") || frame.includes("/src/svelte/pageHandler.") || frame.includes("/src/angular/pageHandler.") || frame.includes("/src/core/streamingSlotWarningScope.");
3115
+ var getWarningLocation = (frame) => frame.match(/\((\/[^)]+:\d+:\d+)\)$/)?.[1] ?? frame.match(/at (\/[^ ]+:\d+:\d+)$/)?.[1];
3116
+ var extractCallsiteFromStack = (stack) => {
3117
+ const location = stack.split(`
3118
+ `).slice(1).map((line) => line.trim()).filter((frame) => !shouldIgnoreWarningFrame(frame)).map((frame) => getWarningLocation(frame)).find((frameLocation) => frameLocation !== undefined);
3119
+ return location ? normalizeCallsitePath2(location) : undefined;
3120
+ };
3121
+ var buildMissingCollectorWarning = (primitiveName, handlerCallsite) => `${primitiveName} rendered during SSR without streaming slot collection enabled. Add { collectStreamingSlots: true } to this page handler to enable out-of-order streaming for this route.${handlerCallsite ? ` Update ${formatWarningCallsite(handlerCallsite)}.` : ""}`;
3122
+ setStreamingSlotWarningController({
3123
+ maybeWarn: (primitiveName) => {
3124
+ const store = getWarningStorage()?.getStore();
3125
+ if (!store || store.hasWarned) {
3126
+ return;
3127
+ }
3128
+ store.hasWarned = true;
3129
+ logWarn(buildMissingCollectorWarning(primitiveName, store.handlerCallsite));
3130
+ }
3131
+ });
3132
+ var captureStreamingSlotWarningCallsite = () => {
3133
+ if (false) {}
3134
+ const { stack } = new Error;
3135
+ if (!stack) {
3136
+ return;
3137
+ }
3138
+ return extractCallsiteFromStack(stack);
3139
+ };
3140
+ var runWithStreamingSlotWarningScope = (task, metadata) => ensureWarningStorage().run({ handlerCallsite: metadata?.handlerCallsite, hasWarned: false }, task);
3141
+
3142
+ // src/react/pageHandler.ts
3143
+ init_ssrCache();
3144
+
3145
+ // src/utils/ssrErrorPage.ts
3146
+ var ssrErrorPage = (framework, error) => {
3147
+ const frameworkColors2 = {
3148
+ angular: "#dd0031",
3149
+ html: "#e34c26",
3150
+ htmx: "#1a365d",
3151
+ react: "#61dafb",
3152
+ svelte: "#ff3e00",
3153
+ vue: "#42b883"
3154
+ };
3155
+ const accent = frameworkColors2[framework] ?? "#94a3b8";
3156
+ const label = framework.charAt(0).toUpperCase() + framework.slice(1);
3157
+ const message = error instanceof Error ? error.message : String(error);
3158
+ return `<!DOCTYPE html>
3159
+ <html>
3160
+ <head>
3161
+ <meta charset="utf-8">
3162
+ <meta name="viewport" content="width=device-width, initial-scale=1">
3163
+ <title>SSR Error - AbsoluteJS</title>
3164
+ <style>
3165
+ *{margin:0;padding:0;box-sizing:border-box}
3166
+ body{min-height:100vh;background:linear-gradient(135deg,rgba(15,23,42,0.98) 0%,rgba(30,41,59,0.98) 100%);color:#e2e8f0;font-family:"JetBrains Mono","Fira Code",ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;font-size:14px;line-height:1.6;display:flex;align-items:flex-start;justify-content:center;padding:32px}
3167
+ .card{max-width:720px;width:100%;background:rgba(30,41,59,0.6);border:1px solid rgba(71,85,105,0.5);border-radius:16px;box-shadow:0 25px 50px -12px rgba(0,0,0,0.5),0 0 0 1px rgba(255,255,255,0.05);overflow:hidden}
3168
+ .header{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:20px 24px;background:rgba(15,23,42,0.5);border-bottom:1px solid rgba(71,85,105,0.4)}
3169
+ .brand{font-weight:700;font-size:20px;color:#fff;letter-spacing:-0.02em}
3170
+ .badge{padding:5px 10px;border-radius:8px;font-size:12px;font-weight:600;background:${accent};color:#fff;opacity:0.95;box-shadow:0 2px 4px rgba(0,0,0,0.2)}
3171
+ .kind{color:#94a3b8;font-size:13px;font-weight:500}
3172
+ .content{padding:24px}
3173
+ .label{font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.08em;color:#94a3b8;margin-bottom:8px}
3174
+ .message{margin:0;padding:16px 20px;background:rgba(239,68,68,0.12);border:1px solid rgba(239,68,68,0.25);border-radius:10px;overflow-x:auto;white-space:pre-wrap;word-break:break-word;color:#fca5a5;font-size:13px;line-height:1.5}
3175
+ .hint{margin-top:20px;padding:12px 20px;background:rgba(71,85,105,0.3);border-radius:10px;border:1px solid rgba(71,85,105,0.4);color:#cbd5e1;font-size:13px}
3176
+ </style>
3177
+ </head>
3178
+ <body>
3179
+ <div class="card">
3180
+ <div class="header">
3181
+ <div style="display:flex;align-items:center;gap:12px">
3182
+ <span class="brand">AbsoluteJS</span>
3183
+ <span class="badge">${label}</span>
3184
+ </div>
3185
+ <span class="kind">Server Render Error</span>
3186
+ </div>
3187
+ <div class="content">
3188
+ <div class="label">What went wrong</div>
3189
+ <pre class="message">${message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")}</pre>
3190
+ <div class="hint">A component threw during server-side rendering. Check the terminal for the full stack trace.</div>
3191
+ </div>
3192
+ </div>
3193
+ </body>
3194
+ </html>`;
3195
+ };
3196
+
3197
+ // src/utils/resolveConvention.ts
3198
+ import { basename } from "path";
3199
+ var CONVENTIONS_KEY = "__absoluteConventions";
3200
+ var isConventionsMap = (value) => Boolean(value) && typeof value === "object";
3201
+ var getMap = () => {
3202
+ const value = Reflect.get(globalThis, CONVENTIONS_KEY);
3203
+ if (isConventionsMap(value))
3204
+ return value;
3205
+ const empty = {};
3206
+ return empty;
3207
+ };
3208
+ var derivePageName = (pagePath) => {
3209
+ const base = basename(pagePath);
3210
+ const dotIndex = base.indexOf(".");
3211
+ const name = dotIndex > 0 ? base.slice(0, dotIndex) : base;
3212
+ return toPascal(name);
3213
+ };
3214
+ var normalizeConventionPageName = (name) => toPascal(name).replace(/\d+$/, "");
3215
+ var resolveErrorConventionPath = (framework, pageName) => {
3216
+ const conventions = getMap()[framework];
3217
+ if (!conventions)
3218
+ return;
3219
+ const exact = conventions.pages?.[pageName]?.error;
3220
+ if (exact)
3221
+ return exact;
3222
+ const normalizedPageName = normalizeConventionPageName(pageName);
3223
+ for (const [candidate, page] of Object.entries(conventions.pages ?? {})) {
3224
+ if (normalizeConventionPageName(candidate) === normalizedPageName) {
3225
+ return page.error ?? conventions.defaults?.error;
3226
+ }
3227
+ }
3228
+ return conventions.defaults?.error;
3229
+ };
3230
+ var resolveNotFoundConventionPath = (framework) => getMap()[framework]?.defaults?.notFound;
3231
+ var hasErrorConvention = (framework) => {
3232
+ const conventions = getMap()[framework];
3233
+ if (!conventions)
3234
+ return false;
3235
+ if (conventions.defaults?.error)
3236
+ return true;
3237
+ return Object.values(conventions.pages ?? {}).some((page) => Boolean(page.error));
3238
+ };
3239
+ var setConventions = (map) => {
3240
+ Reflect.set(globalThis, CONVENTIONS_KEY, map);
3241
+ };
3242
+ var isDev = () => true;
3243
+ var buildErrorProps = (error) => {
3244
+ const message = error instanceof Error ? error.message : String(error);
3245
+ const stack = isDev() && error instanceof Error ? error.stack : undefined;
3246
+ return { error: { message, stack } };
3247
+ };
3248
+ var renderReactError = async (conventionPath, errorProps) => {
3249
+ const { createElement } = await import("react");
3250
+ const { renderToReadableStream } = await import("react-dom/server");
3251
+ const mod = await import(conventionPath);
3252
+ const [firstKey] = Object.keys(mod);
3253
+ const ErrorComponent = mod.default ?? (firstKey ? mod[firstKey] : undefined);
3254
+ const element = createElement(ErrorComponent, errorProps);
3255
+ const stream = await renderToReadableStream(element);
3256
+ return new Response(stream, {
3257
+ headers: { "Content-Type": "text/html" },
3258
+ status: 500
3259
+ });
3260
+ };
3261
+ var renderSvelteError = async (conventionPath, errorProps) => {
3262
+ const { render } = await import("svelte/server");
3263
+ const mod = await import(conventionPath);
3264
+ const ErrorComponent = mod.default;
3265
+ const { head, body } = render(ErrorComponent, {
3266
+ props: errorProps
3267
+ });
3268
+ const html = `<!DOCTYPE html><html><head>${head}</head><body>${body}</body></html>`;
3269
+ return new Response(html, {
3270
+ headers: { "Content-Type": "text/html" },
3271
+ status: 500
3272
+ });
3273
+ };
3274
+ var unescapeVueStyles = (ssrBody) => {
3275
+ let styles = "";
3276
+ const body = ssrBody.replace(/<style>([\s\S]*?)<\/style>/g, (_, css) => {
3277
+ styles += `<style>${css.replace(/&quot;/g, '"').replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">")}</style>`;
3278
+ return "";
3279
+ });
3280
+ return { body, styles };
3281
+ };
3282
+ var renderVueError = async (conventionPath, errorProps) => {
3283
+ const { createSSRApp, h } = await import("vue");
3284
+ const { renderToString } = await import("vue/server-renderer");
3285
+ const mod = await import(conventionPath);
3286
+ const ErrorComponent = mod.default;
3287
+ const app = createSSRApp({
3288
+ render: () => h(ErrorComponent, errorProps)
3289
+ });
3290
+ const rawBody = await renderToString(app);
3291
+ const { styles, body } = unescapeVueStyles(rawBody);
3292
+ const html = `<!DOCTYPE html><html><head>${styles}</head><body><div id="root">${body}</div></body></html>`;
3293
+ return new Response(html, {
3294
+ headers: { "Content-Type": "text/html" },
3295
+ status: 500
3296
+ });
3297
+ };
3298
+ var renderAngularError = async (conventionPath, errorProps) => {
3299
+ const mod = await import(conventionPath);
3300
+ const renderError = mod.default ?? mod.renderError;
3301
+ if (typeof renderError !== "function")
3302
+ return null;
3303
+ const html = renderError(errorProps);
3304
+ return new Response(html, {
3305
+ headers: { "Content-Type": "text/html" },
3306
+ status: 500
3307
+ });
3308
+ };
3309
+ var logConventionRenderError = (framework, label, renderError) => {
3310
+ const message = renderError instanceof Error ? renderError.message : "";
3311
+ if (message.includes("Cannot find module") || message.includes("Cannot find package") || message.includes("not found in module")) {
3312
+ console.error(`[SSR] Convention ${label} page for ${framework} failed: missing framework package. Ensure the ${framework} runtime is installed (e.g. bun add ${framework === "react" ? "react react-dom" : framework}).`);
3313
+ return;
3314
+ }
3315
+ console.error(`[SSR] Failed to render ${framework} convention ${label} page:`, renderError);
3316
+ };
3317
+ var ERROR_RENDERERS = {
3318
+ angular: renderAngularError,
3319
+ react: renderReactError,
3320
+ svelte: renderSvelteError,
3321
+ vue: renderVueError
3322
+ };
3323
+ var renderConventionError = async (framework, pageName, error) => {
3324
+ let conventionPath = resolveErrorConventionPath(framework, pageName);
3325
+ if (!conventionPath && error instanceof Error && error.stack) {
3326
+ for (const match of error.stack.matchAll(/^\s*at\s+([A-Za-z_$][\w$]*)/gm)) {
3327
+ const candidate = match[1];
3328
+ if (!candidate)
3329
+ continue;
3330
+ conventionPath = resolveErrorConventionPath(framework, candidate);
3331
+ if (conventionPath)
3332
+ break;
3333
+ }
3334
+ }
3335
+ if (!conventionPath)
3336
+ return null;
3337
+ const errorProps = buildErrorProps(error);
3338
+ const renderer = ERROR_RENDERERS[framework];
3339
+ if (!renderer)
3340
+ return null;
3341
+ try {
3342
+ return await renderer(conventionPath, errorProps);
3343
+ } catch (renderError) {
3344
+ logConventionRenderError(framework, "error", renderError);
3345
+ }
3346
+ return null;
3347
+ };
3348
+ var renderReactNotFound = async (conventionPath) => {
3349
+ const { createElement } = await import("react");
3350
+ const { renderToReadableStream } = await import("react-dom/server");
3351
+ const mod = await import(conventionPath);
3352
+ const [nfKey] = Object.keys(mod);
3353
+ const NotFoundComponent = mod.default ?? (nfKey ? mod[nfKey] : undefined);
3354
+ const element = createElement(NotFoundComponent);
3355
+ const stream = await renderToReadableStream(element);
3356
+ return new Response(stream, {
3357
+ headers: { "Content-Type": "text/html" },
3358
+ status: 404
3359
+ });
3360
+ };
3361
+ var renderSvelteNotFound = async (conventionPath) => {
3362
+ const { render } = await import("svelte/server");
3363
+ const mod = await import(conventionPath);
3364
+ const NotFoundComponent = mod.default;
3365
+ const { head, body } = render(NotFoundComponent);
3366
+ const html = `<!DOCTYPE html><html><head>${head}</head><body>${body}</body></html>`;
3367
+ return new Response(html, {
3368
+ headers: { "Content-Type": "text/html" },
3369
+ status: 404
3370
+ });
3371
+ };
3372
+ var renderVueNotFound = async (conventionPath) => {
3373
+ const { createSSRApp, h } = await import("vue");
3374
+ const { renderToString } = await import("vue/server-renderer");
3375
+ const mod = await import(conventionPath);
3376
+ const NotFoundComponent = mod.default;
3377
+ const app = createSSRApp({
3378
+ render: () => h(NotFoundComponent)
3379
+ });
3380
+ const rawBody = await renderToString(app);
3381
+ const { styles, body } = unescapeVueStyles(rawBody);
3382
+ const html = `<!DOCTYPE html><html><head>${styles}</head><body><div id="root">${body}</div></body></html>`;
3383
+ return new Response(html, {
3384
+ headers: { "Content-Type": "text/html" },
3385
+ status: 404
3386
+ });
3387
+ };
3388
+ var renderAngularNotFound = async (conventionPath) => {
3389
+ const mod = await import(conventionPath);
3390
+ const renderNotFound = mod.default ?? mod.renderNotFound;
3391
+ if (typeof renderNotFound !== "function")
3392
+ return null;
3393
+ const html = renderNotFound();
3394
+ return new Response(html, {
3395
+ headers: { "Content-Type": "text/html" },
3396
+ status: 404
3397
+ });
3398
+ };
3399
+ var NOT_FOUND_RENDERERS = {
3400
+ angular: renderAngularNotFound,
3401
+ react: renderReactNotFound,
3402
+ svelte: renderSvelteNotFound,
3403
+ vue: renderVueNotFound
3404
+ };
3405
+ var renderConventionNotFound = async (framework) => {
3406
+ const conventionPath = resolveNotFoundConventionPath(framework);
3407
+ if (!conventionPath)
3408
+ return null;
3409
+ const renderer = NOT_FOUND_RENDERERS[framework];
3410
+ if (!renderer)
3411
+ return null;
3412
+ try {
3413
+ return await renderer(conventionPath);
3414
+ } catch (renderError) {
3415
+ logConventionRenderError(framework, "not-found", renderError);
3416
+ }
3417
+ return null;
3418
+ };
3419
+ var NOT_FOUND_PRIORITY = [
3420
+ "react",
3421
+ "svelte",
3422
+ "vue",
3423
+ "angular"
3424
+ ];
3425
+ var renderFirstNotFound = async () => {
3426
+ const renderNext = async (frameworks) => {
3427
+ const [framework, ...remaining] = frameworks;
3428
+ if (!framework) {
3429
+ return null;
3430
+ }
3431
+ if (!getMap()[framework]?.defaults?.notFound) {
3432
+ return renderNext(remaining);
3433
+ }
3434
+ const response = await renderConventionNotFound(framework);
3435
+ if (response) {
3436
+ return response;
3437
+ }
3438
+ return renderNext(remaining);
3439
+ };
3440
+ return renderNext(NOT_FOUND_PRIORITY);
3441
+ };
3442
+
3443
+ // src/react/pageHandler.ts
3444
+ var buildRefreshSetup = () => {
3445
+ if (false) {}
3446
+ return "window.__REFRESH_BUFFER__=[];" + "window.$RefreshReg$=function(t,i){window.__REFRESH_BUFFER__.push([t,i])};" + "window.$RefreshSig$=function(){return function(t){return t}};";
3447
+ };
3448
+ var buildDirtyResponse = (index, maybeProps) => {
3449
+ const propsScript = maybeProps ? `window.__INITIAL_PROPS__=${JSON.stringify(maybeProps)};` : "";
3450
+ const dirtyFlag = "window.__SSR_DIRTY__=true;";
3451
+ const refreshSetup = buildRefreshSetup();
3452
+ const inlineScript = `${propsScript}${dirtyFlag}${refreshSetup}`;
3453
+ const html = `<!DOCTYPE html><html><head></head><body>` + `<script>${inlineScript}</script>` + `<script type="module" src="${index}"></script>` + `</body></html>`;
3454
+ return new Response(html, {
3455
+ headers: { "Content-Type": "text/html" }
3456
+ });
3457
+ };
3458
+ var handleReactPageRequest = async (input) => {
3459
+ const Page = input.Page;
3460
+ const resolvedIndex = input.index;
3461
+ const options = input;
3462
+ const maybeProps = input.props;
3463
+ const pageName = Page.name || Page.displayName || "";
3464
+ if (isSsrCacheDirty("react")) {
3465
+ return buildDirtyResponse(resolvedIndex, maybeProps);
3466
+ }
3467
+ try {
3468
+ const handlerCallsite = options?.collectStreamingSlots === true ? undefined : getCurrentRouteRegistrationCallsite() ?? captureStreamingSlotWarningCallsite();
3469
+ const renderPageResponse = async () => {
3470
+ const { createElement } = await import("react");
3471
+ const { renderToReadableStream } = await import("react-dom/server");
3472
+ const element = maybeProps !== undefined ? createElement(Page, maybeProps) : createElement(Page);
3473
+ const propsScript = maybeProps ? `window.__INITIAL_PROPS__=${JSON.stringify(maybeProps)};` : "";
3474
+ const refreshSetup = buildRefreshSetup();
3475
+ const stream = await renderToReadableStream(element, {
3476
+ bootstrapModules: [resolvedIndex],
3477
+ bootstrapScriptContent: propsScript + refreshSetup || undefined,
3478
+ onError(error) {
3479
+ console.error("[SSR] React streaming error:", error);
3480
+ }
3481
+ });
3482
+ const htmlStream = injectIslandPageContextStream(stream);
3483
+ if (resolveErrorConventionPath("react", pageName) || hasErrorConvention("react")) {
3484
+ const html = await new Response(htmlStream).text();
3485
+ return new Response(html, {
3486
+ headers: { "Content-Type": "text/html" }
3487
+ });
3488
+ }
3489
+ return new Response(htmlStream, {
3490
+ headers: { "Content-Type": "text/html" }
3491
+ });
3492
+ };
3493
+ return await runWithStreamingSlotWarningScope(() => options?.collectStreamingSlots === true ? withRegisteredStreamingSlots(renderPageResponse, options) : renderPageResponse(), { handlerCallsite });
3494
+ } catch (error) {
3495
+ console.error("[SSR] React render error:", error);
3496
+ const conventionResponse = await renderConventionError("react", pageName, error);
3497
+ if (conventionResponse)
3498
+ return conventionResponse;
3499
+ return new Response(ssrErrorPage("react", error), {
3500
+ headers: { "Content-Type": "text/html" },
3501
+ status: 500
3502
+ });
3503
+ }
3504
+ };
38
3505
  // src/react/Island.tsx
3506
+ init_islandMarkupAttributes();
3507
+ init_renderIslandMarkup();
39
3508
  import { jsxDEV } from "react/jsx-dev-runtime";
40
3509
  var Island = async (props) => {
41
3510
  if (typeof window !== "undefined") {
@@ -51,6 +3520,8 @@ var Island = async (props) => {
51
3520
  }, undefined, false, undefined, this);
52
3521
  };
53
3522
  // src/react/createIsland.tsx
3523
+ init_islandMarkupAttributes();
3524
+ init_renderIslandMarkup();
54
3525
  import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
55
3526
  var createTypedIsland = (registry) => {
56
3527
  const Island2 = async (props) => {
@@ -68,6 +3539,126 @@ var createTypedIsland = (registry) => {
68
3539
  };
69
3540
  return Island2;
70
3541
  };
3542
+ // src/react/hooks/useIslandStore.ts
3543
+ import { useSyncExternalStore } from "react";
3544
+
3545
+ // node_modules/zustand/esm/vanilla.mjs
3546
+ var createStoreImpl = (createState) => {
3547
+ let state;
3548
+ const listeners = /* @__PURE__ */ new Set;
3549
+ const setState = (partial, replace) => {
3550
+ const nextState = typeof partial === "function" ? partial(state) : partial;
3551
+ if (!Object.is(nextState, state)) {
3552
+ const previousState = state;
3553
+ state = (replace != null ? replace : typeof nextState !== "object" || nextState === null) ? nextState : Object.assign({}, state, nextState);
3554
+ listeners.forEach((listener) => listener(state, previousState));
3555
+ }
3556
+ };
3557
+ const getState = () => state;
3558
+ const getInitialState = () => initialState;
3559
+ const subscribe = (listener) => {
3560
+ listeners.add(listener);
3561
+ return () => listeners.delete(listener);
3562
+ };
3563
+ const api = { setState, getState, getInitialState, subscribe };
3564
+ const initialState = state = createState(setState, getState, api);
3565
+ return api;
3566
+ };
3567
+ var createStore = (createState) => createState ? createStoreImpl(createState) : createStoreImpl;
3568
+
3569
+ // node_modules/zustand/esm/middleware.mjs
3570
+ function combine(initialState, create) {
3571
+ return (...args) => Object.assign({}, initialState, create(...args));
3572
+ }
3573
+
3574
+ // src/client/islandStore.ts
3575
+ var getIslandStoreSnapshot = () => {
3576
+ globalThis.__ABS_ISLAND_STATE__ ??= {};
3577
+ return globalThis.__ABS_ISLAND_STATE__;
3578
+ };
3579
+ var getIslandStores = () => {
3580
+ globalThis.__ABS_ISLAND_STORES__ ??= new Map;
3581
+ return globalThis.__ABS_ISLAND_STORES__;
3582
+ };
3583
+ var isSerializableValue = (value) => typeof value !== "function" && value !== undefined;
3584
+ var toSerializableState = (state) => Object.fromEntries(Object.entries(state).filter(([, value]) => isSerializableValue(value)));
3585
+ var applySnapshot = (store, snapshot) => {
3586
+ if (!snapshot) {
3587
+ return;
3588
+ }
3589
+ store.setState({
3590
+ ...store.getState(),
3591
+ ...snapshot
3592
+ });
3593
+ };
3594
+ var getPeerStores = (storeInstances, ownerStore) => [...storeInstances].filter((peer) => peer.store !== ownerStore);
3595
+ var syncIslandSnapshot = (storeId, state, storeInstances, ownerStore) => {
3596
+ const nextSnapshot = toSerializableState(state);
3597
+ getIslandStoreSnapshot()[storeId] = nextSnapshot;
3598
+ for (const peerStore of getPeerStores(storeInstances, ownerStore)) {
3599
+ peerStore.applyExternalSnapshot(nextSnapshot);
3600
+ }
3601
+ };
3602
+ var createIslandStore = (storeId, initialState, createState) => {
3603
+ const store = createStore(combine(initialState, createState));
3604
+ const stores = getIslandStores();
3605
+ const storeInstances = stores.get(storeId) ?? new Set;
3606
+ const initialSnapshot = getIslandStoreSnapshot()[storeId];
3607
+ applySnapshot(store, initialSnapshot);
3608
+ let isApplyingExternalSnapshot = false;
3609
+ const applyExternalSnapshot = (snapshot) => {
3610
+ isApplyingExternalSnapshot = true;
3611
+ applySnapshot(store, snapshot);
3612
+ };
3613
+ storeInstances.add({
3614
+ applyExternalSnapshot,
3615
+ store
3616
+ });
3617
+ stores.set(storeId, storeInstances);
3618
+ syncIslandSnapshot(storeId, store.getState(), storeInstances, store);
3619
+ store.subscribe((state) => {
3620
+ if (isApplyingExternalSnapshot) {
3621
+ isApplyingExternalSnapshot = false;
3622
+ return;
3623
+ }
3624
+ syncIslandSnapshot(storeId, state, storeInstances, store);
3625
+ });
3626
+ return store;
3627
+ };
3628
+ var getIslandStoreServerSnapshot = (store, selector) => selector(store.getInitialState());
3629
+ var applySnapshotToStoreInstances = (storeId, instances, snapshot) => {
3630
+ for (const instance of instances) {
3631
+ instance.applyExternalSnapshot(snapshot[storeId] ?? {});
3632
+ }
3633
+ };
3634
+ var initializeIslandStores = (state) => {
3635
+ const currentSnapshot = getIslandStoreSnapshot();
3636
+ const nextSnapshot = {
3637
+ ...state,
3638
+ ...currentSnapshot
3639
+ };
3640
+ globalThis.__ABS_ISLAND_STATE__ = nextSnapshot;
3641
+ for (const [storeId, store] of getIslandStores()) {
3642
+ applySnapshotToStoreInstances(storeId, store, nextSnapshot);
3643
+ }
3644
+ };
3645
+ var readIslandStore = (store, selector) => selector(store.getState());
3646
+ var subscribeIslandStore = (store, selector, listener) => {
3647
+ let currentSelection = selector(store.getState());
3648
+ return store.subscribe((state) => {
3649
+ const nextSelection = selector(state);
3650
+ if (Object.is(nextSelection, currentSelection)) {
3651
+ return;
3652
+ }
3653
+ currentSelection = nextSelection;
3654
+ listener(nextSelection);
3655
+ });
3656
+ };
3657
+
3658
+ // src/react/hooks/useIslandStore.ts
3659
+ var useIslandStore = (store, selector) => useSyncExternalStore((listener) => subscribeIslandStore(store, selector, () => {
3660
+ listener();
3661
+ }), () => readIslandStore(store, selector), () => getIslandStoreServerSnapshot(store, selector));
71
3662
  export {
72
3663
  useIslandStore,
73
3664
  handleReactPageRequest,
@@ -75,5 +3666,5 @@ export {
75
3666
  Island
76
3667
  };
77
3668
 
78
- //# debugId=DA042BAA69FAC61364756E2164756E21
3669
+ //# debugId=3CAE937472B4618264756E2164756E21
79
3670
  //# sourceMappingURL=index.js.map