@maiyunnet/kebab 9.29.6 → 10.0.0

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.
Files changed (52) hide show
  1. package/abox/proxy.js +24 -2
  2. package/abox/response.js +36 -17
  3. package/abox/session-login.js +1 -13
  4. package/doc/kebab-rag.md +1522 -1034
  5. package/index.d.ts +12 -1
  6. package/index.js +1 -1
  7. package/lib/ai.d.ts +4 -0
  8. package/lib/ai.js +32 -16
  9. package/lib/cookie.d.ts +2 -0
  10. package/lib/cookie.js +47 -45
  11. package/lib/core.d.ts +26 -0
  12. package/lib/core.js +36 -13
  13. package/lib/cron.js +1 -8
  14. package/lib/crypto.js +20 -6
  15. package/lib/db/conn.js +1 -0
  16. package/lib/fs.js +78 -31
  17. package/lib/kv.d.ts +182 -79
  18. package/lib/kv.js +518 -214
  19. package/lib/s3.d.ts +2 -0
  20. package/lib/s3.js +14 -27
  21. package/lib/session.d.ts +7 -0
  22. package/lib/session.js +23 -2
  23. package/lib/socket.d.ts +4 -1
  24. package/lib/socket.js +1 -0
  25. package/lib/sql.d.ts +0 -5
  26. package/lib/sql.js +48 -12
  27. package/lib/text.d.ts +10 -5
  28. package/lib/text.js +22 -12
  29. package/lib/turnstile.d.ts +6 -0
  30. package/lib/turnstile.js +16 -9
  31. package/lib/undici.d.ts +7 -1
  32. package/lib/undici.js +72 -36
  33. package/lib/ws.d.ts +1 -1
  34. package/lib/ws.js +85 -128
  35. package/lib/zip.js +46 -45
  36. package/package.json +2 -2
  37. package/sys/child.js +178 -146
  38. package/sys/cmd.js +196 -197
  39. package/sys/ctr.d.ts +14 -14
  40. package/sys/ctr.js +145 -59
  41. package/sys/master.js +111 -80
  42. package/sys/mod.d.ts +8 -2
  43. package/sys/mod.js +23 -11
  44. package/sys/monitor/files.d.ts +2 -1
  45. package/sys/monitor/files.js +77 -21
  46. package/sys/monitor/watchdog.d.ts +7 -0
  47. package/sys/monitor/watchdog.js +311 -203
  48. package/sys/monitor.d.ts +59 -54
  49. package/sys/monitor.js +742 -681
  50. package/sys/route.d.ts +4 -4
  51. package/sys/route.js +93 -52
  52. package/www/example/ctr/test.js +8 -8
package/lib/fs.js CHANGED
@@ -3,11 +3,14 @@
3
3
  * Date: 2019-3-29 23:03:07
4
4
  * Last: 2020-3-11 22:21:51, 2022-12-29 01:18:25, 2023-12-13 20:50:09
5
5
  */
6
+ // --- 系统 ---
6
7
  import * as fs from 'fs';
7
8
  import * as crypto from 'crypto';
8
9
  import * as http2 from 'http2';
9
10
  import * as stream from 'stream';
11
+ // --- 第三方 ---
10
12
  import * as mime from '@litert/mime';
13
+ // --- 库和定义 ---
11
14
  import * as lText from './text.js';
12
15
  import * as lCore from './core.js';
13
16
  import * as lZlib from './zlib.js';
@@ -21,10 +24,10 @@ export async function getContent(path, options) {
21
24
  const { encoding, start, end } = typeof options === 'string' ? { 'encoding': options } : options ?? {};
22
25
  try {
23
26
  if (start === undefined && end === undefined) {
24
- return await fs.promises.readFile(path, { encoding });
27
+ return await fs.promises.readFile(path, { 'encoding': encoding });
25
28
  }
26
29
  const data = [];
27
- for await (const chunk of createReadStream(path, { start, end })) {
30
+ for await (const chunk of createReadStream(path, { 'start': start, 'end': end })) {
28
31
  data.push(chunk);
29
32
  }
30
33
  const content = Buffer.concat(data);
@@ -236,8 +239,8 @@ export async function readDir(path, encoding) {
236
239
  */
237
240
  export async function copyFolder(from, to, ignore = []) {
238
241
  let num = 0;
239
- // --- 如果源目录不存在或不是目录,则直接成功 :) ---
240
- if (!await isDir(from)) {
242
+ // --- 如果源目录不存在、不是目录或为符号链接,则直接返回 0 ---
243
+ if (!await isDir(from.replace(/\/+$/, '') || from)) {
241
244
  return 0;
242
245
  }
243
246
  // --- 遍历源目录文件和文件夹,准备复制 ---
@@ -323,14 +326,15 @@ export function createWriteStream(path, options) {
323
326
  * @returns 区间列表;false 表示全部越界或区间过多;null 表示忽略请求头
324
327
  */
325
328
  function parseFileRanges(value, size) {
329
+ // --- 校验单位与分段上限,防止客户端利用大量小区间放大读取开销 ---
326
330
  if (!/^bytes=/i.test(value) || size === 0 || !Number.isSafeInteger(size)) {
327
331
  return null;
328
332
  }
329
333
  const values = value.slice(6).split(',');
330
- // --- 防止客户端利用大量小区间放大文件读取与响应开销 ---
331
334
  if (value.length > 8192 || values.length > 16) {
332
335
  return false;
333
336
  }
337
+ // --- 逐段解析字节区间(用 BigInt 避免超大偏移被浮点取整) ---
334
338
  const total = BigInt(size);
335
339
  const ranges = [];
336
340
  let count = 0;
@@ -340,11 +344,10 @@ function parseFileRanges(value, size) {
340
344
  continue;
341
345
  }
342
346
  const match = /^(\d*)-(\d*)$/.exec(part);
343
- if (!match || match[1] === '' && match[2] === '') {
347
+ if (!match || (match[1] === '' && match[2] === '')) {
344
348
  return null;
345
349
  }
346
350
  ++count;
347
- // --- 先以 BigInt 解析,避免超大偏移被浮点取整后读错字节 ---
348
351
  const start = match[1] !== '' ? BigInt(match[1]) : total - BigInt(match[2]);
349
352
  const end = match[1] !== '' && match[2] !== '' ? BigInt(match[2]) : total - 1n;
350
353
  if (match[1] !== '' && match[2] !== '' && end < start) {
@@ -356,7 +359,7 @@ function parseFileRanges(value, size) {
356
359
  ranges.push({
357
360
  'start': Number(start < 0n ? 0n : start),
358
361
  'end': Number(end >= total ? total - 1n : end),
359
- 'order': count
362
+ 'order': count,
360
363
  });
361
364
  }
362
365
  if (count === 0) {
@@ -365,6 +368,7 @@ function parseFileRanges(value, size) {
365
368
  if (ranges.length === 0) {
366
369
  return false;
367
370
  }
371
+ // --- 合并重叠或相邻区间,并按客户端请求顺序返回 ---
368
372
  ranges.sort((a, b) => a.start - b.start);
369
373
  const merged = [];
370
374
  for (const range of ranges) {
@@ -413,7 +417,7 @@ async function* readFileRanges(path, ranges, headers, footer) {
413
417
  */
414
418
  export async function readToResponse(path, req, res, stat) {
415
419
  stat ??= await stats(path);
416
- if (!stat) {
420
+ if (!stat?.isFile()) {
417
421
  const content = '<h1>404 Not found</h1>';
418
422
  res.setHeader('content-length', Buffer.byteLength(content));
419
423
  lCore.writeHead(res, 404);
@@ -436,13 +440,14 @@ export async function readToResponse(path, req, res, stat) {
436
440
  res.setHeader('accept-ranges', 'bytes');
437
441
  if (canCompress) {
438
442
  const vary = res.getHeader('vary');
439
- const values = (Array.isArray(vary) ? vary.join(',') : String(vary ?? '')).split(',').map((item) => item.trim()).filter(Boolean);
443
+ const rawVary = Array.isArray(vary) ? vary.join(',') : String(vary ?? '');
444
+ const values = rawVary.split(',').map((item) => item.trim()).filter(Boolean);
440
445
  if (!values.some((item) => item === '*' || item.toLowerCase() === 'accept-encoding')) {
441
446
  values.push('Accept-Encoding');
442
447
  res.setHeader('vary', values.join(', '));
443
448
  }
444
449
  }
445
- // --- 这些文件可能需要缓存 ---
450
+ // --- 设置静态文件缓存策略 ---
446
451
  if (['htm', 'html', 'css', 'js', 'mjs', 'xml', 'jpg', 'jpeg', 'svg', 'gif', 'png', 'json'].includes(mimeData.extension)) {
447
452
  /** --- 静态文件默认缓存秒数 --- */
448
453
  const cacheTTL = 600;
@@ -452,20 +457,31 @@ export async function readToResponse(path, req, res, stat) {
452
457
  else {
453
458
  res.setHeader('cache-control', 'no-cache, must-revalidate');
454
459
  }
455
- // --- 条件请求优先于 Range;弱 ETag 只能用于缓存验证,不能用于 If-Match ---
460
+ // --- 条件请求校验(优先于 Range;弱 ETag 只能用于缓存验证,不能用于 If-Match) ---
456
461
  const match = req.headers['if-match'];
457
462
  const unmodifiedSince = req.headers['if-unmodified-since'];
458
- if (match !== undefined ? match.trim() !== '*' : unmodifiedSince !== undefined && modifiedTime > Date.parse(unmodifiedSince)) {
463
+ const failedPrecondition = match !== undefined
464
+ ? match.trim() !== '*'
465
+ : (unmodifiedSince !== undefined && modifiedTime > Date.parse(unmodifiedSince));
466
+ if (failedPrecondition) {
459
467
  res.setHeader('content-length', 0);
460
468
  lCore.writeHead(res, 412);
461
469
  res.end();
462
470
  return;
463
471
  }
472
+ // --- 缓存未变更校验(If-None-Match / If-Modified-Since) ---
464
473
  const noneMatch = req.headers['if-none-match'];
465
474
  const modifiedSince = req.headers['if-modified-since'];
466
475
  const isRead = req.method === 'GET' || req.method === 'HEAD';
467
- const unchanged = noneMatch !== undefined ? noneMatch.trim() === '*' || noneMatch.split(',').some((item) => item.trim().replace(/^W\//, '') === hash.slice(2)) :
468
- isRead && modifiedSince !== undefined && modifiedTime <= Date.parse(modifiedSince);
476
+ let unchanged = false;
477
+ if (noneMatch !== undefined) {
478
+ const tag = hash.slice(2);
479
+ unchanged = noneMatch.trim() === '*' ||
480
+ noneMatch.split(',').some((item) => item.trim().replace(/^W\//, '') === tag);
481
+ }
482
+ else if (isRead && modifiedSince !== undefined) {
483
+ unchanged = modifiedTime <= Date.parse(modifiedSince);
484
+ }
469
485
  if (unchanged) {
470
486
  if (!isRead) {
471
487
  res.setHeader('content-length', 0);
@@ -474,15 +490,21 @@ export async function readToResponse(path, req, res, stat) {
474
490
  res.end();
475
491
  return;
476
492
  }
493
+ // --- 解析 Range 与 If-Range ---
477
494
  const contentType = mimeData.mime + charset;
478
495
  res.setHeader('content-type', contentType);
479
496
  const rangeHeader = req.headers['range'];
480
497
  const ifRange = req.headers['if-range'];
481
498
  // --- 日期必须精确匹配且至少早一秒;压缩与原始字节共享的日期不能作强校验,避免跨编码续传 ---
482
- const rangeMatches = ifRange === undefined || typeof ifRange === 'string' && !ifRange.includes('"') &&
483
- Date.parse(ifRange) === modifiedTime && modifiedTime <= Date.now() - 1_000 && !canCompress;
484
- const ranges = req.method === 'GET' && rangeHeader !== undefined &&
485
- rangeMatches ? parseFileRanges(rangeHeader, stat.size) : null;
499
+ const rangeMatches = ifRange === undefined || (typeof ifRange === 'string' &&
500
+ !ifRange.includes('"') &&
501
+ Date.parse(ifRange) === modifiedTime &&
502
+ modifiedTime <= Date.now() - 1_000 &&
503
+ !canCompress);
504
+ let ranges = null;
505
+ if (req.method === 'GET' && rangeHeader !== undefined && rangeMatches) {
506
+ ranges = parseFileRanges(rangeHeader, stat.size);
507
+ }
486
508
  if (ranges === false) {
487
509
  res.setHeader('content-range', `bytes */${stat.size}`);
488
510
  res.setHeader('content-length', 0);
@@ -490,19 +512,41 @@ export async function readToResponse(path, req, res, stat) {
490
512
  res.end();
491
513
  return;
492
514
  }
493
- // --- 判断客户端支持的压缩模式 ---
515
+ // --- 判断客户端支持的压缩模式(2 MiB 内缓冲压缩保留精确 Content-Length;大文件走流式压缩防 OOM) ---
494
516
  const encoding = req.headers['accept-encoding'] ?? '';
495
517
  if (ranges === null && canCompress && encoding !== '') {
496
- // --- 压缩 ---
497
- const compress = await lZlib.compress(encoding, await getContent(path));
498
- if (compress) {
499
- res.setHeader('content-encoding', compress.type);
500
- res.setHeader('content-length', Buffer.byteLength(compress.buffer));
501
- lCore.writeHead(res, 200);
502
- res.end(req.method === 'HEAD' ? '' : compress.buffer);
503
- return;
518
+ if (stat.size <= 2 * 1024 * 1024) {
519
+ const compress = await lZlib.compress(encoding, await getContent(path));
520
+ if (compress) {
521
+ res.setHeader('content-encoding', compress.type);
522
+ res.setHeader('content-length', Buffer.byteLength(compress.buffer));
523
+ lCore.writeHead(res, 200);
524
+ res.end(req.method === 'HEAD' ? '' : compress.buffer);
525
+ return;
526
+ }
527
+ }
528
+ else {
529
+ const compress = lZlib.createCompress(encoding);
530
+ if (compress) {
531
+ res.setHeader('content-encoding', compress.type);
532
+ res.removeHeader('content-length');
533
+ lCore.writeHead(res, 200);
534
+ if (req.method === 'HEAD') {
535
+ compress.compress.destroy();
536
+ res.end();
537
+ return;
538
+ }
539
+ try {
540
+ await stream.promises.pipeline(createReadStream(path), compress.compress, res instanceof http2.Http2ServerResponse ? (res.stream ?? res) : res);
541
+ }
542
+ catch {
543
+ res.destroy();
544
+ }
545
+ return;
546
+ }
504
547
  }
505
548
  }
549
+ // --- 设置完整响应或 206 部分响应头 ---
506
550
  let headers = [];
507
551
  let footer = Buffer.alloc(0);
508
552
  if (ranges !== null && ranges.length > 1) {
@@ -510,7 +554,8 @@ export async function readToResponse(path, req, res, stat) {
510
554
  headers = ranges.map((range) => Buffer.from(`--${boundary}\r\nContent-Type: ${contentType}\r\nContent-Range: bytes ${range.start}-${range.end}/${stat.size}\r\n\r\n`));
511
555
  footer = Buffer.from(`--${boundary}--\r\n`);
512
556
  res.setHeader('content-type', `multipart/byteranges; boundary=${boundary}`);
513
- res.setHeader('content-length', ranges.reduce((length, range, i) => length + headers[i].length + (range.end - range.start + 1) + 2, footer.length));
557
+ const totalLength = ranges.reduce((length, range, i) => length + headers[i].length + (range.end - range.start + 1) + 2, footer.length);
558
+ res.setHeader('content-length', totalLength);
514
559
  }
515
560
  else if (ranges !== null) {
516
561
  res.setHeader('content-range', `bytes ${ranges[0].start}-${ranges[0].end}/${stat.size}`);
@@ -524,8 +569,10 @@ export async function readToResponse(path, req, res, stat) {
524
569
  res.end();
525
570
  return;
526
571
  }
527
- const source = ranges !== null && ranges.length > 1 ?
528
- stream.Readable.from(readFileRanges(path, ranges, headers, footer)) : createReadStream(path, ranges?.[0]);
572
+ // --- 流式输出文件内容 ---
573
+ const source = ranges !== null && ranges.length > 1
574
+ ? stream.Readable.from(readFileRanges(path, ranges, headers, footer))
575
+ : createReadStream(path, ranges?.[0]);
529
576
  try {
530
577
  await stream.promises.pipeline(source, res instanceof http2.Http2ServerResponse ? (res.stream ?? res) : res);
531
578
  }