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