k99 0.6.0-alpha.5 → 0.6.0-alpha.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/browser.cjs +1 -1
- package/browser.d.ts +1 -1
- package/browser.js +1 -1
- package/browser.min.js +1 -1
- package/browser.min.mjs +1 -1
- package/browser.mjs +1 -1
- package/cli/index.cjs +2 -2
- package/cli/index.d.ts +1 -1
- package/cli.cjs +1 -1
- package/index.cjs +64 -33
- package/index.d.ts +100 -2
- package/index.js +64 -33
- package/index.min.js +2 -2
- package/index.min.mjs +2 -2
- package/index.mjs +64 -33
- package/node/index.cjs +20 -1
- package/node/index.d.ts +6 -3
- package/package.json +1 -1
- package/services.cjs +1 -1
- package/services.d.ts +1 -1
- package/services.js +1 -1
- package/services.min.js +1 -1
- package/services.min.mjs +1 -1
- package/services.mjs +1 -1
- package/starter.cjs +1 -1
package/browser.cjs
CHANGED
package/browser.d.ts
CHANGED
package/browser.js
CHANGED
package/browser.min.js
CHANGED
package/browser.min.mjs
CHANGED
package/browser.mjs
CHANGED
package/cli/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* k99 v0.6.0-alpha.
|
|
2
|
+
* k99 v0.6.0-alpha.6
|
|
3
3
|
* (c) 2019-2023 猛火Fierflame
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
@@ -106,7 +106,7 @@ async function exec({
|
|
|
106
106
|
cfg.dependencies = {};
|
|
107
107
|
}
|
|
108
108
|
if (!cfg.dependencies.k99) {
|
|
109
|
-
cfg.dependencies.k99 = '^0.6.0-alpha.
|
|
109
|
+
cfg.dependencies.k99 = '^0.6.0-alpha.6';
|
|
110
110
|
}
|
|
111
111
|
await fsPromise__namespace.writeFile('package.json', JSON.stringify(cfg, null, 2));
|
|
112
112
|
}
|
package/cli/index.d.ts
CHANGED
package/cli.cjs
CHANGED
package/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* k99 v0.6.0-alpha.
|
|
2
|
+
* k99 v0.6.0-alpha.6
|
|
3
3
|
* (c) 2019-2023 猛火Fierflame
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
@@ -855,6 +855,11 @@ function createContext({
|
|
|
855
855
|
configurable: true,
|
|
856
856
|
enumerable: true
|
|
857
857
|
},
|
|
858
|
+
currentService: {
|
|
859
|
+
value: service,
|
|
860
|
+
configurable: true,
|
|
861
|
+
enumerable: true
|
|
862
|
+
},
|
|
858
863
|
state: {
|
|
859
864
|
configurable: true,
|
|
860
865
|
enumerable: true,
|
|
@@ -1159,6 +1164,9 @@ function merge(...handlers) {
|
|
|
1159
1164
|
|
|
1160
1165
|
function service(exec, destroy, options) {
|
|
1161
1166
|
const service = function (ctx, ...any) {
|
|
1167
|
+
if (ctx.currentService !== service) {
|
|
1168
|
+
return ctx.service(service, ...any);
|
|
1169
|
+
}
|
|
1162
1170
|
if (!ctx.destroying) {
|
|
1163
1171
|
return exec(ctx, ...any);
|
|
1164
1172
|
}
|
|
@@ -1177,6 +1185,9 @@ function service(exec, destroy, options) {
|
|
|
1177
1185
|
|
|
1178
1186
|
function stateService(init, destroy, exec, options) {
|
|
1179
1187
|
const service = function (ctx) {
|
|
1188
|
+
if (ctx.currentService !== service) {
|
|
1189
|
+
return ctx.service(service);
|
|
1190
|
+
}
|
|
1180
1191
|
if (!ctx.destroying) {
|
|
1181
1192
|
let {
|
|
1182
1193
|
state
|
|
@@ -1205,6 +1216,9 @@ function stateService(init, destroy, exec, options) {
|
|
|
1205
1216
|
|
|
1206
1217
|
function storeService(destroy, exec, options) {
|
|
1207
1218
|
const service = function (ctx, ...s) {
|
|
1219
|
+
if (ctx.currentService !== service) {
|
|
1220
|
+
return ctx.service(service, ...s);
|
|
1221
|
+
}
|
|
1208
1222
|
if (!ctx.destroying) {
|
|
1209
1223
|
if (!s.length) {
|
|
1210
1224
|
return ctx.state;
|
|
@@ -1337,7 +1351,7 @@ function parse(p) {
|
|
|
1337
1351
|
}
|
|
1338
1352
|
let i = 0;
|
|
1339
1353
|
let count = 0;
|
|
1340
|
-
const pattern = ['^('];
|
|
1354
|
+
const pattern = ['^(?:'];
|
|
1341
1355
|
while (i < expression.length) {
|
|
1342
1356
|
const c = expression[i++];
|
|
1343
1357
|
pattern.push(c);
|
|
@@ -1444,12 +1458,7 @@ function toMatch(path, end) {
|
|
|
1444
1458
|
return path => exec(list, path, end);
|
|
1445
1459
|
}
|
|
1446
1460
|
|
|
1447
|
-
function
|
|
1448
|
-
const path = typeof a === 'string' ? a : '';
|
|
1449
|
-
const handler = [a, b].find(v => typeof v === 'function');
|
|
1450
|
-
if (!handler) {
|
|
1451
|
-
return () => {};
|
|
1452
|
-
}
|
|
1461
|
+
function bind(routes, methods, path, handler) {
|
|
1453
1462
|
const route = {
|
|
1454
1463
|
match: toMatch(path || '', true),
|
|
1455
1464
|
methods: new Set(methods),
|
|
@@ -1469,6 +1478,22 @@ function verb(routes, methods, a, b) {
|
|
|
1469
1478
|
routes.splice(index, 1);
|
|
1470
1479
|
};
|
|
1471
1480
|
}
|
|
1481
|
+
function verb(routes, methods, p) {
|
|
1482
|
+
if (!p.length) {
|
|
1483
|
+
return handler => bind(routes, methods, '', handler);
|
|
1484
|
+
}
|
|
1485
|
+
const [a, b] = p;
|
|
1486
|
+
if (a && typeof a === 'object') {
|
|
1487
|
+
const path = String.raw(a, ...p.slice(1));
|
|
1488
|
+
return handler => bind(routes, methods, path, handler);
|
|
1489
|
+
}
|
|
1490
|
+
const path = typeof a === 'string' ? a : '';
|
|
1491
|
+
const handler = [a, b].find(v => typeof v === 'function');
|
|
1492
|
+
if (!handler) {
|
|
1493
|
+
return handler => bind(routes, methods, path, handler);
|
|
1494
|
+
}
|
|
1495
|
+
return bind(routes, methods, path, handler);
|
|
1496
|
+
}
|
|
1472
1497
|
|
|
1473
1498
|
const methods = new Set(['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS']);
|
|
1474
1499
|
function isMethod(v) {
|
|
@@ -1484,6 +1509,14 @@ function getMethods(methods) {
|
|
|
1484
1509
|
return Array.from(methods).map(v => typeof v === 'string' && v.toUpperCase()).filter(isMethod);
|
|
1485
1510
|
}
|
|
1486
1511
|
|
|
1512
|
+
function bindRouter(routes, path, r) {
|
|
1513
|
+
const router = r instanceof Router ? r : typeof r === 'function' ? Router.create(r) : new ApiRouter();
|
|
1514
|
+
routes.push({
|
|
1515
|
+
match: toMatch(path, false),
|
|
1516
|
+
router
|
|
1517
|
+
});
|
|
1518
|
+
return router;
|
|
1519
|
+
}
|
|
1487
1520
|
class ApiRouter extends Router {
|
|
1488
1521
|
/** 路由列表 */
|
|
1489
1522
|
#routes = [];
|
|
@@ -1492,15 +1525,15 @@ class ApiRouter extends Router {
|
|
|
1492
1525
|
* @param router 要注册的子路由
|
|
1493
1526
|
*/
|
|
1494
1527
|
|
|
1495
|
-
route(
|
|
1496
|
-
const
|
|
1497
|
-
|
|
1528
|
+
route(...p) {
|
|
1529
|
+
const [a] = p;
|
|
1530
|
+
if (a && typeof a === 'object' && !(a instanceof Router)) {
|
|
1531
|
+
const path = String.raw(a, ...p.slice(1));
|
|
1532
|
+
return r => bindRouter(this.#routes, path, r);
|
|
1533
|
+
}
|
|
1498
1534
|
const path = typeof a === 'string' ? a : '';
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
router
|
|
1502
|
-
});
|
|
1503
|
-
return router;
|
|
1535
|
+
const r = typeof a === 'string' ? p[1] : a;
|
|
1536
|
+
return bindRouter(this.#routes, path, r);
|
|
1504
1537
|
}
|
|
1505
1538
|
*find(method, path) {
|
|
1506
1539
|
for (const route of Array.from(this.#routes)) {
|
|
@@ -1537,65 +1570,63 @@ class ApiRouter extends Router {
|
|
|
1537
1570
|
if (!allMethods.length) {
|
|
1538
1571
|
return () => {};
|
|
1539
1572
|
}
|
|
1540
|
-
return verb(this.#routes, allMethods, path, handler);
|
|
1573
|
+
return verb(this.#routes, allMethods, [path, handler]);
|
|
1541
1574
|
}
|
|
1542
1575
|
/**
|
|
1543
1576
|
* 注册 HTTP GET/POST/PUT/DELETE 处理函数
|
|
1544
1577
|
* @param handler 要注册的处理函数
|
|
1545
1578
|
*/
|
|
1546
1579
|
|
|
1547
|
-
match(
|
|
1548
|
-
|
|
1549
|
-
return verb(this.#routes, methods, path, handler);
|
|
1580
|
+
match(...p) {
|
|
1581
|
+
return verb(this.#routes, ['GET', 'POST', 'PUT', 'DELETE'], p);
|
|
1550
1582
|
}
|
|
1551
|
-
|
|
1552
1583
|
/**
|
|
1553
1584
|
* 注册 HTTP GET 处理函数
|
|
1554
1585
|
* @param handler 要注册的处理函数
|
|
1555
1586
|
*/
|
|
1556
1587
|
|
|
1557
|
-
get(
|
|
1558
|
-
return verb(this.#routes, ['GET'],
|
|
1588
|
+
get(...p) {
|
|
1589
|
+
return verb(this.#routes, ['GET'], p);
|
|
1559
1590
|
}
|
|
1560
1591
|
/**
|
|
1561
1592
|
* 注册 HTTP POST 处理函数
|
|
1562
1593
|
* @param handler 要注册的处理函数
|
|
1563
1594
|
*/
|
|
1564
1595
|
|
|
1565
|
-
post(
|
|
1566
|
-
return verb(this.#routes, ['POST'],
|
|
1596
|
+
post(...p) {
|
|
1597
|
+
return verb(this.#routes, ['POST'], p);
|
|
1567
1598
|
}
|
|
1568
1599
|
/**
|
|
1569
1600
|
* 注册 HTTP PUT 处理函数
|
|
1570
1601
|
* @param handler 要注册的处理函数
|
|
1571
1602
|
*/
|
|
1572
1603
|
|
|
1573
|
-
put(
|
|
1574
|
-
return verb(this.#routes, ['PUT'],
|
|
1604
|
+
put(...p) {
|
|
1605
|
+
return verb(this.#routes, ['PUT'], p);
|
|
1575
1606
|
}
|
|
1576
1607
|
/**
|
|
1577
1608
|
* 注册 HTTP DELETE 处理函数
|
|
1578
1609
|
* @param handler 要注册的处理函数
|
|
1579
1610
|
*/
|
|
1580
1611
|
|
|
1581
|
-
delete(
|
|
1582
|
-
return verb(this.#routes, ['DELETE'],
|
|
1612
|
+
delete(...p) {
|
|
1613
|
+
return verb(this.#routes, ['DELETE'], p);
|
|
1583
1614
|
}
|
|
1584
1615
|
/**
|
|
1585
1616
|
* 注册 HTTP HEAD 处理函数
|
|
1586
1617
|
* @param handler 要注册的处理函数
|
|
1587
1618
|
*/
|
|
1588
1619
|
|
|
1589
|
-
head(
|
|
1590
|
-
return verb(this.#routes, ['HEAD'],
|
|
1620
|
+
head(...p) {
|
|
1621
|
+
return verb(this.#routes, ['HEAD'], p);
|
|
1591
1622
|
}
|
|
1592
1623
|
/**
|
|
1593
1624
|
* 注册 HTTP OPTIONS 处理函数
|
|
1594
1625
|
* @param handler 要注册的处理函数
|
|
1595
1626
|
*/
|
|
1596
1627
|
|
|
1597
|
-
options(
|
|
1598
|
-
return verb(this.#routes, ['OPTIONS'],
|
|
1628
|
+
options(...p) {
|
|
1629
|
+
return verb(this.#routes, ['OPTIONS'], p);
|
|
1599
1630
|
}
|
|
1600
1631
|
}
|
|
1601
1632
|
|
package/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* k99 v0.6.0-alpha.
|
|
2
|
+
* k99 v0.6.0-alpha.6
|
|
3
3
|
* (c) 2019-2023 猛火Fierflame
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
@@ -196,6 +196,7 @@ declare namespace Log {
|
|
|
196
196
|
|
|
197
197
|
interface ServiceContext<T, D extends boolean = boolean> extends Context {
|
|
198
198
|
readonly destroying: D;
|
|
199
|
+
readonly currentService?: Service<any, any, any>;
|
|
199
200
|
state?: T;
|
|
200
201
|
[key: string]: any;
|
|
201
202
|
}
|
|
@@ -362,6 +363,10 @@ interface Match {
|
|
|
362
363
|
(paths: string[]): [Record<string, string | string[]>, string[]] | undefined;
|
|
363
364
|
}
|
|
364
365
|
|
|
366
|
+
interface Binder {
|
|
367
|
+
(handler: Handler): () => void;
|
|
368
|
+
}
|
|
369
|
+
|
|
365
370
|
interface Route {
|
|
366
371
|
/** 路径匹配 */
|
|
367
372
|
match?: Match;
|
|
@@ -378,6 +383,22 @@ interface RouterRoute {
|
|
|
378
383
|
match?: Match;
|
|
379
384
|
router: Router;
|
|
380
385
|
}
|
|
386
|
+
interface RouteBinder {
|
|
387
|
+
/**
|
|
388
|
+
* 添加子路由
|
|
389
|
+
* @param router 要注册的子路由
|
|
390
|
+
*/
|
|
391
|
+
<T extends Router>(router: T): T;
|
|
392
|
+
/**
|
|
393
|
+
* 添加子路由
|
|
394
|
+
*/
|
|
395
|
+
(): ApiRouter;
|
|
396
|
+
/**
|
|
397
|
+
* 添加子路由
|
|
398
|
+
* @param find 要注册的子路由的 Finder
|
|
399
|
+
*/
|
|
400
|
+
route(find: Finder): Router;
|
|
401
|
+
}
|
|
381
402
|
declare class ApiRouter extends Router {
|
|
382
403
|
#private;
|
|
383
404
|
/**
|
|
@@ -407,6 +428,7 @@ declare class ApiRouter extends Router {
|
|
|
407
428
|
* @param find 要注册的子路由的 Finder
|
|
408
429
|
*/
|
|
409
430
|
route(path: string, find: Finder): Router;
|
|
431
|
+
route(...path: Parameters<typeof String.raw>): RouteBinder;
|
|
410
432
|
find(method: Method, path: string[]): Iterable<FindItem>;
|
|
411
433
|
/**
|
|
412
434
|
* 注册处理函数
|
|
@@ -421,6 +443,12 @@ declare class ApiRouter extends Router {
|
|
|
421
443
|
* @param handler 要注册的处理函数
|
|
422
444
|
*/
|
|
423
445
|
verb(methods: Method | Iterable<Method> | ArrayLike<Method>, path: string, handler: Handler): () => void;
|
|
446
|
+
/**
|
|
447
|
+
* 注册处理函数
|
|
448
|
+
* @param method 要注册的方法
|
|
449
|
+
* @param path 要注册的路径
|
|
450
|
+
*/
|
|
451
|
+
verb(methods: Method | Iterable<Method> | ArrayLike<Method>, path: string): Binder;
|
|
424
452
|
/**
|
|
425
453
|
* 注册 HTTP GET/POST/PUT/DELETE 处理函数
|
|
426
454
|
* @param handler 要注册的处理函数
|
|
@@ -432,6 +460,16 @@ declare class ApiRouter extends Router {
|
|
|
432
460
|
* @param handler 要注册的处理函数
|
|
433
461
|
*/
|
|
434
462
|
match(path: string, handler: Handler): () => void;
|
|
463
|
+
/**
|
|
464
|
+
* 注册 HTTP GET/POST/PUT/DELETE 处理函数
|
|
465
|
+
* @param path 要注册的路径
|
|
466
|
+
*/
|
|
467
|
+
match(path: string): Binder;
|
|
468
|
+
/**
|
|
469
|
+
* 注册 HTTP GET/POST/PUT/DELETE 处理函数
|
|
470
|
+
* @param path 要注册的路径
|
|
471
|
+
*/
|
|
472
|
+
match(...path: Parameters<typeof String.raw>): Binder;
|
|
435
473
|
/**
|
|
436
474
|
* 注册 HTTP GET 处理函数
|
|
437
475
|
* @param handler 要注册的处理函数
|
|
@@ -443,6 +481,16 @@ declare class ApiRouter extends Router {
|
|
|
443
481
|
* @param handler 要注册的处理函数
|
|
444
482
|
*/
|
|
445
483
|
get(path: string, handler: Handler): () => void;
|
|
484
|
+
/**
|
|
485
|
+
* 注册 HTTP GET 处理函数
|
|
486
|
+
* @param path 要注册的路径
|
|
487
|
+
*/
|
|
488
|
+
get(path: string): Binder;
|
|
489
|
+
/**
|
|
490
|
+
* 注册 HTTP GET 处理函数
|
|
491
|
+
* @param path 要注册的路径
|
|
492
|
+
*/
|
|
493
|
+
get(...path: Parameters<typeof String.raw>): Binder;
|
|
446
494
|
/**
|
|
447
495
|
* 注册 HTTP POST 处理函数
|
|
448
496
|
* @param handler 要注册的处理函数
|
|
@@ -454,6 +502,16 @@ declare class ApiRouter extends Router {
|
|
|
454
502
|
* @param handler 要注册的处理函数
|
|
455
503
|
*/
|
|
456
504
|
post(path: string, handler: Handler): () => void;
|
|
505
|
+
/**
|
|
506
|
+
* 注册 HTTP POST 处理函数
|
|
507
|
+
* @param path 要注册的路径
|
|
508
|
+
*/
|
|
509
|
+
post(path: string): Binder;
|
|
510
|
+
/**
|
|
511
|
+
* 注册 HTTP POST 处理函数
|
|
512
|
+
* @param path 要注册的路径
|
|
513
|
+
*/
|
|
514
|
+
post(...path: Parameters<typeof String.raw>): Binder;
|
|
457
515
|
/**
|
|
458
516
|
* 注册 HTTP PUT 处理函数
|
|
459
517
|
* @param handler 要注册的处理函数
|
|
@@ -465,6 +523,16 @@ declare class ApiRouter extends Router {
|
|
|
465
523
|
* @param handler 要注册的处理函数
|
|
466
524
|
*/
|
|
467
525
|
put(path: string, handler: Handler): () => void;
|
|
526
|
+
/**
|
|
527
|
+
* 注册 HTTP PUT 处理函数
|
|
528
|
+
* @param path 要注册的路径
|
|
529
|
+
*/
|
|
530
|
+
put(path: string): Binder;
|
|
531
|
+
/**
|
|
532
|
+
* 注册 HTTP PUT 处理函数
|
|
533
|
+
* @param path 要注册的路径
|
|
534
|
+
*/
|
|
535
|
+
put(...path: Parameters<typeof String.raw>): Binder;
|
|
468
536
|
/**
|
|
469
537
|
* 注册 HTTP DELETE 处理函数
|
|
470
538
|
* @param handler 要注册的处理函数
|
|
@@ -476,6 +544,16 @@ declare class ApiRouter extends Router {
|
|
|
476
544
|
* @param handler 要注册的处理函数
|
|
477
545
|
*/
|
|
478
546
|
delete(path: string, handler: Handler): () => void;
|
|
547
|
+
/**
|
|
548
|
+
* 注册 HTTP DELETE 处理函数
|
|
549
|
+
* @param path 要注册的路径
|
|
550
|
+
*/
|
|
551
|
+
delete(path: string): Binder;
|
|
552
|
+
/**
|
|
553
|
+
* 注册 HTTP DELETE 处理函数
|
|
554
|
+
* @param path 要注册的路径
|
|
555
|
+
*/
|
|
556
|
+
delete(...path: Parameters<typeof String.raw>): Binder;
|
|
479
557
|
/**
|
|
480
558
|
* 注册 HTTP HEAD 处理函数
|
|
481
559
|
* @param handler 要注册的处理函数
|
|
@@ -487,6 +565,16 @@ declare class ApiRouter extends Router {
|
|
|
487
565
|
* @param handler 要注册的处理函数
|
|
488
566
|
*/
|
|
489
567
|
head(path: string, handler: Handler): () => void;
|
|
568
|
+
/**
|
|
569
|
+
* 注册 HTTP HEAD 处理函数
|
|
570
|
+
* @param path 要注册的路径
|
|
571
|
+
*/
|
|
572
|
+
head(path: string): Binder;
|
|
573
|
+
/**
|
|
574
|
+
* 注册 HTTP HEAD 处理函数
|
|
575
|
+
* @param path 要注册的路径
|
|
576
|
+
*/
|
|
577
|
+
head(...path: Parameters<typeof String.raw>): Binder;
|
|
490
578
|
/**
|
|
491
579
|
* 注册 HTTP OPTIONS 处理函数
|
|
492
580
|
* @param handler 要注册的处理函数
|
|
@@ -498,6 +586,16 @@ declare class ApiRouter extends Router {
|
|
|
498
586
|
* @param handler 要注册的处理函数
|
|
499
587
|
*/
|
|
500
588
|
options(path: string, handler: Handler): () => void;
|
|
589
|
+
/**
|
|
590
|
+
* 注册 HTTP OPTIONS 处理函数
|
|
591
|
+
* @param path 要注册的路径
|
|
592
|
+
*/
|
|
593
|
+
options(path: string): Binder;
|
|
594
|
+
/**
|
|
595
|
+
* 注册 HTTP OPTIONS 处理函数
|
|
596
|
+
* @param path 要注册的路径
|
|
597
|
+
*/
|
|
598
|
+
options(...path: Parameters<typeof String.raw>): Binder;
|
|
501
599
|
}
|
|
502
600
|
|
|
503
601
|
declare function run(req: K99Request, getHandler: (ctx: Context, setParams: (v: any) => void) => Promise<Handler | null> | Handler | null, options?: {
|
|
@@ -561,4 +659,4 @@ declare abstract class Plugin<T extends Router = Router> {
|
|
|
561
659
|
set disabled(t: boolean);
|
|
562
660
|
}
|
|
563
661
|
|
|
564
|
-
export { ActionContext, ApiRouter, Asset, Context, CookieClearOption, CookieOption, CookieOptionInfo, Encoding, FindItem, Finder, Guard, Handler, HexEncoding, K99Headers, K99Request, K99Response, Log, Match, Method, Plugin, Route, Router, RouterRoute, Service, ServiceContext, Setting, WriteType, make, merge, run, service, stateService, storeService };
|
|
662
|
+
export { ActionContext, ApiRouter, Asset, Binder, Context, CookieClearOption, CookieOption, CookieOptionInfo, Encoding, FindItem, Finder, Guard, Handler, HexEncoding, K99Headers, K99Request, K99Response, Log, Match, Method, Plugin, Route, RouteBinder, Router, RouterRoute, Service, ServiceContext, Setting, WriteType, make, merge, run, service, stateService, storeService };
|
package/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* k99 v0.6.0-alpha.
|
|
2
|
+
* k99 v0.6.0-alpha.6
|
|
3
3
|
* (c) 2019-2023 猛火Fierflame
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
@@ -859,6 +859,11 @@
|
|
|
859
859
|
configurable: true,
|
|
860
860
|
enumerable: true
|
|
861
861
|
},
|
|
862
|
+
currentService: {
|
|
863
|
+
value: service,
|
|
864
|
+
configurable: true,
|
|
865
|
+
enumerable: true
|
|
866
|
+
},
|
|
862
867
|
state: {
|
|
863
868
|
configurable: true,
|
|
864
869
|
enumerable: true,
|
|
@@ -1163,6 +1168,9 @@
|
|
|
1163
1168
|
|
|
1164
1169
|
function service(exec, destroy, options) {
|
|
1165
1170
|
const service = function (ctx, ...any) {
|
|
1171
|
+
if (ctx.currentService !== service) {
|
|
1172
|
+
return ctx.service(service, ...any);
|
|
1173
|
+
}
|
|
1166
1174
|
if (!ctx.destroying) {
|
|
1167
1175
|
return exec(ctx, ...any);
|
|
1168
1176
|
}
|
|
@@ -1181,6 +1189,9 @@
|
|
|
1181
1189
|
|
|
1182
1190
|
function stateService(init, destroy, exec, options) {
|
|
1183
1191
|
const service = function (ctx) {
|
|
1192
|
+
if (ctx.currentService !== service) {
|
|
1193
|
+
return ctx.service(service);
|
|
1194
|
+
}
|
|
1184
1195
|
if (!ctx.destroying) {
|
|
1185
1196
|
let {
|
|
1186
1197
|
state
|
|
@@ -1209,6 +1220,9 @@
|
|
|
1209
1220
|
|
|
1210
1221
|
function storeService(destroy, exec, options) {
|
|
1211
1222
|
const service = function (ctx, ...s) {
|
|
1223
|
+
if (ctx.currentService !== service) {
|
|
1224
|
+
return ctx.service(service, ...s);
|
|
1225
|
+
}
|
|
1212
1226
|
if (!ctx.destroying) {
|
|
1213
1227
|
if (!s.length) {
|
|
1214
1228
|
return ctx.state;
|
|
@@ -1341,7 +1355,7 @@
|
|
|
1341
1355
|
}
|
|
1342
1356
|
let i = 0;
|
|
1343
1357
|
let count = 0;
|
|
1344
|
-
const pattern = ['^('];
|
|
1358
|
+
const pattern = ['^(?:'];
|
|
1345
1359
|
while (i < expression.length) {
|
|
1346
1360
|
const c = expression[i++];
|
|
1347
1361
|
pattern.push(c);
|
|
@@ -1448,12 +1462,7 @@
|
|
|
1448
1462
|
return path => exec(list, path, end);
|
|
1449
1463
|
}
|
|
1450
1464
|
|
|
1451
|
-
function
|
|
1452
|
-
const path = typeof a === 'string' ? a : '';
|
|
1453
|
-
const handler = [a, b].find(v => typeof v === 'function');
|
|
1454
|
-
if (!handler) {
|
|
1455
|
-
return () => {};
|
|
1456
|
-
}
|
|
1465
|
+
function bind(routes, methods, path, handler) {
|
|
1457
1466
|
const route = {
|
|
1458
1467
|
match: toMatch(path || '', true),
|
|
1459
1468
|
methods: new Set(methods),
|
|
@@ -1473,6 +1482,22 @@
|
|
|
1473
1482
|
routes.splice(index, 1);
|
|
1474
1483
|
};
|
|
1475
1484
|
}
|
|
1485
|
+
function verb(routes, methods, p) {
|
|
1486
|
+
if (!p.length) {
|
|
1487
|
+
return handler => bind(routes, methods, '', handler);
|
|
1488
|
+
}
|
|
1489
|
+
const [a, b] = p;
|
|
1490
|
+
if (a && typeof a === 'object') {
|
|
1491
|
+
const path = String.raw(a, ...p.slice(1));
|
|
1492
|
+
return handler => bind(routes, methods, path, handler);
|
|
1493
|
+
}
|
|
1494
|
+
const path = typeof a === 'string' ? a : '';
|
|
1495
|
+
const handler = [a, b].find(v => typeof v === 'function');
|
|
1496
|
+
if (!handler) {
|
|
1497
|
+
return handler => bind(routes, methods, path, handler);
|
|
1498
|
+
}
|
|
1499
|
+
return bind(routes, methods, path, handler);
|
|
1500
|
+
}
|
|
1476
1501
|
|
|
1477
1502
|
const methods = new Set(['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS']);
|
|
1478
1503
|
function isMethod(v) {
|
|
@@ -1488,6 +1513,14 @@
|
|
|
1488
1513
|
return Array.from(methods).map(v => typeof v === 'string' && v.toUpperCase()).filter(isMethod);
|
|
1489
1514
|
}
|
|
1490
1515
|
|
|
1516
|
+
function bindRouter(routes, path, r) {
|
|
1517
|
+
const router = r instanceof Router ? r : typeof r === 'function' ? Router.create(r) : new ApiRouter();
|
|
1518
|
+
routes.push({
|
|
1519
|
+
match: toMatch(path, false),
|
|
1520
|
+
router
|
|
1521
|
+
});
|
|
1522
|
+
return router;
|
|
1523
|
+
}
|
|
1491
1524
|
class ApiRouter extends Router {
|
|
1492
1525
|
/** 路由列表 */
|
|
1493
1526
|
#routes = [];
|
|
@@ -1496,15 +1529,15 @@
|
|
|
1496
1529
|
* @param router 要注册的子路由
|
|
1497
1530
|
*/
|
|
1498
1531
|
|
|
1499
|
-
route(
|
|
1500
|
-
const
|
|
1501
|
-
|
|
1532
|
+
route(...p) {
|
|
1533
|
+
const [a] = p;
|
|
1534
|
+
if (a && typeof a === 'object' && !(a instanceof Router)) {
|
|
1535
|
+
const path = String.raw(a, ...p.slice(1));
|
|
1536
|
+
return r => bindRouter(this.#routes, path, r);
|
|
1537
|
+
}
|
|
1502
1538
|
const path = typeof a === 'string' ? a : '';
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
router
|
|
1506
|
-
});
|
|
1507
|
-
return router;
|
|
1539
|
+
const r = typeof a === 'string' ? p[1] : a;
|
|
1540
|
+
return bindRouter(this.#routes, path, r);
|
|
1508
1541
|
}
|
|
1509
1542
|
*find(method, path) {
|
|
1510
1543
|
for (const route of Array.from(this.#routes)) {
|
|
@@ -1541,65 +1574,63 @@
|
|
|
1541
1574
|
if (!allMethods.length) {
|
|
1542
1575
|
return () => {};
|
|
1543
1576
|
}
|
|
1544
|
-
return verb(this.#routes, allMethods, path, handler);
|
|
1577
|
+
return verb(this.#routes, allMethods, [path, handler]);
|
|
1545
1578
|
}
|
|
1546
1579
|
/**
|
|
1547
1580
|
* 注册 HTTP GET/POST/PUT/DELETE 处理函数
|
|
1548
1581
|
* @param handler 要注册的处理函数
|
|
1549
1582
|
*/
|
|
1550
1583
|
|
|
1551
|
-
match(
|
|
1552
|
-
|
|
1553
|
-
return verb(this.#routes, methods, path, handler);
|
|
1584
|
+
match(...p) {
|
|
1585
|
+
return verb(this.#routes, ['GET', 'POST', 'PUT', 'DELETE'], p);
|
|
1554
1586
|
}
|
|
1555
|
-
|
|
1556
1587
|
/**
|
|
1557
1588
|
* 注册 HTTP GET 处理函数
|
|
1558
1589
|
* @param handler 要注册的处理函数
|
|
1559
1590
|
*/
|
|
1560
1591
|
|
|
1561
|
-
get(
|
|
1562
|
-
return verb(this.#routes, ['GET'],
|
|
1592
|
+
get(...p) {
|
|
1593
|
+
return verb(this.#routes, ['GET'], p);
|
|
1563
1594
|
}
|
|
1564
1595
|
/**
|
|
1565
1596
|
* 注册 HTTP POST 处理函数
|
|
1566
1597
|
* @param handler 要注册的处理函数
|
|
1567
1598
|
*/
|
|
1568
1599
|
|
|
1569
|
-
post(
|
|
1570
|
-
return verb(this.#routes, ['POST'],
|
|
1600
|
+
post(...p) {
|
|
1601
|
+
return verb(this.#routes, ['POST'], p);
|
|
1571
1602
|
}
|
|
1572
1603
|
/**
|
|
1573
1604
|
* 注册 HTTP PUT 处理函数
|
|
1574
1605
|
* @param handler 要注册的处理函数
|
|
1575
1606
|
*/
|
|
1576
1607
|
|
|
1577
|
-
put(
|
|
1578
|
-
return verb(this.#routes, ['PUT'],
|
|
1608
|
+
put(...p) {
|
|
1609
|
+
return verb(this.#routes, ['PUT'], p);
|
|
1579
1610
|
}
|
|
1580
1611
|
/**
|
|
1581
1612
|
* 注册 HTTP DELETE 处理函数
|
|
1582
1613
|
* @param handler 要注册的处理函数
|
|
1583
1614
|
*/
|
|
1584
1615
|
|
|
1585
|
-
delete(
|
|
1586
|
-
return verb(this.#routes, ['DELETE'],
|
|
1616
|
+
delete(...p) {
|
|
1617
|
+
return verb(this.#routes, ['DELETE'], p);
|
|
1587
1618
|
}
|
|
1588
1619
|
/**
|
|
1589
1620
|
* 注册 HTTP HEAD 处理函数
|
|
1590
1621
|
* @param handler 要注册的处理函数
|
|
1591
1622
|
*/
|
|
1592
1623
|
|
|
1593
|
-
head(
|
|
1594
|
-
return verb(this.#routes, ['HEAD'],
|
|
1624
|
+
head(...p) {
|
|
1625
|
+
return verb(this.#routes, ['HEAD'], p);
|
|
1595
1626
|
}
|
|
1596
1627
|
/**
|
|
1597
1628
|
* 注册 HTTP OPTIONS 处理函数
|
|
1598
1629
|
* @param handler 要注册的处理函数
|
|
1599
1630
|
*/
|
|
1600
1631
|
|
|
1601
|
-
options(
|
|
1602
|
-
return verb(this.#routes, ['OPTIONS'],
|
|
1632
|
+
options(...p) {
|
|
1633
|
+
return verb(this.#routes, ['OPTIONS'], p);
|
|
1603
1634
|
}
|
|
1604
1635
|
}
|
|
1605
1636
|
|
package/index.min.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* k99 v0.6.0-alpha.
|
|
2
|
+
* k99 v0.6.0-alpha.6
|
|
3
3
|
* (c) 2019-2023 猛火Fierflame
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
6
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).k99={})}(this,(function(e){"use strict";async function t(){}async function n(){return!1}function r({read:e=t,write:r=n}={}){return{read:e,write:r}}function o(e,t){if(!e)return null;switch(t){case"utf8":return function(e){let t=[],n=0;for(;n<e.length;){let r=0|e[n++];r>=240?(r=(7&r)<<18,r|=(63&e[n++])<<12,r|=(63&e[n++])<<6,r|=63&e[n++]):r>=224?(r=(15&r)<<12,r|=(63&e[n++])<<6,r|=63&e[n++]):r>=192&&(r=(31&r)<<6,r|=63&e[n++]),t.push(r)}return t.map((e=>String.fromCharCode(e))).join("")}(e);case"base64":return function(e,t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"){const n=Math.floor(Math.log2(t.length)),r=(1<<n)-1;let o=new Array(Math.floor(((e.byteLength<<3)+n-1)/n)),i=0,s=0,u=0;for(let a of e)for(s=s<<8|a,u+=8;u>=n;)u-=n,o[i++]=t[s>>u&r],s&=(1<<u)-1;for(u&&(o[i++]=t[s<<n-u&r]);o.length%4;)o.push("=");return o.join("")}(e);case"hex":return function(e){let t=new Array(2*e.byteLength);for(let n of e)t.push(n>>4&4369,4369&n);return t.map((e=>"0123456789ABCDEF"[e])).join("")}(e)}return e}let i="0123456789ABCDEF";function s(e,t){if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(e instanceof ArrayBuffer)return new Uint8Array(e);if("string"!=typeof e)return null;switch(t){default:case"utf8":return function(e){let t=[],n=0;for(;n<e.length;n++){const r=e.codePointAt(n);if("number"!=typeof r)break;r>=65536&&n++,r<128?t.push(r):r<2048?(t.push(192|31&r>>6),t.push(128|63&r)):r<65536?(t.push(224|15&r>>12),t.push(128|63&r>>6),t.push(128|63&r)):(t.push(240|7&r>>18),t.push(128|63&r>>12),t.push(128|63&r>>6),t.push(128|63&r))}return new Uint8Array(t)}(e);case"base64":return function(e,t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"){const n=Math.floor(Math.log2(t.length));e=e.replace(/[=\s]+/g,"");let r=new Uint8Array(e.length*n>>3),o=0,i=0,s=0;for(let u of e)for(i=i<<n|t.indexOf(u),s+=n;s>=8;)s-=8,r[o++]=i>>s&255,i&=(1<<s)-1;return r}(e);case"hex":return function(e){let t=[];for(let n=0;n<e.length;n+=2)t.push(16*i.indexOf(e[n])+i.indexOf(e[n+1]||"0"));return new Uint8Array(t)}(e)}}async function u(){return null}async function a(){return!1}function c({read:e=u,write:t=a,delete:n=a,stat:r=u}={}){return{read:async function(t,n){const r=await e(t);return r&&o(r,n)},write:async function(e,r,o){if(void 0===r)return n(e);const i=s(r,o);return i?t(e,i):n(e)},delete:function(e){return n(e)},stat:async function(e){return r(e)}}}function f(e){return"string"==typeof e?e:e instanceof Error?e.stack||`${e.name}:${e.message}`:String(e)}const l=/(?:^|\/)(debug|error|warn|info)\/?$|^\/?(debug|error|warn|info)(?:\/|$)/;async function h(e,t){switch(e){case"debug":console.debug(t);break;case"info":console.info(t);break;case"warn":console.warn(t);break;case"error":console.error(t)}console.group(`log @ ${e}`);const n=l.exec(e);switch(n?n[1]||n[2]:""){case"debug":console.debug(t);break;case"info":console.info(t);break;case"warn":console.warn(t);break;case"error":console.error(t);break;default:console.log(t)}return console.groupEnd(),!0}async function p(){return""}async function d(){}function y({read:e=p,write:t=h,clear:n=d}={}){function r(e,n,r){return t(e,function(e,{tags:t,indent:n,date:r}={}){let o="";return t&&(Array.isArray(t)||(t=[t]),o=t.map((e=>`[${e}]`)).join(" ")),r&&(o=`${(new Date).toISOString()} ${o}`),e.includes("\n")?("number"==typeof n&&(n=Math.floor(n),isFinite(n)&&n>0&&(n=Array(n).fill(" ").join(""))),n&&"string"==typeof n||(n=" "),e=(e=`${o}\n${e}`).split("\n").join(`\n${n}`)):`${o} ${e}`}(n,r))}return{read:e,write:r,clear:n,debug:async(e,t)=>r("debug",e,t),info:async(e,t)=>r("info",e,t),warn:async(e,t)=>r("warn",f(e),t),error:async(e,t)=>r("error",f(e),t)}}function g(e,t){if(1===e.length)return new Uint8Array(e[0]);const n=new Uint8Array(t);let r=0;for(const t of e)n.set(t,r),r+=t.byteLength;return n}function m(e,t){if(!t){const t=g(e,e.reduce(((e,t)=>e+t.byteLength),0));return e.length=0,t}let n=0;const r=[];for(let o;o=e.shift();){if(n+o.byteLength>t){const i=o.slice(0,t-n);r.push(i),n+=i.byteLength,e.unshift(o.slice(i.byteLength));break}if(r.push(o),n+=o.byteLength,n===t)break}return g(r,n)}async function*b(e){if(e){if("string"==typeof e)return yield s(e);if("object"==typeof e){if(e instanceof ArrayBuffer)return yield s(e);if(ArrayBuffer.isView(e))return yield s(e);if(Symbol.asyncIterator in e||Symbol.iterator in e)for await(const t of e)yield*b(t)}}}async function w(e,t){const n=[];let r=0,[o,i]=await t();for await(const s of b(e))if(n.push(s),r+=s.byteLength,o<=0)r=0,i(m(n)),[o,i]=await t();else for(r>=o&&(r-=o,i(m(n,o)),[o,i]=await t());r&&(o<=0||o<=r);){if(o<=0){r=0,i(m(n)),[o,i]=await t();break}r-=o,i(m(n,o)),[o,i]=await t()}for(r&&(i(m(n)),[o,i]=await t()),i(null);;)[o,i]=await t(),i(null)}function O(e){if(!e)return()=>Promise.resolve(null);const t=[];let n=null;return w(e,(function(){return new Promise((e=>{const r=t.shift();if(r)return e(r);n=t=>{n=null,e(t)}}))})),function(e=0){return new Promise((r=>{e=Math.max(e,0),n?n([e,r]):t.push([e,r])}))}}const P=/^(?:(?:https?:)?\/\/(?:(?:[^/?#]*@)?)(?:\d+|(?:\[[0-9a-f:]+\])|(?:\d{1,3}\.){3}\d{1,3}|(?:(?:[a-z0-9\u0100-\uffff]+-*)+\.)+[a-z]+)(?::\d+)?)?((?:\/?[^?#]*)?)((?:\?[^#]*)?)(?:#.*)?$/i;function v(e){const t=e.indexOf("=");return t<0?[decodeURIComponent(e),""]:[decodeURIComponent(e.substring(0,t)),decodeURIComponent(e.substring(t+1))]}function j(e){const t={};for(const n of e.split("&").filter(Boolean)){const[e,r]=v(n);t[e]=e in t?[t[e],r].flat():[r]}return t}function A({method:e,path:t,signal:n,body:r,headers:o={}}){const[i,s]=function(e){const t=P.exec(e);if(!t)return["/",""];let[,n,r]=t;const o=[];for(const e of n.replace(/^[\\/]+/,"").replace(/[\\/]+/g,"/").split("/"))"."!==e&&(".."!==e?o.push(e):o.pop());return[`/${o.join("/")}`,r]}(t);return{method:e,url:`${i}${s}`,headers:o,pathname:i,search:s,signal:n||(new AbortController).signal,query:j(s.substring(1)),read:"function"==typeof r?r:O(r)}}function $(e){return e instanceof ArrayBuffer||!!ArrayBuffer.isView(e)}function x(){let e=!1,t=[],n=null;function r(n){if(e)return null;e=!0,n&&n(!1);for(let e;e=t.shift();){const[,t]=e;t(!1)}return null}let o=Promise.resolve((()=>{}));const i={next(){const e=o.then((e=>{if(e)return u?(e(!1),c):(e(!0),Promise.race([c,new Promise((e=>{const r=t.shift();if(r)return e(r);n=t=>{n=null,e(t)}})).then((e=>{const[t,n]=e;if(!u&&void 0!==t)return e;n(!u)}))]))}));return o=e.then((e=>{if(!e)return null;const[,t]=e;return t}),(()=>r())),e.then((e=>{if(!e)return{done:!0,value:void 0};const[t,n]=e;return{done:!1,value:t}}))},throw:e=>(o=o.then(r),o.then((()=>Promise.reject(e)))),return:e=>(o=o.then(r),o.then((()=>e))),[Symbol.asyncIterator]:()=>i};let u,a,c=new Promise(((e,t)=>{u?t(u):a=t}));function f(r,o){if(e)return o(!1);n?n([r,o]):t.push([r,o])}let l=Promise.resolve(!0);async function h(t){if(e)return Promise.resolve();if("string"==typeof t)return new Promise((e=>f(s(t),e)));if("object"!=typeof t)return!1;if($(t))return new Promise((e=>f(s(t),e)));if(!(Symbol.asyncIterator in t)&&!(Symbol.iterator in t))return!1;for await(const n of t){if(e)return Promise.resolve();if(n&&!await h(n))return!1}return!0}let p=!1;return[{write(e){const t=l.then((t=>{if(void 0!==t)return!e||h(e)}));return l=t,t.then((e=>Boolean(e)))},end(){p=!0;const r=l.then((r=>new Promise((o=>{if(void 0===r||e)return o();n?n([void 0,()=>o()]):t.push([void 0,()=>o()])}))));return l=r,r},get ended(){return e||p}},i,function(e){return!u&&(u=e||new DOMException("The user aborted a request."),a&&a(u),!0)}]}function S(e){return e.map((({name:e,value:t,expire:n,domain:r,path:o,secure:i,httpOnly:s})=>e&&[`${encodeURI(e)}=${encodeURI(t||"")}`,n&&`Expires=${n}`,r&&`Domain=${encodeURI(r)}`,o&&`Path=${encodeURI(o)}`,i&&"Secure",s&&"HttpOnly"].filter(Boolean).join("; "))).filter(Boolean)}function k(e){let t=Promise.resolve(!1);return function(n=0,r){const i=t.then((t=>t?null:e(n)));return t=i.then((e=>!e)),i.then((e=>o(e,r)))}}const E=/^(\[[^\]]+\]|^:):(\d+)$/;function T({method:e,url:t,pathname:n,search:r,query:o,read:i,headers:s,signal:u},a,c,f,l,h){const p=new Map,d=s.host||"",y=E.exec(d),[g,m]=y?[y[1],y[2]]:[d,""],b=function(e){let t={};for(const n of e.replace(/\s/g,"").split(";")){const e=n.split("=");t[decodeURIComponent(e.shift())]=decodeURIComponent(e.join("="))}return t}(s.cookie||""),w=[];let O=200,P={},v=!1,j=!1;const A=h?.root;let $=null,x={};const T={setting:a,asset:c,log:f,parent:h,get error(){return $},get root(){return A||this},signal:u,request:l,service(e,...t){if(e.rootOnly&&A)return A.service(e,...t);let n=p.get(e);if(!n){let t;n=Object.create(T,{destroying:{value:!1,configurable:!0,enumerable:!0},state:{configurable:!0,enumerable:!0,get:()=>t,set(e){t=e}}}),p.set(e,n)}return e(n,...t)},method:e,url:t,pathname:n,search:r,query:o,get params(){return x},headers:Object.freeze({...s}),host:d,hostname:g,port:m,requestType:s["content-type"]||"",referer:s.referer||"",userAgent:s["user-agent"]||"",accept:(s.accept||"").split(/,\s*/).filter(Boolean),acceptLanguage:(s["accept-language"]||"").split(/,\s*/).filter(Boolean),cookies:b,read:k(i),get destroyed(){return j},get headersSent(){return v},get status(){return O},set status(e){v||(O=e)},get location(){return P.location||""},set location(e){v||(P.location=e)},get responseType(){return P["content-type"]||""},set responseType(e){v||(P["content-type"]=e)},getCookie:e=>function*(e,t){const n=e;for(const e of n)t&&e.name!==t||(yield{...e})}(w,e),setCookie(e,t,{expire:n,domain:r,path:o,secure:i,httpOnly:s}={}){v||(w.push({name:e,value:t,expire:n,domain:r,path:o,secure:i,httpOnly:s}),P["set-cookie"]=S(w))},clearCookie(e,t){v||(!function(e,t,n,r){let o="Fri, 31 Dec 1999 16:00:00 GMT";if("string"==typeof n){if(!n)return;const{domain:t,path:i,secure:s,httpOnly:u}=!0!==r&&r||{};e.push({name:n,value:"delete",expire:o,domain:t,path:i,secure:s,httpOnly:u})}else{const{domain:i,path:s,secure:u,httpOnly:a}=n||{};if(e.length=0,r)for(let n in t)e.push({name:n,value:"delete",expire:o,domain:i,path:s,secure:u,httpOnly:a})}}(w,b,e,t),P["set-cookie"]=S(w))},hasHeader:e=>e in P,getHeaderNames:()=>Object.keys(P),getHeaders:()=>({...P}),getHeader:e=>P[e],setHeader(e,t){v||(void 0===t?delete P[e]:P[e]=t)}};return{context:T,setParams:e=>{x=e},destroy:e=>{j||(j=!0,v=!0,e&&($=e),function(e,t){let n=Promise.resolve();for(const[r,o]of[...t.entries()])n=n.then((()=>r(Object.create(o,{destroying:{value:!0,configurable:!0,enumerable:!0}})))).catch((t=>e.error(t)))}(f,p))},sendHeaders:()=>!v&&(v=!0,!0)}}function R(e,t){return"bigint"==typeof t?String(t):t}async function U(e,t){if(e.headersSent)return;const n=await t(e);if(!e.finished){if(function(e){return!(!e||"object"!=typeof e||!Array.isArray(e)&&($(e)||Symbol.asyncIterator in e||Symbol.iterator in e))}(n)){if(e.headersSent)return;return e.responseType="application/json",void await e.write(JSON.stringify(n,R))}return e.write(n)}}function B(e,t,n,r,o,i){const s=(u=e.signal,new Promise(((e,t)=>{if(u.aborted)return t(u.reason);u.addEventListener("abort",(()=>t(u.reason)),{once:!0})})));var u;const{context:a,setParams:c,destroy:f,sendHeaders:l}=T(e,n,r,o,(e=>B(A(e),t,n,r,o,a)),i);return Promise.race([s,t(a,c)]).then((e=>new Promise((t=>{if(!e)return f(),t(null);const[n,r,o]=x();function i(){if(!l())return;const{status:e}=a;t({...r,get status(){return e},get finished(){return n.ended},headers:Object.freeze(a.getHeaders()),[Symbol.asyncIterator]:()=>r})}s.catch((e=>o(e)));const u={get finished(){return n.ended},write:e=>(i(),n.write(e))},c=Object.create(a,Object.getOwnPropertyDescriptors(u));Promise.race([s,U(c,e)]).then((()=>{i(),f(),n.end()}),(e=>{a.status=500,i(),o(e),f(e||!0),n.end()}))}))),(e=>(f(e||!0),Promise.reject(e))))}function I(e,t){const n=c(t?.asset),o=r(t?.setting),i=y(t?.log),s=async(t,n)=>e(t,n);return e=>B(e,s,o,n,i)}async function C(e,t,n,r,o){if(!(e instanceof D))return r(o),e;if(e.disabled)return null;const i=await async function(e,t,n,r){if(!e.size)return!0;n(r);for(const n of e){if(t.destroyed)return!1;const e=await n(Object.create(t,{params:{value:{...r}}}));if(!1===e)return!1;if("function"==typeof e)return e}return!0}(e.guards,n,r,o);if(!i)return null;if("function"==typeof i)return i;if(n.destroyed)return null;for await(const[i,s,u]of e.find(n.method,t)){if(n.destroyed)return null;const e=C(i,u,n,r,{...o,...s});if(e)return e}return null}function L(e){try{return decodeURIComponent(e)}catch{return e}}class D{disabled=!1;static make(e){return async(t,n)=>{const r=e.flat(),o=t.pathname.split("/").filter(Boolean).map(L);for(const e of r){const r=await C(e,o,t,n,{});if(r)return r}return null}}static create(e){return Object.create(D.prototype,{find:{configurable:!0,value:e,writable:!0}})}guards=new Set}const H=/^:([a-zA-Z][a-zA-Z0-9]*)(?:\((.+)\))?([ius]+)?([?+*]?)$/;function M(e){const t=H.exec(e);if(!t)return e;const[,n,r=".*",o,i]=t;if(!r)return{name:n,pattern:new RegExp("^.*$",o),optional:"?"===i||"*"===i,many:"+"===i||"*"===i};let s=0,u=0;const a=["^("];for(;s<r.length;){const t=r[s++];if(a.push(t),"\\"!==t)if(")"!==t)if("["!==t){if("("===t&&(u++,"?"===r[s]&&(s+=2,":"!==r[s-1])))return e}else for(;s<r.length;){const e=r[s++];if(a.push(e),"]"===e)break;"\\"===e&&a.push(r[s++])}else{if(0===u)return e;u--}else a.push(r[s++])}return u?e:(a.push(")$"),{name:n,pattern:new RegExp(a.join(""),o),optional:"?"===i||"*"===i,many:"+"===i||"*"===i})}function z(e,t){const n=[];for(const t of e.split("/"))t&&!/^\.+$/.test(t)&&n.push(M(t));if(n.length)return e=>function(e,t,n){const r={};for(let n=0;n<e.length;n++){const o=e[n],i=t[n];if(o!==i){if("string"==typeof o)return;if(!i)return o.optional?[r,[]]:void 0;if(!o.pattern.test(i))return;r[o.name]=i}}if(!n)return[r,t.slice(e.length)];if(t.length<=e.length)return[r,[]];const o=e[e.length-1];if("string"!=typeof o&&(o.many||!(t.length>e.length))){for(let n=e.length;n<t.length;n++)if(!o.pattern.test(t[n]))return;return r[o.name]=t.slice(e.length-1),[r,[]]}}(n,e,t)}function _(e,t,n,r){const o="string"==typeof n?n:"",i=[n,r].find((e=>"function"==typeof e));if(!i)return()=>{};const s={match:z(o||"",!0),methods:new Set(t),handler:i};e.push(s);let u=!1;return()=>{if(u)return;u=!0;const t=e.indexOf(s);t<0||e.splice(t,1)}}const q=new Set(["GET","POST","PUT","DELETE","HEAD","OPTIONS"]);function G(e){return q.has(e)}class F extends D{#e=[];route(e,t){const n="string"==typeof e?t:e,r=n instanceof D?n:"function"==typeof n?D.create(n):new F,o="string"==typeof e?e:"";return this.#e.push({match:z(o,!1),router:r}),r}*find(e,t){for(const n of Array.from(this.#e)){if(!n.router&&!n.methods.has(e))continue;const{match:r}=n;if(!r){!n.router&&t.length||(yield[n.router||n.handler,{},t]);continue}if(!t.length)continue;const o=r(t);o&&(yield[n.router||n.handler,...o])}}verb(e,t,n){const r=function(e){return e?"string"==typeof e?[e.toUpperCase()].filter(G):Array.from(e).map((e=>"string"==typeof e&&e.toUpperCase())).filter(G):["GET","POST","PUT","DELETE"]}(e);return r.length?_(this.#e,r,t,n):()=>{}}match(e,t){return _(this.#e,["GET","POST","PUT","DELETE"],e,t)}get(e,t){return _(this.#e,["GET"],e,t)}post(e,t){return _(this.#e,["POST"],e,t)}put(e,t){return _(this.#e,["PUT"],e,t)}delete(e,t){return _(this.#e,["DELETE"],e,t)}head(e,t){return _(this.#e,["HEAD"],e,t)}options(e,t){return _(this.#e,["OPTIONS"],e,t)}}const N="[a-zA-Z][a-zA-Z0-9_-]*",Z=`${N}(?:.${N})*`,V=new RegExp(`^/(${N})/((?:@${Z}/)?${Z})/(.+)$`);class J{static make(e,{router:t,setting:n,asset:r,log:o}={}){const i=[];for(const t of Object.values(e))i.push(t.router);return t instanceof D&&i.push(t),I(D.make(i),{setting:n,asset:J.bindAsset(r,e),log:o})}static bindAsset(e,t,n="plugins"){if(!t)return e;const r=e?.read;return"function"!=typeof r?e:{...e,read:async e=>{const o=await r(e);if(null!==o)return o;if(!t)return null;const i=V.exec(e);if(!i)return null;const[,s,u,a]=i;if(s!==n)return null;if(!(u in t))return null;const c=t[u];return c?c.readAsset(a):null}}}constructor(e,t,{author:n,license:r}={}){this.name=e,this.version="string"==typeof t?t:"",this.author="string"==typeof n?n:"",this.license="string"==typeof r?r:""}initRouter(){const{router:e}=this;return this.__initRouterPromise?this.__initRouterPromise:this.__initRouterPromise=Promise.resolve(this._initRouter(e)).then((()=>e))}get router(){const e=this._createRouter();return Reflect.defineProperty(this,"router",{value:e,configurable:!0}),this.initRouter(),e}get disabled(){return this.router.disabled}set disabled(e){this.router.disabled=e}}e.ApiRouter=F,e.Plugin=J,e.Router=D,e.make=I,e.merge=function(...e){return t=>async function(e,t){for(const n of t){if(e.headersSent)break;const t=await n(e);if(e.finished)break;if("boolean"==typeof t)return t;if(t)return t}}(t,e.flat())},e.run=function(e,t,n){const o=c(n?.asset);return B(e,(async(e,n)=>t(e,n)),r(n?.setting),o,y(n?.log))},e.service=function(e,t,n){const r=function(n,...r){return n.destroying?"function"==typeof t?t(n):void 0:e(n,...r)},{rootOnly:o}="object"==typeof t&&t||"object"==typeof n&&n||{};return Object.assign(r,{rootOnly:Boolean(o)}),r},e.stateService=function(e,t,n,r){const o=function(r){if(!r.destroying){let{state:t}=r;return t||(t=e(r)||{},r.state=t),"function"==typeof n&&n(t,r),t}if("function"==typeof t)return t(r.state,r)},{rootOnly:i}="object"==typeof t&&t||"object"==typeof n&&n||"object"==typeof r&&r||{};return Object.assign(o,{rootOnly:Boolean(i)}),o},e.storeService=function(e,t,n){const r=function(n,...r){if(!n.destroying){if(!r.length)return n.state;const[e]=r;return n.state=e,"function"==typeof t&&t(e,n),e}if("function"==typeof e)return e(n.state,n)},{rootOnly:o}="object"==typeof e&&e||"object"==typeof t&&t||"object"==typeof n&&n||{};return Object.assign(r,{rootOnly:Boolean(o)}),r}}));
|
|
6
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).k99={})}(this,(function(e){"use strict";async function t(){}async function n(){return!1}function r({read:e=t,write:r=n}={}){return{read:e,write:r}}function o(e,t){if(!e)return null;switch(t){case"utf8":return function(e){let t=[],n=0;for(;n<e.length;){let r=0|e[n++];r>=240?(r=(7&r)<<18,r|=(63&e[n++])<<12,r|=(63&e[n++])<<6,r|=63&e[n++]):r>=224?(r=(15&r)<<12,r|=(63&e[n++])<<6,r|=63&e[n++]):r>=192&&(r=(31&r)<<6,r|=63&e[n++]),t.push(r)}return t.map((e=>String.fromCharCode(e))).join("")}(e);case"base64":return function(e,t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"){const n=Math.floor(Math.log2(t.length)),r=(1<<n)-1;let o=new Array(Math.floor(((e.byteLength<<3)+n-1)/n)),i=0,s=0,u=0;for(let c of e)for(s=s<<8|c,u+=8;u>=n;)u-=n,o[i++]=t[s>>u&r],s&=(1<<u)-1;for(u&&(o[i++]=t[s<<n-u&r]);o.length%4;)o.push("=");return o.join("")}(e);case"hex":return function(e){let t=new Array(2*e.byteLength);for(let n of e)t.push(n>>4&4369,4369&n);return t.map((e=>"0123456789ABCDEF"[e])).join("")}(e)}return e}let i="0123456789ABCDEF";function s(e,t){if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(e instanceof ArrayBuffer)return new Uint8Array(e);if("string"!=typeof e)return null;switch(t){default:case"utf8":return function(e){let t=[],n=0;for(;n<e.length;n++){const r=e.codePointAt(n);if("number"!=typeof r)break;r>=65536&&n++,r<128?t.push(r):r<2048?(t.push(192|31&r>>6),t.push(128|63&r)):r<65536?(t.push(224|15&r>>12),t.push(128|63&r>>6),t.push(128|63&r)):(t.push(240|7&r>>18),t.push(128|63&r>>12),t.push(128|63&r>>6),t.push(128|63&r))}return new Uint8Array(t)}(e);case"base64":return function(e,t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"){const n=Math.floor(Math.log2(t.length));e=e.replace(/[=\s]+/g,"");let r=new Uint8Array(e.length*n>>3),o=0,i=0,s=0;for(let u of e)for(i=i<<n|t.indexOf(u),s+=n;s>=8;)s-=8,r[o++]=i>>s&255,i&=(1<<s)-1;return r}(e);case"hex":return function(e){let t=[];for(let n=0;n<e.length;n+=2)t.push(16*i.indexOf(e[n])+i.indexOf(e[n+1]||"0"));return new Uint8Array(t)}(e)}}async function u(){return null}async function c(){return!1}function a({read:e=u,write:t=c,delete:n=c,stat:r=u}={}){return{read:async function(t,n){const r=await e(t);return r&&o(r,n)},write:async function(e,r,o){if(void 0===r)return n(e);const i=s(r,o);return i?t(e,i):n(e)},delete:function(e){return n(e)},stat:async function(e){return r(e)}}}function f(e){return"string"==typeof e?e:e instanceof Error?e.stack||`${e.name}:${e.message}`:String(e)}const l=/(?:^|\/)(debug|error|warn|info)\/?$|^\/?(debug|error|warn|info)(?:\/|$)/;async function h(e,t){switch(e){case"debug":console.debug(t);break;case"info":console.info(t);break;case"warn":console.warn(t);break;case"error":console.error(t)}console.group(`log @ ${e}`);const n=l.exec(e);switch(n?n[1]||n[2]:""){case"debug":console.debug(t);break;case"info":console.info(t);break;case"warn":console.warn(t);break;case"error":console.error(t);break;default:console.log(t)}return console.groupEnd(),!0}async function p(){return""}async function d(){}function y({read:e=p,write:t=h,clear:n=d}={}){function r(e,n,r){return t(e,function(e,{tags:t,indent:n,date:r}={}){let o="";return t&&(Array.isArray(t)||(t=[t]),o=t.map((e=>`[${e}]`)).join(" ")),r&&(o=`${(new Date).toISOString()} ${o}`),e.includes("\n")?("number"==typeof n&&(n=Math.floor(n),isFinite(n)&&n>0&&(n=Array(n).fill(" ").join(""))),n&&"string"==typeof n||(n=" "),e=(e=`${o}\n${e}`).split("\n").join(`\n${n}`)):`${o} ${e}`}(n,r))}return{read:e,write:r,clear:n,debug:async(e,t)=>r("debug",e,t),info:async(e,t)=>r("info",e,t),warn:async(e,t)=>r("warn",f(e),t),error:async(e,t)=>r("error",f(e),t)}}function g(e,t){if(1===e.length)return new Uint8Array(e[0]);const n=new Uint8Array(t);let r=0;for(const t of e)n.set(t,r),r+=t.byteLength;return n}function m(e,t){if(!t){const t=g(e,e.reduce(((e,t)=>e+t.byteLength),0));return e.length=0,t}let n=0;const r=[];for(let o;o=e.shift();){if(n+o.byteLength>t){const i=o.slice(0,t-n);r.push(i),n+=i.byteLength,e.unshift(o.slice(i.byteLength));break}if(r.push(o),n+=o.byteLength,n===t)break}return g(r,n)}async function*b(e){if(e){if("string"==typeof e)return yield s(e);if("object"==typeof e){if(e instanceof ArrayBuffer)return yield s(e);if(ArrayBuffer.isView(e))return yield s(e);if(Symbol.asyncIterator in e||Symbol.iterator in e)for await(const t of e)yield*b(t)}}}async function w(e,t){const n=[];let r=0,[o,i]=await t();for await(const s of b(e))if(n.push(s),r+=s.byteLength,o<=0)r=0,i(m(n)),[o,i]=await t();else for(r>=o&&(r-=o,i(m(n,o)),[o,i]=await t());r&&(o<=0||o<=r);){if(o<=0){r=0,i(m(n)),[o,i]=await t();break}r-=o,i(m(n,o)),[o,i]=await t()}for(r&&(i(m(n)),[o,i]=await t()),i(null);;)[o,i]=await t(),i(null)}function v(e){if(!e)return()=>Promise.resolve(null);const t=[];let n=null;return w(e,(function(){return new Promise((e=>{const r=t.shift();if(r)return e(r);n=t=>{n=null,e(t)}}))})),function(e=0){return new Promise((r=>{e=Math.max(e,0),n?n([e,r]):t.push([e,r])}))}}const O=/^(?:(?:https?:)?\/\/(?:(?:[^/?#]*@)?)(?:\d+|(?:\[[0-9a-f:]+\])|(?:\d{1,3}\.){3}\d{1,3}|(?:(?:[a-z0-9\u0100-\uffff]+-*)+\.)+[a-z]+)(?::\d+)?)?((?:\/?[^?#]*)?)((?:\?[^#]*)?)(?:#.*)?$/i;function P(e){const t=e.indexOf("=");return t<0?[decodeURIComponent(e),""]:[decodeURIComponent(e.substring(0,t)),decodeURIComponent(e.substring(t+1))]}function j(e){const t={};for(const n of e.split("&").filter(Boolean)){const[e,r]=P(n);t[e]=e in t?[t[e],r].flat():[r]}return t}function A({method:e,path:t,signal:n,body:r,headers:o={}}){const[i,s]=function(e){const t=O.exec(e);if(!t)return["/",""];let[,n,r]=t;const o=[];for(const e of n.replace(/^[\\/]+/,"").replace(/[\\/]+/g,"/").split("/"))"."!==e&&(".."!==e?o.push(e):o.pop());return[`/${o.join("/")}`,r]}(t);return{method:e,url:`${i}${s}`,headers:o,pathname:i,search:s,signal:n||(new AbortController).signal,query:j(s.substring(1)),read:"function"==typeof r?r:v(r)}}function S(e){return e instanceof ArrayBuffer||!!ArrayBuffer.isView(e)}function $(){let e=!1,t=[],n=null;function r(n){if(e)return null;e=!0,n&&n(!1);for(let e;e=t.shift();){const[,t]=e;t(!1)}return null}let o=Promise.resolve((()=>{}));const i={next(){const e=o.then((e=>{if(e)return u?(e(!1),a):(e(!0),Promise.race([a,new Promise((e=>{const r=t.shift();if(r)return e(r);n=t=>{n=null,e(t)}})).then((e=>{const[t,n]=e;if(!u&&void 0!==t)return e;n(!u)}))]))}));return o=e.then((e=>{if(!e)return null;const[,t]=e;return t}),(()=>r())),e.then((e=>{if(!e)return{done:!0,value:void 0};const[t,n]=e;return{done:!1,value:t}}))},throw:e=>(o=o.then(r),o.then((()=>Promise.reject(e)))),return:e=>(o=o.then(r),o.then((()=>e))),[Symbol.asyncIterator]:()=>i};let u,c,a=new Promise(((e,t)=>{u?t(u):c=t}));function f(r,o){if(e)return o(!1);n?n([r,o]):t.push([r,o])}let l=Promise.resolve(!0);async function h(t){if(e)return Promise.resolve();if("string"==typeof t)return new Promise((e=>f(s(t),e)));if("object"!=typeof t)return!1;if(S(t))return new Promise((e=>f(s(t),e)));if(!(Symbol.asyncIterator in t)&&!(Symbol.iterator in t))return!1;for await(const n of t){if(e)return Promise.resolve();if(n&&!await h(n))return!1}return!0}let p=!1;return[{write(e){const t=l.then((t=>{if(void 0!==t)return!e||h(e)}));return l=t,t.then((e=>Boolean(e)))},end(){p=!0;const r=l.then((r=>new Promise((o=>{if(void 0===r||e)return o();n?n([void 0,()=>o()]):t.push([void 0,()=>o()])}))));return l=r,r},get ended(){return e||p}},i,function(e){return!u&&(u=e||new DOMException("The user aborted a request."),c&&c(u),!0)}]}function x(e){return e.map((({name:e,value:t,expire:n,domain:r,path:o,secure:i,httpOnly:s})=>e&&[`${encodeURI(e)}=${encodeURI(t||"")}`,n&&`Expires=${n}`,r&&`Domain=${encodeURI(r)}`,o&&`Path=${encodeURI(o)}`,i&&"Secure",s&&"HttpOnly"].filter(Boolean).join("; "))).filter(Boolean)}function k(e){let t=Promise.resolve(!1);return function(n=0,r){const i=t.then((t=>t?null:e(n)));return t=i.then((e=>!e)),i.then((e=>o(e,r)))}}const E=/^(\[[^\]]+\]|^:):(\d+)$/;function T({method:e,url:t,pathname:n,search:r,query:o,read:i,headers:s,signal:u},c,a,f,l,h){const p=new Map,d=s.host||"",y=E.exec(d),[g,m]=y?[y[1],y[2]]:[d,""],b=function(e){let t={};for(const n of e.replace(/\s/g,"").split(";")){const e=n.split("=");t[decodeURIComponent(e.shift())]=decodeURIComponent(e.join("="))}return t}(s.cookie||""),w=[];let v=200,O={},P=!1,j=!1;const A=h?.root;let S=null,$={};const T={setting:c,asset:a,log:f,parent:h,get error(){return S},get root(){return A||this},signal:u,request:l,service(e,...t){if(e.rootOnly&&A)return A.service(e,...t);let n=p.get(e);if(!n){let t;n=Object.create(T,{destroying:{value:!1,configurable:!0,enumerable:!0},currentService:{value:e,configurable:!0,enumerable:!0},state:{configurable:!0,enumerable:!0,get:()=>t,set(e){t=e}}}),p.set(e,n)}return e(n,...t)},method:e,url:t,pathname:n,search:r,query:o,get params(){return $},headers:Object.freeze({...s}),host:d,hostname:g,port:m,requestType:s["content-type"]||"",referer:s.referer||"",userAgent:s["user-agent"]||"",accept:(s.accept||"").split(/,\s*/).filter(Boolean),acceptLanguage:(s["accept-language"]||"").split(/,\s*/).filter(Boolean),cookies:b,read:k(i),get destroyed(){return j},get headersSent(){return P},get status(){return v},set status(e){P||(v=e)},get location(){return O.location||""},set location(e){P||(O.location=e)},get responseType(){return O["content-type"]||""},set responseType(e){P||(O["content-type"]=e)},getCookie:e=>function*(e,t){const n=e;for(const e of n)t&&e.name!==t||(yield{...e})}(w,e),setCookie(e,t,{expire:n,domain:r,path:o,secure:i,httpOnly:s}={}){P||(w.push({name:e,value:t,expire:n,domain:r,path:o,secure:i,httpOnly:s}),O["set-cookie"]=x(w))},clearCookie(e,t){P||(!function(e,t,n,r){let o="Fri, 31 Dec 1999 16:00:00 GMT";if("string"==typeof n){if(!n)return;const{domain:t,path:i,secure:s,httpOnly:u}=!0!==r&&r||{};e.push({name:n,value:"delete",expire:o,domain:t,path:i,secure:s,httpOnly:u})}else{const{domain:i,path:s,secure:u,httpOnly:c}=n||{};if(e.length=0,r)for(let n in t)e.push({name:n,value:"delete",expire:o,domain:i,path:s,secure:u,httpOnly:c})}}(w,b,e,t),O["set-cookie"]=x(w))},hasHeader:e=>e in O,getHeaderNames:()=>Object.keys(O),getHeaders:()=>({...O}),getHeader:e=>O[e],setHeader(e,t){P||(void 0===t?delete O[e]:O[e]=t)}};return{context:T,setParams:e=>{$=e},destroy:e=>{j||(j=!0,P=!0,e&&(S=e),function(e,t){let n=Promise.resolve();for(const[r,o]of[...t.entries()])n=n.then((()=>r(Object.create(o,{destroying:{value:!0,configurable:!0,enumerable:!0}})))).catch((t=>e.error(t)))}(f,p))},sendHeaders:()=>!P&&(P=!0,!0)}}function R(e,t){return"bigint"==typeof t?String(t):t}async function U(e,t){if(e.headersSent)return;const n=await t(e);if(!e.finished){if(function(e){return!(!e||"object"!=typeof e||!Array.isArray(e)&&(S(e)||Symbol.asyncIterator in e||Symbol.iterator in e))}(n)){if(e.headersSent)return;return e.responseType="application/json",void await e.write(JSON.stringify(n,R))}return e.write(n)}}function B(e,t,n,r,o,i){const s=(u=e.signal,new Promise(((e,t)=>{if(u.aborted)return t(u.reason);u.addEventListener("abort",(()=>t(u.reason)),{once:!0})})));var u;const{context:c,setParams:a,destroy:f,sendHeaders:l}=T(e,n,r,o,(e=>B(A(e),t,n,r,o,c)),i);return Promise.race([s,t(c,a)]).then((e=>new Promise((t=>{if(!e)return f(),t(null);const[n,r,o]=$();function i(){if(!l())return;const{status:e}=c;t({...r,get status(){return e},get finished(){return n.ended},headers:Object.freeze(c.getHeaders()),[Symbol.asyncIterator]:()=>r})}s.catch((e=>o(e)));const u={get finished(){return n.ended},write:e=>(i(),n.write(e))},a=Object.create(c,Object.getOwnPropertyDescriptors(u));Promise.race([s,U(a,e)]).then((()=>{i(),f(),n.end()}),(e=>{c.status=500,i(),o(e),f(e||!0),n.end()}))}))),(e=>(f(e||!0),Promise.reject(e))))}function I(e,t){const n=a(t?.asset),o=r(t?.setting),i=y(t?.log),s=async(t,n)=>e(t,n);return e=>B(e,s,o,n,i)}async function C(e,t,n,r,o){if(!(e instanceof D))return r(o),e;if(e.disabled)return null;const i=await async function(e,t,n,r){if(!e.size)return!0;n(r);for(const n of e){if(t.destroyed)return!1;const e=await n(Object.create(t,{params:{value:{...r}}}));if(!1===e)return!1;if("function"==typeof e)return e}return!0}(e.guards,n,r,o);if(!i)return null;if("function"==typeof i)return i;if(n.destroyed)return null;for await(const[i,s,u]of e.find(n.method,t)){if(n.destroyed)return null;const e=C(i,u,n,r,{...o,...s});if(e)return e}return null}function L(e){try{return decodeURIComponent(e)}catch{return e}}class D{disabled=!1;static make(e){return async(t,n)=>{const r=e.flat(),o=t.pathname.split("/").filter(Boolean).map(L);for(const e of r){const r=await C(e,o,t,n,{});if(r)return r}return null}}static create(e){return Object.create(D.prototype,{find:{configurable:!0,value:e,writable:!0}})}guards=new Set}const H=/^:([a-zA-Z][a-zA-Z0-9]*)(?:\((.+)\))?([ius]+)?([?+*]?)$/;function M(e){const t=H.exec(e);if(!t)return e;const[,n,r=".*",o,i]=t;if(!r)return{name:n,pattern:new RegExp("^.*$",o),optional:"?"===i||"*"===i,many:"+"===i||"*"===i};let s=0,u=0;const c=["^(?:"];for(;s<r.length;){const t=r[s++];if(c.push(t),"\\"!==t)if(")"!==t)if("["!==t){if("("===t&&(u++,"?"===r[s]&&(s+=2,":"!==r[s-1])))return e}else for(;s<r.length;){const e=r[s++];if(c.push(e),"]"===e)break;"\\"===e&&c.push(r[s++])}else{if(0===u)return e;u--}else c.push(r[s++])}return u?e:(c.push(")$"),{name:n,pattern:new RegExp(c.join(""),o),optional:"?"===i||"*"===i,many:"+"===i||"*"===i})}function z(e,t){const n=[];for(const t of e.split("/"))t&&!/^\.+$/.test(t)&&n.push(M(t));if(n.length)return e=>function(e,t,n){const r={};for(let n=0;n<e.length;n++){const o=e[n],i=t[n];if(o!==i){if("string"==typeof o)return;if(!i)return o.optional?[r,[]]:void 0;if(!o.pattern.test(i))return;r[o.name]=i}}if(!n)return[r,t.slice(e.length)];if(t.length<=e.length)return[r,[]];const o=e[e.length-1];if("string"!=typeof o&&(o.many||!(t.length>e.length))){for(let n=e.length;n<t.length;n++)if(!o.pattern.test(t[n]))return;return r[o.name]=t.slice(e.length-1),[r,[]]}}(n,e,t)}function _(e,t,n,r){const o={match:z(n||"",!0),methods:new Set(t),handler:r};e.push(o);let i=!1;return()=>{if(i)return;i=!0;const t=e.indexOf(o);t<0||e.splice(t,1)}}function q(e,t,n){if(!n.length)return n=>_(e,t,"",n);const[r,o]=n;if(r&&"object"==typeof r){const o=String.raw(r,...n.slice(1));return n=>_(e,t,o,n)}const i="string"==typeof r?r:"",s=[r,o].find((e=>"function"==typeof e));return s?_(e,t,i,s):n=>_(e,t,i,n)}const G=new Set(["GET","POST","PUT","DELETE","HEAD","OPTIONS"]);function F(e){return G.has(e)}function N(e,t,n){const r=n instanceof D?n:"function"==typeof n?D.create(n):new Z;return e.push({match:z(t,!1),router:r}),r}class Z extends D{#e=[];route(...e){const[t]=e;if(t&&"object"==typeof t&&!(t instanceof D)){const n=String.raw(t,...e.slice(1));return e=>N(this.#e,n,e)}const n="string"==typeof t?t:"",r="string"==typeof t?e[1]:t;return N(this.#e,n,r)}*find(e,t){for(const n of Array.from(this.#e)){if(!n.router&&!n.methods.has(e))continue;const{match:r}=n;if(!r){!n.router&&t.length||(yield[n.router||n.handler,{},t]);continue}if(!t.length)continue;const o=r(t);o&&(yield[n.router||n.handler,...o])}}verb(e,t,n){const r=function(e){return e?"string"==typeof e?[e.toUpperCase()].filter(F):Array.from(e).map((e=>"string"==typeof e&&e.toUpperCase())).filter(F):["GET","POST","PUT","DELETE"]}(e);return r.length?q(this.#e,r,[t,n]):()=>{}}match(...e){return q(this.#e,["GET","POST","PUT","DELETE"],e)}get(...e){return q(this.#e,["GET"],e)}post(...e){return q(this.#e,["POST"],e)}put(...e){return q(this.#e,["PUT"],e)}delete(...e){return q(this.#e,["DELETE"],e)}head(...e){return q(this.#e,["HEAD"],e)}options(...e){return q(this.#e,["OPTIONS"],e)}}const V="[a-zA-Z][a-zA-Z0-9_-]*",J=`${V}(?:.${V})*`,K=new RegExp(`^/(${V})/((?:@${J}/)?${J})/(.+)$`);class Q{static make(e,{router:t,setting:n,asset:r,log:o}={}){const i=[];for(const t of Object.values(e))i.push(t.router);return t instanceof D&&i.push(t),I(D.make(i),{setting:n,asset:Q.bindAsset(r,e),log:o})}static bindAsset(e,t,n="plugins"){if(!t)return e;const r=e?.read;return"function"!=typeof r?e:{...e,read:async e=>{const o=await r(e);if(null!==o)return o;if(!t)return null;const i=K.exec(e);if(!i)return null;const[,s,u,c]=i;if(s!==n)return null;if(!(u in t))return null;const a=t[u];return a?a.readAsset(c):null}}}constructor(e,t,{author:n,license:r}={}){this.name=e,this.version="string"==typeof t?t:"",this.author="string"==typeof n?n:"",this.license="string"==typeof r?r:""}initRouter(){const{router:e}=this;return this.__initRouterPromise?this.__initRouterPromise:this.__initRouterPromise=Promise.resolve(this._initRouter(e)).then((()=>e))}get router(){const e=this._createRouter();return Reflect.defineProperty(this,"router",{value:e,configurable:!0}),this.initRouter(),e}get disabled(){return this.router.disabled}set disabled(e){this.router.disabled=e}}e.ApiRouter=Z,e.Plugin=Q,e.Router=D,e.make=I,e.merge=function(...e){return t=>async function(e,t){for(const n of t){if(e.headersSent)break;const t=await n(e);if(e.finished)break;if("boolean"==typeof t)return t;if(t)return t}}(t,e.flat())},e.run=function(e,t,n){const o=a(n?.asset);return B(e,(async(e,n)=>t(e,n)),r(n?.setting),o,y(n?.log))},e.service=function(e,t,n){const r=function(n,...o){return n.currentService!==r?n.service(r,...o):n.destroying?"function"==typeof t?t(n):void 0:e(n,...o)},{rootOnly:o}="object"==typeof t&&t||"object"==typeof n&&n||{};return Object.assign(r,{rootOnly:Boolean(o)}),r},e.stateService=function(e,t,n,r){const o=function(r){if(r.currentService!==o)return r.service(o);if(!r.destroying){let{state:t}=r;return t||(t=e(r)||{},r.state=t),"function"==typeof n&&n(t,r),t}return"function"==typeof t?t(r.state,r):void 0},{rootOnly:i}="object"==typeof t&&t||"object"==typeof n&&n||"object"==typeof r&&r||{};return Object.assign(o,{rootOnly:Boolean(i)}),o},e.storeService=function(e,t,n){const r=function(n,...o){if(n.currentService!==r)return n.service(r,...o);if(!n.destroying){if(!o.length)return n.state;const[e]=o;return n.state=e,"function"==typeof t&&t(e,n),e}return"function"==typeof e?e(n.state,n):void 0},{rootOnly:o}="object"==typeof e&&e||"object"==typeof t&&t||"object"==typeof n&&n||{};return Object.assign(r,{rootOnly:Boolean(o)}),r}}));
|
package/index.min.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* k99 v0.6.0-alpha.
|
|
2
|
+
* k99 v0.6.0-alpha.6
|
|
3
3
|
* (c) 2019-2023 猛火Fierflame
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
6
|
-
async function e(){}async function t(){return!1}function n({read:n=e,write:r=t}={}){return{read:n,write:r}}function r(e,t){if(!e)return null;switch(t){case"utf8":return function(e){let t=[],n=0;for(;n<e.length;){let r=0|e[n++];r>=240?(r=(7&r)<<18,r|=(63&e[n++])<<12,r|=(63&e[n++])<<6,r|=63&e[n++]):r>=224?(r=(15&r)<<12,r|=(63&e[n++])<<6,r|=63&e[n++]):r>=192&&(r=(31&r)<<6,r|=63&e[n++]),t.push(r)}return t.map((e=>String.fromCharCode(e))).join("")}(e);case"base64":return function(e,t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"){const n=Math.floor(Math.log2(t.length)),r=(1<<n)-1;let o=new Array(Math.floor(((e.byteLength<<3)+n-1)/n)),i=0,s=0,u=0;for(let a of e)for(s=s<<8|a,u+=8;u>=n;)u-=n,o[i++]=t[s>>u&r],s&=(1<<u)-1;for(u&&(o[i++]=t[s<<n-u&r]);o.length%4;)o.push("=");return o.join("")}(e);case"hex":return function(e){let t=new Array(2*e.byteLength);for(let n of e)t.push(n>>4&4369,4369&n);return t.map((e=>"0123456789ABCDEF"[e])).join("")}(e)}return e}let o="0123456789ABCDEF";function i(e,t){if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(e instanceof ArrayBuffer)return new Uint8Array(e);if("string"!=typeof e)return null;switch(t){default:case"utf8":return function(e){let t=[],n=0;for(;n<e.length;n++){const r=e.codePointAt(n);if("number"!=typeof r)break;r>=65536&&n++,r<128?t.push(r):r<2048?(t.push(192|31&r>>6),t.push(128|63&r)):r<65536?(t.push(224|15&r>>12),t.push(128|63&r>>6),t.push(128|63&r)):(t.push(240|7&r>>18),t.push(128|63&r>>12),t.push(128|63&r>>6),t.push(128|63&r))}return new Uint8Array(t)}(e);case"base64":return function(e,t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"){const n=Math.floor(Math.log2(t.length));e=e.replace(/[=\s]+/g,"");let r=new Uint8Array(e.length*n>>3),o=0,i=0,s=0;for(let u of e)for(i=i<<n|t.indexOf(u),s+=n;s>=8;)s-=8,r[o++]=i>>s&255,i&=(1<<s)-1;return r}(e);case"hex":return function(e){let t=[];for(let n=0;n<e.length;n+=2)t.push(16*o.indexOf(e[n])+o.indexOf(e[n+1]||"0"));return new Uint8Array(t)}(e)}}async function s(){return null}async function u(){return!1}function a({read:e=s,write:t=u,delete:n=u,stat:o=s}={}){return{read:async function(t,n){const o=await e(t);return o&&r(o,n)},write:async function(e,r,o){if(void 0===r)return n(e);const s=i(r,o);return s?t(e,s):n(e)},delete:function(e){return n(e)},stat:async function(e){return o(e)}}}function c(e){return"string"==typeof e?e:e instanceof Error?e.stack||`${e.name}:${e.message}`:String(e)}const f=/(?:^|\/)(debug|error|warn|info)\/?$|^\/?(debug|error|warn|info)(?:\/|$)/;async function l(e,t){switch(e){case"debug":console.debug(t);break;case"info":console.info(t);break;case"warn":console.warn(t);break;case"error":console.error(t)}console.group(`log @ ${e}`);const n=f.exec(e);switch(n?n[1]||n[2]:""){case"debug":console.debug(t);break;case"info":console.info(t);break;case"warn":console.warn(t);break;case"error":console.error(t);break;default:console.log(t)}return console.groupEnd(),!0}async function h(){return""}async function p(){}function d({read:e=h,write:t=l,clear:n=p}={}){function r(e,n,r){return t(e,function(e,{tags:t,indent:n,date:r}={}){let o="";return t&&(Array.isArray(t)||(t=[t]),o=t.map((e=>`[${e}]`)).join(" ")),r&&(o=`${(new Date).toISOString()} ${o}`),e.includes("\n")?("number"==typeof n&&(n=Math.floor(n),isFinite(n)&&n>0&&(n=Array(n).fill(" ").join(""))),n&&"string"==typeof n||(n=" "),e=(e=`${o}\n${e}`).split("\n").join(`\n${n}`)):`${o} ${e}`}(n,r))}return{read:e,write:r,clear:n,debug:async(e,t)=>r("debug",e,t),info:async(e,t)=>r("info",e,t),warn:async(e,t)=>r("warn",c(e),t),error:async(e,t)=>r("error",c(e),t)}}function y(e,t){if(1===e.length)return new Uint8Array(e[0]);const n=new Uint8Array(t);let r=0;for(const t of e)n.set(t,r),r+=t.byteLength;return n}function g(e,t){if(!t){const t=y(e,e.reduce(((e,t)=>e+t.byteLength),0));return e.length=0,t}let n=0;const r=[];for(let o;o=e.shift();){if(n+o.byteLength>t){const i=o.slice(0,t-n);r.push(i),n+=i.byteLength,e.unshift(o.slice(i.byteLength));break}if(r.push(o),n+=o.byteLength,n===t)break}return y(r,n)}async function*m(e){if(e){if("string"==typeof e)return yield i(e);if("object"==typeof e){if(e instanceof ArrayBuffer)return yield i(e);if(ArrayBuffer.isView(e))return yield i(e);if(Symbol.asyncIterator in e||Symbol.iterator in e)for await(const t of e)yield*m(t)}}}async function b(e,t){const n=[];let r=0,[o,i]=await t();for await(const s of m(e))if(n.push(s),r+=s.byteLength,o<=0)r=0,i(g(n)),[o,i]=await t();else for(r>=o&&(r-=o,i(g(n,o)),[o,i]=await t());r&&(o<=0||o<=r);){if(o<=0){r=0,i(g(n)),[o,i]=await t();break}r-=o,i(g(n,o)),[o,i]=await t()}for(r&&(i(g(n)),[o,i]=await t()),i(null);;)[o,i]=await t(),i(null)}function w(e){if(!e)return()=>Promise.resolve(null);const t=[];let n=null;return b(e,(function(){return new Promise((e=>{const r=t.shift();if(r)return e(r);n=t=>{n=null,e(t)}}))})),function(e=0){return new Promise((r=>{e=Math.max(e,0),n?n([e,r]):t.push([e,r])}))}}const O=/^(?:(?:https?:)?\/\/(?:(?:[^/?#]*@)?)(?:\d+|(?:\[[0-9a-f:]+\])|(?:\d{1,3}\.){3}\d{1,3}|(?:(?:[a-z0-9\u0100-\uffff]+-*)+\.)+[a-z]+)(?::\d+)?)?((?:\/?[^?#]*)?)((?:\?[^#]*)?)(?:#.*)?$/i;function P(e){const t=e.indexOf("=");return t<0?[decodeURIComponent(e),""]:[decodeURIComponent(e.substring(0,t)),decodeURIComponent(e.substring(t+1))]}function j(e){const t={};for(const n of e.split("&").filter(Boolean)){const[e,r]=P(n);t[e]=e in t?[t[e],r].flat():[r]}return t}function v({method:e,path:t,signal:n,body:r,headers:o={}}){const[i,s]=function(e){const t=O.exec(e);if(!t)return["/",""];let[,n,r]=t;const o=[];for(const e of n.replace(/^[\\/]+/,"").replace(/[\\/]+/g,"/").split("/"))"."!==e&&(".."!==e?o.push(e):o.pop());return[`/${o.join("/")}`,r]}(t);return{method:e,url:`${i}${s}`,headers:o,pathname:i,search:s,signal:n||(new AbortController).signal,query:j(s.substring(1)),read:"function"==typeof r?r:w(r)}}function A(e){return e instanceof ArrayBuffer||!!ArrayBuffer.isView(e)}function $(){let e=!1,t=[],n=null;function r(n){if(e)return null;e=!0,n&&n(!1);for(let e;e=t.shift();){const[,t]=e;t(!1)}return null}let o=Promise.resolve((()=>{}));const s={next(){const e=o.then((e=>{if(e)return u?(e(!1),c):(e(!0),Promise.race([c,new Promise((e=>{const r=t.shift();if(r)return e(r);n=t=>{n=null,e(t)}})).then((e=>{const[t,n]=e;if(!u&&void 0!==t)return e;n(!u)}))]))}));return o=e.then((e=>{if(!e)return null;const[,t]=e;return t}),(()=>r())),e.then((e=>{if(!e)return{done:!0,value:void 0};const[t,n]=e;return{done:!1,value:t}}))},throw:e=>(o=o.then(r),o.then((()=>Promise.reject(e)))),return:e=>(o=o.then(r),o.then((()=>e))),[Symbol.asyncIterator]:()=>s};let u,a,c=new Promise(((e,t)=>{u?t(u):a=t}));function f(r,o){if(e)return o(!1);n?n([r,o]):t.push([r,o])}let l=Promise.resolve(!0);async function h(t){if(e)return Promise.resolve();if("string"==typeof t)return new Promise((e=>f(i(t),e)));if("object"!=typeof t)return!1;if(A(t))return new Promise((e=>f(i(t),e)));if(!(Symbol.asyncIterator in t)&&!(Symbol.iterator in t))return!1;for await(const n of t){if(e)return Promise.resolve();if(n&&!await h(n))return!1}return!0}let p=!1;return[{write(e){const t=l.then((t=>{if(void 0!==t)return!e||h(e)}));return l=t,t.then((e=>Boolean(e)))},end(){p=!0;const r=l.then((r=>new Promise((o=>{if(void 0===r||e)return o();n?n([void 0,()=>o()]):t.push([void 0,()=>o()])}))));return l=r,r},get ended(){return e||p}},s,function(e){return!u&&(u=e||new DOMException("The user aborted a request."),a&&a(u),!0)}]}function x(e){return e.map((({name:e,value:t,expire:n,domain:r,path:o,secure:i,httpOnly:s})=>e&&[`${encodeURI(e)}=${encodeURI(t||"")}`,n&&`Expires=${n}`,r&&`Domain=${encodeURI(r)}`,o&&`Path=${encodeURI(o)}`,i&&"Secure",s&&"HttpOnly"].filter(Boolean).join("; "))).filter(Boolean)}function E(e){let t=Promise.resolve(!1);return function(n=0,o){const i=t.then((t=>t?null:e(n)));return t=i.then((e=>!e)),i.then((e=>r(e,o)))}}const S=/^(\[[^\]]+\]|^:):(\d+)$/;function k({method:e,url:t,pathname:n,search:r,query:o,read:i,headers:s,signal:u},a,c,f,l,h){const p=new Map,d=s.host||"",y=S.exec(d),[g,m]=y?[y[1],y[2]]:[d,""],b=function(e){let t={};for(const n of e.replace(/\s/g,"").split(";")){const e=n.split("=");t[decodeURIComponent(e.shift())]=decodeURIComponent(e.join("="))}return t}(s.cookie||""),w=[];let O=200,P={},j=!1,v=!1;const A=h?.root;let $=null,k={};const T={setting:a,asset:c,log:f,parent:h,get error(){return $},get root(){return A||this},signal:u,request:l,service(e,...t){if(e.rootOnly&&A)return A.service(e,...t);let n=p.get(e);if(!n){let t;n=Object.create(T,{destroying:{value:!1,configurable:!0,enumerable:!0},state:{configurable:!0,enumerable:!0,get:()=>t,set(e){t=e}}}),p.set(e,n)}return e(n,...t)},method:e,url:t,pathname:n,search:r,query:o,get params(){return k},headers:Object.freeze({...s}),host:d,hostname:g,port:m,requestType:s["content-type"]||"",referer:s.referer||"",userAgent:s["user-agent"]||"",accept:(s.accept||"").split(/,\s*/).filter(Boolean),acceptLanguage:(s["accept-language"]||"").split(/,\s*/).filter(Boolean),cookies:b,read:E(i),get destroyed(){return v},get headersSent(){return j},get status(){return O},set status(e){j||(O=e)},get location(){return P.location||""},set location(e){j||(P.location=e)},get responseType(){return P["content-type"]||""},set responseType(e){j||(P["content-type"]=e)},getCookie:e=>function*(e,t){const n=e;for(const e of n)t&&e.name!==t||(yield{...e})}(w,e),setCookie(e,t,{expire:n,domain:r,path:o,secure:i,httpOnly:s}={}){j||(w.push({name:e,value:t,expire:n,domain:r,path:o,secure:i,httpOnly:s}),P["set-cookie"]=x(w))},clearCookie(e,t){j||(!function(e,t,n,r){let o="Fri, 31 Dec 1999 16:00:00 GMT";if("string"==typeof n){if(!n)return;const{domain:t,path:i,secure:s,httpOnly:u}=!0!==r&&r||{};e.push({name:n,value:"delete",expire:o,domain:t,path:i,secure:s,httpOnly:u})}else{const{domain:i,path:s,secure:u,httpOnly:a}=n||{};if(e.length=0,r)for(let n in t)e.push({name:n,value:"delete",expire:o,domain:i,path:s,secure:u,httpOnly:a})}}(w,b,e,t),P["set-cookie"]=x(w))},hasHeader:e=>e in P,getHeaderNames:()=>Object.keys(P),getHeaders:()=>({...P}),getHeader:e=>P[e],setHeader(e,t){j||(void 0===t?delete P[e]:P[e]=t)}};return{context:T,setParams:e=>{k=e},destroy:e=>{v||(v=!0,j=!0,e&&($=e),function(e,t){let n=Promise.resolve();for(const[r,o]of[...t.entries()])n=n.then((()=>r(Object.create(o,{destroying:{value:!0,configurable:!0,enumerable:!0}})))).catch((t=>e.error(t)))}(f,p))},sendHeaders:()=>!j&&(j=!0,!0)}}function T(e,t){return"bigint"==typeof t?String(t):t}async function U(e,t){if(e.headersSent)return;const n=await t(e);if(!e.finished){if(function(e){return!(!e||"object"!=typeof e||!Array.isArray(e)&&(A(e)||Symbol.asyncIterator in e||Symbol.iterator in e))}(n)){if(e.headersSent)return;return e.responseType="application/json",void await e.write(JSON.stringify(n,T))}return e.write(n)}}function R(e,t,n,r,o,i){const s=(u=e.signal,new Promise(((e,t)=>{if(u.aborted)return t(u.reason);u.addEventListener("abort",(()=>t(u.reason)),{once:!0})})));var u;const{context:a,setParams:c,destroy:f,sendHeaders:l}=k(e,n,r,o,(e=>R(v(e),t,n,r,o,a)),i);return Promise.race([s,t(a,c)]).then((e=>new Promise((t=>{if(!e)return f(),t(null);const[n,r,o]=$();function i(){if(!l())return;const{status:e}=a;t({...r,get status(){return e},get finished(){return n.ended},headers:Object.freeze(a.getHeaders()),[Symbol.asyncIterator]:()=>r})}s.catch((e=>o(e)));const u={get finished(){return n.ended},write:e=>(i(),n.write(e))},c=Object.create(a,Object.getOwnPropertyDescriptors(u));Promise.race([s,U(c,e)]).then((()=>{i(),f(),n.end()}),(e=>{a.status=500,i(),o(e),f(e||!0),n.end()}))}))),(e=>(f(e||!0),Promise.reject(e))))}function B(e,t,r){const o=a(r?.asset);return R(e,(async(e,n)=>t(e,n)),n(r?.setting),o,d(r?.log))}function I(e,t){const r=a(t?.asset),o=n(t?.setting),i=d(t?.log),s=async(t,n)=>e(t,n);return e=>R(e,s,o,r,i)}function C(...e){return t=>async function(e,t){for(const n of t){if(e.headersSent)break;const t=await n(e);if(e.finished)break;if("boolean"==typeof t)return t;if(t)return t}}(t,e.flat())}function L(e,t,n){const r=function(n,...r){return n.destroying?"function"==typeof t?t(n):void 0:e(n,...r)},{rootOnly:o}="object"==typeof t&&t||"object"==typeof n&&n||{};return Object.assign(r,{rootOnly:Boolean(o)}),r}function D(e,t,n,r){const o=function(r){if(!r.destroying){let{state:t}=r;return t||(t=e(r)||{},r.state=t),"function"==typeof n&&n(t,r),t}if("function"==typeof t)return t(r.state,r)},{rootOnly:i}="object"==typeof t&&t||"object"==typeof n&&n||"object"==typeof r&&r||{};return Object.assign(o,{rootOnly:Boolean(i)}),o}function H(e,t,n){const r=function(n,...r){if(!n.destroying){if(!r.length)return n.state;const[e]=r;return n.state=e,"function"==typeof t&&t(e,n),e}if("function"==typeof e)return e(n.state,n)},{rootOnly:o}="object"==typeof e&&e||"object"==typeof t&&t||"object"==typeof n&&n||{};return Object.assign(r,{rootOnly:Boolean(o)}),r}async function M(e,t,n,r,o){if(!(e instanceof _))return r(o),e;if(e.disabled)return null;const i=await async function(e,t,n,r){if(!e.size)return!0;n(r);for(const n of e){if(t.destroyed)return!1;const e=await n(Object.create(t,{params:{value:{...r}}}));if(!1===e)return!1;if("function"==typeof e)return e}return!0}(e.guards,n,r,o);if(!i)return null;if("function"==typeof i)return i;if(n.destroyed)return null;for await(const[i,s,u]of e.find(n.method,t)){if(n.destroyed)return null;const e=M(i,u,n,r,{...o,...s});if(e)return e}return null}function z(e){try{return decodeURIComponent(e)}catch{return e}}class _{disabled=!1;static make(e){return async(t,n)=>{const r=e.flat(),o=t.pathname.split("/").filter(Boolean).map(z);for(const e of r){const r=await M(e,o,t,n,{});if(r)return r}return null}}static create(e){return Object.create(_.prototype,{find:{configurable:!0,value:e,writable:!0}})}guards=new Set}const q=/^:([a-zA-Z][a-zA-Z0-9]*)(?:\((.+)\))?([ius]+)?([?+*]?)$/;function G(e){const t=q.exec(e);if(!t)return e;const[,n,r=".*",o,i]=t;if(!r)return{name:n,pattern:new RegExp("^.*$",o),optional:"?"===i||"*"===i,many:"+"===i||"*"===i};let s=0,u=0;const a=["^("];for(;s<r.length;){const t=r[s++];if(a.push(t),"\\"!==t)if(")"!==t)if("["!==t){if("("===t&&(u++,"?"===r[s]&&(s+=2,":"!==r[s-1])))return e}else for(;s<r.length;){const e=r[s++];if(a.push(e),"]"===e)break;"\\"===e&&a.push(r[s++])}else{if(0===u)return e;u--}else a.push(r[s++])}return u?e:(a.push(")$"),{name:n,pattern:new RegExp(a.join(""),o),optional:"?"===i||"*"===i,many:"+"===i||"*"===i})}function F(e,t){const n=[];for(const t of e.split("/"))t&&!/^\.+$/.test(t)&&n.push(G(t));if(n.length)return e=>function(e,t,n){const r={};for(let n=0;n<e.length;n++){const o=e[n],i=t[n];if(o!==i){if("string"==typeof o)return;if(!i)return o.optional?[r,[]]:void 0;if(!o.pattern.test(i))return;r[o.name]=i}}if(!n)return[r,t.slice(e.length)];if(t.length<=e.length)return[r,[]];const o=e[e.length-1];if("string"!=typeof o&&(o.many||!(t.length>e.length))){for(let n=e.length;n<t.length;n++)if(!o.pattern.test(t[n]))return;return r[o.name]=t.slice(e.length-1),[r,[]]}}(n,e,t)}function N(e,t,n,r){const o="string"==typeof n?n:"",i=[n,r].find((e=>"function"==typeof e));if(!i)return()=>{};const s={match:F(o||"",!0),methods:new Set(t),handler:i};e.push(s);let u=!1;return()=>{if(u)return;u=!0;const t=e.indexOf(s);t<0||e.splice(t,1)}}const Z=new Set(["GET","POST","PUT","DELETE","HEAD","OPTIONS"]);function V(e){return Z.has(e)}class J extends _{#e=[];route(e,t){const n="string"==typeof e?t:e,r=n instanceof _?n:"function"==typeof n?_.create(n):new J,o="string"==typeof e?e:"";return this.#e.push({match:F(o,!1),router:r}),r}*find(e,t){for(const n of Array.from(this.#e)){if(!n.router&&!n.methods.has(e))continue;const{match:r}=n;if(!r){!n.router&&t.length||(yield[n.router||n.handler,{},t]);continue}if(!t.length)continue;const o=r(t);o&&(yield[n.router||n.handler,...o])}}verb(e,t,n){const r=function(e){return e?"string"==typeof e?[e.toUpperCase()].filter(V):Array.from(e).map((e=>"string"==typeof e&&e.toUpperCase())).filter(V):["GET","POST","PUT","DELETE"]}(e);return r.length?N(this.#e,r,t,n):()=>{}}match(e,t){return N(this.#e,["GET","POST","PUT","DELETE"],e,t)}get(e,t){return N(this.#e,["GET"],e,t)}post(e,t){return N(this.#e,["POST"],e,t)}put(e,t){return N(this.#e,["PUT"],e,t)}delete(e,t){return N(this.#e,["DELETE"],e,t)}head(e,t){return N(this.#e,["HEAD"],e,t)}options(e,t){return N(this.#e,["OPTIONS"],e,t)}}const K="[a-zA-Z][a-zA-Z0-9_-]*",Q=`${K}(?:.${K})*`,W=new RegExp(`^/(${K})/((?:@${Q}/)?${Q})/(.+)$`);class X{static make(e,{router:t,setting:n,asset:r,log:o}={}){const i=[];for(const t of Object.values(e))i.push(t.router);return t instanceof _&&i.push(t),I(_.make(i),{setting:n,asset:X.bindAsset(r,e),log:o})}static bindAsset(e,t,n="plugins"){if(!t)return e;const r=e?.read;return"function"!=typeof r?e:{...e,read:async e=>{const o=await r(e);if(null!==o)return o;if(!t)return null;const i=W.exec(e);if(!i)return null;const[,s,u,a]=i;if(s!==n)return null;if(!(u in t))return null;const c=t[u];return c?c.readAsset(a):null}}}constructor(e,t,{author:n,license:r}={}){this.name=e,this.version="string"==typeof t?t:"",this.author="string"==typeof n?n:"",this.license="string"==typeof r?r:""}initRouter(){const{router:e}=this;return this.__initRouterPromise?this.__initRouterPromise:this.__initRouterPromise=Promise.resolve(this._initRouter(e)).then((()=>e))}get router(){const e=this._createRouter();return Reflect.defineProperty(this,"router",{value:e,configurable:!0}),this.initRouter(),e}get disabled(){return this.router.disabled}set disabled(e){this.router.disabled=e}}export{J as ApiRouter,X as Plugin,_ as Router,I as make,C as merge,B as run,L as service,D as stateService,H as storeService};
|
|
6
|
+
async function e(){}async function t(){return!1}function n({read:n=e,write:r=t}={}){return{read:n,write:r}}function r(e,t){if(!e)return null;switch(t){case"utf8":return function(e){let t=[],n=0;for(;n<e.length;){let r=0|e[n++];r>=240?(r=(7&r)<<18,r|=(63&e[n++])<<12,r|=(63&e[n++])<<6,r|=63&e[n++]):r>=224?(r=(15&r)<<12,r|=(63&e[n++])<<6,r|=63&e[n++]):r>=192&&(r=(31&r)<<6,r|=63&e[n++]),t.push(r)}return t.map((e=>String.fromCharCode(e))).join("")}(e);case"base64":return function(e,t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"){const n=Math.floor(Math.log2(t.length)),r=(1<<n)-1;let o=new Array(Math.floor(((e.byteLength<<3)+n-1)/n)),i=0,s=0,u=0;for(let c of e)for(s=s<<8|c,u+=8;u>=n;)u-=n,o[i++]=t[s>>u&r],s&=(1<<u)-1;for(u&&(o[i++]=t[s<<n-u&r]);o.length%4;)o.push("=");return o.join("")}(e);case"hex":return function(e){let t=new Array(2*e.byteLength);for(let n of e)t.push(n>>4&4369,4369&n);return t.map((e=>"0123456789ABCDEF"[e])).join("")}(e)}return e}let o="0123456789ABCDEF";function i(e,t){if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(e instanceof ArrayBuffer)return new Uint8Array(e);if("string"!=typeof e)return null;switch(t){default:case"utf8":return function(e){let t=[],n=0;for(;n<e.length;n++){const r=e.codePointAt(n);if("number"!=typeof r)break;r>=65536&&n++,r<128?t.push(r):r<2048?(t.push(192|31&r>>6),t.push(128|63&r)):r<65536?(t.push(224|15&r>>12),t.push(128|63&r>>6),t.push(128|63&r)):(t.push(240|7&r>>18),t.push(128|63&r>>12),t.push(128|63&r>>6),t.push(128|63&r))}return new Uint8Array(t)}(e);case"base64":return function(e,t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"){const n=Math.floor(Math.log2(t.length));e=e.replace(/[=\s]+/g,"");let r=new Uint8Array(e.length*n>>3),o=0,i=0,s=0;for(let u of e)for(i=i<<n|t.indexOf(u),s+=n;s>=8;)s-=8,r[o++]=i>>s&255,i&=(1<<s)-1;return r}(e);case"hex":return function(e){let t=[];for(let n=0;n<e.length;n+=2)t.push(16*o.indexOf(e[n])+o.indexOf(e[n+1]||"0"));return new Uint8Array(t)}(e)}}async function s(){return null}async function u(){return!1}function c({read:e=s,write:t=u,delete:n=u,stat:o=s}={}){return{read:async function(t,n){const o=await e(t);return o&&r(o,n)},write:async function(e,r,o){if(void 0===r)return n(e);const s=i(r,o);return s?t(e,s):n(e)},delete:function(e){return n(e)},stat:async function(e){return o(e)}}}function a(e){return"string"==typeof e?e:e instanceof Error?e.stack||`${e.name}:${e.message}`:String(e)}const f=/(?:^|\/)(debug|error|warn|info)\/?$|^\/?(debug|error|warn|info)(?:\/|$)/;async function l(e,t){switch(e){case"debug":console.debug(t);break;case"info":console.info(t);break;case"warn":console.warn(t);break;case"error":console.error(t)}console.group(`log @ ${e}`);const n=f.exec(e);switch(n?n[1]||n[2]:""){case"debug":console.debug(t);break;case"info":console.info(t);break;case"warn":console.warn(t);break;case"error":console.error(t);break;default:console.log(t)}return console.groupEnd(),!0}async function h(){return""}async function p(){}function d({read:e=h,write:t=l,clear:n=p}={}){function r(e,n,r){return t(e,function(e,{tags:t,indent:n,date:r}={}){let o="";return t&&(Array.isArray(t)||(t=[t]),o=t.map((e=>`[${e}]`)).join(" ")),r&&(o=`${(new Date).toISOString()} ${o}`),e.includes("\n")?("number"==typeof n&&(n=Math.floor(n),isFinite(n)&&n>0&&(n=Array(n).fill(" ").join(""))),n&&"string"==typeof n||(n=" "),e=(e=`${o}\n${e}`).split("\n").join(`\n${n}`)):`${o} ${e}`}(n,r))}return{read:e,write:r,clear:n,debug:async(e,t)=>r("debug",e,t),info:async(e,t)=>r("info",e,t),warn:async(e,t)=>r("warn",a(e),t),error:async(e,t)=>r("error",a(e),t)}}function y(e,t){if(1===e.length)return new Uint8Array(e[0]);const n=new Uint8Array(t);let r=0;for(const t of e)n.set(t,r),r+=t.byteLength;return n}function g(e,t){if(!t){const t=y(e,e.reduce(((e,t)=>e+t.byteLength),0));return e.length=0,t}let n=0;const r=[];for(let o;o=e.shift();){if(n+o.byteLength>t){const i=o.slice(0,t-n);r.push(i),n+=i.byteLength,e.unshift(o.slice(i.byteLength));break}if(r.push(o),n+=o.byteLength,n===t)break}return y(r,n)}async function*b(e){if(e){if("string"==typeof e)return yield i(e);if("object"==typeof e){if(e instanceof ArrayBuffer)return yield i(e);if(ArrayBuffer.isView(e))return yield i(e);if(Symbol.asyncIterator in e||Symbol.iterator in e)for await(const t of e)yield*b(t)}}}async function m(e,t){const n=[];let r=0,[o,i]=await t();for await(const s of b(e))if(n.push(s),r+=s.byteLength,o<=0)r=0,i(g(n)),[o,i]=await t();else for(r>=o&&(r-=o,i(g(n,o)),[o,i]=await t());r&&(o<=0||o<=r);){if(o<=0){r=0,i(g(n)),[o,i]=await t();break}r-=o,i(g(n,o)),[o,i]=await t()}for(r&&(i(g(n)),[o,i]=await t()),i(null);;)[o,i]=await t(),i(null)}function w(e){if(!e)return()=>Promise.resolve(null);const t=[];let n=null;return m(e,(function(){return new Promise((e=>{const r=t.shift();if(r)return e(r);n=t=>{n=null,e(t)}}))})),function(e=0){return new Promise((r=>{e=Math.max(e,0),n?n([e,r]):t.push([e,r])}))}}const v=/^(?:(?:https?:)?\/\/(?:(?:[^/?#]*@)?)(?:\d+|(?:\[[0-9a-f:]+\])|(?:\d{1,3}\.){3}\d{1,3}|(?:(?:[a-z0-9\u0100-\uffff]+-*)+\.)+[a-z]+)(?::\d+)?)?((?:\/?[^?#]*)?)((?:\?[^#]*)?)(?:#.*)?$/i;function O(e){const t=e.indexOf("=");return t<0?[decodeURIComponent(e),""]:[decodeURIComponent(e.substring(0,t)),decodeURIComponent(e.substring(t+1))]}function P(e){const t={};for(const n of e.split("&").filter(Boolean)){const[e,r]=O(n);t[e]=e in t?[t[e],r].flat():[r]}return t}function j({method:e,path:t,signal:n,body:r,headers:o={}}){const[i,s]=function(e){const t=v.exec(e);if(!t)return["/",""];let[,n,r]=t;const o=[];for(const e of n.replace(/^[\\/]+/,"").replace(/[\\/]+/g,"/").split("/"))"."!==e&&(".."!==e?o.push(e):o.pop());return[`/${o.join("/")}`,r]}(t);return{method:e,url:`${i}${s}`,headers:o,pathname:i,search:s,signal:n||(new AbortController).signal,query:P(s.substring(1)),read:"function"==typeof r?r:w(r)}}function A(e){return e instanceof ArrayBuffer||!!ArrayBuffer.isView(e)}function S(){let e=!1,t=[],n=null;function r(n){if(e)return null;e=!0,n&&n(!1);for(let e;e=t.shift();){const[,t]=e;t(!1)}return null}let o=Promise.resolve((()=>{}));const s={next(){const e=o.then((e=>{if(e)return u?(e(!1),a):(e(!0),Promise.race([a,new Promise((e=>{const r=t.shift();if(r)return e(r);n=t=>{n=null,e(t)}})).then((e=>{const[t,n]=e;if(!u&&void 0!==t)return e;n(!u)}))]))}));return o=e.then((e=>{if(!e)return null;const[,t]=e;return t}),(()=>r())),e.then((e=>{if(!e)return{done:!0,value:void 0};const[t,n]=e;return{done:!1,value:t}}))},throw:e=>(o=o.then(r),o.then((()=>Promise.reject(e)))),return:e=>(o=o.then(r),o.then((()=>e))),[Symbol.asyncIterator]:()=>s};let u,c,a=new Promise(((e,t)=>{u?t(u):c=t}));function f(r,o){if(e)return o(!1);n?n([r,o]):t.push([r,o])}let l=Promise.resolve(!0);async function h(t){if(e)return Promise.resolve();if("string"==typeof t)return new Promise((e=>f(i(t),e)));if("object"!=typeof t)return!1;if(A(t))return new Promise((e=>f(i(t),e)));if(!(Symbol.asyncIterator in t)&&!(Symbol.iterator in t))return!1;for await(const n of t){if(e)return Promise.resolve();if(n&&!await h(n))return!1}return!0}let p=!1;return[{write(e){const t=l.then((t=>{if(void 0!==t)return!e||h(e)}));return l=t,t.then((e=>Boolean(e)))},end(){p=!0;const r=l.then((r=>new Promise((o=>{if(void 0===r||e)return o();n?n([void 0,()=>o()]):t.push([void 0,()=>o()])}))));return l=r,r},get ended(){return e||p}},s,function(e){return!u&&(u=e||new DOMException("The user aborted a request."),c&&c(u),!0)}]}function $(e){return e.map((({name:e,value:t,expire:n,domain:r,path:o,secure:i,httpOnly:s})=>e&&[`${encodeURI(e)}=${encodeURI(t||"")}`,n&&`Expires=${n}`,r&&`Domain=${encodeURI(r)}`,o&&`Path=${encodeURI(o)}`,i&&"Secure",s&&"HttpOnly"].filter(Boolean).join("; "))).filter(Boolean)}function x(e){let t=Promise.resolve(!1);return function(n=0,o){const i=t.then((t=>t?null:e(n)));return t=i.then((e=>!e)),i.then((e=>r(e,o)))}}const E=/^(\[[^\]]+\]|^:):(\d+)$/;function k({method:e,url:t,pathname:n,search:r,query:o,read:i,headers:s,signal:u},c,a,f,l,h){const p=new Map,d=s.host||"",y=E.exec(d),[g,b]=y?[y[1],y[2]]:[d,""],m=function(e){let t={};for(const n of e.replace(/\s/g,"").split(";")){const e=n.split("=");t[decodeURIComponent(e.shift())]=decodeURIComponent(e.join("="))}return t}(s.cookie||""),w=[];let v=200,O={},P=!1,j=!1;const A=h?.root;let S=null,k={};const T={setting:c,asset:a,log:f,parent:h,get error(){return S},get root(){return A||this},signal:u,request:l,service(e,...t){if(e.rootOnly&&A)return A.service(e,...t);let n=p.get(e);if(!n){let t;n=Object.create(T,{destroying:{value:!1,configurable:!0,enumerable:!0},currentService:{value:e,configurable:!0,enumerable:!0},state:{configurable:!0,enumerable:!0,get:()=>t,set(e){t=e}}}),p.set(e,n)}return e(n,...t)},method:e,url:t,pathname:n,search:r,query:o,get params(){return k},headers:Object.freeze({...s}),host:d,hostname:g,port:b,requestType:s["content-type"]||"",referer:s.referer||"",userAgent:s["user-agent"]||"",accept:(s.accept||"").split(/,\s*/).filter(Boolean),acceptLanguage:(s["accept-language"]||"").split(/,\s*/).filter(Boolean),cookies:m,read:x(i),get destroyed(){return j},get headersSent(){return P},get status(){return v},set status(e){P||(v=e)},get location(){return O.location||""},set location(e){P||(O.location=e)},get responseType(){return O["content-type"]||""},set responseType(e){P||(O["content-type"]=e)},getCookie:e=>function*(e,t){const n=e;for(const e of n)t&&e.name!==t||(yield{...e})}(w,e),setCookie(e,t,{expire:n,domain:r,path:o,secure:i,httpOnly:s}={}){P||(w.push({name:e,value:t,expire:n,domain:r,path:o,secure:i,httpOnly:s}),O["set-cookie"]=$(w))},clearCookie(e,t){P||(!function(e,t,n,r){let o="Fri, 31 Dec 1999 16:00:00 GMT";if("string"==typeof n){if(!n)return;const{domain:t,path:i,secure:s,httpOnly:u}=!0!==r&&r||{};e.push({name:n,value:"delete",expire:o,domain:t,path:i,secure:s,httpOnly:u})}else{const{domain:i,path:s,secure:u,httpOnly:c}=n||{};if(e.length=0,r)for(let n in t)e.push({name:n,value:"delete",expire:o,domain:i,path:s,secure:u,httpOnly:c})}}(w,m,e,t),O["set-cookie"]=$(w))},hasHeader:e=>e in O,getHeaderNames:()=>Object.keys(O),getHeaders:()=>({...O}),getHeader:e=>O[e],setHeader(e,t){P||(void 0===t?delete O[e]:O[e]=t)}};return{context:T,setParams:e=>{k=e},destroy:e=>{j||(j=!0,P=!0,e&&(S=e),function(e,t){let n=Promise.resolve();for(const[r,o]of[...t.entries()])n=n.then((()=>r(Object.create(o,{destroying:{value:!0,configurable:!0,enumerable:!0}})))).catch((t=>e.error(t)))}(f,p))},sendHeaders:()=>!P&&(P=!0,!0)}}function T(e,t){return"bigint"==typeof t?String(t):t}async function U(e,t){if(e.headersSent)return;const n=await t(e);if(!e.finished){if(function(e){return!(!e||"object"!=typeof e||!Array.isArray(e)&&(A(e)||Symbol.asyncIterator in e||Symbol.iterator in e))}(n)){if(e.headersSent)return;return e.responseType="application/json",void await e.write(JSON.stringify(n,T))}return e.write(n)}}function R(e,t,n,r,o,i){const s=(u=e.signal,new Promise(((e,t)=>{if(u.aborted)return t(u.reason);u.addEventListener("abort",(()=>t(u.reason)),{once:!0})})));var u;const{context:c,setParams:a,destroy:f,sendHeaders:l}=k(e,n,r,o,(e=>R(j(e),t,n,r,o,c)),i);return Promise.race([s,t(c,a)]).then((e=>new Promise((t=>{if(!e)return f(),t(null);const[n,r,o]=S();function i(){if(!l())return;const{status:e}=c;t({...r,get status(){return e},get finished(){return n.ended},headers:Object.freeze(c.getHeaders()),[Symbol.asyncIterator]:()=>r})}s.catch((e=>o(e)));const u={get finished(){return n.ended},write:e=>(i(),n.write(e))},a=Object.create(c,Object.getOwnPropertyDescriptors(u));Promise.race([s,U(a,e)]).then((()=>{i(),f(),n.end()}),(e=>{c.status=500,i(),o(e),f(e||!0),n.end()}))}))),(e=>(f(e||!0),Promise.reject(e))))}function B(e,t,r){const o=c(r?.asset);return R(e,(async(e,n)=>t(e,n)),n(r?.setting),o,d(r?.log))}function I(e,t){const r=c(t?.asset),o=n(t?.setting),i=d(t?.log),s=async(t,n)=>e(t,n);return e=>R(e,s,o,r,i)}function C(...e){return t=>async function(e,t){for(const n of t){if(e.headersSent)break;const t=await n(e);if(e.finished)break;if("boolean"==typeof t)return t;if(t)return t}}(t,e.flat())}function L(e,t,n){const r=function(n,...o){return n.currentService!==r?n.service(r,...o):n.destroying?"function"==typeof t?t(n):void 0:e(n,...o)},{rootOnly:o}="object"==typeof t&&t||"object"==typeof n&&n||{};return Object.assign(r,{rootOnly:Boolean(o)}),r}function D(e,t,n,r){const o=function(r){if(r.currentService!==o)return r.service(o);if(!r.destroying){let{state:t}=r;return t||(t=e(r)||{},r.state=t),"function"==typeof n&&n(t,r),t}return"function"==typeof t?t(r.state,r):void 0},{rootOnly:i}="object"==typeof t&&t||"object"==typeof n&&n||"object"==typeof r&&r||{};return Object.assign(o,{rootOnly:Boolean(i)}),o}function H(e,t,n){const r=function(n,...o){if(n.currentService!==r)return n.service(r,...o);if(!n.destroying){if(!o.length)return n.state;const[e]=o;return n.state=e,"function"==typeof t&&t(e,n),e}return"function"==typeof e?e(n.state,n):void 0},{rootOnly:o}="object"==typeof e&&e||"object"==typeof t&&t||"object"==typeof n&&n||{};return Object.assign(r,{rootOnly:Boolean(o)}),r}async function M(e,t,n,r,o){if(!(e instanceof _))return r(o),e;if(e.disabled)return null;const i=await async function(e,t,n,r){if(!e.size)return!0;n(r);for(const n of e){if(t.destroyed)return!1;const e=await n(Object.create(t,{params:{value:{...r}}}));if(!1===e)return!1;if("function"==typeof e)return e}return!0}(e.guards,n,r,o);if(!i)return null;if("function"==typeof i)return i;if(n.destroyed)return null;for await(const[i,s,u]of e.find(n.method,t)){if(n.destroyed)return null;const e=M(i,u,n,r,{...o,...s});if(e)return e}return null}function z(e){try{return decodeURIComponent(e)}catch{return e}}class _{disabled=!1;static make(e){return async(t,n)=>{const r=e.flat(),o=t.pathname.split("/").filter(Boolean).map(z);for(const e of r){const r=await M(e,o,t,n,{});if(r)return r}return null}}static create(e){return Object.create(_.prototype,{find:{configurable:!0,value:e,writable:!0}})}guards=new Set}const q=/^:([a-zA-Z][a-zA-Z0-9]*)(?:\((.+)\))?([ius]+)?([?+*]?)$/;function G(e){const t=q.exec(e);if(!t)return e;const[,n,r=".*",o,i]=t;if(!r)return{name:n,pattern:new RegExp("^.*$",o),optional:"?"===i||"*"===i,many:"+"===i||"*"===i};let s=0,u=0;const c=["^(?:"];for(;s<r.length;){const t=r[s++];if(c.push(t),"\\"!==t)if(")"!==t)if("["!==t){if("("===t&&(u++,"?"===r[s]&&(s+=2,":"!==r[s-1])))return e}else for(;s<r.length;){const e=r[s++];if(c.push(e),"]"===e)break;"\\"===e&&c.push(r[s++])}else{if(0===u)return e;u--}else c.push(r[s++])}return u?e:(c.push(")$"),{name:n,pattern:new RegExp(c.join(""),o),optional:"?"===i||"*"===i,many:"+"===i||"*"===i})}function F(e,t){const n=[];for(const t of e.split("/"))t&&!/^\.+$/.test(t)&&n.push(G(t));if(n.length)return e=>function(e,t,n){const r={};for(let n=0;n<e.length;n++){const o=e[n],i=t[n];if(o!==i){if("string"==typeof o)return;if(!i)return o.optional?[r,[]]:void 0;if(!o.pattern.test(i))return;r[o.name]=i}}if(!n)return[r,t.slice(e.length)];if(t.length<=e.length)return[r,[]];const o=e[e.length-1];if("string"!=typeof o&&(o.many||!(t.length>e.length))){for(let n=e.length;n<t.length;n++)if(!o.pattern.test(t[n]))return;return r[o.name]=t.slice(e.length-1),[r,[]]}}(n,e,t)}function N(e,t,n,r){const o={match:F(n||"",!0),methods:new Set(t),handler:r};e.push(o);let i=!1;return()=>{if(i)return;i=!0;const t=e.indexOf(o);t<0||e.splice(t,1)}}function Z(e,t,n){if(!n.length)return n=>N(e,t,"",n);const[r,o]=n;if(r&&"object"==typeof r){const o=String.raw(r,...n.slice(1));return n=>N(e,t,o,n)}const i="string"==typeof r?r:"",s=[r,o].find((e=>"function"==typeof e));return s?N(e,t,i,s):n=>N(e,t,i,n)}const V=new Set(["GET","POST","PUT","DELETE","HEAD","OPTIONS"]);function J(e){return V.has(e)}function K(e,t,n){const r=n instanceof _?n:"function"==typeof n?_.create(n):new Q;return e.push({match:F(t,!1),router:r}),r}class Q extends _{#e=[];route(...e){const[t]=e;if(t&&"object"==typeof t&&!(t instanceof _)){const n=String.raw(t,...e.slice(1));return e=>K(this.#e,n,e)}const n="string"==typeof t?t:"",r="string"==typeof t?e[1]:t;return K(this.#e,n,r)}*find(e,t){for(const n of Array.from(this.#e)){if(!n.router&&!n.methods.has(e))continue;const{match:r}=n;if(!r){!n.router&&t.length||(yield[n.router||n.handler,{},t]);continue}if(!t.length)continue;const o=r(t);o&&(yield[n.router||n.handler,...o])}}verb(e,t,n){const r=function(e){return e?"string"==typeof e?[e.toUpperCase()].filter(J):Array.from(e).map((e=>"string"==typeof e&&e.toUpperCase())).filter(J):["GET","POST","PUT","DELETE"]}(e);return r.length?Z(this.#e,r,[t,n]):()=>{}}match(...e){return Z(this.#e,["GET","POST","PUT","DELETE"],e)}get(...e){return Z(this.#e,["GET"],e)}post(...e){return Z(this.#e,["POST"],e)}put(...e){return Z(this.#e,["PUT"],e)}delete(...e){return Z(this.#e,["DELETE"],e)}head(...e){return Z(this.#e,["HEAD"],e)}options(...e){return Z(this.#e,["OPTIONS"],e)}}const W="[a-zA-Z][a-zA-Z0-9_-]*",X=`${W}(?:.${W})*`,Y=new RegExp(`^/(${W})/((?:@${X}/)?${X})/(.+)$`);class ee{static make(e,{router:t,setting:n,asset:r,log:o}={}){const i=[];for(const t of Object.values(e))i.push(t.router);return t instanceof _&&i.push(t),I(_.make(i),{setting:n,asset:ee.bindAsset(r,e),log:o})}static bindAsset(e,t,n="plugins"){if(!t)return e;const r=e?.read;return"function"!=typeof r?e:{...e,read:async e=>{const o=await r(e);if(null!==o)return o;if(!t)return null;const i=Y.exec(e);if(!i)return null;const[,s,u,c]=i;if(s!==n)return null;if(!(u in t))return null;const a=t[u];return a?a.readAsset(c):null}}}constructor(e,t,{author:n,license:r}={}){this.name=e,this.version="string"==typeof t?t:"",this.author="string"==typeof n?n:"",this.license="string"==typeof r?r:""}initRouter(){const{router:e}=this;return this.__initRouterPromise?this.__initRouterPromise:this.__initRouterPromise=Promise.resolve(this._initRouter(e)).then((()=>e))}get router(){const e=this._createRouter();return Reflect.defineProperty(this,"router",{value:e,configurable:!0}),this.initRouter(),e}get disabled(){return this.router.disabled}set disabled(e){this.router.disabled=e}}export{Q as ApiRouter,ee as Plugin,_ as Router,I as make,C as merge,B as run,L as service,D as stateService,H as storeService};
|
package/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* k99 v0.6.0-alpha.
|
|
2
|
+
* k99 v0.6.0-alpha.6
|
|
3
3
|
* (c) 2019-2023 猛火Fierflame
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
@@ -853,6 +853,11 @@ function createContext({
|
|
|
853
853
|
configurable: true,
|
|
854
854
|
enumerable: true
|
|
855
855
|
},
|
|
856
|
+
currentService: {
|
|
857
|
+
value: service,
|
|
858
|
+
configurable: true,
|
|
859
|
+
enumerable: true
|
|
860
|
+
},
|
|
856
861
|
state: {
|
|
857
862
|
configurable: true,
|
|
858
863
|
enumerable: true,
|
|
@@ -1157,6 +1162,9 @@ function merge(...handlers) {
|
|
|
1157
1162
|
|
|
1158
1163
|
function service(exec, destroy, options) {
|
|
1159
1164
|
const service = function (ctx, ...any) {
|
|
1165
|
+
if (ctx.currentService !== service) {
|
|
1166
|
+
return ctx.service(service, ...any);
|
|
1167
|
+
}
|
|
1160
1168
|
if (!ctx.destroying) {
|
|
1161
1169
|
return exec(ctx, ...any);
|
|
1162
1170
|
}
|
|
@@ -1175,6 +1183,9 @@ function service(exec, destroy, options) {
|
|
|
1175
1183
|
|
|
1176
1184
|
function stateService(init, destroy, exec, options) {
|
|
1177
1185
|
const service = function (ctx) {
|
|
1186
|
+
if (ctx.currentService !== service) {
|
|
1187
|
+
return ctx.service(service);
|
|
1188
|
+
}
|
|
1178
1189
|
if (!ctx.destroying) {
|
|
1179
1190
|
let {
|
|
1180
1191
|
state
|
|
@@ -1203,6 +1214,9 @@ function stateService(init, destroy, exec, options) {
|
|
|
1203
1214
|
|
|
1204
1215
|
function storeService(destroy, exec, options) {
|
|
1205
1216
|
const service = function (ctx, ...s) {
|
|
1217
|
+
if (ctx.currentService !== service) {
|
|
1218
|
+
return ctx.service(service, ...s);
|
|
1219
|
+
}
|
|
1206
1220
|
if (!ctx.destroying) {
|
|
1207
1221
|
if (!s.length) {
|
|
1208
1222
|
return ctx.state;
|
|
@@ -1335,7 +1349,7 @@ function parse(p) {
|
|
|
1335
1349
|
}
|
|
1336
1350
|
let i = 0;
|
|
1337
1351
|
let count = 0;
|
|
1338
|
-
const pattern = ['^('];
|
|
1352
|
+
const pattern = ['^(?:'];
|
|
1339
1353
|
while (i < expression.length) {
|
|
1340
1354
|
const c = expression[i++];
|
|
1341
1355
|
pattern.push(c);
|
|
@@ -1442,12 +1456,7 @@ function toMatch(path, end) {
|
|
|
1442
1456
|
return path => exec(list, path, end);
|
|
1443
1457
|
}
|
|
1444
1458
|
|
|
1445
|
-
function
|
|
1446
|
-
const path = typeof a === 'string' ? a : '';
|
|
1447
|
-
const handler = [a, b].find(v => typeof v === 'function');
|
|
1448
|
-
if (!handler) {
|
|
1449
|
-
return () => {};
|
|
1450
|
-
}
|
|
1459
|
+
function bind(routes, methods, path, handler) {
|
|
1451
1460
|
const route = {
|
|
1452
1461
|
match: toMatch(path || '', true),
|
|
1453
1462
|
methods: new Set(methods),
|
|
@@ -1467,6 +1476,22 @@ function verb(routes, methods, a, b) {
|
|
|
1467
1476
|
routes.splice(index, 1);
|
|
1468
1477
|
};
|
|
1469
1478
|
}
|
|
1479
|
+
function verb(routes, methods, p) {
|
|
1480
|
+
if (!p.length) {
|
|
1481
|
+
return handler => bind(routes, methods, '', handler);
|
|
1482
|
+
}
|
|
1483
|
+
const [a, b] = p;
|
|
1484
|
+
if (a && typeof a === 'object') {
|
|
1485
|
+
const path = String.raw(a, ...p.slice(1));
|
|
1486
|
+
return handler => bind(routes, methods, path, handler);
|
|
1487
|
+
}
|
|
1488
|
+
const path = typeof a === 'string' ? a : '';
|
|
1489
|
+
const handler = [a, b].find(v => typeof v === 'function');
|
|
1490
|
+
if (!handler) {
|
|
1491
|
+
return handler => bind(routes, methods, path, handler);
|
|
1492
|
+
}
|
|
1493
|
+
return bind(routes, methods, path, handler);
|
|
1494
|
+
}
|
|
1470
1495
|
|
|
1471
1496
|
const methods = new Set(['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS']);
|
|
1472
1497
|
function isMethod(v) {
|
|
@@ -1482,6 +1507,14 @@ function getMethods(methods) {
|
|
|
1482
1507
|
return Array.from(methods).map(v => typeof v === 'string' && v.toUpperCase()).filter(isMethod);
|
|
1483
1508
|
}
|
|
1484
1509
|
|
|
1510
|
+
function bindRouter(routes, path, r) {
|
|
1511
|
+
const router = r instanceof Router ? r : typeof r === 'function' ? Router.create(r) : new ApiRouter();
|
|
1512
|
+
routes.push({
|
|
1513
|
+
match: toMatch(path, false),
|
|
1514
|
+
router
|
|
1515
|
+
});
|
|
1516
|
+
return router;
|
|
1517
|
+
}
|
|
1485
1518
|
class ApiRouter extends Router {
|
|
1486
1519
|
/** 路由列表 */
|
|
1487
1520
|
#routes = [];
|
|
@@ -1490,15 +1523,15 @@ class ApiRouter extends Router {
|
|
|
1490
1523
|
* @param router 要注册的子路由
|
|
1491
1524
|
*/
|
|
1492
1525
|
|
|
1493
|
-
route(
|
|
1494
|
-
const
|
|
1495
|
-
|
|
1526
|
+
route(...p) {
|
|
1527
|
+
const [a] = p;
|
|
1528
|
+
if (a && typeof a === 'object' && !(a instanceof Router)) {
|
|
1529
|
+
const path = String.raw(a, ...p.slice(1));
|
|
1530
|
+
return r => bindRouter(this.#routes, path, r);
|
|
1531
|
+
}
|
|
1496
1532
|
const path = typeof a === 'string' ? a : '';
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
router
|
|
1500
|
-
});
|
|
1501
|
-
return router;
|
|
1533
|
+
const r = typeof a === 'string' ? p[1] : a;
|
|
1534
|
+
return bindRouter(this.#routes, path, r);
|
|
1502
1535
|
}
|
|
1503
1536
|
*find(method, path) {
|
|
1504
1537
|
for (const route of Array.from(this.#routes)) {
|
|
@@ -1535,65 +1568,63 @@ class ApiRouter extends Router {
|
|
|
1535
1568
|
if (!allMethods.length) {
|
|
1536
1569
|
return () => {};
|
|
1537
1570
|
}
|
|
1538
|
-
return verb(this.#routes, allMethods, path, handler);
|
|
1571
|
+
return verb(this.#routes, allMethods, [path, handler]);
|
|
1539
1572
|
}
|
|
1540
1573
|
/**
|
|
1541
1574
|
* 注册 HTTP GET/POST/PUT/DELETE 处理函数
|
|
1542
1575
|
* @param handler 要注册的处理函数
|
|
1543
1576
|
*/
|
|
1544
1577
|
|
|
1545
|
-
match(
|
|
1546
|
-
|
|
1547
|
-
return verb(this.#routes, methods, path, handler);
|
|
1578
|
+
match(...p) {
|
|
1579
|
+
return verb(this.#routes, ['GET', 'POST', 'PUT', 'DELETE'], p);
|
|
1548
1580
|
}
|
|
1549
|
-
|
|
1550
1581
|
/**
|
|
1551
1582
|
* 注册 HTTP GET 处理函数
|
|
1552
1583
|
* @param handler 要注册的处理函数
|
|
1553
1584
|
*/
|
|
1554
1585
|
|
|
1555
|
-
get(
|
|
1556
|
-
return verb(this.#routes, ['GET'],
|
|
1586
|
+
get(...p) {
|
|
1587
|
+
return verb(this.#routes, ['GET'], p);
|
|
1557
1588
|
}
|
|
1558
1589
|
/**
|
|
1559
1590
|
* 注册 HTTP POST 处理函数
|
|
1560
1591
|
* @param handler 要注册的处理函数
|
|
1561
1592
|
*/
|
|
1562
1593
|
|
|
1563
|
-
post(
|
|
1564
|
-
return verb(this.#routes, ['POST'],
|
|
1594
|
+
post(...p) {
|
|
1595
|
+
return verb(this.#routes, ['POST'], p);
|
|
1565
1596
|
}
|
|
1566
1597
|
/**
|
|
1567
1598
|
* 注册 HTTP PUT 处理函数
|
|
1568
1599
|
* @param handler 要注册的处理函数
|
|
1569
1600
|
*/
|
|
1570
1601
|
|
|
1571
|
-
put(
|
|
1572
|
-
return verb(this.#routes, ['PUT'],
|
|
1602
|
+
put(...p) {
|
|
1603
|
+
return verb(this.#routes, ['PUT'], p);
|
|
1573
1604
|
}
|
|
1574
1605
|
/**
|
|
1575
1606
|
* 注册 HTTP DELETE 处理函数
|
|
1576
1607
|
* @param handler 要注册的处理函数
|
|
1577
1608
|
*/
|
|
1578
1609
|
|
|
1579
|
-
delete(
|
|
1580
|
-
return verb(this.#routes, ['DELETE'],
|
|
1610
|
+
delete(...p) {
|
|
1611
|
+
return verb(this.#routes, ['DELETE'], p);
|
|
1581
1612
|
}
|
|
1582
1613
|
/**
|
|
1583
1614
|
* 注册 HTTP HEAD 处理函数
|
|
1584
1615
|
* @param handler 要注册的处理函数
|
|
1585
1616
|
*/
|
|
1586
1617
|
|
|
1587
|
-
head(
|
|
1588
|
-
return verb(this.#routes, ['HEAD'],
|
|
1618
|
+
head(...p) {
|
|
1619
|
+
return verb(this.#routes, ['HEAD'], p);
|
|
1589
1620
|
}
|
|
1590
1621
|
/**
|
|
1591
1622
|
* 注册 HTTP OPTIONS 处理函数
|
|
1592
1623
|
* @param handler 要注册的处理函数
|
|
1593
1624
|
*/
|
|
1594
1625
|
|
|
1595
|
-
options(
|
|
1596
|
-
return verb(this.#routes, ['OPTIONS'],
|
|
1626
|
+
options(...p) {
|
|
1627
|
+
return verb(this.#routes, ['OPTIONS'], p);
|
|
1597
1628
|
}
|
|
1598
1629
|
}
|
|
1599
1630
|
|
package/node/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* k99 v0.6.0-alpha.
|
|
2
|
+
* k99 v0.6.0-alpha.6
|
|
3
3
|
* (c) 2019-2023 猛火Fierflame
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
@@ -13,6 +13,7 @@ var urlFn = require('node:url');
|
|
|
13
13
|
var JSON5 = require('json5');
|
|
14
14
|
var yaml = require('yaml');
|
|
15
15
|
var node = require('k99/node');
|
|
16
|
+
var node_stream = require('node:stream');
|
|
16
17
|
|
|
17
18
|
function _interopNamespaceDefault(e) {
|
|
18
19
|
var n = Object.create(null);
|
|
@@ -999,8 +1000,26 @@ async function start() {
|
|
|
999
1000
|
return node.FsPlugin.make(plugins, mainPlugin);
|
|
1000
1001
|
}
|
|
1001
1002
|
|
|
1003
|
+
function contextToReadable(ctx) {
|
|
1004
|
+
const {
|
|
1005
|
+
read
|
|
1006
|
+
} = ctx;
|
|
1007
|
+
return node_stream.Readable.from(async function* () {
|
|
1008
|
+
for (;;) {
|
|
1009
|
+
const s = await read();
|
|
1010
|
+
if (s === null) {
|
|
1011
|
+
return;
|
|
1012
|
+
}
|
|
1013
|
+
yield s;
|
|
1014
|
+
}
|
|
1015
|
+
}(), {
|
|
1016
|
+
encoding: 'binary'
|
|
1017
|
+
});
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1002
1020
|
exports.FsPlugin = FsPlugin;
|
|
1003
1021
|
exports.Scanner = Scanner;
|
|
1022
|
+
exports.contextToReadable = contextToReadable;
|
|
1004
1023
|
exports.createFsAssetsApi = createFsAssetsApi;
|
|
1005
1024
|
exports.createFsLogApi = createFsLogApi;
|
|
1006
1025
|
exports.createFsSettingsApi = createFsSettingsApi;
|
package/node/index.d.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* k99 v0.6.0-alpha.
|
|
2
|
+
* k99 v0.6.0-alpha.6
|
|
3
3
|
* (c) 2019-2023 猛火Fierflame
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
6
6
|
import * as k99 from 'k99';
|
|
7
|
-
import { Plugin, ApiRouter, Router, Asset, Setting, Log, K99Request as K99Request$1, K99Response as K99Response$1 } from 'k99';
|
|
7
|
+
import { Plugin, ApiRouter, Router, Asset, Setting, Log, K99Request as K99Request$1, K99Response as K99Response$1, Context } from 'k99';
|
|
8
8
|
import { IncomingMessage, ServerResponse } from 'node:http';
|
|
9
9
|
import { Http2ServerRequest, Http2ServerResponse } from 'node:http2';
|
|
10
|
+
import { Readable } from 'node:stream';
|
|
10
11
|
|
|
11
12
|
interface K99Headers {
|
|
12
13
|
'accept'?: string;
|
|
@@ -223,4 +224,6 @@ interface K99Response {
|
|
|
223
224
|
|
|
224
225
|
declare function start(): Promise<(r: K99Request) => Promise<K99Response | null>>;
|
|
225
226
|
|
|
226
|
-
|
|
227
|
+
declare function contextToReadable(ctx: Context): Readable;
|
|
228
|
+
|
|
229
|
+
export { FsPlugin, Scanner, contextToReadable, createFsAssetsApi, createFsLogApi, createFsSettingsApi, createHttpCallback, start };
|
package/package.json
CHANGED
package/services.cjs
CHANGED
package/services.d.ts
CHANGED
package/services.js
CHANGED
package/services.min.js
CHANGED
package/services.min.mjs
CHANGED
package/services.mjs
CHANGED