@ktjs/router 0.19.0 → 0.31.9

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,575 +0,0 @@
1
- var __ktjs_router__ = (function (exports) {
2
- 'use strict';
3
-
4
- /******************************************************************************
5
- Copyright (c) Microsoft Corporation.
6
-
7
- Permission to use, copy, modify, and/or distribute this software for any
8
- purpose with or without fee is hereby granted.
9
-
10
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
11
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
12
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
13
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
14
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
15
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
16
- PERFORMANCE OF THIS SOFTWARE.
17
- ***************************************************************************** */
18
- /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
19
-
20
-
21
- var __assign = function() {
22
- __assign = Object.assign || function __assign(t) {
23
- for (var s, i = 1, n = arguments.length; i < n; i++) {
24
- s = arguments[i];
25
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
26
- }
27
- return t;
28
- };
29
- return __assign.apply(this, arguments);
30
- };
31
-
32
- function __awaiter(thisArg, _arguments, P, generator) {
33
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
34
- return new (P || (P = Promise))(function (resolve, reject) {
35
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
36
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
37
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
38
- step((generator = generator.apply(thisArg, _arguments || [])).next());
39
- });
40
- }
41
-
42
- function __generator(thisArg, body) {
43
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
44
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
45
- function verb(n) { return function (v) { return step([n, v]); }; }
46
- function step(op) {
47
- if (f) throw new TypeError("Generator is already executing.");
48
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
49
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
50
- if (y = 0, t) op = [op[0] & 2, t.value];
51
- switch (op[0]) {
52
- case 0: case 1: t = op; break;
53
- case 4: _.label++; return { value: op[1], done: false };
54
- case 5: _.label++; y = op[1]; op = [0]; continue;
55
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
56
- default:
57
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
58
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
59
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
60
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
61
- if (t[2]) _.ops.pop();
62
- _.trys.pop(); continue;
63
- }
64
- op = body.call(thisArg, _);
65
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
66
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
67
- }
68
- }
69
-
70
- function __spreadArray(to, from, pack) {
71
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
72
- if (ar || !(i in from)) {
73
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
74
- ar[i] = from[i];
75
- }
76
- }
77
- return to.concat(ar || Array.prototype.slice.call(from));
78
- }
79
-
80
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
81
- var e = new Error(message);
82
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
83
- };
84
-
85
- // Cached native methods for performance optimization
86
-
87
- // Error handling utilities
88
- const $throw = (message) => {
89
- throw new Error('@ktjs/shared: ' + message);
90
- };
91
-
92
- // String manipulation utilities
93
- /**
94
- * Default empty function
95
- */
96
- const $emptyFn = (() => true);
97
-
98
- /**
99
- * Normalize path by joining parts and ensuring leading slash
100
- */
101
- const normalizePath = (...paths) => {
102
- const p = paths
103
- .map((p) => p.split('/'))
104
- .flat()
105
- .filter(Boolean);
106
- return '/' + p.join('/');
107
- };
108
- /**
109
- * Parse query string into object
110
- */
111
- const parseQuery = (queryString) => {
112
- const query = {};
113
- if (!queryString || queryString === '?') {
114
- return query;
115
- }
116
- const params = queryString.replace(/^\?/, '').split('&');
117
- for (const param of params) {
118
- const [key, value] = param.split('=');
119
- if (key) {
120
- query[decodeURIComponent(key)] = value ? decodeURIComponent(value) : '';
121
- }
122
- }
123
- return query;
124
- };
125
- /**
126
- * Build query string from object
127
- */
128
- const buildQuery = (query) => {
129
- const keys = Object.keys(query);
130
- if (keys.length === 0)
131
- return '';
132
- const params = keys.map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(query[key])}`).join('&');
133
- return `?${params}`;
134
- };
135
- /**
136
- * Substitute params into path pattern
137
- * @example '/user/:id' + {id: '123'} => '/user/123'
138
- */
139
- const emplaceParams = (path, params) => {
140
- let result = path;
141
- for (const key in params) {
142
- result = result.replace(`:${key}`, params[key]);
143
- }
144
- return result;
145
- };
146
- /**
147
- * Extract dynamic params from path using pattern
148
- * @example pattern: '/user/:id', path: '/user/123' => {id: '123'}
149
- */
150
- const extractParams = (pattern, path) => {
151
- const params = {};
152
- const patternParts = pattern.split('/');
153
- const pathParts = path.split('/');
154
- if (patternParts.length !== pathParts.length) {
155
- return null;
156
- }
157
- for (let i = 0; i < patternParts.length; i++) {
158
- const patternPart = patternParts[i];
159
- const pathPart = pathParts[i];
160
- if (patternPart.startsWith(':')) {
161
- const paramName = patternPart.slice(1);
162
- params[paramName] = pathPart;
163
- }
164
- else if (patternPart !== pathPart) {
165
- return null;
166
- }
167
- }
168
- return params;
169
- };
170
-
171
- // Shared utilities and cached native methods for kt.js framework
172
- // Re-export all utilities
173
- Object.defineProperty(window, '@ktjs/shared', { value: '0.19.0' });
174
-
175
- /**
176
- * Route matcher for finding matching routes and extracting params
177
- */
178
- var createMatcher = function (routes) {
179
- var nameMap = {};
180
- for (var i = 0; i < routes.length; i++) {
181
- var route = routes[i];
182
- if (route.name !== undefined) {
183
- if (route.name in nameMap) {
184
- $throw("Duplicate route name detected: '".concat(route.name, "'"));
185
- }
186
- nameMap[route.name] = route;
187
- }
188
- }
189
- /**
190
- * Find route by name
191
- */
192
- var findByName = function (name) {
193
- var _a;
194
- return (_a = nameMap[name]) !== null && _a !== void 0 ? _a : null;
195
- };
196
- /**
197
- * Match path against all routes
198
- */
199
- var match = function (path) {
200
- var normalizedPath = normalizePath(path);
201
- // Try exact match first
202
- for (var _i = 0, routes_1 = routes; _i < routes_1.length; _i++) {
203
- var route = routes_1[_i];
204
- if (route.path === normalizedPath) {
205
- return {
206
- route: route,
207
- params: {},
208
- result: getMatchedChain(route),
209
- };
210
- }
211
- }
212
- // Try dynamic routes
213
- for (var _a = 0, routes_2 = routes; _a < routes_2.length; _a++) {
214
- var route = routes_2[_a];
215
- if (route.path.includes(':')) {
216
- var params = extractParams(route.path, normalizedPath);
217
- if (params) {
218
- return {
219
- route: route,
220
- params: params,
221
- result: getMatchedChain(route),
222
- };
223
- }
224
- }
225
- }
226
- return null;
227
- };
228
- /**
229
- * Get chain of matched routes (for nested routes)
230
- * - parent roots ahead
231
- */
232
- var getMatchedChain = function (route) {
233
- var matched = [route];
234
- var path = route.path;
235
- // Find parent routes by path prefix matching
236
- for (var i = 0; i < routes.length; i++) {
237
- var r = routes[i];
238
- if (r !== route && path.startsWith(r.path) && path !== r.path) {
239
- matched.push(r);
240
- }
241
- }
242
- return matched.reverse();
243
- };
244
- return {
245
- findByName: findByName,
246
- match: match,
247
- };
248
- };
249
-
250
- /**
251
- * Create a router view container that automatically renders route components
252
- */
253
- function KTRouter(_a) {
254
- var router = _a.router;
255
- var view = document.createElement('kt-router-view');
256
- router.setRouterView(view);
257
- return view;
258
- }
259
-
260
- /**
261
- * Create a new router instance
262
- */
263
- var createRouter = function (_a) {
264
- var _b = _a.beforeEach, beforeEach = _b === void 0 ? $emptyFn : _b, _c = _a.afterEach, afterEach = _c === void 0 ? $emptyFn : _c, _d = _a.onNotFound, onNotFound = _d === void 0 ? $emptyFn : _d, _e = _a.onError, onError = _e === void 0 ? $emptyFn : _e, _f = _a.prefix, prefix = _f === void 0 ? '' : _f, rawRoutes = _a.routes;
265
- // # private values
266
- var routes = [];
267
- var history = [];
268
- var routerView = null;
269
- var current = null;
270
- // # methods
271
- var normalize = function (rawRoutes, parentPath) {
272
- return rawRoutes.map(function (route) {
273
- var _a, _b, _c, _d;
274
- var path = normalizePath(parentPath, route.path);
275
- var normalized = {
276
- path: prefix + path,
277
- name: (_a = route.name) !== null && _a !== void 0 ? _a : '',
278
- meta: (_b = route.meta) !== null && _b !== void 0 ? _b : {},
279
- beforeEnter: (_c = route.beforeEnter) !== null && _c !== void 0 ? _c : $emptyFn,
280
- after: (_d = route.after) !== null && _d !== void 0 ? _d : $emptyFn,
281
- children: route.children ? normalize(route.children, path) : [],
282
- component: route.component,
283
- };
284
- // directly push the normalized route to the list
285
- // avoid flatten them again
286
- routes.push(normalized);
287
- return normalized;
288
- });
289
- };
290
- var guard = function (to, from, guardLevel) { return __awaiter(void 0, void 0, void 0, function () {
291
- var result, targetRoute, result, error_1;
292
- return __generator(this, function (_a) {
293
- switch (_a.label) {
294
- case 0:
295
- _a.trys.push([0, 5, , 6]);
296
- if (guardLevel === 0 /* GuardLevel.None */) {
297
- return [2 /*return*/, { continue: true }];
298
- }
299
- if (!(guardLevel & 1 /* GuardLevel.Global */)) return [3 /*break*/, 2];
300
- return [4 /*yield*/, beforeEach(to, from)];
301
- case 1:
302
- result = _a.sent();
303
- if (result === false) {
304
- return [2 /*return*/, { continue: false }];
305
- }
306
- if (typeof result === 'string') {
307
- return [2 /*return*/, { continue: false, redirectTo: { path: result } }];
308
- }
309
- if (result && typeof result === 'object') {
310
- return [2 /*return*/, { continue: false, redirectTo: result }];
311
- }
312
- _a.label = 2;
313
- case 2:
314
- if (!(guardLevel & 2 /* GuardLevel.Route */)) return [3 /*break*/, 4];
315
- targetRoute = to.matched[to.matched.length - 1];
316
- return [4 /*yield*/, targetRoute.beforeEnter(to)];
317
- case 3:
318
- result = _a.sent();
319
- if (result === false) {
320
- return [2 /*return*/, { continue: false }];
321
- }
322
- if (typeof result === 'string') {
323
- return [2 /*return*/, { continue: false, redirectTo: { path: result } }];
324
- }
325
- if (result && typeof result === 'object') {
326
- return [2 /*return*/, { continue: false, redirectTo: result }];
327
- }
328
- _a.label = 4;
329
- case 4: return [2 /*return*/, { continue: true }];
330
- case 5:
331
- error_1 = _a.sent();
332
- onError(error_1);
333
- return [2 /*return*/, { continue: false }];
334
- case 6: return [2 /*return*/];
335
- }
336
- });
337
- }); };
338
- var navigatePrepare = function (options) {
339
- var _a, _b, _c, _d, _e, _f;
340
- // Resolve target route
341
- var targetPath;
342
- var targetRoute;
343
- if (options.name) {
344
- targetRoute = findByName(options.name);
345
- if (!targetRoute) {
346
- $throw("Route not found: ".concat(options.name));
347
- }
348
- targetPath = targetRoute.path;
349
- }
350
- else if (options.path) {
351
- targetPath = normalizePath(options.path);
352
- targetRoute = (_a = match(targetPath)) === null || _a === void 0 ? void 0 : _a.route;
353
- }
354
- else {
355
- $throw("Either path or name must be provided");
356
- }
357
- // Substitute params
358
- if (options.params) {
359
- targetPath = emplaceParams(targetPath, options.params);
360
- }
361
- // Match final path
362
- var matched = match(targetPath);
363
- if (!matched) {
364
- onNotFound(targetPath);
365
- return null;
366
- }
367
- // Build route context
368
- var queryString = options.query ? buildQuery(options.query) : '';
369
- var fullPath = targetPath + queryString;
370
- var to = {
371
- path: targetPath,
372
- name: matched.route.name,
373
- params: __assign(__assign({}, matched.params), ((_b = options.params) !== null && _b !== void 0 ? _b : {})),
374
- query: (_c = options.query) !== null && _c !== void 0 ? _c : {},
375
- meta: (_d = matched.route.meta) !== null && _d !== void 0 ? _d : {},
376
- matched: matched.result,
377
- };
378
- return {
379
- guardLevel: (_e = options.guardLevel) !== null && _e !== void 0 ? _e : 15 /* GuardLevel.Default */,
380
- replace: (_f = options.replace) !== null && _f !== void 0 ? _f : false,
381
- to: to,
382
- fullPath: fullPath,
383
- };
384
- };
385
- var navigate = function (options_1) {
386
- var args_1 = [];
387
- for (var _i = 1; _i < arguments.length; _i++) {
388
- args_1[_i - 1] = arguments[_i];
389
- }
390
- return __awaiter(void 0, __spreadArray([options_1], args_1, true), void 0, function (options, redirectCount) {
391
- var prep, guardLevel, replace, to, fullPath, guardResult, hashUrl, route, element, error_2;
392
- var _a;
393
- if (redirectCount === void 0) { redirectCount = 0; }
394
- return __generator(this, function (_b) {
395
- switch (_b.label) {
396
- case 0:
397
- _b.trys.push([0, 7, , 8]);
398
- // Prevent infinite redirect loop
399
- if (redirectCount > 10) {
400
- onError(new Error('Maximum redirect count exceeded'));
401
- return [2 /*return*/, false];
402
- }
403
- prep = navigatePrepare(options);
404
- if (!prep) {
405
- return [2 /*return*/, false];
406
- }
407
- guardLevel = prep.guardLevel, replace = prep.replace, to = prep.to, fullPath = prep.fullPath;
408
- return [4 /*yield*/, guard(to, current, guardLevel)];
409
- case 1:
410
- guardResult = _b.sent();
411
- if (!!guardResult.continue) return [3 /*break*/, 4];
412
- if (!guardResult.redirectTo) return [3 /*break*/, 3];
413
- return [4 /*yield*/, navigate(guardResult.redirectTo, redirectCount + 1)];
414
- case 2: return [2 /*return*/, _b.sent()];
415
- case 3: return [2 /*return*/, false];
416
- case 4:
417
- hashUrl = '#' + fullPath;
418
- if (replace) {
419
- window.location.replace(hashUrl);
420
- }
421
- else {
422
- window.location.hash = fullPath;
423
- }
424
- current = to;
425
- if (replace) {
426
- if (history.length > 0) {
427
- history[history.length - 1] = to;
428
- }
429
- else {
430
- history.push(to);
431
- }
432
- }
433
- else {
434
- history.push(to);
435
- }
436
- if (!(routerView && to.matched.length > 0)) return [3 /*break*/, 6];
437
- route = to.matched[to.matched.length - 1];
438
- if (!route.component) return [3 /*break*/, 6];
439
- return [4 /*yield*/, route.component()];
440
- case 5:
441
- element = _b.sent();
442
- routerView.innerHTML = '';
443
- routerView.appendChild(element);
444
- _b.label = 6;
445
- case 6:
446
- executeAfterHooks(to, (_a = history[history.length - 2]) !== null && _a !== void 0 ? _a : null);
447
- return [2 /*return*/, true];
448
- case 7:
449
- error_2 = _b.sent();
450
- onError(error_2);
451
- return [2 /*return*/, false];
452
- case 8: return [2 /*return*/];
453
- }
454
- });
455
- });
456
- };
457
- var executeAfterHooks = function (to, from) { return __awaiter(void 0, void 0, void 0, function () {
458
- var targetRoute;
459
- return __generator(this, function (_a) {
460
- switch (_a.label) {
461
- case 0:
462
- targetRoute = to.matched[to.matched.length - 1];
463
- return [4 /*yield*/, targetRoute.after(to)];
464
- case 1:
465
- _a.sent();
466
- return [4 /*yield*/, afterEach(to, from)];
467
- case 2:
468
- _a.sent();
469
- return [2 /*return*/];
470
- }
471
- });
472
- }); };
473
- /**
474
- * Normalize navigation argument
475
- */
476
- var normalizeLocation = function (loc) {
477
- if (typeof loc !== 'string') {
478
- return loc;
479
- }
480
- var _a = loc.split('?'), path = _a[0], queryString = _a[1];
481
- return {
482
- path: path,
483
- query: queryString ? parseQuery(queryString) : undefined,
484
- };
485
- };
486
- // # register events
487
- window.addEventListener('hashchange', function () {
488
- var _a, _b;
489
- var hash = window.location.hash.slice(1);
490
- var path = hash.split('?')[0];
491
- var normalizedPath = normalizePath(path);
492
- if (current && current.path === normalizedPath) {
493
- return;
494
- }
495
- // render route for new hash without adding extra history entry
496
- var matched = match(normalizedPath);
497
- if (!matched) {
498
- onNotFound(normalizedPath);
499
- return;
500
- }
501
- var queryString = window.location.hash.slice(1).split('?')[1];
502
- var to = {
503
- path: normalizedPath,
504
- name: matched.route.name,
505
- params: matched.params,
506
- query: queryString ? parseQuery(queryString) : {},
507
- meta: (_a = matched.route.meta) !== null && _a !== void 0 ? _a : {},
508
- matched: matched.result,
509
- };
510
- // apply without modifying browser history
511
- current = to;
512
- history.push(to);
513
- if (routerView && to.matched.length > 0) {
514
- var route = to.matched[to.matched.length - 1];
515
- if (route.component) {
516
- var element = route.component();
517
- if (element instanceof Promise) {
518
- element.then(function (el) {
519
- routerView.innerHTML = '';
520
- routerView.appendChild(el);
521
- });
522
- }
523
- else {
524
- routerView.innerHTML = '';
525
- routerView.appendChild(element);
526
- }
527
- }
528
- }
529
- executeAfterHooks(to, (_b = history[history.length - 2]) !== null && _b !== void 0 ? _b : null);
530
- });
531
- // # initialize
532
- var instance = {
533
- get current() {
534
- return current;
535
- },
536
- get history() {
537
- return history.concat();
538
- },
539
- setRouterView: function (view) {
540
- routerView = view;
541
- },
542
- push: function (location) {
543
- var options = normalizeLocation(location);
544
- return navigate(options);
545
- },
546
- silentPush: function (location) {
547
- var options = normalizeLocation(location);
548
- return navigate(__assign(__assign({}, options), { guardLevel: 2 /* GuardLevel.Route */ }));
549
- },
550
- replace: function (location) {
551
- var options = normalizeLocation(location);
552
- return navigate(__assign(__assign({}, options), { replace: true }));
553
- },
554
- back: function () {
555
- window.history.back();
556
- },
557
- forward: function () {
558
- window.history.forward();
559
- },
560
- };
561
- normalize(rawRoutes, '/');
562
- var _g = createMatcher(routes), findByName = _g.findByName, match = _g.match;
563
- var currentHash = window.location.hash.slice(1);
564
- if (currentHash) {
565
- instance.push(currentHash);
566
- }
567
- return instance;
568
- };
569
-
570
- exports.KTRouter = KTRouter;
571
- exports.createRouter = createRouter;
572
-
573
- return exports;
574
-
575
- })({});