@serveryyswys/node.operit 0.1.2 → 0.1.3

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.
@@ -0,0 +1,30 @@
1
+ /** v8 的堆统计类型(与 Node 的字段名一致)。 */
2
+ export interface HeapStatistics {
3
+ total_heap_size: number;
4
+ total_heap_size_executable: number;
5
+ total_physical_size: number;
6
+ total_available_size: number;
7
+ used_heap_size: number;
8
+ heap_size_limit: number;
9
+ malloced_memory: number;
10
+ peak_malloced_memory: number;
11
+ does_zap_garbage: boolean;
12
+ number_of_native_contexts: number;
13
+ number_of_detached_contexts: number;
14
+ total_global_handles_size: number;
15
+ used_global_handles_size: number;
16
+ external_memory: number;
17
+ }
18
+ export interface HeapSpaceStatistics {
19
+ space_name: string;
20
+ space_size: number;
21
+ space_used_size: number;
22
+ space_available_size: number;
23
+ physical_space_size: number;
24
+ }
25
+ export interface HeapCodeStatistics {
26
+ code_and_metadata_size: number;
27
+ bytecode_and_metadata_size: number;
28
+ external_script_source_size: number;
29
+ cpu_profiler_metadata_size: number;
30
+ }
@@ -0,0 +1,2 @@
1
+ 'use strict';
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/dist/module.js CHANGED
@@ -17,21 +17,42 @@
17
17
  */
18
18
  const errors_1 = require("./lib/errors");
19
19
  const builtinModules = [
20
+ '_http_agent',
21
+ '_http_client',
22
+ '_http_common',
23
+ '_http_incoming',
24
+ '_http_outgoing',
25
+ '_http_server',
26
+ '_stream_duplex',
27
+ '_stream_passthrough',
28
+ '_stream_readable',
29
+ '_stream_transform',
30
+ '_stream_wrap',
31
+ '_stream_writable',
32
+ '_tls_common',
33
+ '_tls_wrap',
20
34
  'assert',
21
35
  'assert/strict',
22
36
  'async_hooks',
23
37
  'buffer',
24
38
  'child_process',
25
39
  'cluster',
40
+ 'console',
26
41
  'constants',
27
42
  'crypto',
43
+ 'dgram',
44
+ 'diagnostics_channel',
28
45
  'dns',
46
+ 'dns/promises',
47
+ 'domain',
29
48
  'events',
30
49
  'fs',
31
50
  'fs/promises',
32
51
  'http',
52
+ 'http2',
33
53
  'https',
34
54
  'inspector',
55
+ 'inspector/promises',
35
56
  'module',
36
57
  'net',
37
58
  'os',
@@ -40,18 +61,27 @@ const builtinModules = [
40
61
  'path/win32',
41
62
  'perf_hooks',
42
63
  'process',
64
+ 'punycode',
43
65
  'querystring',
44
66
  'readline',
45
67
  'repl',
46
68
  'stream',
69
+ 'stream/consumers',
47
70
  'stream/promises',
71
+ 'stream/web',
48
72
  'string_decoder',
73
+ 'sys',
49
74
  'timers',
50
75
  'timers/promises',
76
+ 'tls',
77
+ 'trace_events',
51
78
  'tty',
52
79
  'url',
53
80
  'util',
81
+ 'util/types',
82
+ 'v8',
54
83
  'vm',
84
+ 'wasi',
55
85
  'worker_threads',
56
86
  'zlib'
57
87
  ];
@@ -0,0 +1,22 @@
1
+ /**
2
+ * punycode(已废弃,但仍被不少包直接 require)。
3
+ *
4
+ * 实现复用 lib/punycode.ts —— url 模块内部也在用它,所以这里不重复一份。
5
+ * 与 Node 的差异:`version` 报 '2.1.1'(Node 内置的是同一个算法实现的 2.x)。
6
+ */
7
+ import punycodeCore = require('./lib/punycode');
8
+ /** UTF-16 码元序列(Node 的 punycode.ucs2.decode 返回的是码元,不是码点)。 */
9
+ declare function ucs2decode(value: string): number[];
10
+ declare function ucs2encode(codePoints: readonly number[]): string;
11
+ declare const punycode: {
12
+ version: string;
13
+ ucs2: {
14
+ decode: typeof ucs2decode;
15
+ encode: typeof ucs2encode;
16
+ };
17
+ decode: typeof punycodeCore.decode;
18
+ encode: typeof punycodeCore.encode;
19
+ toASCII: typeof punycodeCore.toASCII;
20
+ toUnicode: typeof punycodeCore.toUnicode;
21
+ };
22
+ export = punycode;
@@ -0,0 +1,53 @@
1
+ 'use strict';
2
+ /**
3
+ * punycode(已废弃,但仍被不少包直接 require)。
4
+ *
5
+ * 实现复用 lib/punycode.ts —— url 模块内部也在用它,所以这里不重复一份。
6
+ * 与 Node 的差异:`version` 报 '2.1.1'(Node 内置的是同一个算法实现的 2.x)。
7
+ */
8
+ const punycodeCore = require("./lib/punycode");
9
+ /** UTF-16 码元序列(Node 的 punycode.ucs2.decode 返回的是码元,不是码点)。 */
10
+ function ucs2decode(value) {
11
+ const output = [];
12
+ let counter = 0;
13
+ while (counter < value.length) {
14
+ const first = value.charCodeAt(counter);
15
+ counter += 1;
16
+ if (first >= 0xd800 && first <= 0xdbff && counter < value.length) {
17
+ const second = value.charCodeAt(counter);
18
+ if ((second & 0xfc00) === 0xdc00) {
19
+ counter += 1;
20
+ output.push(((first & 0x3ff) << 10) + (second & 0x3ff) + 0x10000);
21
+ continue;
22
+ }
23
+ }
24
+ output.push(first);
25
+ }
26
+ return output;
27
+ }
28
+ function ucs2encode(codePoints) {
29
+ let output = '';
30
+ for (let index = 0; index < codePoints.length; index += 1) {
31
+ const value = codePoints[index];
32
+ if (value > 0xffff) {
33
+ const adjusted = value - 0x10000;
34
+ output += String.fromCharCode((adjusted >>> 10) + 0xd800, (adjusted % 0x400) + 0xdc00);
35
+ }
36
+ else {
37
+ output += String.fromCharCode(value);
38
+ }
39
+ }
40
+ return output;
41
+ }
42
+ const punycode = {
43
+ version: '2.1.1',
44
+ ucs2: {
45
+ decode: ucs2decode,
46
+ encode: ucs2encode
47
+ },
48
+ decode: punycodeCore.decode,
49
+ encode: punycodeCore.encode,
50
+ toASCII: punycodeCore.toASCII,
51
+ toUnicode: punycodeCore.toUnicode
52
+ };
53
+ module.exports = punycode;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * stream/consumers:把一个可读流整体读成各种表示。
3
+ *
4
+ * 与 Node 的差异(都写进 BUILTINS.json):
5
+ * - `blob` 显式抛 ONJ_UNSUPPORTED:运行时不提供 Blob(Node 的 blob() 返回一个 Blob 实例),
6
+ * 与其返回一个形状相似但不是 Blob 的对象,不如明确拒绝;
7
+ * - 不做 Node 内部的 `stream.Readable` 品牌校验,只要求对象有 on()。
8
+ */
9
+ import bufferModule = require('../buffer');
10
+ import { ReadableLike } from '../lib/stream-consumers-types';
11
+ type BufferInstance = InstanceType<typeof bufferModule.Buffer>;
12
+ declare function buffer(stream: ReadableLike): Promise<BufferInstance>;
13
+ declare function text(stream: ReadableLike): Promise<string>;
14
+ declare function json(stream: ReadableLike): Promise<unknown>;
15
+ declare function arrayBuffer(stream: ReadableLike): Promise<ArrayBuffer>;
16
+ declare function blob(_stream: ReadableLike): Promise<never>;
17
+ declare const consumers: {
18
+ buffer: typeof buffer;
19
+ text: typeof text;
20
+ json: typeof json;
21
+ arrayBuffer: typeof arrayBuffer;
22
+ blob: typeof blob;
23
+ };
24
+ export = consumers;
@@ -0,0 +1,75 @@
1
+ 'use strict';
2
+ /**
3
+ * stream/consumers:把一个可读流整体读成各种表示。
4
+ *
5
+ * 与 Node 的差异(都写进 BUILTINS.json):
6
+ * - `blob` 显式抛 ONJ_UNSUPPORTED:运行时不提供 Blob(Node 的 blob() 返回一个 Blob 实例),
7
+ * 与其返回一个形状相似但不是 Blob 的对象,不如明确拒绝;
8
+ * - 不做 Node 内部的 `stream.Readable` 品牌校验,只要求对象有 on()。
9
+ */
10
+ const bufferModule = require("../buffer");
11
+ function onjUnsupported(feature) {
12
+ const failure = new Error(feature + ' 需要运行时的 Blob 实现,Android 的 QuickJS 运行时不提供。');
13
+ failure.code = 'ONJ_UNSUPPORTED';
14
+ return failure;
15
+ }
16
+ function toBytes(chunk) {
17
+ if (typeof chunk === 'string') {
18
+ return bufferModule.Buffer.from(chunk);
19
+ }
20
+ if (chunk instanceof Uint8Array) {
21
+ return chunk;
22
+ }
23
+ throw new TypeError('流给出的数据块既不是字符串也不是 Uint8Array。');
24
+ }
25
+ function consume(stream) {
26
+ return new Promise((resolve, reject) => {
27
+ const chunks = [];
28
+ let finished = false;
29
+ stream.on('data', (chunk) => {
30
+ chunks.push(toBytes(chunk));
31
+ });
32
+ stream.on('end', () => {
33
+ if (finished) {
34
+ return;
35
+ }
36
+ finished = true;
37
+ resolve(bufferModule.Buffer.concat(chunks));
38
+ });
39
+ stream.on('error', (error) => {
40
+ if (finished) {
41
+ return;
42
+ }
43
+ finished = true;
44
+ reject(error);
45
+ });
46
+ });
47
+ }
48
+ async function buffer(stream) {
49
+ return consume(stream);
50
+ }
51
+ async function text(stream) {
52
+ const bytes = await consume(stream);
53
+ return bytes.toString('utf8');
54
+ }
55
+ async function json(stream) {
56
+ const content = await text(stream);
57
+ return JSON.parse(content);
58
+ }
59
+ async function arrayBuffer(stream) {
60
+ const bytes = await consume(stream);
61
+ const copy = new Uint8Array(bytes.length);
62
+ copy.set(bytes);
63
+ return copy.buffer;
64
+ }
65
+ function blob(_stream) {
66
+ return Promise.reject(onjUnsupported('stream/consumers.blob()'));
67
+ }
68
+ const consumers = {
69
+ buffer: buffer,
70
+ text: text,
71
+ json: json,
72
+ arrayBuffer: arrayBuffer,
73
+ blob: blob
74
+ };
75
+ module.exports = consumers;
package/dist/sys.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * 已废弃的 `sys` 模块。
3
+ *
4
+ * Node 里它就是 `util` 的**同一个对象**(`require('sys') === require('util')`),
5
+ * 历史上是 util 的前身。仍有老包 require 它,所以保持这个别名。
6
+ */
7
+ import utilModule = require('./util');
8
+ export = utilModule;
package/dist/sys.js ADDED
@@ -0,0 +1,9 @@
1
+ 'use strict';
2
+ /**
3
+ * 已废弃的 `sys` 模块。
4
+ *
5
+ * Node 里它就是 `util` 的**同一个对象**(`require('sys') === require('util')`),
6
+ * 历史上是 util 的前身。仍有老包 require 它,所以保持这个别名。
7
+ */
8
+ const utilModule = require("./util");
9
+ module.exports = utilModule;
@@ -0,0 +1,16 @@
1
+ declare const _default: {
2
+ isDate: (value: unknown) => boolean;
3
+ isRegExp: (value: unknown) => boolean;
4
+ isArray: (value: unknown) => boolean;
5
+ isTypedArray: (value: unknown) => boolean;
6
+ isUint8Array: (value: unknown) => boolean;
7
+ isArrayBuffer: (value: unknown) => boolean;
8
+ isPromise: (value: unknown) => boolean;
9
+ isNativeError: (value: unknown) => boolean;
10
+ isMap: (value: unknown) => boolean;
11
+ isSet: (value: unknown) => boolean;
12
+ isBigInt64Array: (value: unknown) => boolean;
13
+ isAsyncFunction: (value: unknown) => boolean;
14
+ isGeneratorFunction: (value: unknown) => boolean;
15
+ };
16
+ export = _default;
@@ -0,0 +1,9 @@
1
+ 'use strict';
2
+ /**
3
+ * `util/types` 子路径入口:与 `require('util').types` 是同一个对象。
4
+ *
5
+ * 它是很多包的高频依赖(比如 `is-* 系列、`has-symbols` 这类能力探测),
6
+ * 而且写法通常是 `require('util/types')` 而不是从 `util` 上取。
7
+ */
8
+ const utilModule = require("../util");
9
+ module.exports = utilModule.types;
package/dist/util.d.ts CHANGED
@@ -1,15 +1,4 @@
1
- interface InspectOptions {
2
- depth?: number | null;
3
- colors?: boolean;
4
- showHidden?: boolean;
5
- compact?: boolean | number;
6
- breakLength?: number;
7
- sorted?: boolean;
8
- maxArrayLength?: number;
9
- maxStringLength?: number | null;
10
- getters?: boolean;
11
- showProxy?: boolean;
12
- }
1
+ import { InspectOptions } from './lib/util-types';
13
2
  declare function inspect(value: unknown, options?: InspectOptions | boolean | number): string;
14
3
  declare function formatWithOptions(options: InspectOptions, template?: unknown, ...rest: unknown[]): string;
15
4
  declare function format(template?: unknown, ...rest: unknown[]): string;
package/dist/util.js CHANGED
@@ -245,6 +245,12 @@ function jsonOf(value) {
245
245
  }
246
246
  }
247
247
  function formatWithOptions(options, template, ...rest) {
248
+ // Node 的 util.format() / util.formatWithOptions({}) 在**没有要格式化的值**时返回空串,
249
+ // 而不是字符串 'undefined'。两者必须区分开 —— 否则 console.log() 会多打印一个 "undefined"
250
+ // (console 与 Node 的逐字节对拍抓到了这一条)。
251
+ if (arguments.length <= 1) {
252
+ return '';
253
+ }
248
254
  const args = [template].concat(rest);
249
255
  const first = args[0];
250
256
  const inspectOptions = options === undefined || options === null ? {} : options;
@@ -323,6 +329,12 @@ function formatWithOptions(options, template, ...rest) {
323
329
  return out;
324
330
  }
325
331
  function format(template, ...rest) {
332
+ // 必须在**这一层**判断参数个数:下面那次调用永远会给 formatWithOptions 传两个实参
333
+ // (options 和显式的 template),所以那边无法区分"没传值"和"传了 undefined"。
334
+ // Node:util.format() === '',util.format(undefined) === 'undefined'。
335
+ if (arguments.length === 0) {
336
+ return '';
337
+ }
326
338
  return formatWithOptions({}, template, ...rest);
327
339
  }
328
340
  function inherits(constructor, superConstructor) {
package/dist/v8.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ import { HeapStatistics, HeapSpaceStatistics, HeapCodeStatistics } from './lib/v8-types';
2
+ declare function getHeapStatistics(): HeapStatistics;
3
+ /** QuickJS 不暴露分空间统计,返回空数组(Node 在 V8 下会给出各 space)。 */
4
+ declare function getHeapSpaceStatistics(): HeapSpaceStatistics[];
5
+ declare function getHeapCodeStatistics(): HeapCodeStatistics;
6
+ declare function serialize(): never;
7
+ declare function deserialize(): never;
8
+ declare function setFlagsFromString(): never;
9
+ declare function cachedDataVersionTag(): never;
10
+ declare function writeHeapSnapshot(): never;
11
+ declare function takeCoverage(): never;
12
+ declare function stopCoverage(): never;
13
+ declare const v8Module: {
14
+ getHeapStatistics: typeof getHeapStatistics;
15
+ getHeapSpaceStatistics: typeof getHeapSpaceStatistics;
16
+ getHeapCodeStatistics: typeof getHeapCodeStatistics;
17
+ serialize: typeof serialize;
18
+ deserialize: typeof deserialize;
19
+ setFlagsFromString: typeof setFlagsFromString;
20
+ cachedDataVersionTag: typeof cachedDataVersionTag;
21
+ writeHeapSnapshot: typeof writeHeapSnapshot;
22
+ takeCoverage: typeof takeCoverage;
23
+ stopCoverage: typeof stopCoverage;
24
+ };
25
+ export = v8Module;
package/dist/v8.js ADDED
@@ -0,0 +1,127 @@
1
+ 'use strict';
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ /**
36
+ * v8 —— **partial**。
37
+ *
38
+ * 只实现"能从 JVM 如实取到"的堆统计;V8 专有的东西(序列化格式、V8 标志、覆盖率、
39
+ * 堆快照)在 QuickJS + Android 上没有对应物,一律显式抛 ONJ_UNSUPPORTED,
40
+ * 不给形状相似但语义不同的假实现。
41
+ *
42
+ * 注意:这里的堆统计是 **JVM 堆**,不是 V8 堆(Node 里是 V8 堆)。
43
+ * 这一点与 os.totalmem / os.freemem 的近似同类,已在 BUILTINS.json 里记明。
44
+ */
45
+ const bridge = __importStar(require("./lib/bridge"));
46
+ function onjUnsupported(feature, reason) {
47
+ const failure = new Error(feature + ':' + reason);
48
+ failure.code = 'ONJ_UNSUPPORTED';
49
+ return failure;
50
+ }
51
+ function runtime() {
52
+ return bridge.callStatic('java.lang.Runtime', 'getRuntime', []);
53
+ }
54
+ function heapNumbers() {
55
+ const handle = runtime();
56
+ return {
57
+ total: Number(bridge.callInstance(handle, 'totalMemory', [])) || 0,
58
+ free: Number(bridge.callInstance(handle, 'freeMemory', [])) || 0,
59
+ max: Number(bridge.callInstance(handle, 'maxMemory', [])) || 0
60
+ };
61
+ }
62
+ function getHeapStatistics() {
63
+ const heap = heapNumbers();
64
+ const used = heap.total - heap.free;
65
+ return {
66
+ total_heap_size: heap.total,
67
+ total_heap_size_executable: 0,
68
+ total_physical_size: heap.total,
69
+ total_available_size: heap.max - used,
70
+ used_heap_size: used,
71
+ heap_size_limit: heap.max,
72
+ malloced_memory: 0,
73
+ peak_malloced_memory: 0,
74
+ does_zap_garbage: false,
75
+ number_of_native_contexts: 1,
76
+ number_of_detached_contexts: 0,
77
+ total_global_handles_size: 0,
78
+ used_global_handles_size: 0,
79
+ external_memory: 0
80
+ };
81
+ }
82
+ /** QuickJS 不暴露分空间统计,返回空数组(Node 在 V8 下会给出各 space)。 */
83
+ function getHeapSpaceStatistics() {
84
+ return [];
85
+ }
86
+ function getHeapCodeStatistics() {
87
+ return {
88
+ code_and_metadata_size: 0,
89
+ bytecode_and_metadata_size: 0,
90
+ external_script_source_size: 0,
91
+ cpu_profiler_metadata_size: 0
92
+ };
93
+ }
94
+ function serialize() {
95
+ throw onjUnsupported('v8.serialize()', 'V8 的二进制序列化格式依赖 V8 本身,QuickJS 无法产出兼容字节流');
96
+ }
97
+ function deserialize() {
98
+ throw onjUnsupported('v8.deserialize()', '同上:无法解析 V8 的序列化格式');
99
+ }
100
+ function setFlagsFromString() {
101
+ throw onjUnsupported('v8.setFlagsFromString()', '这是 V8 专有的标志开关,运行时不是 V8');
102
+ }
103
+ function cachedDataVersionTag() {
104
+ throw onjUnsupported('v8.cachedDataVersionTag()', '该值标识 V8 版本,用于判断编译缓存是否可用;运行时不用 V8 缓存');
105
+ }
106
+ function writeHeapSnapshot() {
107
+ throw onjUnsupported('v8.writeHeapSnapshot()', '堆快照是 V8 专有格式');
108
+ }
109
+ function takeCoverage() {
110
+ throw onjUnsupported('v8.takeCoverage()', '覆盖率采集是 V8 专有能力');
111
+ }
112
+ function stopCoverage() {
113
+ throw onjUnsupported('v8.stopCoverage()', '覆盖率采集是 V8 专有能力');
114
+ }
115
+ const v8Module = {
116
+ getHeapStatistics: getHeapStatistics,
117
+ getHeapSpaceStatistics: getHeapSpaceStatistics,
118
+ getHeapCodeStatistics: getHeapCodeStatistics,
119
+ serialize: serialize,
120
+ deserialize: deserialize,
121
+ setFlagsFromString: setFlagsFromString,
122
+ cachedDataVersionTag: cachedDataVersionTag,
123
+ writeHeapSnapshot: writeHeapSnapshot,
124
+ takeCoverage: takeCoverage,
125
+ stopCoverage: stopCoverage
126
+ };
127
+ module.exports = v8Module;
package/package.json CHANGED
@@ -1,17 +1,9 @@
1
1
  {
2
2
  "name": "@serveryyswys/node.operit",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "为 Operit 的 CommonJS 运行时补齐 Node 核心能力(fs / path / os / buffer / ...)",
5
- "license": "GPL-3.0-or-later",
6
- "keywords": [
7
- "operit",
8
- "quickjs",
9
- "node-compat",
10
- "commonjs",
11
- "polyfill",
12
- "android",
13
- "shim"
14
- ],
5
+ "license": "Apache-2.0",
6
+ "author": "serveryyswys",
15
7
  "main": "dist/index.js",
16
8
  "types": "dist/index.d.ts",
17
9
  "exports": {
@@ -26,6 +18,16 @@
26
18
  "BUILTINS.json",
27
19
  "README.md",
28
20
  "DESIGN.md",
29
- "LICENSE*"
21
+ "LICENSE*",
22
+ "NOTICE"
23
+ ],
24
+ "keywords": [
25
+ "operit",
26
+ "quickjs",
27
+ "node-compat",
28
+ "commonjs",
29
+ "polyfill",
30
+ "android",
31
+ "shim"
30
32
  ]
31
33
  }