@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/sys/master.js CHANGED
@@ -3,6 +3,7 @@
3
3
  * Date: 2019-5-2 21:03:42
4
4
  * Last: 2020-3-7 10:33:17, 2022-07-22 13:40:10, 2022-09-06 22:40:58, 2024-2-7 01:44:59, 2024-7-2 15:17:09, 2025-6-13 13:06:43, 2025-12-5 13:15:03, 2026-3-22 00:00:00, 2026-4-30 13:49:44
5
5
  */
6
+ // --- 系统 ---
6
7
  import cluster from 'cluster';
7
8
  import * as os from 'os';
8
9
  import * as fs from 'fs';
@@ -41,6 +42,29 @@ const replaceVhost = masterVhost.replace;
41
42
  * @returns true 表示所有文件可写入;false 表示整批拒绝,不修改旧配置
42
43
  */
43
44
  const isVhostFiles = masterVhost.isFiles;
45
+ /** --- kebab 子项目中仅允许部署的子文件夹名集合 --- */
46
+ const KEBAB_ALLOWED_DIRS = new Set(['ctr', 'data', 'stc', 'view', 'lib', 'abox']);
47
+ /** --- 常见开发、依赖、缓存、构建产物目录不参与部署 --- */
48
+ const DEPLOY_EXCLUDE_DIRS = new Set([
49
+ '.git',
50
+ '.svn',
51
+ '.hg',
52
+ '.vscode',
53
+ '.idea',
54
+ '.history',
55
+ 'node_modules',
56
+ 'bower_components',
57
+ '.cache',
58
+ '.parcel-cache',
59
+ '.turbo',
60
+ '.next',
61
+ '.nuxt',
62
+ '.vite',
63
+ 'coverage',
64
+ '.nyc_output',
65
+ 'tmp',
66
+ 'temp',
67
+ ]);
44
68
  /** --- 当前运行中的子进程列表 --- */
45
69
  const workerList = {};
46
70
  /** --- 是否已开始停止整个服务 --- */
@@ -101,6 +125,27 @@ async function resolvePathInside(rootPath, inputPath) {
101
125
  }
102
126
  }
103
127
  }
128
+ /**
129
+ * --- 解析并校验目标目录是否位于根目录内(同时兼容相对路径与根目录内的绝对路径) ---
130
+ * @param rootPath 限定的根目录
131
+ * @param inputPath 待校验目录路径
132
+ */
133
+ async function resolveDirInside(rootPath, inputPath) {
134
+ if ((typeof inputPath !== 'string') || inputPath.includes('\0')) {
135
+ return null;
136
+ }
137
+ const rootReal = await fs.promises.realpath(rootPath);
138
+ if (path.isAbsolute(inputPath)) {
139
+ try {
140
+ const targetReal = await fs.promises.realpath(inputPath);
141
+ return isPathInside(rootReal, targetReal) ? targetReal : null;
142
+ }
143
+ catch {
144
+ return null;
145
+ }
146
+ }
147
+ return resolvePathInside(rootReal, inputPath);
148
+ }
104
149
  /**
105
150
  * --- 统一 ZIP 文件路径中的斜杠,并拒绝 .. 等不安全写法 ---
106
151
  * @param archivePath ZIP 内的原始路径
@@ -304,6 +349,10 @@ function createRpcListener() {
304
349
  break;
305
350
  }
306
351
  case 'global': {
352
+ if (typeof msg.key !== 'string' || msg.key === '__proto__' || msg.key === 'constructor' || msg.key === 'prototype') {
353
+ res.end('Invalid key');
354
+ return;
355
+ }
307
356
  // --- 为所有子进程更新 global 变量 ---
308
357
  for (const pid in workerList) {
309
358
  workerList[pid].worker.send({
@@ -350,12 +399,17 @@ function createRpcListener() {
350
399
  return;
351
400
  }
352
401
  case 'npm': {
353
- // --- 执行 npm install 操作 ---
402
+ // --- 执行 npm install 操作(路径必须位于项目根目录内) ---
354
403
  if (!msg.path || typeof msg.path !== 'string') {
355
404
  res.end('Invalid path');
356
405
  return;
357
406
  }
358
- if (!await lFs.isDir(msg.path)) {
407
+ const npmPath = await resolveDirInside(kebab.ROOT_CWD, msg.path);
408
+ if (!npmPath) {
409
+ res.end('Invalid path');
410
+ return;
411
+ }
412
+ if (!await lFs.isDir(npmPath)) {
359
413
  res.end('Path not found');
360
414
  return;
361
415
  }
@@ -363,7 +417,7 @@ function createRpcListener() {
363
417
  const npmTimeout = 300_000;
364
418
  const npmDeadline = Date.now() + npmTimeout;
365
419
  let rtn = await lCore.exec('npm i --omit=dev', {
366
- 'cwd': msg.path,
420
+ 'cwd': npmPath,
367
421
  'timeout': npmTimeout,
368
422
  });
369
423
  if (rtn === false) {
@@ -371,7 +425,7 @@ function createRpcListener() {
371
425
  const remaining = npmDeadline - Date.now();
372
426
  if (remaining > 0) {
373
427
  rtn = await lCore.exec('npm i --omit=dev --legacy-peer-deps', {
374
- 'cwd': msg.path,
428
+ 'cwd': npmPath,
375
429
  'timeout': remaining,
376
430
  });
377
431
  }
@@ -433,6 +487,11 @@ function createRpcListener() {
433
487
  res.end('Invalid content');
434
488
  return;
435
489
  }
490
+ const parsedPkg = lText.parseJson(msg.content);
491
+ if (!parsedPkg || typeof parsedPkg !== 'object' || Array.isArray(parsedPkg)) {
492
+ res.end('Invalid content');
493
+ return;
494
+ }
436
495
  const packageFile = kebab.ROOT_CWD + 'package.json';
437
496
  if (!await lFs.isFile(packageFile)) {
438
497
  res.end('package.json not found');
@@ -522,35 +581,28 @@ function createRpcListener() {
522
581
  ls[normalizedPath] = rawList[archivePath];
523
582
  }
524
583
  // --- 预扫描:收集 .cga 锁定目录和 kebab 子项目目录 ---
525
- /** --- .cga 锁定的目录集合,key 格式为"父路径/目录名/"(不含开头/,含尾部/),例如 "www/pika/" --- */
584
+ /** --- .cga 锁定的目录集合,格式如 "www/pika/" --- */
526
585
  const cgaLockedDirs = new Set();
527
- /** --- 含有 kebab.json 的目录路径集合(不含开头/,含尾部/,根目录为空字符串) --- */
586
+ /** --- 含有 kebab.json 的目录集合,格式如 "www/pika/",根目录为空字符串 --- */
528
587
  const kebabProjectDirs = new Set();
529
- /** --- 本次部署涉及到的目录路径集合(不含开头/,含尾部/,根目录为空字符串) --- */
588
+ /** --- 本次部署涉及的目录集合 --- */
530
589
  const touchedDirs = new Set();
531
590
  for (const scanPath in ls) {
532
- /** --- 纯路径中最后一个 / 的位置索引 --- */
533
591
  const scanLio = scanPath.lastIndexOf('/');
534
- /** --- 纯路径,不以 / 开头,以 / 结尾,若是根路径就是空字符串,例如 "www/pika/" --- */
535
592
  const scanPat = scanPath.slice(1, scanLio + 1);
536
- /** --- 纯文件名,例如 "index.ts" 或 "pika.cga" --- */
537
593
  const scanFname = scanPath.slice(scanLio + 1);
538
594
  touchedDirs.add(scanPat);
539
- if (scanFname.endsWith('.cga')) {
540
- // --- 记录 .cga 锁定的同级目录(去掉 .cga 后缀的名字即为被锁定的目录名)---
541
- cgaLockedDirs.add(scanPat + scanFname.slice(0, -4) + '/');
595
+ if (scanFname.toLowerCase().endsWith('.cga')) {
596
+ cgaLockedDirs.add((scanPat + scanFname.slice(0, -4) + '/').toLowerCase());
542
597
  }
543
- if (scanFname === 'kebab.json') {
544
- // --- 记录含有 kebab.json 的目录(即 kebab 子项目根目录)---
598
+ if (scanFname.toLowerCase() === 'kebab.json') {
545
599
  kebabProjectDirs.add(scanPat);
546
600
  }
547
601
  }
548
602
  // --- 补充扫描目标目录中现存的 kebab.json,兼容压缩包未携带 kebab.json 的情况 ---
549
603
  for (const dir of touchedDirs) {
550
- /** --- 把目录拆成各级目录名,先检查当前目录,再一层层往上找 --- */
551
604
  const dirs = dir ? dir.split('/').filter(Boolean) : [];
552
605
  for (let i = dirs.length; i >= 0; --i) {
553
- /** --- 当前要检查的目录路径,不含开头/,含尾部/,根目录为空字符串 --- */
554
606
  const currentDir = i ? dirs.slice(0, i).join('/') + '/' : '';
555
607
  if (kebabProjectDirs.has(currentDir)) {
556
608
  break;
@@ -561,68 +613,42 @@ function createRpcListener() {
561
613
  }
562
614
  }
563
615
  }
564
- /** --- kebab 子项目中仅允许部署的子文件夹名集合 --- */
565
- const KEBAB_ALLOWED_DIRS = new Set(['ctr', 'data', 'stc', 'view', 'lib', 'abox']);
566
- /** --- 常见开发、依赖、缓存、构建产物目录不参与部署 --- */
567
- const DEPLOY_EXCLUDE_DIRS = new Set([
568
- '.git',
569
- '.svn',
570
- '.hg',
571
- '.vscode',
572
- '.idea',
573
- '.history',
574
- 'node_modules',
575
- 'bower_components',
576
- '.cache',
577
- '.parcel-cache',
578
- '.turbo',
579
- '.next',
580
- '.nuxt',
581
- '.vite',
582
- 'coverage',
583
- '.nyc_output',
584
- 'tmp',
585
- 'temp',
586
- ]);
616
+ // --- 按安全与过滤规则逐项写入文件(统一小写比对防止大小写绕过) ---
587
617
  for (const archivePath in ls) {
588
- /** --- 纯路径中最后一个 / 的位置索引 --- */
589
618
  const lio = archivePath.lastIndexOf('/');
590
- /** --- 纯路径,不以 / 开头,以 / 结尾,若是根路径就是空字符串,例如 "www/pika/ctr/" --- */
591
619
  const pat = archivePath.slice(1, lio + 1);
592
- /** --- 纯文件名,例如 "api.js" --- */
593
620
  const fname = archivePath.slice(lio + 1);
621
+ const fnameLower = fname.toLowerCase();
594
622
  const dirs = archivePath.slice(1).split('/').slice(0, -1);
595
- if (dirs.some(seg => DEPLOY_EXCLUDE_DIRS.has(seg))) {
596
- // --- 开发、依赖、缓存、构建产物目录不覆盖 ---
623
+ const dirsLower = dirs.map(seg => seg.toLowerCase());
624
+ if (dirsLower.some(seg => DEPLOY_EXCLUDE_DIRS.has(seg))) {
597
625
  continue;
598
626
  }
599
- if (dirs.some((seg, index) => seg === 'abox' && ['test', 'tests'].includes(dirs[index + 1]))) {
627
+ if (dirsLower.some((seg, index) => seg === 'abox' && ['test', 'tests'].includes(dirsLower[index + 1]))) {
600
628
  // --- abox 运行代码参与部署,测试目录不进入线上目录 ---
601
629
  continue;
602
630
  }
603
- if (fname === 'kebab.json' && hasSensitiveConfig(ls[archivePath])) {
604
- // --- 包含密码或密钥的 kebab.json 不覆盖,避免部署包覆盖现有敏感配置 ---
605
- continue;
606
- }
607
- if (pat === 'conf/' && fname === 'config.json') {
608
- // --- 全局配置文件不能覆盖 ---
631
+ if (fnameLower === 'kebab.json' && hasSensitiveConfig(ls[archivePath])) {
632
+ // --- 包含密码或密钥的 kebab.json 不覆盖 ---
609
633
  continue;
610
634
  }
611
- if (fname.endsWith('.js.map') || fname.endsWith('.ts') || fname.endsWith('.tsx') || fname.endsWith('.scss') || fname.endsWith('.gitignore') || fname.endsWith('.DS_Store')) {
612
- // --- 测试或开发文件不覆盖 ---
635
+ if (pat.toLowerCase() === 'conf/' && fnameLower === 'config.json') {
613
636
  continue;
614
637
  }
615
- if (fname === 'AGENTS.md') {
616
- // --- 排除文件不部署 ---
638
+ if (fnameLower.endsWith('.js.map') ||
639
+ fnameLower.endsWith('.ts') ||
640
+ fnameLower.endsWith('.tsx') ||
641
+ fnameLower.endsWith('.scss') ||
642
+ fnameLower.endsWith('.gitignore') ||
643
+ fnameLower.endsWith('.ds_store') ||
644
+ fnameLower === 'agents.md') {
617
645
  continue;
618
646
  }
619
- // --- 规则 1:若同级目录存在 xxx.cga,则 xxx 目录下所有内容不部署 ---
647
+ // --- 规则 1:若同级或上级目录存在 xxx.cga,则 xxx 目录下所有内容不部署 ---
620
648
  if (pat) {
621
- /** --- 当前目录或上级目录是否有同名 .cga 文件 --- */
622
649
  let cgaBlocked = false;
623
- /** --- 逐层拼出的目录路径,如 a/、a/b/,检查是否有同名 .cga 文件 --- */
624
650
  let accumulated = '';
625
- for (const seg of pat.split('/').filter(Boolean)) {
651
+ for (const seg of pat.toLowerCase().split('/').filter(Boolean)) {
626
652
  accumulated += seg + '/';
627
653
  if (cgaLockedDirs.has(accumulated)) {
628
654
  cgaBlocked = true;
@@ -633,26 +659,20 @@ function createRpcListener() {
633
659
  continue;
634
660
  }
635
661
  }
636
- // --- 规则 2:kebab 子项目目录中,仅允许部署 ctr/data/stc/view/lib/abox 子文件夹内的内容 ---
662
+ // --- 规则 2:kebab 子项目目录中,仅允许部署 ctr/data/stc/view/lib/abox 子目录 ---
637
663
  if (kebabProjectDirs.size > 0) {
638
- // --- 同时属于多个 Kebab 项目时,按最外层项目的部署规则检查 ---
639
- // --- 例如根项目不允许 backup/,backup/ 自带 kebab.json 也不能绕过 ---
640
- /** --- 当前文件所属的最外层 Kebab 项目目录,找不到时为 null --- */
664
+ // --- 同时属于多个 Kebab 项目时,按最外层项目规则检查 ---
641
665
  let shortestMatch = null;
642
666
  for (const kdir of kebabProjectDirs) {
643
- /** --- kdir 是否比已选的项目目录更靠外(路径更短)--- */
644
- const isShallower = shortestMatch === null || kdir.length < shortestMatch.length;
645
- if (pat.startsWith(kdir) && isShallower) {
667
+ if (pat.startsWith(kdir) &&
668
+ (shortestMatch === null || kdir.length < shortestMatch.length)) {
646
669
  shortestMatch = kdir;
647
670
  }
648
671
  }
649
672
  if (shortestMatch !== null) {
650
- // --- 取相对于 kebab 项目目录的路径,检查第一级子目录 ---
651
- /** --- 相对路径,例如若 pat 为 "www/pika/ctr/" 且 shortestMatch 为 "www/pika/",则 relPath 为 "ctr/" --- */
652
673
  const relPath = pat.slice(shortestMatch.length);
653
674
  if (relPath) {
654
- /** --- 路径的第一级子目录名,例如 "ctr" 或 "data",用于判断是否在允许列表中 --- */
655
- const firstSeg = relPath.split('/')[0];
675
+ const firstSeg = relPath.split('/')[0].toLowerCase();
656
676
  if (!KEBAB_ALLOWED_DIRS.has(firstSeg)) {
657
677
  continue;
658
678
  }
@@ -783,11 +803,7 @@ function createRpcListener() {
783
803
  const list = [];
784
804
  let total = 0;
785
805
  let skipHeader = format === 'csv';
786
- /**
787
- * --- 统计匹配行数并取出当前页,跳过 CSV 表头 ---
788
- * @param line 不含换行符的日志行
789
- * @returns 无返回值
790
- */
806
+ // --- 统计匹配行数并取出当前页,跳过 CSV 表头 ---
791
807
  const consumeLine = (line) => {
792
808
  if (skipHeader) {
793
809
  skipHeader = false;
@@ -840,21 +856,30 @@ function createRpcListener() {
840
856
  return;
841
857
  }
842
858
  case 'monitor-events': {
859
+ // --- 按天分页查询监控事件摘要 ---
843
860
  const result = await sMonitorFiles.getEvents(path.join(kebab.LOG_CWD, 'monitor'), msg.path ?? lTime.format(null, 'Y/m/d'), msg.offset ?? 0, msg.limit ?? 20);
844
861
  res.setHeader('cache-control', 'no-store');
845
- res.end(lText.stringifyJson(result === false ? { 'result': 0 } : { 'result': 1, ...result }));
862
+ res.end(lText.stringifyJson(result === false ? { 'result': 0 } : {
863
+ 'result': 1,
864
+ ...result,
865
+ }));
846
866
  return;
847
867
  }
848
868
  case 'monitor-event': {
869
+ // --- 查询单条监控事件详情与文件清单 ---
849
870
  const data = await sMonitorFiles.getEvent(path.join(kebab.LOG_CWD, 'monitor'), msg.path);
850
871
  res.setHeader('cache-control', 'no-store');
851
- res.end(lText.stringifyJson(data === false ? { 'result': 0 } : { 'result': 1, data }));
872
+ res.end(lText.stringifyJson(data === false ? { 'result': 0 } : {
873
+ 'result': 1,
874
+ 'data': data,
875
+ }));
852
876
  return;
853
877
  }
854
878
  case 'monitor-file': {
879
+ // --- 校验目标诊断文件及预览权限 ---
855
880
  const file = await sMonitorFiles.getFile(path.join(kebab.LOG_CWD, 'monitor'), msg.path);
856
881
  res.setHeader('cache-control', 'no-store');
857
- if (file === false || msg.preview !== undefined && typeof msg.preview !== 'boolean') {
882
+ if (file === false || (msg.preview !== undefined && typeof msg.preview !== 'boolean')) {
858
883
  res.writeHead(400);
859
884
  res.end();
860
885
  return;
@@ -869,9 +894,12 @@ function createRpcListener() {
869
894
  res.end();
870
895
  return;
871
896
  }
897
+ // --- 设置响应头并流式输出文件 ---
872
898
  let contentType = 'application/octet-stream';
873
899
  if (msg.preview) {
874
- contentType = file.info.preview === 'json' ? 'application/json; charset=utf-8' : 'text/plain; charset=utf-8';
900
+ contentType = file.info.preview === 'json'
901
+ ? 'application/json; charset=utf-8'
902
+ : 'text/plain; charset=utf-8';
875
903
  }
876
904
  res.setHeader('content-type', contentType);
877
905
  res.setHeader('x-content-type-options', 'nosniff');
@@ -1120,6 +1148,9 @@ async function createChildProcess(cpu) {
1120
1148
  break;
1121
1149
  }
1122
1150
  case 'global': {
1151
+ if (typeof msg.key !== 'string' || msg.key === '__proto__' || msg.key === 'constructor' || msg.key === 'prototype') {
1152
+ break;
1153
+ }
1123
1154
  // --- 为所有子进程更新 global 变量 ---
1124
1155
  for (const pid in workerList) {
1125
1156
  workerList[pid].worker.send({
package/sys/mod.d.ts CHANGED
@@ -15,14 +15,19 @@ export type TOnlyProperties<T> = {
15
15
  export type TModRow = Record<string, kebab.Json>;
16
16
  /** --- 按条件查询单条记录的选项 --- */
17
17
  export interface IModOneOptions {
18
+ /** --- 所属控制器,用于错误日志 --- */
18
19
  'ctr'?: sCtr.Ctr;
19
20
  /** --- 加锁时确保 WHERE 条件命中索引,以免锁定过多记录 --- */
20
21
  'lock'?: boolean;
21
22
  /** --- MySQL 表前缀或 PostgreSQL Schema 名 --- */
22
23
  'pre'?: string;
24
+ /** --- 分表后缀 --- */
23
25
  'index'?: string | string[];
26
+ /** --- 指定查询字段 --- */
24
27
  'select'?: string | string[];
28
+ /** --- 排序字段与方向 --- */
25
29
  'by'?: [string | string[], 'DESC' | 'ASC'];
30
+ /** --- SQL 优化提示 --- */
26
31
  'hint'?: string;
27
32
  }
28
33
  /** --- 一批游标查询结果,hasMore 表示扫描方向上还有记录 --- */
@@ -640,7 +645,7 @@ export default class Mod {
640
645
  */
641
646
  updates(): Record<string, any>;
642
647
  /**
643
- * --- 当前是否设置了未保存 --=
648
+ * --- 当前是否设置了未保存 ---
644
649
  */
645
650
  unsaved(): boolean;
646
651
  /**
@@ -654,8 +659,9 @@ export default class Mod {
654
659
  */
655
660
  protected _keyGenerator(): string;
656
661
  }
662
+ /** --- 模型记录集合接口 --- */
657
663
  export interface IRows<T> extends Iterable<T> {
658
- readonly length: number;
664
+ readonly 'length': number;
659
665
  item(index: number): T;
660
666
  toArray(): Array<Record<string, any>>;
661
667
  }
package/sys/mod.js CHANGED
@@ -164,6 +164,9 @@ export default class Mod {
164
164
  return r.packet.affected ? true : null;
165
165
  }
166
166
  // --- 可能是多行 ---
167
+ if (!vs.length) {
168
+ return true;
169
+ }
167
170
  if (vs.some(item => !Array.isArray(item))) {
168
171
  vs = [vs];
169
172
  }
@@ -359,6 +362,7 @@ export default class Mod {
359
362
  if (groups.size === 0) {
360
363
  return true;
361
364
  }
365
+ // --- 按组计算分批大小并逐批执行 UPDATE ---
362
366
  const tableName = this._$table + (opt.index ? ('_' + opt.index) : '');
363
367
  for (const [, groupItems] of groups) {
364
368
  const cols = Object.keys(groupItems[0]).filter(k => k !== key).sort();
@@ -368,12 +372,11 @@ export default class Mod {
368
372
  const maxBatchSize = Math.floor(65000 / allCols.length);
369
373
  // --- 控制单条 SQL 的解析、临时数据和持锁规模;PostgreSQL 不应默认吃满协议参数上限 ---
370
374
  const defaultBatchSize = service === lDb.ESERVICE.MYSQL ? 200 : 1_000;
371
- const requestedBatchSize = opt.batchSize;
372
- const normalizedBatchSize = (requestedBatchSize !== undefined &&
373
- Number.isSafeInteger(requestedBatchSize) &&
374
- requestedBatchSize > 0) ?
375
- requestedBatchSize : defaultBatchSize;
376
- const batchSize = Math.max(1, Math.min(normalizedBatchSize, maxBatchSize));
375
+ const customBatch = opt.batchSize;
376
+ const wantedBatch = (customBatch !== undefined && Number.isSafeInteger(customBatch) && customBatch > 0)
377
+ ? customBatch
378
+ : defaultBatchSize;
379
+ const batchSize = Math.max(1, Math.min(wantedBatch, maxBatchSize));
377
380
  for (let i = 0; i < groupItems.length; i += batchSize) {
378
381
  const batch = groupItems.slice(i, i + batchSize);
379
382
  const sq = lSql.get({
@@ -505,9 +508,7 @@ export default class Mod {
505
508
  return null;
506
509
  }
507
510
  static async oneArray(db, s, opt = {}) {
508
- const queryOptions = opt;
509
- queryOptions.array = true;
510
- return this.one(db, s, queryOptions);
511
+ return this.one(db, s, { ...opt, 'array': true });
511
512
  }
512
513
  /**
513
514
  * --- 根据 where 条件获取主键值列表 ---
@@ -701,7 +702,10 @@ export default class Mod {
701
702
  if (r.packet?.affected) {
702
703
  this._updates = {};
703
704
  this._jsonUpdates = {};
704
- this._data[cstr._$primary] = r.packet.insert;
705
+ // --- 非自增主键(如 UUID)时 insertId 为 0,保留调用方已设置的主键值 ---
706
+ if (r.packet.insert || this._data[cstr._$primary] === undefined || this._data[cstr._$primary] === null) {
707
+ this._data[cstr._$primary] = r.packet.insert;
708
+ }
705
709
  this[cstr._$primary] = this._data[cstr._$primary];
706
710
  return true;
707
711
  }
@@ -717,6 +721,7 @@ export default class Mod {
717
721
  * @returns 是否成功;至少需要一个可更新字段,失败保留待写数据
718
722
  */
719
723
  async upsert(conflict) {
724
+ // --- 校验冲突键并分离 WHERE 条件与待更新字段 ---
720
725
  const cstr = this.constructor;
721
726
  const conflicts = typeof conflict === 'string' ? [conflict] : conflict;
722
727
  const inserts = this._getUpdates();
@@ -738,6 +743,7 @@ export default class Mod {
738
743
  if (!Object.keys(updates).length) {
739
744
  return false;
740
745
  }
746
+ // --- 按数据库类型执行插入/锁定(MySQL 分步,PGSQL 原子 UPSERT) ---
741
747
  const mysql = this._db.getService() === lDb.ESERVICE.MYSQL;
742
748
  const table = cstr._$table + (this._index ? `_${this._index[0]}` : '');
743
749
  const identity = [...new Set([cstr._$primary, cstr._$key, ...cstr._$partition].filter(field => field))];
@@ -756,6 +762,7 @@ export default class Mod {
756
762
  this._sql.insert(table).values(inserts).upsert(updates, conflicts);
757
763
  this._sql.append(` RETURNING ${identity.map(field => this._sql.field(field)).join(', ')}`);
758
764
  }
765
+ // --- 读取目标身份并在 MySQL 下补做更新 ---
759
766
  const result = await this._db.query(this._sql.getSql(), this._sql.getData());
760
767
  if (result.error) {
761
768
  lCore.log(this._ctr ?? {}, `[MOD][upsert][${cstr._$table}] database error: ${result.error.errno}`, '-error');
@@ -777,6 +784,7 @@ export default class Mod {
777
784
  return false;
778
785
  }
779
786
  }
787
+ // --- 回填主键/自动键并清空待写脏字段 ---
780
788
  for (const field of identity) {
781
789
  this._setProperty(field, row[field]);
782
790
  }
@@ -1001,6 +1009,7 @@ export default class Mod {
1001
1009
  offset += count;
1002
1010
  continue;
1003
1011
  }
1012
+ offset = -1;
1004
1013
  }
1005
1014
  const lsql = sql.replace(/ LIMIT [0-9 ,]+(OFFSET [0-9]+)?/g, ` LIMIT ${remain} OFFSET ${cz}`);
1006
1015
  const r = await this._db.query(lsql, this._sql.getData());
@@ -1352,6 +1361,7 @@ export default class Mod {
1352
1361
  * @returns 列表、首末行游标和扫描方向上的 hasMore,数据库错误返回 false
1353
1362
  */
1354
1363
  async allCursor(count, opt) {
1364
+ // --- 校验分页与游标参数 ---
1355
1365
  if (!Number.isSafeInteger(count) || count < 1 || count >= Number.MAX_SAFE_INTEGER ||
1356
1366
  this._index !== null || this._contain || (opt.before && !opt.cursor) ||
1357
1367
  (opt.order !== undefined && !['ASC', 'DESC'].includes(opt.order))) {
@@ -1362,6 +1372,7 @@ export default class Mod {
1362
1372
  if (keys.length !== fields.length || new Set(keys).size !== keys.length) {
1363
1373
  throw new Error('Cursor result keys must match ordering fields');
1364
1374
  }
1375
+ // --- 构造游标查询(多取 1 条判断 hasMore) ---
1365
1376
  const order = opt.order ?? 'DESC';
1366
1377
  const direction = opt.before ? (order === 'DESC' ? 'ASC' : 'DESC') : order;
1367
1378
  const sql = this._sql.copy(undefined, { 'order': false, 'limit': false });
@@ -1371,6 +1382,7 @@ export default class Mod {
1371
1382
  lCore.log(this._ctr ?? {}, '[MOD][allCursor] Query failed', '-error');
1372
1383
  return false;
1373
1384
  }
1385
+ // --- 裁剪结果并提取首末行游标 ---
1374
1386
  const hasMore = result.rows.length > count;
1375
1387
  const list = result.rows.slice(0, count);
1376
1388
  if (opt.before) {
@@ -1625,7 +1637,7 @@ export default class Mod {
1625
1637
  return updates;
1626
1638
  }
1627
1639
  /**
1628
- * --- 当前是否设置了未保存 --=
1640
+ * --- 当前是否设置了未保存 ---
1629
1641
  */
1630
1642
  unsaved() {
1631
1643
  return Object.keys(this._updates).length ? true : false;
@@ -1,6 +1,7 @@
1
+ /** --- master 读取落盘监控数据;只读取有界事件 JSON,Profile 和堆快照仅提供文件元数据 --- */
1
2
  import type { Stats } from 'fs';
2
3
  import type { IMonitorEvent, IMonitorEventSummary, IMonitorFile } from '#kebab/lib/core.js';
3
- /** --- 小型 JSON/文本预览上限,Profile 和堆快照不预览 --- */
4
+ /** --- 小型 JSON/文本预览上限(1MB),Profile 和堆快照不预览 --- */
4
5
  export declare const PREVIEW_LIMIT: number;
5
6
  /**
6
7
  * --- 获取一天的事件摘要,先分页目录再读取记录 ---