alepha 0.15.1 → 0.15.3

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 (523) hide show
  1. package/README.md +68 -80
  2. package/dist/api/audits/index.d.ts +10 -33
  3. package/dist/api/audits/index.d.ts.map +1 -1
  4. package/dist/api/audits/index.js +10 -33
  5. package/dist/api/audits/index.js.map +1 -1
  6. package/dist/api/files/index.d.ts +10 -3
  7. package/dist/api/files/index.d.ts.map +1 -1
  8. package/dist/api/files/index.js +10 -3
  9. package/dist/api/files/index.js.map +1 -1
  10. package/dist/api/jobs/index.d.ts +162 -155
  11. package/dist/api/jobs/index.d.ts.map +1 -1
  12. package/dist/api/jobs/index.js +10 -3
  13. package/dist/api/jobs/index.js.map +1 -1
  14. package/dist/api/keys/index.d.ts +413 -0
  15. package/dist/api/keys/index.d.ts.map +1 -0
  16. package/dist/api/keys/index.js +476 -0
  17. package/dist/api/keys/index.js.map +1 -0
  18. package/dist/api/notifications/index.d.ts +10 -4
  19. package/dist/api/notifications/index.d.ts.map +1 -1
  20. package/dist/api/notifications/index.js +10 -4
  21. package/dist/api/notifications/index.js.map +1 -1
  22. package/dist/api/parameters/index.d.ts +43 -50
  23. package/dist/api/parameters/index.d.ts.map +1 -1
  24. package/dist/api/parameters/index.js +30 -37
  25. package/dist/api/parameters/index.js.map +1 -1
  26. package/dist/api/users/index.d.ts +1081 -760
  27. package/dist/api/users/index.d.ts.map +1 -1
  28. package/dist/api/users/index.js +2539 -218
  29. package/dist/api/users/index.js.map +1 -1
  30. package/dist/api/verifications/index.d.ts +138 -132
  31. package/dist/api/verifications/index.d.ts.map +1 -1
  32. package/dist/api/verifications/index.js +12 -4
  33. package/dist/api/verifications/index.js.map +1 -1
  34. package/dist/batch/index.d.ts +20 -40
  35. package/dist/batch/index.d.ts.map +1 -1
  36. package/dist/batch/index.js +31 -44
  37. package/dist/batch/index.js.map +1 -1
  38. package/dist/bucket/index.d.ts +440 -8
  39. package/dist/bucket/index.d.ts.map +1 -1
  40. package/dist/bucket/index.js +1861 -12
  41. package/dist/bucket/index.js.map +1 -1
  42. package/dist/cache/core/index.d.ts +179 -7
  43. package/dist/cache/core/index.d.ts.map +1 -1
  44. package/dist/cache/core/index.js +213 -7
  45. package/dist/cache/core/index.js.map +1 -1
  46. package/dist/cache/redis/index.d.ts +1 -0
  47. package/dist/cache/redis/index.d.ts.map +1 -1
  48. package/dist/cache/redis/index.js +4 -0
  49. package/dist/cache/redis/index.js.map +1 -1
  50. package/dist/cli/index.d.ts +638 -5645
  51. package/dist/cli/index.d.ts.map +1 -1
  52. package/dist/cli/index.js +2550 -368
  53. package/dist/cli/index.js.map +1 -1
  54. package/dist/command/index.d.ts +203 -45
  55. package/dist/command/index.d.ts.map +1 -1
  56. package/dist/command/index.js +2060 -71
  57. package/dist/command/index.js.map +1 -1
  58. package/dist/core/index.browser.js +70 -40
  59. package/dist/core/index.browser.js.map +1 -1
  60. package/dist/core/index.d.ts +34 -13
  61. package/dist/core/index.d.ts.map +1 -1
  62. package/dist/core/index.js +90 -40
  63. package/dist/core/index.js.map +1 -1
  64. package/dist/core/index.native.js +70 -40
  65. package/dist/core/index.native.js.map +1 -1
  66. package/dist/datetime/index.d.ts +15 -0
  67. package/dist/datetime/index.d.ts.map +1 -1
  68. package/dist/datetime/index.js +15 -0
  69. package/dist/datetime/index.js.map +1 -1
  70. package/dist/email/index.d.ts +323 -20
  71. package/dist/email/index.d.ts.map +1 -1
  72. package/dist/email/index.js +1857 -7
  73. package/dist/email/index.js.map +1 -1
  74. package/dist/fake/index.d.ts +90 -8
  75. package/dist/fake/index.d.ts.map +1 -1
  76. package/dist/fake/index.js +91 -20
  77. package/dist/fake/index.js.map +1 -1
  78. package/dist/lock/core/index.d.ts +11 -4
  79. package/dist/lock/core/index.d.ts.map +1 -1
  80. package/dist/lock/core/index.js +11 -4
  81. package/dist/lock/core/index.js.map +1 -1
  82. package/dist/logger/index.d.ts +17 -66
  83. package/dist/logger/index.d.ts.map +1 -1
  84. package/dist/logger/index.js +14 -63
  85. package/dist/logger/index.js.map +1 -1
  86. package/dist/mcp/index.d.ts +10 -30
  87. package/dist/mcp/index.d.ts.map +1 -1
  88. package/dist/mcp/index.js +12 -35
  89. package/dist/mcp/index.js.map +1 -1
  90. package/dist/orm/index.browser.js +3 -3
  91. package/dist/orm/index.browser.js.map +1 -1
  92. package/dist/orm/index.bun.js +39 -20
  93. package/dist/orm/index.bun.js.map +1 -1
  94. package/dist/orm/index.d.ts +517 -540
  95. package/dist/orm/index.d.ts.map +1 -1
  96. package/dist/orm/index.js +58 -71
  97. package/dist/orm/index.js.map +1 -1
  98. package/dist/queue/core/index.d.ts +18 -10
  99. package/dist/queue/core/index.d.ts.map +1 -1
  100. package/dist/queue/core/index.js +14 -6
  101. package/dist/queue/core/index.js.map +1 -1
  102. package/dist/react/auth/index.browser.js +108 -0
  103. package/dist/react/auth/index.browser.js.map +1 -0
  104. package/dist/react/auth/index.d.ts +100 -0
  105. package/dist/react/auth/index.d.ts.map +1 -0
  106. package/dist/react/auth/index.js +145 -0
  107. package/dist/react/auth/index.js.map +1 -0
  108. package/dist/react/core/index.d.ts +469 -0
  109. package/dist/react/core/index.d.ts.map +1 -0
  110. package/dist/react/core/index.js +464 -0
  111. package/dist/react/core/index.js.map +1 -0
  112. package/dist/react/form/index.d.ts +232 -0
  113. package/dist/react/form/index.d.ts.map +1 -0
  114. package/dist/react/form/index.js +432 -0
  115. package/dist/react/form/index.js.map +1 -0
  116. package/dist/react/head/index.browser.js +423 -0
  117. package/dist/react/head/index.browser.js.map +1 -0
  118. package/dist/react/head/index.d.ts +288 -0
  119. package/dist/react/head/index.d.ts.map +1 -0
  120. package/dist/react/head/index.js +465 -0
  121. package/dist/react/head/index.js.map +1 -0
  122. package/dist/react/i18n/index.d.ts +175 -0
  123. package/dist/react/i18n/index.d.ts.map +1 -0
  124. package/dist/react/i18n/index.js +224 -0
  125. package/dist/react/i18n/index.js.map +1 -0
  126. package/dist/react/router/index.browser.js +1974 -0
  127. package/dist/react/router/index.browser.js.map +1 -0
  128. package/dist/react/router/index.d.ts +1956 -0
  129. package/dist/react/router/index.d.ts.map +1 -0
  130. package/dist/react/router/index.js +4722 -0
  131. package/dist/react/router/index.js.map +1 -0
  132. package/dist/react/websocket/index.d.ts +117 -0
  133. package/dist/react/websocket/index.d.ts.map +1 -0
  134. package/dist/react/websocket/index.js +107 -0
  135. package/dist/react/websocket/index.js.map +1 -0
  136. package/dist/redis/index.bun.js +4 -0
  137. package/dist/redis/index.bun.js.map +1 -1
  138. package/dist/redis/index.d.ts +41 -44
  139. package/dist/redis/index.d.ts.map +1 -1
  140. package/dist/redis/index.js +16 -25
  141. package/dist/redis/index.js.map +1 -1
  142. package/dist/retry/index.d.ts +11 -2
  143. package/dist/retry/index.d.ts.map +1 -1
  144. package/dist/retry/index.js +11 -2
  145. package/dist/retry/index.js.map +1 -1
  146. package/dist/scheduler/index.d.ts +11 -2
  147. package/dist/scheduler/index.d.ts.map +1 -1
  148. package/dist/scheduler/index.js +11 -2
  149. package/dist/scheduler/index.js.map +1 -1
  150. package/dist/security/index.d.ts +140 -49
  151. package/dist/security/index.d.ts.map +1 -1
  152. package/dist/security/index.js +164 -32
  153. package/dist/security/index.js.map +1 -1
  154. package/dist/server/auth/index.d.ts +12 -7
  155. package/dist/server/auth/index.d.ts.map +1 -1
  156. package/dist/server/auth/index.js +12 -7
  157. package/dist/server/auth/index.js.map +1 -1
  158. package/dist/server/cache/index.d.ts +7 -22
  159. package/dist/server/cache/index.d.ts.map +1 -1
  160. package/dist/server/cache/index.js +7 -22
  161. package/dist/server/cache/index.js.map +1 -1
  162. package/dist/server/compress/index.d.ts +10 -2
  163. package/dist/server/compress/index.d.ts.map +1 -1
  164. package/dist/server/compress/index.js +10 -2
  165. package/dist/server/compress/index.js.map +1 -1
  166. package/dist/server/cookies/index.d.ts +40 -16
  167. package/dist/server/cookies/index.d.ts.map +1 -1
  168. package/dist/server/cookies/index.js +7 -5
  169. package/dist/server/cookies/index.js.map +1 -1
  170. package/dist/server/core/index.d.ts +124 -23
  171. package/dist/server/core/index.d.ts.map +1 -1
  172. package/dist/server/core/index.js +231 -14
  173. package/dist/server/core/index.js.map +1 -1
  174. package/dist/server/cors/index.d.ts +13 -23
  175. package/dist/server/cors/index.d.ts.map +1 -1
  176. package/dist/server/cors/index.js +7 -21
  177. package/dist/server/cors/index.js.map +1 -1
  178. package/dist/server/health/index.d.ts +8 -2
  179. package/dist/server/health/index.d.ts.map +1 -1
  180. package/dist/server/health/index.js +8 -2
  181. package/dist/server/health/index.js.map +1 -1
  182. package/dist/server/helmet/index.d.ts +11 -3
  183. package/dist/server/helmet/index.d.ts.map +1 -1
  184. package/dist/server/helmet/index.js +11 -3
  185. package/dist/server/helmet/index.js.map +1 -1
  186. package/dist/server/links/index.d.ts +11 -6
  187. package/dist/server/links/index.d.ts.map +1 -1
  188. package/dist/server/links/index.js +11 -6
  189. package/dist/server/links/index.js.map +1 -1
  190. package/dist/server/metrics/index.d.ts +10 -3
  191. package/dist/server/metrics/index.d.ts.map +1 -1
  192. package/dist/server/metrics/index.js +10 -3
  193. package/dist/server/metrics/index.js.map +1 -1
  194. package/dist/server/multipart/index.d.ts +9 -3
  195. package/dist/server/multipart/index.d.ts.map +1 -1
  196. package/dist/server/multipart/index.js +9 -3
  197. package/dist/server/multipart/index.js.map +1 -1
  198. package/dist/server/proxy/index.d.ts +8 -2
  199. package/dist/server/proxy/index.d.ts.map +1 -1
  200. package/dist/server/proxy/index.js +8 -2
  201. package/dist/server/proxy/index.js.map +1 -1
  202. package/dist/server/rate-limit/index.d.ts +30 -35
  203. package/dist/server/rate-limit/index.d.ts.map +1 -1
  204. package/dist/server/rate-limit/index.js +18 -55
  205. package/dist/server/rate-limit/index.js.map +1 -1
  206. package/dist/server/static/index.d.ts +137 -4
  207. package/dist/server/static/index.d.ts.map +1 -1
  208. package/dist/server/static/index.js +1853 -5
  209. package/dist/server/static/index.js.map +1 -1
  210. package/dist/server/swagger/index.d.ts +309 -6
  211. package/dist/server/swagger/index.d.ts.map +1 -1
  212. package/dist/server/swagger/index.js +1854 -6
  213. package/dist/server/swagger/index.js.map +1 -1
  214. package/dist/sms/index.d.ts +309 -7
  215. package/dist/sms/index.d.ts.map +1 -1
  216. package/dist/sms/index.js +1856 -7
  217. package/dist/sms/index.js.map +1 -1
  218. package/dist/system/index.browser.js +1218 -0
  219. package/dist/system/index.browser.js.map +1 -0
  220. package/dist/{file → system}/index.d.ts +343 -16
  221. package/dist/system/index.d.ts.map +1 -0
  222. package/dist/{file → system}/index.js +419 -22
  223. package/dist/system/index.js.map +1 -0
  224. package/dist/thread/index.d.ts +11 -2
  225. package/dist/thread/index.d.ts.map +1 -1
  226. package/dist/thread/index.js +11 -2
  227. package/dist/thread/index.js.map +1 -1
  228. package/dist/topic/core/index.d.ts +12 -5
  229. package/dist/topic/core/index.d.ts.map +1 -1
  230. package/dist/topic/core/index.js +12 -5
  231. package/dist/topic/core/index.js.map +1 -1
  232. package/dist/vite/index.d.ts +5 -6272
  233. package/dist/vite/index.d.ts.map +1 -1
  234. package/dist/vite/index.js +23 -10
  235. package/dist/vite/index.js.map +1 -1
  236. package/dist/websocket/index.d.ts +12 -8
  237. package/dist/websocket/index.d.ts.map +1 -1
  238. package/dist/websocket/index.js +12 -8
  239. package/dist/websocket/index.js.map +1 -1
  240. package/package.json +82 -11
  241. package/src/api/audits/index.ts +10 -33
  242. package/src/api/files/__tests__/$bucket.spec.ts +1 -1
  243. package/src/api/files/controllers/AdminFileStatsController.spec.ts +1 -1
  244. package/src/api/files/controllers/FileController.spec.ts +1 -1
  245. package/src/api/files/index.ts +10 -3
  246. package/src/api/files/jobs/FileJobs.spec.ts +1 -1
  247. package/src/api/files/services/FileService.spec.ts +1 -1
  248. package/src/api/jobs/index.ts +10 -3
  249. package/src/api/keys/controllers/AdminApiKeyController.ts +75 -0
  250. package/src/api/keys/controllers/ApiKeyController.ts +103 -0
  251. package/src/api/keys/entities/apiKeyEntity.ts +41 -0
  252. package/src/api/keys/index.ts +49 -0
  253. package/src/api/keys/schemas/adminApiKeyQuerySchema.ts +7 -0
  254. package/src/api/keys/schemas/adminApiKeyResourceSchema.ts +17 -0
  255. package/src/api/keys/schemas/createApiKeyBodySchema.ts +7 -0
  256. package/src/api/keys/schemas/createApiKeyResponseSchema.ts +11 -0
  257. package/src/api/keys/schemas/listApiKeyResponseSchema.ts +15 -0
  258. package/src/api/keys/schemas/revokeApiKeyParamsSchema.ts +5 -0
  259. package/src/api/keys/schemas/revokeApiKeyResponseSchema.ts +5 -0
  260. package/src/api/keys/services/ApiKeyService.spec.ts +553 -0
  261. package/src/api/keys/services/ApiKeyService.ts +306 -0
  262. package/src/api/logs/TODO.md +55 -0
  263. package/src/api/notifications/index.ts +10 -4
  264. package/src/api/parameters/index.ts +9 -30
  265. package/src/api/parameters/primitives/$config.ts +12 -4
  266. package/src/api/parameters/services/ConfigStore.ts +9 -3
  267. package/src/api/users/__tests__/ApiKeys-integration.spec.ts +1035 -0
  268. package/src/api/users/__tests__/ApiKeys.spec.ts +401 -0
  269. package/src/api/users/index.ts +14 -3
  270. package/src/api/users/primitives/$realm.ts +33 -5
  271. package/src/api/users/providers/RealmProvider.ts +1 -12
  272. package/src/api/users/services/SessionService.ts +1 -1
  273. package/src/api/verifications/controllers/VerificationController.ts +2 -0
  274. package/src/api/verifications/index.ts +10 -4
  275. package/src/batch/index.ts +9 -36
  276. package/src/batch/primitives/$batch.ts +0 -8
  277. package/src/batch/providers/BatchProvider.ts +29 -2
  278. package/src/bucket/__tests__/shared.ts +1 -1
  279. package/src/bucket/index.ts +13 -6
  280. package/src/bucket/primitives/$bucket.ts +1 -1
  281. package/src/bucket/providers/LocalFileStorageProvider.ts +1 -1
  282. package/src/bucket/providers/MemoryFileStorageProvider.ts +1 -1
  283. package/src/cache/core/__tests__/shared.ts +30 -0
  284. package/src/cache/core/index.ts +11 -6
  285. package/src/cache/core/primitives/$cache.spec.ts +5 -0
  286. package/src/cache/core/providers/CacheProvider.ts +17 -0
  287. package/src/cache/core/providers/MemoryCacheProvider.ts +300 -1
  288. package/src/cache/redis/__tests__/cache-redis.spec.ts +5 -0
  289. package/src/cache/redis/providers/RedisCacheProvider.ts +9 -0
  290. package/src/cli/apps/AlephaCli.ts +1 -14
  291. package/src/cli/apps/AlephaPackageBuilderCli.ts +10 -1
  292. package/src/cli/atoms/buildOptions.ts +99 -9
  293. package/src/cli/commands/build.ts +150 -37
  294. package/src/cli/commands/db.ts +22 -18
  295. package/src/cli/commands/deploy.ts +1 -1
  296. package/src/cli/commands/dev.ts +1 -20
  297. package/src/cli/commands/gen/env.ts +5 -2
  298. package/src/cli/commands/gen/openapi.ts +5 -2
  299. package/src/cli/commands/init.spec.ts +588 -0
  300. package/src/cli/commands/init.ts +115 -58
  301. package/src/cli/commands/lint.ts +7 -1
  302. package/src/cli/commands/typecheck.ts +11 -0
  303. package/src/cli/providers/AppEntryProvider.ts +1 -1
  304. package/src/cli/providers/ViteBuildProvider.ts +8 -50
  305. package/src/cli/providers/ViteDevServerProvider.ts +35 -16
  306. package/src/cli/services/AlephaCliUtils.ts +52 -121
  307. package/src/cli/services/PackageManagerUtils.ts +129 -11
  308. package/src/cli/services/ProjectScaffolder.spec.ts +97 -0
  309. package/src/cli/services/ProjectScaffolder.ts +148 -81
  310. package/src/cli/services/ViteUtils.ts +82 -0
  311. package/src/cli/{assets/claudeMd.ts → templates/agentMd.ts} +37 -24
  312. package/src/cli/templates/apiAppSecurityTs.ts +11 -0
  313. package/src/cli/templates/apiIndexTs.ts +30 -0
  314. package/src/cli/templates/gitignore.ts +39 -0
  315. package/src/cli/{assets → templates}/mainCss.ts +11 -2
  316. package/src/cli/templates/mainServerTs.ts +33 -0
  317. package/src/cli/templates/webAppRouterTs.ts +74 -0
  318. package/src/cli/templates/webHelloComponentTsx.ts +30 -0
  319. package/src/command/helpers/Runner.spec.ts +139 -0
  320. package/src/command/helpers/Runner.ts +7 -22
  321. package/src/command/index.ts +12 -4
  322. package/src/command/providers/CliProvider.spec.ts +1392 -0
  323. package/src/command/providers/CliProvider.ts +320 -47
  324. package/src/core/Alepha.ts +34 -27
  325. package/src/core/__tests__/Alepha-start.spec.ts +4 -4
  326. package/src/core/helpers/jsonSchemaToTypeBox.spec.ts +771 -0
  327. package/src/core/helpers/jsonSchemaToTypeBox.ts +62 -10
  328. package/src/core/index.shared.ts +1 -0
  329. package/src/core/index.ts +20 -0
  330. package/src/core/providers/EventManager.spec.ts +0 -71
  331. package/src/core/providers/EventManager.ts +3 -15
  332. package/src/core/providers/Json.ts +2 -14
  333. package/src/datetime/index.ts +15 -0
  334. package/src/email/index.ts +10 -5
  335. package/src/email/providers/LocalEmailProvider.spec.ts +1 -1
  336. package/src/email/providers/LocalEmailProvider.ts +1 -1
  337. package/src/fake/__tests__/keyName.example.ts +1 -1
  338. package/src/fake/__tests__/keyName.spec.ts +5 -5
  339. package/src/fake/index.ts +9 -6
  340. package/src/fake/providers/FakeProvider.spec.ts +258 -40
  341. package/src/fake/providers/FakeProvider.ts +133 -19
  342. package/src/lock/core/index.ts +11 -4
  343. package/src/logger/index.ts +17 -66
  344. package/src/mcp/index.ts +10 -27
  345. package/src/mcp/transports/SseMcpTransport.ts +0 -11
  346. package/src/orm/__tests__/PostgresProvider.spec.ts +2 -2
  347. package/src/orm/index.browser.ts +2 -2
  348. package/src/orm/index.bun.ts +5 -3
  349. package/src/orm/index.ts +23 -53
  350. package/src/orm/providers/drivers/BunSqliteProvider.ts +5 -1
  351. package/src/orm/providers/drivers/CloudflareD1Provider.ts +57 -30
  352. package/src/orm/providers/drivers/DatabaseProvider.ts +9 -1
  353. package/src/orm/providers/drivers/NodeSqliteProvider.ts +4 -1
  354. package/src/orm/services/Repository.ts +7 -3
  355. package/src/queue/core/index.ts +14 -6
  356. package/src/react/auth/__tests__/$auth.spec.ts +202 -0
  357. package/src/react/auth/hooks/useAuth.ts +32 -0
  358. package/src/react/auth/index.browser.ts +13 -0
  359. package/src/react/auth/index.shared.ts +2 -0
  360. package/src/react/auth/index.ts +48 -0
  361. package/src/react/auth/providers/ReactAuthProvider.ts +16 -0
  362. package/src/react/auth/services/ReactAuth.ts +135 -0
  363. package/src/react/core/__tests__/Router.spec.tsx +169 -0
  364. package/src/react/core/components/ClientOnly.tsx +49 -0
  365. package/src/react/core/components/ErrorBoundary.tsx +73 -0
  366. package/src/react/core/contexts/AlephaContext.ts +7 -0
  367. package/src/react/core/contexts/AlephaProvider.tsx +42 -0
  368. package/src/react/core/hooks/useAction.browser.spec.tsx +569 -0
  369. package/src/react/core/hooks/useAction.ts +480 -0
  370. package/src/react/core/hooks/useAlepha.ts +26 -0
  371. package/src/react/core/hooks/useClient.ts +17 -0
  372. package/src/react/core/hooks/useEvents.ts +51 -0
  373. package/src/react/core/hooks/useInject.ts +12 -0
  374. package/src/react/core/hooks/useStore.ts +52 -0
  375. package/src/react/core/index.ts +90 -0
  376. package/src/react/form/components/FormState.tsx +17 -0
  377. package/src/react/form/errors/FormValidationError.ts +18 -0
  378. package/src/react/form/hooks/useForm.browser.spec.tsx +366 -0
  379. package/src/react/form/hooks/useForm.ts +47 -0
  380. package/src/react/form/hooks/useFormState.ts +130 -0
  381. package/src/react/form/index.ts +44 -0
  382. package/src/react/form/services/FormModel.ts +614 -0
  383. package/src/react/head/helpers/SeoExpander.spec.ts +203 -0
  384. package/src/react/head/helpers/SeoExpander.ts +142 -0
  385. package/src/react/head/hooks/useHead.spec.tsx +288 -0
  386. package/src/react/head/hooks/useHead.ts +62 -0
  387. package/src/react/head/index.browser.ts +26 -0
  388. package/src/react/head/index.ts +44 -0
  389. package/src/react/head/interfaces/Head.ts +105 -0
  390. package/src/react/head/primitives/$head.ts +25 -0
  391. package/src/react/head/providers/BrowserHeadProvider.browser.spec.ts +196 -0
  392. package/src/react/head/providers/BrowserHeadProvider.ts +212 -0
  393. package/src/react/head/providers/HeadProvider.ts +168 -0
  394. package/src/react/head/providers/ServerHeadProvider.ts +31 -0
  395. package/src/react/i18n/__tests__/integration.spec.tsx +239 -0
  396. package/src/react/i18n/components/Localize.spec.tsx +357 -0
  397. package/src/react/i18n/components/Localize.tsx +35 -0
  398. package/src/react/i18n/hooks/useI18n.browser.spec.tsx +438 -0
  399. package/src/react/i18n/hooks/useI18n.ts +18 -0
  400. package/src/react/i18n/index.ts +41 -0
  401. package/src/react/i18n/primitives/$dictionary.ts +69 -0
  402. package/src/react/i18n/providers/I18nProvider.spec.ts +389 -0
  403. package/src/react/i18n/providers/I18nProvider.ts +278 -0
  404. package/src/react/router/__tests__/page-head-browser.browser.spec.ts +95 -0
  405. package/src/react/router/__tests__/page-head.spec.ts +48 -0
  406. package/src/react/router/__tests__/seo-head.spec.ts +125 -0
  407. package/src/react/router/atoms/ssrManifestAtom.ts +58 -0
  408. package/src/react/router/components/ErrorViewer.tsx +872 -0
  409. package/src/react/router/components/Link.tsx +23 -0
  410. package/src/react/router/components/NestedView.tsx +223 -0
  411. package/src/react/router/components/NotFound.tsx +30 -0
  412. package/src/react/router/constants/PAGE_PRELOAD_KEY.ts +6 -0
  413. package/src/react/router/contexts/RouterLayerContext.ts +12 -0
  414. package/src/react/router/errors/Redirection.ts +28 -0
  415. package/src/react/router/hooks/useActive.ts +52 -0
  416. package/src/react/router/hooks/useQueryParams.ts +63 -0
  417. package/src/react/router/hooks/useRouter.ts +20 -0
  418. package/src/react/router/hooks/useRouterState.ts +11 -0
  419. package/src/react/router/index.browser.ts +45 -0
  420. package/src/react/router/index.shared.ts +19 -0
  421. package/src/react/router/index.ts +146 -0
  422. package/src/react/router/primitives/$page.browser.spec.tsx +851 -0
  423. package/src/react/router/primitives/$page.spec.tsx +676 -0
  424. package/src/react/router/primitives/$page.ts +489 -0
  425. package/src/react/router/providers/ReactBrowserProvider.ts +312 -0
  426. package/src/react/router/providers/ReactBrowserRendererProvider.ts +25 -0
  427. package/src/react/router/providers/ReactBrowserRouterProvider.ts +168 -0
  428. package/src/react/router/providers/ReactPageProvider.ts +726 -0
  429. package/src/react/router/providers/ReactPreloadProvider.spec.ts +142 -0
  430. package/src/react/router/providers/ReactPreloadProvider.ts +85 -0
  431. package/src/react/router/providers/ReactServerProvider.spec.tsx +316 -0
  432. package/src/react/router/providers/ReactServerProvider.ts +487 -0
  433. package/src/react/router/providers/ReactServerTemplateProvider.spec.ts +210 -0
  434. package/src/react/router/providers/ReactServerTemplateProvider.ts +542 -0
  435. package/src/react/router/providers/SSRManifestProvider.ts +334 -0
  436. package/src/react/router/services/ReactPageServerService.ts +48 -0
  437. package/src/react/router/services/ReactPageService.ts +27 -0
  438. package/src/react/router/services/ReactRouter.ts +262 -0
  439. package/src/react/websocket/hooks/useRoom.tsx +242 -0
  440. package/src/react/websocket/index.ts +7 -0
  441. package/src/redis/__tests__/redis.spec.ts +13 -0
  442. package/src/redis/index.ts +9 -25
  443. package/src/redis/providers/BunRedisProvider.ts +9 -0
  444. package/src/redis/providers/NodeRedisProvider.ts +8 -0
  445. package/src/redis/providers/RedisProvider.ts +16 -0
  446. package/src/retry/index.ts +11 -2
  447. package/src/router/index.ts +15 -0
  448. package/src/scheduler/index.ts +11 -2
  449. package/src/security/__tests__/BasicAuth.spec.ts +2 -0
  450. package/src/security/__tests__/ServerSecurityProvider.spec.ts +90 -5
  451. package/src/security/index.ts +15 -10
  452. package/src/security/interfaces/IssuerResolver.ts +27 -0
  453. package/src/security/primitives/$issuer.ts +55 -0
  454. package/src/security/providers/SecurityProvider.ts +179 -0
  455. package/src/security/providers/ServerBasicAuthProvider.ts +6 -2
  456. package/src/security/providers/ServerSecurityProvider.ts +63 -41
  457. package/src/server/auth/index.ts +12 -7
  458. package/src/server/cache/index.ts +7 -22
  459. package/src/server/compress/index.ts +10 -2
  460. package/src/server/cookies/index.ts +7 -5
  461. package/src/server/cookies/primitives/$cookie.ts +33 -11
  462. package/src/server/core/index.ts +16 -6
  463. package/src/server/core/interfaces/ServerRequest.ts +83 -1
  464. package/src/server/core/primitives/$action.spec.ts +1 -1
  465. package/src/server/core/primitives/$action.ts +8 -3
  466. package/src/server/core/providers/NodeHttpServerProvider.spec.ts +9 -3
  467. package/src/server/core/providers/NodeHttpServerProvider.ts +9 -3
  468. package/src/server/core/services/ServerRequestParser.spec.ts +520 -0
  469. package/src/server/core/services/ServerRequestParser.ts +306 -13
  470. package/src/server/cors/index.ts +7 -21
  471. package/src/server/cors/primitives/$cors.ts +6 -2
  472. package/src/server/health/index.ts +8 -2
  473. package/src/server/helmet/index.ts +11 -3
  474. package/src/server/links/index.ts +11 -6
  475. package/src/server/metrics/index.ts +10 -3
  476. package/src/server/multipart/index.ts +9 -3
  477. package/src/server/proxy/index.ts +8 -2
  478. package/src/server/rate-limit/index.ts +21 -25
  479. package/src/server/rate-limit/primitives/$rateLimit.ts +6 -2
  480. package/src/server/rate-limit/providers/ServerRateLimitProvider.spec.ts +38 -14
  481. package/src/server/rate-limit/providers/ServerRateLimitProvider.ts +22 -56
  482. package/src/server/static/index.ts +8 -2
  483. package/src/server/static/providers/ServerStaticProvider.ts +1 -1
  484. package/src/server/swagger/index.ts +9 -4
  485. package/src/server/swagger/providers/ServerSwaggerProvider.ts +1 -1
  486. package/src/sms/index.ts +9 -5
  487. package/src/sms/providers/LocalSmsProvider.spec.ts +1 -1
  488. package/src/sms/providers/LocalSmsProvider.ts +1 -1
  489. package/src/system/index.browser.ts +36 -0
  490. package/src/system/index.ts +62 -0
  491. package/src/system/index.workerd.ts +1 -0
  492. package/src/{file → system}/providers/FileSystemProvider.ts +24 -0
  493. package/src/{file → system}/providers/MemoryFileSystemProvider.ts +116 -3
  494. package/src/system/providers/MemoryShellProvider.ts +164 -0
  495. package/src/{file → system}/providers/NodeFileSystemProvider.spec.ts +2 -2
  496. package/src/{file → system}/providers/NodeFileSystemProvider.ts +47 -2
  497. package/src/system/providers/NodeShellProvider.ts +184 -0
  498. package/src/system/providers/ShellProvider.ts +74 -0
  499. package/src/{file → system}/services/FileDetector.spec.ts +2 -2
  500. package/src/thread/index.ts +11 -2
  501. package/src/topic/core/index.ts +12 -5
  502. package/src/vite/tasks/buildClient.ts +2 -7
  503. package/src/vite/tasks/buildServer.ts +19 -13
  504. package/src/vite/tasks/generateCloudflare.ts +10 -7
  505. package/src/vite/tasks/generateDocker.ts +4 -0
  506. package/src/websocket/index.ts +12 -8
  507. package/dist/file/index.d.ts.map +0 -1
  508. package/dist/file/index.js.map +0 -1
  509. package/src/cli/assets/apiIndexTs.ts +0 -16
  510. package/src/cli/assets/mainServerTs.ts +0 -24
  511. package/src/cli/assets/webAppRouterTs.ts +0 -16
  512. package/src/cli/assets/webHelloComponentTsx.ts +0 -20
  513. package/src/cli/providers/ViteTemplateProvider.ts +0 -27
  514. package/src/file/index.ts +0 -43
  515. /package/src/cli/{assets → templates}/apiHelloControllerTs.ts +0 -0
  516. /package/src/cli/{assets → templates}/biomeJson.ts +0 -0
  517. /package/src/cli/{assets → templates}/dummySpecTs.ts +0 -0
  518. /package/src/cli/{assets → templates}/editorconfig.ts +0 -0
  519. /package/src/cli/{assets → templates}/mainBrowserTs.ts +0 -0
  520. /package/src/cli/{assets → templates}/tsconfigJson.ts +0 -0
  521. /package/src/cli/{assets → templates}/webIndexTs.ts +0 -0
  522. /package/src/{file → system}/errors/FileError.ts +0 -0
  523. /package/src/{file → system}/services/FileDetector.ts +0 -0
@@ -0,0 +1,1974 @@
1
+ import { $atom, $env, $hook, $inject, $module, $use, Alepha, AlephaError, KIND, Primitive, createPrimitive, t } from "alepha";
2
+ import { AlephaDateTime, DateTimeProvider } from "alepha/datetime";
3
+ import { AlephaContext, AlephaReact, ClientOnly, ErrorBoundary, useAlepha, useEvents, useInject, useStore } from "alepha/react";
4
+ import { AlephaServer } from "alepha/server";
5
+ import { AlephaServerLinks, LinkProvider } from "alepha/server/links";
6
+ import { $logger } from "alepha/logger";
7
+ import { BrowserHeadProvider } from "alepha/react/head";
8
+ import { RouterProvider } from "alepha/router";
9
+ import { StrictMode, createContext, createElement, memo, use, useEffect, useRef, useState } from "react";
10
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
11
+ import { createRoot, hydrateRoot } from "react-dom/client";
12
+
13
+ //#region ../../src/react/router/constants/PAGE_PRELOAD_KEY.ts
14
+ /**
15
+ * Symbol key for SSR module preloading path.
16
+ * Using Symbol.for() allows the Vite plugin to inject this at build time.
17
+ * @internal
18
+ */
19
+ const PAGE_PRELOAD_KEY = Symbol.for("alepha.page.preload");
20
+
21
+ //#endregion
22
+ //#region ../../src/react/router/services/ReactPageService.ts
23
+ /**
24
+ * $page methods interface.
25
+ */
26
+ var ReactPageService = class {
27
+ fetch(pathname, options = {}) {
28
+ throw new AlephaError("Fetch is not available for this environment.");
29
+ }
30
+ render(name, options = {}) {
31
+ throw new AlephaError("Render is not available for this environment.");
32
+ }
33
+ };
34
+
35
+ //#endregion
36
+ //#region ../../src/react/router/primitives/$page.ts
37
+ /**
38
+ * Main primitive for defining a React route in the application.
39
+ *
40
+ * The $page primitive is the core building block for creating type-safe, SSR-enabled React routes.
41
+ * It provides a declarative way to define pages with powerful features:
42
+ *
43
+ * **Routing & Navigation**
44
+ * - URL pattern matching with parameters (e.g., `/users/:id`)
45
+ * - Nested routing with parent-child relationships
46
+ * - Type-safe URL parameter and query string validation
47
+ *
48
+ * **Data Loading**
49
+ * - Server-side data fetching with the `loader` function
50
+ * - Automatic serialization and hydration for SSR
51
+ * - Access to request context, URL params, and parent data
52
+ *
53
+ * **Component Loading**
54
+ * - Direct component rendering or lazy loading for code splitting
55
+ * - Client-only rendering when browser APIs are needed
56
+ * - Automatic fallback handling during hydration
57
+ *
58
+ * **Performance Optimization**
59
+ * - Static generation for pre-rendered pages at build time
60
+ * - Server-side caching with configurable TTL and providers
61
+ * - Code splitting through lazy component loading
62
+ *
63
+ * **Error Handling**
64
+ * - Custom error handlers with support for redirects
65
+ * - Hierarchical error handling (child → parent)
66
+ * - HTTP status code handling (404, 401, etc.)
67
+ *
68
+ * **Page Animations**
69
+ * - CSS-based enter/exit animations
70
+ * - Dynamic animations based on page state
71
+ * - Custom timing and easing functions
72
+ *
73
+ * **Lifecycle Management**
74
+ * - Server response hooks for headers and status codes
75
+ * - Page leave handlers for cleanup (browser only)
76
+ * - Permission-based access control
77
+ *
78
+ * @example Simple page with data fetching
79
+ * ```typescript
80
+ * const userProfile = $page({
81
+ * path: "/users/:id",
82
+ * schema: {
83
+ * params: t.object({ id: t.integer() }),
84
+ * query: t.object({ tab: t.optional(t.text()) })
85
+ * },
86
+ * loader: async ({ params }) => {
87
+ * const user = await userApi.getUser(params.id);
88
+ * return { user };
89
+ * },
90
+ * lazy: () => import("./UserProfile.tsx")
91
+ * });
92
+ * ```
93
+ *
94
+ * @example Nested routing with error handling
95
+ * ```typescript
96
+ * const projectSection = $page({
97
+ * path: "/projects/:id",
98
+ * children: () => [projectBoard, projectSettings],
99
+ * loader: async ({ params }) => {
100
+ * const project = await projectApi.get(params.id);
101
+ * return { project };
102
+ * },
103
+ * errorHandler: (error) => {
104
+ * if (HttpError.is(error, 404)) {
105
+ * return <ProjectNotFound />;
106
+ * }
107
+ * }
108
+ * });
109
+ * ```
110
+ *
111
+ * @example Static generation with caching
112
+ * ```typescript
113
+ * const blogPost = $page({
114
+ * path: "/blog/:slug",
115
+ * static: {
116
+ * entries: posts.map(p => ({ params: { slug: p.slug } }))
117
+ * },
118
+ * loader: async ({ params }) => {
119
+ * const post = await loadPost(params.slug);
120
+ * return { post };
121
+ * }
122
+ * });
123
+ * ```
124
+ */
125
+ const $page = (options) => {
126
+ return createPrimitive(PagePrimitive, options);
127
+ };
128
+ var PagePrimitive = class extends Primitive {
129
+ reactPageService = $inject(ReactPageService);
130
+ onInit() {
131
+ if (this.options.static) this.options.cache ??= { store: {
132
+ provider: "memory",
133
+ ttl: [1, "week"]
134
+ } };
135
+ }
136
+ get name() {
137
+ return this.options.name ?? this.config.propertyKey;
138
+ }
139
+ /**
140
+ * For testing or build purposes.
141
+ *
142
+ * This will render the page (HTML layout included or not) and return the HTML + context.
143
+ * Only valid for server-side rendering, it will throw an error if called on the client-side.
144
+ */
145
+ async render(options) {
146
+ return this.reactPageService.render(this.name, options);
147
+ }
148
+ async fetch(options) {
149
+ return this.reactPageService.fetch(this.options.path || "", options);
150
+ }
151
+ };
152
+ $page[KIND] = PagePrimitive;
153
+
154
+ //#endregion
155
+ //#region ../../src/react/router/components/NotFound.tsx
156
+ /**
157
+ * Default 404 Not Found page component.
158
+ */
159
+ const NotFound = (props) => /* @__PURE__ */ jsxs("div", {
160
+ style: {
161
+ width: "100%",
162
+ minHeight: "90vh",
163
+ boxSizing: "border-box",
164
+ display: "flex",
165
+ flexDirection: "column",
166
+ justifyContent: "center",
167
+ alignItems: "center",
168
+ textAlign: "center",
169
+ fontFamily: "system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, sans-serif",
170
+ padding: "2rem",
171
+ ...props.style
172
+ },
173
+ children: [/* @__PURE__ */ jsx("div", {
174
+ style: {
175
+ fontSize: "6rem",
176
+ fontWeight: 200,
177
+ lineHeight: 1
178
+ },
179
+ children: "404"
180
+ }), /* @__PURE__ */ jsx("div", {
181
+ style: {
182
+ fontSize: "0.875rem",
183
+ marginTop: "1rem",
184
+ opacity: .6
185
+ },
186
+ children: "Page not found"
187
+ })]
188
+ });
189
+ var NotFound_default = NotFound;
190
+
191
+ //#endregion
192
+ //#region ../../src/react/router/components/ErrorViewer.tsx
193
+ const isBrowser = typeof window !== "undefined";
194
+ /**
195
+ * Error viewer component - Terminal/brutalist aesthetic
196
+ */
197
+ const ErrorViewer = ({ error, alepha }) => {
198
+ const [expanded, setExpanded] = useState(false);
199
+ const [showNodeModules, setShowNodeModules] = useState(false);
200
+ const [visible, setVisible] = useState(false);
201
+ const containerRef = useRef(null);
202
+ const isProduction = alepha.isProduction();
203
+ useEffect(() => {
204
+ const timer = setTimeout(() => setVisible(true), 10);
205
+ return () => clearTimeout(timer);
206
+ }, []);
207
+ useEffect(() => {
208
+ if (!isBrowser) return;
209
+ const handler = (e) => {
210
+ if (e.key === "c" && !e.metaKey && !e.ctrlKey) copyToClipboard(error.stack || error.message);
211
+ };
212
+ window.addEventListener("keydown", handler);
213
+ return () => window.removeEventListener("keydown", handler);
214
+ }, [error]);
215
+ if (isProduction) return /* @__PURE__ */ jsx(ErrorViewerProduction, {});
216
+ const frames = parseStackTrace(error.stack);
217
+ const appFrames = frames.filter((f) => !f.isNodeModules);
218
+ const nodeModulesFrames = frames.filter((f) => f.isNodeModules);
219
+ const visibleAppFrames = expanded ? appFrames : appFrames.slice(0, 5);
220
+ const hiddenAppCount = appFrames.length - 5;
221
+ const timestamp = (/* @__PURE__ */ new Date()).toLocaleTimeString("en-US", {
222
+ hour12: false,
223
+ hour: "2-digit",
224
+ minute: "2-digit",
225
+ second: "2-digit"
226
+ });
227
+ return /* @__PURE__ */ jsxs("div", {
228
+ ref: containerRef,
229
+ style: {
230
+ ...styles.overlay,
231
+ opacity: visible ? 1 : 0
232
+ },
233
+ role: "alertdialog",
234
+ "aria-modal": "true",
235
+ "aria-labelledby": "error-viewer-title",
236
+ children: [/* @__PURE__ */ jsx("div", {
237
+ style: styles.scanlines,
238
+ "aria-hidden": "true"
239
+ }), /* @__PURE__ */ jsxs("div", {
240
+ style: {
241
+ ...styles.container,
242
+ transform: visible ? "translateY(0)" : "translateY(-20px)",
243
+ opacity: visible ? 1 : 0
244
+ },
245
+ children: [
246
+ /* @__PURE__ */ jsxs("div", {
247
+ style: styles.terminalBar,
248
+ children: [
249
+ /* @__PURE__ */ jsxs("div", {
250
+ style: styles.terminalDots,
251
+ children: [
252
+ /* @__PURE__ */ jsx("span", { style: {
253
+ ...styles.dot,
254
+ backgroundColor: "#ff5f57"
255
+ } }),
256
+ /* @__PURE__ */ jsx("span", { style: {
257
+ ...styles.dot,
258
+ backgroundColor: "#febc2e"
259
+ } }),
260
+ /* @__PURE__ */ jsx("span", { style: {
261
+ ...styles.dot,
262
+ backgroundColor: "#28c840"
263
+ } })
264
+ ]
265
+ }),
266
+ /* @__PURE__ */ jsx("div", {
267
+ style: styles.terminalTitle,
268
+ children: /* @__PURE__ */ jsxs("span", {
269
+ style: styles.terminalTitleText,
270
+ children: ["error — ", timestamp]
271
+ })
272
+ }),
273
+ /* @__PURE__ */ jsxs("div", {
274
+ style: styles.terminalActions,
275
+ children: [/* @__PURE__ */ jsx("kbd", {
276
+ style: styles.kbd,
277
+ children: "C"
278
+ }), /* @__PURE__ */ jsx("span", {
279
+ style: styles.kbdLabel,
280
+ children: "copy"
281
+ })]
282
+ })
283
+ ]
284
+ }),
285
+ /* @__PURE__ */ jsx(Header, { error }),
286
+ /* @__PURE__ */ jsxs("div", {
287
+ style: styles.stackSection,
288
+ children: [/* @__PURE__ */ jsxs("div", {
289
+ style: styles.stackHeader,
290
+ children: [/* @__PURE__ */ jsx("span", {
291
+ style: styles.stackHeaderText,
292
+ children: "STACK TRACE"
293
+ }), /* @__PURE__ */ jsxs("span", {
294
+ style: styles.stackCount,
295
+ children: [
296
+ appFrames.length,
297
+ " frames",
298
+ nodeModulesFrames.length > 0 && ` · ${nodeModulesFrames.length} in node_modules`
299
+ ]
300
+ })]
301
+ }), /* @__PURE__ */ jsxs("div", {
302
+ style: styles.frameList,
303
+ children: [
304
+ visibleAppFrames.map((frame, i) => /* @__PURE__ */ jsx(StackFrameRow, {
305
+ frame,
306
+ index: i
307
+ }, `${frame.raw}-${i}`)),
308
+ hiddenAppCount > 0 && !expanded && /* @__PURE__ */ jsx(ExpandButton, {
309
+ onClick: () => setExpanded(true),
310
+ label: `Show ${hiddenAppCount} more frames`
311
+ }),
312
+ expanded && hiddenAppCount > 0 && /* @__PURE__ */ jsx(ExpandButton, {
313
+ onClick: () => setExpanded(false),
314
+ label: "Collapse"
315
+ }),
316
+ nodeModulesFrames.length > 0 && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs("button", {
317
+ type: "button",
318
+ onClick: () => setShowNodeModules(!showNodeModules),
319
+ style: styles.nodeModulesToggle,
320
+ children: [
321
+ /* @__PURE__ */ jsx("span", {
322
+ style: styles.nodeModulesIcon,
323
+ children: showNodeModules ? "▼" : "▶"
324
+ }),
325
+ /* @__PURE__ */ jsx("span", {
326
+ style: styles.nodeModulesLabel,
327
+ children: "node_modules"
328
+ }),
329
+ /* @__PURE__ */ jsx("span", {
330
+ style: styles.nodeModulesCount,
331
+ children: nodeModulesFrames.length
332
+ })
333
+ ]
334
+ }), showNodeModules && /* @__PURE__ */ jsx("div", {
335
+ style: styles.nodeModulesFrames,
336
+ children: nodeModulesFrames.map((frame, i) => /* @__PURE__ */ jsx(StackFrameRow, {
337
+ frame,
338
+ index: appFrames.length + i,
339
+ dimmed: true
340
+ }, `nm-${frame.raw}-${i}`))
341
+ })] })
342
+ ]
343
+ })]
344
+ }),
345
+ /* @__PURE__ */ jsx("div", {
346
+ style: styles.footer,
347
+ children: /* @__PURE__ */ jsxs("span", {
348
+ style: styles.footerText,
349
+ children: [
350
+ "Press ",
351
+ /* @__PURE__ */ jsx("kbd", {
352
+ style: styles.kbdInline,
353
+ children: "C"
354
+ }),
355
+ " to copy stack trace"
356
+ ]
357
+ })
358
+ })
359
+ ]
360
+ })]
361
+ });
362
+ };
363
+ var ErrorViewer_default = ErrorViewer;
364
+ function parseStackTrace(stack) {
365
+ if (!stack) return [];
366
+ const lines = stack.split("\n").slice(1);
367
+ const frames = [];
368
+ for (const line of lines) {
369
+ const trimmed = line.trim();
370
+ if (!trimmed.startsWith("at ")) continue;
371
+ const frame = parseStackLine(trimmed);
372
+ if (frame) frames.push(frame);
373
+ }
374
+ return frames;
375
+ }
376
+ function parseStackLine(line) {
377
+ const isNodeModules = line.includes("node_modules") || line.includes("node:");
378
+ const withFn = line.match(/^at\s+(.+?)\s+\((.+):(\d+):(\d+)\)$/);
379
+ if (withFn) return {
380
+ fn: withFn[1],
381
+ file: withFn[2],
382
+ line: withFn[3],
383
+ col: withFn[4],
384
+ raw: line,
385
+ isNodeModules
386
+ };
387
+ const withoutFn = line.match(/^at\s+(.+):(\d+):(\d+)$/);
388
+ if (withoutFn) return {
389
+ fn: "<anonymous>",
390
+ file: withoutFn[1],
391
+ line: withoutFn[2],
392
+ col: withoutFn[3],
393
+ raw: line,
394
+ isNodeModules
395
+ };
396
+ return {
397
+ fn: "",
398
+ file: line.replace(/^at\s+/, ""),
399
+ line: "",
400
+ col: "",
401
+ raw: line,
402
+ isNodeModules
403
+ };
404
+ }
405
+ function copyToClipboard(text) {
406
+ if (!isBrowser || !navigator.clipboard) return Promise.resolve(false);
407
+ return navigator.clipboard.writeText(text).then(() => true).catch(() => false);
408
+ }
409
+ /**
410
+ * Header with error badge and message
411
+ */
412
+ function Header({ error }) {
413
+ const [copied, setCopied] = useState(false);
414
+ const [hovered, setHovered] = useState(false);
415
+ useEffect(() => {
416
+ if (!copied) return;
417
+ const timer = setTimeout(() => setCopied(false), 2e3);
418
+ return () => clearTimeout(timer);
419
+ }, [copied]);
420
+ const handleCopy = async () => {
421
+ if (await copyToClipboard(error.stack || error.message)) setCopied(true);
422
+ };
423
+ return /* @__PURE__ */ jsxs("div", {
424
+ style: styles.header,
425
+ children: [/* @__PURE__ */ jsxs("div", {
426
+ style: styles.headerRow,
427
+ children: [/* @__PURE__ */ jsxs("div", {
428
+ style: styles.errorIndicator,
429
+ children: [/* @__PURE__ */ jsx("div", { style: styles.errorGlow }), /* @__PURE__ */ jsx("div", {
430
+ style: styles.errorBadge,
431
+ children: error.name
432
+ })]
433
+ }), /* @__PURE__ */ jsx("button", {
434
+ type: "button",
435
+ onClick: handleCopy,
436
+ onMouseEnter: () => setHovered(true),
437
+ onMouseLeave: () => setHovered(false),
438
+ style: {
439
+ ...styles.copyBtn,
440
+ ...hovered ? styles.copyBtnHover : {}
441
+ },
442
+ children: copied ? "✓ Copied" : "Copy"
443
+ })]
444
+ }), /* @__PURE__ */ jsx("h1", {
445
+ id: "error-viewer-title",
446
+ style: styles.message,
447
+ children: error.message
448
+ })]
449
+ });
450
+ }
451
+ /**
452
+ * Single stack frame row
453
+ */
454
+ function StackFrameRow({ frame, index, dimmed = false }) {
455
+ const [hovered, setHovered] = useState(false);
456
+ const isFirst = index === 0 && !dimmed;
457
+ const fileName = frame.file.split("/").pop() || frame.file;
458
+ const dirPath = frame.file.substring(0, frame.file.length - fileName.length);
459
+ const vsCodeLink = frame.file && frame.line ? `vscode://file${frame.file}:${frame.line}:${frame.col || 1}` : null;
460
+ const content = /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("div", {
461
+ style: {
462
+ ...styles.frameIndex,
463
+ color: isFirst ? "#ff6b6b" : dimmed ? "#555" : "#666"
464
+ },
465
+ children: String(index + 1).padStart(2, "0")
466
+ }), /* @__PURE__ */ jsxs("div", {
467
+ style: styles.frameContent,
468
+ children: [frame.fn && /* @__PURE__ */ jsx("div", {
469
+ style: {
470
+ ...styles.fnName,
471
+ color: dimmed ? "#888" : "#f0f0f0"
472
+ },
473
+ children: formatFunctionName(frame.fn)
474
+ }), /* @__PURE__ */ jsxs("div", {
475
+ style: styles.filePath,
476
+ children: [
477
+ /* @__PURE__ */ jsx("span", {
478
+ style: {
479
+ ...styles.dirPath,
480
+ opacity: dimmed ? .6 : .8
481
+ },
482
+ children: dirPath
483
+ }),
484
+ /* @__PURE__ */ jsx("span", {
485
+ style: {
486
+ ...styles.fileName,
487
+ color: dimmed ? "#5a9aba" : "#7cc4eb"
488
+ },
489
+ children: fileName
490
+ }),
491
+ frame.line && /* @__PURE__ */ jsxs("span", {
492
+ style: {
493
+ ...styles.lineCol,
494
+ color: dimmed ? "#9a8a40" : "#e5b83a"
495
+ },
496
+ children: [
497
+ ":",
498
+ frame.line,
499
+ frame.col && `:${frame.col}`
500
+ ]
501
+ })
502
+ ]
503
+ })]
504
+ })] });
505
+ const rowStyles = {
506
+ ...styles.frame,
507
+ ...isFirst ? styles.frameFirst : {},
508
+ backgroundColor: hovered ? "rgba(255,255,255,0.03)" : "transparent"
509
+ };
510
+ if (vsCodeLink && isBrowser) return /* @__PURE__ */ jsx("a", {
511
+ href: vsCodeLink,
512
+ style: {
513
+ ...rowStyles,
514
+ textDecoration: "none"
515
+ },
516
+ onMouseEnter: () => setHovered(true),
517
+ onMouseLeave: () => setHovered(false),
518
+ children: content
519
+ });
520
+ return /* @__PURE__ */ jsx("div", {
521
+ style: rowStyles,
522
+ children: content
523
+ });
524
+ }
525
+ /**
526
+ * Format function name with syntax highlighting
527
+ */
528
+ function formatFunctionName(fn) {
529
+ const asyncMatch = fn.match(/^(async\s+)?(.+)$/);
530
+ if (asyncMatch?.[1]) return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("span", {
531
+ style: { color: "#c678dd" },
532
+ children: "async "
533
+ }), /* @__PURE__ */ jsx("span", { children: asyncMatch[2] })] });
534
+ const methodMatch = fn.match(/^(.+)\.([^.]+)$/);
535
+ if (methodMatch) return /* @__PURE__ */ jsxs(Fragment, { children: [
536
+ /* @__PURE__ */ jsx("span", {
537
+ style: { color: "#e5c07b" },
538
+ children: methodMatch[1]
539
+ }),
540
+ /* @__PURE__ */ jsx("span", {
541
+ style: { color: "#666" },
542
+ children: "."
543
+ }),
544
+ /* @__PURE__ */ jsx("span", { children: methodMatch[2] })
545
+ ] });
546
+ return fn;
547
+ }
548
+ /**
549
+ * Expand/collapse button
550
+ */
551
+ function ExpandButton({ onClick, label }) {
552
+ const [hovered, setHovered] = useState(false);
553
+ return /* @__PURE__ */ jsx("button", {
554
+ type: "button",
555
+ onClick,
556
+ onMouseEnter: () => setHovered(true),
557
+ onMouseLeave: () => setHovered(false),
558
+ style: {
559
+ ...styles.expandBtn,
560
+ backgroundColor: hovered ? "rgba(255,255,255,0.05)" : "transparent",
561
+ color: hovered ? "#aaa" : "#777"
562
+ },
563
+ children: label
564
+ });
565
+ }
566
+ /**
567
+ * Production error view - minimal, user-friendly
568
+ */
569
+ function ErrorViewerProduction() {
570
+ const [hovered, setHovered] = useState(false);
571
+ const handleReload = () => {
572
+ if (isBrowser) window.location.reload();
573
+ };
574
+ return /* @__PURE__ */ jsx("div", {
575
+ style: styles.overlay,
576
+ role: "alertdialog",
577
+ "aria-modal": "true",
578
+ children: /* @__PURE__ */ jsxs("div", {
579
+ style: styles.prodContainer,
580
+ children: [
581
+ /* @__PURE__ */ jsx("div", {
582
+ style: styles.prodIcon,
583
+ children: /* @__PURE__ */ jsxs("svg", {
584
+ width: "32",
585
+ height: "32",
586
+ viewBox: "0 0 24 24",
587
+ fill: "none",
588
+ stroke: "currentColor",
589
+ strokeWidth: "2",
590
+ children: [
591
+ /* @__PURE__ */ jsx("circle", {
592
+ cx: "12",
593
+ cy: "12",
594
+ r: "10"
595
+ }),
596
+ /* @__PURE__ */ jsx("line", {
597
+ x1: "12",
598
+ y1: "8",
599
+ x2: "12",
600
+ y2: "12"
601
+ }),
602
+ /* @__PURE__ */ jsx("line", {
603
+ x1: "12",
604
+ y1: "16",
605
+ x2: "12.01",
606
+ y2: "16"
607
+ })
608
+ ]
609
+ })
610
+ }),
611
+ /* @__PURE__ */ jsx("h1", {
612
+ style: styles.prodTitle,
613
+ children: "Something went wrong"
614
+ }),
615
+ /* @__PURE__ */ jsx("p", {
616
+ style: styles.prodMessage,
617
+ children: "We encountered an unexpected error. Please try again."
618
+ }),
619
+ /* @__PURE__ */ jsx("button", {
620
+ type: "button",
621
+ onClick: handleReload,
622
+ onMouseEnter: () => setHovered(true),
623
+ onMouseLeave: () => setHovered(false),
624
+ style: {
625
+ ...styles.prodButton,
626
+ backgroundColor: hovered ? "#333" : "#222",
627
+ borderColor: hovered ? "#555" : "#444"
628
+ },
629
+ children: "Reload page"
630
+ })
631
+ ]
632
+ })
633
+ });
634
+ }
635
+ const MONO_FONT = "ui-monospace, \"JetBrains Mono\", \"Fira Code\", SFMono-Regular, Menlo, Monaco, Consolas, monospace";
636
+ const styles = {
637
+ overlay: {
638
+ position: "fixed",
639
+ inset: 0,
640
+ backgroundColor: "rgba(0, 0, 0, 0.92)",
641
+ display: "flex",
642
+ alignItems: "flex-start",
643
+ justifyContent: "center",
644
+ padding: "40px 20px",
645
+ overflow: "auto",
646
+ fontFamily: MONO_FONT,
647
+ fontSize: "13px",
648
+ zIndex: 99999,
649
+ transition: "opacity 0.2s ease-out"
650
+ },
651
+ scanlines: {
652
+ position: "fixed",
653
+ inset: 0,
654
+ background: "repeating-linear-gradient(0deg, transparent, transparent 2px, rgba(0,0,0,0.1) 2px, rgba(0,0,0,0.1) 4px)",
655
+ pointerEvents: "none",
656
+ zIndex: 1e5
657
+ },
658
+ container: {
659
+ width: "100%",
660
+ maxWidth: "900px",
661
+ backgroundColor: "#0d0d0d",
662
+ borderRadius: "8px",
663
+ overflow: "hidden",
664
+ boxShadow: "0 0 0 1px #333, 0 25px 80px -12px rgba(0, 0, 0, 0.8)",
665
+ transition: "transform 0.3s ease-out, opacity 0.3s ease-out"
666
+ },
667
+ terminalBar: {
668
+ display: "flex",
669
+ alignItems: "center",
670
+ padding: "12px 16px",
671
+ backgroundColor: "#1a1a1a",
672
+ borderBottom: "1px solid #333"
673
+ },
674
+ terminalDots: {
675
+ display: "flex",
676
+ gap: "8px"
677
+ },
678
+ dot: {
679
+ width: "12px",
680
+ height: "12px",
681
+ borderRadius: "50%"
682
+ },
683
+ terminalTitle: {
684
+ flex: 1,
685
+ textAlign: "center"
686
+ },
687
+ terminalTitleText: {
688
+ color: "#777",
689
+ fontSize: "12px",
690
+ letterSpacing: "0.5px"
691
+ },
692
+ terminalActions: {
693
+ display: "flex",
694
+ alignItems: "center",
695
+ gap: "6px"
696
+ },
697
+ kbd: {
698
+ display: "inline-block",
699
+ padding: "2px 6px",
700
+ backgroundColor: "#2a2a2a",
701
+ borderRadius: "4px",
702
+ fontSize: "11px",
703
+ color: "#aaa",
704
+ border: "1px solid #444"
705
+ },
706
+ kbdInline: {
707
+ display: "inline-block",
708
+ padding: "1px 5px",
709
+ backgroundColor: "#222",
710
+ borderRadius: "3px",
711
+ fontSize: "11px",
712
+ color: "#888",
713
+ border: "1px solid #444",
714
+ marginLeft: "4px",
715
+ marginRight: "4px"
716
+ },
717
+ kbdLabel: {
718
+ color: "#777",
719
+ fontSize: "11px"
720
+ },
721
+ header: {
722
+ padding: "24px",
723
+ borderBottom: "1px solid #333"
724
+ },
725
+ headerRow: {
726
+ display: "flex",
727
+ alignItems: "center",
728
+ justifyContent: "space-between",
729
+ marginBottom: "16px"
730
+ },
731
+ errorIndicator: {
732
+ position: "relative",
733
+ display: "inline-flex"
734
+ },
735
+ errorGlow: {
736
+ position: "absolute",
737
+ inset: "-4px",
738
+ background: "radial-gradient(ellipse at center, rgba(255,80,80,0.3) 0%, transparent 70%)",
739
+ borderRadius: "12px",
740
+ filter: "blur(8px)"
741
+ },
742
+ errorBadge: {
743
+ position: "relative",
744
+ display: "inline-block",
745
+ padding: "6px 14px",
746
+ backgroundColor: "#3d1a1a",
747
+ color: "#ff7b7b",
748
+ fontSize: "12px",
749
+ fontWeight: 600,
750
+ borderRadius: "6px",
751
+ border: "1px solid #5a2828",
752
+ letterSpacing: "0.5px"
753
+ },
754
+ copyBtn: {
755
+ padding: "8px 14px",
756
+ backgroundColor: "transparent",
757
+ color: "#888",
758
+ fontSize: "12px",
759
+ fontWeight: 500,
760
+ borderWidth: "1px",
761
+ borderStyle: "solid",
762
+ borderColor: "#444",
763
+ borderRadius: "6px",
764
+ cursor: "pointer",
765
+ transition: "all 0.15s",
766
+ fontFamily: MONO_FONT
767
+ },
768
+ copyBtnHover: {
769
+ backgroundColor: "#252525",
770
+ color: "#bbb",
771
+ borderColor: "#555"
772
+ },
773
+ message: {
774
+ margin: 0,
775
+ fontSize: "18px",
776
+ fontWeight: 400,
777
+ color: "#e8e8e8",
778
+ lineHeight: 1.6,
779
+ wordBreak: "break-word",
780
+ fontFamily: MONO_FONT
781
+ },
782
+ stackSection: { borderTop: "1px solid #2a2a2a" },
783
+ stackHeader: {
784
+ display: "flex",
785
+ alignItems: "center",
786
+ justifyContent: "space-between",
787
+ padding: "14px 24px",
788
+ borderBottom: "1px solid #2a2a2a"
789
+ },
790
+ stackHeaderText: {
791
+ fontSize: "10px",
792
+ fontWeight: 600,
793
+ color: "#666",
794
+ letterSpacing: "1.5px"
795
+ },
796
+ stackCount: {
797
+ fontSize: "11px",
798
+ color: "#555"
799
+ },
800
+ frameList: {
801
+ display: "flex",
802
+ flexDirection: "column"
803
+ },
804
+ frame: {
805
+ display: "flex",
806
+ alignItems: "flex-start",
807
+ padding: "12px 24px",
808
+ borderBottom: "1px solid #222",
809
+ transition: "background-color 0.1s",
810
+ cursor: "pointer"
811
+ },
812
+ frameFirst: {
813
+ backgroundColor: "rgba(255, 80, 80, 0.08)",
814
+ borderLeft: "2px solid #ff6b6b"
815
+ },
816
+ frameIndex: {
817
+ width: "28px",
818
+ flexShrink: 0,
819
+ fontSize: "11px",
820
+ fontWeight: 500,
821
+ fontFamily: MONO_FONT
822
+ },
823
+ frameContent: {
824
+ flex: 1,
825
+ minWidth: 0
826
+ },
827
+ fnName: {
828
+ fontSize: "13px",
829
+ fontWeight: 500,
830
+ marginBottom: "4px",
831
+ fontFamily: MONO_FONT
832
+ },
833
+ filePath: {
834
+ fontSize: "12px",
835
+ color: "#888",
836
+ fontFamily: MONO_FONT,
837
+ wordBreak: "break-all"
838
+ },
839
+ dirPath: { color: "#666" },
840
+ fileName: { color: "#7cc4eb" },
841
+ lineCol: { color: "#e5b83a" },
842
+ expandBtn: {
843
+ width: "100%",
844
+ padding: "14px 24px",
845
+ backgroundColor: "transparent",
846
+ color: "#777",
847
+ fontSize: "12px",
848
+ fontWeight: 500,
849
+ border: "none",
850
+ borderTop: "1px solid #2a2a2a",
851
+ cursor: "pointer",
852
+ textAlign: "left",
853
+ transition: "all 0.15s",
854
+ fontFamily: MONO_FONT
855
+ },
856
+ nodeModulesToggle: {
857
+ display: "flex",
858
+ alignItems: "center",
859
+ gap: "10px",
860
+ width: "100%",
861
+ padding: "12px 24px",
862
+ backgroundColor: "#0a0a0a",
863
+ color: "#666",
864
+ fontSize: "11px",
865
+ fontWeight: 500,
866
+ border: "none",
867
+ borderTop: "1px solid #2a2a2a",
868
+ cursor: "pointer",
869
+ textAlign: "left",
870
+ fontFamily: MONO_FONT
871
+ },
872
+ nodeModulesIcon: {
873
+ fontSize: "8px",
874
+ color: "#555"
875
+ },
876
+ nodeModulesLabel: {
877
+ flex: 1,
878
+ letterSpacing: "0.5px"
879
+ },
880
+ nodeModulesCount: { color: "#555" },
881
+ nodeModulesFrames: { backgroundColor: "#080808" },
882
+ footer: {
883
+ padding: "14px 24px",
884
+ borderTop: "1px solid #2a2a2a",
885
+ backgroundColor: "#0a0a0a"
886
+ },
887
+ footerText: {
888
+ fontSize: "11px",
889
+ color: "#555"
890
+ },
891
+ prodContainer: {
892
+ textAlign: "center",
893
+ padding: "60px 40px",
894
+ backgroundColor: "#0d0d0d",
895
+ borderRadius: "8px",
896
+ maxWidth: "400px",
897
+ border: "1px solid #333"
898
+ },
899
+ prodIcon: {
900
+ width: "64px",
901
+ height: "64px",
902
+ margin: "0 auto 24px",
903
+ color: "#666",
904
+ display: "flex",
905
+ alignItems: "center",
906
+ justifyContent: "center"
907
+ },
908
+ prodTitle: {
909
+ margin: "0 0 12px",
910
+ fontSize: "18px",
911
+ fontWeight: 500,
912
+ color: "#f0f0f0",
913
+ fontFamily: MONO_FONT
914
+ },
915
+ prodMessage: {
916
+ margin: "0 0 28px",
917
+ fontSize: "13px",
918
+ color: "#888",
919
+ lineHeight: 1.6,
920
+ fontFamily: MONO_FONT
921
+ },
922
+ prodButton: {
923
+ padding: "12px 24px",
924
+ backgroundColor: "#222",
925
+ color: "#bbb",
926
+ fontSize: "13px",
927
+ fontWeight: 500,
928
+ borderWidth: "1px",
929
+ borderStyle: "solid",
930
+ borderColor: "#444",
931
+ borderRadius: "6px",
932
+ cursor: "pointer",
933
+ transition: "all 0.15s",
934
+ fontFamily: MONO_FONT
935
+ }
936
+ };
937
+
938
+ //#endregion
939
+ //#region ../../src/react/router/contexts/RouterLayerContext.ts
940
+ const RouterLayerContext = createContext(void 0);
941
+
942
+ //#endregion
943
+ //#region ../../src/react/router/errors/Redirection.ts
944
+ /**
945
+ * Used for Redirection during the page loading.
946
+ *
947
+ * Depends on the context, it can be thrown or just returned.
948
+ *
949
+ * @example
950
+ * ```ts
951
+ * import { Redirection } from "alepha/react";
952
+ *
953
+ * const MyPage = $page({
954
+ * loader: async () => {
955
+ * if (needRedirect) {
956
+ * throw new Redirection("/new-path");
957
+ * }
958
+ * },
959
+ * });
960
+ * ```
961
+ */
962
+ var Redirection = class extends AlephaError {
963
+ redirect;
964
+ constructor(redirect) {
965
+ super("Redirection");
966
+ this.redirect = redirect;
967
+ }
968
+ };
969
+
970
+ //#endregion
971
+ //#region ../../src/react/router/hooks/useRouterState.ts
972
+ const useRouterState = () => {
973
+ const [state] = useStore("alepha.react.router.state");
974
+ if (!state) throw new AlephaError("Missing react router state");
975
+ return state;
976
+ };
977
+
978
+ //#endregion
979
+ //#region ../../src/react/router/components/NestedView.tsx
980
+ /**
981
+ * A component that renders the current view of the nested router layer.
982
+ *
983
+ * To be simple, it renders the `element` of the current child page of a parent page.
984
+ *
985
+ * @example
986
+ * ```tsx
987
+ * import { NestedView } from "alepha/react";
988
+ *
989
+ * class App {
990
+ * parent = $page({
991
+ * component: () => <NestedView />,
992
+ * });
993
+ *
994
+ * child = $page({
995
+ * parent: this.root,
996
+ * component: () => <div>Child Page</div>,
997
+ * });
998
+ * }
999
+ * ```
1000
+ */
1001
+ const NestedView = (props) => {
1002
+ const routerLayer = use(RouterLayerContext);
1003
+ const index = routerLayer?.index ?? 0;
1004
+ const onError = routerLayer?.onError;
1005
+ const state = useRouterState();
1006
+ const alepha = useAlepha();
1007
+ const [view, setView] = useState(state.layers[index]?.element);
1008
+ const [animation, setAnimation] = useState("");
1009
+ const animationExitDuration = useRef(0);
1010
+ const animationExitNow = useRef(0);
1011
+ useEvents({
1012
+ "react:transition:begin": async ({ previous, state }) => {
1013
+ const layer = previous.layers[index];
1014
+ if (!layer) return;
1015
+ if (`${state.url.pathname}/`.startsWith(`${layer.path}/`)) return;
1016
+ const animationExit = parseAnimation(layer.route?.animation, state, "exit");
1017
+ if (animationExit) {
1018
+ const duration = animationExit.duration || 200;
1019
+ animationExitNow.current = Date.now();
1020
+ animationExitDuration.current = duration;
1021
+ setAnimation(animationExit.animation);
1022
+ } else {
1023
+ animationExitNow.current = 0;
1024
+ animationExitDuration.current = 0;
1025
+ setAnimation("");
1026
+ }
1027
+ },
1028
+ "react:transition:end": async ({ state }) => {
1029
+ const layer = state.layers[index];
1030
+ if (animationExitNow.current) {
1031
+ const duration = animationExitDuration.current;
1032
+ const diff = Date.now() - animationExitNow.current;
1033
+ if (diff < duration) await new Promise((resolve) => setTimeout(resolve, duration - diff));
1034
+ }
1035
+ if (!layer?.cache) {
1036
+ setView(layer?.element);
1037
+ const animationEnter = parseAnimation(layer?.route?.animation, state, "enter");
1038
+ if (animationEnter) setAnimation(animationEnter.animation);
1039
+ else setAnimation("");
1040
+ }
1041
+ }
1042
+ }, []);
1043
+ let element = view ?? props.children ?? null;
1044
+ if (animation) element = /* @__PURE__ */ jsx("div", {
1045
+ style: {
1046
+ display: "flex",
1047
+ flex: 1,
1048
+ height: "100%",
1049
+ width: "100%",
1050
+ position: "relative",
1051
+ overflow: "hidden"
1052
+ },
1053
+ children: /* @__PURE__ */ jsx("div", {
1054
+ style: {
1055
+ height: "100%",
1056
+ width: "100%",
1057
+ display: "flex",
1058
+ animation
1059
+ },
1060
+ children: element
1061
+ })
1062
+ });
1063
+ if (props.errorBoundary === false) return /* @__PURE__ */ jsx(Fragment, { children: element });
1064
+ if (props.errorBoundary) return /* @__PURE__ */ jsx(ErrorBoundary, {
1065
+ fallback: props.errorBoundary,
1066
+ children: element
1067
+ });
1068
+ const fallback = (error) => {
1069
+ const result = onError?.(error, state) ?? /* @__PURE__ */ jsx(ErrorViewer_default, {
1070
+ error,
1071
+ alepha
1072
+ });
1073
+ if (result instanceof Redirection) return "Redirection inside ErrorBoundary is not allowed.";
1074
+ return result;
1075
+ };
1076
+ return /* @__PURE__ */ jsx(ErrorBoundary, {
1077
+ fallback,
1078
+ children: element
1079
+ });
1080
+ };
1081
+ var NestedView_default = memo(NestedView);
1082
+ function parseAnimation(animationLike, state, type = "enter") {
1083
+ if (!animationLike) return;
1084
+ const DEFAULT_DURATION = 300;
1085
+ const animation = typeof animationLike === "function" ? animationLike(state) : animationLike;
1086
+ if (typeof animation === "string") {
1087
+ if (type === "exit") return;
1088
+ return {
1089
+ duration: DEFAULT_DURATION,
1090
+ animation: `${DEFAULT_DURATION}ms ${animation}`
1091
+ };
1092
+ }
1093
+ if (typeof animation === "object") {
1094
+ const anim = animation[type];
1095
+ const duration = typeof anim === "object" ? anim.duration ?? DEFAULT_DURATION : DEFAULT_DURATION;
1096
+ const name = typeof anim === "object" ? anim.name : anim;
1097
+ if (type === "exit") return {
1098
+ duration,
1099
+ animation: `${duration}ms ${typeof anim === "object" ? anim.timing ?? "" : ""} ${name}`
1100
+ };
1101
+ return {
1102
+ duration,
1103
+ animation: `${duration}ms ${typeof anim === "object" ? anim.timing ?? "" : ""} ${name}`
1104
+ };
1105
+ }
1106
+ }
1107
+
1108
+ //#endregion
1109
+ //#region ../../src/react/router/providers/ReactPageProvider.ts
1110
+ const envSchema = t.object({ REACT_STRICT_MODE: t.boolean({ default: true }) });
1111
+ /**
1112
+ * Handle page routes for React applications. (Browser and Server)
1113
+ */
1114
+ var ReactPageProvider = class {
1115
+ log = $logger();
1116
+ env = $env(envSchema);
1117
+ alepha = $inject(Alepha);
1118
+ pages = [];
1119
+ getPages() {
1120
+ return this.pages;
1121
+ }
1122
+ getConcretePages() {
1123
+ const pages = [];
1124
+ for (const page of this.pages) {
1125
+ if (page.children && page.children.length > 0) continue;
1126
+ const fullPath = this.pathname(page.name);
1127
+ if (fullPath.includes(":") || fullPath.includes("*")) {
1128
+ if (typeof page.static === "object") {
1129
+ const entries = page.static.entries;
1130
+ if (entries && entries.length > 0) for (const entry of entries) {
1131
+ const params = entry.params;
1132
+ const path = this.compile(page.path ?? "", params);
1133
+ if (!path.includes(":") && !path.includes("*")) pages.push({
1134
+ ...page,
1135
+ name: params[Object.keys(params)[0]],
1136
+ staticName: page.name,
1137
+ path,
1138
+ ...entry
1139
+ });
1140
+ }
1141
+ }
1142
+ continue;
1143
+ }
1144
+ pages.push(page);
1145
+ }
1146
+ return pages;
1147
+ }
1148
+ page(name) {
1149
+ for (const page of this.pages) if (page.name === name) return page;
1150
+ throw new AlephaError(`Page '${name}' not found`);
1151
+ }
1152
+ pathname(name, options = {}) {
1153
+ const page = this.page(name);
1154
+ if (!page) throw new AlephaError(`Page ${name} not found`);
1155
+ let url = page.path ?? "";
1156
+ let parent = page.parent;
1157
+ while (parent) {
1158
+ url = `${parent.path ?? ""}/${url}`;
1159
+ parent = parent.parent;
1160
+ }
1161
+ url = this.compile(url, options.params ?? {});
1162
+ if (options.query) {
1163
+ const query = new URLSearchParams(options.query);
1164
+ if (query.toString()) url += `?${query.toString()}`;
1165
+ }
1166
+ return url.replace(/\/\/+/g, "/") || "/";
1167
+ }
1168
+ url(name, options = {}) {
1169
+ return new URL(this.pathname(name, options), options.host ?? `http://localhost`);
1170
+ }
1171
+ root(state) {
1172
+ const root = createElement(AlephaContext.Provider, { value: this.alepha }, createElement(NestedView_default, {}, state.layers[0]?.element));
1173
+ if (this.env.REACT_STRICT_MODE) return createElement(StrictMode, {}, root);
1174
+ return root;
1175
+ }
1176
+ convertStringObjectToObject = (schema, value) => {
1177
+ if (t.schema.isObject(schema) && typeof value === "object") {
1178
+ for (const key in schema.properties) if (t.schema.isObject(schema.properties[key]) && typeof value[key] === "string") try {
1179
+ value[key] = this.alepha.codec.decode(schema.properties[key], decodeURIComponent(value[key]));
1180
+ } catch (e) {}
1181
+ }
1182
+ return value;
1183
+ };
1184
+ /**
1185
+ * Create a new RouterState based on a given route and request.
1186
+ * This method resolves the layers for the route, applying any query and params schemas defined in the route.
1187
+ * It also handles errors and redirects.
1188
+ */
1189
+ async createLayers(route, state, previous = []) {
1190
+ let context = {};
1191
+ const stack = [{ route }];
1192
+ let parent = route.parent;
1193
+ while (parent) {
1194
+ stack.unshift({ route: parent });
1195
+ parent = parent.parent;
1196
+ }
1197
+ let forceRefresh = false;
1198
+ for (let i = 0; i < stack.length; i++) {
1199
+ const it = stack[i];
1200
+ const route = it.route;
1201
+ const config = {};
1202
+ try {
1203
+ this.convertStringObjectToObject(route.schema?.query, state.query);
1204
+ config.query = route.schema?.query ? this.alepha.codec.decode(route.schema.query, state.query) : {};
1205
+ } catch (e) {
1206
+ it.error = e;
1207
+ break;
1208
+ }
1209
+ try {
1210
+ config.params = route.schema?.params ? this.alepha.codec.decode(route.schema.params, state.params) : {};
1211
+ } catch (e) {
1212
+ it.error = e;
1213
+ break;
1214
+ }
1215
+ it.config = { ...config };
1216
+ if (previous?.[i] && !forceRefresh && previous[i].name === route.name) {
1217
+ const url = (str) => str ? str.replace(/\/\/+/g, "/") : "/";
1218
+ if (JSON.stringify({
1219
+ part: url(previous[i].part),
1220
+ params: previous[i].config?.params ?? {}
1221
+ }) === JSON.stringify({
1222
+ part: url(route.path),
1223
+ params: config.params ?? {}
1224
+ })) {
1225
+ it.props = previous[i].props;
1226
+ it.error = previous[i].error;
1227
+ it.cache = true;
1228
+ context = {
1229
+ ...context,
1230
+ ...it.props
1231
+ };
1232
+ continue;
1233
+ }
1234
+ forceRefresh = true;
1235
+ }
1236
+ if (!route.loader) continue;
1237
+ try {
1238
+ const args = Object.create(state);
1239
+ Object.assign(args, config, context);
1240
+ const props = await route.loader?.(args) ?? {};
1241
+ it.props = { ...props };
1242
+ context = {
1243
+ ...context,
1244
+ ...props
1245
+ };
1246
+ } catch (e) {
1247
+ if (e instanceof Redirection) return { redirect: e.redirect };
1248
+ this.log.error("Page loader has failed", e);
1249
+ it.error = e;
1250
+ break;
1251
+ }
1252
+ }
1253
+ let acc = "";
1254
+ for (let i = 0; i < stack.length; i++) {
1255
+ const it = stack[i];
1256
+ const props = it.props ?? {};
1257
+ const params = { ...it.config?.params };
1258
+ for (const key of Object.keys(params)) params[key] = String(params[key]);
1259
+ acc += "/";
1260
+ acc += it.route.path ? this.compile(it.route.path, params) : "";
1261
+ const path = acc.replace(/\/+/, "/");
1262
+ const localErrorHandler = this.getErrorHandler(it.route);
1263
+ if (localErrorHandler) {
1264
+ const onErrorParent = state.onError;
1265
+ state.onError = (error, context) => {
1266
+ const result = localErrorHandler(error, context);
1267
+ if (result === void 0) return onErrorParent(error, context);
1268
+ return result;
1269
+ };
1270
+ }
1271
+ if (!it.error) try {
1272
+ const element = await this.createElement(it.route, {
1273
+ ...it.route.props ? it.route.props() : {},
1274
+ ...props,
1275
+ ...context
1276
+ });
1277
+ state.layers.push({
1278
+ name: it.route.name,
1279
+ props,
1280
+ part: it.route.path,
1281
+ config: it.config,
1282
+ element: this.renderView(i + 1, path, element, it.route),
1283
+ index: i + 1,
1284
+ path,
1285
+ route: it.route,
1286
+ cache: it.cache
1287
+ });
1288
+ } catch (e) {
1289
+ it.error = e;
1290
+ }
1291
+ if (it.error) try {
1292
+ let element = await state.onError(it.error, state);
1293
+ if (element === void 0) throw it.error;
1294
+ if (element instanceof Redirection) return { redirect: element.redirect };
1295
+ if (element === null) element = this.renderError(it.error);
1296
+ state.layers.push({
1297
+ props,
1298
+ error: it.error,
1299
+ name: it.route.name,
1300
+ part: it.route.path,
1301
+ config: it.config,
1302
+ element: this.renderView(i + 1, path, element, it.route),
1303
+ index: i + 1,
1304
+ path,
1305
+ route: it.route
1306
+ });
1307
+ break;
1308
+ } catch (e) {
1309
+ if (e instanceof Redirection) return { redirect: e.redirect };
1310
+ throw e;
1311
+ }
1312
+ }
1313
+ return { state };
1314
+ }
1315
+ getErrorHandler(route) {
1316
+ if (route.errorHandler) return route.errorHandler;
1317
+ let parent = route.parent;
1318
+ while (parent) {
1319
+ if (parent.errorHandler) return parent.errorHandler;
1320
+ parent = parent.parent;
1321
+ }
1322
+ }
1323
+ async createElement(page, props) {
1324
+ if (page.lazy && page.component) this.log.warn(`Page ${page.name} has both lazy and component options, lazy will be used`);
1325
+ if (page.lazy) return createElement((await page.lazy()).default, props);
1326
+ if (page.component) return createElement(page.component, props);
1327
+ }
1328
+ renderError(error) {
1329
+ return createElement(ErrorViewer_default, {
1330
+ error,
1331
+ alepha: this.alepha
1332
+ });
1333
+ }
1334
+ renderEmptyView() {
1335
+ return createElement(NestedView_default, {});
1336
+ }
1337
+ href(page, params = {}) {
1338
+ const found = this.pages.find((it) => it.name === page.options.name);
1339
+ if (!found) throw new AlephaError(`Page ${page.options.name} not found`);
1340
+ let url = found.path ?? "";
1341
+ let parent = found.parent;
1342
+ while (parent) {
1343
+ url = `${parent.path ?? ""}/${url}`;
1344
+ parent = parent.parent;
1345
+ }
1346
+ url = this.compile(url, params);
1347
+ return url.replace(/\/\/+/g, "/") || "/";
1348
+ }
1349
+ compile(path, params = {}) {
1350
+ for (const [key, value] of Object.entries(params)) path = path.replace(`:${key}`, value);
1351
+ return path;
1352
+ }
1353
+ renderView(index, path, view, page) {
1354
+ view ??= this.renderEmptyView();
1355
+ const element = page.client ? createElement(ClientOnly, typeof page.client === "object" ? page.client : {}, view) : view;
1356
+ return createElement(RouterLayerContext.Provider, { value: {
1357
+ index,
1358
+ path,
1359
+ onError: this.getErrorHandler(page) ?? ((error) => this.renderError(error))
1360
+ } }, element);
1361
+ }
1362
+ configure = $hook({
1363
+ on: "configure",
1364
+ handler: () => {
1365
+ let hasNotFoundHandler = false;
1366
+ const pages = this.alepha.primitives($page);
1367
+ const hasParent = (it) => {
1368
+ if (it.options.parent) return true;
1369
+ for (const page of pages) if ((page.options.children ? Array.isArray(page.options.children) ? page.options.children : page.options.children() : []).includes(it)) return true;
1370
+ };
1371
+ for (const page of pages) {
1372
+ if (page.options.path === "/*") hasNotFoundHandler = true;
1373
+ if (hasParent(page)) continue;
1374
+ this.add(this.map(pages, page));
1375
+ }
1376
+ if (!hasNotFoundHandler && pages.length > 0) this.add({
1377
+ path: "/*",
1378
+ name: "notFound",
1379
+ cache: true,
1380
+ component: NotFound_default,
1381
+ onServerResponse: ({ reply }) => {
1382
+ reply.status = 404;
1383
+ }
1384
+ });
1385
+ }
1386
+ });
1387
+ map(pages, target) {
1388
+ const children = target.options.children ? Array.isArray(target.options.children) ? target.options.children : target.options.children() : [];
1389
+ const getChildrenFromParent = (it) => {
1390
+ const children = [];
1391
+ for (const page of pages) if (page.options.parent === it) children.push(page);
1392
+ return children;
1393
+ };
1394
+ children.push(...getChildrenFromParent(target));
1395
+ return {
1396
+ ...target.options,
1397
+ name: target.name,
1398
+ parent: void 0,
1399
+ children: children.map((it) => this.map(pages, it))
1400
+ };
1401
+ }
1402
+ add(entry) {
1403
+ if (this.alepha.isReady()) throw new AlephaError("Router is already initialized");
1404
+ entry.name ??= this.nextId();
1405
+ const page = entry;
1406
+ page.match = this.createMatch(page);
1407
+ this.pages.push(page);
1408
+ if (page.children) for (const child of page.children) {
1409
+ child.parent = page;
1410
+ this.add(child);
1411
+ }
1412
+ }
1413
+ createMatch(page) {
1414
+ let url = page.path ?? "/";
1415
+ let target = page.parent;
1416
+ while (target) {
1417
+ url = `${target.path ?? ""}/${url}`;
1418
+ target = target.parent;
1419
+ }
1420
+ let path = url.replace(/\/\/+/g, "/");
1421
+ if (path.endsWith("/") && path !== "/") path = path.slice(0, -1);
1422
+ return path;
1423
+ }
1424
+ _next = 0;
1425
+ nextId() {
1426
+ this._next += 1;
1427
+ return `P${this._next}`;
1428
+ }
1429
+ };
1430
+ const isPageRoute = (it) => {
1431
+ return it && typeof it === "object" && typeof it.path === "string" && typeof it.page === "object";
1432
+ };
1433
+
1434
+ //#endregion
1435
+ //#region ../../src/react/router/providers/ReactBrowserRouterProvider.ts
1436
+ /**
1437
+ * Implementation of AlephaRouter for React in browser environment.
1438
+ */
1439
+ var ReactBrowserRouterProvider = class extends RouterProvider {
1440
+ log = $logger();
1441
+ alepha = $inject(Alepha);
1442
+ pageApi = $inject(ReactPageProvider);
1443
+ browserHeadProvider = $inject(BrowserHeadProvider);
1444
+ add(entry) {
1445
+ this.pageApi.add(entry);
1446
+ }
1447
+ configure = $hook({
1448
+ on: "configure",
1449
+ handler: async () => {
1450
+ for (const page of this.pageApi.getPages()) if (page.component || page.lazy) this.push({
1451
+ path: page.match,
1452
+ page
1453
+ });
1454
+ }
1455
+ });
1456
+ async transition(url, previous = [], meta = {}) {
1457
+ const { pathname, search } = url;
1458
+ const state = {
1459
+ url,
1460
+ query: {},
1461
+ params: {},
1462
+ layers: [],
1463
+ onError: () => null,
1464
+ meta
1465
+ };
1466
+ await this.alepha.events.emit("react:action:begin", { type: "transition" });
1467
+ await this.alepha.events.emit("react:transition:begin", {
1468
+ previous: this.alepha.store.get("alepha.react.router.state"),
1469
+ state
1470
+ });
1471
+ try {
1472
+ const { route, params } = this.match(pathname);
1473
+ const query = {};
1474
+ if (search) for (const [key, value] of new URLSearchParams(search).entries()) query[key] = String(value);
1475
+ state.name = route?.page.name;
1476
+ state.query = query;
1477
+ state.params = params ?? {};
1478
+ if (isPageRoute(route)) {
1479
+ const { redirect } = await this.pageApi.createLayers(route.page, state, previous);
1480
+ if (redirect) return redirect;
1481
+ }
1482
+ if (state.layers.length === 0) state.layers.push({
1483
+ name: "not-found",
1484
+ element: createElement(NotFound_default),
1485
+ index: 0,
1486
+ path: "/"
1487
+ });
1488
+ await this.alepha.events.emit("react:action:success", { type: "transition" });
1489
+ await this.alepha.events.emit("react:transition:success", { state });
1490
+ } catch (e) {
1491
+ this.log.error("Transition has failed", e);
1492
+ state.layers = [{
1493
+ name: "error",
1494
+ element: this.pageApi.renderError(e),
1495
+ index: 0,
1496
+ path: "/"
1497
+ }];
1498
+ await this.alepha.events.emit("react:action:error", {
1499
+ type: "transition",
1500
+ error: e
1501
+ });
1502
+ await this.alepha.events.emit("react:transition:error", {
1503
+ error: e,
1504
+ state
1505
+ });
1506
+ }
1507
+ if (previous) for (let i = 0; i < previous.length; i++) {
1508
+ const layer = previous[i];
1509
+ if (state.layers[i]?.name !== layer.name) this.pageApi.page(layer.name)?.onLeave?.();
1510
+ }
1511
+ for (let i = 0; i < state.layers.length; i++) {
1512
+ const layer = state.layers[i];
1513
+ if (previous?.[i]?.name !== layer.name) this.pageApi.page(layer.name)?.onEnter?.();
1514
+ }
1515
+ this.alepha.store.set("alepha.react.router.state", state);
1516
+ await this.alepha.events.emit("react:action:end", { type: "transition" });
1517
+ await this.alepha.events.emit("react:transition:end", { state });
1518
+ this.browserHeadProvider.fillAndRenderHead(state);
1519
+ }
1520
+ root(state) {
1521
+ return this.pageApi.root(state);
1522
+ }
1523
+ };
1524
+
1525
+ //#endregion
1526
+ //#region ../../src/react/router/providers/ReactBrowserProvider.ts
1527
+ /**
1528
+ * React browser renderer configuration atom
1529
+ */
1530
+ const reactBrowserOptions = $atom({
1531
+ name: "alepha.react.browser.options",
1532
+ schema: t.object({ scrollRestoration: t.enum(["top", "manual"]) }),
1533
+ default: { scrollRestoration: "top" }
1534
+ });
1535
+ var ReactBrowserProvider = class {
1536
+ log = $logger();
1537
+ client = $inject(LinkProvider);
1538
+ alepha = $inject(Alepha);
1539
+ router = $inject(ReactBrowserRouterProvider);
1540
+ dateTimeProvider = $inject(DateTimeProvider);
1541
+ browserHeadProvider = $inject(BrowserHeadProvider);
1542
+ options = $use(reactBrowserOptions);
1543
+ get rootId() {
1544
+ return "root";
1545
+ }
1546
+ getRootElement() {
1547
+ const root = this.document.getElementById(this.rootId);
1548
+ if (root) return root;
1549
+ const div = this.document.createElement("div");
1550
+ div.id = this.rootId;
1551
+ this.document.body.prepend(div);
1552
+ return div;
1553
+ }
1554
+ transitioning;
1555
+ get state() {
1556
+ return this.alepha.store.get("alepha.react.router.state");
1557
+ }
1558
+ /**
1559
+ * Accessor for Document DOM API.
1560
+ */
1561
+ get document() {
1562
+ return window.document;
1563
+ }
1564
+ /**
1565
+ * Accessor for History DOM API.
1566
+ */
1567
+ get history() {
1568
+ return window.history;
1569
+ }
1570
+ /**
1571
+ * Accessor for Location DOM API.
1572
+ */
1573
+ get location() {
1574
+ return window.location;
1575
+ }
1576
+ get base() {
1577
+ const base = import.meta.env?.BASE_URL;
1578
+ if (!base || base === "/") return "";
1579
+ return base;
1580
+ }
1581
+ get url() {
1582
+ const url = this.location.pathname + this.location.search;
1583
+ if (this.base) return url.replace(this.base, "");
1584
+ return url;
1585
+ }
1586
+ pushState(path, replace) {
1587
+ const url = this.base + path;
1588
+ if (replace) this.history.replaceState({}, "", url);
1589
+ else this.history.pushState({}, "", url);
1590
+ }
1591
+ async invalidate(props) {
1592
+ const previous = [];
1593
+ this.log.trace("Invalidating layers");
1594
+ if (props) {
1595
+ const [key] = Object.keys(props);
1596
+ const value = props[key];
1597
+ for (const layer of this.state.layers) {
1598
+ if (layer.props?.[key]) {
1599
+ previous.push({
1600
+ ...layer,
1601
+ props: {
1602
+ ...layer.props,
1603
+ [key]: value
1604
+ }
1605
+ });
1606
+ break;
1607
+ }
1608
+ previous.push(layer);
1609
+ }
1610
+ }
1611
+ await this.render({ previous });
1612
+ }
1613
+ async push(url, options = {}) {
1614
+ this.log.trace(`Going to ${url}`, {
1615
+ url,
1616
+ options
1617
+ });
1618
+ await this.render({
1619
+ url,
1620
+ previous: options.force ? [] : this.state.layers,
1621
+ meta: options.meta
1622
+ });
1623
+ if (this.state.url.pathname + this.state.url.search !== url) {
1624
+ this.pushState(this.state.url.pathname + this.state.url.search);
1625
+ return;
1626
+ }
1627
+ this.pushState(url, options.replace);
1628
+ }
1629
+ async render(options = {}) {
1630
+ const previous = options.previous ?? this.state.layers;
1631
+ const url = options.url ?? this.url;
1632
+ const start = this.dateTimeProvider.now();
1633
+ this.transitioning = {
1634
+ to: url,
1635
+ from: this.state?.url.pathname
1636
+ };
1637
+ this.log.debug("Transitioning...", { to: url });
1638
+ const redirect = await this.router.transition(new URL(`http://localhost${url}`), previous, options.meta);
1639
+ if (redirect) {
1640
+ this.log.info("Redirecting to", { redirect });
1641
+ if (redirect.startsWith("http")) window.location.href = redirect;
1642
+ else return await this.render({ url: redirect });
1643
+ }
1644
+ const ms = this.dateTimeProvider.now().diff(start);
1645
+ this.log.info(`Transition OK [${ms}ms]`, this.transitioning);
1646
+ this.transitioning = void 0;
1647
+ }
1648
+ /**
1649
+ * Get embedded layers from the server.
1650
+ */
1651
+ getHydrationState() {
1652
+ try {
1653
+ if ("__ssr" in window && typeof window.__ssr === "object") return window.__ssr;
1654
+ } catch (error) {
1655
+ console.error(error);
1656
+ }
1657
+ }
1658
+ onTransitionEnd = $hook({
1659
+ on: "react:transition:end",
1660
+ handler: () => {
1661
+ if (this.options.scrollRestoration === "top" && typeof window !== "undefined" && !this.alepha.isTest()) {
1662
+ this.log.trace("Restoring scroll position to top");
1663
+ window.scrollTo(0, 0);
1664
+ }
1665
+ }
1666
+ });
1667
+ ready = $hook({
1668
+ on: "ready",
1669
+ handler: async () => {
1670
+ const hydration = this.getHydrationState();
1671
+ const previous = hydration?.layers ?? [];
1672
+ if (hydration) {
1673
+ for (const [key, value] of Object.entries(hydration)) if (key !== "layers") this.alepha.set(key, value);
1674
+ }
1675
+ await this.render({ previous });
1676
+ const element = this.router.root(this.state);
1677
+ await this.alepha.events.emit("react:browser:render", {
1678
+ element,
1679
+ root: this.getRootElement(),
1680
+ hydration,
1681
+ state: this.state
1682
+ });
1683
+ this.browserHeadProvider.fillAndRenderHead(this.state);
1684
+ window.addEventListener("popstate", () => {
1685
+ if (this.base + this.state.url.pathname === this.location.pathname) return;
1686
+ this.log.debug("Popstate event triggered - rendering new state", { url: this.location.pathname + this.location.search });
1687
+ this.render();
1688
+ });
1689
+ }
1690
+ });
1691
+ };
1692
+
1693
+ //#endregion
1694
+ //#region ../../src/react/router/providers/ReactBrowserRendererProvider.ts
1695
+ /**
1696
+ * Browser specific React renderer (react-dom/client interface)
1697
+ */
1698
+ var ReactBrowserRendererProvider = class {
1699
+ log = $logger();
1700
+ root;
1701
+ onBrowserRender = $hook({
1702
+ on: "react:browser:render",
1703
+ handler: async ({ hydration, root, element }) => {
1704
+ if (hydration?.layers) {
1705
+ this.root = hydrateRoot(root, element);
1706
+ this.log.info("Hydrated root element");
1707
+ } else {
1708
+ this.root ??= createRoot(root);
1709
+ this.root.render(element);
1710
+ this.log.info("Created root element");
1711
+ }
1712
+ }
1713
+ });
1714
+ };
1715
+
1716
+ //#endregion
1717
+ //#region ../../src/react/router/services/ReactRouter.ts
1718
+ /**
1719
+ * Friendly browser router API.
1720
+ *
1721
+ * Can be safely used server-side, but most methods will be no-op.
1722
+ */
1723
+ var ReactRouter = class {
1724
+ alepha = $inject(Alepha);
1725
+ pageApi = $inject(ReactPageProvider);
1726
+ get state() {
1727
+ return this.alepha.store.get("alepha.react.router.state");
1728
+ }
1729
+ get pages() {
1730
+ return this.pageApi.getPages();
1731
+ }
1732
+ get concretePages() {
1733
+ return this.pageApi.getConcretePages();
1734
+ }
1735
+ get browser() {
1736
+ if (this.alepha.isBrowser()) return this.alepha.inject(ReactBrowserProvider);
1737
+ }
1738
+ isActive(href, options = {}) {
1739
+ const current = this.state.url.pathname;
1740
+ let isActive = current === href || current === `${href}/` || `${current}/` === href;
1741
+ if (options.startWith && !isActive) isActive = current.startsWith(href);
1742
+ return isActive;
1743
+ }
1744
+ node(name, config = {}) {
1745
+ const page = this.pageApi.page(name);
1746
+ if (!page.lazy && !page.component) return {
1747
+ ...page,
1748
+ label: page.label ?? page.name,
1749
+ children: void 0
1750
+ };
1751
+ return {
1752
+ ...page,
1753
+ label: page.label ?? page.name,
1754
+ href: this.path(name, config),
1755
+ children: void 0
1756
+ };
1757
+ }
1758
+ path(name, config = {}) {
1759
+ return this.pageApi.pathname(name, {
1760
+ params: {
1761
+ ...this.state?.params,
1762
+ ...config.params
1763
+ },
1764
+ query: config.query
1765
+ });
1766
+ }
1767
+ /**
1768
+ * Reload the current page.
1769
+ * This is equivalent to calling `go()` with the current pathname and search.
1770
+ */
1771
+ async reload() {
1772
+ if (!this.browser) return;
1773
+ await this.push(this.location.pathname + this.location.search, {
1774
+ replace: true,
1775
+ force: true
1776
+ });
1777
+ }
1778
+ getURL() {
1779
+ if (!this.browser) return this.state.url;
1780
+ return new URL(this.location.href);
1781
+ }
1782
+ get location() {
1783
+ if (!this.browser) throw new Error("Browser is required");
1784
+ return this.browser.location;
1785
+ }
1786
+ get current() {
1787
+ return this.state;
1788
+ }
1789
+ get pathname() {
1790
+ return this.state.url.pathname;
1791
+ }
1792
+ get query() {
1793
+ const query = {};
1794
+ for (const [key, value] of new URLSearchParams(this.state.url.search).entries()) query[key] = String(value);
1795
+ return query;
1796
+ }
1797
+ async back() {
1798
+ this.browser?.history.back();
1799
+ }
1800
+ async forward() {
1801
+ this.browser?.history.forward();
1802
+ }
1803
+ async invalidate(props) {
1804
+ await this.browser?.invalidate(props);
1805
+ }
1806
+ async push(path, options) {
1807
+ for (const page of this.pages) if (page.name === path) {
1808
+ await this.browser?.push(this.path(path, options), options);
1809
+ return;
1810
+ }
1811
+ await this.browser?.push(path, options);
1812
+ }
1813
+ anchor(path, options = {}) {
1814
+ let href = path;
1815
+ for (const page of this.pages) if (page.name === path) {
1816
+ href = this.path(path, options);
1817
+ break;
1818
+ }
1819
+ return {
1820
+ href: this.base(href),
1821
+ onClick: (ev) => {
1822
+ ev.stopPropagation();
1823
+ ev.preventDefault();
1824
+ this.push(href, options).catch(console.error);
1825
+ }
1826
+ };
1827
+ }
1828
+ base(path) {
1829
+ const base = import.meta.env?.BASE_URL;
1830
+ if (!base || base === "/") return path;
1831
+ return base + path;
1832
+ }
1833
+ /**
1834
+ * Set query params.
1835
+ *
1836
+ * @param record
1837
+ * @param options
1838
+ */
1839
+ setQueryParams(record, options = {}) {
1840
+ const func = typeof record === "function" ? record : () => record;
1841
+ const search = new URLSearchParams(func(this.query)).toString();
1842
+ const state = search ? `${this.pathname}?${search}` : this.pathname;
1843
+ if (options.push) window.history.pushState({}, "", state);
1844
+ else window.history.replaceState({}, "", state);
1845
+ }
1846
+ };
1847
+
1848
+ //#endregion
1849
+ //#region ../../src/react/router/hooks/useRouter.ts
1850
+ /**
1851
+ * Use this hook to access the React Router instance.
1852
+ *
1853
+ * You can add a type parameter to specify the type of your application.
1854
+ * This will allow you to use the router in a typesafe way.
1855
+ *
1856
+ * @example
1857
+ * class App {
1858
+ * home = $page();
1859
+ * }
1860
+ *
1861
+ * const router = useRouter<App>();
1862
+ * router.push("home"); // typesafe
1863
+ */
1864
+ const useRouter = () => {
1865
+ return useInject(ReactRouter);
1866
+ };
1867
+
1868
+ //#endregion
1869
+ //#region ../../src/react/router/components/Link.tsx
1870
+ /**
1871
+ * Link component for client-side navigation.
1872
+ *
1873
+ * It's a simple wrapper around an anchor (`<a>`) element using the `useRouter` hook.
1874
+ */
1875
+ const Link = (props) => {
1876
+ const router = useRouter();
1877
+ return createElement("a", {
1878
+ ...props,
1879
+ ...router.anchor(props.href)
1880
+ }, props.children);
1881
+ };
1882
+ var Link_default = Link;
1883
+
1884
+ //#endregion
1885
+ //#region ../../src/react/router/hooks/useActive.ts
1886
+ /**
1887
+ * Hook to determine if a given route is active and to provide anchor props for navigation.
1888
+ * This hook refreshes on router state changes.
1889
+ */
1890
+ const useActive = (args) => {
1891
+ useRouterState();
1892
+ const router = useRouter();
1893
+ const [isPending, setPending] = useState(false);
1894
+ const options = typeof args === "string" ? { href: args } : {
1895
+ ...args,
1896
+ href: args.href
1897
+ };
1898
+ const href = options.href;
1899
+ const isActive = router.isActive(href, options);
1900
+ return {
1901
+ isPending,
1902
+ isActive,
1903
+ anchorProps: {
1904
+ href: router.base(href),
1905
+ onClick: async (ev) => {
1906
+ ev?.stopPropagation();
1907
+ ev?.preventDefault();
1908
+ if (isActive) return;
1909
+ if (isPending) return;
1910
+ setPending(true);
1911
+ try {
1912
+ await router.push(href);
1913
+ } finally {
1914
+ setPending(false);
1915
+ }
1916
+ }
1917
+ }
1918
+ };
1919
+ };
1920
+
1921
+ //#endregion
1922
+ //#region ../../src/react/router/hooks/useQueryParams.ts
1923
+ /**
1924
+ * Hook to manage query parameters in the URL using a defined schema.
1925
+ */
1926
+ const useQueryParams = (schema, options = {}) => {
1927
+ const alepha = useAlepha();
1928
+ const key = options.key ?? "q";
1929
+ const router = useRouter();
1930
+ const querystring = router.query[key];
1931
+ const [queryParams = {}, setQueryParams] = useState(decode(alepha, schema, router.query[key]));
1932
+ useEffect(() => {
1933
+ setQueryParams(decode(alepha, schema, querystring));
1934
+ }, [querystring]);
1935
+ return [queryParams, (queryParams) => {
1936
+ setQueryParams(queryParams);
1937
+ router.setQueryParams((data) => {
1938
+ return {
1939
+ ...data,
1940
+ [key]: encode(alepha, schema, queryParams)
1941
+ };
1942
+ });
1943
+ }];
1944
+ };
1945
+ const encode = (alepha, schema, data) => {
1946
+ return btoa(JSON.stringify(alepha.codec.decode(schema, data)));
1947
+ };
1948
+ const decode = (alepha, schema, data) => {
1949
+ try {
1950
+ return alepha.codec.decode(schema, JSON.parse(atob(decodeURIComponent(data))));
1951
+ } catch {
1952
+ return;
1953
+ }
1954
+ };
1955
+
1956
+ //#endregion
1957
+ //#region ../../src/react/router/index.browser.ts
1958
+ const AlephaReactRouter = $module({
1959
+ name: "alepha.react.router",
1960
+ primitives: [$page],
1961
+ services: [
1962
+ ReactPageProvider,
1963
+ ReactBrowserRouterProvider,
1964
+ ReactBrowserProvider,
1965
+ ReactRouter,
1966
+ ReactBrowserRendererProvider,
1967
+ ReactPageService
1968
+ ],
1969
+ register: (alepha) => alepha.with(AlephaReact).with(AlephaDateTime).with(AlephaServer).with(AlephaServerLinks).with(ReactPageProvider).with(ReactBrowserProvider).with(ReactBrowserRouterProvider).with(ReactBrowserRendererProvider).with(ReactRouter)
1970
+ });
1971
+
1972
+ //#endregion
1973
+ export { $page, AlephaReactRouter, ErrorViewer_default as ErrorViewer, Link_default as Link, NestedView_default as NestedView, NotFound_default as NotFound, PAGE_PRELOAD_KEY, PagePrimitive, ReactBrowserProvider, ReactBrowserRendererProvider, ReactBrowserRouterProvider, ReactPageProvider, ReactPageService, ReactRouter, Redirection, RouterLayerContext, isPageRoute, reactBrowserOptions, useActive, useQueryParams, useRouter, useRouterState };
1974
+ //# sourceMappingURL=index.browser.js.map