@alepha/react 0.13.0 → 0.13.1

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