@zenithbuild/router 0.7.4 → 0.7.5

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/README.md CHANGED
@@ -18,3 +18,4 @@
18
18
  - Redirects, denies, unmatched routes, non-HTML responses, and runtime failures fall back to browser navigation.
19
19
  - Client routing mirrors server route precedence and pathname-based identity.
20
20
  - Phase 2 adds awaited lifecycle barriers at `navigation:before-leave`, `navigation:before-swap`, and `navigation:before-enter`.
21
+ - `zenNavigationShell(...)` is the narrow canonical Phase 3 utility for projecting visual shell phase on top of that lifecycle without changing route truth.
package/dist/history.js CHANGED
@@ -1,12 +1,17 @@
1
1
  // ---------------------------------------------------------------------------
2
2
  // history.js — Zenith Router V0
3
3
  // ---------------------------------------------------------------------------
4
- // Minimal navigation helpers without History API mutation.
4
+ // Minimal source-router path helpers.
5
5
  //
6
- // - push(path) → hard navigation (assign)
7
- // - replace(path) → hard navigation (replace)
6
+ // The template-generated router owns real History API writes.
7
+ // This source helper keeps a narrow in-memory path override for
8
+ // source-level tests and simple router assembly without leaking
9
+ // soft-nav history writes into the shipped runtime contract.
10
+ //
11
+ // - push(path) → update source-router current path
12
+ // - replace(path) → update source-router current path
8
13
  // - listen(cb) → popstate listener, returns unlisten
9
- // - current() → location.pathname
14
+ // - current() → source-router path or current location.pathname
10
15
  //
11
16
  // No hash routing. No scroll restoration. No batching.
12
17
  // ---------------------------------------------------------------------------
@@ -14,11 +19,26 @@
14
19
  const _listeners = new Set();
15
20
  /** @type {boolean} */
16
21
  let _listening = false;
22
+ /** @type {string | null} */
23
+ let _currentPathOverride = null;
24
+ /** @type {string | null} */
25
+ let _lastObservedWindowPath = null;
26
+ function _readWindowPath() {
27
+ return window.location.pathname;
28
+ }
29
+ function _syncWindowPath() {
30
+ const windowPath = _readWindowPath();
31
+ if (_lastObservedWindowPath !== windowPath) {
32
+ _lastObservedWindowPath = windowPath;
33
+ _currentPathOverride = null;
34
+ }
35
+ return windowPath;
36
+ }
17
37
  /**
18
38
  * Internal popstate handler — fires all registered listeners.
19
39
  */
20
40
  function _onPopState() {
21
- const path = current();
41
+ const path = _syncWindowPath();
22
42
  for (const cb of _listeners) {
23
43
  cb(path);
24
44
  }
@@ -38,7 +58,8 @@ function _ensureListening() {
38
58
  * @param {string} path
39
59
  */
40
60
  export function push(path) {
41
- window.location.assign(path);
61
+ _lastObservedWindowPath = _readWindowPath();
62
+ _currentPathOverride = path;
42
63
  }
43
64
  /**
44
65
  * Replace the current path in browser history.
@@ -46,7 +67,8 @@ export function push(path) {
46
67
  * @param {string} path
47
68
  */
48
69
  export function replace(path) {
49
- window.location.replace(path);
70
+ _lastObservedWindowPath = _readWindowPath();
71
+ _currentPathOverride = path;
50
72
  }
51
73
  /**
52
74
  * Subscribe to popstate (back/forward) events.
@@ -72,5 +94,6 @@ export function listen(callback) {
72
94
  * @returns {string}
73
95
  */
74
96
  export function current() {
75
- return window.location.pathname;
97
+ const windowPath = _syncWindowPath();
98
+ return _currentPathOverride ?? windowPath;
76
99
  }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export { createRouter } from "./router.js";
2
+ export { zenNavigationShell } from "./navigation-shell.js";
2
3
  export { matchRoute } from "./match.js";
3
- export { navigate, back, forward, getCurrentPath } from "./navigate.js";
4
+ export { navigate, refreshCurrentRoute, back, forward, getCurrentPath } from "./navigate.js";
4
5
  export { onRouteChange, on, off, setRouteProtectionPolicy, _getRouteProtectionPolicy, _dispatchRouteEvent } from "./events.js";
package/dist/index.js CHANGED
@@ -4,6 +4,7 @@
4
4
  // Structural navigation exports + route protection policy/event hooks.
5
5
  // ---------------------------------------------------------------------------
6
6
  export { createRouter } from './router.js';
7
- export { navigate, back, forward, getCurrentPath } from './navigate.js';
7
+ export { navigate, refreshCurrentRoute, back, forward, getCurrentPath } from './navigate.js';
8
8
  export { onRouteChange, on, off, setRouteProtectionPolicy, _getRouteProtectionPolicy, _dispatchRouteEvent } from './events.js';
9
+ export { zenNavigationShell } from './navigation-shell.js';
9
10
  export { matchRoute } from './match.js';
@@ -1,5 +1,7 @@
1
1
  export declare function _setNavigationResolver(resolver: ((path: string) => Promise<void>) | null): void;
2
+ export declare function _setRefreshResolver(resolver: (() => Promise<void>) | null): void;
2
3
  export declare function navigate(path: string): Promise<void>;
4
+ export declare function refreshCurrentRoute(): Promise<void>;
3
5
  export declare function back(): void;
4
6
  export declare function forward(): void;
5
7
  export declare function getCurrentPath(): string;
package/dist/navigate.js CHANGED
@@ -4,6 +4,7 @@
4
4
  // Navigation API.
5
5
  //
6
6
  // - navigate(path) → push to history, trigger route change
7
+ // - refreshCurrentRoute() → rerun the current matched route without pushing history
7
8
  // - back() → history.back()
8
9
  // - forward() → history.forward()
9
10
  // - getCurrentPath() → current pathname
@@ -13,15 +14,30 @@
13
14
  // ---------------------------------------------------------------------------
14
15
  import { current, push } from './history.js';
15
16
  let resolveNavigation = null;
17
+ let resolveRefresh = null;
18
+ const ROUTER_REFRESH_KEY = '__zenith_refresh_current_route';
16
19
  export function _setNavigationResolver(resolver) {
17
20
  resolveNavigation = resolver;
18
21
  }
22
+ export function _setRefreshResolver(resolver) {
23
+ resolveRefresh = resolver;
24
+ }
19
25
  export async function navigate(path) {
20
26
  push(path);
21
27
  if (resolveNavigation) {
22
28
  await resolveNavigation(path);
23
29
  }
24
30
  }
31
+ export async function refreshCurrentRoute() {
32
+ const scope = typeof globalThis === 'object' && globalThis
33
+ ? globalThis
34
+ : {};
35
+ const resolver = resolveRefresh || scope[ROUTER_REFRESH_KEY] || null;
36
+ if (typeof resolver !== 'function') {
37
+ throw new Error('[Zenith Router] refreshCurrentRoute() requires a current matched Zenith page route');
38
+ }
39
+ await resolver();
40
+ }
25
41
  export function back() {
26
42
  history.back();
27
43
  }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Tiny visual-only navigation shell controller layered on the existing router lifecycle.
3
+ *
4
+ * @param {{ current?: Element | null }} ref
5
+ * @param {{ timeoutMs?: number, onStateChange?: ((state: { phase: ZenNavigationShellPhase, navigationId: number | null, navigationType: 'push' | 'pop' | null }, context: { previousState: { phase: ZenNavigationShellPhase, navigationId: number | null, navigationType: 'push' | 'pop' | null } }) => void) } | null | undefined} [options]
6
+ * @returns {{
7
+ * mount: () => () => void,
8
+ * destroy: () => void,
9
+ * getPhase: () => ZenNavigationShellPhase,
10
+ * getState: () => { phase: ZenNavigationShellPhase, navigationId: number | null, navigationType: 'push' | 'pop' | null }
11
+ * }}
12
+ */
13
+ export function zenNavigationShell(ref: {
14
+ current?: Element | null;
15
+ }, options?: {
16
+ timeoutMs?: number;
17
+ onStateChange?: ((state: {
18
+ phase: ZenNavigationShellPhase;
19
+ navigationId: number | null;
20
+ navigationType: "push" | "pop" | null;
21
+ }, context: {
22
+ previousState: {
23
+ phase: ZenNavigationShellPhase;
24
+ navigationId: number | null;
25
+ navigationType: "push" | "pop" | null;
26
+ };
27
+ }) => void);
28
+ } | null | undefined): {
29
+ mount: () => () => void;
30
+ destroy: () => void;
31
+ getPhase: () => ZenNavigationShellPhase;
32
+ getState: () => {
33
+ phase: ZenNavigationShellPhase;
34
+ navigationId: number | null;
35
+ navigationType: "push" | "pop" | null;
36
+ };
37
+ };
38
+ export type ZenNavigationShellPhase = "idle" | "leaving" | "swapping" | "entering";
@@ -0,0 +1,392 @@
1
+ // @ts-nocheck
2
+ import { on, off } from './events.js';
3
+ /**
4
+ * @typedef {'idle' | 'leaving' | 'swapping' | 'entering'} ZenNavigationShellPhase
5
+ */
6
+ function isRefLike(value) {
7
+ return !!value && typeof value === 'object' && 'current' in value;
8
+ }
9
+ function normalizeOptions(options) {
10
+ if (options === undefined || options === null) {
11
+ return {
12
+ timeoutMs: undefined,
13
+ onStateChange: null
14
+ };
15
+ }
16
+ if (!options || typeof options !== 'object' || Array.isArray(options)) {
17
+ throw new Error('[Zenith Router] zenNavigationShell(ref, options) requires an options object when provided');
18
+ }
19
+ if (options.timeoutMs !== undefined) {
20
+ if (!Number.isFinite(options.timeoutMs) || options.timeoutMs < 0) {
21
+ throw new Error('[Zenith Router] zenNavigationShell options.timeoutMs must be a non-negative number');
22
+ }
23
+ }
24
+ if (options.onStateChange !== undefined && typeof options.onStateChange !== 'function') {
25
+ throw new Error('[Zenith Router] zenNavigationShell options.onStateChange must be a function when provided');
26
+ }
27
+ return {
28
+ timeoutMs: options.timeoutMs === undefined ? undefined : Math.floor(options.timeoutMs),
29
+ onStateChange: typeof options.onStateChange === 'function' ? options.onStateChange : null
30
+ };
31
+ }
32
+ function parseCssTimeToken(token) {
33
+ const value = String(token || '').trim();
34
+ if (value.length === 0) {
35
+ return 0;
36
+ }
37
+ if (value.endsWith('ms')) {
38
+ const milliseconds = Number.parseFloat(value.slice(0, -2));
39
+ return Number.isFinite(milliseconds) ? Math.max(0, milliseconds) : 0;
40
+ }
41
+ if (value.endsWith('s')) {
42
+ const seconds = Number.parseFloat(value.slice(0, -1));
43
+ return Number.isFinite(seconds) ? Math.max(0, seconds * 1000) : 0;
44
+ }
45
+ const numeric = Number.parseFloat(value);
46
+ return Number.isFinite(numeric) ? Math.max(0, numeric) : 0;
47
+ }
48
+ function parseCssTimeList(value) {
49
+ return String(value || '')
50
+ .split(',')
51
+ .map((entry) => parseCssTimeToken(entry))
52
+ .filter((candidate) => Number.isFinite(candidate));
53
+ }
54
+ function computeMaxCssTotal(durations, delays) {
55
+ if (!Array.isArray(durations) || durations.length === 0) {
56
+ return 0;
57
+ }
58
+ let maxTotal = 0;
59
+ for (let index = 0; index < durations.length; index += 1) {
60
+ const duration = durations[index] || 0;
61
+ const delay = Array.isArray(delays) && delays.length > 0
62
+ ? delays[index % delays.length] || 0
63
+ : 0;
64
+ const total = duration + delay;
65
+ if (total > maxTotal) {
66
+ maxTotal = total;
67
+ }
68
+ }
69
+ return maxTotal;
70
+ }
71
+ function resolveFallbackTimeoutMs(node, explicitTimeoutMs) {
72
+ if (Number.isFinite(explicitTimeoutMs)) {
73
+ return explicitTimeoutMs;
74
+ }
75
+ const activeWindow = node?.ownerDocument?.defaultView;
76
+ if (!activeWindow || typeof activeWindow.getComputedStyle !== 'function') {
77
+ return 0;
78
+ }
79
+ const styles = activeWindow.getComputedStyle(node);
80
+ const transitionTotal = computeMaxCssTotal(parseCssTimeList(styles.transitionDuration), parseCssTimeList(styles.transitionDelay));
81
+ const animationTotal = computeMaxCssTotal(parseCssTimeList(styles.animationDuration), parseCssTimeList(styles.animationDelay));
82
+ const total = Math.max(transitionTotal, animationTotal);
83
+ return total > 0 ? Math.ceil(total + 34) : 0;
84
+ }
85
+ function getTimerApi(node) {
86
+ const activeWindow = node?.ownerDocument?.defaultView;
87
+ if (activeWindow && typeof activeWindow.setTimeout === 'function' && typeof activeWindow.clearTimeout === 'function') {
88
+ return {
89
+ setTimeout: activeWindow.setTimeout.bind(activeWindow),
90
+ clearTimeout: activeWindow.clearTimeout.bind(activeWindow)
91
+ };
92
+ }
93
+ return {
94
+ setTimeout: globalThis.setTimeout.bind(globalThis),
95
+ clearTimeout: globalThis.clearTimeout.bind(globalThis)
96
+ };
97
+ }
98
+ function addOwnedListener(node, eventName, handler) {
99
+ if (!node || typeof node.addEventListener !== 'function' || typeof node.removeEventListener !== 'function') {
100
+ return () => {
101
+ };
102
+ }
103
+ node.addEventListener(eventName, handler);
104
+ return () => {
105
+ node.removeEventListener(eventName, handler);
106
+ };
107
+ }
108
+ function isOwnedEvent(event, node) {
109
+ return !!event && event.target === node;
110
+ }
111
+ function cloneState(state) {
112
+ return {
113
+ phase: state.phase,
114
+ navigationId: state.navigationId,
115
+ navigationType: state.navigationType
116
+ };
117
+ }
118
+ function normalizeNavigationType(value) {
119
+ return value === 'push' || value === 'pop' ? value : null;
120
+ }
121
+ function readNavigationId(payload) {
122
+ return payload && typeof payload.navigationId === 'number' ? payload.navigationId : null;
123
+ }
124
+ function isLifecyclePayload(payload) {
125
+ return !!payload && typeof payload === 'object';
126
+ }
127
+ /**
128
+ * Tiny visual-only navigation shell controller layered on the existing router lifecycle.
129
+ *
130
+ * @param {{ current?: Element | null }} ref
131
+ * @param {{ timeoutMs?: number, onStateChange?: ((state: { phase: ZenNavigationShellPhase, navigationId: number | null, navigationType: 'push' | 'pop' | null }, context: { previousState: { phase: ZenNavigationShellPhase, navigationId: number | null, navigationType: 'push' | 'pop' | null } }) => void) } | null | undefined} [options]
132
+ * @returns {{
133
+ * mount: () => () => void,
134
+ * destroy: () => void,
135
+ * getPhase: () => ZenNavigationShellPhase,
136
+ * getState: () => { phase: ZenNavigationShellPhase, navigationId: number | null, navigationType: 'push' | 'pop' | null }
137
+ * }}
138
+ */
139
+ export function zenNavigationShell(ref, options = null) {
140
+ if (!isRefLike(ref)) {
141
+ throw new Error('[Zenith Router] zenNavigationShell(ref, options) requires a ref-like object with current');
142
+ }
143
+ const normalizedOptions = normalizeOptions(options);
144
+ let mounted = false;
145
+ let pendingPhaseWait = null;
146
+ let phaseEpoch = 0;
147
+ let routeDisposers = [];
148
+ let shellState = {
149
+ phase: /** @type {ZenNavigationShellPhase} */ ('idle'),
150
+ navigationId: null,
151
+ navigationType: null
152
+ };
153
+ function getNode() {
154
+ const candidate = ref.current;
155
+ if (!candidate || typeof candidate !== 'object' || typeof candidate.nodeType !== 'number') {
156
+ return null;
157
+ }
158
+ return candidate;
159
+ }
160
+ function getState() {
161
+ return cloneState(shellState);
162
+ }
163
+ function applyStateToNode() {
164
+ const node = getNode();
165
+ if (!node) {
166
+ return;
167
+ }
168
+ node.setAttribute('data-zen-navigation-phase', shellState.phase);
169
+ if (shellState.navigationId === null) {
170
+ node.removeAttribute('data-zen-navigation-id');
171
+ }
172
+ else {
173
+ node.setAttribute('data-zen-navigation-id', String(shellState.navigationId));
174
+ }
175
+ if (shellState.navigationType === null) {
176
+ node.removeAttribute('data-zen-navigation-type');
177
+ }
178
+ else {
179
+ node.setAttribute('data-zen-navigation-type', shellState.navigationType);
180
+ }
181
+ }
182
+ function clearNodeState() {
183
+ const node = getNode();
184
+ if (!node) {
185
+ return;
186
+ }
187
+ node.removeAttribute('data-zen-navigation-phase');
188
+ node.removeAttribute('data-zen-navigation-id');
189
+ node.removeAttribute('data-zen-navigation-type');
190
+ }
191
+ function notifyStateChange(previousState) {
192
+ if (typeof normalizedOptions.onStateChange !== 'function') {
193
+ return;
194
+ }
195
+ normalizedOptions.onStateChange(getState(), {
196
+ previousState: cloneState(previousState)
197
+ });
198
+ }
199
+ function setState(nextState, forceApply = false) {
200
+ const previousState = cloneState(shellState);
201
+ const changed = previousState.phase !== nextState.phase ||
202
+ previousState.navigationId !== nextState.navigationId ||
203
+ previousState.navigationType !== nextState.navigationType;
204
+ if (!changed && !forceApply) {
205
+ return;
206
+ }
207
+ shellState = cloneState(nextState);
208
+ if (mounted) {
209
+ applyStateToNode();
210
+ }
211
+ if (changed) {
212
+ notifyStateChange(previousState);
213
+ }
214
+ }
215
+ function cancelPendingPhaseWait() {
216
+ if (!pendingPhaseWait) {
217
+ return;
218
+ }
219
+ pendingPhaseWait.cancel();
220
+ pendingPhaseWait = null;
221
+ }
222
+ function resetShellState() {
223
+ phaseEpoch += 1;
224
+ cancelPendingPhaseWait();
225
+ setState({
226
+ phase: 'idle',
227
+ navigationId: null,
228
+ navigationType: null
229
+ });
230
+ }
231
+ function waitForPhaseSettlement(nextPhase, payload) {
232
+ phaseEpoch += 1;
233
+ cancelPendingPhaseWait();
234
+ const navigationId = readNavigationId(payload);
235
+ const navigationType = normalizeNavigationType(payload?.navigationType);
236
+ setState({
237
+ phase: nextPhase,
238
+ navigationId,
239
+ navigationType
240
+ });
241
+ const node = getNode();
242
+ const timeoutMs = resolveFallbackTimeoutMs(node, normalizedOptions.timeoutMs);
243
+ if (!mounted || !node || timeoutMs === 0) {
244
+ return Promise.resolve();
245
+ }
246
+ const timerApi = getTimerApi(node);
247
+ const activeEpoch = phaseEpoch;
248
+ return new Promise((resolve) => {
249
+ const disposers = [];
250
+ let settled = false;
251
+ let timeoutId = null;
252
+ const finish = () => {
253
+ if (settled) {
254
+ return;
255
+ }
256
+ settled = true;
257
+ while (disposers.length > 0) {
258
+ const dispose = disposers.pop();
259
+ try {
260
+ dispose();
261
+ }
262
+ catch {
263
+ }
264
+ }
265
+ if (timeoutId !== null) {
266
+ timerApi.clearTimeout(timeoutId);
267
+ timeoutId = null;
268
+ }
269
+ if (pendingPhaseWait === record) {
270
+ pendingPhaseWait = null;
271
+ }
272
+ resolve();
273
+ };
274
+ const handleEnd = (event) => {
275
+ if (activeEpoch !== phaseEpoch) {
276
+ return;
277
+ }
278
+ if (!isOwnedEvent(event, node)) {
279
+ return;
280
+ }
281
+ finish();
282
+ };
283
+ disposers.push(addOwnedListener(node, 'transitionend', handleEnd));
284
+ disposers.push(addOwnedListener(node, 'animationend', handleEnd));
285
+ timeoutId = timerApi.setTimeout(finish, timeoutMs);
286
+ const record = {
287
+ cancel() {
288
+ finish();
289
+ }
290
+ };
291
+ pendingPhaseWait = record;
292
+ });
293
+ }
294
+ async function handlePhase(phase, payload) {
295
+ if (!mounted || !isLifecyclePayload(payload)) {
296
+ return;
297
+ }
298
+ await waitForPhaseSettlement(phase, payload);
299
+ if (!mounted) {
300
+ return;
301
+ }
302
+ const activeNavigationId = readNavigationId(payload);
303
+ if (activeNavigationId !== null && shellState.navigationId !== activeNavigationId) {
304
+ return;
305
+ }
306
+ if (phase === 'entering') {
307
+ setState({
308
+ phase: 'idle',
309
+ navigationId: null,
310
+ navigationType: null
311
+ });
312
+ }
313
+ }
314
+ function shouldResetForPayload(payload) {
315
+ if (!mounted || !isLifecyclePayload(payload)) {
316
+ return false;
317
+ }
318
+ const navigationId = readNavigationId(payload);
319
+ if (navigationId === null) {
320
+ return shellState.phase !== 'idle';
321
+ }
322
+ return shellState.navigationId === navigationId;
323
+ }
324
+ function installRouteListeners() {
325
+ if (routeDisposers.length > 0) {
326
+ return;
327
+ }
328
+ const subscriptions = [
329
+ ['navigation:before-leave', (payload) => handlePhase('leaving', payload)],
330
+ ['navigation:before-swap', (payload) => handlePhase('swapping', payload)],
331
+ ['navigation:before-enter', (payload) => handlePhase('entering', payload)],
332
+ ['navigation:abort', (payload) => {
333
+ if (shouldResetForPayload(payload)) {
334
+ resetShellState();
335
+ }
336
+ }],
337
+ ['navigation:error', (payload) => {
338
+ if (shouldResetForPayload(payload)) {
339
+ resetShellState();
340
+ }
341
+ }]
342
+ ];
343
+ for (let index = 0; index < subscriptions.length; index += 1) {
344
+ const [eventName, handler] = subscriptions[index];
345
+ on(eventName, handler);
346
+ routeDisposers.push(() => {
347
+ off(eventName, handler);
348
+ });
349
+ }
350
+ }
351
+ function destroy() {
352
+ cancelPendingPhaseWait();
353
+ while (routeDisposers.length > 0) {
354
+ const dispose = routeDisposers.pop();
355
+ try {
356
+ dispose();
357
+ }
358
+ catch {
359
+ }
360
+ }
361
+ const previousState = cloneState(shellState);
362
+ mounted = false;
363
+ shellState = {
364
+ phase: 'idle',
365
+ navigationId: null,
366
+ navigationType: null
367
+ };
368
+ clearNodeState();
369
+ if (previousState.phase !== 'idle' || previousState.navigationId !== null || previousState.navigationType !== null) {
370
+ notifyStateChange(previousState);
371
+ }
372
+ }
373
+ function mount() {
374
+ destroy();
375
+ mounted = true;
376
+ installRouteListeners();
377
+ setState({
378
+ phase: 'idle',
379
+ navigationId: null,
380
+ navigationType: null
381
+ }, true);
382
+ return destroy;
383
+ }
384
+ return {
385
+ mount,
386
+ destroy,
387
+ getPhase() {
388
+ return shellState.phase;
389
+ },
390
+ getState
391
+ };
392
+ }
package/dist/router.js CHANGED
@@ -14,7 +14,7 @@
14
14
  import { _dispatchRouteChange } from './events.js';
15
15
  import { current, listen } from './history.js';
16
16
  import { matchRoute } from './match.js';
17
- import { _setNavigationResolver } from './navigate.js';
17
+ import { _setNavigationResolver, _setRefreshResolver } from './navigate.js';
18
18
  export function createRouter(config) {
19
19
  const { routes, container } = config;
20
20
  const mountFn = typeof config.mount === 'function' ? config.mount : null;
@@ -28,9 +28,12 @@ export function createRouter(config) {
28
28
  let unlisten = null;
29
29
  let started = false;
30
30
  let hasMounted = false;
31
- async function resolvePath(path) {
31
+ async function resolvePath(path, options = {}) {
32
32
  const result = matchRoute(routes, path);
33
33
  if (!result) {
34
+ if (options.failOnUnmatched) {
35
+ throw new Error('[Zenith Router] refreshCurrentRoute() requires a current matched Zenith page route');
36
+ }
34
37
  _dispatchRouteChange({ path, matched: false });
35
38
  return;
36
39
  }
@@ -53,6 +56,9 @@ export function createRouter(config) {
53
56
  return;
54
57
  started = true;
55
58
  _setNavigationResolver(resolvePath);
59
+ _setRefreshResolver(async () => {
60
+ await resolvePath(current(), { failOnUnmatched: true });
61
+ });
56
62
  unlisten = listen((path) => {
57
63
  void resolvePath(path);
58
64
  });
@@ -64,6 +70,7 @@ export function createRouter(config) {
64
70
  unlisten = null;
65
71
  }
66
72
  _setNavigationResolver(null);
73
+ _setRefreshResolver(null);
67
74
  started = false;
68
75
  }
69
76
  return { start, destroy };
package/index.d.ts CHANGED
@@ -1,11 +1,26 @@
1
+ export type RouteDownloadBody = string | Uint8Array | ArrayBuffer;
2
+
3
+ export interface RouteDownloadOptions {
4
+ filename: string;
5
+ contentType?: string;
6
+ }
7
+
1
8
  export type RouteResult =
2
9
  | { kind: "allow" }
3
10
  | { kind: "redirect"; location: string; status?: number }
4
11
  | { kind: "deny"; status: 401 | 403 | 404; message?: string }
5
- | { kind: "data"; data: any };
12
+ | { kind: "data"; data: any }
13
+ | { kind: "invalid"; data: any; status: 400 | 422 }
14
+ | { kind: "json"; data: any; status?: number }
15
+ | { kind: "text"; body: string; status?: number }
16
+ | { kind: "download"; filename: string; contentType: string; status?: 200 };
6
17
 
7
18
  export type GuardResult = Extract<RouteResult, { kind: "allow" | "redirect" | "deny" }>;
8
19
  export type LoadResult = Extract<RouteResult, { kind: "data" | "redirect" | "deny" }>;
20
+ export type RouteSession = Record<string, unknown>;
21
+ export type RequireSessionOptions =
22
+ | { redirectTo: string; status?: 302 | 303 | 307 }
23
+ | { deny: 401 | 403 | 404; message?: string };
9
24
 
10
25
  export interface RouteContext {
11
26
  params: Record<string, string>;
@@ -17,17 +32,24 @@ export interface RouteContext {
17
32
  route: { id: string; pattern: string; file: string };
18
33
  env: Record<string, string>;
19
34
  auth: {
20
- getSession(ctx: RouteContext): Promise<any>;
21
- requireSession(ctx: RouteContext): Promise<void>;
35
+ getSession(): Promise<RouteSession | null>;
36
+ requireSession(options: RequireSessionOptions): Promise<RouteSession>;
37
+ signIn(sessionObject: RouteSession): Promise<void>;
38
+ signOut(): Promise<void>;
22
39
  };
23
40
  allow(): { kind: "allow" };
24
41
  redirect(location: string, status?: number): { kind: "redirect"; location: string; status: number };
25
42
  deny(status: 401 | 403 | 404, message?: string): { kind: "deny"; status: 401 | 403 | 404; message?: string };
26
43
  data(payload: any): { kind: "data"; data: any };
44
+ invalid(payload: any, status?: 400 | 422): { kind: "invalid"; data: any; status: 400 | 422 };
45
+ json(payload: any, status?: number): { kind: "json"; data: any; status: number };
46
+ text(body: string, status?: number): { kind: "text"; body: string; status: number };
47
+ download(body: RouteDownloadBody, options: RouteDownloadOptions): { kind: "download"; filename: string; contentType: string; status: 200 };
27
48
  }
28
49
 
29
50
  export declare function createRouter(config: { routes: any[]; container: HTMLElement }): { start: () => Promise<void>; destroy: () => void; };
30
51
  export declare function navigate(path: string): Promise<void>;
52
+ export declare function refreshCurrentRoute(): Promise<void>;
31
53
  export declare function back(): void;
32
54
  export declare function forward(): void;
33
55
  export declare function getCurrentPath(): string;
@@ -41,7 +63,26 @@ export interface RouteProtectionPolicy {
41
63
  forbiddenPath?: string;
42
64
  }
43
65
 
44
- export type NavigationType = "push" | "pop";
66
+ export type NavigationType = "push" | "pop" | "refresh";
67
+ export type NavigationShellPhase = "idle" | "leaving" | "swapping" | "entering";
68
+
69
+ export interface NavigationShellState {
70
+ phase: NavigationShellPhase;
71
+ navigationId: number | null;
72
+ navigationType: NavigationType | null;
73
+ }
74
+
75
+ export interface NavigationShellOptions {
76
+ timeoutMs?: number;
77
+ onStateChange?: (state: NavigationShellState, context: { previousState: NavigationShellState }) => void;
78
+ }
79
+
80
+ export interface NavigationShellController {
81
+ mount(): () => void;
82
+ destroy(): void;
83
+ getPhase(): NavigationShellPhase;
84
+ getState(): NavigationShellState;
85
+ }
45
86
 
46
87
  export interface NavigationLifecyclePayload {
47
88
  navigationId: number;
@@ -95,3 +136,4 @@ export type RouteEventName =
95
136
  export declare function setRouteProtectionPolicy(policy: RouteProtectionPolicy): void;
96
137
  export declare function on(eventName: RouteEventName, handler: RouteEventHandler): void;
97
138
  export declare function off(eventName: RouteEventName, handler: RouteEventHandler): void;
139
+ export declare function zenNavigationShell(ref: { current?: Element | null }, options?: NavigationShellOptions | null): NavigationShellController;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zenithbuild/router",
3
- "version": "0.7.4",
3
+ "version": "0.7.5",
4
4
  "description": "File-based SPA router for Zenith framework with deterministic, compile-time route resolution",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/template-core.js CHANGED
@@ -437,6 +437,14 @@ function resolveScrollTarget(targetUrl, historyMode, popstateState) {
437
437
  const saved = readStoredScroll(popstateState);
438
438
  return { mode: "restore", x: saved.x, y: saved.y, focusTarget: null };
439
439
  }
440
+ if (historyMode === "refresh") {
441
+ return {
442
+ mode: "restore",
443
+ x: window.scrollX || window.pageXOffset || 0,
444
+ y: window.scrollY || window.pageYOffset || 0,
445
+ focusTarget: null
446
+ };
447
+ }
440
448
  return { mode: "top", x: 0, y: 0, focusTarget: null };
441
449
  }
442
450
 
package/template-form.js CHANGED
@@ -36,15 +36,6 @@ function resolveFormMethod(form, submitter) {
36
36
  );
37
37
  }
38
38
 
39
- function resolveFormEnctype(form, submitter) {
40
- return String(
41
- readSubmitOverride(submitter, "formenctype", "formEnctype") ||
42
- form.getAttribute("enctype") ||
43
- form.enctype ||
44
- "application/x-www-form-urlencoded"
45
- ).toLowerCase();
46
- }
47
-
48
39
  function createFormSubmissionPayload(form, submitter) {
49
40
  try {
50
41
  return submitter ? new FormData(form, submitter) : new FormData(form);
@@ -63,7 +54,6 @@ function shouldEnhanceForm(form, submitter) {
63
54
  const target = resolveFormTargetValue(form, submitter);
64
55
  if (target && target !== "_self") return false;
65
56
  if (resolveFormMethod(form, submitter) !== "POST") return false;
66
- if (resolveFormEnctype(form, submitter).includes("multipart/form-data")) return false;
67
57
 
68
58
  const targetUrl = resolveFormTargetUrl(form, submitter);
69
59
  if (targetUrl.origin !== window.location.origin) return false;
@@ -98,6 +98,10 @@ function navigateViaBrowser(targetUrl, replace) {
98
98
  window.location.assign(targetUrl.href);
99
99
  }
100
100
 
101
+ function shouldReplaceBrowserNavigation(historyMode) {
102
+ return historyMode === "pop";
103
+ }
104
+
101
105
  function dispatchNavigationFallback(context, detail) {
102
106
  emitNavigationAbort(context, detail);
103
107
  }
@@ -231,7 +235,7 @@ async function performNavigation(targetUrl, historyMode, popstateState) {
231
235
  location: redirectUrl.href,
232
236
  status: checkResult.status
233
237
  });
234
- navigateViaBrowser(redirectUrl, historyMode === "pop");
238
+ navigateViaBrowser(redirectUrl, shouldReplaceBrowserNavigation(historyMode));
235
239
  return true;
236
240
  }
237
241
  if (checkResult.kind === "deny") {
@@ -239,7 +243,7 @@ async function performNavigation(targetUrl, historyMode, popstateState) {
239
243
  reason: "server-deny",
240
244
  status: checkResult.status
241
245
  });
242
- navigateViaBrowser(targetUrl, historyMode === "pop");
246
+ navigateViaBrowser(targetUrl, shouldReplaceBrowserNavigation(historyMode));
243
247
  return true;
244
248
  }
245
249
 
@@ -259,7 +263,7 @@ async function performNavigation(targetUrl, historyMode, popstateState) {
259
263
  location: redirectUrl.href,
260
264
  status: response.status
261
265
  });
262
- navigateViaBrowser(redirectUrl, historyMode === "pop");
266
+ navigateViaBrowser(redirectUrl, shouldReplaceBrowserNavigation(historyMode));
263
267
  return true;
264
268
  }
265
269
 
@@ -270,7 +274,7 @@ async function performNavigation(targetUrl, historyMode, popstateState) {
270
274
  reason: "http-status",
271
275
  status: response.status
272
276
  });
273
- navigateViaBrowser(targetUrl, historyMode === "pop");
277
+ navigateViaBrowser(targetUrl, shouldReplaceBrowserNavigation(historyMode));
274
278
  return true;
275
279
  }
276
280
  if (!isHtmlResponse(response)) {
@@ -278,7 +282,7 @@ async function performNavigation(targetUrl, historyMode, popstateState) {
278
282
  reason: "non-html",
279
283
  status: response.status
280
284
  });
281
- navigateViaBrowser(targetUrl, historyMode === "pop");
285
+ navigateViaBrowser(targetUrl, shouldReplaceBrowserNavigation(historyMode));
282
286
  return true;
283
287
  }
284
288
 
@@ -287,7 +291,7 @@ async function performNavigation(targetUrl, historyMode, popstateState) {
287
291
  dispatchNavigationFallback(context, {
288
292
  reason: "document-parse"
289
293
  });
290
- navigateViaBrowser(targetUrl, historyMode === "pop");
294
+ navigateViaBrowser(targetUrl, shouldReplaceBrowserNavigation(historyMode));
291
295
  return true;
292
296
  }
293
297
  const committed = await commitNavigationDocument(
@@ -317,7 +321,7 @@ async function performNavigation(targetUrl, historyMode, popstateState) {
317
321
  reason: "runtime-failure",
318
322
  historyCommitted
319
323
  });
320
- navigateViaBrowser(targetUrl, historyMode === "pop" || historyCommitted);
324
+ navigateViaBrowser(targetUrl, shouldReplaceBrowserNavigation(historyMode) || historyCommitted);
321
325
  return true;
322
326
  }
323
327
  dispatchNavigationFallback(context, context.abortReason || {
package/template.js CHANGED
@@ -3,6 +3,7 @@ import { renderRouterDocumentSource } from './template-document.js';
3
3
  import { renderRouterFormSource } from './template-form.js';
4
4
  import { renderRouterLifecycleSource } from './template-lifecycle.js';
5
5
  import { renderRouterNavigationSource } from './template-navigation.js';
6
+ import { renderRouterRefreshSource } from './template-refresh.js';
6
7
 
7
8
  function normalizeManifestJson(manifestJson) {
8
9
  return manifestJson.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
@@ -36,5 +37,5 @@ export function renderRouterModule(opts) {
36
37
  const runtimeSpec = sanitizeImportSpecifier(runtimeImport);
37
38
  const coreSpec = sanitizeImportSpecifier(coreImport);
38
39
 
39
- return `${renderRouterCoreSource({ manifest, runtimeSpec, coreSpec, routeCheck })}\n\n${renderRouterDocumentSource()}\n\n${renderRouterLifecycleSource()}\n\n${renderRouterNavigationSource()}\n\n${renderRouterFormSource()}\n`;
40
+ return `${renderRouterCoreSource({ manifest, runtimeSpec, coreSpec, routeCheck })}\n\n${renderRouterDocumentSource()}\n\n${renderRouterLifecycleSource()}\n\n${renderRouterRefreshSource()}\n\n${renderRouterNavigationSource()}\n\n${renderRouterFormSource()}\n`;
40
41
  }