@alepha/react 0.7.5 → 0.7.7

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.
package/dist/index.cjs CHANGED
@@ -1,384 +1,1297 @@
1
- 'use strict';
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
2
22
 
3
- var core = require('@alepha/core');
4
- var server = require('@alepha/server');
5
- var serverCache = require('@alepha/server-cache');
6
- var useRouterState = require('./useRouterState-BTmuHxkM.cjs');
7
- var node_fs = require('node:fs');
8
- var node_path = require('node:path');
9
- var serverStatic = require('@alepha/server-static');
10
- var server$1 = require('react-dom/server');
11
- require('react/jsx-runtime');
12
- require('react');
13
- require('@alepha/router');
23
+ //#endregion
24
+ const __alepha_core = __toESM(require("@alepha/core"));
25
+ const __alepha_server = __toESM(require("@alepha/server"));
26
+ const __alepha_server_cache = __toESM(require("@alepha/server-cache"));
27
+ const react = __toESM(require("react"));
28
+ const react_jsx_runtime = __toESM(require("react/jsx-runtime"));
29
+ const node_fs = __toESM(require("node:fs"));
30
+ const node_path = __toESM(require("node:path"));
31
+ const __alepha_server_links = __toESM(require("@alepha/server-links"));
32
+ const __alepha_server_static = __toESM(require("@alepha/server-static"));
33
+ const react_dom_server = __toESM(require("react-dom/server"));
34
+ const __alepha_router = __toESM(require("@alepha/router"));
14
35
 
15
- class ServerHeadProvider {
16
- renderHead(template, head) {
17
- let result = template;
18
- const htmlAttributes = head.htmlAttributes;
19
- if (htmlAttributes) {
20
- result = result.replace(
21
- /<html([^>]*)>/i,
22
- (_, existingAttrs) => `<html${this.mergeAttributes(existingAttrs, htmlAttributes)}>`
23
- );
24
- }
25
- const bodyAttributes = head.bodyAttributes;
26
- if (bodyAttributes) {
27
- result = result.replace(
28
- /<body([^>]*)>/i,
29
- (_, existingAttrs) => `<body${this.mergeAttributes(existingAttrs, bodyAttributes)}>`
30
- );
31
- }
32
- let headContent = "";
33
- const title = head.title;
34
- if (title) {
35
- if (template.includes("<title>")) {
36
- result = result.replace(
37
- /<title>(.*?)<\/title>/i,
38
- () => `<title>${this.escapeHtml(title)}</title>`
39
- );
40
- } else {
41
- headContent += `<title>${this.escapeHtml(title)}</title>
42
- `;
43
- }
44
- }
45
- if (head.meta) {
46
- for (const meta of head.meta) {
47
- headContent += `<meta name="${this.escapeHtml(meta.name)}" content="${this.escapeHtml(meta.content)}">
48
- `;
49
- }
50
- }
51
- result = result.replace(
52
- /<head([^>]*)>(.*?)<\/head>/is,
53
- (_, existingAttrs, existingHead) => `<head${existingAttrs}>${existingHead}${headContent}</head>`
54
- );
55
- return result.trim();
56
- }
57
- mergeAttributes(existing, attrs) {
58
- const existingAttrs = this.parseAttributes(existing);
59
- const merged = { ...existingAttrs, ...attrs };
60
- return Object.entries(merged).map(([k, v]) => ` ${k}="${this.escapeHtml(v)}"`).join("");
61
- }
62
- parseAttributes(attrStr) {
63
- const attrs = {};
64
- const attrRegex = /([^\s=]+)(?:="([^"]*)")?/g;
65
- let match = attrRegex.exec(attrStr);
66
- while (match) {
67
- attrs[match[1]] = match[2] ?? "";
68
- match = attrRegex.exec(attrStr);
69
- }
70
- return attrs;
71
- }
72
- escapeHtml(str) {
73
- return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
74
- }
36
+ //#region src/descriptors/$page.ts
37
+ const KEY = "PAGE";
38
+ /**
39
+ * Main descriptor for defining a React route in the application.
40
+ */
41
+ const $page = (options) => {
42
+ (0, __alepha_core.__descriptor)(KEY);
43
+ if (options.children) for (const child of options.children) child[__alepha_core.OPTIONS].parent = { [__alepha_core.OPTIONS]: options };
44
+ if (options.parent) {
45
+ options.parent[__alepha_core.OPTIONS].children ??= [];
46
+ options.parent[__alepha_core.OPTIONS].children.push({ [__alepha_core.OPTIONS]: options });
47
+ }
48
+ return {
49
+ [__alepha_core.KIND]: KEY,
50
+ [__alepha_core.OPTIONS]: options,
51
+ render: () => {
52
+ throw new __alepha_core.NotImplementedError(KEY);
53
+ }
54
+ };
55
+ };
56
+ $page[__alepha_core.KIND] = KEY;
57
+
58
+ //#endregion
59
+ //#region src/components/ClientOnly.tsx
60
+ /**
61
+ * A small utility component that renders its children only on the client side.
62
+ *
63
+ * Optionally, you can provide a fallback React node that will be rendered.
64
+ *
65
+ * You should use this component when
66
+ * - you have code that relies on browser-specific APIs
67
+ * - you want to avoid server-side rendering for a specific part of your application
68
+ * - you want to prevent pre-rendering of a component
69
+ */
70
+ const ClientOnly = (props) => {
71
+ const [mounted, setMounted] = (0, react.useState)(false);
72
+ (0, react.useEffect)(() => setMounted(true), []);
73
+ if (props.disabled) return props.children;
74
+ return mounted ? props.children : props.fallback;
75
+ };
76
+ var ClientOnly_default = ClientOnly;
77
+
78
+ //#endregion
79
+ //#region src/contexts/RouterContext.ts
80
+ const RouterContext = (0, react.createContext)(void 0);
81
+
82
+ //#endregion
83
+ //#region src/hooks/useAlepha.ts
84
+ const useAlepha = () => {
85
+ const routerContext = (0, react.useContext)(RouterContext);
86
+ if (!routerContext) throw new Error("useAlepha must be used within a RouterProvider");
87
+ return routerContext.alepha;
88
+ };
89
+
90
+ //#endregion
91
+ //#region src/components/ErrorViewer.tsx
92
+ const ErrorViewer = ({ error }) => {
93
+ const [expanded, setExpanded] = (0, react.useState)(false);
94
+ const isProduction = useAlepha().isProduction();
95
+ if (isProduction) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ErrorViewerProduction, {});
96
+ const stackLines = error.stack?.split("\n") ?? [];
97
+ const previewLines = stackLines.slice(0, 5);
98
+ const hiddenLineCount = stackLines.length - previewLines.length;
99
+ const copyToClipboard = (text) => {
100
+ navigator.clipboard.writeText(text).catch((err) => {
101
+ console.error("Clipboard error:", err);
102
+ });
103
+ };
104
+ const styles = {
105
+ container: {
106
+ padding: "24px",
107
+ backgroundColor: "#FEF2F2",
108
+ color: "#7F1D1D",
109
+ border: "1px solid #FECACA",
110
+ borderRadius: "16px",
111
+ boxShadow: "0 8px 24px rgba(0,0,0,0.05)",
112
+ fontFamily: "monospace",
113
+ maxWidth: "768px",
114
+ margin: "40px auto"
115
+ },
116
+ heading: {
117
+ fontSize: "20px",
118
+ fontWeight: "bold",
119
+ marginBottom: "4px"
120
+ },
121
+ name: {
122
+ fontSize: "16px",
123
+ fontWeight: 600
124
+ },
125
+ message: {
126
+ fontSize: "14px",
127
+ marginBottom: "16px"
128
+ },
129
+ sectionHeader: {
130
+ display: "flex",
131
+ justifyContent: "space-between",
132
+ alignItems: "center",
133
+ fontSize: "12px",
134
+ marginBottom: "4px",
135
+ color: "#991B1B"
136
+ },
137
+ copyButton: {
138
+ fontSize: "12px",
139
+ color: "#DC2626",
140
+ background: "none",
141
+ border: "none",
142
+ cursor: "pointer",
143
+ textDecoration: "underline"
144
+ },
145
+ stackContainer: {
146
+ backgroundColor: "#FEE2E2",
147
+ padding: "12px",
148
+ borderRadius: "8px",
149
+ fontSize: "13px",
150
+ lineHeight: "1.4",
151
+ overflowX: "auto",
152
+ whiteSpace: "pre-wrap"
153
+ },
154
+ expandLine: {
155
+ color: "#F87171",
156
+ cursor: "pointer",
157
+ marginTop: "8px"
158
+ }
159
+ };
160
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
161
+ style: styles.container,
162
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { children: [
163
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
164
+ style: styles.heading,
165
+ children: "🔥 Error"
166
+ }),
167
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
168
+ style: styles.name,
169
+ children: error.name
170
+ }),
171
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
172
+ style: styles.message,
173
+ children: error.message
174
+ })
175
+ ] }), stackLines.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
176
+ style: styles.sectionHeader,
177
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: "Stack trace" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
178
+ onClick: () => copyToClipboard(error.stack),
179
+ style: styles.copyButton,
180
+ children: "Copy all"
181
+ })]
182
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("pre", {
183
+ style: styles.stackContainer,
184
+ children: [(expanded ? stackLines : previewLines).map((line, i) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { children: line }, i)), !expanded && hiddenLineCount > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
185
+ style: styles.expandLine,
186
+ onClick: () => setExpanded(true),
187
+ children: [
188
+ "+ ",
189
+ hiddenLineCount,
190
+ " more lines..."
191
+ ]
192
+ })]
193
+ })] })]
194
+ });
195
+ };
196
+ var ErrorViewer_default = ErrorViewer;
197
+ const ErrorViewerProduction = () => {
198
+ const styles = {
199
+ container: {
200
+ padding: "24px",
201
+ backgroundColor: "#FEF2F2",
202
+ color: "#7F1D1D",
203
+ border: "1px solid #FECACA",
204
+ borderRadius: "16px",
205
+ boxShadow: "0 8px 24px rgba(0,0,0,0.05)",
206
+ fontFamily: "monospace",
207
+ maxWidth: "768px",
208
+ margin: "40px auto",
209
+ textAlign: "center"
210
+ },
211
+ heading: {
212
+ fontSize: "20px",
213
+ fontWeight: "bold",
214
+ marginBottom: "8px"
215
+ },
216
+ name: {
217
+ fontSize: "16px",
218
+ fontWeight: 600,
219
+ marginBottom: "4px"
220
+ },
221
+ message: {
222
+ fontSize: "14px",
223
+ opacity: .85
224
+ }
225
+ };
226
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
227
+ style: styles.container,
228
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
229
+ style: styles.heading,
230
+ children: "🚨 An error occurred"
231
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
232
+ style: styles.message,
233
+ children: "Something went wrong. Please try again later."
234
+ })]
235
+ });
236
+ };
237
+
238
+ //#endregion
239
+ //#region src/contexts/RouterLayerContext.ts
240
+ const RouterLayerContext = (0, react.createContext)(void 0);
241
+
242
+ //#endregion
243
+ //#region src/hooks/useRouterEvents.ts
244
+ const useRouterEvents = (opts = {}, deps = []) => {
245
+ const ctx = (0, react.useContext)(RouterContext);
246
+ if (!ctx) throw new Error("useRouter must be used within a RouterProvider");
247
+ (0, react.useEffect)(() => {
248
+ if (!ctx.alepha.isBrowser()) return;
249
+ const subs = [];
250
+ const onBegin = opts.onBegin;
251
+ const onEnd = opts.onEnd;
252
+ const onError = opts.onError;
253
+ if (onBegin) subs.push(ctx.alepha.on("react:transition:begin", { callback: onBegin }));
254
+ if (onEnd) subs.push(ctx.alepha.on("react:transition:end", { callback: onEnd }));
255
+ if (onError) subs.push(ctx.alepha.on("react:transition:error", { callback: onError }));
256
+ return () => {
257
+ for (const sub of subs) sub();
258
+ };
259
+ }, deps);
260
+ };
261
+
262
+ //#endregion
263
+ //#region src/components/ErrorBoundary.tsx
264
+ /**
265
+ * A reusable error boundary for catching rendering errors
266
+ * in any part of the React component tree.
267
+ */
268
+ var ErrorBoundary = class extends react.default.Component {
269
+ constructor(props) {
270
+ super(props);
271
+ this.state = {};
272
+ }
273
+ /**
274
+ * Update state so the next render shows the fallback UI.
275
+ */
276
+ static getDerivedStateFromError(error) {
277
+ return { error };
278
+ }
279
+ /**
280
+ * Lifecycle method called when an error is caught.
281
+ * You can log the error or perform side effects here.
282
+ */
283
+ componentDidCatch(error, info) {
284
+ if (this.props.onError) this.props.onError(error, info);
285
+ }
286
+ render() {
287
+ if (this.state.error) return this.props.fallback(this.state.error);
288
+ return this.props.children;
289
+ }
290
+ };
291
+ var ErrorBoundary_default = ErrorBoundary;
292
+
293
+ //#endregion
294
+ //#region src/components/NestedView.tsx
295
+ /**
296
+ * A component that renders the current view of the nested router layer.
297
+ *
298
+ * To be simple, it renders the `element` of the current child page of a parent page.
299
+ *
300
+ * @example
301
+ * ```tsx
302
+ * import { NestedView } from "@alepha/react";
303
+ *
304
+ * class App {
305
+ * parent = $page({
306
+ * component: () => <NestedView />,
307
+ * });
308
+ *
309
+ * child = $page({
310
+ * parent: this.root,
311
+ * component: () => <div>Child Page</div>,
312
+ * });
313
+ * }
314
+ * ```
315
+ */
316
+ const NestedView = (props) => {
317
+ const app = (0, react.useContext)(RouterContext);
318
+ const layer = (0, react.useContext)(RouterLayerContext);
319
+ const index = layer?.index ?? 0;
320
+ const [view, setView] = (0, react.useState)(app?.state.layers[index]?.element);
321
+ useRouterEvents({ onEnd: ({ state }) => {
322
+ setView(state.layers[index]?.element);
323
+ } }, [app]);
324
+ if (!app) throw new Error("NestedView must be used within a RouterContext.");
325
+ const element = view ?? props.children ?? null;
326
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ErrorBoundary_default, {
327
+ fallback: app.context.onError,
328
+ children: element
329
+ });
330
+ };
331
+ var NestedView_default = NestedView;
332
+
333
+ //#endregion
334
+ //#region src/components/NotFound.tsx
335
+ function NotFoundPage() {
336
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
337
+ style: {
338
+ height: "100vh",
339
+ display: "flex",
340
+ flexDirection: "column",
341
+ justifyContent: "center",
342
+ alignItems: "center",
343
+ textAlign: "center",
344
+ fontFamily: "sans-serif",
345
+ padding: "1rem"
346
+ },
347
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("h1", {
348
+ style: {
349
+ fontSize: "1rem",
350
+ marginBottom: "0.5rem"
351
+ },
352
+ children: "This page does not exist"
353
+ })
354
+ });
75
355
  }
76
356
 
77
- const envSchema = core.t.object({
78
- REACT_SERVER_DIST: core.t.string({ default: "public" }),
79
- REACT_SERVER_PREFIX: core.t.string({ default: "" }),
80
- REACT_SSR_ENABLED: core.t.optional(core.t.boolean()),
81
- REACT_ROOT_ID: core.t.string({ default: "root" })
357
+ //#endregion
358
+ //#region src/errors/RedirectionError.ts
359
+ var RedirectionError = class extends Error {
360
+ page;
361
+ constructor(page) {
362
+ super("Redirection");
363
+ this.page = page;
364
+ }
365
+ };
366
+
367
+ //#endregion
368
+ //#region src/providers/PageDescriptorProvider.ts
369
+ const envSchema$1 = __alepha_core.t.object({ REACT_STRICT_MODE: __alepha_core.t.boolean({ default: true }) });
370
+ var PageDescriptorProvider = class {
371
+ log = (0, __alepha_core.$logger)();
372
+ env = (0, __alepha_core.$inject)(envSchema$1);
373
+ alepha = (0, __alepha_core.$inject)(__alepha_core.Alepha);
374
+ pages = [];
375
+ getPages() {
376
+ return this.pages;
377
+ }
378
+ page(name) {
379
+ for (const page of this.pages) if (page.name === name) return page;
380
+ throw new Error(`Page ${name} not found`);
381
+ }
382
+ url(name, options = {}) {
383
+ const page = this.page(name);
384
+ if (!page) throw new Error(`Page ${name} not found`);
385
+ let url = page.path ?? "";
386
+ let parent = page.parent;
387
+ while (parent) {
388
+ url = `${parent.path ?? ""}/${url}`;
389
+ parent = parent.parent;
390
+ }
391
+ url = this.compile(url, options.params ?? {});
392
+ return new URL(url.replace(/\/\/+/g, "/") || "/", options.base ?? `http://localhost`);
393
+ }
394
+ root(state, context) {
395
+ const root = (0, react.createElement)(RouterContext.Provider, { value: {
396
+ alepha: this.alepha,
397
+ state,
398
+ context
399
+ } }, (0, react.createElement)(NestedView_default, {}, state.layers[0]?.element));
400
+ if (this.env.REACT_STRICT_MODE) return (0, react.createElement)(react.StrictMode, {}, root);
401
+ return root;
402
+ }
403
+ async createLayers(route, request) {
404
+ const { pathname, search } = request.url;
405
+ const layers = [];
406
+ let context = {};
407
+ const stack = [{ route }];
408
+ request.onError = (error) => this.renderError(error);
409
+ let parent = route.parent;
410
+ while (parent) {
411
+ stack.unshift({ route: parent });
412
+ parent = parent.parent;
413
+ }
414
+ let forceRefresh = false;
415
+ for (let i = 0; i < stack.length; i++) {
416
+ const it = stack[i];
417
+ const route$1 = it.route;
418
+ const config = {};
419
+ try {
420
+ config.query = route$1.schema?.query ? this.alepha.parse(route$1.schema.query, request.query) : request.query;
421
+ } catch (e) {
422
+ it.error = e;
423
+ break;
424
+ }
425
+ try {
426
+ config.params = route$1.schema?.params ? this.alepha.parse(route$1.schema.params, request.params) : request.params;
427
+ } catch (e) {
428
+ it.error = e;
429
+ break;
430
+ }
431
+ it.config = { ...config };
432
+ if (!route$1.resolve) continue;
433
+ const previous = request.previous;
434
+ if (previous?.[i] && !forceRefresh && previous[i].name === route$1.name) {
435
+ const url = (str) => str ? str.replace(/\/\/+/g, "/") : "/";
436
+ const prev = JSON.stringify({
437
+ part: url(previous[i].part),
438
+ params: previous[i].config?.params ?? {}
439
+ });
440
+ const curr = JSON.stringify({
441
+ part: url(route$1.path),
442
+ params: config.params ?? {}
443
+ });
444
+ if (prev === curr) {
445
+ it.props = previous[i].props;
446
+ it.error = previous[i].error;
447
+ context = {
448
+ ...context,
449
+ ...it.props
450
+ };
451
+ continue;
452
+ }
453
+ forceRefresh = true;
454
+ }
455
+ try {
456
+ const props = await route$1.resolve?.({
457
+ ...request,
458
+ ...config,
459
+ ...context
460
+ }) ?? {};
461
+ it.props = { ...props };
462
+ context = {
463
+ ...context,
464
+ ...props
465
+ };
466
+ } catch (e) {
467
+ if (e instanceof RedirectionError) return {
468
+ layers: [],
469
+ redirect: typeof e.page === "string" ? e.page : this.href(e.page),
470
+ pathname,
471
+ search
472
+ };
473
+ this.log.error(e);
474
+ it.error = e;
475
+ break;
476
+ }
477
+ }
478
+ let acc = "";
479
+ for (let i = 0; i < stack.length; i++) {
480
+ const it = stack[i];
481
+ const props = it.props ?? {};
482
+ const params = { ...it.config?.params };
483
+ for (const key of Object.keys(params)) params[key] = String(params[key]);
484
+ acc += "/";
485
+ acc += it.route.path ? this.compile(it.route.path, params) : "";
486
+ const path = acc.replace(/\/+/, "/");
487
+ const localErrorHandler = this.getErrorHandler(it.route);
488
+ if (localErrorHandler) request.onError = localErrorHandler;
489
+ if (it.error) {
490
+ let element$1 = await request.onError(it.error);
491
+ if (element$1 === null) element$1 = this.renderError(it.error);
492
+ layers.push({
493
+ props,
494
+ error: it.error,
495
+ name: it.route.name,
496
+ part: it.route.path,
497
+ config: it.config,
498
+ element: this.renderView(i + 1, path, element$1, it.route),
499
+ index: i + 1,
500
+ path,
501
+ route
502
+ });
503
+ break;
504
+ }
505
+ const element = await this.createElement(it.route, {
506
+ ...props,
507
+ ...context
508
+ });
509
+ layers.push({
510
+ name: it.route.name,
511
+ props,
512
+ part: it.route.path,
513
+ config: it.config,
514
+ element: this.renderView(i + 1, path, element, it.route),
515
+ index: i + 1,
516
+ path,
517
+ route
518
+ });
519
+ }
520
+ return {
521
+ layers,
522
+ pathname,
523
+ search
524
+ };
525
+ }
526
+ getErrorHandler(route) {
527
+ if (route.errorHandler) return route.errorHandler;
528
+ let parent = route.parent;
529
+ while (parent) {
530
+ if (parent.errorHandler) return parent.errorHandler;
531
+ parent = parent.parent;
532
+ }
533
+ }
534
+ async createElement(page, props) {
535
+ if (page.lazy) {
536
+ const component = await page.lazy();
537
+ return (0, react.createElement)(component.default, props);
538
+ }
539
+ if (page.component) return (0, react.createElement)(page.component, props);
540
+ return void 0;
541
+ }
542
+ renderError(error) {
543
+ return (0, react.createElement)(ErrorViewer_default, { error });
544
+ }
545
+ renderEmptyView() {
546
+ return (0, react.createElement)(NestedView_default, {});
547
+ }
548
+ href(page, params = {}) {
549
+ const found = this.pages.find((it) => it.name === page.options.name);
550
+ if (!found) throw new Error(`Page ${page.options.name} not found`);
551
+ let url = found.path ?? "";
552
+ let parent = found.parent;
553
+ while (parent) {
554
+ url = `${parent.path ?? ""}/${url}`;
555
+ parent = parent.parent;
556
+ }
557
+ url = this.compile(url, params);
558
+ return url.replace(/\/\/+/g, "/") || "/";
559
+ }
560
+ compile(path, params = {}) {
561
+ for (const [key, value] of Object.entries(params)) path = path.replace(`:${key}`, value);
562
+ return path;
563
+ }
564
+ renderView(index, path, view, page) {
565
+ view ??= this.renderEmptyView();
566
+ const element = page.client ? (0, react.createElement)(ClientOnly_default, typeof page.client === "object" ? page.client : {}, view) : view;
567
+ return (0, react.createElement)(RouterLayerContext.Provider, { value: {
568
+ index,
569
+ path
570
+ } }, element);
571
+ }
572
+ configure = (0, __alepha_core.$hook)({
573
+ name: "configure",
574
+ handler: () => {
575
+ let hasNotFoundHandler = false;
576
+ const pages = this.alepha.getDescriptorValues($page);
577
+ for (const { value, key } of pages) value[__alepha_core.OPTIONS].name ??= key;
578
+ for (const { value } of pages) {
579
+ if (value[__alepha_core.OPTIONS].parent) continue;
580
+ if (value[__alepha_core.OPTIONS].path === "/*") hasNotFoundHandler = true;
581
+ this.add(this.map(pages, value));
582
+ }
583
+ if (!hasNotFoundHandler && pages.length > 0) this.add({
584
+ path: "/*",
585
+ name: "notFound",
586
+ cache: true,
587
+ component: NotFoundPage,
588
+ afterHandler: ({ reply }) => {
589
+ reply.status = 404;
590
+ }
591
+ });
592
+ }
593
+ });
594
+ map(pages, target) {
595
+ const children = target[__alepha_core.OPTIONS].children ?? [];
596
+ return {
597
+ ...target[__alepha_core.OPTIONS],
598
+ parent: void 0,
599
+ children: children.map((it) => this.map(pages, it))
600
+ };
601
+ }
602
+ add(entry) {
603
+ if (this.alepha.isReady()) throw new Error("Router is already initialized");
604
+ entry.name ??= this.nextId();
605
+ const page = entry;
606
+ page.match = this.createMatch(page);
607
+ this.pages.push(page);
608
+ if (page.children) for (const child of page.children) {
609
+ child.parent = page;
610
+ this.add(child);
611
+ }
612
+ }
613
+ createMatch(page) {
614
+ let url = page.path ?? "/";
615
+ let target = page.parent;
616
+ while (target) {
617
+ url = `${target.path ?? ""}/${url}`;
618
+ target = target.parent;
619
+ }
620
+ let path = url.replace(/\/\/+/g, "/");
621
+ if (path.endsWith("/") && path !== "/") path = path.slice(0, -1);
622
+ return path;
623
+ }
624
+ _next = 0;
625
+ nextId() {
626
+ this._next += 1;
627
+ return `P${this._next}`;
628
+ }
629
+ };
630
+ const isPageRoute = (it) => {
631
+ return it && typeof it === "object" && typeof it.path === "string" && typeof it.page === "object";
632
+ };
633
+
634
+ //#endregion
635
+ //#region src/providers/ReactServerProvider.ts
636
+ const envSchema = __alepha_core.t.object({
637
+ REACT_SERVER_DIST: __alepha_core.t.string({ default: "public" }),
638
+ REACT_SERVER_PREFIX: __alepha_core.t.string({ default: "" }),
639
+ REACT_SSR_ENABLED: __alepha_core.t.optional(__alepha_core.t.boolean()),
640
+ REACT_ROOT_ID: __alepha_core.t.string({ default: "root" })
82
641
  });
83
- class ReactServerProvider {
84
- log = core.$logger();
85
- alepha = core.$inject(core.Alepha);
86
- pageDescriptorProvider = core.$inject(useRouterState.PageDescriptorProvider);
87
- serverStaticProvider = core.$inject(serverStatic.ServerStaticProvider);
88
- serverRouterProvider = core.$inject(server.ServerRouterProvider);
89
- headProvider = core.$inject(ServerHeadProvider);
90
- serverTimingProvider = core.$inject(server.ServerTimingProvider);
91
- env = core.$inject(envSchema);
92
- ROOT_DIV_REGEX = new RegExp(
93
- `<div([^>]*)\\s+id=["']${this.env.REACT_ROOT_ID}["']([^>]*)>(.*?)<\\/div>`,
94
- "is"
95
- );
96
- onConfigure = core.$hook({
97
- name: "configure",
98
- handler: async () => {
99
- const pages = this.alepha.getDescriptorValues(useRouterState.$page);
100
- const ssrEnabled = pages.length > 0 && this.env.REACT_SSR_ENABLED !== false;
101
- this.alepha.state("ReactServerProvider.ssr", ssrEnabled);
102
- for (const { key, instance, value } of pages) {
103
- const name = value[core.OPTIONS].name ?? key;
104
- instance[key].prerender = this.createRenderFunction(name, true);
105
- if (this.alepha.isTest()) {
106
- instance[key].render = this.createRenderFunction(name);
107
- }
108
- }
109
- if (this.alepha.isServerless() === "vite") {
110
- await this.configureVite(ssrEnabled);
111
- return;
112
- }
113
- let root = "";
114
- if (!this.alepha.isServerless()) {
115
- root = this.getPublicDirectory();
116
- if (!root) {
117
- this.log.warn(
118
- "Missing static files, static file server will be disabled"
119
- );
120
- } else {
121
- this.log.debug(`Using static files from: ${root}`);
122
- await this.configureStaticServer(root);
123
- }
124
- }
125
- if (ssrEnabled) {
126
- await this.registerPages(async () => this.template);
127
- this.log.info("SSR OK");
128
- return;
129
- }
130
- this.log.info("SSR is disabled, use History API fallback");
131
- await this.serverRouterProvider.route({
132
- path: "*",
133
- handler: async ({ url, reply }) => {
134
- if (url.pathname.includes(".")) {
135
- reply.headers["content-type"] = "text/plain";
136
- reply.body = "Not Found";
137
- reply.status = 404;
138
- return;
139
- }
140
- reply.headers["content-type"] = "text/html";
141
- return this.template;
142
- }
143
- });
144
- }
145
- });
146
- get template() {
147
- return this.alepha.state("ReactServerProvider.template");
148
- }
149
- async registerPages(templateLoader) {
150
- for (const page of this.pageDescriptorProvider.getPages()) {
151
- if (page.children?.length) {
152
- continue;
153
- }
154
- this.log.debug(`+ ${page.match} -> ${page.name}`);
155
- await this.serverRouterProvider.route({
156
- ...page,
157
- schema: void 0,
158
- // schema is handled by the page descriptor provider for now (shared by browser and server)
159
- method: "GET",
160
- path: page.match,
161
- handler: this.createHandler(page, templateLoader)
162
- });
163
- }
164
- }
165
- getPublicDirectory() {
166
- const maybe = [
167
- node_path.join(process.cwd(), `dist/${this.env.REACT_SERVER_DIST}`),
168
- node_path.join(process.cwd(), this.env.REACT_SERVER_DIST)
169
- ];
170
- for (const it of maybe) {
171
- if (node_fs.existsSync(it)) {
172
- return it;
173
- }
174
- }
175
- return "";
176
- }
177
- async configureStaticServer(root) {
178
- await this.serverStaticProvider.serve({
179
- root,
180
- path: this.env.REACT_SERVER_PREFIX
181
- });
182
- }
183
- async configureVite(ssrEnabled) {
184
- if (!ssrEnabled) {
185
- return;
186
- }
187
- this.log.info("SSR (vite) OK");
188
- const url = `http://${process.env.SERVER_HOST}:${process.env.SERVER_PORT}`;
189
- await this.registerPages(
190
- () => fetch(`${url}/index.html`).then((it) => it.text()).catch(() => void 0)
191
- );
192
- }
193
- /**
194
- * For testing purposes, creates a render function that can be used.
195
- */
196
- createRenderFunction(name, withIndex = false) {
197
- return async (options = {}) => {
198
- const page = this.pageDescriptorProvider.page(name);
199
- const url = new URL(this.pageDescriptorProvider.url(name, options));
200
- const context = {
201
- url,
202
- params: options.params ?? {},
203
- query: options.query ?? {},
204
- head: {},
205
- onError: () => null
206
- };
207
- const state = await this.pageDescriptorProvider.createLayers(
208
- page,
209
- context
210
- );
211
- if (!withIndex) {
212
- return {
213
- context,
214
- html: server$1.renderToString(
215
- this.pageDescriptorProvider.root(state, context)
216
- )
217
- };
218
- }
219
- return {
220
- context,
221
- html: this.renderToHtml(this.template ?? "", state, context)
222
- };
223
- };
224
- }
225
- createHandler(page, templateLoader) {
226
- return async (serverRequest) => {
227
- const { url, reply, query, params } = serverRequest;
228
- const template = await templateLoader();
229
- if (!template) {
230
- throw new Error("Template not found");
231
- }
232
- const context = {
233
- url,
234
- params,
235
- query,
236
- // plugins
237
- head: {},
238
- onError: () => null
239
- };
240
- if (this.alepha.has(server.ServerLinksProvider)) {
241
- const srv = this.alepha.get(server.ServerLinksProvider);
242
- const schema = server.apiLinksResponseSchema;
243
- context.links = this.alepha.parse(
244
- schema,
245
- await srv.getLinks({
246
- user: serverRequest.user,
247
- authorization: serverRequest.headers.authorization
248
- })
249
- );
250
- this.alepha.context.set("links", context.links);
251
- }
252
- let target = page;
253
- while (target) {
254
- if (page.can && !page.can()) {
255
- reply.status = 403;
256
- reply.headers["content-type"] = "text/plain";
257
- return "Forbidden";
258
- }
259
- target = target.parent;
260
- }
261
- await this.alepha.emit(
262
- "react:server:render",
263
- {
264
- request: serverRequest,
265
- pageRequest: context
266
- },
267
- {
268
- log: false
269
- }
270
- );
271
- this.serverTimingProvider.beginTiming("createLayers");
272
- const state = await this.pageDescriptorProvider.createLayers(
273
- page,
274
- context
275
- );
276
- this.serverTimingProvider.endTiming("createLayers");
277
- if (state.redirect) {
278
- return reply.redirect(state.redirect);
279
- }
280
- reply.headers["content-type"] = "text/html";
281
- reply.headers["cache-control"] = "no-store, no-cache, must-revalidate, proxy-revalidate";
282
- reply.headers.pragma = "no-cache";
283
- reply.headers.expires = "0";
284
- if (page.cache && serverRequest.user) {
285
- delete context.links;
286
- }
287
- const html = this.renderToHtml(template, state, context);
288
- page.afterHandler?.(serverRequest);
289
- return html;
290
- };
291
- }
292
- renderToHtml(template, state, context) {
293
- const element = this.pageDescriptorProvider.root(state, context);
294
- this.serverTimingProvider.beginTiming("renderToString");
295
- let app = "";
296
- try {
297
- app = server$1.renderToString(element);
298
- } catch (error) {
299
- this.log.error("Error during SSR", error);
300
- app = server$1.renderToString(context.onError(error));
301
- }
302
- this.serverTimingProvider.endTiming("renderToString");
303
- const hydrationData = {
304
- links: context.links,
305
- layers: state.layers.map((it) => ({
306
- ...it,
307
- error: it.error ? {
308
- ...it.error,
309
- name: it.error.name,
310
- message: it.error.message,
311
- stack: it.error.stack
312
- // TODO: Hide stack in production ?
313
- } : void 0,
314
- index: void 0,
315
- path: void 0,
316
- element: void 0
317
- }))
318
- };
319
- const script = `<script>window.__ssr=${JSON.stringify(hydrationData)}<\/script>`;
320
- const response = {
321
- html: template
322
- };
323
- this.fillTemplate(response, app, script);
324
- if (context.head) {
325
- response.html = this.headProvider.renderHead(response.html, context.head);
326
- }
327
- return response.html;
328
- }
329
- fillTemplate(response, app, script) {
330
- if (this.ROOT_DIV_REGEX.test(response.html)) {
331
- response.html = response.html.replace(
332
- this.ROOT_DIV_REGEX,
333
- (_match, beforeId, afterId) => {
334
- return `<div${beforeId} id="${this.env.REACT_ROOT_ID}"${afterId}>${app}</div>`;
335
- }
336
- );
337
- } else {
338
- const bodyOpenTag = /<body([^>]*)>/i;
339
- if (bodyOpenTag.test(response.html)) {
340
- response.html = response.html.replace(bodyOpenTag, (match) => {
341
- return `${match}
342
- <div id="${this.env.REACT_ROOT_ID}">${app}</div>`;
343
- });
344
- }
345
- }
346
- const bodyCloseTagRegex = /<\/body>/i;
347
- if (bodyCloseTagRegex.test(response.html)) {
348
- response.html = response.html.replace(
349
- bodyCloseTagRegex,
350
- `${script}
351
- </body>`
352
- );
353
- }
354
- }
355
- }
642
+ var ReactServerProvider = class {
643
+ log = (0, __alepha_core.$logger)();
644
+ alepha = (0, __alepha_core.$inject)(__alepha_core.Alepha);
645
+ pageDescriptorProvider = (0, __alepha_core.$inject)(PageDescriptorProvider);
646
+ serverStaticProvider = (0, __alepha_core.$inject)(__alepha_server_static.ServerStaticProvider);
647
+ serverRouterProvider = (0, __alepha_core.$inject)(__alepha_server.ServerRouterProvider);
648
+ serverTimingProvider = (0, __alepha_core.$inject)(__alepha_server.ServerTimingProvider);
649
+ env = (0, __alepha_core.$inject)(envSchema);
650
+ ROOT_DIV_REGEX = new RegExp(`<div([^>]*)\\s+id=["']${this.env.REACT_ROOT_ID}["']([^>]*)>(.*?)<\\/div>`, "is");
651
+ onConfigure = (0, __alepha_core.$hook)({
652
+ name: "configure",
653
+ handler: async () => {
654
+ const pages = this.alepha.getDescriptorValues($page);
655
+ const ssrEnabled = pages.length > 0 && this.env.REACT_SSR_ENABLED !== false;
656
+ this.alepha.state("ReactServerProvider.ssr", ssrEnabled);
657
+ for (const { key, instance, value } of pages) {
658
+ const name = value[__alepha_core.OPTIONS].name ?? key;
659
+ instance[key].render = this.createRenderFunction(name);
660
+ }
661
+ if (this.alepha.isServerless() === "vite") {
662
+ await this.configureVite(ssrEnabled);
663
+ return;
664
+ }
665
+ let root = "";
666
+ if (!this.alepha.isServerless()) {
667
+ root = this.getPublicDirectory();
668
+ if (!root) this.log.warn("Missing static files, static file server will be disabled");
669
+ else {
670
+ this.log.debug(`Using static files from: ${root}`);
671
+ await this.configureStaticServer(root);
672
+ }
673
+ }
674
+ if (ssrEnabled) {
675
+ await this.registerPages(async () => this.template);
676
+ this.log.info("SSR OK");
677
+ return;
678
+ }
679
+ this.log.info("SSR is disabled, use History API fallback");
680
+ await this.serverRouterProvider.route({
681
+ path: "*",
682
+ handler: async ({ url, reply }) => {
683
+ if (url.pathname.includes(".")) {
684
+ reply.headers["content-type"] = "text/plain";
685
+ reply.body = "Not Found";
686
+ reply.status = 404;
687
+ return;
688
+ }
689
+ reply.headers["content-type"] = "text/html";
690
+ return this.template;
691
+ }
692
+ });
693
+ }
694
+ });
695
+ get template() {
696
+ return this.alepha.state("ReactServerProvider.template") ?? "<!DOCTYPE html><html lang='en'><head></head><body></body></html>";
697
+ }
698
+ async registerPages(templateLoader) {
699
+ for (const page of this.pageDescriptorProvider.getPages()) {
700
+ if (page.children?.length) continue;
701
+ this.log.debug(`+ ${page.match} -> ${page.name}`);
702
+ await this.serverRouterProvider.route({
703
+ ...page,
704
+ schema: void 0,
705
+ method: "GET",
706
+ path: page.match,
707
+ handler: this.createHandler(page, templateLoader)
708
+ });
709
+ }
710
+ }
711
+ getPublicDirectory() {
712
+ const maybe = [(0, node_path.join)(process.cwd(), `dist/${this.env.REACT_SERVER_DIST}`), (0, node_path.join)(process.cwd(), this.env.REACT_SERVER_DIST)];
713
+ for (const it of maybe) if ((0, node_fs.existsSync)(it)) return it;
714
+ return "";
715
+ }
716
+ async configureStaticServer(root) {
717
+ await this.serverStaticProvider.serve({
718
+ root,
719
+ path: this.env.REACT_SERVER_PREFIX
720
+ });
721
+ }
722
+ async configureVite(ssrEnabled) {
723
+ if (!ssrEnabled) return;
724
+ this.log.info("SSR (vite) OK");
725
+ const url = `http://${process.env.SERVER_HOST}:${process.env.SERVER_PORT}`;
726
+ await this.registerPages(() => fetch(`${url}/index.html`).then((it) => it.text()).catch(() => void 0));
727
+ }
728
+ /**
729
+ * For testing purposes, creates a render function that can be used.
730
+ */
731
+ createRenderFunction(name, withIndex = false) {
732
+ return async (options = {}) => {
733
+ const page = this.pageDescriptorProvider.page(name);
734
+ const url = new URL(this.pageDescriptorProvider.url(name, options));
735
+ const context = {
736
+ url,
737
+ params: options.params ?? {},
738
+ query: options.query ?? {},
739
+ head: {},
740
+ onError: () => null
741
+ };
742
+ await this.alepha.emit("react:server:render:begin", { context });
743
+ const state = await this.pageDescriptorProvider.createLayers(page, context);
744
+ if (!withIndex && !options.html) return {
745
+ context,
746
+ html: (0, react_dom_server.renderToString)(this.pageDescriptorProvider.root(state, context))
747
+ };
748
+ const html = this.renderToHtml(this.template ?? "", state, context, options.hydration);
749
+ const result = {
750
+ context,
751
+ state,
752
+ html
753
+ };
754
+ await this.alepha.emit("react:server:render:end", result);
755
+ return result;
756
+ };
757
+ }
758
+ createHandler(page, templateLoader) {
759
+ return async (serverRequest) => {
760
+ const { url, reply, query, params } = serverRequest;
761
+ const template = await templateLoader();
762
+ if (!template) throw new Error("Template not found");
763
+ const context = {
764
+ url,
765
+ params,
766
+ query,
767
+ head: {},
768
+ onError: () => null
769
+ };
770
+ if (this.alepha.has(__alepha_server_links.ServerLinksProvider)) {
771
+ const srv = this.alepha.get(__alepha_server_links.ServerLinksProvider);
772
+ const schema = __alepha_server.apiLinksResponseSchema;
773
+ context.links = this.alepha.parse(schema, await srv.getLinks({
774
+ user: serverRequest.user,
775
+ authorization: serverRequest.headers.authorization
776
+ }));
777
+ this.alepha.context.set("links", context.links);
778
+ }
779
+ let target = page;
780
+ while (target) {
781
+ if (page.can && !page.can()) {
782
+ reply.status = 403;
783
+ reply.headers["content-type"] = "text/plain";
784
+ return "Forbidden";
785
+ }
786
+ target = target.parent;
787
+ }
788
+ await this.alepha.emit("react:server:render:begin", {
789
+ request: serverRequest,
790
+ context
791
+ });
792
+ this.serverTimingProvider.beginTiming("createLayers");
793
+ const state = await this.pageDescriptorProvider.createLayers(page, context);
794
+ this.serverTimingProvider.endTiming("createLayers");
795
+ if (state.redirect) return reply.redirect(state.redirect);
796
+ reply.headers["content-type"] = "text/html";
797
+ reply.headers["cache-control"] = "no-store, no-cache, must-revalidate, proxy-revalidate";
798
+ reply.headers.pragma = "no-cache";
799
+ reply.headers.expires = "0";
800
+ if (page.cache && serverRequest.user) delete context.links;
801
+ const html = this.renderToHtml(template, state, context);
802
+ await this.alepha.emit("react:server:render:end", {
803
+ request: serverRequest,
804
+ context,
805
+ state,
806
+ html
807
+ });
808
+ page.afterHandler?.(serverRequest);
809
+ return html;
810
+ };
811
+ }
812
+ renderToHtml(template, state, context, hydration = true) {
813
+ const element = this.pageDescriptorProvider.root(state, context);
814
+ this.serverTimingProvider.beginTiming("renderToString");
815
+ let app = "";
816
+ try {
817
+ app = (0, react_dom_server.renderToString)(element);
818
+ } catch (error) {
819
+ this.log.error("Error during SSR", error);
820
+ app = (0, react_dom_server.renderToString)(context.onError(error));
821
+ }
822
+ this.serverTimingProvider.endTiming("renderToString");
823
+ const response = { html: template };
824
+ if (hydration) {
825
+ const hydrationData = {
826
+ links: context.links,
827
+ layers: state.layers.map((it) => ({
828
+ ...it,
829
+ error: it.error ? {
830
+ ...it.error,
831
+ name: it.error.name,
832
+ message: it.error.message,
833
+ stack: it.error.stack
834
+ } : void 0,
835
+ index: void 0,
836
+ path: void 0,
837
+ element: void 0,
838
+ route: void 0
839
+ }))
840
+ };
841
+ const script = `<script>window.__ssr=${JSON.stringify(hydrationData)}</script>`;
842
+ this.fillTemplate(response, app, script);
843
+ }
844
+ return response.html;
845
+ }
846
+ fillTemplate(response, app, script) {
847
+ if (this.ROOT_DIV_REGEX.test(response.html)) response.html = response.html.replace(this.ROOT_DIV_REGEX, (_match, beforeId, afterId) => {
848
+ return `<div${beforeId} id="${this.env.REACT_ROOT_ID}"${afterId}>${app}</div>`;
849
+ });
850
+ else {
851
+ const bodyOpenTag = /<body([^>]*)>/i;
852
+ if (bodyOpenTag.test(response.html)) response.html = response.html.replace(bodyOpenTag, (match) => {
853
+ return `${match}\n<div id="${this.env.REACT_ROOT_ID}">${app}</div>`;
854
+ });
855
+ }
856
+ const bodyCloseTagRegex = /<\/body>/i;
857
+ if (bodyCloseTagRegex.test(response.html)) response.html = response.html.replace(bodyCloseTagRegex, `${script}\n</body>`);
858
+ }
859
+ };
356
860
 
357
- class AlephaReact {
358
- name = "alepha.react";
359
- $services = (alepha) => alepha.with(server.AlephaServer).with(serverCache.AlephaServerCache).with(ReactServerProvider).with(useRouterState.PageDescriptorProvider);
360
- }
361
- core.__bind(useRouterState.$page, AlephaReact);
861
+ //#endregion
862
+ //#region src/providers/BrowserRouterProvider.ts
863
+ var BrowserRouterProvider = class extends __alepha_router.RouterProvider {
864
+ log = (0, __alepha_core.$logger)();
865
+ alepha = (0, __alepha_core.$inject)(__alepha_core.Alepha);
866
+ pageDescriptorProvider = (0, __alepha_core.$inject)(PageDescriptorProvider);
867
+ add(entry) {
868
+ this.pageDescriptorProvider.add(entry);
869
+ }
870
+ configure = (0, __alepha_core.$hook)({
871
+ name: "configure",
872
+ handler: async () => {
873
+ for (const page of this.pageDescriptorProvider.getPages()) if (page.component || page.lazy) this.push({
874
+ path: page.match,
875
+ page
876
+ });
877
+ }
878
+ });
879
+ async transition(url, options = {}) {
880
+ const { pathname, search } = url;
881
+ const state = {
882
+ pathname,
883
+ search,
884
+ layers: []
885
+ };
886
+ const context = {
887
+ url,
888
+ query: {},
889
+ params: {},
890
+ onError: () => null,
891
+ ...options.context ?? {}
892
+ };
893
+ await this.alepha.emit("react:transition:begin", {
894
+ state,
895
+ context
896
+ });
897
+ try {
898
+ const previous = options.previous;
899
+ const { route, params } = this.match(pathname);
900
+ const query = {};
901
+ if (search) for (const [key, value] of new URLSearchParams(search).entries()) query[key] = String(value);
902
+ context.query = query;
903
+ context.params = params ?? {};
904
+ context.previous = previous;
905
+ if (isPageRoute(route)) {
906
+ const result = await this.pageDescriptorProvider.createLayers(route.page, context);
907
+ if (result.redirect) return {
908
+ redirect: result.redirect,
909
+ state,
910
+ context
911
+ };
912
+ state.layers = result.layers;
913
+ }
914
+ if (state.layers.length === 0) state.layers.push({
915
+ name: "not-found",
916
+ element: (0, react.createElement)(NotFoundPage),
917
+ index: 0,
918
+ path: "/"
919
+ });
920
+ await this.alepha.emit("react:transition:success", {
921
+ state,
922
+ context
923
+ });
924
+ } catch (e) {
925
+ this.log.error(e);
926
+ state.layers = [{
927
+ name: "error",
928
+ element: this.pageDescriptorProvider.renderError(e),
929
+ index: 0,
930
+ path: "/"
931
+ }];
932
+ await this.alepha.emit("react:transition:error", {
933
+ error: e,
934
+ state,
935
+ context
936
+ });
937
+ }
938
+ if (options.state) {
939
+ options.state.layers = state.layers;
940
+ options.state.pathname = state.pathname;
941
+ options.state.search = state.search;
942
+ }
943
+ await this.alepha.emit("react:transition:end", {
944
+ state: options.state,
945
+ context
946
+ });
947
+ return {
948
+ context,
949
+ state
950
+ };
951
+ }
952
+ root(state, context) {
953
+ return this.pageDescriptorProvider.root(state, context);
954
+ }
955
+ };
956
+
957
+ //#endregion
958
+ //#region src/providers/ReactBrowserProvider.ts
959
+ var ReactBrowserProvider = class {
960
+ log = (0, __alepha_core.$logger)();
961
+ client = (0, __alepha_core.$inject)(__alepha_server_links.LinkProvider);
962
+ alepha = (0, __alepha_core.$inject)(__alepha_core.Alepha);
963
+ router = (0, __alepha_core.$inject)(BrowserRouterProvider);
964
+ root;
965
+ transitioning;
966
+ state = {
967
+ layers: [],
968
+ pathname: "",
969
+ search: ""
970
+ };
971
+ get document() {
972
+ return window.document;
973
+ }
974
+ get history() {
975
+ return window.history;
976
+ }
977
+ get url() {
978
+ return window.location.pathname + window.location.search;
979
+ }
980
+ async invalidate(props) {
981
+ const previous = [];
982
+ if (props) {
983
+ const [key] = Object.keys(props);
984
+ const value = props[key];
985
+ for (const layer of this.state.layers) {
986
+ if (layer.props?.[key]) {
987
+ previous.push({
988
+ ...layer,
989
+ props: {
990
+ ...layer.props,
991
+ [key]: value
992
+ }
993
+ });
994
+ break;
995
+ }
996
+ previous.push(layer);
997
+ }
998
+ }
999
+ await this.render({ previous });
1000
+ }
1001
+ async go(url, options = {}) {
1002
+ const result = await this.render({ url });
1003
+ if (result.context.url.pathname !== url) {
1004
+ this.history.replaceState({}, "", result.context.url.pathname);
1005
+ return;
1006
+ }
1007
+ if (options.replace) {
1008
+ this.history.replaceState({}, "", url);
1009
+ return;
1010
+ }
1011
+ this.history.pushState({}, "", url);
1012
+ }
1013
+ async render(options = {}) {
1014
+ const previous = options.previous ?? this.state.layers;
1015
+ const url = options.url ?? this.url;
1016
+ this.transitioning = { to: url };
1017
+ const result = await this.router.transition(new URL(`http://localhost${url}`), {
1018
+ previous,
1019
+ state: this.state
1020
+ });
1021
+ if (result.redirect) return await this.render({ url: result.redirect });
1022
+ this.transitioning = void 0;
1023
+ return result;
1024
+ }
1025
+ /**
1026
+ * Get embedded layers from the server.
1027
+ */
1028
+ getHydrationState() {
1029
+ try {
1030
+ if ("__ssr" in window && typeof window.__ssr === "object") return window.__ssr;
1031
+ } catch (error) {
1032
+ console.error(error);
1033
+ }
1034
+ }
1035
+ ready = (0, __alepha_core.$hook)({
1036
+ name: "ready",
1037
+ handler: async () => {
1038
+ const hydration = this.getHydrationState();
1039
+ const previous = hydration?.layers ?? [];
1040
+ if (hydration?.links) for (const link of hydration.links.links) this.client.pushLink(link);
1041
+ const { context } = await this.render({ previous });
1042
+ await this.alepha.emit("react:browser:render", {
1043
+ state: this.state,
1044
+ context,
1045
+ hydration
1046
+ });
1047
+ window.addEventListener("popstate", () => {
1048
+ this.render();
1049
+ });
1050
+ }
1051
+ });
1052
+ };
1053
+
1054
+ //#endregion
1055
+ //#region src/hooks/RouterHookApi.ts
1056
+ var RouterHookApi = class {
1057
+ constructor(pages, state, layer, browser) {
1058
+ this.pages = pages;
1059
+ this.state = state;
1060
+ this.layer = layer;
1061
+ this.browser = browser;
1062
+ }
1063
+ get current() {
1064
+ return this.state;
1065
+ }
1066
+ get pathname() {
1067
+ return this.state.pathname;
1068
+ }
1069
+ get query() {
1070
+ const query = {};
1071
+ for (const [key, value] of new URLSearchParams(this.state.search).entries()) query[key] = String(value);
1072
+ return query;
1073
+ }
1074
+ async back() {
1075
+ this.browser?.history.back();
1076
+ }
1077
+ async forward() {
1078
+ this.browser?.history.forward();
1079
+ }
1080
+ async invalidate(props) {
1081
+ await this.browser?.invalidate(props);
1082
+ }
1083
+ /**
1084
+ * Create a valid href for the given pathname.
1085
+ *
1086
+ * @param pathname
1087
+ * @param layer
1088
+ */
1089
+ createHref(pathname, layer = this.layer, options = {}) {
1090
+ if (typeof pathname === "object") pathname = pathname.options.path ?? "";
1091
+ if (options.params) for (const [key, value] of Object.entries(options.params)) pathname = pathname.replace(`:${key}`, String(value));
1092
+ return pathname.startsWith("/") ? pathname : `${layer.path}/${pathname}`.replace(/\/\/+/g, "/");
1093
+ }
1094
+ async go(path, options) {
1095
+ for (const page of this.pages) if (page.name === path) {
1096
+ path = page.path ?? "";
1097
+ break;
1098
+ }
1099
+ await this.browser?.go(this.createHref(path, this.layer, options), options);
1100
+ }
1101
+ anchor(path, options = {}) {
1102
+ for (const page of this.pages) if (page.name === path) {
1103
+ path = page.path ?? "";
1104
+ break;
1105
+ }
1106
+ const href = this.createHref(path, this.layer, options);
1107
+ return {
1108
+ href,
1109
+ onClick: (ev) => {
1110
+ ev.stopPropagation();
1111
+ ev.preventDefault();
1112
+ this.go(path, options).catch(console.error);
1113
+ }
1114
+ };
1115
+ }
1116
+ /**
1117
+ * Set query params.
1118
+ *
1119
+ * @param record
1120
+ * @param options
1121
+ */
1122
+ setQueryParams(record, options = {}) {
1123
+ const func = typeof record === "function" ? record : () => record;
1124
+ const search = new URLSearchParams(func(this.query)).toString();
1125
+ const state = search ? `${this.pathname}?${search}` : this.pathname;
1126
+ if (options.push) window.history.pushState({}, "", state);
1127
+ else window.history.replaceState({}, "", state);
1128
+ }
1129
+ };
1130
+
1131
+ //#endregion
1132
+ //#region src/hooks/useRouter.ts
1133
+ const useRouter = () => {
1134
+ const ctx = (0, react.useContext)(RouterContext);
1135
+ const layer = (0, react.useContext)(RouterLayerContext);
1136
+ if (!ctx || !layer) throw new Error("useRouter must be used within a RouterProvider");
1137
+ const pages = (0, react.useMemo)(() => {
1138
+ return ctx.alepha.get(PageDescriptorProvider).getPages();
1139
+ }, []);
1140
+ return (0, react.useMemo)(() => new RouterHookApi(pages, ctx.state, layer, ctx.alepha.isBrowser() ? ctx.alepha.get(ReactBrowserProvider) : void 0), [layer]);
1141
+ };
1142
+
1143
+ //#endregion
1144
+ //#region src/components/Link.tsx
1145
+ const Link = (props) => {
1146
+ react.default.useContext(RouterContext);
1147
+ const router = useRouter();
1148
+ const to = typeof props.to === "string" ? props.to : props.to[__alepha_core.OPTIONS].path;
1149
+ if (!to) return null;
1150
+ const can = typeof props.to === "string" ? void 0 : props.to[__alepha_core.OPTIONS].can;
1151
+ if (can && !can()) return null;
1152
+ const name = typeof props.to === "string" ? void 0 : props.to[__alepha_core.OPTIONS].name;
1153
+ const anchorProps = {
1154
+ ...props,
1155
+ to: void 0
1156
+ };
1157
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("a", {
1158
+ ...router.anchor(to),
1159
+ ...anchorProps,
1160
+ children: props.children ?? name
1161
+ });
1162
+ };
1163
+ var Link_default = Link;
1164
+
1165
+ //#endregion
1166
+ //#region src/hooks/useActive.ts
1167
+ const useActive = (path) => {
1168
+ const router = useRouter();
1169
+ const ctx = (0, react.useContext)(RouterContext);
1170
+ const layer = (0, react.useContext)(RouterLayerContext);
1171
+ if (!ctx || !layer) throw new Error("useRouter must be used within a RouterProvider");
1172
+ let name;
1173
+ if (typeof path === "object" && path.options.name) name = path.options.name;
1174
+ const [current, setCurrent] = (0, react.useState)(ctx.state.pathname);
1175
+ const href = (0, react.useMemo)(() => router.createHref(path, layer), [path, layer]);
1176
+ const [isPending, setPending] = (0, react.useState)(false);
1177
+ const isActive = current === href;
1178
+ useRouterEvents({ onEnd: ({ state }) => setCurrent(state.pathname) });
1179
+ return {
1180
+ name,
1181
+ isPending,
1182
+ isActive,
1183
+ anchorProps: {
1184
+ href,
1185
+ onClick: (ev) => {
1186
+ ev.stopPropagation();
1187
+ ev.preventDefault();
1188
+ if (isActive) return;
1189
+ if (isPending) return;
1190
+ setPending(true);
1191
+ router.go(href).then(() => {
1192
+ setPending(false);
1193
+ });
1194
+ }
1195
+ }
1196
+ };
1197
+ };
1198
+
1199
+ //#endregion
1200
+ //#region src/hooks/useInject.ts
1201
+ const useInject = (clazz) => {
1202
+ const ctx = (0, react.useContext)(RouterContext);
1203
+ if (!ctx) throw new Error("useRouter must be used within a <RouterProvider>");
1204
+ return (0, react.useMemo)(() => ctx.alepha.get(clazz), []);
1205
+ };
1206
+
1207
+ //#endregion
1208
+ //#region src/hooks/useClient.ts
1209
+ const useClient = (_scope) => {
1210
+ return useInject(__alepha_server_links.LinkProvider).client();
1211
+ };
1212
+
1213
+ //#endregion
1214
+ //#region src/hooks/useQueryParams.ts
1215
+ const useQueryParams = (schema, options = {}) => {
1216
+ const ctx = (0, react.useContext)(RouterContext);
1217
+ if (!ctx) throw new Error("useQueryParams must be used within a RouterProvider");
1218
+ const key = options.key ?? "q";
1219
+ const router = useRouter();
1220
+ const querystring = router.query[key];
1221
+ const [queryParams, setQueryParams] = (0, react.useState)(decode(ctx.alepha, schema, router.query[key]));
1222
+ (0, react.useEffect)(() => {
1223
+ setQueryParams(decode(ctx.alepha, schema, querystring));
1224
+ }, [querystring]);
1225
+ return [queryParams, (queryParams$1) => {
1226
+ setQueryParams(queryParams$1);
1227
+ router.setQueryParams((data) => {
1228
+ return {
1229
+ ...data,
1230
+ [key]: encode(ctx.alepha, schema, queryParams$1)
1231
+ };
1232
+ });
1233
+ }];
1234
+ };
1235
+ const encode = (alepha, schema, data) => {
1236
+ return btoa(JSON.stringify(alepha.parse(schema, data)));
1237
+ };
1238
+ const decode = (alepha, schema, data) => {
1239
+ try {
1240
+ return alepha.parse(schema, JSON.parse(atob(decodeURIComponent(data))));
1241
+ } catch (_error) {
1242
+ return {};
1243
+ }
1244
+ };
1245
+
1246
+ //#endregion
1247
+ //#region src/hooks/useRouterState.ts
1248
+ const useRouterState = () => {
1249
+ const ctx = (0, react.useContext)(RouterContext);
1250
+ const layer = (0, react.useContext)(RouterLayerContext);
1251
+ if (!ctx || !layer) throw new Error("useRouter must be used within a RouterProvider");
1252
+ const [state, setState] = (0, react.useState)(ctx.state);
1253
+ useRouterEvents({ onEnd: ({ state: state$1 }) => setState({ ...state$1 }) });
1254
+ return state;
1255
+ };
1256
+
1257
+ //#endregion
1258
+ //#region src/index.ts
1259
+ /**
1260
+ * Alepha React Module
1261
+ *
1262
+ * Alepha React Module contains a router for client-side navigation and server-side rendering.
1263
+ * Routes can be defined using the `$page` descriptor.
1264
+ *
1265
+ * @see {@link $page}
1266
+ * @module alepha.react
1267
+ */
1268
+ var AlephaReact = class {
1269
+ name = "alepha.react";
1270
+ $services = (alepha) => alepha.with(__alepha_server.AlephaServer).with(__alepha_server_cache.AlephaServerCache).with(ReactServerProvider).with(PageDescriptorProvider);
1271
+ };
1272
+ (0, __alepha_core.__bind)($page, AlephaReact);
362
1273
 
363
- exports.$page = useRouterState.$page;
364
- exports.ClientOnly = useRouterState.ClientOnly;
365
- exports.ErrorBoundary = useRouterState.ErrorBoundary;
366
- exports.Link = useRouterState.Link;
367
- exports.NestedView = useRouterState.NestedView;
368
- exports.PageDescriptorProvider = useRouterState.PageDescriptorProvider;
369
- exports.ReactBrowserProvider = useRouterState.ReactBrowserProvider;
370
- exports.RedirectionError = useRouterState.RedirectionError;
371
- exports.RouterContext = useRouterState.RouterContext;
372
- exports.RouterHookApi = useRouterState.RouterHookApi;
373
- exports.RouterLayerContext = useRouterState.RouterLayerContext;
374
- exports.isPageRoute = useRouterState.isPageRoute;
375
- exports.useActive = useRouterState.useActive;
376
- exports.useAlepha = useRouterState.useAlepha;
377
- exports.useClient = useRouterState.useClient;
378
- exports.useInject = useRouterState.useInject;
379
- exports.useQueryParams = useRouterState.useQueryParams;
380
- exports.useRouter = useRouterState.useRouter;
381
- exports.useRouterEvents = useRouterState.useRouterEvents;
382
- exports.useRouterState = useRouterState.useRouterState;
1274
+ //#endregion
1275
+ exports.$page = $page;
383
1276
  exports.AlephaReact = AlephaReact;
1277
+ exports.ClientOnly = ClientOnly_default;
1278
+ exports.ErrorBoundary = ErrorBoundary_default;
1279
+ exports.Link = Link_default;
1280
+ exports.NestedView = NestedView_default;
1281
+ exports.PageDescriptorProvider = PageDescriptorProvider;
1282
+ exports.ReactBrowserProvider = ReactBrowserProvider;
384
1283
  exports.ReactServerProvider = ReactServerProvider;
1284
+ exports.RedirectionError = RedirectionError;
1285
+ exports.RouterContext = RouterContext;
1286
+ exports.RouterHookApi = RouterHookApi;
1287
+ exports.RouterLayerContext = RouterLayerContext;
1288
+ exports.isPageRoute = isPageRoute;
1289
+ exports.useActive = useActive;
1290
+ exports.useAlepha = useAlepha;
1291
+ exports.useClient = useClient;
1292
+ exports.useInject = useInject;
1293
+ exports.useQueryParams = useQueryParams;
1294
+ exports.useRouter = useRouter;
1295
+ exports.useRouterEvents = useRouterEvents;
1296
+ exports.useRouterState = useRouterState;
1297
+ //# sourceMappingURL=index.cjs.map