@alepha/react 0.7.5 → 0.7.6

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.
@@ -1,53 +1,1095 @@
1
- import { t, $inject, $logger, $hook, __bind } from '@alepha/core';
2
- import { l as ReactBrowserProvider, B as BrowserRouterProvider, $ as $page, P as PageDescriptorProvider } from './useRouterState-cCucJfTC.js';
3
- export { C as ClientOnly, E as ErrorBoundary, L as Link, N as NestedView, b as RedirectionError, R as RouterContext, c as RouterHookApi, a as RouterLayerContext, k as isPageRoute, u as useActive, d as useAlepha, e as useClient, f as useInject, g as useQueryParams, h as useRouter, i as useRouterEvents, j as useRouterState } from './useRouterState-cCucJfTC.js';
4
- import { hydrateRoot, createRoot } from 'react-dom/client';
5
- import 'react/jsx-runtime';
6
- import 'react';
7
- import '@alepha/server';
8
- import '@alepha/router';
9
-
10
- const envSchema = t.object({
11
- REACT_ROOT_ID: t.string({ default: "root" })
12
- });
13
- class ReactBrowserRenderer {
14
- browserProvider = $inject(ReactBrowserProvider);
15
- browserRouterProvider = $inject(BrowserRouterProvider);
16
- env = $inject(envSchema);
17
- log = $logger();
18
- root;
19
- getRootElement() {
20
- const root = this.browserProvider.document.getElementById(
21
- this.env.REACT_ROOT_ID
22
- );
23
- if (root) {
24
- return root;
25
- }
26
- const div = this.browserProvider.document.createElement("div");
27
- div.id = this.env.REACT_ROOT_ID;
28
- this.browserProvider.document.body.prepend(div);
29
- return div;
30
- }
31
- ready = $hook({
32
- name: "react:browser:render",
33
- handler: async ({ state, context, hydration }) => {
34
- const element = this.browserRouterProvider.root(state, context);
35
- if (hydration?.layers) {
36
- this.root = hydrateRoot(this.getRootElement(), element);
37
- this.log.info("Hydrated root element");
38
- } else {
39
- this.root ??= createRoot(this.getRootElement());
40
- this.root.render(element);
41
- this.log.info("Created root element");
42
- }
43
- }
44
- });
45
- }
1
+ import { $hook, $inject, $logger, Alepha, KIND, NotImplementedError, OPTIONS, __bind, __descriptor, t } from "@alepha/core";
2
+ import { RouterProvider } from "@alepha/router";
3
+ import React, { StrictMode, createContext, createElement, useContext, useEffect, useMemo, useState } from "react";
4
+ import { jsx, jsxs } from "react/jsx-runtime";
5
+ import { HttpClient } from "@alepha/server";
6
+ import { createRoot, hydrateRoot } from "react-dom/client";
7
+
8
+ //#region src/descriptors/$page.ts
9
+ const KEY = "PAGE";
10
+ /**
11
+ * Main descriptor for defining a React route in the application.
12
+ */
13
+ const $page = (options) => {
14
+ __descriptor(KEY);
15
+ if (options.children) for (const child of options.children) child[OPTIONS].parent = { [OPTIONS]: options };
16
+ if (options.parent) {
17
+ options.parent[OPTIONS].children ??= [];
18
+ options.parent[OPTIONS].children.push({ [OPTIONS]: options });
19
+ }
20
+ return {
21
+ [KIND]: KEY,
22
+ [OPTIONS]: options,
23
+ render: () => {
24
+ throw new NotImplementedError(KEY);
25
+ }
26
+ };
27
+ };
28
+ $page[KIND] = KEY;
46
29
 
47
- class AlephaReact {
48
- name = "alepha.react";
49
- $services = (alepha) => alepha.with(PageDescriptorProvider).with(ReactBrowserProvider).with(BrowserRouterProvider).with(ReactBrowserRenderer);
30
+ //#endregion
31
+ //#region src/components/NotFound.tsx
32
+ function NotFoundPage() {
33
+ return /* @__PURE__ */ jsx("div", {
34
+ style: {
35
+ height: "100vh",
36
+ display: "flex",
37
+ flexDirection: "column",
38
+ justifyContent: "center",
39
+ alignItems: "center",
40
+ textAlign: "center",
41
+ fontFamily: "sans-serif",
42
+ padding: "1rem"
43
+ },
44
+ children: /* @__PURE__ */ jsx("h1", {
45
+ style: {
46
+ fontSize: "1rem",
47
+ marginBottom: "0.5rem"
48
+ },
49
+ children: "This page does not exist"
50
+ })
51
+ });
50
52
  }
53
+
54
+ //#endregion
55
+ //#region src/components/ClientOnly.tsx
56
+ /**
57
+ * A small utility component that renders its children only on the client side.
58
+ *
59
+ * Optionally, you can provide a fallback React node that will be rendered.
60
+ *
61
+ * You should use this component when
62
+ * - you have code that relies on browser-specific APIs
63
+ * - you want to avoid server-side rendering for a specific part of your application
64
+ * - you want to prevent pre-rendering of a component
65
+ */
66
+ const ClientOnly = (props) => {
67
+ const [mounted, setMounted] = useState(false);
68
+ useEffect(() => setMounted(true), []);
69
+ if (props.disabled) return props.children;
70
+ return mounted ? props.children : props.fallback;
71
+ };
72
+ var ClientOnly_default = ClientOnly;
73
+
74
+ //#endregion
75
+ //#region src/contexts/RouterContext.ts
76
+ const RouterContext = createContext(void 0);
77
+
78
+ //#endregion
79
+ //#region src/hooks/useAlepha.ts
80
+ const useAlepha = () => {
81
+ const routerContext = useContext(RouterContext);
82
+ if (!routerContext) throw new Error("useAlepha must be used within a RouterProvider");
83
+ return routerContext.alepha;
84
+ };
85
+
86
+ //#endregion
87
+ //#region src/components/ErrorViewer.tsx
88
+ const ErrorViewer = ({ error }) => {
89
+ const [expanded, setExpanded] = useState(false);
90
+ const isProduction = useAlepha().isProduction();
91
+ if (isProduction) return /* @__PURE__ */ jsx(ErrorViewerProduction, {});
92
+ const stackLines = error.stack?.split("\n") ?? [];
93
+ const previewLines = stackLines.slice(0, 5);
94
+ const hiddenLineCount = stackLines.length - previewLines.length;
95
+ const copyToClipboard = (text) => {
96
+ navigator.clipboard.writeText(text).catch((err) => {
97
+ console.error("Clipboard error:", err);
98
+ });
99
+ };
100
+ const styles = {
101
+ container: {
102
+ padding: "24px",
103
+ backgroundColor: "#FEF2F2",
104
+ color: "#7F1D1D",
105
+ border: "1px solid #FECACA",
106
+ borderRadius: "16px",
107
+ boxShadow: "0 8px 24px rgba(0,0,0,0.05)",
108
+ fontFamily: "monospace",
109
+ maxWidth: "768px",
110
+ margin: "40px auto"
111
+ },
112
+ heading: {
113
+ fontSize: "20px",
114
+ fontWeight: "bold",
115
+ marginBottom: "4px"
116
+ },
117
+ name: {
118
+ fontSize: "16px",
119
+ fontWeight: 600
120
+ },
121
+ message: {
122
+ fontSize: "14px",
123
+ marginBottom: "16px"
124
+ },
125
+ sectionHeader: {
126
+ display: "flex",
127
+ justifyContent: "space-between",
128
+ alignItems: "center",
129
+ fontSize: "12px",
130
+ marginBottom: "4px",
131
+ color: "#991B1B"
132
+ },
133
+ copyButton: {
134
+ fontSize: "12px",
135
+ color: "#DC2626",
136
+ background: "none",
137
+ border: "none",
138
+ cursor: "pointer",
139
+ textDecoration: "underline"
140
+ },
141
+ stackContainer: {
142
+ backgroundColor: "#FEE2E2",
143
+ padding: "12px",
144
+ borderRadius: "8px",
145
+ fontSize: "13px",
146
+ lineHeight: "1.4",
147
+ overflowX: "auto",
148
+ whiteSpace: "pre-wrap"
149
+ },
150
+ expandLine: {
151
+ color: "#F87171",
152
+ cursor: "pointer",
153
+ marginTop: "8px"
154
+ }
155
+ };
156
+ return /* @__PURE__ */ jsxs("div", {
157
+ style: styles.container,
158
+ children: [/* @__PURE__ */ jsxs("div", { children: [
159
+ /* @__PURE__ */ jsx("div", {
160
+ style: styles.heading,
161
+ children: "🔥 Error"
162
+ }),
163
+ /* @__PURE__ */ jsx("div", {
164
+ style: styles.name,
165
+ children: error.name
166
+ }),
167
+ /* @__PURE__ */ jsx("div", {
168
+ style: styles.message,
169
+ children: error.message
170
+ })
171
+ ] }), stackLines.length > 0 && /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsxs("div", {
172
+ style: styles.sectionHeader,
173
+ children: [/* @__PURE__ */ jsx("span", { children: "Stack trace" }), /* @__PURE__ */ jsx("button", {
174
+ onClick: () => copyToClipboard(error.stack),
175
+ style: styles.copyButton,
176
+ children: "Copy all"
177
+ })]
178
+ }), /* @__PURE__ */ jsxs("pre", {
179
+ style: styles.stackContainer,
180
+ children: [(expanded ? stackLines : previewLines).map((line, i) => /* @__PURE__ */ jsx("div", { children: line }, i)), !expanded && hiddenLineCount > 0 && /* @__PURE__ */ jsxs("div", {
181
+ style: styles.expandLine,
182
+ onClick: () => setExpanded(true),
183
+ children: [
184
+ "+ ",
185
+ hiddenLineCount,
186
+ " more lines..."
187
+ ]
188
+ })]
189
+ })] })]
190
+ });
191
+ };
192
+ var ErrorViewer_default = ErrorViewer;
193
+ const ErrorViewerProduction = () => {
194
+ const styles = {
195
+ container: {
196
+ padding: "24px",
197
+ backgroundColor: "#FEF2F2",
198
+ color: "#7F1D1D",
199
+ border: "1px solid #FECACA",
200
+ borderRadius: "16px",
201
+ boxShadow: "0 8px 24px rgba(0,0,0,0.05)",
202
+ fontFamily: "monospace",
203
+ maxWidth: "768px",
204
+ margin: "40px auto",
205
+ textAlign: "center"
206
+ },
207
+ heading: {
208
+ fontSize: "20px",
209
+ fontWeight: "bold",
210
+ marginBottom: "8px"
211
+ },
212
+ name: {
213
+ fontSize: "16px",
214
+ fontWeight: 600,
215
+ marginBottom: "4px"
216
+ },
217
+ message: {
218
+ fontSize: "14px",
219
+ opacity: .85
220
+ }
221
+ };
222
+ return /* @__PURE__ */ jsxs("div", {
223
+ style: styles.container,
224
+ children: [/* @__PURE__ */ jsx("div", {
225
+ style: styles.heading,
226
+ children: "🚨 An error occurred"
227
+ }), /* @__PURE__ */ jsx("div", {
228
+ style: styles.message,
229
+ children: "Something went wrong. Please try again later."
230
+ })]
231
+ });
232
+ };
233
+
234
+ //#endregion
235
+ //#region src/contexts/RouterLayerContext.ts
236
+ const RouterLayerContext = createContext(void 0);
237
+
238
+ //#endregion
239
+ //#region src/hooks/useRouterEvents.ts
240
+ const useRouterEvents = (opts = {}, deps = []) => {
241
+ const ctx = useContext(RouterContext);
242
+ if (!ctx) throw new Error("useRouter must be used within a RouterProvider");
243
+ useEffect(() => {
244
+ if (!ctx.alepha.isBrowser()) return;
245
+ const subs = [];
246
+ const onBegin = opts.onBegin;
247
+ const onEnd = opts.onEnd;
248
+ const onError = opts.onError;
249
+ if (onBegin) subs.push(ctx.alepha.on("react:transition:begin", { callback: onBegin }));
250
+ if (onEnd) subs.push(ctx.alepha.on("react:transition:end", { callback: onEnd }));
251
+ if (onError) subs.push(ctx.alepha.on("react:transition:error", { callback: onError }));
252
+ return () => {
253
+ for (const sub of subs) sub();
254
+ };
255
+ }, deps);
256
+ };
257
+
258
+ //#endregion
259
+ //#region src/components/ErrorBoundary.tsx
260
+ /**
261
+ * A reusable error boundary for catching rendering errors
262
+ * in any part of the React component tree.
263
+ */
264
+ var ErrorBoundary = class extends React.Component {
265
+ constructor(props) {
266
+ super(props);
267
+ this.state = {};
268
+ }
269
+ /**
270
+ * Update state so the next render shows the fallback UI.
271
+ */
272
+ static getDerivedStateFromError(error) {
273
+ return { error };
274
+ }
275
+ /**
276
+ * Lifecycle method called when an error is caught.
277
+ * You can log the error or perform side effects here.
278
+ */
279
+ componentDidCatch(error, info) {
280
+ if (this.props.onError) this.props.onError(error, info);
281
+ }
282
+ render() {
283
+ if (this.state.error) return this.props.fallback(this.state.error);
284
+ return this.props.children;
285
+ }
286
+ };
287
+ var ErrorBoundary_default = ErrorBoundary;
288
+
289
+ //#endregion
290
+ //#region src/components/NestedView.tsx
291
+ /**
292
+ * A component that renders the current view of the nested router layer.
293
+ *
294
+ * To be simple, it renders the `element` of the current child page of a parent page.
295
+ *
296
+ * @example
297
+ * ```tsx
298
+ * import { NestedView } from "@alepha/react";
299
+ *
300
+ * class App {
301
+ * parent = $page({
302
+ * component: () => <NestedView />,
303
+ * });
304
+ *
305
+ * child = $page({
306
+ * parent: this.root,
307
+ * component: () => <div>Child Page</div>,
308
+ * });
309
+ * }
310
+ * ```
311
+ */
312
+ const NestedView = (props) => {
313
+ const app = useContext(RouterContext);
314
+ const layer = useContext(RouterLayerContext);
315
+ const index = layer?.index ?? 0;
316
+ const [view, setView] = useState(app?.state.layers[index]?.element);
317
+ useRouterEvents({ onEnd: ({ state }) => {
318
+ setView(state.layers[index]?.element);
319
+ } }, [app]);
320
+ if (!app) throw new Error("NestedView must be used within a RouterContext.");
321
+ const element = view ?? props.children ?? null;
322
+ return /* @__PURE__ */ jsx(ErrorBoundary_default, {
323
+ fallback: app.context.onError,
324
+ children: element
325
+ });
326
+ };
327
+ var NestedView_default = NestedView;
328
+
329
+ //#endregion
330
+ //#region src/errors/RedirectionError.ts
331
+ var RedirectionError = class extends Error {
332
+ page;
333
+ constructor(page) {
334
+ super("Redirection");
335
+ this.page = page;
336
+ }
337
+ };
338
+
339
+ //#endregion
340
+ //#region src/providers/PageDescriptorProvider.ts
341
+ const envSchema$1 = t.object({ REACT_STRICT_MODE: t.boolean({ default: true }) });
342
+ var PageDescriptorProvider = class {
343
+ log = $logger();
344
+ env = $inject(envSchema$1);
345
+ alepha = $inject(Alepha);
346
+ pages = [];
347
+ getPages() {
348
+ return this.pages;
349
+ }
350
+ page(name) {
351
+ for (const page of this.pages) if (page.name === name) return page;
352
+ throw new Error(`Page ${name} not found`);
353
+ }
354
+ url(name, options = {}) {
355
+ const page = this.page(name);
356
+ if (!page) throw new Error(`Page ${name} not found`);
357
+ let url = page.path ?? "";
358
+ let parent = page.parent;
359
+ while (parent) {
360
+ url = `${parent.path ?? ""}/${url}`;
361
+ parent = parent.parent;
362
+ }
363
+ url = this.compile(url, options.params ?? {});
364
+ return new URL(url.replace(/\/\/+/g, "/") || "/", options.base ?? `http://localhost`);
365
+ }
366
+ root(state, context) {
367
+ const root = createElement(RouterContext.Provider, { value: {
368
+ alepha: this.alepha,
369
+ state,
370
+ context
371
+ } }, createElement(NestedView_default, {}, state.layers[0]?.element));
372
+ if (this.env.REACT_STRICT_MODE) return createElement(StrictMode, {}, root);
373
+ return root;
374
+ }
375
+ async createLayers(route, request) {
376
+ const { pathname, search } = request.url;
377
+ const layers = [];
378
+ let context = {};
379
+ const stack = [{ route }];
380
+ request.onError = (error) => this.renderError(error);
381
+ let parent = route.parent;
382
+ while (parent) {
383
+ stack.unshift({ route: parent });
384
+ parent = parent.parent;
385
+ }
386
+ let forceRefresh = false;
387
+ for (let i = 0; i < stack.length; i++) {
388
+ const it = stack[i];
389
+ const route$1 = it.route;
390
+ const config = {};
391
+ try {
392
+ config.query = route$1.schema?.query ? this.alepha.parse(route$1.schema.query, request.query) : request.query;
393
+ } catch (e) {
394
+ it.error = e;
395
+ break;
396
+ }
397
+ try {
398
+ config.params = route$1.schema?.params ? this.alepha.parse(route$1.schema.params, request.params) : request.params;
399
+ } catch (e) {
400
+ it.error = e;
401
+ break;
402
+ }
403
+ it.config = { ...config };
404
+ if (!route$1.resolve) continue;
405
+ const previous = request.previous;
406
+ if (previous?.[i] && !forceRefresh && previous[i].name === route$1.name) {
407
+ const url = (str) => str ? str.replace(/\/\/+/g, "/") : "/";
408
+ const prev = JSON.stringify({
409
+ part: url(previous[i].part),
410
+ params: previous[i].config?.params ?? {}
411
+ });
412
+ const curr = JSON.stringify({
413
+ part: url(route$1.path),
414
+ params: config.params ?? {}
415
+ });
416
+ if (prev === curr) {
417
+ it.props = previous[i].props;
418
+ it.error = previous[i].error;
419
+ context = {
420
+ ...context,
421
+ ...it.props
422
+ };
423
+ continue;
424
+ }
425
+ forceRefresh = true;
426
+ }
427
+ try {
428
+ const props = await route$1.resolve?.({
429
+ ...request,
430
+ ...config,
431
+ ...context
432
+ }) ?? {};
433
+ it.props = { ...props };
434
+ context = {
435
+ ...context,
436
+ ...props
437
+ };
438
+ } catch (e) {
439
+ if (e instanceof RedirectionError) return {
440
+ layers: [],
441
+ redirect: typeof e.page === "string" ? e.page : this.href(e.page),
442
+ pathname,
443
+ search
444
+ };
445
+ this.log.error(e);
446
+ it.error = e;
447
+ break;
448
+ }
449
+ }
450
+ let acc = "";
451
+ for (let i = 0; i < stack.length; i++) {
452
+ const it = stack[i];
453
+ const props = it.props ?? {};
454
+ const params = { ...it.config?.params };
455
+ for (const key of Object.keys(params)) params[key] = String(params[key]);
456
+ if (it.route.head && !it.error) this.fillHead(it.route, request, {
457
+ ...props,
458
+ ...context
459
+ });
460
+ acc += "/";
461
+ acc += it.route.path ? this.compile(it.route.path, params) : "";
462
+ const path = acc.replace(/\/+/, "/");
463
+ const localErrorHandler = this.getErrorHandler(it.route);
464
+ if (localErrorHandler) request.onError = localErrorHandler;
465
+ if (it.error) {
466
+ let element$1 = await request.onError(it.error);
467
+ if (element$1 === null) element$1 = this.renderError(it.error);
468
+ layers.push({
469
+ props,
470
+ error: it.error,
471
+ name: it.route.name,
472
+ part: it.route.path,
473
+ config: it.config,
474
+ element: this.renderView(i + 1, path, element$1, it.route),
475
+ index: i + 1,
476
+ path
477
+ });
478
+ break;
479
+ }
480
+ const element = await this.createElement(it.route, {
481
+ ...props,
482
+ ...context
483
+ });
484
+ layers.push({
485
+ name: it.route.name,
486
+ props,
487
+ part: it.route.path,
488
+ config: it.config,
489
+ element: this.renderView(i + 1, path, element, it.route),
490
+ index: i + 1,
491
+ path
492
+ });
493
+ }
494
+ return {
495
+ layers,
496
+ pathname,
497
+ search
498
+ };
499
+ }
500
+ getErrorHandler(route) {
501
+ if (route.errorHandler) return route.errorHandler;
502
+ let parent = route.parent;
503
+ while (parent) {
504
+ if (parent.errorHandler) return parent.errorHandler;
505
+ parent = parent.parent;
506
+ }
507
+ }
508
+ async createElement(page, props) {
509
+ if (page.lazy) {
510
+ const component = await page.lazy();
511
+ return createElement(component.default, props);
512
+ }
513
+ if (page.component) return createElement(page.component, props);
514
+ return void 0;
515
+ }
516
+ fillHead(page, ctx, props) {
517
+ if (!page.head) return;
518
+ ctx.head ??= {};
519
+ const head = typeof page.head === "function" ? page.head(props, ctx.head) : page.head;
520
+ if (head.title) {
521
+ ctx.head ??= {};
522
+ if (ctx.head.titleSeparator) ctx.head.title = `${head.title}${ctx.head.titleSeparator}${ctx.head.title}`;
523
+ else ctx.head.title = head.title;
524
+ ctx.head.titleSeparator = head.titleSeparator;
525
+ }
526
+ if (head.htmlAttributes) ctx.head.htmlAttributes = {
527
+ ...ctx.head.htmlAttributes,
528
+ ...head.htmlAttributes
529
+ };
530
+ if (head.bodyAttributes) ctx.head.bodyAttributes = {
531
+ ...ctx.head.bodyAttributes,
532
+ ...head.bodyAttributes
533
+ };
534
+ if (head.meta) ctx.head.meta = [...ctx.head.meta ?? [], ...head.meta ?? []];
535
+ }
536
+ renderError(error) {
537
+ return createElement(ErrorViewer_default, { error });
538
+ }
539
+ renderEmptyView() {
540
+ return createElement(NestedView_default, {});
541
+ }
542
+ href(page, params = {}) {
543
+ const found = this.pages.find((it) => it.name === page.options.name);
544
+ if (!found) throw new Error(`Page ${page.options.name} not found`);
545
+ let url = found.path ?? "";
546
+ let parent = found.parent;
547
+ while (parent) {
548
+ url = `${parent.path ?? ""}/${url}`;
549
+ parent = parent.parent;
550
+ }
551
+ url = this.compile(url, params);
552
+ return url.replace(/\/\/+/g, "/") || "/";
553
+ }
554
+ compile(path, params = {}) {
555
+ for (const [key, value] of Object.entries(params)) path = path.replace(`:${key}`, value);
556
+ return path;
557
+ }
558
+ renderView(index, path, view, page) {
559
+ view ??= this.renderEmptyView();
560
+ const element = page.client ? createElement(ClientOnly_default, typeof page.client === "object" ? page.client : {}, view) : view;
561
+ return createElement(RouterLayerContext.Provider, { value: {
562
+ index,
563
+ path
564
+ } }, element);
565
+ }
566
+ configure = $hook({
567
+ name: "configure",
568
+ handler: () => {
569
+ let hasNotFoundHandler = false;
570
+ const pages = this.alepha.getDescriptorValues($page);
571
+ for (const { value, key } of pages) value[OPTIONS].name ??= key;
572
+ for (const { value } of pages) {
573
+ if (value[OPTIONS].parent) continue;
574
+ if (value[OPTIONS].path === "/*") hasNotFoundHandler = true;
575
+ this.add(this.map(pages, value));
576
+ }
577
+ if (!hasNotFoundHandler && pages.length > 0) this.add({
578
+ path: "/*",
579
+ name: "notFound",
580
+ cache: true,
581
+ component: NotFoundPage,
582
+ afterHandler: ({ reply }) => {
583
+ reply.status = 404;
584
+ }
585
+ });
586
+ }
587
+ });
588
+ map(pages, target) {
589
+ const children = target[OPTIONS].children ?? [];
590
+ return {
591
+ ...target[OPTIONS],
592
+ parent: void 0,
593
+ children: children.map((it) => this.map(pages, it))
594
+ };
595
+ }
596
+ add(entry) {
597
+ if (this.alepha.isReady()) throw new Error("Router is already initialized");
598
+ entry.name ??= this.nextId();
599
+ const page = entry;
600
+ page.match = this.createMatch(page);
601
+ this.pages.push(page);
602
+ if (page.children) for (const child of page.children) {
603
+ child.parent = page;
604
+ this.add(child);
605
+ }
606
+ }
607
+ createMatch(page) {
608
+ let url = page.path ?? "/";
609
+ let target = page.parent;
610
+ while (target) {
611
+ url = `${target.path ?? ""}/${url}`;
612
+ target = target.parent;
613
+ }
614
+ let path = url.replace(/\/\/+/g, "/");
615
+ if (path.endsWith("/") && path !== "/") path = path.slice(0, -1);
616
+ return path;
617
+ }
618
+ _next = 0;
619
+ nextId() {
620
+ this._next += 1;
621
+ return `P${this._next}`;
622
+ }
623
+ };
624
+ const isPageRoute = (it) => {
625
+ return it && typeof it === "object" && typeof it.path === "string" && typeof it.page === "object";
626
+ };
627
+
628
+ //#endregion
629
+ //#region src/providers/BrowserRouterProvider.ts
630
+ var BrowserRouterProvider = class extends RouterProvider {
631
+ log = $logger();
632
+ alepha = $inject(Alepha);
633
+ pageDescriptorProvider = $inject(PageDescriptorProvider);
634
+ add(entry) {
635
+ this.pageDescriptorProvider.add(entry);
636
+ }
637
+ configure = $hook({
638
+ name: "configure",
639
+ handler: async () => {
640
+ for (const page of this.pageDescriptorProvider.getPages()) if (page.component || page.lazy) this.push({
641
+ path: page.match,
642
+ page
643
+ });
644
+ }
645
+ });
646
+ async transition(url, options = {}) {
647
+ const { pathname, search } = url;
648
+ const state = {
649
+ pathname,
650
+ search,
651
+ layers: []
652
+ };
653
+ const context = {
654
+ url,
655
+ query: {},
656
+ params: {},
657
+ head: {},
658
+ onError: () => null,
659
+ ...options.context ?? {}
660
+ };
661
+ await this.alepha.emit("react:transition:begin", {
662
+ state,
663
+ context
664
+ });
665
+ try {
666
+ const previous = options.previous;
667
+ const { route, params } = this.match(pathname);
668
+ const query = {};
669
+ if (search) for (const [key, value] of new URLSearchParams(search).entries()) query[key] = String(value);
670
+ context.query = query;
671
+ context.params = params ?? {};
672
+ context.previous = previous;
673
+ if (isPageRoute(route)) {
674
+ const result = await this.pageDescriptorProvider.createLayers(route.page, context);
675
+ if (result.redirect) return {
676
+ redirect: result.redirect,
677
+ state,
678
+ context
679
+ };
680
+ state.layers = result.layers;
681
+ }
682
+ if (state.layers.length === 0) state.layers.push({
683
+ name: "not-found",
684
+ element: createElement(NotFoundPage),
685
+ index: 0,
686
+ path: "/"
687
+ });
688
+ await this.alepha.emit("react:transition:success", { state });
689
+ } catch (e) {
690
+ this.log.error(e);
691
+ state.layers = [{
692
+ name: "error",
693
+ element: this.pageDescriptorProvider.renderError(e),
694
+ index: 0,
695
+ path: "/"
696
+ }];
697
+ await this.alepha.emit("react:transition:error", {
698
+ error: e,
699
+ state,
700
+ context
701
+ });
702
+ }
703
+ if (options.state) {
704
+ options.state.layers = state.layers;
705
+ options.state.pathname = state.pathname;
706
+ options.state.search = state.search;
707
+ }
708
+ await this.alepha.emit("react:transition:end", {
709
+ state: options.state,
710
+ context
711
+ });
712
+ return {
713
+ context,
714
+ state
715
+ };
716
+ }
717
+ root(state, context) {
718
+ return this.pageDescriptorProvider.root(state, context);
719
+ }
720
+ };
721
+
722
+ //#endregion
723
+ //#region src/providers/BrowserHeadProvider.ts
724
+ var BrowserHeadProvider = class {
725
+ renderHead(document, head) {
726
+ if (head.title) document.title = head.title;
727
+ if (head.bodyAttributes) for (const [key, value] of Object.entries(head.bodyAttributes)) if (value) document.body.setAttribute(key, value);
728
+ else document.body.removeAttribute(key);
729
+ if (head.htmlAttributes) for (const [key, value] of Object.entries(head.htmlAttributes)) if (value) document.documentElement.setAttribute(key, value);
730
+ else document.documentElement.removeAttribute(key);
731
+ if (head.meta) for (const [key, value] of Object.entries(head.meta)) {
732
+ const meta = document.querySelector(`meta[name="${key}"]`);
733
+ if (meta) meta.setAttribute("content", value.content);
734
+ else {
735
+ const newMeta = document.createElement("meta");
736
+ newMeta.setAttribute("name", key);
737
+ newMeta.setAttribute("content", value.content);
738
+ document.head.appendChild(newMeta);
739
+ }
740
+ }
741
+ }
742
+ };
743
+
744
+ //#endregion
745
+ //#region src/providers/ReactBrowserProvider.ts
746
+ var ReactBrowserProvider = class {
747
+ log = $logger();
748
+ client = $inject(HttpClient);
749
+ alepha = $inject(Alepha);
750
+ router = $inject(BrowserRouterProvider);
751
+ headProvider = $inject(BrowserHeadProvider);
752
+ root;
753
+ transitioning;
754
+ state = {
755
+ layers: [],
756
+ pathname: "",
757
+ search: ""
758
+ };
759
+ get document() {
760
+ return window.document;
761
+ }
762
+ get history() {
763
+ return window.history;
764
+ }
765
+ get url() {
766
+ return window.location.pathname + window.location.search;
767
+ }
768
+ async invalidate(props) {
769
+ const previous = [];
770
+ if (props) {
771
+ const [key] = Object.keys(props);
772
+ const value = props[key];
773
+ for (const layer of this.state.layers) {
774
+ if (layer.props?.[key]) {
775
+ previous.push({
776
+ ...layer,
777
+ props: {
778
+ ...layer.props,
779
+ [key]: value
780
+ }
781
+ });
782
+ break;
783
+ }
784
+ previous.push(layer);
785
+ }
786
+ }
787
+ await this.render({ previous });
788
+ }
789
+ async go(url, options = {}) {
790
+ const result = await this.render({ url });
791
+ if (result.context.url.pathname !== url) {
792
+ this.history.replaceState({}, "", result.context.url.pathname);
793
+ return;
794
+ }
795
+ if (options.replace) {
796
+ this.history.replaceState({}, "", url);
797
+ return;
798
+ }
799
+ this.history.pushState({}, "", url);
800
+ }
801
+ async render(options = {}) {
802
+ const previous = options.previous ?? this.state.layers;
803
+ const url = options.url ?? this.url;
804
+ this.transitioning = { to: url };
805
+ const result = await this.router.transition(new URL(`http://localhost${url}`), {
806
+ previous,
807
+ state: this.state
808
+ });
809
+ if (result.redirect) return await this.render({ url: result.redirect });
810
+ this.transitioning = void 0;
811
+ return result;
812
+ }
813
+ /**
814
+ * Get embedded layers from the server.
815
+ */
816
+ getHydrationState() {
817
+ try {
818
+ if ("__ssr" in window && typeof window.__ssr === "object") return window.__ssr;
819
+ } catch (error) {
820
+ console.error(error);
821
+ }
822
+ }
823
+ ready = $hook({
824
+ name: "ready",
825
+ handler: async () => {
826
+ const hydration = this.getHydrationState();
827
+ const previous = hydration?.layers ?? [];
828
+ if (hydration?.links) for (const link of hydration.links.links) this.client.pushLink(link);
829
+ const { context } = await this.render({ previous });
830
+ if (context.head) this.headProvider.renderHead(this.document, context.head);
831
+ await this.alepha.emit("react:browser:render", {
832
+ state: this.state,
833
+ context,
834
+ hydration
835
+ });
836
+ window.addEventListener("popstate", () => {
837
+ this.render();
838
+ });
839
+ }
840
+ });
841
+ onTransitionEnd = $hook({
842
+ name: "react:transition:end",
843
+ handler: async ({ context }) => {
844
+ this.headProvider.renderHead(this.document, context.head);
845
+ }
846
+ });
847
+ };
848
+
849
+ //#endregion
850
+ //#region src/providers/ReactBrowserRenderer.ts
851
+ const envSchema = t.object({ REACT_ROOT_ID: t.string({ default: "root" }) });
852
+ var ReactBrowserRenderer = class {
853
+ browserProvider = $inject(ReactBrowserProvider);
854
+ browserRouterProvider = $inject(BrowserRouterProvider);
855
+ env = $inject(envSchema);
856
+ log = $logger();
857
+ root;
858
+ getRootElement() {
859
+ const root = this.browserProvider.document.getElementById(this.env.REACT_ROOT_ID);
860
+ if (root) return root;
861
+ const div = this.browserProvider.document.createElement("div");
862
+ div.id = this.env.REACT_ROOT_ID;
863
+ this.browserProvider.document.body.prepend(div);
864
+ return div;
865
+ }
866
+ ready = $hook({
867
+ name: "react:browser:render",
868
+ handler: async ({ state, context, hydration }) => {
869
+ const element = this.browserRouterProvider.root(state, context);
870
+ if (hydration?.layers) {
871
+ this.root = hydrateRoot(this.getRootElement(), element);
872
+ this.log.info("Hydrated root element");
873
+ } else {
874
+ this.root ??= createRoot(this.getRootElement());
875
+ this.root.render(element);
876
+ this.log.info("Created root element");
877
+ }
878
+ }
879
+ });
880
+ };
881
+
882
+ //#endregion
883
+ //#region src/hooks/RouterHookApi.ts
884
+ var RouterHookApi = class {
885
+ constructor(pages, state, layer, browser) {
886
+ this.pages = pages;
887
+ this.state = state;
888
+ this.layer = layer;
889
+ this.browser = browser;
890
+ }
891
+ get current() {
892
+ return this.state;
893
+ }
894
+ get pathname() {
895
+ return this.state.pathname;
896
+ }
897
+ get query() {
898
+ const query = {};
899
+ for (const [key, value] of new URLSearchParams(this.state.search).entries()) query[key] = String(value);
900
+ return query;
901
+ }
902
+ async back() {
903
+ this.browser?.history.back();
904
+ }
905
+ async forward() {
906
+ this.browser?.history.forward();
907
+ }
908
+ async invalidate(props) {
909
+ await this.browser?.invalidate(props);
910
+ }
911
+ /**
912
+ * Create a valid href for the given pathname.
913
+ *
914
+ * @param pathname
915
+ * @param layer
916
+ */
917
+ createHref(pathname, layer = this.layer, options = {}) {
918
+ if (typeof pathname === "object") pathname = pathname.options.path ?? "";
919
+ if (options.params) for (const [key, value] of Object.entries(options.params)) pathname = pathname.replace(`:${key}`, String(value));
920
+ return pathname.startsWith("/") ? pathname : `${layer.path}/${pathname}`.replace(/\/\/+/g, "/");
921
+ }
922
+ async go(path, options) {
923
+ for (const page of this.pages) if (page.name === path) {
924
+ path = page.path ?? "";
925
+ break;
926
+ }
927
+ await this.browser?.go(this.createHref(path, this.layer, options), options);
928
+ }
929
+ anchor(path, options = {}) {
930
+ for (const page of this.pages) if (page.name === path) {
931
+ path = page.path ?? "";
932
+ break;
933
+ }
934
+ const href = this.createHref(path, this.layer, options);
935
+ return {
936
+ href,
937
+ onClick: (ev) => {
938
+ ev.stopPropagation();
939
+ ev.preventDefault();
940
+ this.go(path, options).catch(console.error);
941
+ }
942
+ };
943
+ }
944
+ /**
945
+ * Set query params.
946
+ *
947
+ * @param record
948
+ * @param options
949
+ */
950
+ setQueryParams(record, options = {}) {
951
+ const func = typeof record === "function" ? record : () => record;
952
+ const search = new URLSearchParams(func(this.query)).toString();
953
+ const state = search ? `${this.pathname}?${search}` : this.pathname;
954
+ if (options.push) window.history.pushState({}, "", state);
955
+ else window.history.replaceState({}, "", state);
956
+ }
957
+ };
958
+
959
+ //#endregion
960
+ //#region src/hooks/useRouter.ts
961
+ const useRouter = () => {
962
+ const ctx = useContext(RouterContext);
963
+ const layer = useContext(RouterLayerContext);
964
+ if (!ctx || !layer) throw new Error("useRouter must be used within a RouterProvider");
965
+ const pages = useMemo(() => {
966
+ return ctx.alepha.get(PageDescriptorProvider).getPages();
967
+ }, []);
968
+ return useMemo(() => new RouterHookApi(pages, ctx.state, layer, ctx.alepha.isBrowser() ? ctx.alepha.get(ReactBrowserProvider) : void 0), [layer]);
969
+ };
970
+
971
+ //#endregion
972
+ //#region src/components/Link.tsx
973
+ const Link = (props) => {
974
+ React.useContext(RouterContext);
975
+ const router = useRouter();
976
+ const to = typeof props.to === "string" ? props.to : props.to[OPTIONS].path;
977
+ if (!to) return null;
978
+ const can = typeof props.to === "string" ? void 0 : props.to[OPTIONS].can;
979
+ if (can && !can()) return null;
980
+ const name = typeof props.to === "string" ? void 0 : props.to[OPTIONS].name;
981
+ const anchorProps = {
982
+ ...props,
983
+ to: void 0
984
+ };
985
+ return /* @__PURE__ */ jsx("a", {
986
+ ...router.anchor(to),
987
+ ...anchorProps,
988
+ children: props.children ?? name
989
+ });
990
+ };
991
+ var Link_default = Link;
992
+
993
+ //#endregion
994
+ //#region src/hooks/useActive.ts
995
+ const useActive = (path) => {
996
+ const router = useRouter();
997
+ const ctx = useContext(RouterContext);
998
+ const layer = useContext(RouterLayerContext);
999
+ if (!ctx || !layer) throw new Error("useRouter must be used within a RouterProvider");
1000
+ let name;
1001
+ if (typeof path === "object" && path.options.name) name = path.options.name;
1002
+ const [current, setCurrent] = useState(ctx.state.pathname);
1003
+ const href = useMemo(() => router.createHref(path, layer), [path, layer]);
1004
+ const [isPending, setPending] = useState(false);
1005
+ const isActive = current === href;
1006
+ useRouterEvents({ onEnd: ({ state }) => setCurrent(state.pathname) });
1007
+ return {
1008
+ name,
1009
+ isPending,
1010
+ isActive,
1011
+ anchorProps: {
1012
+ href,
1013
+ onClick: (ev) => {
1014
+ ev.stopPropagation();
1015
+ ev.preventDefault();
1016
+ if (isActive) return;
1017
+ if (isPending) return;
1018
+ setPending(true);
1019
+ router.go(href).then(() => {
1020
+ setPending(false);
1021
+ });
1022
+ }
1023
+ }
1024
+ };
1025
+ };
1026
+
1027
+ //#endregion
1028
+ //#region src/hooks/useInject.ts
1029
+ const useInject = (clazz) => {
1030
+ const ctx = useContext(RouterContext);
1031
+ if (!ctx) throw new Error("useRouter must be used within a <RouterProvider>");
1032
+ return useMemo(() => ctx.alepha.get(clazz), []);
1033
+ };
1034
+
1035
+ //#endregion
1036
+ //#region src/hooks/useClient.ts
1037
+ const useClient = (_scope) => {
1038
+ return useInject(HttpClient).of();
1039
+ };
1040
+
1041
+ //#endregion
1042
+ //#region src/hooks/useQueryParams.ts
1043
+ const useQueryParams = (schema, options = {}) => {
1044
+ const ctx = useContext(RouterContext);
1045
+ if (!ctx) throw new Error("useQueryParams must be used within a RouterProvider");
1046
+ const key = options.key ?? "q";
1047
+ const router = useRouter();
1048
+ const querystring = router.query[key];
1049
+ const [queryParams, setQueryParams] = useState(decode(ctx.alepha, schema, router.query[key]));
1050
+ useEffect(() => {
1051
+ setQueryParams(decode(ctx.alepha, schema, querystring));
1052
+ }, [querystring]);
1053
+ return [queryParams, (queryParams$1) => {
1054
+ setQueryParams(queryParams$1);
1055
+ router.setQueryParams((data) => {
1056
+ return {
1057
+ ...data,
1058
+ [key]: encode(ctx.alepha, schema, queryParams$1)
1059
+ };
1060
+ });
1061
+ }];
1062
+ };
1063
+ const encode = (alepha, schema, data) => {
1064
+ return btoa(JSON.stringify(alepha.parse(schema, data)));
1065
+ };
1066
+ const decode = (alepha, schema, data) => {
1067
+ try {
1068
+ return alepha.parse(schema, JSON.parse(atob(decodeURIComponent(data))));
1069
+ } catch (_error) {
1070
+ return {};
1071
+ }
1072
+ };
1073
+
1074
+ //#endregion
1075
+ //#region src/hooks/useRouterState.ts
1076
+ const useRouterState = () => {
1077
+ const ctx = useContext(RouterContext);
1078
+ const layer = useContext(RouterLayerContext);
1079
+ if (!ctx || !layer) throw new Error("useRouter must be used within a RouterProvider");
1080
+ const [state, setState] = useState(ctx.state);
1081
+ useRouterEvents({ onEnd: ({ state: state$1 }) => setState({ ...state$1 }) });
1082
+ return state;
1083
+ };
1084
+
1085
+ //#endregion
1086
+ //#region src/index.browser.ts
1087
+ var AlephaReact = class {
1088
+ name = "alepha.react";
1089
+ $services = (alepha) => alepha.with(PageDescriptorProvider).with(ReactBrowserProvider).with(BrowserRouterProvider).with(ReactBrowserRenderer);
1090
+ };
51
1091
  __bind($page, AlephaReact);
52
1092
 
53
- export { $page, AlephaReact, BrowserRouterProvider, PageDescriptorProvider, ReactBrowserProvider };
1093
+ //#endregion
1094
+ export { $page, AlephaReact, BrowserRouterProvider, ClientOnly_default as ClientOnly, ErrorBoundary_default as ErrorBoundary, Link_default as Link, NestedView_default as NestedView, PageDescriptorProvider, ReactBrowserProvider, RedirectionError, RouterContext, RouterHookApi, RouterLayerContext, isPageRoute, useActive, useAlepha, useClient, useInject, useQueryParams, useRouter, useRouterEvents, useRouterState };
1095
+ //# sourceMappingURL=index.browser.js.map