@alepha/react 0.11.10 → 0.11.12

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 (128) hide show
  1. package/README.md +1 -183
  2. package/dist/auth/index.browser.js +1460 -0
  3. package/dist/auth/index.browser.js.map +1 -0
  4. package/dist/auth/index.cjs +3647 -0
  5. package/dist/auth/index.cjs.map +1 -0
  6. package/dist/auth/index.d.cts +564 -0
  7. package/dist/auth/index.d.cts.map +1 -0
  8. package/dist/auth/index.d.ts +564 -0
  9. package/dist/auth/index.d.ts.map +1 -0
  10. package/dist/auth/index.js +3615 -0
  11. package/dist/auth/index.js.map +1 -0
  12. package/dist/{index.browser.js → core/index.browser.js} +36 -35
  13. package/dist/core/index.browser.js.map +1 -0
  14. package/dist/{index.cjs → core/index.cjs} +141 -140
  15. package/dist/core/index.cjs.map +1 -0
  16. package/dist/{index.d.cts → core/index.d.cts} +68 -68
  17. package/dist/core/index.d.cts.map +1 -0
  18. package/dist/{index.d.ts → core/index.d.ts} +68 -68
  19. package/dist/core/index.d.ts.map +1 -0
  20. package/dist/{index.js → core/index.js} +39 -38
  21. package/dist/core/index.js.map +1 -0
  22. package/dist/form/index.cjs +2054 -0
  23. package/dist/form/index.cjs.map +1 -0
  24. package/dist/form/index.d.cts +211 -0
  25. package/dist/form/index.d.cts.map +1 -0
  26. package/dist/form/index.d.ts +211 -0
  27. package/dist/form/index.d.ts.map +1 -0
  28. package/dist/form/index.js +2026 -0
  29. package/dist/form/index.js.map +1 -0
  30. package/dist/head/index.browser.js +1503 -0
  31. package/dist/head/index.browser.js.map +1 -0
  32. package/dist/head/index.cjs +1908 -0
  33. package/dist/head/index.cjs.map +1 -0
  34. package/dist/head/index.d.cts +595 -0
  35. package/dist/head/index.d.cts.map +1 -0
  36. package/dist/head/index.d.ts +601 -0
  37. package/dist/head/index.d.ts.map +1 -0
  38. package/dist/head/index.js +1880 -0
  39. package/dist/head/index.js.map +1 -0
  40. package/dist/i18n/index.cjs +1886 -0
  41. package/dist/i18n/index.cjs.map +1 -0
  42. package/dist/i18n/index.d.cts +168 -0
  43. package/dist/i18n/index.d.cts.map +1 -0
  44. package/dist/i18n/index.d.ts +168 -0
  45. package/dist/i18n/index.d.ts.map +1 -0
  46. package/dist/i18n/index.js +1857 -0
  47. package/dist/i18n/index.js.map +1 -0
  48. package/dist/websocket/index.cjs +1774 -0
  49. package/dist/websocket/index.cjs.map +1 -0
  50. package/dist/websocket/index.d.cts +118 -0
  51. package/dist/websocket/index.d.cts.map +1 -0
  52. package/dist/websocket/index.d.ts +118 -0
  53. package/dist/websocket/index.d.ts.map +1 -0
  54. package/dist/websocket/index.js +1750 -0
  55. package/dist/websocket/index.js.map +1 -0
  56. package/package.json +89 -67
  57. package/src/auth/descriptors/$auth.ts +436 -0
  58. package/src/auth/descriptors/$authApple.ts +8 -0
  59. package/src/auth/descriptors/$authGithub.ts +81 -0
  60. package/src/auth/descriptors/$authGoogle.ts +38 -0
  61. package/src/auth/errors/SessionExpiredError.ts +6 -0
  62. package/src/auth/hooks/useAuth.ts +31 -0
  63. package/src/auth/index.browser.ts +16 -0
  64. package/src/auth/index.shared.ts +3 -0
  65. package/src/auth/index.ts +47 -0
  66. package/src/auth/providers/ReactAuthProvider.ts +629 -0
  67. package/src/auth/schemas/tokenResponseSchema.ts +11 -0
  68. package/src/auth/schemas/tokensSchema.ts +21 -0
  69. package/src/auth/schemas/userinfoResponseSchema.ts +10 -0
  70. package/src/auth/services/ReactAuth.ts +124 -0
  71. package/src/{components → core/components}/ErrorViewer.tsx +3 -2
  72. package/src/{components → core/components}/NestedView.tsx +1 -1
  73. package/src/{contexts → core/contexts}/AlephaContext.ts +1 -1
  74. package/src/{descriptors → core/descriptors}/$page.ts +4 -4
  75. package/src/{hooks → core/hooks}/useAction.ts +1 -1
  76. package/src/{hooks → core/hooks}/useAlepha.ts +1 -1
  77. package/src/{hooks → core/hooks}/useClient.ts +1 -1
  78. package/src/{hooks → core/hooks}/useEvents.ts +1 -1
  79. package/src/{hooks → core/hooks}/useInject.ts +1 -1
  80. package/src/{hooks → core/hooks}/useQueryParams.ts +1 -1
  81. package/src/{hooks → core/hooks}/useRouterState.ts +1 -1
  82. package/src/{hooks → core/hooks}/useSchema.ts +3 -3
  83. package/src/{hooks → core/hooks}/useStore.ts +2 -2
  84. package/src/{index.browser.ts → core/index.browser.ts} +4 -4
  85. package/src/{index.ts → core/index.ts} +6 -6
  86. package/src/{providers → core/providers}/ReactBrowserProvider.ts +6 -6
  87. package/src/{providers → core/providers}/ReactBrowserRendererProvider.ts +2 -2
  88. package/src/{providers → core/providers}/ReactBrowserRouterProvider.ts +3 -3
  89. package/src/{providers → core/providers}/ReactPageProvider.ts +3 -3
  90. package/src/{providers → core/providers}/ReactServerProvider.ts +7 -7
  91. package/src/{services → core/services}/ReactPageServerService.ts +2 -2
  92. package/src/{services → core/services}/ReactPageService.ts +1 -1
  93. package/src/{services → core/services}/ReactRouter.ts +1 -1
  94. package/src/form/components/FormState.tsx +17 -0
  95. package/src/form/hooks/useForm.ts +47 -0
  96. package/src/form/hooks/useFormState.ts +130 -0
  97. package/src/form/index.ts +38 -0
  98. package/src/form/services/FormModel.ts +548 -0
  99. package/src/head/descriptors/$head.ts +25 -0
  100. package/src/head/hooks/useHead.ts +62 -0
  101. package/src/head/index.browser.ts +25 -0
  102. package/src/head/index.ts +47 -0
  103. package/src/head/interfaces/Head.ts +46 -0
  104. package/src/head/providers/BrowserHeadProvider.ts +105 -0
  105. package/src/head/providers/HeadProvider.ts +73 -0
  106. package/src/head/providers/ServerHeadProvider.ts +109 -0
  107. package/src/i18n/README.md +76 -0
  108. package/src/i18n/components/Localize.tsx +35 -0
  109. package/src/i18n/descriptors/$dictionary.ts +65 -0
  110. package/src/i18n/hooks/useI18n.ts +18 -0
  111. package/src/i18n/index.ts +34 -0
  112. package/src/i18n/providers/I18nProvider.ts +277 -0
  113. package/src/websocket/hooks/useRoom.tsx +223 -0
  114. package/src/websocket/index.ts +7 -0
  115. package/dist/index.browser.js.map +0 -1
  116. package/dist/index.cjs.map +0 -1
  117. package/dist/index.d.cts.map +0 -1
  118. package/dist/index.d.ts.map +0 -1
  119. package/dist/index.js.map +0 -1
  120. /package/src/{components → core/components}/ClientOnly.tsx +0 -0
  121. /package/src/{components → core/components}/ErrorBoundary.tsx +0 -0
  122. /package/src/{components → core/components}/Link.tsx +0 -0
  123. /package/src/{components → core/components}/NotFound.tsx +0 -0
  124. /package/src/{contexts → core/contexts}/RouterLayerContext.ts +0 -0
  125. /package/src/{errors → core/errors}/Redirection.ts +0 -0
  126. /package/src/{hooks → core/hooks}/useActive.ts +0 -0
  127. /package/src/{hooks → core/hooks}/useRouter.ts +0 -0
  128. /package/src/{index.shared.ts → core/index.shared.ts} +0 -0
@@ -0,0 +1,1857 @@
1
+ import { $atom, $env, $hook, $inject, $module, $use, Alepha, AlephaError, Atom, Descriptor, KIND, TypeBoxError, TypeProvider, createDescriptor, t } from "alepha";
2
+ import { AlephaDateTime, DateTimeProvider } from "alepha/datetime";
3
+ import { $logger } from "alepha/logger";
4
+ import { $cookie } from "alepha/server/cookies";
5
+ import { AlephaServer, ServerProvider, ServerRouterProvider, ServerTimingProvider } from "alepha/server";
6
+ import { AlephaServerCache } from "alepha/server/cache";
7
+ import { AlephaServerLinks, LinkProvider, ServerLinksProvider } from "alepha/server/links";
8
+ import React, { StrictMode, createContext, createElement, memo, use, useContext, useEffect, useMemo, useRef, useState } from "react";
9
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
10
+ import { existsSync } from "node:fs";
11
+ import { join } from "node:path";
12
+ import { ServerStaticProvider } from "alepha/server/static";
13
+ import { renderToString } from "react-dom/server";
14
+ import { RouterProvider } from "alepha/router";
15
+
16
+ //#region src/i18n/providers/I18nProvider.ts
17
+ var I18nProvider = class {
18
+ logger = $logger();
19
+ alepha = $inject(Alepha);
20
+ dateTimeProvider = $inject(DateTimeProvider);
21
+ cookie = $cookie({
22
+ name: "lang",
23
+ schema: t.text()
24
+ });
25
+ registry = [];
26
+ options = { fallbackLang: "en" };
27
+ dateFormat = new Intl.DateTimeFormat(this.lang);
28
+ numberFormat = new Intl.NumberFormat(this.lang);
29
+ get languages() {
30
+ const languages = /* @__PURE__ */ new Set();
31
+ for (const item of this.registry) languages.add(item.lang);
32
+ languages.add(this.options.fallbackLang);
33
+ return Array.from(languages);
34
+ }
35
+ constructor() {
36
+ this.refreshLocale();
37
+ }
38
+ onRender = $hook({
39
+ on: "server:onRequest",
40
+ priority: "last",
41
+ handler: async ({ request }) => {
42
+ this.alepha.state.set("alepha.react.i18n.lang", this.cookie.get(request));
43
+ }
44
+ });
45
+ onStart = $hook({
46
+ on: "start",
47
+ handler: async () => {
48
+ if (this.alepha.isBrowser()) {
49
+ const cookieLang = this.cookie.get();
50
+ if (cookieLang) this.alepha.state.set("alepha.react.i18n.lang", cookieLang);
51
+ for (const item of this.registry) if (item.lang === this.lang || item.lang === this.options.fallbackLang) item.translations = await item.loader();
52
+ return;
53
+ }
54
+ for (const item of this.registry) item.translations = await item.loader();
55
+ }
56
+ });
57
+ refreshLocale() {
58
+ this.numberFormat = new Intl.NumberFormat(this.lang);
59
+ this.dateFormat = new Intl.DateTimeFormat(this.lang);
60
+ this.dateTimeProvider.setLocale(this.lang);
61
+ TypeProvider.setLocale(this.lang);
62
+ }
63
+ setLang = async (lang) => {
64
+ if (this.alepha.isBrowser()) {
65
+ for (const item of this.registry) if (lang === item.lang) {
66
+ if (Object.keys(item.translations).length > 0) continue;
67
+ item.translations = await item.loader();
68
+ }
69
+ this.cookie.set(lang);
70
+ }
71
+ this.alepha.state.set("alepha.react.i18n.lang", lang);
72
+ this.refreshLocale();
73
+ };
74
+ mutate = $hook({
75
+ on: "state:mutate",
76
+ handler: async ({ key, value }) => {
77
+ if (key === "alepha.react.i18n.lang" && this.alepha.isBrowser()) {
78
+ let hasChanged = false;
79
+ for (const item of this.registry) if (value === item.lang) {
80
+ if (Object.keys(item.translations).length > 0) continue;
81
+ item.translations = await item.loader();
82
+ hasChanged = true;
83
+ }
84
+ this.refreshLocale();
85
+ if (hasChanged) this.alepha.state.set("alepha.react.i18n.lang", value);
86
+ }
87
+ }
88
+ });
89
+ get lang() {
90
+ return this.alepha.state.get("alepha.react.i18n.lang") || this.options.fallbackLang;
91
+ }
92
+ translate = (key, args = []) => {
93
+ for (const item of this.registry) if (item.lang === this.lang) if (item.translations[key]) return this.render(item.translations[key], args);
94
+ else break;
95
+ for (const item of this.registry) if (item.lang === this.options.fallbackLang) if (item.translations[key]) return this.render(item.translations[key], args);
96
+ else break;
97
+ return key;
98
+ };
99
+ l = (value, options = {}) => {
100
+ if (typeof value === "number") {
101
+ if (options.number) return new Intl.NumberFormat(this.lang, options.number).format(value);
102
+ return this.numberFormat.format(value);
103
+ }
104
+ if (value instanceof Date || this.dateTimeProvider.isDateTime(value) || typeof value === "string" && options.date) {
105
+ let dt = this.dateTimeProvider.of(value);
106
+ if (options.timezone) dt = dt.tz(options.timezone);
107
+ if (typeof options.date === "string") {
108
+ if (options.date === "fromNow") return dt.locale(this.lang).fromNow();
109
+ return dt.locale(this.lang).format(options.date);
110
+ }
111
+ if (options.date) return new Intl.DateTimeFormat(this.lang, options.timezone ? {
112
+ ...options.date,
113
+ timeZone: options.timezone
114
+ } : options.date).format(dt.toDate());
115
+ if (options.timezone) return new Intl.DateTimeFormat(this.lang, { timeZone: options.timezone }).format(dt.toDate());
116
+ return this.dateFormat.format(dt.toDate());
117
+ }
118
+ if (value instanceof TypeBoxError) return TypeProvider.translateError(value, this.lang);
119
+ return value;
120
+ };
121
+ tr = (key, options = {}) => {
122
+ const translation = this.translate(key, options.args || []);
123
+ if (translation === key && options.default) return options.default;
124
+ return translation;
125
+ };
126
+ render(item, args) {
127
+ let result = item;
128
+ for (let i = 0; i < args.length; i++) result = result.replace(`$${i + 1}`, args[i]);
129
+ return result;
130
+ }
131
+ };
132
+
133
+ //#endregion
134
+ //#region src/i18n/descriptors/$dictionary.ts
135
+ /**
136
+ * Register a dictionary entry for translations.
137
+ *
138
+ * It allows you to define a set of translations for a specific language.
139
+ * Entry can be lazy-loaded, which is useful for large dictionaries or when translations are not needed immediately.
140
+ *
141
+ * @example
142
+ * ```ts
143
+ * import { $dictionary } from "@alepha/react/i18n";
144
+ *
145
+ * const Example = () => {
146
+ * const { tr } = useI18n<App, "en">();
147
+ * return <div>{tr("hello")}</div>; //
148
+ * }
149
+ *
150
+ * class App {
151
+ *
152
+ * en = $dictionary({
153
+ * // { default: { hello: "Hey" } }
154
+ * lazy: () => import("./translations/en.ts"),
155
+ * });
156
+ *
157
+ * home = $page({
158
+ * path: "/",
159
+ * component: Example,
160
+ * })
161
+ * }
162
+ *
163
+ * run(App);
164
+ * ```
165
+ */
166
+ const $dictionary = (options) => {
167
+ return createDescriptor(DictionaryDescriptor, options);
168
+ };
169
+ var DictionaryDescriptor = class extends Descriptor {
170
+ provider = $inject(I18nProvider);
171
+ onInit() {
172
+ this.provider.registry.push({
173
+ name: this.options.name ?? this.config.propertyKey,
174
+ lang: this.options.lang ?? this.config.propertyKey,
175
+ loader: () => this.options.lazy().then((it) => it.default),
176
+ translations: {}
177
+ });
178
+ }
179
+ };
180
+ $dictionary[KIND] = DictionaryDescriptor;
181
+
182
+ //#endregion
183
+ //#region src/core/services/ReactPageService.ts
184
+ var ReactPageService = class {
185
+ fetch(pathname, options = {}) {
186
+ throw new AlephaError("Fetch is not available for this environment.");
187
+ }
188
+ render(name, options = {}) {
189
+ throw new AlephaError("Render is not available for this environment.");
190
+ }
191
+ };
192
+
193
+ //#endregion
194
+ //#region src/core/descriptors/$page.ts
195
+ /**
196
+ * Main descriptor for defining a React route in the application.
197
+ *
198
+ * The $page descriptor is the core building block for creating type-safe, SSR-enabled React routes.
199
+ * It provides a declarative way to define pages with powerful features:
200
+ *
201
+ * **Routing & Navigation**
202
+ * - URL pattern matching with parameters (e.g., `/users/:id`)
203
+ * - Nested routing with parent-child relationships
204
+ * - Type-safe URL parameter and query string validation
205
+ *
206
+ * **Data Loading**
207
+ * - Server-side data fetching with the `resolve` function
208
+ * - Automatic serialization and hydration for SSR
209
+ * - Access to request context, URL params, and parent data
210
+ *
211
+ * **Component Loading**
212
+ * - Direct component rendering or lazy loading for code splitting
213
+ * - Client-only rendering when browser APIs are needed
214
+ * - Automatic fallback handling during hydration
215
+ *
216
+ * **Performance Optimization**
217
+ * - Static generation for pre-rendered pages at build time
218
+ * - Server-side caching with configurable TTL and providers
219
+ * - Code splitting through lazy component loading
220
+ *
221
+ * **Error Handling**
222
+ * - Custom error handlers with support for redirects
223
+ * - Hierarchical error handling (child → parent)
224
+ * - HTTP status code handling (404, 401, etc.)
225
+ *
226
+ * **Page Animations**
227
+ * - CSS-based enter/exit animations
228
+ * - Dynamic animations based on page state
229
+ * - Custom timing and easing functions
230
+ *
231
+ * **Lifecycle Management**
232
+ * - Server response hooks for headers and status codes
233
+ * - Page leave handlers for cleanup (browser only)
234
+ * - Permission-based access control
235
+ *
236
+ * @example Simple page with data fetching
237
+ * ```typescript
238
+ * const userProfile = $page({
239
+ * path: "/users/:id",
240
+ * schema: {
241
+ * params: t.object({ id: t.int() }),
242
+ * query: t.object({ tab: t.optional(t.text()) })
243
+ * },
244
+ * resolve: async ({ params }) => {
245
+ * const user = await userApi.getUser(params.id);
246
+ * return { user };
247
+ * },
248
+ * lazy: () => import("./UserProfile.tsx")
249
+ * });
250
+ * ```
251
+ *
252
+ * @example Nested routing with error handling
253
+ * ```typescript
254
+ * const projectSection = $page({
255
+ * path: "/projects/:id",
256
+ * children: () => [projectBoard, projectSettings],
257
+ * resolve: async ({ params }) => {
258
+ * const project = await projectApi.get(params.id);
259
+ * return { project };
260
+ * },
261
+ * errorHandler: (error) => {
262
+ * if (HttpError.is(error, 404)) {
263
+ * return <ProjectNotFound />;
264
+ * }
265
+ * }
266
+ * });
267
+ * ```
268
+ *
269
+ * @example Static generation with caching
270
+ * ```typescript
271
+ * const blogPost = $page({
272
+ * path: "/blog/:slug",
273
+ * static: {
274
+ * entries: posts.map(p => ({ params: { slug: p.slug } }))
275
+ * },
276
+ * resolve: async ({ params }) => {
277
+ * const post = await loadPost(params.slug);
278
+ * return { post };
279
+ * }
280
+ * });
281
+ * ```
282
+ */
283
+ const $page = (options) => {
284
+ return createDescriptor(PageDescriptor, options);
285
+ };
286
+ var PageDescriptor = class extends Descriptor {
287
+ reactPageService = $inject(ReactPageService);
288
+ onInit() {
289
+ if (this.options.static) this.options.cache ??= { store: {
290
+ provider: "memory",
291
+ ttl: [1, "week"]
292
+ } };
293
+ }
294
+ get name() {
295
+ return this.options.name ?? this.config.propertyKey;
296
+ }
297
+ /**
298
+ * For testing or build purposes.
299
+ *
300
+ * This will render the page (HTML layout included or not) and return the HTML + context.
301
+ * Only valid for server-side rendering, it will throw an error if called on the client-side.
302
+ */
303
+ async render(options) {
304
+ return this.reactPageService.render(this.name, options);
305
+ }
306
+ async fetch(options) {
307
+ return this.reactPageService.fetch(this.options.path || "", options);
308
+ }
309
+ match(url) {
310
+ return false;
311
+ }
312
+ pathname(config) {
313
+ return this.options.path || "";
314
+ }
315
+ };
316
+ $page[KIND] = PageDescriptor;
317
+
318
+ //#endregion
319
+ //#region src/core/components/ClientOnly.tsx
320
+ /**
321
+ * A small utility component that renders its children only on the client side.
322
+ *
323
+ * Optionally, you can provide a fallback React node that will be rendered.
324
+ *
325
+ * You should use this component when
326
+ * - you have code that relies on browser-specific APIs
327
+ * - you want to avoid server-side rendering for a specific part of your application
328
+ * - you want to prevent pre-rendering of a component
329
+ */
330
+ const ClientOnly = (props) => {
331
+ const [mounted, setMounted] = useState(false);
332
+ useEffect(() => setMounted(true), []);
333
+ if (props.disabled) return props.children;
334
+ return mounted ? props.children : props.fallback;
335
+ };
336
+ var ClientOnly_default = ClientOnly;
337
+
338
+ //#endregion
339
+ //#region src/core/components/ErrorViewer.tsx
340
+ const ErrorViewer = ({ error, alepha }) => {
341
+ const [expanded, setExpanded] = useState(false);
342
+ if (alepha.isProduction()) return /* @__PURE__ */ jsx(ErrorViewerProduction, {});
343
+ const stackLines = error.stack?.split("\n") ?? [];
344
+ const previewLines = stackLines.slice(0, 5);
345
+ const hiddenLineCount = stackLines.length - previewLines.length;
346
+ const copyToClipboard = (text) => {
347
+ navigator.clipboard.writeText(text).catch((err) => {
348
+ console.error("Clipboard error:", err);
349
+ });
350
+ };
351
+ const styles = {
352
+ container: {
353
+ padding: "24px",
354
+ backgroundColor: "#FEF2F2",
355
+ color: "#7F1D1D",
356
+ border: "1px solid #FECACA",
357
+ borderRadius: "16px",
358
+ boxShadow: "0 8px 24px rgba(0,0,0,0.05)",
359
+ fontFamily: "monospace",
360
+ maxWidth: "768px",
361
+ margin: "40px auto"
362
+ },
363
+ heading: {
364
+ fontSize: "20px",
365
+ fontWeight: "bold",
366
+ marginBottom: "10px"
367
+ },
368
+ name: {
369
+ fontSize: "16px",
370
+ fontWeight: 600
371
+ },
372
+ message: {
373
+ fontSize: "14px",
374
+ marginBottom: "16px"
375
+ },
376
+ sectionHeader: {
377
+ display: "flex",
378
+ justifyContent: "space-between",
379
+ alignItems: "center",
380
+ fontSize: "12px",
381
+ marginBottom: "4px",
382
+ color: "#991B1B"
383
+ },
384
+ copyButton: {
385
+ fontSize: "12px",
386
+ color: "#DC2626",
387
+ background: "none",
388
+ border: "none",
389
+ cursor: "pointer",
390
+ textDecoration: "underline"
391
+ },
392
+ stackContainer: {
393
+ backgroundColor: "#FEE2E2",
394
+ padding: "12px",
395
+ borderRadius: "8px",
396
+ fontSize: "13px",
397
+ lineHeight: "1.4",
398
+ overflowX: "auto",
399
+ whiteSpace: "pre-wrap"
400
+ },
401
+ expandLine: {
402
+ color: "#F87171",
403
+ cursor: "pointer",
404
+ marginTop: "8px"
405
+ }
406
+ };
407
+ return /* @__PURE__ */ jsxs("div", {
408
+ style: styles.container,
409
+ children: [/* @__PURE__ */ jsxs("div", { children: [
410
+ /* @__PURE__ */ jsx("div", {
411
+ style: styles.heading,
412
+ children: "🔥 Error"
413
+ }),
414
+ /* @__PURE__ */ jsx("div", {
415
+ style: styles.name,
416
+ children: error.name
417
+ }),
418
+ /* @__PURE__ */ jsx("div", {
419
+ style: styles.message,
420
+ children: error.message
421
+ })
422
+ ] }), stackLines.length > 0 && /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsxs("div", {
423
+ style: styles.sectionHeader,
424
+ children: [/* @__PURE__ */ jsx("span", { children: "Stack trace" }), /* @__PURE__ */ jsx("button", {
425
+ type: "button",
426
+ onClick: () => copyToClipboard(error.stack),
427
+ style: styles.copyButton,
428
+ children: "Copy all"
429
+ })]
430
+ }), /* @__PURE__ */ jsxs("pre", {
431
+ style: styles.stackContainer,
432
+ children: [(expanded ? stackLines : previewLines).map((line, i) => /* @__PURE__ */ jsx("div", { children: line }, i)), !expanded && hiddenLineCount > 0 && /* @__PURE__ */ jsxs("div", {
433
+ style: styles.expandLine,
434
+ onClick: () => setExpanded(true),
435
+ children: [
436
+ "+ ",
437
+ hiddenLineCount,
438
+ " more lines..."
439
+ ]
440
+ })]
441
+ })] })]
442
+ });
443
+ };
444
+ var ErrorViewer_default = ErrorViewer;
445
+ const ErrorViewerProduction = () => {
446
+ const styles = {
447
+ container: {
448
+ padding: "24px",
449
+ backgroundColor: "#FEF2F2",
450
+ color: "#7F1D1D",
451
+ border: "1px solid #FECACA",
452
+ borderRadius: "16px",
453
+ boxShadow: "0 8px 24px rgba(0,0,0,0.05)",
454
+ fontFamily: "monospace",
455
+ maxWidth: "768px",
456
+ margin: "40px auto",
457
+ textAlign: "center"
458
+ },
459
+ heading: {
460
+ fontSize: "20px",
461
+ fontWeight: "bold",
462
+ marginBottom: "8px"
463
+ },
464
+ name: {
465
+ fontSize: "16px",
466
+ fontWeight: 600,
467
+ marginBottom: "4px"
468
+ },
469
+ message: {
470
+ fontSize: "14px",
471
+ opacity: .85
472
+ }
473
+ };
474
+ return /* @__PURE__ */ jsxs("div", {
475
+ style: styles.container,
476
+ children: [/* @__PURE__ */ jsx("div", {
477
+ style: styles.heading,
478
+ children: "🚨 An error occurred"
479
+ }), /* @__PURE__ */ jsx("div", {
480
+ style: styles.message,
481
+ children: "Something went wrong. Please try again later."
482
+ })]
483
+ });
484
+ };
485
+
486
+ //#endregion
487
+ //#region src/core/contexts/RouterLayerContext.ts
488
+ const RouterLayerContext = createContext(void 0);
489
+
490
+ //#endregion
491
+ //#region src/core/errors/Redirection.ts
492
+ /**
493
+ * Used for Redirection during the page loading.
494
+ *
495
+ * Depends on the context, it can be thrown or just returned.
496
+ */
497
+ var Redirection = class extends Error {
498
+ redirect;
499
+ constructor(redirect) {
500
+ super("Redirection");
501
+ this.redirect = redirect;
502
+ }
503
+ };
504
+
505
+ //#endregion
506
+ //#region src/core/contexts/AlephaContext.ts
507
+ const AlephaContext = createContext(void 0);
508
+
509
+ //#endregion
510
+ //#region src/core/hooks/useAlepha.ts
511
+ /**
512
+ * Main Alepha hook.
513
+ *
514
+ * It provides access to the Alepha instance within a React component.
515
+ *
516
+ * With Alepha, you can access the core functionalities of the framework:
517
+ *
518
+ * - alepha.state() for state management
519
+ * - alepha.inject() for dependency injection
520
+ * - alepha.events.emit() for event handling
521
+ * etc...
522
+ */
523
+ const useAlepha = () => {
524
+ const alepha = useContext(AlephaContext);
525
+ if (!alepha) throw new AlephaError("Hook 'useAlepha()' must be used within an AlephaContext.Provider");
526
+ return alepha;
527
+ };
528
+
529
+ //#endregion
530
+ //#region src/core/hooks/useEvents.ts
531
+ /**
532
+ * Allow subscribing to multiple Alepha events. See {@link Hooks} for available events.
533
+ *
534
+ * useEvents is fully typed to ensure correct event callback signatures.
535
+ *
536
+ * @example
537
+ * ```tsx
538
+ * useEvents(
539
+ * {
540
+ * "react:transition:begin": (ev) => {
541
+ * console.log("Transition began to:", ev.to);
542
+ * },
543
+ * "react:transition:error": {
544
+ * priority: "first",
545
+ * callback: (ev) => {
546
+ * console.error("Transition error:", ev.error);
547
+ * },
548
+ * },
549
+ * },
550
+ * [],
551
+ * );
552
+ * ```
553
+ */
554
+ const useEvents = (opts, deps) => {
555
+ const alepha = useAlepha();
556
+ useEffect(() => {
557
+ if (!alepha.isBrowser()) return;
558
+ const subs = [];
559
+ for (const [name, hook] of Object.entries(opts)) subs.push(alepha.events.on(name, hook));
560
+ return () => {
561
+ for (const clear of subs) clear();
562
+ };
563
+ }, deps);
564
+ };
565
+
566
+ //#endregion
567
+ //#region src/core/hooks/useStore.ts
568
+ function useStore(target, defaultValue) {
569
+ const alepha = useAlepha();
570
+ useMemo(() => {
571
+ if (defaultValue != null && alepha.state.get(target) == null) alepha.state.set(target, defaultValue);
572
+ }, [defaultValue]);
573
+ const [state, setState] = useState(alepha.state.get(target));
574
+ useEffect(() => {
575
+ if (!alepha.isBrowser()) return;
576
+ const key = target instanceof Atom ? target.key : target;
577
+ return alepha.events.on("state:mutate", (ev) => {
578
+ if (ev.key === key) setState(ev.value);
579
+ });
580
+ }, []);
581
+ return [state, (value) => {
582
+ alepha.state.set(target, value);
583
+ }];
584
+ }
585
+
586
+ //#endregion
587
+ //#region src/core/hooks/useRouterState.ts
588
+ const useRouterState = () => {
589
+ const [state] = useStore("alepha.react.router.state");
590
+ if (!state) throw new AlephaError("Missing react router state");
591
+ return state;
592
+ };
593
+
594
+ //#endregion
595
+ //#region src/core/components/ErrorBoundary.tsx
596
+ /**
597
+ * A reusable error boundary for catching rendering errors
598
+ * in any part of the React component tree.
599
+ */
600
+ var ErrorBoundary = class extends React.Component {
601
+ constructor(props) {
602
+ super(props);
603
+ this.state = {};
604
+ }
605
+ /**
606
+ * Update state so the next render shows the fallback UI.
607
+ */
608
+ static getDerivedStateFromError(error) {
609
+ return { error };
610
+ }
611
+ /**
612
+ * Lifecycle method called when an error is caught.
613
+ * You can log the error or perform side effects here.
614
+ */
615
+ componentDidCatch(error, info) {
616
+ if (this.props.onError) this.props.onError(error, info);
617
+ }
618
+ render() {
619
+ if (this.state.error) return this.props.fallback(this.state.error);
620
+ return this.props.children;
621
+ }
622
+ };
623
+ var ErrorBoundary_default = ErrorBoundary;
624
+
625
+ //#endregion
626
+ //#region src/core/components/NestedView.tsx
627
+ /**
628
+ * A component that renders the current view of the nested router layer.
629
+ *
630
+ * To be simple, it renders the `element` of the current child page of a parent page.
631
+ *
632
+ * @example
633
+ * ```tsx
634
+ * import { NestedView } from "@alepha/react";
635
+ *
636
+ * class App {
637
+ * parent = $page({
638
+ * component: () => <NestedView />,
639
+ * });
640
+ *
641
+ * child = $page({
642
+ * parent: this.root,
643
+ * component: () => <div>Child Page</div>,
644
+ * });
645
+ * }
646
+ * ```
647
+ */
648
+ const NestedView = (props) => {
649
+ const index = use(RouterLayerContext)?.index ?? 0;
650
+ const state = useRouterState();
651
+ const [view, setView] = useState(state.layers[index]?.element);
652
+ const [animation, setAnimation] = useState("");
653
+ const animationExitDuration = useRef(0);
654
+ const animationExitNow = useRef(0);
655
+ useEvents({
656
+ "react:transition:begin": async ({ previous, state: state$1 }) => {
657
+ const layer = previous.layers[index];
658
+ if (`${state$1.url.pathname}/`.startsWith(`${layer?.path}/`)) return;
659
+ const animationExit = parseAnimation(layer.route?.animation, state$1, "exit");
660
+ if (animationExit) {
661
+ const duration = animationExit.duration || 200;
662
+ animationExitNow.current = Date.now();
663
+ animationExitDuration.current = duration;
664
+ setAnimation(animationExit.animation);
665
+ } else {
666
+ animationExitNow.current = 0;
667
+ animationExitDuration.current = 0;
668
+ setAnimation("");
669
+ }
670
+ },
671
+ "react:transition:end": async ({ state: state$1 }) => {
672
+ const layer = state$1.layers[index];
673
+ if (animationExitNow.current) {
674
+ const duration = animationExitDuration.current;
675
+ const diff = Date.now() - animationExitNow.current;
676
+ if (diff < duration) await new Promise((resolve) => setTimeout(resolve, duration - diff));
677
+ }
678
+ if (!layer?.cache) {
679
+ setView(layer?.element);
680
+ const animationEnter = parseAnimation(layer?.route?.animation, state$1, "enter");
681
+ if (animationEnter) setAnimation(animationEnter.animation);
682
+ else setAnimation("");
683
+ }
684
+ }
685
+ }, []);
686
+ let element = view ?? props.children ?? null;
687
+ if (animation) element = /* @__PURE__ */ jsx("div", {
688
+ style: {
689
+ display: "flex",
690
+ flex: 1,
691
+ height: "100%",
692
+ width: "100%",
693
+ position: "relative",
694
+ overflow: "hidden"
695
+ },
696
+ children: /* @__PURE__ */ jsx("div", {
697
+ style: {
698
+ height: "100%",
699
+ width: "100%",
700
+ display: "flex",
701
+ animation
702
+ },
703
+ children: element
704
+ })
705
+ });
706
+ if (props.errorBoundary === false) return /* @__PURE__ */ jsx(Fragment, { children: element });
707
+ if (props.errorBoundary) return /* @__PURE__ */ jsx(ErrorBoundary_default, {
708
+ fallback: props.errorBoundary,
709
+ children: element
710
+ });
711
+ return /* @__PURE__ */ jsx(ErrorBoundary_default, {
712
+ fallback: (error) => {
713
+ const result = state.onError(error, state);
714
+ if (result instanceof Redirection) return "Redirection inside ErrorBoundary is not allowed.";
715
+ return result;
716
+ },
717
+ children: element
718
+ });
719
+ };
720
+ var NestedView_default = memo(NestedView);
721
+ function parseAnimation(animationLike, state, type = "enter") {
722
+ if (!animationLike) return;
723
+ const DEFAULT_DURATION = 300;
724
+ const animation = typeof animationLike === "function" ? animationLike(state) : animationLike;
725
+ if (typeof animation === "string") {
726
+ if (type === "exit") return;
727
+ return {
728
+ duration: DEFAULT_DURATION,
729
+ animation: `${DEFAULT_DURATION}ms ${animation}`
730
+ };
731
+ }
732
+ if (typeof animation === "object") {
733
+ const anim = animation[type];
734
+ const duration = typeof anim === "object" ? anim.duration ?? DEFAULT_DURATION : DEFAULT_DURATION;
735
+ const name = typeof anim === "object" ? anim.name : anim;
736
+ if (type === "exit") return {
737
+ duration,
738
+ animation: `${duration}ms ${typeof anim === "object" ? anim.timing ?? "" : ""} ${name}`
739
+ };
740
+ return {
741
+ duration,
742
+ animation: `${duration}ms ${typeof anim === "object" ? anim.timing ?? "" : ""} ${name}`
743
+ };
744
+ }
745
+ }
746
+
747
+ //#endregion
748
+ //#region src/core/components/NotFound.tsx
749
+ function NotFoundPage(props) {
750
+ return /* @__PURE__ */ jsx("div", {
751
+ style: {
752
+ height: "100vh",
753
+ display: "flex",
754
+ flexDirection: "column",
755
+ justifyContent: "center",
756
+ alignItems: "center",
757
+ textAlign: "center",
758
+ fontFamily: "sans-serif",
759
+ padding: "1rem",
760
+ ...props.style
761
+ },
762
+ children: /* @__PURE__ */ jsx("h1", {
763
+ style: {
764
+ fontSize: "1rem",
765
+ marginBottom: "0.5rem"
766
+ },
767
+ children: "404 - This page does not exist"
768
+ })
769
+ });
770
+ }
771
+
772
+ //#endregion
773
+ //#region src/core/providers/ReactPageProvider.ts
774
+ const envSchema$2 = t.object({ REACT_STRICT_MODE: t.boolean({ default: true }) });
775
+ var ReactPageProvider = class {
776
+ log = $logger();
777
+ env = $env(envSchema$2);
778
+ alepha = $inject(Alepha);
779
+ pages = [];
780
+ getPages() {
781
+ return this.pages;
782
+ }
783
+ getConcretePages() {
784
+ const pages = [];
785
+ for (const page of this.pages) {
786
+ if (page.children && page.children.length > 0) continue;
787
+ const fullPath = this.pathname(page.name);
788
+ if (fullPath.includes(":") || fullPath.includes("*")) {
789
+ if (typeof page.static === "object") {
790
+ const entries = page.static.entries;
791
+ if (entries && entries.length > 0) for (const entry of entries) {
792
+ const params = entry.params;
793
+ const path = this.compile(page.path ?? "", params);
794
+ if (!path.includes(":") && !path.includes("*")) pages.push({
795
+ ...page,
796
+ name: params[Object.keys(params)[0]],
797
+ path,
798
+ ...entry
799
+ });
800
+ }
801
+ }
802
+ continue;
803
+ }
804
+ pages.push(page);
805
+ }
806
+ return pages;
807
+ }
808
+ page(name) {
809
+ for (const page of this.pages) if (page.name === name) return page;
810
+ throw new AlephaError(`Page '${name}' not found`);
811
+ }
812
+ pathname(name, options = {}) {
813
+ const page = this.page(name);
814
+ if (!page) throw new Error(`Page ${name} not found`);
815
+ let url = page.path ?? "";
816
+ let parent = page.parent;
817
+ while (parent) {
818
+ url = `${parent.path ?? ""}/${url}`;
819
+ parent = parent.parent;
820
+ }
821
+ url = this.compile(url, options.params ?? {});
822
+ if (options.query) {
823
+ const query = new URLSearchParams(options.query);
824
+ if (query.toString()) url += `?${query.toString()}`;
825
+ }
826
+ return url.replace(/\/\/+/g, "/") || "/";
827
+ }
828
+ url(name, options = {}) {
829
+ return new URL(this.pathname(name, options), options.host ?? `http://localhost`);
830
+ }
831
+ root(state) {
832
+ const root = createElement(AlephaContext.Provider, { value: this.alepha }, createElement(NestedView_default, {}, state.layers[0]?.element));
833
+ if (this.env.REACT_STRICT_MODE) return createElement(StrictMode, {}, root);
834
+ return root;
835
+ }
836
+ convertStringObjectToObject = (schema, value) => {
837
+ if (t.schema.isObject(schema) && typeof value === "object") {
838
+ for (const key in schema.properties) if (t.schema.isObject(schema.properties[key]) && typeof value[key] === "string") try {
839
+ value[key] = this.alepha.codec.decode(schema.properties[key], decodeURIComponent(value[key]));
840
+ } catch (e) {}
841
+ }
842
+ return value;
843
+ };
844
+ /**
845
+ * Create a new RouterState based on a given route and request.
846
+ * This method resolves the layers for the route, applying any query and params schemas defined in the route.
847
+ * It also handles errors and redirects.
848
+ */
849
+ async createLayers(route, state, previous = []) {
850
+ let context = {};
851
+ const stack = [{ route }];
852
+ let parent = route.parent;
853
+ while (parent) {
854
+ stack.unshift({ route: parent });
855
+ parent = parent.parent;
856
+ }
857
+ let forceRefresh = false;
858
+ for (let i = 0; i < stack.length; i++) {
859
+ const it = stack[i];
860
+ const route$1 = it.route;
861
+ const config = {};
862
+ try {
863
+ this.convertStringObjectToObject(route$1.schema?.query, state.query);
864
+ config.query = route$1.schema?.query ? this.alepha.codec.decode(route$1.schema.query, state.query) : {};
865
+ } catch (e) {
866
+ it.error = e;
867
+ break;
868
+ }
869
+ try {
870
+ config.params = route$1.schema?.params ? this.alepha.codec.decode(route$1.schema.params, state.params) : {};
871
+ } catch (e) {
872
+ it.error = e;
873
+ break;
874
+ }
875
+ it.config = { ...config };
876
+ if (previous?.[i] && !forceRefresh && previous[i].name === route$1.name) {
877
+ const url = (str) => str ? str.replace(/\/\/+/g, "/") : "/";
878
+ if (JSON.stringify({
879
+ part: url(previous[i].part),
880
+ params: previous[i].config?.params ?? {}
881
+ }) === JSON.stringify({
882
+ part: url(route$1.path),
883
+ params: config.params ?? {}
884
+ })) {
885
+ it.props = previous[i].props;
886
+ it.error = previous[i].error;
887
+ it.cache = true;
888
+ context = {
889
+ ...context,
890
+ ...it.props
891
+ };
892
+ continue;
893
+ }
894
+ forceRefresh = true;
895
+ }
896
+ if (!route$1.resolve) continue;
897
+ try {
898
+ const args = Object.create(state);
899
+ Object.assign(args, config, context);
900
+ const props = await route$1.resolve?.(args) ?? {};
901
+ it.props = { ...props };
902
+ context = {
903
+ ...context,
904
+ ...props
905
+ };
906
+ } catch (e) {
907
+ if (e instanceof Redirection) return { redirect: e.redirect };
908
+ this.log.error("Page resolver has failed", e);
909
+ it.error = e;
910
+ break;
911
+ }
912
+ }
913
+ let acc = "";
914
+ for (let i = 0; i < stack.length; i++) {
915
+ const it = stack[i];
916
+ const props = it.props ?? {};
917
+ const params = { ...it.config?.params };
918
+ for (const key of Object.keys(params)) params[key] = String(params[key]);
919
+ acc += "/";
920
+ acc += it.route.path ? this.compile(it.route.path, params) : "";
921
+ const path = acc.replace(/\/+/, "/");
922
+ const localErrorHandler = this.getErrorHandler(it.route);
923
+ if (localErrorHandler) {
924
+ const onErrorParent = state.onError;
925
+ state.onError = (error, context$1) => {
926
+ const result = localErrorHandler(error, context$1);
927
+ if (result === void 0) return onErrorParent(error, context$1);
928
+ return result;
929
+ };
930
+ }
931
+ if (!it.error) try {
932
+ const element = await this.createElement(it.route, {
933
+ ...props,
934
+ ...context
935
+ });
936
+ state.layers.push({
937
+ name: it.route.name,
938
+ props,
939
+ part: it.route.path,
940
+ config: it.config,
941
+ element: this.renderView(i + 1, path, element, it.route),
942
+ index: i + 1,
943
+ path,
944
+ route: it.route,
945
+ cache: it.cache
946
+ });
947
+ } catch (e) {
948
+ it.error = e;
949
+ }
950
+ if (it.error) try {
951
+ let element = await state.onError(it.error, state);
952
+ if (element === void 0) throw it.error;
953
+ if (element instanceof Redirection) return { redirect: element.redirect };
954
+ if (element === null) element = this.renderError(it.error);
955
+ state.layers.push({
956
+ props,
957
+ error: it.error,
958
+ name: it.route.name,
959
+ part: it.route.path,
960
+ config: it.config,
961
+ element: this.renderView(i + 1, path, element, it.route),
962
+ index: i + 1,
963
+ path,
964
+ route: it.route
965
+ });
966
+ break;
967
+ } catch (e) {
968
+ if (e instanceof Redirection) return { redirect: e.redirect };
969
+ throw e;
970
+ }
971
+ }
972
+ return { state };
973
+ }
974
+ createRedirectionLayer(redirect) {
975
+ return { redirect };
976
+ }
977
+ getErrorHandler(route) {
978
+ if (route.errorHandler) return route.errorHandler;
979
+ let parent = route.parent;
980
+ while (parent) {
981
+ if (parent.errorHandler) return parent.errorHandler;
982
+ parent = parent.parent;
983
+ }
984
+ }
985
+ async createElement(page, props) {
986
+ if (page.lazy && page.component) this.log.warn(`Page ${page.name} has both lazy and component options, lazy will be used`);
987
+ if (page.lazy) return createElement((await page.lazy()).default, props);
988
+ if (page.component) return createElement(page.component, props);
989
+ }
990
+ renderError(error) {
991
+ return createElement(ErrorViewer_default, {
992
+ error,
993
+ alepha: this.alepha
994
+ });
995
+ }
996
+ renderEmptyView() {
997
+ return createElement(NestedView_default, {});
998
+ }
999
+ href(page, params = {}) {
1000
+ const found = this.pages.find((it) => it.name === page.options.name);
1001
+ if (!found) throw new Error(`Page ${page.options.name} not found`);
1002
+ let url = found.path ?? "";
1003
+ let parent = found.parent;
1004
+ while (parent) {
1005
+ url = `${parent.path ?? ""}/${url}`;
1006
+ parent = parent.parent;
1007
+ }
1008
+ url = this.compile(url, params);
1009
+ return url.replace(/\/\/+/g, "/") || "/";
1010
+ }
1011
+ compile(path, params = {}) {
1012
+ for (const [key, value] of Object.entries(params)) path = path.replace(`:${key}`, value);
1013
+ return path;
1014
+ }
1015
+ renderView(index, path, view, page) {
1016
+ view ??= this.renderEmptyView();
1017
+ const element = page.client ? createElement(ClientOnly_default, typeof page.client === "object" ? page.client : {}, view) : view;
1018
+ return createElement(RouterLayerContext.Provider, { value: {
1019
+ index,
1020
+ path
1021
+ } }, element);
1022
+ }
1023
+ configure = $hook({
1024
+ on: "configure",
1025
+ handler: () => {
1026
+ let hasNotFoundHandler = false;
1027
+ const pages = this.alepha.descriptors($page);
1028
+ const hasParent = (it) => {
1029
+ if (it.options.parent) return true;
1030
+ for (const page of pages) if ((page.options.children ? Array.isArray(page.options.children) ? page.options.children : page.options.children() : []).includes(it)) return true;
1031
+ };
1032
+ for (const page of pages) {
1033
+ if (page.options.path === "/*") hasNotFoundHandler = true;
1034
+ if (hasParent(page)) continue;
1035
+ this.add(this.map(pages, page));
1036
+ }
1037
+ if (!hasNotFoundHandler && pages.length > 0) this.add({
1038
+ path: "/*",
1039
+ name: "notFound",
1040
+ cache: true,
1041
+ component: NotFoundPage,
1042
+ onServerResponse: ({ reply }) => {
1043
+ reply.status = 404;
1044
+ }
1045
+ });
1046
+ }
1047
+ });
1048
+ map(pages, target) {
1049
+ const children = target.options.children ? Array.isArray(target.options.children) ? target.options.children : target.options.children() : [];
1050
+ const getChildrenFromParent = (it) => {
1051
+ const children$1 = [];
1052
+ for (const page of pages) if (page.options.parent === it) children$1.push(page);
1053
+ return children$1;
1054
+ };
1055
+ children.push(...getChildrenFromParent(target));
1056
+ return {
1057
+ ...target.options,
1058
+ name: target.name,
1059
+ parent: void 0,
1060
+ children: children.map((it) => this.map(pages, it))
1061
+ };
1062
+ }
1063
+ add(entry) {
1064
+ if (this.alepha.isReady()) throw new AlephaError("Router is already initialized");
1065
+ entry.name ??= this.nextId();
1066
+ const page = entry;
1067
+ page.match = this.createMatch(page);
1068
+ this.pages.push(page);
1069
+ if (page.children) for (const child of page.children) {
1070
+ child.parent = page;
1071
+ this.add(child);
1072
+ }
1073
+ }
1074
+ createMatch(page) {
1075
+ let url = page.path ?? "/";
1076
+ let target = page.parent;
1077
+ while (target) {
1078
+ url = `${target.path ?? ""}/${url}`;
1079
+ target = target.parent;
1080
+ }
1081
+ let path = url.replace(/\/\/+/g, "/");
1082
+ if (path.endsWith("/") && path !== "/") path = path.slice(0, -1);
1083
+ return path;
1084
+ }
1085
+ _next = 0;
1086
+ nextId() {
1087
+ this._next += 1;
1088
+ return `P${this._next}`;
1089
+ }
1090
+ };
1091
+ const isPageRoute = (it) => {
1092
+ return it && typeof it === "object" && typeof it.path === "string" && typeof it.page === "object";
1093
+ };
1094
+
1095
+ //#endregion
1096
+ //#region src/core/providers/ReactServerProvider.ts
1097
+ const envSchema$1 = t.object({
1098
+ REACT_SSR_ENABLED: t.optional(t.boolean()),
1099
+ REACT_ROOT_ID: t.text({ default: "root" }),
1100
+ REACT_SERVER_TEMPLATE: t.optional(t.text({ size: "rich" }))
1101
+ });
1102
+ /**
1103
+ * React server provider configuration atom
1104
+ */
1105
+ const reactServerOptions = $atom({
1106
+ name: "alepha.react.server.options",
1107
+ schema: t.object({
1108
+ publicDir: t.string(),
1109
+ staticServer: t.object({
1110
+ disabled: t.boolean(),
1111
+ path: t.string({ description: "URL path where static files will be served." })
1112
+ })
1113
+ }),
1114
+ default: {
1115
+ publicDir: "public",
1116
+ staticServer: {
1117
+ disabled: false,
1118
+ path: "/"
1119
+ }
1120
+ }
1121
+ });
1122
+ var ReactServerProvider = class {
1123
+ log = $logger();
1124
+ alepha = $inject(Alepha);
1125
+ env = $env(envSchema$1);
1126
+ pageApi = $inject(ReactPageProvider);
1127
+ serverProvider = $inject(ServerProvider);
1128
+ serverStaticProvider = $inject(ServerStaticProvider);
1129
+ serverRouterProvider = $inject(ServerRouterProvider);
1130
+ serverTimingProvider = $inject(ServerTimingProvider);
1131
+ ROOT_DIV_REGEX = new RegExp(`<div([^>]*)\\s+id=["']${this.env.REACT_ROOT_ID}["']([^>]*)>(.*?)<\\/div>`, "is");
1132
+ preprocessedTemplate = null;
1133
+ options = $use(reactServerOptions);
1134
+ /**
1135
+ * Configure the React server provider.
1136
+ */
1137
+ onConfigure = $hook({
1138
+ on: "configure",
1139
+ handler: async () => {
1140
+ const ssrEnabled = this.alepha.descriptors($page).length > 0 && this.env.REACT_SSR_ENABLED !== false;
1141
+ this.alepha.state.set("alepha.react.server.ssr", ssrEnabled);
1142
+ if (this.alepha.isViteDev()) {
1143
+ await this.configureVite(ssrEnabled);
1144
+ return;
1145
+ }
1146
+ let root = "";
1147
+ if (!this.alepha.isServerless()) {
1148
+ root = this.getPublicDirectory();
1149
+ if (!root) this.log.warn("Missing static files, static file server will be disabled");
1150
+ else {
1151
+ this.log.debug(`Using static files from: ${root}`);
1152
+ await this.configureStaticServer(root);
1153
+ }
1154
+ }
1155
+ if (ssrEnabled) {
1156
+ await this.registerPages(async () => this.template);
1157
+ this.log.info("SSR OK");
1158
+ return;
1159
+ }
1160
+ this.log.info("SSR is disabled, use History API fallback");
1161
+ this.serverRouterProvider.createRoute({
1162
+ path: "*",
1163
+ handler: async ({ url, reply }) => {
1164
+ if (url.pathname.includes(".")) {
1165
+ reply.headers["content-type"] = "text/plain";
1166
+ reply.body = "Not Found";
1167
+ reply.status = 404;
1168
+ return;
1169
+ }
1170
+ reply.headers["content-type"] = "text/html";
1171
+ return this.template;
1172
+ }
1173
+ });
1174
+ }
1175
+ });
1176
+ get template() {
1177
+ return this.alepha.env.REACT_SERVER_TEMPLATE ?? "<!DOCTYPE html><html lang='en'><head></head><body></body></html>";
1178
+ }
1179
+ async registerPages(templateLoader) {
1180
+ const template = await templateLoader();
1181
+ if (template) this.preprocessedTemplate = this.preprocessTemplate(template);
1182
+ for (const page of this.pageApi.getPages()) {
1183
+ if (page.children?.length) continue;
1184
+ this.log.debug(`+ ${page.match} -> ${page.name}`);
1185
+ this.serverRouterProvider.createRoute({
1186
+ ...page,
1187
+ schema: void 0,
1188
+ method: "GET",
1189
+ path: page.match,
1190
+ handler: this.createHandler(page, templateLoader)
1191
+ });
1192
+ }
1193
+ }
1194
+ /**
1195
+ * Get the public directory path where static files are located.
1196
+ */
1197
+ getPublicDirectory() {
1198
+ const maybe = [join(process.cwd(), `dist/${this.options.publicDir}`), join(process.cwd(), this.options.publicDir)];
1199
+ for (const it of maybe) if (existsSync(it)) return it;
1200
+ return "";
1201
+ }
1202
+ /**
1203
+ * Configure the static file server to serve files from the given root directory.
1204
+ */
1205
+ async configureStaticServer(root) {
1206
+ await this.serverStaticProvider.createStaticServer({
1207
+ root,
1208
+ cacheControl: {
1209
+ maxAge: 3600,
1210
+ immutable: true
1211
+ },
1212
+ ...this.options.staticServer
1213
+ });
1214
+ }
1215
+ /**
1216
+ * Configure Vite for SSR.
1217
+ */
1218
+ async configureVite(ssrEnabled) {
1219
+ if (!ssrEnabled) return;
1220
+ this.log.info("SSR (dev) OK");
1221
+ const url = `http://${process.env.SERVER_HOST}:${process.env.SERVER_PORT}`;
1222
+ await this.registerPages(() => fetch(`${url}/index.html`).then((it) => it.text()).catch(() => void 0));
1223
+ }
1224
+ /**
1225
+ * For testing purposes, creates a render function that can be used.
1226
+ */
1227
+ async render(name, options = {}) {
1228
+ const page = this.pageApi.page(name);
1229
+ const url = new URL(this.pageApi.url(name, options));
1230
+ const state = {
1231
+ url,
1232
+ params: options.params ?? {},
1233
+ query: options.query ?? {},
1234
+ onError: () => null,
1235
+ layers: [],
1236
+ meta: {}
1237
+ };
1238
+ this.log.trace("Rendering", { url });
1239
+ await this.alepha.events.emit("react:server:render:begin", { state });
1240
+ const { redirect } = await this.pageApi.createLayers(page, state);
1241
+ if (redirect) return {
1242
+ state,
1243
+ html: "",
1244
+ redirect
1245
+ };
1246
+ if (!options.html) {
1247
+ this.alepha.state.set("alepha.react.router.state", state);
1248
+ return {
1249
+ state,
1250
+ html: renderToString(this.pageApi.root(state))
1251
+ };
1252
+ }
1253
+ const template = this.template ?? "";
1254
+ const html = this.renderToHtml(template, state, options.hydration);
1255
+ if (html instanceof Redirection) return {
1256
+ state,
1257
+ html: "",
1258
+ redirect
1259
+ };
1260
+ const result = {
1261
+ state,
1262
+ html
1263
+ };
1264
+ await this.alepha.events.emit("react:server:render:end", result);
1265
+ return result;
1266
+ }
1267
+ createHandler(route, templateLoader) {
1268
+ return async (serverRequest) => {
1269
+ const { url, reply, query, params } = serverRequest;
1270
+ const template = await templateLoader();
1271
+ if (!template) throw new AlephaError("Missing template for SSR rendering");
1272
+ this.log.trace("Rendering page", { name: route.name });
1273
+ const state = {
1274
+ url,
1275
+ params,
1276
+ query,
1277
+ onError: () => null,
1278
+ layers: []
1279
+ };
1280
+ if (this.alepha.has(ServerLinksProvider)) this.alepha.state.set("alepha.server.request.apiLinks", await this.alepha.inject(ServerLinksProvider).getUserApiLinks({
1281
+ user: serverRequest.user,
1282
+ authorization: serverRequest.headers.authorization
1283
+ }));
1284
+ let target = route;
1285
+ while (target) {
1286
+ if (route.can && !route.can()) {
1287
+ reply.status = 403;
1288
+ reply.headers["content-type"] = "text/plain";
1289
+ return "Forbidden";
1290
+ }
1291
+ target = target.parent;
1292
+ }
1293
+ await this.alepha.events.emit("react:server:render:begin", {
1294
+ request: serverRequest,
1295
+ state
1296
+ });
1297
+ this.serverTimingProvider.beginTiming("createLayers");
1298
+ const { redirect } = await this.pageApi.createLayers(route, state);
1299
+ this.serverTimingProvider.endTiming("createLayers");
1300
+ if (redirect) return reply.redirect(redirect);
1301
+ reply.headers["content-type"] = "text/html";
1302
+ reply.headers["cache-control"] = "no-store, no-cache, must-revalidate, proxy-revalidate";
1303
+ reply.headers.pragma = "no-cache";
1304
+ reply.headers.expires = "0";
1305
+ const html = this.renderToHtml(template, state);
1306
+ if (html instanceof Redirection) {
1307
+ reply.redirect(typeof html.redirect === "string" ? html.redirect : this.pageApi.href(html.redirect));
1308
+ return;
1309
+ }
1310
+ const event = {
1311
+ request: serverRequest,
1312
+ state,
1313
+ html
1314
+ };
1315
+ await this.alepha.events.emit("react:server:render:end", event);
1316
+ route.onServerResponse?.(serverRequest);
1317
+ this.log.trace("Page rendered", { name: route.name });
1318
+ return event.html;
1319
+ };
1320
+ }
1321
+ renderToHtml(template, state, hydration = true) {
1322
+ const element = this.pageApi.root(state);
1323
+ this.alepha.state.set("alepha.react.router.state", state);
1324
+ this.serverTimingProvider.beginTiming("renderToString");
1325
+ let app = "";
1326
+ try {
1327
+ app = renderToString(element);
1328
+ } catch (error) {
1329
+ this.log.error("renderToString has failed, fallback to error handler", error);
1330
+ const element$1 = state.onError(error, state);
1331
+ if (element$1 instanceof Redirection) return element$1;
1332
+ app = renderToString(element$1);
1333
+ this.log.debug("Error handled successfully with fallback");
1334
+ }
1335
+ this.serverTimingProvider.endTiming("renderToString");
1336
+ const response = { html: template };
1337
+ if (hydration) {
1338
+ const { request, context, ...store } = this.alepha.context.als?.getStore() ?? {};
1339
+ const hydrationData = {
1340
+ ...store,
1341
+ "alepha.react.router.state": void 0,
1342
+ layers: state.layers.map((it) => ({
1343
+ ...it,
1344
+ error: it.error ? {
1345
+ ...it.error,
1346
+ name: it.error.name,
1347
+ message: it.error.message,
1348
+ stack: !this.alepha.isProduction() ? it.error.stack : void 0
1349
+ } : void 0,
1350
+ index: void 0,
1351
+ path: void 0,
1352
+ element: void 0,
1353
+ route: void 0
1354
+ }))
1355
+ };
1356
+ const script = `<script>window.__ssr=${JSON.stringify(hydrationData)}<\/script>`;
1357
+ this.fillTemplate(response, app, script);
1358
+ }
1359
+ return response.html;
1360
+ }
1361
+ preprocessTemplate(template) {
1362
+ const bodyCloseIndex = template.match(/<\/body>/i)?.index ?? template.length;
1363
+ const beforeScript = template.substring(0, bodyCloseIndex);
1364
+ const afterScript = template.substring(bodyCloseIndex);
1365
+ const rootDivMatch = beforeScript.match(this.ROOT_DIV_REGEX);
1366
+ if (rootDivMatch) {
1367
+ const beforeDiv = beforeScript.substring(0, rootDivMatch.index);
1368
+ const afterDivStart = rootDivMatch.index + rootDivMatch[0].length;
1369
+ const afterDiv = beforeScript.substring(afterDivStart);
1370
+ return {
1371
+ beforeApp: `${beforeDiv}<div${rootDivMatch[1]} id="${this.env.REACT_ROOT_ID}"${rootDivMatch[2]}>`,
1372
+ afterApp: `</div>${afterDiv}`,
1373
+ beforeScript: "",
1374
+ afterScript
1375
+ };
1376
+ }
1377
+ const bodyMatch = beforeScript.match(/<body([^>]*)>/i);
1378
+ if (bodyMatch) {
1379
+ const beforeBody = beforeScript.substring(0, bodyMatch.index + bodyMatch[0].length);
1380
+ const afterBody = beforeScript.substring(bodyMatch.index + bodyMatch[0].length);
1381
+ return {
1382
+ beforeApp: `${beforeBody}<div id="${this.env.REACT_ROOT_ID}">`,
1383
+ afterApp: `</div>${afterBody}`,
1384
+ beforeScript: "",
1385
+ afterScript
1386
+ };
1387
+ }
1388
+ return {
1389
+ beforeApp: `<div id="${this.env.REACT_ROOT_ID}">`,
1390
+ afterApp: `</div>`,
1391
+ beforeScript,
1392
+ afterScript
1393
+ };
1394
+ }
1395
+ fillTemplate(response, app, script) {
1396
+ if (!this.preprocessedTemplate) this.preprocessedTemplate = this.preprocessTemplate(response.html);
1397
+ response.html = this.preprocessedTemplate.beforeApp + app + this.preprocessedTemplate.afterApp + script + this.preprocessedTemplate.afterScript;
1398
+ }
1399
+ };
1400
+
1401
+ //#endregion
1402
+ //#region src/core/services/ReactPageServerService.ts
1403
+ var ReactPageServerService = class extends ReactPageService {
1404
+ reactServerProvider = $inject(ReactServerProvider);
1405
+ serverProvider = $inject(ServerProvider);
1406
+ async render(name, options = {}) {
1407
+ return this.reactServerProvider.render(name, options);
1408
+ }
1409
+ async fetch(pathname, options = {}) {
1410
+ const response = await fetch(`${this.serverProvider.hostname}/${pathname}`);
1411
+ const html = await response.text();
1412
+ if (options?.html) return {
1413
+ html,
1414
+ response
1415
+ };
1416
+ const match = html.match(this.reactServerProvider.ROOT_DIV_REGEX);
1417
+ if (match) return {
1418
+ html: match[3],
1419
+ response
1420
+ };
1421
+ throw new AlephaError("Invalid HTML response");
1422
+ }
1423
+ };
1424
+
1425
+ //#endregion
1426
+ //#region src/core/providers/ReactBrowserRouterProvider.ts
1427
+ var ReactBrowserRouterProvider = class extends RouterProvider {
1428
+ log = $logger();
1429
+ alepha = $inject(Alepha);
1430
+ pageApi = $inject(ReactPageProvider);
1431
+ add(entry) {
1432
+ this.pageApi.add(entry);
1433
+ }
1434
+ configure = $hook({
1435
+ on: "configure",
1436
+ handler: async () => {
1437
+ for (const page of this.pageApi.getPages()) if (page.component || page.lazy) this.push({
1438
+ path: page.match,
1439
+ page
1440
+ });
1441
+ }
1442
+ });
1443
+ async transition(url, previous = [], meta = {}) {
1444
+ const { pathname, search } = url;
1445
+ const state = {
1446
+ url,
1447
+ query: {},
1448
+ params: {},
1449
+ layers: [],
1450
+ onError: () => null,
1451
+ meta
1452
+ };
1453
+ await this.alepha.events.emit("react:action:begin", { type: "transition" });
1454
+ await this.alepha.events.emit("react:transition:begin", {
1455
+ previous: this.alepha.state.get("alepha.react.router.state"),
1456
+ state
1457
+ });
1458
+ try {
1459
+ const { route, params } = this.match(pathname);
1460
+ const query = {};
1461
+ if (search) for (const [key, value] of new URLSearchParams(search).entries()) query[key] = String(value);
1462
+ state.query = query;
1463
+ state.params = params ?? {};
1464
+ if (isPageRoute(route)) {
1465
+ const { redirect } = await this.pageApi.createLayers(route.page, state, previous);
1466
+ if (redirect) return redirect;
1467
+ }
1468
+ if (state.layers.length === 0) state.layers.push({
1469
+ name: "not-found",
1470
+ element: createElement(NotFoundPage),
1471
+ index: 0,
1472
+ path: "/"
1473
+ });
1474
+ await this.alepha.events.emit("react:action:success", { type: "transition" });
1475
+ await this.alepha.events.emit("react:transition:success", { state });
1476
+ } catch (e) {
1477
+ this.log.error("Transition has failed", e);
1478
+ state.layers = [{
1479
+ name: "error",
1480
+ element: this.pageApi.renderError(e),
1481
+ index: 0,
1482
+ path: "/"
1483
+ }];
1484
+ await this.alepha.events.emit("react:action:error", {
1485
+ type: "transition",
1486
+ error: e
1487
+ });
1488
+ await this.alepha.events.emit("react:transition:error", {
1489
+ error: e,
1490
+ state
1491
+ });
1492
+ }
1493
+ if (previous) for (let i = 0; i < previous.length; i++) {
1494
+ const layer = previous[i];
1495
+ if (state.layers[i]?.name !== layer.name) this.pageApi.page(layer.name)?.onLeave?.();
1496
+ }
1497
+ this.alepha.state.set("alepha.react.router.state", state);
1498
+ await this.alepha.events.emit("react:action:end", { type: "transition" });
1499
+ await this.alepha.events.emit("react:transition:end", { state });
1500
+ }
1501
+ root(state) {
1502
+ return this.pageApi.root(state);
1503
+ }
1504
+ };
1505
+
1506
+ //#endregion
1507
+ //#region src/core/providers/ReactBrowserProvider.ts
1508
+ const envSchema = t.object({ REACT_ROOT_ID: t.text({ default: "root" }) });
1509
+ /**
1510
+ * React browser renderer configuration atom
1511
+ */
1512
+ const reactBrowserOptions = $atom({
1513
+ name: "alepha.react.browser.options",
1514
+ schema: t.object({ scrollRestoration: t.enum(["top", "manual"]) }),
1515
+ default: { scrollRestoration: "top" }
1516
+ });
1517
+ var ReactBrowserProvider = class {
1518
+ env = $env(envSchema);
1519
+ log = $logger();
1520
+ client = $inject(LinkProvider);
1521
+ alepha = $inject(Alepha);
1522
+ router = $inject(ReactBrowserRouterProvider);
1523
+ dateTimeProvider = $inject(DateTimeProvider);
1524
+ options = $use(reactBrowserOptions);
1525
+ getRootElement() {
1526
+ const root = this.document.getElementById(this.env.REACT_ROOT_ID);
1527
+ if (root) return root;
1528
+ const div = this.document.createElement("div");
1529
+ div.id = this.env.REACT_ROOT_ID;
1530
+ this.document.body.prepend(div);
1531
+ return div;
1532
+ }
1533
+ transitioning;
1534
+ get state() {
1535
+ return this.alepha.state.get("alepha.react.router.state");
1536
+ }
1537
+ /**
1538
+ * Accessor for Document DOM API.
1539
+ */
1540
+ get document() {
1541
+ return window.document;
1542
+ }
1543
+ /**
1544
+ * Accessor for History DOM API.
1545
+ */
1546
+ get history() {
1547
+ return window.history;
1548
+ }
1549
+ /**
1550
+ * Accessor for Location DOM API.
1551
+ */
1552
+ get location() {
1553
+ return window.location;
1554
+ }
1555
+ get base() {
1556
+ const base = import.meta.env?.BASE_URL;
1557
+ if (!base || base === "/") return "";
1558
+ return base;
1559
+ }
1560
+ get url() {
1561
+ const url = this.location.pathname + this.location.search;
1562
+ if (this.base) return url.replace(this.base, "");
1563
+ return url;
1564
+ }
1565
+ pushState(path, replace) {
1566
+ const url = this.base + path;
1567
+ if (replace) this.history.replaceState({}, "", url);
1568
+ else this.history.pushState({}, "", url);
1569
+ }
1570
+ async invalidate(props) {
1571
+ const previous = [];
1572
+ this.log.trace("Invalidating layers");
1573
+ if (props) {
1574
+ const [key] = Object.keys(props);
1575
+ const value = props[key];
1576
+ for (const layer of this.state.layers) {
1577
+ if (layer.props?.[key]) {
1578
+ previous.push({
1579
+ ...layer,
1580
+ props: {
1581
+ ...layer.props,
1582
+ [key]: value
1583
+ }
1584
+ });
1585
+ break;
1586
+ }
1587
+ previous.push(layer);
1588
+ }
1589
+ }
1590
+ await this.render({ previous });
1591
+ }
1592
+ async go(url, options = {}) {
1593
+ this.log.trace(`Going to ${url}`, {
1594
+ url,
1595
+ options
1596
+ });
1597
+ await this.render({
1598
+ url,
1599
+ previous: options.force ? [] : this.state.layers,
1600
+ meta: options.meta
1601
+ });
1602
+ if (this.state.url.pathname + this.state.url.search !== url) {
1603
+ this.pushState(this.state.url.pathname + this.state.url.search);
1604
+ return;
1605
+ }
1606
+ this.pushState(url, options.replace);
1607
+ }
1608
+ async render(options = {}) {
1609
+ const previous = options.previous ?? this.state.layers;
1610
+ const url = options.url ?? this.url;
1611
+ const start = this.dateTimeProvider.now();
1612
+ this.transitioning = {
1613
+ to: url,
1614
+ from: this.state?.url.pathname
1615
+ };
1616
+ this.log.debug("Transitioning...", { to: url });
1617
+ const redirect = await this.router.transition(new URL(`http://localhost${url}`), previous, options.meta);
1618
+ if (redirect) {
1619
+ this.log.info("Redirecting to", { redirect });
1620
+ if (redirect.startsWith("http")) window.location.href = redirect;
1621
+ else return await this.render({ url: redirect });
1622
+ }
1623
+ const ms = this.dateTimeProvider.now().diff(start);
1624
+ this.log.info(`Transition OK [${ms}ms]`, this.transitioning);
1625
+ this.transitioning = void 0;
1626
+ }
1627
+ /**
1628
+ * Get embedded layers from the server.
1629
+ */
1630
+ getHydrationState() {
1631
+ try {
1632
+ if ("__ssr" in window && typeof window.__ssr === "object") return window.__ssr;
1633
+ } catch (error) {
1634
+ console.error(error);
1635
+ }
1636
+ }
1637
+ onTransitionEnd = $hook({
1638
+ on: "react:transition:end",
1639
+ handler: () => {
1640
+ if (this.options.scrollRestoration === "top" && typeof window !== "undefined" && !this.alepha.isTest()) {
1641
+ this.log.trace("Restoring scroll position to top");
1642
+ window.scrollTo(0, 0);
1643
+ }
1644
+ }
1645
+ });
1646
+ ready = $hook({
1647
+ on: "ready",
1648
+ handler: async () => {
1649
+ const hydration = this.getHydrationState();
1650
+ const previous = hydration?.layers ?? [];
1651
+ if (hydration) {
1652
+ for (const [key, value] of Object.entries(hydration)) if (key !== "layers") this.alepha.state.set(key, value);
1653
+ }
1654
+ await this.render({ previous });
1655
+ const element = this.router.root(this.state);
1656
+ await this.alepha.events.emit("react:browser:render", {
1657
+ element,
1658
+ root: this.getRootElement(),
1659
+ hydration,
1660
+ state: this.state
1661
+ });
1662
+ window.addEventListener("popstate", () => {
1663
+ if (this.base + this.state.url.pathname === this.location.pathname) return;
1664
+ this.log.debug("Popstate event triggered - rendering new state", { url: this.location.pathname + this.location.search });
1665
+ this.render();
1666
+ });
1667
+ }
1668
+ });
1669
+ };
1670
+
1671
+ //#endregion
1672
+ //#region src/core/services/ReactRouter.ts
1673
+ var ReactRouter = class {
1674
+ alepha = $inject(Alepha);
1675
+ pageApi = $inject(ReactPageProvider);
1676
+ get state() {
1677
+ return this.alepha.state.get("alepha.react.router.state");
1678
+ }
1679
+ get pages() {
1680
+ return this.pageApi.getPages();
1681
+ }
1682
+ get concretePages() {
1683
+ return this.pageApi.getConcretePages();
1684
+ }
1685
+ get browser() {
1686
+ if (this.alepha.isBrowser()) return this.alepha.inject(ReactBrowserProvider);
1687
+ }
1688
+ isActive(href, options = {}) {
1689
+ const current = this.state.url.pathname;
1690
+ let isActive = current === href || current === `${href}/` || `${current}/` === href;
1691
+ if (options.startWith && !isActive) isActive = current.startsWith(href);
1692
+ return isActive;
1693
+ }
1694
+ path(name, config = {}) {
1695
+ return this.pageApi.pathname(name, {
1696
+ params: {
1697
+ ...this.state.params,
1698
+ ...config.params
1699
+ },
1700
+ query: config.query
1701
+ });
1702
+ }
1703
+ /**
1704
+ * Reload the current page.
1705
+ * This is equivalent to calling `go()` with the current pathname and search.
1706
+ */
1707
+ async reload() {
1708
+ if (!this.browser) return;
1709
+ await this.go(this.location.pathname + this.location.search, {
1710
+ replace: true,
1711
+ force: true
1712
+ });
1713
+ }
1714
+ getURL() {
1715
+ if (!this.browser) return this.state.url;
1716
+ return new URL(this.location.href);
1717
+ }
1718
+ get location() {
1719
+ if (!this.browser) throw new Error("Browser is required");
1720
+ return this.browser.location;
1721
+ }
1722
+ get current() {
1723
+ return this.state;
1724
+ }
1725
+ get pathname() {
1726
+ return this.state.url.pathname;
1727
+ }
1728
+ get query() {
1729
+ const query = {};
1730
+ for (const [key, value] of new URLSearchParams(this.state.url.search).entries()) query[key] = String(value);
1731
+ return query;
1732
+ }
1733
+ async back() {
1734
+ this.browser?.history.back();
1735
+ }
1736
+ async forward() {
1737
+ this.browser?.history.forward();
1738
+ }
1739
+ async invalidate(props) {
1740
+ await this.browser?.invalidate(props);
1741
+ }
1742
+ async go(path, options) {
1743
+ for (const page of this.pages) if (page.name === path) {
1744
+ await this.browser?.go(this.path(path, options), options);
1745
+ return;
1746
+ }
1747
+ await this.browser?.go(path, options);
1748
+ }
1749
+ anchor(path, options = {}) {
1750
+ let href = path;
1751
+ for (const page of this.pages) if (page.name === path) {
1752
+ href = this.path(path, options);
1753
+ break;
1754
+ }
1755
+ return {
1756
+ href: this.base(href),
1757
+ onClick: (ev) => {
1758
+ ev.stopPropagation();
1759
+ ev.preventDefault();
1760
+ this.go(href, options).catch(console.error);
1761
+ }
1762
+ };
1763
+ }
1764
+ base(path) {
1765
+ const base = import.meta.env?.BASE_URL;
1766
+ if (!base || base === "/") return path;
1767
+ return base + path;
1768
+ }
1769
+ /**
1770
+ * Set query params.
1771
+ *
1772
+ * @param record
1773
+ * @param options
1774
+ */
1775
+ setQueryParams(record, options = {}) {
1776
+ const func = typeof record === "function" ? record : () => record;
1777
+ const search = new URLSearchParams(func(this.query)).toString();
1778
+ const state = search ? `${this.pathname}?${search}` : this.pathname;
1779
+ if (options.push) window.history.pushState({}, "", state);
1780
+ else window.history.replaceState({}, "", state);
1781
+ }
1782
+ };
1783
+
1784
+ //#endregion
1785
+ //#region src/core/hooks/useInject.ts
1786
+ /**
1787
+ * Hook to inject a service instance.
1788
+ * It's a wrapper of `useAlepha().inject(service)` with a memoization.
1789
+ */
1790
+ const useInject = (service) => {
1791
+ const alepha = useAlepha();
1792
+ return useMemo(() => alepha.inject(service), []);
1793
+ };
1794
+
1795
+ //#endregion
1796
+ //#region src/core/index.ts
1797
+ /**
1798
+ * Provides full-stack React development with declarative routing, server-side rendering, and client-side hydration.
1799
+ *
1800
+ * The React module enables building modern React applications using the `$page` descriptor on class properties.
1801
+ * It delivers seamless server-side rendering, automatic code splitting, and client-side navigation with full
1802
+ * type safety and schema validation for route parameters and data.
1803
+ *
1804
+ * @see {@link $page}
1805
+ * @module alepha.react
1806
+ */
1807
+ const AlephaReact = $module({
1808
+ name: "alepha.react",
1809
+ descriptors: [$page],
1810
+ services: [
1811
+ ReactServerProvider,
1812
+ ReactPageProvider,
1813
+ ReactRouter,
1814
+ ReactPageService,
1815
+ ReactPageServerService
1816
+ ],
1817
+ register: (alepha) => alepha.with(AlephaDateTime).with(AlephaServer).with(AlephaServerCache).with(AlephaServerLinks).with({
1818
+ provide: ReactPageService,
1819
+ use: ReactPageServerService
1820
+ }).with(ReactServerProvider).with(ReactPageProvider).with(ReactRouter)
1821
+ });
1822
+
1823
+ //#endregion
1824
+ //#region src/i18n/hooks/useI18n.ts
1825
+ /**
1826
+ * Hook to access the i18n service.
1827
+ */
1828
+ const useI18n = () => {
1829
+ useStore("alepha.react.i18n.lang");
1830
+ return useInject(I18nProvider);
1831
+ };
1832
+
1833
+ //#endregion
1834
+ //#region src/i18n/components/Localize.tsx
1835
+ const Localize = (props) => {
1836
+ return useI18n().l(props.value, props);
1837
+ };
1838
+ var Localize_default = Localize;
1839
+
1840
+ //#endregion
1841
+ //#region src/i18n/index.ts
1842
+ /**
1843
+ * Add i18n support to your Alepha React application. SSR and CSR compatible.
1844
+ *
1845
+ * It supports lazy loading of translations and provides a context to access the current language.
1846
+ *
1847
+ * @module alepha.react.i18n
1848
+ */
1849
+ const AlephaReactI18n = $module({
1850
+ name: "alepha.react.i18n",
1851
+ descriptors: [$dictionary],
1852
+ services: [I18nProvider]
1853
+ });
1854
+
1855
+ //#endregion
1856
+ export { $dictionary, AlephaReactI18n, DictionaryDescriptor, I18nProvider, Localize_default as Localize, useI18n };
1857
+ //# sourceMappingURL=index.js.map