@maiyunnet/kebab 9.25.1 → 9.26.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.
package/README.md CHANGED
@@ -1,203 +1,261 @@
1
- <p align="center"><img src="./doc/icon.png" width="64" height="64" alt="Kebab"></p>
2
- <p align="center">
3
- <a href="https://github.com/maiyun/kebab/blob/main/LICENSE">
4
- <img alt="License" src="https://img.shields.io/github/license/maiyun/kebab?color=blue" />
5
- </a>
6
- <a href="https://www.npmjs.com/package/@maiyunnet/kebab">
7
- <img alt="NPM stable version" src="https://img.shields.io/npm/v/@maiyunnet/kebab?color=brightgreen&logo=npm" />
8
- </a>
9
- <a href="https://github.com/maiyun/kebab/releases">
10
- <img alt="GitHub releases" src="https://img.shields.io/github/v/release/maiyun/kebab?color=brightgreen&logo=github" />
11
- </a>
12
- <a href="https://github.com/maiyun/kebab/issues">
13
- <img alt="GitHub issues" src="https://img.shields.io/github/issues/maiyun/kebab?color=blue&logo=github" />
14
- </a>
15
- </p>
16
-
17
- Simple, easy-to-use, and fully-featured Node.js framework that is ready-to-use out of the box.
18
-
19
- ## Languages
20
-
21
- [简体中文](doc/README.sc.md) | [繁體中文](doc/README.tc.md)
22
-
23
- ## Requirement
24
-
25
- Node 22+
26
-
27
- ## Installation
28
-
29
- Run `npm i @maiyunnet/kebab` to install the latest version. After installation, run `npx kebab init` to initialize, then run `npx kebab` to start the project.
30
-
31
- You can also use pm2 to start the project by running:
32
-
33
- `pm2 start npx --name "kebab" -- kebab`
34
-
35
- ## Library
36
-
37
- Ai, Buffer, Captcha, Consistent, Core, Cron, Crypto, Db (MySQL, PostgreSQL), Dns (DNSPod, Alibaba Cloud), Fs, Kv (Redis), Lan, Lang, Net, S3, Scan, Session, Socket, Sql, Ssh (Shell, Sftp), Text, Time, Turnstile (Cloudflare, Tencent Cloud), Vector (Milvus), Ws, Zip, Zlib.
38
-
39
- ## Partial Features
40
-
41
- ### Ready-to-use
42
-
43
- Following the principle of "ready-to-use", this package includes commonly used libraries in a unified style.
44
-
45
- ### Hot update
46
-
47
- By calling the Core.sendRestart method, you can smoothly achieve alternating hot updates between old and new code without interrupting any existing business or connections.
48
-
49
- ### Multi-process support
50
-
51
- Create a multi-process model based on the number of CPU cores to fully utilize the multi-core CPU.
52
-
53
- ### Global connection pool
54
-
55
- If different sites in the same process connect to the same server, such as db, kv, etc., they share the same connection pool, maximizing efficiency and reducing overhead.
56
-
57
- ### Super Easy-to-use net Library
58
-
59
- ```typescript
60
- const res = await lNet.open('https://xxx/test').post().data({ 'a': '1', 'b': '2' }).request();
61
- ```
62
-
63
- It can also be used like this:
64
-
65
- ```typescript
66
- const res = await lNet.get('https://xxx/test');
67
- ```
68
-
69
- You can set custom parsing results:
70
-
71
- ```typescript
72
- const res = await lNet.get('https://xxx/test', {
73
- 'hosts': {
74
- 'xxx': '111.111.111.111'
75
- }
76
- });
77
- ```
78
-
79
- You can also choose other local network cards to access:
80
-
81
- ```typescript
82
- const res = await lNet.get('https://xxx/test', {
83
- 'local': '123.123.123.123'
84
- });
85
- ```
86
-
87
- It also has a complete cookie manager, which can easily obtain and store cookies anywhere. When sending a request, the system will select the domain and path based on the cookie settings. If Set-Cookie has an illegal cross-domain setting, it will be discarded and not recorded, just like a real browser.
88
-
89
- ```typescript
90
- const res1 = await lNet.get('https://xxx1.xxx/test1', { 'cookie': cookie });
91
- const res2 = await lNet.get('https://xxx2.xxx/test2', { 'cookie': cookie });
92
- ```
93
-
94
- > Note: The net library supports both options and open chain operations. For example, await lNet.open('xxx').follow().timeout(60).save(this._config.const.rootPath + 'doc/test.txt').request();
95
-
96
- ### Easy-to-Use Db Library
97
-
98
- With a large number of useful interfaces, you can easily filter the data you need from the database:
99
-
100
- ```typescript
101
- const ls = Order.where<Order>(this, db, {
102
- 'state': '1'
103
- }).by('id', 'DESC').page(10, 1);
104
- const list = await ls.all();
105
- const count = await ls.count();
106
- const total = await ls.total();
107
- ```
108
-
109
- Get a user:
110
-
111
- ```typescript
112
- const user = await User.select<User>(this, db, ['id', 'user']).filter([
113
- ['time_add', '>=', '1583405134']
114
- ]).first();
115
- ```
116
-
117
- ### XSRF Detection
118
-
119
- Use the _checkXInput method to perform XSRF detection and prevent malicious access.
120
-
121
- ### Scan Login
122
-
123
- With the help of the Scan library, it's easy to implement scan login.
124
-
125
- ### Reverse Proxy
126
-
127
- Achieve reverse proxy functionality effortlessly by utilizing the rproxy method from the net library, combined with route parameters.
128
-
129
- #### There are more features waiting for you to explore
130
-
131
- ## Examples
132
-
133
- ### Creating a 16-bit random number
134
-
135
- ```typescript
136
- let str: string = Core.random(16, Core.RANDOM_N)
137
- ```
138
-
139
- ### Creating a verification code
140
-
141
- ```typescript
142
- Captcha.get(400, 100).getBuffer();
143
- ```
144
-
145
- ### Getting a list
146
-
147
- ```typescript
148
- const userList = await User.where<User>(this, db, [
149
- ['state', '!=', '0'],
150
- {
151
- 'type': ['1', '2', '3'],
152
- 'is_lock': '0'
153
- }
154
- ]).all();
155
- ```
156
-
157
- > Note: All database operations have been protected against injection attacks.
158
-
159
- ### Sql Library Automatically Adds Table Prefixes and Wrapping Characters "`"
160
-
161
- ```typescript
162
- sql.select(['SUM(user.age) age'], 'order').leftJoin('user', {'order.user_id': lSql.column('user.id')});
163
- ```
164
-
165
- The output will be:
166
-
167
- ```sql
168
- SELECT SUM(`test_user`.`age`) AS `age` FROM `test_order` LEFT JOIN `test_user` ON `test_order`.`user_id` = `test_user`.`id`
169
- ```
170
-
171
- It's so easy to write!
172
-
173
- ### Localization
174
-
175
- ```typescript
176
- await this._loadLocale(this._get['lang'], 'test');
177
- return this._l('copy');
178
- ```
179
-
180
- Based on the different values of lang, the output will be: Copy, 复制, 複製, コピー, etc., configured in the /data/locale/ directory.
181
-
182
- ### Data Validation
183
-
184
- Directly validate submitted data based on strings, numbers, comparisons, and even regular expressions. It's convenient!
185
-
186
- ```typescript
187
- {
188
- 'he': ['require', [0, 'The he param does not exist.']],
189
- 'num': ['> 10', [0, 'The num param must > 10.']],
190
- 'reg': ['/^[A-CX-Z5-7]+$/', [0, 'The reg param is incorrect.']],
191
- 'arr': [['a', 'x', 'hehe'], [0, 'The arr param is incorrect.']]
192
- }
193
- ```
194
-
195
- See: /test/ctr-checkinput
196
-
197
- ### Other Examples
198
-
199
- You can visit /test/ to see more examples.
200
-
201
- ## License
202
-
203
- This library is published under [Apache-2.0](./LICENSE) license.
1
+ <p align="center"><img src="./doc/icon.png" width="64" height="64" alt="Kebab"></p>
2
+ <p align="center">
3
+ <a href="https://github.com/maiyun/kebab/blob/main/LICENSE">
4
+ <img alt="License" src="https://img.shields.io/github/license/maiyun/kebab?color=blue" />
5
+ </a>
6
+ <a href="https://www.npmjs.com/package/@maiyunnet/kebab">
7
+ <img alt="NPM stable version" src="https://img.shields.io/npm/v/@maiyunnet/kebab?color=brightgreen&logo=npm" />
8
+ </a>
9
+ <a href="https://github.com/maiyun/kebab/releases">
10
+ <img alt="GitHub releases" src="https://img.shields.io/github/v/release/maiyun/kebab?color=brightgreen&logo=github" />
11
+ </a>
12
+ <a href="https://github.com/maiyun/kebab/issues">
13
+ <img alt="GitHub issues" src="https://img.shields.io/github/issues/maiyun/kebab?color=blue&logo=github" />
14
+ </a>
15
+ </p>
16
+
17
+ A simple, easy-to-use, full-featured Node.js framework, ready to use out of the box.
18
+
19
+ > Project statement: This project was first committed to GitHub on February 25, 2019. Its predecessor, the Mutton framework, was first committed on July 13, 2015, after several years of development. In 2026, the project formally introduced AI-assisted development and adaptations for AI integration, but software engineers still lead, review, verify and test the project; it is not automatically generated by simply telling AI what we want. Non-Chinese content is translated with assistance from Byterun Translator, so the wording may have an AI-like tone.
20
+
21
+ > The releases on GitHub may be incomplete. For versions after 2.0.0, refer to NPM as the source of record: [NPM](https://www.npmjs.com/package/@maiyunnet/kebab?activeTab=versions)
22
+
23
+ ## Languages
24
+
25
+ [简体中文](doc/README.sc.md) | [繁體中文](doc/README.tc.md)
26
+
27
+ ## Requirements
28
+
29
+ Node.js 24+
30
+
31
+ ## Installation
32
+
33
+ Run `npm i @maiyunnet/kebab` to install the latest version. After installation, run `npx kebab init` to initialize, then run `npx kebab` to start the project.
34
+
35
+ You can also start the project with pm2 by running `pm2 start npx --name "kebab" -- kebab`.
36
+
37
+ ## Libraries
38
+
39
+ Ai, Buffer, Captcha, Consistent, Cookie, Core, Cron, Crypto, Db (MySQL, PostgreSQL), Dns (DNSPod, Alibaba Cloud), Fs, Kv (Redis), Lan, Lang, Net, Ratelimit, S3, Scan, Session, Socket, Sql, Ssh (Shell, Sftp), Text, Time, Turnstile (Cloudflare, Tencent Cloud), Undici, Vector (Milvus), Ws, Zip, Zlib.
40
+
41
+ Use Undici for new HTTP requests; Net remains available for compatibility with existing code.
42
+
43
+ ## Documentation
44
+
45
+ - [Quick start](doc/sc/quick-start.md)
46
+ - [Cursor pagination and approximate totals in PostgreSQL](doc/sc/query-pagination.md)
47
+ - [Performance monitoring and incident review](doc/sc/monitor.md)
48
+ - [API reference](doc/sc/api/index.md)
49
+
50
+ ## Selected features
51
+
52
+ ### Ready to use
53
+
54
+ Following the principle of being ready to use out of the box, Kebab wraps commonly used libraries in a consistent style.
55
+
56
+ ### Hot updates
57
+
58
+ Call `lCore.sendRestart()` to initiate a graceful restart: new processes accept connections, while old processes exit once their existing connections have ended.
59
+
60
+ ### Multiple processes
61
+
62
+ Create multiple processes based on the number of CPU cores to make full use of a multi-core CPU.
63
+
64
+ ### Shared connection pools
65
+
66
+ Different sites in the same process share a connection pool when connecting to the same Db, Kv or other server, maximizing efficiency and reducing overhead.
67
+
68
+ ### Easy-to-use Undici library
69
+
70
+ ```typescript
71
+ import * as lUndici from '@maiyunnet/kebab/lib/undici.js';
72
+
73
+ const res = await lUndici.open('https://example.com/test').post().data({ 'a': '1', 'b': '2' }).request();
74
+ const content = await res.getContent();
75
+ ```
76
+
77
+ You can also use it like this:
78
+
79
+ ```typescript
80
+ const res = await lUndici.get('https://example.com/test');
81
+ const content = await res.getContent();
82
+ ```
83
+
84
+ When you only need a JSON response, use the corresponding shortcut method. Request or read failures return `null`; JSON parsing failures return `false`:
85
+
86
+ ```typescript
87
+ const data = await lUndici.getResponseJson('https://example.com/data');
88
+ ```
89
+
90
+ You can customize hostname resolution. Here, `hostsMap` is a caller-provided mapping of hostnames to IP addresses:
91
+
92
+ ```typescript
93
+ const res = await lUndici.get('https://example.com/test', {
94
+ 'hosts': hostsMap,
95
+ });
96
+ const content = await res.getContent();
97
+ ```
98
+
99
+ You can also use another local network interface. Here, `localAddress` is the local IP address from your configuration:
100
+
101
+ ```typescript
102
+ const res = await lUndici.get('https://example.com/test', {
103
+ 'local': localAddress,
104
+ });
105
+ const content = await res.getContent();
106
+ ```
107
+
108
+ It also has a complete cookie manager that stores received cookies in a caller-provided object. When sending requests, the system selects cookies based on their domain, path and other attributes, and discards Set-Cookie values with invalid cross-domain settings:
109
+
110
+ ```typescript
111
+ import * as lCookie from '@maiyunnet/kebab/lib/cookie.js';
112
+
113
+ const cookie: Record<string, lCookie.ICookie> = {};
114
+ const res1 = await lUndici.get('https://example.com/login', { 'cookie': cookie });
115
+ await res1.getContent();
116
+ const res2 = await lUndici.get('https://example.com/profile', { 'cookie': cookie });
117
+ await res2.getContent();
118
+ ```
119
+
120
+ > Note: Undici supports both options and chained open calls, such as `await lUndici.open('https://example.com/file').follow().timeout(60).save(filePath).request()`; `filePath` is a caller-provided local file path.
121
+
122
+ ### Easy-to-use Db library
123
+
124
+ A wide range of useful interfaces makes it easy to select the data you need from a database. In the following controller method snippets, `db` is a database connection pool, and `mOrder` and `mUser` are application-defined models:
125
+
126
+ ```typescript
127
+ const query = mOrder.where<mOrder>(db, {
128
+ 'state': '1',
129
+ }, { 'ctr': this }).by('id', 'DESC').page(10, 1);
130
+ const list = await query.all();
131
+ if (list === false) {
132
+ return [0, 'Query failed.'];
133
+ }
134
+ const count = list.length;
135
+ const total = await query.total();
136
+ ```
137
+
138
+ Get a user:
139
+
140
+ ```typescript
141
+ const user = await mUser.select<mUser>(db, ['id', 'user'], { 'ctr': this }).filter([
142
+ ['time_add', '>=', '1583405134']
143
+ ]).first();
144
+ ```
145
+
146
+ ### XSRF checks
147
+
148
+ For data-changing endpoints that rely on browser session cookies, use `_valibotx` to validate input and check XSRF, preventing cross-site request forgery. Pages generate a token with `_enabledXsrf()` and submit it as `_xsrf`; read-only endpoints use `_valibot`.
149
+
150
+ ### QR code login
151
+
152
+ The Scan library makes QR code login easy to implement.
153
+
154
+ ### Reverse proxy
155
+
156
+ Use the Undici library’s `rproxy` method with the current controller and a route-prefix mapping to implement a reverse proxy.
157
+
158
+ #### More features await your exploration
159
+
160
+ ## Code examples
161
+
162
+ ### Generate a random 16-digit string
163
+
164
+ ```typescript
165
+ import * as lCore from '@maiyunnet/kebab/lib/core.js';
166
+
167
+ const str = lCore.random(16, lCore.RANDOM_N);
168
+ ```
169
+
170
+ ### Generate a CAPTCHA image
171
+
172
+ ```typescript
173
+ import * as lCaptcha from '@maiyunnet/kebab/lib/captcha.js';
174
+
175
+ const captcha = lCaptcha.get(400, 100);
176
+ const svg = captcha.getBuffer();
177
+ const phrase = captcha.getPhrase();
178
+ ```
179
+
180
+ `getBuffer()` returns an SVG string; `phrase` is the corresponding CAPTCHA text, which should be stored on the server for subsequent verification.
181
+
182
+ ### Get a list
183
+
184
+ ```typescript
185
+ const userList = await mUser.where<mUser>(db, [
186
+ ['state', '!=', '0'],
187
+ {
188
+ 'type': ['1', '2', '3'],
189
+ 'is_lock': '0',
190
+ },
191
+ ], { 'ctr': this }).all();
192
+ ```
193
+
194
+ > Note: Values in query conditions are passed through parameter binding. Handwritten SQL should also bind user input, and dynamic table and column names should be restricted to trusted values.
195
+
196
+ ### Automatic table prefixes and identifier quoting with Sql
197
+
198
+ ```typescript
199
+ import * as lSql from '@maiyunnet/kebab/lib/sql.js';
200
+
201
+ const sql = lSql.get({ 'service': lSql.ESERVICE.MYSQL, 'pre': 'test' });
202
+ sql.select(['SUM(user.age) age'], 'order').leftJoin('user', { 'order.user_id': lSql.column('user.id') });
203
+ const statement = sql.getSql();
204
+ ```
205
+
206
+ The following output is for MySQL with the `test_` table prefix; PostgreSQL uses schemas and double quotes:
207
+
208
+ ```sql
209
+ SELECT SUM(`test_user`.`age`) AS `age` FROM `test_order` LEFT JOIN `test_user` ON `test_order`.`user_id` = `test_user`.`id`
210
+ ```
211
+
212
+ ### Localization
213
+
214
+ In the following controller method snippet, `lang` is a validated language code:
215
+
216
+ ```typescript
217
+ if (!await this._loadLocale(lang, 'test')) {
218
+ return 'Could not load locale.';
219
+ }
220
+ return this._l('copy');
221
+ ```
222
+
223
+ Depending on the value of lang, the output will be Copy, 复制, 複製, コピー, etc., configured in the site’s /data/locale/ directory.
224
+
225
+ ### Data validation
226
+
227
+ New endpoints use Valibot to validate strings, numbers, value ranges and regular expressions. On success, use `output` to obtain the converted data. Define rules in an application module for reuse, such as `lib/schema/input.ts`:
228
+
229
+ ```typescript
230
+ import * as lCore from '@maiyunnet/kebab/lib/core.js';
231
+
232
+ const v = lCore.v;
233
+ export const inputSchema = v.strictObject({
234
+ 'he': v.pipe(v.string(), v.nonEmpty()),
235
+ 'num': v.pipe(v.string(), v.toNumber(), v.gtValue(10)),
236
+ 'reg': v.pipe(v.string(), v.regex(/^[A-CX-Z5-7]+$/)),
237
+ 'arr': v.picklist(['a', 'x', 'hehe']),
238
+ });
239
+ ```
240
+
241
+ Import the rules in the `ctr/main.ts` controller and validate within a method:
242
+
243
+ ```typescript
244
+ import * as lInputSchema from '../lib/schema/input.js';
245
+
246
+ const parsed = this._valibot(lInputSchema.inputSchema, this._post);
247
+ if (!parsed.success) {
248
+ return parsed.response;
249
+ }
250
+ return [1, parsed.output];
251
+ ```
252
+
253
+ Use `_valibotx` instead for data-changing endpoints that rely on browser session cookies. See the [quick start](doc/sc/quick-start.md#使用-valibot-进行类型安全校验) for multilingual messages and XSRF usage, and `/test/ctr-valibot` for a working example.
254
+
255
+ ### Other examples
256
+
257
+ Visit /test/ to see more examples.
258
+
259
+ ## License
260
+
261
+ This framework is licensed under [Apache-2.0](./LICENSE).
package/abox/text.d.ts CHANGED
@@ -1,2 +1,3 @@
1
+ export declare function redact(value: string, secrets: readonly string[], replacement: string, encoded: boolean): string;
1
2
  export declare function parseJson<T>(str: string): T | false;
2
3
  export declare function stringifyJson(obj: unknown, space?: string | number): string;
package/abox/text.js CHANGED
@@ -1,5 +1,41 @@
1
1
  // TypeScript's bundled JSON declarations do not yet include these Node 22 APIs.
2
2
  const nativeJson = JSON;
3
+ export function redact(value, secrets, replacement, encoded) {
4
+ if (!value || !secrets.length)
5
+ return value;
6
+ const patterns = new Map();
7
+ const add = (text, uri = false) => {
8
+ if (text.length > value.length)
9
+ return;
10
+ let pattern = text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
11
+ if (uri) {
12
+ pattern = pattern.replace(/%[\dA-F]{2}/g, part => part.replace(/[A-F]/g, hex => `[${hex}${hex.toLowerCase()}]`));
13
+ }
14
+ patterns.set(pattern, text.length);
15
+ };
16
+ for (const secret of new Set(secrets)) {
17
+ if (!secret || secret.length > value.length)
18
+ continue;
19
+ add(secret);
20
+ if (!encoded)
21
+ continue;
22
+ const json = JSON.stringify(secret).slice(1, -1);
23
+ if (json !== secret)
24
+ add(json);
25
+ try {
26
+ const uri = encodeURIComponent(secret);
27
+ if (uri !== secret)
28
+ add(uri, true);
29
+ }
30
+ catch {
31
+ // A lone surrogate has no URI encoding; raw and JSON forms remain usable.
32
+ }
33
+ }
34
+ if (!patterns.size)
35
+ return value;
36
+ const pattern = [...patterns].sort((a, b) => b[1] - a[1]).map(([text]) => text).join('|');
37
+ return value.replace(new RegExp(pattern, 'g'), () => replacement);
38
+ }
3
39
  export function parseJson(str) {
4
40
  try {
5
41
  return nativeJson.parse(str, (_key, value, context) => {