@alepha/react 0.11.11 → 0.12.0

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