mirror of
https://github.com/vercel-labs/scriptc.git
synced 2026-12-06 04:56:15 +08:00
Merge canary into the release branch
This commit is contained in:
@@ -520,7 +520,10 @@ jobs:
|
||||
# scripts/ci/canary-suite.mjs, so a local check of the canary tier runs the same command this job does.
|
||||
- name: Canary source-rule and snapshot tests
|
||||
if: needs.validation_scope.outputs.tier == 'canary'
|
||||
run: node scripts/ci/canary-suite.mjs
|
||||
# Four processes: the case-sharded heavy suites split their tests by
|
||||
# SCRIPTC_CANARY_SHARD, the small files are placed whole. Every test
|
||||
# still runs exactly once (scripts/ci/canary-suite.mjs --shard-plan).
|
||||
run: node scripts/ci/canary-suite.mjs --shards 4
|
||||
|
||||
native_macos:
|
||||
needs: [validation_scope, lanes, code_quality]
|
||||
@@ -861,6 +864,13 @@ jobs:
|
||||
echo "self-build lowering: reachable-emit=$emits relowers=$relowers"
|
||||
test "$emits" -eq 1
|
||||
test "$relowers" -eq 0
|
||||
# A view-cast program the width-copies pass rewrites: the pass's probe
|
||||
# of every expression is an identity lookup, and an asserted subtype
|
||||
# there is a checked conversion that throws only in the native compiler.
|
||||
- name: Compile the view-cast fixture with the native compiler
|
||||
env:
|
||||
SCRIPTC_NATIVE_CLI: ${{ github.workspace }}/.scriptc/native-cli/bin/scriptc
|
||||
run: pnpm exec vitest run tests/harness/native-compiler-view-cast.test.ts
|
||||
|
||||
effects:
|
||||
needs: [validation_scope, lanes, native_linux]
|
||||
|
||||
@@ -98,14 +98,14 @@ Naming a package skips the declaration requirement above, but the package still
|
||||
|
||||
scriptc implements a few packages itself and compiles that implementation in place of the package's published JavaScript. Which implementation compiles depends on the version your program has installed, so an import resolves the same way it does under Node.js: a package that isn't installed is still a missing package, and a version scriptc doesn't implement compiles from its own files as usual.
|
||||
|
||||
`undici` 5.x, 7.x and 8.x are built in. The implementation covers `request()`, `Dispatcher` (including subclasses that override `dispatch`), `Client`, `Pool` with its `stats`, `Agent` with per-origin `factory` functions and `connect` options, `buildConnector`, the `errors` classes and their `UND_ERR_*` codes, `setGlobalDispatcher` and `getGlobalDispatcher`, `fetch` and `Headers`, and the request events undici publishes on `node:diagnostics_channel`. With 5.x, `ProxyAgent` is built in too: every request travels through an HTTP CONNECT tunnel that an `http:` or `https:` proxy opens, with the `uri`, `token`, `auth`, `headers`, `requestTls` and `proxyTls` options. Requests use HTTP/1.1 with keep-alive connection reuse and undici's headers, body and idle timeouts, and each version keeps its own behavior where the versions differ, such as the error an aborted request rejects with. The 8.x entry also declares the classes that release adds (`MaxRedirectsError`, `ProxyConnectionError` and `WebAssemblyNotSupportedError`; the last is exported but never thrown, since this parser needs no WebAssembly); `Dispatcher1Wrapper` is not declared. The package's other exports aren't declared, so using one is a type error at build time. Known differences:
|
||||
`undici` 5.x, 7.x and 8.x are built in. The implementation covers `request()`, `Dispatcher` (including subclasses that override `dispatch`), `Client`, `Pool` with its `stats`, `Agent` with per-origin `factory` functions and `connect` options, `buildConnector`, the `errors` classes and their `UND_ERR_*` codes, `setGlobalDispatcher` and `getGlobalDispatcher`, `fetch` and `Headers`, and the request events undici publishes on `node:diagnostics_channel`. `ProxyAgent` is built in for every version, and 7.x and 8.x also declare `EnvHttpProxyAgent`: a `ProxyAgent` sends every request through an HTTP CONNECT tunnel that an `http:` or `https:` proxy opens, with the `uri`, `token`, `auth`, `headers`, `requestTls` and `proxyTls` options, and an `EnvHttpProxyAgent` picks that tunnel, or a direct connection, for each request from `http_proxy`/`HTTP_PROXY`, `https_proxy`/`HTTPS_PROXY` and `no_proxy`/`NO_PROXY` (or the `httpProxy`, `httpsProxy` and `noProxy` options that override them). Requests use HTTP/1.1 with keep-alive connection reuse and undici's headers, body and idle timeouts, and each version keeps its own behavior where the versions differ, such as the error an aborted request rejects with. The 8.x entry also declares the classes that release adds (`MaxRedirectsError`, `ProxyConnectionError` and `WebAssemblyNotSupportedError`; the last is exported but never thrown, since this parser needs no WebAssembly); `Dispatcher1Wrapper` is not declared. The package's other exports aren't declared, so using one is a type error at build time. Known differences:
|
||||
|
||||
- A response body supports the readable-stream members undici's body mixin uses: `on`, `once`, `pause`, `resume`, `destroy`, `text()`, `json()`, `arrayBuffer()`, `bytes()`, `blob()` and `dump()`. It can't be piped or iterated with `for await`.
|
||||
- A response body supports the readable-stream members undici's body mixin uses: `on`, `once`, `pause`, `resume`, `destroy`, `text()`, `json()`, `arrayBuffer()`, `bytes()`, `blob()` and `dump()`. It is an async iterable, so `for await (const chunk of response.body)` reads the body chunk by chunk, and `stream/promises.pipeline(response.body, destination)` accepts it as the source. Iteration applies backpressure: a slow consumer pauses the body at its high-water mark instead of queuing the rest, and an iteration started after the body ended completes immediately. It has no `pipe()` method.
|
||||
- Diagnostics channel messages carry the request but not the socket or connector.
|
||||
- `fetch` with a dispatcher returns a response whose `url` is empty and whose `redirected` is `false`, and offers only `gzip, deflate` encodings. Without a dispatcher it is the built-in `fetch`. Its init can be undici's `RequestInit` or the global one, and it sends string and byte bodies (a string, an `ArrayBuffer` or one of its views); a stream, `Blob`, `FormData` or `URLSearchParams` body rejects with a `NotSupportedError`. The init members undici acts on and this implementation doesn't (`integrity`, `cache`, `mode`, `referrer`, `referrerPolicy`, `credentials`, `duplex`, `keepalive`, `priority`, `window`) are taken only with a value that asks for nothing, such as an empty `integrity` or `mode: "cors"`; any other value rejects with a `NotSupportedError` that names the member, so a digest is never accepted and then not checked.
|
||||
- The global `fetch` called with an init whose `dispatcher` is an object of this package (an `Agent`, a `ProxyAgent`, an instance of a class that extends `Dispatcher`) sends the request through that dispatcher, with the same limits as the package's own `fetch`. An object that implements `dispatch()` itself is refused: when the program is built if it is written in the init, otherwise where the call runs, with a `NotSupportedError` that says so.
|
||||
- `ProxyAgent` dials the proxy once for each tunnel instead of through a pooled client, doesn't take `clientFactory`, and isn't declared for 7.x or 8.x. Of `requestTls` it applies `servername`, `rejectUnauthorized` and `ca`, of `proxyTls` those and `timeout`, `maxCachedSessions` and `lookup`; another member of either, and a `host`, `content-length` or `connection` header for the tunnel, throws a `NotSupportedError` when the agent is made. It doesn't read `HTTP_PROXY` or its relatives, as in undici: the program passes the proxy.
|
||||
- Request bodies are strings and bytes; stream, iterable and form-data bodies, `pipelining` above 1, `CONNECT` requests and Unix socket paths aren't supported.
|
||||
- `ProxyAgent` dials the proxy once for each tunnel instead of through a pooled client and doesn't take `clientFactory`. Of `requestTls` it applies `servername`, `rejectUnauthorized` and `ca`, of `proxyTls` those and `timeout`, `maxCachedSessions` and `lookup`; another member of either, and a `host`, `content-length` or `connection` header for the tunnel, throws a `NotSupportedError` when the agent is made. A `ProxyAgent` doesn't read `HTTP_PROXY` or its relatives, as in undici: the program passes the proxy to it, or uses `EnvHttpProxyAgent`, which reads the environment again on every request when it was not given `noProxy`.
|
||||
- Request bodies are strings, bytes and async iterables (a `node:stream` `Readable`, an async generator, or anything else with `[Symbol.asyncIterator]`); a streamed body is written with chunked transfer encoding unless the request declares its `content-length`, in which case the stream must write exactly that many bytes (more or fewer fails the request with `RequestContentLengthMismatchError` and destroys the connection). `Blob` and `FormData` bodies, `pipelining` above 1, `CONNECT` requests and Unix socket paths aren't supported.
|
||||
|
||||
`fs-extra` 8.x through 11.x is built in, and its declarations replace `@types/fs-extra`. The default import, a namespace import and named imports all read the same exports. fs's members are re-exported, and fs-extra's wrapped methods follow its rule: with a callback as the last argument they call back, otherwise they return a promise. The extra methods cover `copy`, `copySync`, `move`, `moveSync`, `remove`, `removeSync`, `emptyDir`, `ensureDir`, `mkdirs`, `mkdirp`, `ensureFile`, `pathExists`, `outputFile`, `readJson`, `readJsonSync`, `writeJson`, `writeJsonSync`, `outputJson` and their aliases, with fs-extra's error messages. Known differences:
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ A worker's uncaught exception reaches its `error` listeners as Node's error seri
|
||||
An unhandled rejection whose reason is not error-like arrives as an `UnhandledPromiseRejection` Error with code `ERR_UNHANDLED_REJECTION` quoting the reason.
|
||||
A thrown value that does not clone, such as a function, arrives as an `ERR_WORKER_UNSERIALIZABLE_ERROR` Error, where Node sends its `util.inspect` string.
|
||||
`new MessageChannel()` from `node:worker_threads` makes two entangled MessagePorts, in one thread or across threads once a port is transferred, with `receiveMessageOnPort`.
|
||||
A closed port still hands out its queue to `receiveMessageOnPort`: the messages queued before the close, then any the other side posts afterwards, until the queue is empty; a transferred port answers `undefined`, as in Node.
|
||||
The `MessageChannel` global constructs the channel `new MessageChannel()` builds, so `new` through a stored value (`const Channel = MessageChannel; new Channel()`) builds one too.
|
||||
Port messages arrive in Node's order: each port's queued messages as one batch before `setImmediate` callbacks, a port's own `'close'` after the poll phase, and the other port's `'close'` after its queued messages while the loop keeps running.
|
||||
A worker's messages to its parent, and the parent's messages in the worker, also arrive as one batch before `setImmediate` callbacks, each followed by its microtasks, as in Node: the messages queued when delivery starts, and those that arrive meanwhile until the batch holds 1000.
|
||||
|
||||
@@ -14792,9 +14792,9 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "not-implemented",
|
||||
"detail": "No static compiler lowering is registered for this API yet.",
|
||||
"verification": "registry-gap"
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -14815,9 +14815,9 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "not-implemented",
|
||||
"detail": "No static compiler lowering is registered for this API yet.",
|
||||
"verification": "registry-gap"
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -14838,9 +14838,9 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "not-implemented",
|
||||
"detail": "No static compiler lowering is registered for this API yet.",
|
||||
"verification": "registry-gap"
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -26738,8 +26738,8 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"detail": "Implemented for the call shapes accepted by the compiler lowering.",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
@@ -26761,8 +26761,8 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"detail": "Implemented for the call shapes accepted by the compiler lowering.",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
@@ -26784,8 +26784,8 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"detail": "Implemented for the call shapes accepted by the compiler lowering.",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
@@ -26807,8 +26807,8 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"detail": "Implemented for the call shapes accepted by the compiler lowering.",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
@@ -26830,8 +26830,8 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"detail": "Implemented for the call shapes accepted by the compiler lowering.",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
@@ -26922,8 +26922,8 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"detail": "Implemented for the call shapes accepted by the compiler lowering.",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
@@ -26945,8 +26945,8 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"detail": "Implemented for the call shapes accepted by the compiler lowering.",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
@@ -26968,8 +26968,8 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"detail": "Implemented for the call shapes accepted by the compiler lowering.",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
@@ -26991,7 +26991,7 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
@@ -27014,8 +27014,8 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"detail": "Implemented for the call shapes accepted by the compiler lowering.",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
@@ -27037,8 +27037,8 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"detail": "Implemented for the call shapes accepted by the compiler lowering.",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
@@ -27083,8 +27083,8 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"detail": "Implemented for the call shapes accepted by the compiler lowering.",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
@@ -27106,8 +27106,8 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"detail": "Implemented for the call shapes accepted by the compiler lowering.",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
@@ -27129,7 +27129,7 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
@@ -27152,8 +27152,8 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"detail": "Implemented for the call shapes accepted by the compiler lowering.",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
@@ -27175,8 +27175,8 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"detail": "Implemented for the call shapes accepted by the compiler lowering.",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
@@ -27221,8 +27221,8 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"detail": "Implemented for the call shapes accepted by the compiler lowering.",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
@@ -27244,8 +27244,8 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"detail": "Implemented for the call shapes accepted by the compiler lowering.",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
@@ -27267,8 +27267,8 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"detail": "Implemented for the call shapes accepted by the compiler lowering.",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
@@ -27290,8 +27290,8 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"detail": "Implemented for the call shapes accepted by the compiler lowering.",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
@@ -27313,8 +27313,8 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"detail": "Reads filesystem capacity using string, Buffer, or file URL paths with number or BigInt fields and deferred callbacks; StatFs prototype behavior and complete filesystem error metadata remain unsupported.",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
@@ -27336,8 +27336,8 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"detail": "Implemented for the call shapes accepted by the compiler lowering.",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
@@ -27359,8 +27359,8 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"detail": "Implemented for the call shapes accepted by the compiler lowering.",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
@@ -27382,8 +27382,8 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"detail": "Implemented for the call shapes accepted by the compiler lowering.",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
@@ -27405,8 +27405,8 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"detail": "Implemented for the call shapes accepted by the compiler lowering.",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
@@ -27451,8 +27451,8 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"detail": "Implemented for the call shapes accepted by the compiler lowering.",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
@@ -28118,7 +28118,7 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
@@ -28141,7 +28141,7 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
@@ -28164,7 +28164,7 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
@@ -28279,7 +28279,7 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
@@ -28302,7 +28302,7 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
@@ -28601,7 +28601,7 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
@@ -28624,7 +28624,7 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
@@ -28647,7 +28647,7 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
@@ -29429,8 +29429,8 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"detail": "Implemented for the call shapes accepted by the compiler lowering.",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
@@ -29452,8 +29452,8 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"detail": "Implemented for the call shapes accepted by the compiler lowering.",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
@@ -30602,7 +30602,7 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
@@ -30625,7 +30625,7 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
@@ -30648,7 +30648,7 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
@@ -32304,7 +32304,7 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
@@ -32327,7 +32327,7 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
@@ -32350,7 +32350,7 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
@@ -44732,9 +44732,9 @@
|
||||
"inherited": false
|
||||
},
|
||||
"static": {
|
||||
"status": "not-implemented",
|
||||
"detail": "No static compiler lowering is registered for this API yet.",
|
||||
"verification": "registry-gap"
|
||||
"status": "partial",
|
||||
"detail": "Implemented for the documented scriptc module-loader subset.",
|
||||
"verification": "test-backed"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@@ -30661,7 +30661,8 @@
|
||||
"tests/corpus/diagnostics-channel-console-instance.cjs",
|
||||
"tests/corpus/diagnostics-channel-console.cjs",
|
||||
"tests/corpus/diagnostics-channel-store-mutation.cjs",
|
||||
"tests/corpus/diagnostics-channel-store-order.cjs"
|
||||
"tests/corpus/diagnostics-channel-store-order.cjs",
|
||||
"tests/corpus/http-server-diagnostics-channels.ts"
|
||||
]
|
||||
},
|
||||
"anchorSource": "chapter"
|
||||
@@ -31375,8 +31376,11 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "not-implemented",
|
||||
"evidence": "compiler-unmatched:diagnostics_channel"
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:diagnostics_channel.'http.server.request.start'",
|
||||
"tests": [
|
||||
"tests/corpus/http-server-diagnostics-channels.ts"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
},
|
||||
@@ -31398,8 +31402,11 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "not-implemented",
|
||||
"evidence": "compiler-unmatched:diagnostics_channel"
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:diagnostics_channel.'http.server.response.created'",
|
||||
"tests": [
|
||||
"tests/corpus/http-server-diagnostics-channels.ts"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
},
|
||||
@@ -31421,8 +31428,11 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "not-implemented",
|
||||
"evidence": "compiler-unmatched:diagnostics_channel"
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:diagnostics_channel.'http.server.response.finish'",
|
||||
"tests": [
|
||||
"tests/corpus/http-server-diagnostics-channels.ts"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
},
|
||||
@@ -47562,10 +47572,8 @@
|
||||
"tests/corpus/5450-fs-glob-validation.js",
|
||||
"tests/corpus/5451-fs-promises-glob.ts",
|
||||
"tests/corpus/5452-fs-glob-callback.ts",
|
||||
"tests/corpus/5540-fs-callback-forms.cjs",
|
||||
"tests/corpus/5541-fs-stats-fields.cjs",
|
||||
"tests/corpus/5542-fs-promises-parity.cjs",
|
||||
"tests/corpus/5543-fs-promises-typed.ts",
|
||||
"tests/corpus/5544-fs-opendir.cjs",
|
||||
"tests/corpus/5545-fs-options-encoding.cjs",
|
||||
"tests/corpus/5546-fs-read-stream.cjs",
|
||||
@@ -47607,7 +47615,6 @@
|
||||
"tests/corpus/fs-lchmod.cjs",
|
||||
"tests/corpus/fs-links-times.cjs",
|
||||
"tests/corpus/fs-mkdtemp-disposable.ts",
|
||||
"tests/corpus/fs-native-realpath.ts",
|
||||
"tests/corpus/fs-open-as-blob.ts",
|
||||
"tests/corpus/fs-opendir-buffer-size-uncaught.cjs",
|
||||
"tests/corpus/fs-opendir-callbacks.ts",
|
||||
@@ -47617,9 +47624,11 @@
|
||||
"tests/corpus/fs-promises-watch.ts",
|
||||
"tests/corpus/fs-read-file-sync-option-errors.cjs",
|
||||
"tests/corpus/fs-read-file-sync-options-typed.ts",
|
||||
"tests/corpus/fs-read-write-overloads.cjs",
|
||||
"tests/corpus/fs-readdir-callback-options.ts",
|
||||
"tests/corpus/fs-readdir-encodings.ts",
|
||||
"tests/corpus/fs-readdir-recursive-types.ts",
|
||||
"tests/corpus/fs-realpath-forms.ts",
|
||||
"tests/corpus/fs-realpath-native-callback.cjs",
|
||||
"tests/corpus/fs-stat-callback-ladder.cjs",
|
||||
"tests/corpus/fs-stat-callback-options.cjs",
|
||||
@@ -47639,12 +47648,14 @@
|
||||
"tests/corpus/fs-write-callback-options.cjs",
|
||||
"tests/corpus/fs-write-options.ts",
|
||||
"tests/corpus/fs-write-stored-options.ts",
|
||||
"tests/corpus/fsp-content-ops.cjs",
|
||||
"tests/corpus/fsp-dir-statfs-ops.cjs",
|
||||
"tests/corpus/fsp-options-forms.cjs",
|
||||
"tests/corpus/fsp-path-ops.cjs",
|
||||
"tests/corpus/node24-fs-callback-numeric-flags.cjs",
|
||||
"tests/corpus/node24-fs-links-callbacks.cjs",
|
||||
"tests/corpus/node24-fs-links-errors.cjs",
|
||||
"tests/corpus/node24-fs-links-options.cjs",
|
||||
"tests/corpus/node24-fs-links-promise-errors.cjs",
|
||||
"tests/corpus/node24-fs-links-promises.ts",
|
||||
"tests/corpus/node24-fs-mkdir-sync.ts",
|
||||
"tests/corpus/node24-fs-modes-sync.ts",
|
||||
"tests/corpus/node24-fs-open-sync.ts",
|
||||
@@ -48585,11 +48596,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"evidence": "surface-manifest:node-builtin.fs.promises.access",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fsPromises.access",
|
||||
"tests": [
|
||||
"tests/corpus/5542-fs-promises-parity.cjs",
|
||||
"tests/corpus/5543-fs-promises-typed.ts"
|
||||
"tests/corpus/fsp-path-ops.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -48612,11 +48622,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"evidence": "surface-manifest:node-builtin.fs.promises.appendFile",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fsPromises.appendFile",
|
||||
"tests": [
|
||||
"tests/corpus/5542-fs-promises-parity.cjs",
|
||||
"tests/corpus/5543-fs-promises-typed.ts"
|
||||
"tests/corpus/fsp-content-ops.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -48639,21 +48648,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"evidence": "surface-manifest:node-builtin.fs.promises.chmod",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fsPromises.chmod",
|
||||
"tests": [
|
||||
"tests/corpus/1403-buffer-fs.ts",
|
||||
"tests/corpus/2595-fs-arg-ladders.cjs",
|
||||
"tests/corpus/2919-fs-function-values.ts",
|
||||
"tests/corpus/2920-fs-promises-function-values.ts",
|
||||
"tests/corpus/fs-exists-optional-path.ts",
|
||||
"tests/corpus/fs-write-options.ts",
|
||||
"tests/corpus/node24-fs-callback-numeric-flags.cjs",
|
||||
"tests/corpus/node24-fs-mkdir-sync.ts",
|
||||
"tests/corpus/node24-fs-modes-sync.ts",
|
||||
"tests/corpus/node24-fs-open-sync.ts",
|
||||
"tests/corpus/node24-fs-write-modes-sync.ts",
|
||||
"tests/corpus/node24-fs-write-options-flags.ts"
|
||||
"tests/corpus/fsp-path-ops.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -48676,11 +48674,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"evidence": "surface-manifest:node-builtin.fs.promises.chown",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fsPromises.chown",
|
||||
"tests": [
|
||||
"tests/corpus/5542-fs-promises-parity.cjs",
|
||||
"tests/corpus/5543-fs-promises-typed.ts"
|
||||
"tests/corpus/fsp-path-ops.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -48703,12 +48700,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"evidence": "surface-manifest:node-builtin.fs.promises.copyFile",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fsPromises.copyFile",
|
||||
"tests": [
|
||||
"tests/corpus/5542-fs-promises-parity.cjs",
|
||||
"tests/corpus/5543-fs-promises-typed.ts",
|
||||
"tests/corpus/8427-fs-copyfile-writefile-flags.ts"
|
||||
"tests/corpus/fsp-content-ops.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -48819,11 +48814,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"evidence": "surface-manifest:node-builtin.fs.promises.lchown",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fsPromises.lchown",
|
||||
"tests": [
|
||||
"tests/corpus/5542-fs-promises-parity.cjs",
|
||||
"tests/corpus/5543-fs-promises-typed.ts"
|
||||
"tests/corpus/fsp-path-ops.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -48846,11 +48840,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"evidence": "surface-manifest:node-builtin.fs.promises.lutimes",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fsPromises.lutimes",
|
||||
"tests": [
|
||||
"tests/corpus/node24-fs-timestamps-promises.ts",
|
||||
"tests/corpus/node24-fs-timestamps-symlinks.ts"
|
||||
"tests/corpus/fsp-path-ops.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -48873,12 +48866,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"evidence": "surface-manifest:node-builtin.fs.promises.link",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fsPromises.link",
|
||||
"tests": [
|
||||
"tests/corpus/node24-fs-links-promises.ts",
|
||||
"tests/corpus/node24-fs-links-promise-errors.cjs",
|
||||
"tests/fixtures/node-types/fs-links.ts"
|
||||
"tests/corpus/fsp-path-ops.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -48901,10 +48892,11 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fsPromises.lstat",
|
||||
"tests": [
|
||||
"tests/corpus/2941-fsp-lstat-identity.ts"
|
||||
"tests/corpus/2941-fsp-lstat-identity.ts",
|
||||
"tests/corpus/fsp-options-forms.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -48927,21 +48919,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"evidence": "surface-manifest:node-builtin.fs.promises.mkdir",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fsPromises.mkdir",
|
||||
"tests": [
|
||||
"tests/corpus/1403-buffer-fs.ts",
|
||||
"tests/corpus/2595-fs-arg-ladders.cjs",
|
||||
"tests/corpus/2919-fs-function-values.ts",
|
||||
"tests/corpus/2920-fs-promises-function-values.ts",
|
||||
"tests/corpus/fs-exists-optional-path.ts",
|
||||
"tests/corpus/fs-write-options.ts",
|
||||
"tests/corpus/node24-fs-callback-numeric-flags.cjs",
|
||||
"tests/corpus/node24-fs-mkdir-sync.ts",
|
||||
"tests/corpus/node24-fs-modes-sync.ts",
|
||||
"tests/corpus/node24-fs-open-sync.ts",
|
||||
"tests/corpus/node24-fs-write-modes-sync.ts",
|
||||
"tests/corpus/node24-fs-write-options-flags.ts"
|
||||
"tests/corpus/fsp-options-forms.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -48964,11 +48945,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"evidence": "surface-manifest:node-builtin.fs.promises.mkdtemp",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fsPromises.mkdtemp",
|
||||
"tests": [
|
||||
"tests/corpus/5542-fs-promises-parity.cjs",
|
||||
"tests/corpus/5543-fs-promises-typed.ts"
|
||||
"tests/corpus/fsp-options-forms.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -49017,21 +48997,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"evidence": "surface-manifest:node-builtin.fs.promises.open",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fsPromises.open",
|
||||
"tests": [
|
||||
"tests/corpus/1403-buffer-fs.ts",
|
||||
"tests/corpus/2595-fs-arg-ladders.cjs",
|
||||
"tests/corpus/2919-fs-function-values.ts",
|
||||
"tests/corpus/2920-fs-promises-function-values.ts",
|
||||
"tests/corpus/fs-exists-optional-path.ts",
|
||||
"tests/corpus/fs-write-options.ts",
|
||||
"tests/corpus/node24-fs-callback-numeric-flags.cjs",
|
||||
"tests/corpus/node24-fs-mkdir-sync.ts",
|
||||
"tests/corpus/node24-fs-modes-sync.ts",
|
||||
"tests/corpus/node24-fs-open-sync.ts",
|
||||
"tests/corpus/node24-fs-write-modes-sync.ts",
|
||||
"tests/corpus/node24-fs-write-options-flags.ts"
|
||||
"tests/corpus/fsp-options-forms.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -49054,10 +49023,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"evidence": "surface-manifest:node-builtin.fs.promises.opendir",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fsPromises.opendir",
|
||||
"tests": [
|
||||
"tests/corpus/5544-fs-opendir.cjs"
|
||||
"tests/corpus/fsp-dir-statfs-ops.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -49080,12 +49049,13 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fsPromises.readdir",
|
||||
"tests": [
|
||||
"tests/corpus/2942-fsp-readdir-dirent.ts",
|
||||
"tests/corpus/fs-readdir-encodings.ts",
|
||||
"tests/corpus/fs-readdir-recursive-types.ts"
|
||||
"tests/corpus/fs-readdir-recursive-types.ts",
|
||||
"tests/corpus/fsp-options-forms.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -49108,21 +49078,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"evidence": "surface-manifest:node-builtin.fs.promises.readFile",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fsPromises.readFile",
|
||||
"tests": [
|
||||
"tests/corpus/1403-buffer-fs.ts",
|
||||
"tests/corpus/2595-fs-arg-ladders.cjs",
|
||||
"tests/corpus/2919-fs-function-values.ts",
|
||||
"tests/corpus/2920-fs-promises-function-values.ts",
|
||||
"tests/corpus/fs-exists-optional-path.ts",
|
||||
"tests/corpus/fs-write-options.ts",
|
||||
"tests/corpus/node24-fs-callback-numeric-flags.cjs",
|
||||
"tests/corpus/node24-fs-mkdir-sync.ts",
|
||||
"tests/corpus/node24-fs-modes-sync.ts",
|
||||
"tests/corpus/node24-fs-open-sync.ts",
|
||||
"tests/corpus/node24-fs-write-modes-sync.ts",
|
||||
"tests/corpus/node24-fs-write-options-flags.ts"
|
||||
"tests/corpus/fsp-content-ops.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -49145,13 +49104,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"evidence": "surface-manifest:node-builtin.fs.promises.readlink",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fsPromises.readlink",
|
||||
"tests": [
|
||||
"tests/corpus/node24-fs-links-promises.ts",
|
||||
"tests/corpus/node24-fs-links-options.cjs",
|
||||
"tests/corpus/node24-fs-links-promise-errors.cjs",
|
||||
"tests/fixtures/node-types/fs-links.ts"
|
||||
"tests/corpus/fsp-options-forms.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -49200,21 +49156,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"evidence": "surface-manifest:node-builtin.fs.promises.rename",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fsPromises.rename",
|
||||
"tests": [
|
||||
"tests/corpus/1403-buffer-fs.ts",
|
||||
"tests/corpus/2595-fs-arg-ladders.cjs",
|
||||
"tests/corpus/2919-fs-function-values.ts",
|
||||
"tests/corpus/2920-fs-promises-function-values.ts",
|
||||
"tests/corpus/fs-exists-optional-path.ts",
|
||||
"tests/corpus/fs-write-options.ts",
|
||||
"tests/corpus/node24-fs-callback-numeric-flags.cjs",
|
||||
"tests/corpus/node24-fs-mkdir-sync.ts",
|
||||
"tests/corpus/node24-fs-modes-sync.ts",
|
||||
"tests/corpus/node24-fs-open-sync.ts",
|
||||
"tests/corpus/node24-fs-write-modes-sync.ts",
|
||||
"tests/corpus/node24-fs-write-options-flags.ts"
|
||||
"tests/corpus/fsp-path-ops.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -49237,11 +49182,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"evidence": "surface-manifest:node-builtin.fs.promises.rmdir",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fsPromises.rmdir",
|
||||
"tests": [
|
||||
"tests/corpus/5542-fs-promises-parity.cjs",
|
||||
"tests/corpus/5543-fs-promises-typed.ts"
|
||||
"tests/corpus/fsp-path-ops.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -49264,21 +49208,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"evidence": "surface-manifest:node-builtin.fs.promises.rm",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fsPromises.rm",
|
||||
"tests": [
|
||||
"tests/corpus/1403-buffer-fs.ts",
|
||||
"tests/corpus/2595-fs-arg-ladders.cjs",
|
||||
"tests/corpus/2919-fs-function-values.ts",
|
||||
"tests/corpus/2920-fs-promises-function-values.ts",
|
||||
"tests/corpus/fs-exists-optional-path.ts",
|
||||
"tests/corpus/fs-write-options.ts",
|
||||
"tests/corpus/node24-fs-callback-numeric-flags.cjs",
|
||||
"tests/corpus/node24-fs-mkdir-sync.ts",
|
||||
"tests/corpus/node24-fs-modes-sync.ts",
|
||||
"tests/corpus/node24-fs-open-sync.ts",
|
||||
"tests/corpus/node24-fs-write-modes-sync.ts",
|
||||
"tests/corpus/node24-fs-write-options-flags.ts"
|
||||
"tests/corpus/fsp-options-forms.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -49301,21 +49234,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"evidence": "surface-manifest:node-builtin.fs.promises.stat",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fsPromises.stat",
|
||||
"tests": [
|
||||
"tests/corpus/1403-buffer-fs.ts",
|
||||
"tests/corpus/2595-fs-arg-ladders.cjs",
|
||||
"tests/corpus/2919-fs-function-values.ts",
|
||||
"tests/corpus/2920-fs-promises-function-values.ts",
|
||||
"tests/corpus/fs-exists-optional-path.ts",
|
||||
"tests/corpus/fs-write-options.ts",
|
||||
"tests/corpus/node24-fs-callback-numeric-flags.cjs",
|
||||
"tests/corpus/node24-fs-mkdir-sync.ts",
|
||||
"tests/corpus/node24-fs-modes-sync.ts",
|
||||
"tests/corpus/node24-fs-open-sync.ts",
|
||||
"tests/corpus/node24-fs-write-modes-sync.ts",
|
||||
"tests/corpus/node24-fs-write-options-flags.ts"
|
||||
"tests/corpus/fsp-options-forms.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -49338,13 +49260,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"evidence": "surface-manifest:node-builtin.fs.promises.statfs",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fsPromises.statfs",
|
||||
"tests": [
|
||||
"tests/corpus/node24-fs-statfs.ts",
|
||||
"tests/corpus/node24-fs-statfs-options.cjs",
|
||||
"tests/corpus/node24-fs-statfs-errors.cjs",
|
||||
"tests/fixtures/node-types/fs-statfs.ts"
|
||||
"tests/corpus/fsp-dir-statfs-ops.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -49367,13 +49286,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"evidence": "surface-manifest:node-builtin.fs.promises.symlink",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fsPromises.symlink",
|
||||
"tests": [
|
||||
"tests/corpus/node24-fs-links-promises.ts",
|
||||
"tests/corpus/node24-fs-links-options.cjs",
|
||||
"tests/corpus/node24-fs-links-promise-errors.cjs",
|
||||
"tests/fixtures/node-types/fs-links.ts"
|
||||
"tests/corpus/fsp-path-ops.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -49396,11 +49312,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"evidence": "surface-manifest:node-builtin.fs.promises.truncate",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fsPromises.truncate",
|
||||
"tests": [
|
||||
"tests/corpus/5542-fs-promises-parity.cjs",
|
||||
"tests/corpus/5543-fs-promises-typed.ts"
|
||||
"tests/corpus/fsp-path-ops.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -49423,21 +49338,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"evidence": "surface-manifest:node-builtin.fs.promises.unlink",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fsPromises.unlink",
|
||||
"tests": [
|
||||
"tests/corpus/1403-buffer-fs.ts",
|
||||
"tests/corpus/2595-fs-arg-ladders.cjs",
|
||||
"tests/corpus/2919-fs-function-values.ts",
|
||||
"tests/corpus/2920-fs-promises-function-values.ts",
|
||||
"tests/corpus/fs-exists-optional-path.ts",
|
||||
"tests/corpus/fs-write-options.ts",
|
||||
"tests/corpus/node24-fs-callback-numeric-flags.cjs",
|
||||
"tests/corpus/node24-fs-mkdir-sync.ts",
|
||||
"tests/corpus/node24-fs-modes-sync.ts",
|
||||
"tests/corpus/node24-fs-open-sync.ts",
|
||||
"tests/corpus/node24-fs-write-modes-sync.ts",
|
||||
"tests/corpus/node24-fs-write-options-flags.ts"
|
||||
"tests/corpus/fsp-path-ops.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -49460,10 +49364,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"evidence": "surface-manifest:node-builtin.fs.promises.utimes",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fsPromises.utimes",
|
||||
"tests": [
|
||||
"tests/corpus/node24-fs-timestamps-promises.ts"
|
||||
"tests/corpus/fsp-path-ops.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -49513,14 +49417,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"evidence": "surface-manifest:node-builtin.fs.promises.writeFile",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fsPromises.writeFile",
|
||||
"tests": [
|
||||
"tests/corpus/1403-buffer-fs.ts",
|
||||
"tests/corpus/2595-fs-arg-ladders.cjs",
|
||||
"tests/corpus/2919-fs-function-values.ts",
|
||||
"tests/corpus/2920-fs-promises-function-values.ts",
|
||||
"tests/corpus/8427-fs-copyfile-writefile-flags.ts"
|
||||
"tests/corpus/fsp-content-ops.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -50405,12 +50305,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fs.read",
|
||||
"tests": [
|
||||
"tests/corpus/5548-fs-callback-arguments.cjs",
|
||||
"tests/corpus/5549-fs-callback-option-checks.cjs",
|
||||
"tests/corpus/fs-readdir-callback-options.ts"
|
||||
"tests/corpus/fs-read-write-overloads.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -50433,12 +50331,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fs.read",
|
||||
"tests": [
|
||||
"tests/corpus/5548-fs-callback-arguments.cjs",
|
||||
"tests/corpus/5549-fs-callback-option-checks.cjs",
|
||||
"tests/corpus/fs-readdir-callback-options.ts"
|
||||
"tests/corpus/fs-read-write-overloads.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -50461,12 +50357,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fs.read",
|
||||
"tests": [
|
||||
"tests/corpus/5548-fs-callback-arguments.cjs",
|
||||
"tests/corpus/5549-fs-callback-option-checks.cjs",
|
||||
"tests/corpus/fs-readdir-callback-options.ts"
|
||||
"tests/corpus/fs-read-write-overloads.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -50647,12 +50541,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fs.realpath",
|
||||
"tests": [
|
||||
"tests/corpus/5548-fs-callback-arguments.cjs",
|
||||
"tests/corpus/5549-fs-callback-option-checks.cjs",
|
||||
"tests/corpus/fs-readdir-callback-options.ts"
|
||||
"tests/corpus/fs-realpath-forms.ts"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -50675,10 +50567,11 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fs.realpath.native",
|
||||
"tests": [
|
||||
"tests/corpus/fs-realpath-native-callback.cjs"
|
||||
"tests/corpus/fs-realpath-native-callback.cjs",
|
||||
"tests/corpus/fs-realpath-forms.ts"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -51156,12 +51049,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fs.write",
|
||||
"tests": [
|
||||
"tests/corpus/5548-fs-callback-arguments.cjs",
|
||||
"tests/corpus/5549-fs-callback-option-checks.cjs",
|
||||
"tests/corpus/fs-readdir-callback-options.ts"
|
||||
"tests/corpus/fs-read-write-overloads.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -51184,12 +51075,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fs.write",
|
||||
"tests": [
|
||||
"tests/corpus/5548-fs-callback-arguments.cjs",
|
||||
"tests/corpus/5549-fs-callback-option-checks.cjs",
|
||||
"tests/corpus/fs-readdir-callback-options.ts"
|
||||
"tests/corpus/fs-read-write-overloads.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -51212,10 +51101,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fs.write",
|
||||
"tests": [
|
||||
"tests/corpus/5540-fs-callback-forms.cjs"
|
||||
"tests/corpus/fs-read-write-overloads.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -52287,21 +52176,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"evidence": "surface-manifest:node-builtin.fs.realpathSync",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fs.realpathSync",
|
||||
"tests": [
|
||||
"tests/corpus/1403-buffer-fs.ts",
|
||||
"tests/corpus/2595-fs-arg-ladders.cjs",
|
||||
"tests/corpus/2919-fs-function-values.ts",
|
||||
"tests/corpus/2920-fs-promises-function-values.ts",
|
||||
"tests/corpus/fs-exists-optional-path.ts",
|
||||
"tests/corpus/fs-write-options.ts",
|
||||
"tests/corpus/node24-fs-callback-numeric-flags.cjs",
|
||||
"tests/corpus/node24-fs-mkdir-sync.ts",
|
||||
"tests/corpus/node24-fs-modes-sync.ts",
|
||||
"tests/corpus/node24-fs-open-sync.ts",
|
||||
"tests/corpus/node24-fs-write-modes-sync.ts",
|
||||
"tests/corpus/node24-fs-write-options-flags.ts"
|
||||
"tests/corpus/fs-realpath-forms.ts"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -52324,10 +52202,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"evidence": "surface-manifest:node-builtin.fs.realpathSync.native",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.fs.realpathSync.native",
|
||||
"tests": [
|
||||
"tests/corpus/fs-native-realpath.ts"
|
||||
"tests/corpus/fs-realpath-forms.ts"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -53795,12 +53673,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.'close'",
|
||||
"tests": [
|
||||
"tests/corpus/5546-fs-read-stream.cjs",
|
||||
"tests/corpus/5547-fs-write-stream.cjs",
|
||||
"tests/corpus/5554-fs-streams-typed.ts"
|
||||
"tests/corpus/5546-fs-read-stream.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -53823,12 +53699,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.'open'",
|
||||
"tests": [
|
||||
"tests/corpus/5546-fs-read-stream.cjs",
|
||||
"tests/corpus/5547-fs-write-stream.cjs",
|
||||
"tests/corpus/5554-fs-streams-typed.ts"
|
||||
"tests/corpus/5546-fs-read-stream.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -53851,12 +53725,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.'ready'",
|
||||
"tests": [
|
||||
"tests/corpus/5546-fs-read-stream.cjs",
|
||||
"tests/corpus/5547-fs-write-stream.cjs",
|
||||
"tests/corpus/5554-fs-streams-typed.ts"
|
||||
"tests/corpus/5546-fs-read-stream.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -55882,12 +55754,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.'close'",
|
||||
"tests": [
|
||||
"tests/corpus/5546-fs-read-stream.cjs",
|
||||
"tests/corpus/5547-fs-write-stream.cjs",
|
||||
"tests/corpus/5554-fs-streams-typed.ts"
|
||||
"tests/corpus/5547-fs-write-stream.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -55910,12 +55780,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.'open'",
|
||||
"tests": [
|
||||
"tests/corpus/5546-fs-read-stream.cjs",
|
||||
"tests/corpus/5547-fs-write-stream.cjs",
|
||||
"tests/corpus/5554-fs-streams-typed.ts"
|
||||
"tests/corpus/5547-fs-write-stream.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -55938,12 +55806,10 @@
|
||||
"inherited": true
|
||||
},
|
||||
"static": {
|
||||
"status": "partial",
|
||||
"status": "supported",
|
||||
"evidence": "compiler-feature:fs.'ready'",
|
||||
"tests": [
|
||||
"tests/corpus/5546-fs-read-stream.cjs",
|
||||
"tests/corpus/5547-fs-write-stream.cjs",
|
||||
"tests/corpus/5554-fs-streams-typed.ts"
|
||||
"tests/corpus/5547-fs-write-stream.cjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -75059,6 +74925,7 @@
|
||||
"status": "partial",
|
||||
"evidence": "derived:descendants",
|
||||
"tests": [
|
||||
"packages/compiler/src/frontend/strip-typescript-types.test.ts",
|
||||
"packages/compiler/test/find-package-json.test.ts",
|
||||
"tests/corpus/2631-create-require/main.ts",
|
||||
"tests/corpus/2637-create-require-bare/main.ts",
|
||||
@@ -75078,8 +74945,11 @@
|
||||
"tests/corpus/module-source-map-class.ts",
|
||||
"tests/corpus/module-source-maps-values.mjs",
|
||||
"tests/corpus/module-source-maps.ts",
|
||||
"tests/corpus/module-strip-types-options-chain/main.cjs",
|
||||
"tests/corpus/module-strip-typescript-types/main.cjs",
|
||||
"tests/harness/module-compile-cache.test.ts",
|
||||
"tests/harness/module-source-maps.test.ts",
|
||||
"tests/harness/module-strip-types-warning.test.ts",
|
||||
"tests/harness/npm-static.test.ts"
|
||||
]
|
||||
},
|
||||
@@ -75244,8 +75114,14 @@
|
||||
"inherited": false
|
||||
},
|
||||
"static": {
|
||||
"status": "not-implemented",
|
||||
"evidence": "compiler-unmatched:module"
|
||||
"status": "partial",
|
||||
"evidence": "compiler-feature:module.module.stripTypeScriptTypes",
|
||||
"tests": [
|
||||
"tests/corpus/module-strip-typescript-types/main.cjs",
|
||||
"tests/corpus/module-strip-types-options-chain/main.cjs",
|
||||
"packages/compiler/src/frontend/strip-typescript-types.test.ts",
|
||||
"tests/harness/module-strip-types-warning.test.ts"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
},
|
||||
@@ -126016,6 +125892,7 @@
|
||||
"tests/corpus/5990-worker-uncloneable.mjs",
|
||||
"tests/corpus/5991-worker-async-dispose.mjs",
|
||||
"tests/corpus/broadcast-channel-messageerror.ts",
|
||||
"tests/corpus/broadcast-channel-receive-message.mjs",
|
||||
"tests/corpus/native-worker-clone-errors.ts",
|
||||
"tests/corpus/native-worker-commonjs.cjs",
|
||||
"tests/corpus/native-worker-delayed-messages.ts",
|
||||
@@ -126034,15 +125911,19 @@
|
||||
"tests/corpus/native-worker-terminate-wait.ts",
|
||||
"tests/corpus/port-add-listener-order.mjs",
|
||||
"tests/corpus/port-clone-error-text.mjs",
|
||||
"tests/corpus/port-close-argument.mjs",
|
||||
"tests/corpus/port-event-name-coercion.mjs",
|
||||
"tests/corpus/port-handler-attribute.mjs",
|
||||
"tests/corpus/port-listener-bookkeeping.mjs",
|
||||
"tests/corpus/port-listener-order-cycle.mjs",
|
||||
"tests/corpus/port-listeners-typed.ts",
|
||||
"tests/corpus/port-post-closed-cross-thread-bound.mjs",
|
||||
"tests/corpus/port-post-closed-queue-bound.mjs",
|
||||
"tests/corpus/port-post-message-return.mjs",
|
||||
"tests/corpus/port-post-message-void-result.ts",
|
||||
"tests/corpus/port-post-message-void-value.mjs",
|
||||
"tests/corpus/port-post-self-warning.mjs",
|
||||
"tests/corpus/port-receive-closed.mjs",
|
||||
"tests/corpus/port-transfer-detached.mjs",
|
||||
"tests/corpus/worker-cpu-usage-quiet/main.ts",
|
||||
"tests/corpus/worker-cpu-usage.ts",
|
||||
@@ -126052,6 +125933,7 @@
|
||||
"tests/corpus/worker-messageerror-events.ts",
|
||||
"tests/corpus/worker-messageerror-surface.ts",
|
||||
"tests/corpus/worker-performance.ts",
|
||||
"tests/corpus/worker-receive-closed-parent-port.mjs",
|
||||
"tests/corpus/worker-resource-limits-echo.ts",
|
||||
"tests/corpus/worker-share-env.ts"
|
||||
]
|
||||
@@ -126354,7 +126236,10 @@
|
||||
"tests/corpus/5793-worker-message-channel.ts",
|
||||
"tests/corpus/5796-worker-message-channel.cjs",
|
||||
"tests/corpus/5797-worker-message-port-transfer.ts",
|
||||
"tests/corpus/5805-worker-receive-message-parent-port.ts"
|
||||
"tests/corpus/5805-worker-receive-message-parent-port.ts",
|
||||
"tests/corpus/port-receive-closed.mjs",
|
||||
"tests/corpus/worker-receive-closed-parent-port.mjs",
|
||||
"tests/corpus/broadcast-channel-receive-message.mjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -126414,7 +126299,8 @@
|
||||
"status": "partial",
|
||||
"evidence": "compiler-feature:worker_threads.port.close",
|
||||
"tests": [
|
||||
"tests/corpus/native-worker-port-lifetime.ts"
|
||||
"tests/corpus/native-worker-port-lifetime.ts",
|
||||
"tests/corpus/port-close-argument.mjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -126449,7 +126335,9 @@
|
||||
"tests/corpus/port-post-self-warning.mjs",
|
||||
"tests/corpus/port-clone-error-text.mjs",
|
||||
"tests/corpus/port-post-message-void-result.ts",
|
||||
"tests/corpus/port-post-message-void-value.mjs"
|
||||
"tests/corpus/port-post-message-void-value.mjs",
|
||||
"tests/corpus/port-post-closed-queue-bound.mjs",
|
||||
"tests/corpus/port-post-closed-cross-thread-bound.mjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -126521,7 +126409,8 @@
|
||||
"status": "partial",
|
||||
"evidence": "compiler-feature:worker_threads.port.hasRef",
|
||||
"tests": [
|
||||
"tests/corpus/native-worker-port-lifetime.ts"
|
||||
"tests/corpus/native-worker-port-lifetime.ts",
|
||||
"tests/corpus/port-close-argument.mjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -126547,7 +126436,8 @@
|
||||
"status": "partial",
|
||||
"evidence": "compiler-feature:worker_threads.port.ref",
|
||||
"tests": [
|
||||
"tests/corpus/native-worker-port-lifetime.ts"
|
||||
"tests/corpus/native-worker-port-lifetime.ts",
|
||||
"tests/corpus/port-close-argument.mjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -126573,7 +126463,8 @@
|
||||
"status": "partial",
|
||||
"evidence": "compiler-feature:worker_threads.port.start",
|
||||
"tests": [
|
||||
"tests/corpus/native-worker-port-lifetime.ts"
|
||||
"tests/corpus/native-worker-port-lifetime.ts",
|
||||
"tests/corpus/port-close-argument.mjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -126599,7 +126490,8 @@
|
||||
"status": "partial",
|
||||
"evidence": "compiler-feature:worker_threads.port.unref",
|
||||
"tests": [
|
||||
"tests/corpus/native-worker-port-lifetime.ts"
|
||||
"tests/corpus/native-worker-port-lifetime.ts",
|
||||
"tests/corpus/port-close-argument.mjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -126826,7 +126718,9 @@
|
||||
"tests/corpus/port-post-self-warning.mjs",
|
||||
"tests/corpus/port-clone-error-text.mjs",
|
||||
"tests/corpus/port-post-message-void-result.ts",
|
||||
"tests/corpus/port-post-message-void-value.mjs"
|
||||
"tests/corpus/port-post-message-void-value.mjs",
|
||||
"tests/corpus/port-post-closed-queue-bound.mjs",
|
||||
"tests/corpus/port-post-closed-cross-thread-bound.mjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
@@ -127540,7 +127434,10 @@
|
||||
"tests/corpus/5793-worker-message-channel.ts",
|
||||
"tests/corpus/5796-worker-message-channel.cjs",
|
||||
"tests/corpus/5797-worker-message-port-transfer.ts",
|
||||
"tests/corpus/5805-worker-receive-message-parent-port.ts"
|
||||
"tests/corpus/5805-worker-receive-message-parent-port.ts",
|
||||
"tests/corpus/port-receive-closed.mjs",
|
||||
"tests/corpus/worker-receive-closed-parent-port.mjs",
|
||||
"tests/corpus/broadcast-channel-receive-message.mjs"
|
||||
]
|
||||
},
|
||||
"anchorSource": "exact"
|
||||
|
||||
@@ -6,5 +6,6 @@
|
||||
{ "chapter": "diagnostics_channel", "symbols": ["channel.bindStore", "channel.unbindStore", "channel.runStores"], "status": "partial", "evidence": ["tests/corpus/2214-dc-bind-store.cjs", "tests/corpus/diagnostics-channel-store-order.cjs", "tests/corpus/diagnostics-channel-store-mutation.cjs", "tests/corpus/diagnostics-channel-audit.cjs"], "reason": "The bound store must be an AsyncLocalStorage instance (the lowering keys bindings by its handle); Node keys a binding by any value the program passes." },
|
||||
{ "chapter": "diagnostics_channel", "signatures": ["`start(event)`", "`end(event)`", "`asyncStart(event)`", "`asyncEnd(event)`", "`error(event)`"], "status": "supported", "evidence": ["tests/corpus/2160-dc-tracing-channel.cjs", "tests/corpus/2211-dc-trace-promise.cjs", "tests/corpus/diagnostics-channel-audit.cjs"] },
|
||||
{ "chapter": "diagnostics_channel", "signatures": ["Event: `'console.log'`", "Event: `'console.info'`", "Event: `'console.debug'`", "Event: `'console.warn'`", "Event: `'console.error'`"], "status": "supported", "evidence": ["tests/corpus/diagnostics-channel-console.cjs", "tests/corpus/diagnostics-channel-console-instance.cjs"], "reason": "A call to a global console output member, a Console instance's output method, the console object called as a value and a method held as a separate function value publish the call's own argument array on the matching channel before the line is written, when the channel has subscribers; every argument type crosses, including a spread's elements, because node:console's output is util.format over that same array." },
|
||||
{ "chapter": "diagnostics_channel", "signatures": ["Event: `'tracing:module.require:start'`", "Event: `'tracing:module.require:end'`", "Event: `'tracing:module.require:error'`", "Event: `'tracing:module.import:asyncStart'`", "Event: `'tracing:module.import:asyncEnd'`", "Event: `'tracing:module.import:error'`"], "status": "not-implemented", "reason": "Node emits these around each CommonJS require() and ESM import() call from its module loaders. A compiled program resolves statically linked modules at compile time: there is no per-call load at run time to trace, and emitting the events would mean instrumenting every require and import site in the module lowering, with the loader's id and parentFilename context. That is module-loader work, not diagnostics_channel work." }
|
||||
{ "chapter": "diagnostics_channel", "signatures": ["Event: `'tracing:module.require:start'`", "Event: `'tracing:module.require:end'`", "Event: `'tracing:module.require:error'`", "Event: `'tracing:module.import:asyncStart'`", "Event: `'tracing:module.import:asyncEnd'`", "Event: `'tracing:module.import:error'`"], "status": "not-implemented", "reason": "Node emits these around each CommonJS require() and ESM import() call from its module loaders. A compiled program resolves statically linked modules at compile time: there is no per-call load at run time to trace, and emitting the events would mean instrumenting every require and import site in the module lowering, with the loader's id and parentFilename context. That is module-loader work, not diagnostics_channel work." },
|
||||
{ "chapter": "diagnostics_channel", "signatures": ["Event: `'http.server.request.start'`", "Event: `'http.server.response.created'`", "Event: `'http.server.response.finish'`"], "status": "supported", "evidence": ["tests/corpus/http-server-diagnostics-channels.ts"], "reason": "An HTTP/1 server publishes Node's three server events when the channel has subscribers: {request, response} on response.created as the response is constructed and {request, response, socket, server} on request.start just after it, both before the 'request' listeners and before the maxRequestsPerSocket and Expect decisions (a request the server answers with its own 417 still publishes them), then {request, response, socket, server} on response.finish from the server's own 'finish' listener, ahead of any the program added. request, response, socket and server are the objects the program holds, so they compare equal; CONNECT and Upgrade requests take the socket without a response and publish none, and the HTTP/2 compatibility layer's responses are not ServerResponses in Node and publish none here. The one shape that stays outside: a request the runtime answers itself for a missing Host header is refused at the connection level before a response exists, where Node constructs the response (publishing all three) and then sends its 400." }
|
||||
]
|
||||
|
||||
@@ -5,11 +5,11 @@
|
||||
{ "chapter": "fs", "signatures": ["`fsPromises.mkdtempDisposable(prefix[, options])`"], "status": "supported", "evidence": ["tests/corpus/fs-mkdtemp-disposable.ts"] },
|
||||
{ "chapter": "fs", "signatures": ["`fs.mkdtempDisposableSync(prefix[, options])`"], "status": "supported", "evidence": ["tests/corpus/fs-mkdtemp-disposable.ts"] },
|
||||
{ "chapter": "fs", "signatures": ["`fs.close(fd[, callback])`"], "status": "partial", "evidence": ["tests/corpus/fs-close-callback.cjs"] },
|
||||
{ "chapter": "fs", "signatures": ["`fs.realpath.native(path[, options], callback)`"], "status": "partial", "evidence": ["tests/corpus/fs-realpath-native-callback.cjs"] },
|
||||
{ "chapter": "fs", "signatures": ["`fs.realpath.native(path[, options], callback)`"], "status": "supported", "evidence": ["tests/corpus/fs-realpath-native-callback.cjs", "tests/corpus/fs-realpath-forms.ts"] },
|
||||
{ "chapter": "fs", "signatures": ["`fs.stat(path[, options], callback)`", "`fs.lstat(path[, options], callback)`", "`fs.fstat(fd[, options], callback)`"], "status": "supported", "evidence": ["tests/corpus/5548-fs-callback-arguments.cjs", "tests/corpus/5549-fs-callback-option-checks.cjs", "tests/corpus/fs-stat-callback-options.cjs", "tests/corpus/fs-stat-callback-ladder.cjs"] },
|
||||
{ "chapter": "fs", "symbols": ["fs.statSync", "fs.lstatSync", "fs.fstatSync"], "status": "supported", "evidence": ["tests/corpus/fs-stat-sync-ladder.cjs", "tests/corpus/fs-stat-runtime-options.ts", "tests/corpus/5747-fs-stat-throw-if-no-entry.ts", "tests/corpus/5748-fs-stat-throw-if-no-entry-js.cjs", "tests/corpus/2950-fs-descriptor-publication.ts"] },
|
||||
{ "chapter": "fs", "signatures": ["`fs.writeFile(file, data[, options], callback)`", "`fs.appendFile(path, data[, options], callback)`"], "status": "supported", "evidence": ["tests/corpus/fs-write-callback-options.cjs", "tests/corpus/5548-fs-callback-arguments.cjs"] },
|
||||
{ "chapter": "fs", "signatures": ["`fs.appendFile(path, data[, options], callback)`", "`fs.chmod(path, mode, callback)`", "`fs.close(fd[, callback])`", "`fs.copyFile(src, dest[, mode], callback)`", "`fs.fstat(fd[, options], callback)`", "`fs.fsync(fd, callback)`", "`fs.lstat(path[, options], callback)`", "`fs.mkdir(path[, options], callback)`", "`fs.mkdtemp(prefix[, options], callback)`", "`fs.open(path[, flags[, mode]], callback)`", "`fs.read(fd, buffer, offset, length, position, callback)`", "`fs.read(fd[, options], callback)`", "`fs.read(fd, buffer[, options], callback)`", "`fs.readdir(path[, options], callback)`", "`fs.readFile(path[, options], callback)`", "`fs.realpath(path[, options], callback)`", "`fs.realpath.native(path[, options], callback)`", "`fs.rmdir(path[, options], callback)`", "`fs.stat(path[, options], callback)`", "`fs.unlink(path, callback)`", "`fs.write(fd, buffer, offset[, length[, position]], callback)`", "`fs.write(fd, buffer[, options], callback)`", "`fs.writeFile(file, data[, options], callback)`"], "status": "partial", "evidence": ["tests/corpus/5548-fs-callback-arguments.cjs", "tests/corpus/5549-fs-callback-option-checks.cjs", "tests/corpus/fs-readdir-callback-options.ts"] },
|
||||
{ "chapter": "fs", "signatures": ["`fs.appendFile(path, data[, options], callback)`", "`fs.chmod(path, mode, callback)`", "`fs.close(fd[, callback])`", "`fs.copyFile(src, dest[, mode], callback)`", "`fs.fstat(fd[, options], callback)`", "`fs.fsync(fd, callback)`", "`fs.lstat(path[, options], callback)`", "`fs.mkdir(path[, options], callback)`", "`fs.mkdtemp(prefix[, options], callback)`", "`fs.open(path[, flags[, mode]], callback)`", "`fs.readdir(path[, options], callback)`", "`fs.readFile(path[, options], callback)`", "`fs.rmdir(path[, options], callback)`", "`fs.stat(path[, options], callback)`", "`fs.unlink(path, callback)`", "`fs.writeFile(file, data[, options], callback)`"], "status": "partial", "evidence": ["tests/corpus/5548-fs-callback-arguments.cjs", "tests/corpus/5549-fs-callback-option-checks.cjs", "tests/corpus/fs-readdir-callback-options.ts"] },
|
||||
{ "chapter": "fs", "parent": "Class: `FileHandle`", "symbols": ["fd"], "status": "supported", "evidence": ["tests/corpus/2686-fs-file-handle.ts", "tests/corpus/fs-filehandle-controls.ts"] },
|
||||
{ "chapter": "fs", "symbols": ["filehandle.chown"], "status": "supported", "evidence": ["tests/corpus/fs-filehandle-data-options.ts"] },
|
||||
{ "chapter": "fs", "symbols": ["FileHandle", "filehandle.fd", "filehandle.close", "filehandle.read", "filehandle.write", "filehandle.readFile", "filehandle.writeFile", "filehandle.appendFile", "filehandle.stat"], "status": "supported", "evidence": ["tests/corpus/2686-fs-file-handle.ts", "tests/corpus/3136-fs-file-handle-options.ts", "tests/corpus/fs-filehandle-data-options.ts"] },
|
||||
@@ -19,11 +19,16 @@
|
||||
{ "chapter": "fs", "symbols": ["fs.statfs", "fs.statfsSync"], "status": "supported", "evidence": ["tests/corpus/node24-fs-statfs-callbacks.cjs", "tests/corpus/node24-fs-statfs-options.cjs", "tests/corpus/node24-fs-statfs-errors.cjs", "tests/corpus/fs-statfs-family.ts", "tests/fixtures/node-types/fs-statfs.ts"] },
|
||||
{ "chapter": "fs", "symbols": ["fs.StatFs"], "status": "supported", "evidence": ["tests/corpus/node24-fs-statfs.ts", "tests/corpus/node24-fs-statfs-options.cjs", "tests/corpus/fs-statfs-family.ts", "tests/fixtures/node-types/fs-statfs.ts"] },
|
||||
{ "chapter": "fs", "parent": "Class: `fs.StatFs`", "symbols": ["type", "bsize", "blocks", "bfree", "bavail", "files", "ffree"], "status": "supported", "evidence": ["tests/corpus/node24-fs-statfs.ts", "tests/corpus/node24-fs-statfs-options.cjs", "tests/fixtures/node-types/fs-statfs.ts"] },
|
||||
{ "chapter": "fs", "signatures": ["`fs.mkdir(path[, options], callback)`", "`fs.readFile(path[, options], callback)`", "`fs.write(fd, string[, position[, encoding]], callback)`"], "status": "partial", "evidence": ["tests/corpus/5540-fs-callback-forms.cjs"] },
|
||||
{ "chapter": "fs", "signatures": ["`fs.read(fd, buffer, offset, length, position, callback)`", "`fs.read(fd[, options], callback)`", "`fs.read(fd, buffer[, options], callback)`", "`fs.write(fd, buffer, offset[, length[, position]], callback)`", "`fs.write(fd, buffer[, options], callback)`", "`fs.write(fd, string[, position[, encoding]], callback)`"], "status": "supported", "evidence": ["tests/corpus/fs-read-write-overloads.cjs"] },
|
||||
{ "chapter": "fs", "signatures": ["`fs.realpath(path[, options], callback)`", "`fs.realpath.native(path[, options], callback)`", "`fs.realpathSync(path[, options])`", "`fs.realpathSync.native(path[, options])`"], "status": "supported", "evidence": ["tests/corpus/fs-realpath-forms.ts"] },
|
||||
{ "chapter": "fs", "signatures": ["`fsPromises.realpath(path[, options])`"], "status": "partial", "evidence": ["tests/corpus/2940-fsp-realpath.ts"] },
|
||||
{ "chapter": "fs", "signatures": ["`fs.mkdir(path[, options], callback)`", "`fs.readFile(path[, options], callback)`"], "status": "partial", "evidence": ["tests/corpus/5540-fs-callback-forms.cjs"] },
|
||||
{ "chapter": "fs", "signatures": ["`fs.access(path[, mode], callback)`", "`fs.chown(path, uid, gid, callback)`", "`fs.lchown(path, uid, gid, callback)`", "`fs.fchown(fd, uid, gid, callback)`", "`fs.truncate(path[, len], callback)`", "`fs.accessSync(path[, mode])`", "`fs.chownSync(path, uid, gid)`", "`fs.lchownSync(path, uid, gid)`", "`fs.truncateSync(path[, len])`"], "status": "supported", "evidence": ["tests/corpus/5542-fs-promises-parity.cjs", "tests/corpus/fs-permissions-family.cjs", "tests/corpus/fs-access-truncate-optional.ts"] },
|
||||
{ "chapter": "fs", "signatures": ["`fs.createReadStream(path[, options])`", "`fs.createWriteStream(path[, options])`", "Class: `fs.ReadStream`", "Class: `fs.WriteStream`", "`writeStream.close([callback])`", "`writeStream.bytesWritten`", "`writeStream.path`"], "status": "partial", "evidence": ["tests/corpus/5546-fs-read-stream.cjs", "tests/corpus/5547-fs-write-stream.cjs", "tests/corpus/5554-fs-streams-typed.ts", "tests/corpus/9751-fs-read-stream-signal.ts", "tests/corpus/9752-fs-write-stream-signal.ts", "tests/corpus/9754-fs-stream-signal-option-values.ts", "tests/corpus/9755-fs-stream-signal-untyped.cjs"] },
|
||||
{ "chapter": "fs", "parent": "Class: `fs.ReadStream`", "signatures": ["`bytesRead` Type: {number}", "`path` Type: {string|Buffer}", "`pending` Type: {boolean}", "Event: `'close'`", "Event: `'open'`", "Event: `'ready'`"], "status": "partial", "evidence": ["tests/corpus/5546-fs-read-stream.cjs", "tests/corpus/5547-fs-write-stream.cjs", "tests/corpus/5554-fs-streams-typed.ts"] },
|
||||
{ "chapter": "fs", "parent": "Class: `fs.WriteStream`", "signatures": ["`pending` Type: {boolean}", "Event: `'close'`", "Event: `'open'`", "Event: `'ready'`"], "status": "partial", "evidence": ["tests/corpus/5546-fs-read-stream.cjs", "tests/corpus/5547-fs-write-stream.cjs", "tests/corpus/5554-fs-streams-typed.ts"] },
|
||||
{ "chapter": "fs", "parent": "Class: `fs.ReadStream`", "signatures": ["`bytesRead` Type: {number}", "`path` Type: {string|Buffer}", "`pending` Type: {boolean}"], "status": "partial", "evidence": ["tests/corpus/5546-fs-read-stream.cjs", "tests/corpus/5547-fs-write-stream.cjs", "tests/corpus/5554-fs-streams-typed.ts"] },
|
||||
{ "chapter": "fs", "parent": "Class: `fs.WriteStream`", "signatures": ["`pending` Type: {boolean}"], "status": "partial", "evidence": ["tests/corpus/5546-fs-read-stream.cjs", "tests/corpus/5547-fs-write-stream.cjs", "tests/corpus/5554-fs-streams-typed.ts"] },
|
||||
{ "chapter": "fs", "parent": "Class: `fs.ReadStream`", "signatures": ["Event: `'open'`", "Event: `'ready'`", "Event: `'close'`"], "status": "supported", "evidence": ["tests/corpus/5546-fs-read-stream.cjs"] },
|
||||
{ "chapter": "fs", "parent": "Class: `fs.WriteStream`", "signatures": ["Event: `'open'`", "Event: `'ready'`", "Event: `'close'`"], "status": "supported", "evidence": ["tests/corpus/5547-fs-write-stream.cjs"] },
|
||||
{ "chapter": "fs", "signatures": ["`filehandle.createReadStream([options])`", "`filehandle.createWriteStream([options])`", "`filehandle.readLines([options])`"], "status": "supported", "evidence": ["tests/corpus/5554-fs-streams-typed.ts", "tests/corpus/9753-file-handle-stream-signal.ts", "tests/corpus/fs-filehandle-lines.ts"] },
|
||||
{"chapter": "fs", "symbols": ["filehandle.pull", "filehandle.pullSync", "filehandle.writer"], "status": "not-applicable", "reason": "Stability 1 and gated by V8's --experimental-stream-iter: in a default Node 24 process typeof fh.pull, typeof fh.pullSync and typeof fh.writer are all \"undefined\", and a compiled program cannot pass V8 flags."},
|
||||
{"chapter": "fs", "signatures": ["`fs.lchmod(path, mode, callback)`", "`fs.lchmodSync(path, mode)`"], "status": "not-applicable", "reason": "Node exports these only where lchmod(2) exists (macOS): on Linux typeof fs.lchmod and typeof fs.lchmodSync are \"undefined\", and the runtime answers Node's not-a-function TypeError if a program reaches them dynamically. The promise form, which exists on every platform, is fsPromises.lchmod."},
|
||||
@@ -37,7 +42,10 @@
|
||||
{ "chapter": "fs", "signatures": ["`dirent.isFile()`", "`dirent.isDirectory()`", "`dirent.isBlockDevice()`", "`dirent.isCharacterDevice()`", "`dirent.isSymbolicLink()`", "`dirent.isFIFO()`", "`dirent.isSocket()`"], "status": "supported", "evidence": ["tests/corpus/fs-dir-listing.ts", "tests/corpus/1541-fs-readdir-dirent.ts", "tests/corpus/5544-fs-opendir.cjs", "tests/corpus/fs-opendir-callbacks.ts"] },
|
||||
{ "chapter": "fs", "signatures": ["`constants` Type: {Object}"], "status": "supported", "evidence": ["tests/corpus/6207-fs-constants-object.ts", "tests/corpus/6208-fs-constants-require.cjs", "tests/corpus/fs-promises-constants.ts"] },
|
||||
{ "chapter": "fs", "symbols": ["fs.utimes", "fs.futimes", "fs.lutimes", "fs.utimesSync", "fs.lutimesSync"], "status": "supported", "evidence": ["tests/corpus/node24-fs-timestamps-callbacks.cjs", "tests/corpus/node24-fs-timestamps-symlinks.ts", "tests/corpus/node24-fs-timestamps-errors.cjs", "tests/corpus/fs-links-times.cjs"] },
|
||||
{ "chapter": "fs", "signatures": ["`fsPromises.lstat(path[, options])`"], "status": "partial", "evidence": ["tests/corpus/2941-fsp-lstat-identity.ts"] },
|
||||
{ "chapter": "fs", "signatures": ["`fsPromises.access(path[, mode])`", "`fsPromises.chmod(path, mode)`", "`fsPromises.chown(path, uid, gid)`", "`fsPromises.lchown(path, uid, gid)`", "`fsPromises.link(existingPath, newPath)`", "`fsPromises.symlink(target, path[, type])`", "`fsPromises.rename(oldPath, newPath)`", "`fsPromises.truncate(path[, len])`", "`fsPromises.utimes(path, atime, mtime)`", "`fsPromises.lutimes(path, atime, mtime)`", "`fsPromises.unlink(path)`", "`fsPromises.rmdir(path[, options])`"], "status": "supported", "evidence": ["tests/corpus/fsp-path-ops.cjs"] },
|
||||
{ "chapter": "fs", "signatures": ["`fsPromises.appendFile(path, data[, options])`", "`fsPromises.copyFile(src, dest[, mode])`", "`fsPromises.readFile(path[, options])`", "`fsPromises.writeFile(file, data[, options])`"], "status": "supported", "evidence": ["tests/corpus/fsp-content-ops.cjs"] },
|
||||
{ "chapter": "fs", "signatures": ["`fsPromises.opendir(path[, options])`", "`fsPromises.statfs(path[, options])`"], "status": "supported", "evidence": ["tests/corpus/fsp-dir-statfs-ops.cjs"] },
|
||||
{ "chapter": "fs", "signatures": ["`fsPromises.lstat(path[, options])`"], "status": "supported", "evidence": ["tests/corpus/2941-fsp-lstat-identity.ts", "tests/corpus/fsp-options-forms.cjs"] },
|
||||
{ "chapter": "fs", "signatures": ["`fs.globSync(pattern[, options])`", "`fs.glob(pattern[, options], callback)`", "`fsPromises.glob(pattern[, options])`"], "status": "supported", "evidence": ["tests/corpus/5448-fs-glob-patterns.ts", "tests/corpus/5449-fs-glob-options.ts", "tests/corpus/5450-fs-glob-validation.js", "tests/corpus/5451-fs-promises-glob.ts", "tests/corpus/5452-fs-glob-callback.ts", "tests/fixtures/node-types/fs-glob.ts"] },
|
||||
{ "chapter": "fs", "signatures": ["`fs.cpSync(src, dest[, options])`", "`fs.cp(src, dest[, options], callback)`", "`fsPromises.cp(src, dest[, options])`"], "status": "supported", "evidence": ["tests/corpus/5567-fs-cpsync.ts", "tests/corpus/5568-fs-cp-errors.js", "tests/corpus/5569-fs-cp-symlinks.ts", "tests/corpus/5570-fs-cp-async.ts", "tests/corpus/5571-fs-cp-deep.ts"] },
|
||||
{ "chapter": "fs", "symbols": ["fs.Stats", "stats.isBlockDevice", "stats.isCharacterDevice", "stats.isDirectory", "stats.isFIFO", "stats.isFile", "stats.isSocket", "stats.isSymbolicLink"], "status": "supported", "evidence": ["tests/corpus/5541-fs-stats-fields.cjs", "tests/corpus/fs-stat-callback-options.cjs", "tests/corpus/fs-stat-sync-ladder.cjs", "tests/corpus/fs-stat-runtime-options.ts", "tests/corpus/fs-stat-callback-ladder.cjs"] },
|
||||
@@ -45,8 +53,9 @@
|
||||
{ "chapter": "fs", "signatures": ["`dev` Type: {number|bigint}", "`ino` Type: {number|bigint}", "`ctimeMs` Type: {number|bigint}"], "status": "supported", "evidence": ["tests/corpus/fs-stats-fields.ts", "tests/corpus/fs-stats-bigint-fields.ts", "tests/corpus/fs-stats-member-tables.cjs", "tests/corpus/2941-fsp-lstat-identity.ts"] },
|
||||
{ "chapter": "fs", "signatures": ["`filehandle.readableWebStream([options])`"], "status": "supported", "evidence": ["tests/corpus/fs-filehandle-web-stream.ts"] },
|
||||
{ "chapter": "fs", "signatures": ["`filehandle[Symbol.asyncDispose]()`"], "status": "supported", "evidence": ["tests/corpus/2844-node-disposable-resources.ts", "tests/corpus/fs-filehandle-lines.ts"] },
|
||||
{ "chapter": "fs", "signatures": ["`fsPromises.realpath(path[, options])`"], "status": "partial", "evidence": ["tests/corpus/2940-fsp-realpath.ts"] },
|
||||
{ "chapter": "fs", "signatures": ["`fsPromises.readdir(path[, options])`"], "status": "partial", "evidence": ["tests/corpus/2942-fsp-readdir-dirent.ts", "tests/corpus/fs-readdir-encodings.ts", "tests/corpus/fs-readdir-recursive-types.ts"] },
|
||||
{ "chapter": "fs", "signatures": [], "status": "partial", "evidence": ["tests/corpus/2940-fsp-realpath.ts"] },
|
||||
{ "chapter": "fs", "signatures": ["`fsPromises.stat(path[, options])`", "`fsPromises.lstat(path[, options])`", "`fsPromises.readlink(path[, options])`", "`fsPromises.mkdir(path[, options])`", "`fsPromises.mkdtemp(prefix[, options])`", "`fsPromises.open(path, flags[, mode])`", "`fsPromises.rm(path[, options])`"], "status": "supported", "evidence": ["tests/corpus/fsp-options-forms.cjs"] },
|
||||
{ "chapter": "fs", "signatures": ["`fsPromises.readdir(path[, options])`"], "status": "supported", "evidence": ["tests/corpus/2942-fsp-readdir-dirent.ts", "tests/corpus/fs-readdir-encodings.ts", "tests/corpus/fs-readdir-recursive-types.ts", "tests/corpus/fsp-options-forms.cjs"] },
|
||||
{ "chapter": "fs", "signatures": ["`fsPromises.watch(filename[, options])`"], "status": "partial", "evidence": ["tests/corpus/fs-promises-watch.ts", "tests/corpus/fs-promises-watch-overflow.cjs"], "fences": ["recursive: true (Node's non-native recursive walker)", "options.signal (AbortSignal)", "options.ignore (a matcher over entry names)", "a non-utf8 encoding, and the iterator outside a `for await`"] },
|
||||
{ "chapter": "fs", "parent": "Common Objects", "signatures": ["Class: `fs.Dirent`"], "status": "partial", "evidence": ["tests/corpus/compat-fs-dirent-realpath.ts"] },
|
||||
{ "chapter": "fs", "parent": "Class: `fs.Dirent`", "signatures": ["`name` Type: {string|Buffer}", "`parentPath` Type: {string}"], "status": "partial", "evidence": ["tests/corpus/compat-fs-dirent-realpath.ts"] },
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
[
|
||||
{ "chapter": "module", "symbols": ["module.createRequire"], "status": "partial", "evidence": ["tests/corpus/2631-create-require/main.ts", "tests/corpus/2637-create-require-bare/main.ts", "tests/corpus/2675-create-require-nested-esm.js", "tests/corpus/2932-create-require-program/main.ts", "tests/harness/npm-static.test.ts", "tests/corpus/module-create-require-args/main.cjs", "tests/corpus/module-create-require-shapes/main.cjs"], "reason": "createRequire(<filename>) accepts Node's argument shapes — a file URL object, a file URL string or an absolute path string — and answers Node's TypeError with ERR_INVALID_ARG_VALUE for every other statically known shape where the factory call stands, in every call shape: a const binding over the run-time loader, a chained createRequire(base)(id) call, and a destructured factory binding. A value whose printed form the check does not reproduce — a bigint, a symbol, a string util.inspect would escape — keeps the run-time fence. The loader's own require calls lower statically: a string-literal specifier resolves at build time (builtins, JSON documents, program modules); a runtime-computed specifier or base is refused."},
|
||||
{ "chapter": "module", "symbols": ["module.createRequire"], "status": "partial", "evidence": ["tests/corpus/2631-create-require/main.ts", "tests/corpus/2637-create-require-bare/main.ts", "tests/corpus/2675-create-require-nested-esm.js", "tests/corpus/2932-create-require-program/main.ts", "tests/harness/npm-static.test.ts", "tests/corpus/module-create-require-args/main.cjs", "tests/corpus/module-create-require-shapes/main.cjs"], "reason": "createRequire(<filename>) accepts Node's argument shapes — a file URL object, a file URL string or an absolute path string — and answers Node's TypeError with ERR_INVALID_ARG_VALUE for every other statically known shape where the factory call stands, in every call shape: a const binding over the run-time loader, a chained createRequire(base)(id) call, and a destructured factory binding. A value whose printed form the check does not reproduce — a bigint, a symbol, a string util.inspect would escape — keeps the run-time fence. The loader's own require calls lower statically: a string-literal specifier resolves at build time (builtins, JSON documents, program modules); a runtime-computed specifier or base is refused." },
|
||||
{ "chapter": "module", "symbols": ["module.findPackageJSON"], "status": "partial", "evidence": ["tests/corpus/module-find-package-json/main.ts", "packages/compiler/test/find-package-json.test.ts"], "reason": "The lookup is resolved at build time for a string-literal specifier and a static base (import.meta.url, __filename, or a path or file: URL literal): a bare specifier answers its package's root package.json through a self-reference or the node_modules chain, and a relative or absolute specifier answers the nearest package.json after the same URL resolution Node's default resolver performs, including its trailing-separator rule for directories. A runtime-computed specifier or base is refused, and a lookup Node would reject (a missing package or file, an invalid package name, a non-file URL) keeps a named refusal." },
|
||||
{ "chapter": "module", "symbols": ["module.isBuiltin", "module.syncBuiltinESMExports"], "status": "supported", "evidence": ["tests/corpus/2932-create-require-program/main.ts", "tests/corpus/5846-events-esm-default-max.ts", "tests/corpus/module-function-values/main.ts"] },
|
||||
{ "chapter": "module", "symbols": ["module.enableCompileCache", "module.getCompileCacheDir", "module.flushCompileCache"], "status": "partial", "evidence": ["tests/corpus/module-compile-cache-disabled.ts", "tests/corpus/module-compile-cache-values.mjs", "tests/corpus/module-compile-cache-require.cjs", "tests/corpus/module-compile-cache-entry.mjs", "tests/harness/module-compile-cache.test.ts"] },
|
||||
@@ -11,5 +11,6 @@
|
||||
{ "chapter": "module", "parent": "Registration of synchronous customization hooks", "signatures": ["Registering hooks before application code runs with a `data:` URL"], "status": "not-applicable" },
|
||||
{ "chapter": "module", "symbols": ["module.getSourceMapsSupport", "module.setSourceMapsSupport"], "status": "supported", "evidence": ["tests/corpus/module-source-maps.ts", "tests/corpus/module-source-maps-values.mjs"], "reason": "getSourceMapsSupport answers Node's frozen { enabled, nodeModules, generatedCode } record; setSourceMapsSupport and process.setSourceMapsEnabled change that record with Node's validation and Node's option-member read order, so the process flag and the record agree as they do in Node." },
|
||||
{ "chapter": "module", "symbols": ["module.findSourceMap"], "status": "partial", "evidence": ["tests/corpus/module-source-maps.ts", "tests/corpus/module-source-maps-values.mjs", "tests/harness/module-source-maps.test.ts"], "reason": "findSourceMap answers undefined without throwing, which is Node's answer for every path whose source map was never parsed; a compiled program registers no source map because it loads no JavaScript whose footer could name one. Where Node has parsed a map, which a compiled binary never does, the answers differ by design, and tests/harness/module-source-maps.test.ts pins that difference." },
|
||||
{ "chapter": "module", "symbols": ["module.SourceMap", "sourceMap.findEntry", "sourceMap.findOrigin", "payload"], "status": "supported", "evidence": ["tests/corpus/module-source-map-class.ts", "tests/corpus/module-source-map-class-values.mjs"], "reason": "The constructor validates the payload and copies it the way Node does: a shallow copy of its own enumerable properties, with array-valued fields sliced, and a fresh copy on every payload read. Both the mappings and sections forms parse, and findEntry and findOrigin answer Node's range objects, including the empty object before the first range. The instance has no own enumerable fields (Object.keys is empty, JSON.stringify is \"{}\", and inspect prints SourceMap {}), and a detached method throws a TypeError as Node's private-field access does. Object.getOwnPropertyNames on an instance refuses with SC2020, and a payload missing sources or mappings answers an empty map." }
|
||||
{ "chapter": "module", "symbols": ["module.SourceMap", "sourceMap.findEntry", "sourceMap.findOrigin", "payload"], "status": "supported", "evidence": ["tests/corpus/module-source-map-class.ts", "tests/corpus/module-source-map-class-values.mjs"], "reason": "The constructor validates the payload and copies it the way Node does: a shallow copy of its own enumerable properties, with array-valued fields sliced, and a fresh copy on every payload read. Both the mappings and sections forms parse, and findEntry and findOrigin answer Node's range objects, including the empty object before the first range. The instance has no own enumerable fields (Object.keys is empty, JSON.stringify is \"{}\", and inspect prints SourceMap {}), and a detached method throws a TypeError as Node's private-field access does. Object.getOwnPropertyNames on an instance refuses with SC2020, and a payload missing sources or mappings answers an empty map." },
|
||||
{ "chapter": "module", "symbols": ["module.stripTypeScriptTypes"], "status": "partial", "evidence": ["tests/corpus/module-strip-typescript-types/main.cjs", "tests/corpus/module-strip-types-options-chain/main.cjs", "packages/compiler/src/frontend/strip-typescript-types.test.ts", "tests/harness/module-strip-types-warning.test.ts"], "reason": "A compiled program strips the code at build time, in Node's strip mode only. The code and the options are written literally, and the answers are Node's: the stripped text keeps every source position and only blanks the type syntax, the options are read the way Node's Get reads them — own members first, then the literal's own `__proto__` levels — so `mode`, `sourceMap` and `sourceUrl` answer inherited values and their defaults, the argument and option checks raise Node's own validation errors in Node's order, the strip-only syntax errors carry Node's codes and messages, and the first call reports the ExperimentalWarning once. transform mode re-prints the program through SWC's code generator and is a named refusal, as are code, options or option chains the program computes at run time (a getter, a spread, a computed name, a prototype built at run time)." }
|
||||
]
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
{"chapter": "worker_threads", "symbols": ["Worker"], "status": "partial", "evidence": ["tests/corpus/native-worker-messages.ts", "tests/corpus/native-worker-commonjs.cjs", "tests/corpus/native-worker-environment.ts", "tests/corpus/native-worker-roots/main.ts", "tests/corpus/worker-env-option.ts", "tests/corpus/worker-share-env.ts", "tests/corpus/worker-listeners.ts"]},
|
||||
{"chapter": "worker_threads", "symbols": ["Worker"], "status": "partial", "evidence": ["tests/corpus/native-worker-messages.ts", "tests/corpus/native-worker-commonjs.cjs", "tests/corpus/native-worker-environment.ts", "tests/corpus/native-worker-roots/main.ts", "tests/corpus/worker-env-option.ts", "tests/corpus/worker-share-env.ts"]},
|
||||
{"chapter": "worker_threads", "symbols": ["MessagePort", "parentPort", "worker_threads.workerData", "isMainThread", "threadId"], "status": "partial", "evidence": ["tests/corpus/native-worker-commonjs.cjs", "tests/corpus/native-worker-port-lifetime.ts", "tests/corpus/native-worker-references.ts", "tests/corpus/port-listener-bookkeeping.mjs", "tests/corpus/port-handler-attribute.mjs", "tests/corpus/port-listeners-typed.ts", "tests/corpus/port-event-name-coercion.mjs", "tests/corpus/port-listener-order-cycle.mjs", "tests/corpus/port-add-listener-order.mjs"]},
|
||||
{"chapter": "worker_threads", "symbols": ["worker.postMessage", "port.postMessage"], "status": "partial", "evidence": ["tests/corpus/native-worker-message-graphs.ts", "tests/corpus/native-worker-shared-views.ts", "tests/corpus/native-worker-clone-errors.ts", "tests/corpus/native-worker-delayed-messages.ts", "tests/corpus/port-post-message-return.mjs", "tests/corpus/port-transfer-detached.mjs", "tests/corpus/port-post-self-warning.mjs", "tests/corpus/port-clone-error-text.mjs", "tests/corpus/port-post-message-void-result.ts", "tests/corpus/port-post-message-void-value.mjs"]},
|
||||
{"chapter": "worker_threads", "symbols": ["worker.postMessage", "port.postMessage"], "status": "partial", "evidence": ["tests/corpus/native-worker-message-graphs.ts", "tests/corpus/native-worker-shared-views.ts", "tests/corpus/native-worker-clone-errors.ts", "tests/corpus/native-worker-delayed-messages.ts", "tests/corpus/port-post-message-return.mjs", "tests/corpus/port-transfer-detached.mjs", "tests/corpus/port-post-self-warning.mjs", "tests/corpus/port-clone-error-text.mjs", "tests/corpus/port-post-message-void-result.ts", "tests/corpus/port-post-message-void-value.mjs", "tests/corpus/port-post-closed-queue-bound.mjs", "tests/corpus/port-post-closed-cross-thread-bound.mjs"]},
|
||||
{"chapter": "worker_threads", "symbols": ["worker.terminate"], "status": "partial", "evidence": ["tests/corpus/native-worker-terminate-loop.ts", "tests/corpus/native-worker-terminate-wait.ts", "tests/corpus/native-worker-terminate-suspended.ts", "tests/corpus/native-worker-loop-cancellation.ts"]},
|
||||
{"chapter": "worker_threads", "symbols": ["worker.ref", "worker.unref"], "status": "partial", "evidence": ["tests/corpus/native-worker-references.ts"]},
|
||||
{"chapter": "worker_threads", "symbols": ["port.close", "port.start", "port.ref", "port.unref", "port.hasRef"], "status": "partial", "evidence": ["tests/corpus/native-worker-port-lifetime.ts"]},
|
||||
{"chapter": "worker_threads", "symbols": ["port.close", "port.start", "port.ref", "port.unref", "port.hasRef"], "status": "partial", "evidence": ["tests/corpus/native-worker-port-lifetime.ts", "tests/corpus/port-close-argument.mjs"]},
|
||||
{"chapter": "worker_threads", "parent": "Class: `Worker`", "signatures": ["Event: `'online'`", "Event: `'message'`", "Event: `'error'`", "Event: `'exit'`", "Event: `'messageerror'`"], "status": "partial", "evidence": ["tests/corpus/native-worker-references.ts", "tests/corpus/native-worker-error.ts", "tests/corpus/native-worker-exit-listeners.ts", "tests/corpus/5807-worker-error-values.ts", "tests/corpus/5808-worker-unhandled-rejections.ts", "tests/corpus/worker-messageerror-events.ts"]},
|
||||
{"chapter": "worker_threads", "parent": "Class: `MessagePort`", "signatures": ["Event: `'message'`", "Event: `'close'`", "Event: `'messageerror'`"], "status": "partial", "evidence": ["tests/corpus/native-worker-port-lifetime.ts", "tests/corpus/native-worker-messages.ts", "tests/corpus/worker-messageerror-surface.ts"]},
|
||||
{"chapter": "worker_threads", "symbols": ["MessageChannel", "worker_threads.receiveMessageOnPort"], "status": "partial", "evidence": ["tests/corpus/5793-worker-message-channel.ts", "tests/corpus/5796-worker-message-channel.cjs", "tests/corpus/5797-worker-message-port-transfer.ts", "tests/corpus/5805-worker-receive-message-parent-port.ts"]},
|
||||
{"chapter": "worker_threads", "symbols": ["MessageChannel", "worker_threads.receiveMessageOnPort"], "status": "partial", "evidence": ["tests/corpus/5793-worker-message-channel.ts", "tests/corpus/5796-worker-message-channel.cjs", "tests/corpus/5797-worker-message-port-transfer.ts", "tests/corpus/5805-worker-receive-message-parent-port.ts", "tests/corpus/port-receive-closed.mjs", "tests/corpus/worker-receive-closed-parent-port.mjs", "tests/corpus/broadcast-channel-receive-message.mjs"]},
|
||||
{"chapter": "worker_threads", "symbols": ["worker_threads.getEnvironmentData", "worker_threads.setEnvironmentData"], "status": "partial", "evidence": ["tests/corpus/5803-worker-environment-data.ts", "tests/corpus/5804-worker-environment-data.cjs"]},
|
||||
{"chapter": "worker_threads", "symbols": ["stdout", "stderr", "stdin"], "status": "partial", "evidence": ["tests/corpus/5874-worker-stdio-streams.ts", "tests/corpus/5875-worker-stdout-pipe.cjs", "tests/corpus/5879-worker-stdin.ts"]},
|
||||
{"chapter": "worker_threads", "symbols": ["threadName", "worker_threads.markAsUntransferable", "worker_threads.isMarkedAsUntransferable"], "status": "partial", "evidence": ["tests/corpus/5870-worker-thread-names.ts", "tests/corpus/5871-worker-untransferable.cjs"]},
|
||||
|
||||
@@ -50,6 +50,7 @@
|
||||
"js-yaml": "4.3.2",
|
||||
"oxfmt": "0.71.0",
|
||||
"oxlint": "1.86.0",
|
||||
"reflect-metadata": "0.2.2",
|
||||
"rollup": "4.62.2",
|
||||
"smol-toml": "1.7.1",
|
||||
"three": "0.186.1",
|
||||
|
||||
@@ -37,8 +37,11 @@ test("a build reports the conversions that copy, and --no-copy-warning leaves th
|
||||
await mkdir(join(dir, "cache"), { mode: 0o700 });
|
||||
const warned = await cli(["build", fixture, "-o", join(dir, "program")], join(dir, "cache"));
|
||||
expect(warned.code).toBe(0);
|
||||
expect(warned.stderr.match(/warning SC6001/g)?.length).toBe(3);
|
||||
expect(warned.stderr).toContain("3 warnings: the program compiled");
|
||||
// Two sites still copy: the parameter that adds an optional property and
|
||||
// the array element. An assignment to a binding declared with a narrower
|
||||
// type keeps the object (a view), so it reports nothing.
|
||||
expect(warned.stderr.match(/warning SC6001/g)?.length).toBe(2);
|
||||
expect(warned.stderr).toContain("2 warnings: the program compiled");
|
||||
|
||||
await mkdir(join(dir, "quiet"), { mode: 0o700 });
|
||||
const quiet = await cli(
|
||||
|
||||
@@ -39,11 +39,16 @@ const cli = (args: string[], cacheRoot: string): Promise<Result> =>
|
||||
const launcherCli = (args: string[], cacheRoot: string, cwd: string): Promise<Result> =>
|
||||
run([launcher, ...args], cacheRoot, cwd);
|
||||
|
||||
// A conversion to a different layout copies: the target adds an optional
|
||||
// property, so the write reaches the copy and Node's aliasing prints 2 where
|
||||
// the program prints 1. A conversion to a projection the record already
|
||||
// presents keeps the object (a view), which is why this shape is not the
|
||||
// narrower-only one.
|
||||
const COPY = `interface Narrow { a: number }
|
||||
interface Wide { a: number; b: string }
|
||||
const wide: Wide = { a: 1, b: "x" };
|
||||
const narrow: Narrow = wide;
|
||||
narrow.a = 2;
|
||||
interface OptionalB { a: number; b?: string }
|
||||
const wide: Narrow = { a: 1 };
|
||||
function annotate(target: OptionalB) { target.a = 2 }
|
||||
annotate(wide);
|
||||
console.log(wide.a);
|
||||
`;
|
||||
|
||||
@@ -259,10 +264,7 @@ test("build --strict fails on a copy, accepts an allow comment, and a cached bui
|
||||
const allowed = join(dir, "allowed.ts");
|
||||
await writeFile(
|
||||
allowed,
|
||||
COPY.replace(
|
||||
"const narrow: Narrow = wide;",
|
||||
"const narrow: Narrow = wide; // scriptc-allow SC6001",
|
||||
),
|
||||
COPY.replace("annotate(wide);", "annotate(wide); // scriptc-allow SC6001"),
|
||||
);
|
||||
const ok = await cli(["build", allowed, "-o", join(dir, "ok-program")], join(dir, "ok-cache"));
|
||||
expect(ok.code).toBe(0);
|
||||
|
||||
+24
-5
@@ -149,17 +149,21 @@ declare module "fs/promises" {
|
||||
destination: string | URL,
|
||||
options?: import("node:fs").CopyOptions,
|
||||
): Promise<void>;
|
||||
export function readlink(
|
||||
export function readlink<U extends { readonly __untyped: never }>(
|
||||
path: string | Uint8Array | URL,
|
||||
options: "buffer" | { encoding: "buffer" },
|
||||
): Promise<Buffer>;
|
||||
options: U,
|
||||
): Promise<string | Buffer>;
|
||||
export function readlink(
|
||||
path: string | Uint8Array | URL,
|
||||
options?: BufferEncoding | { encoding?: BufferEncoding | null } | null,
|
||||
): Promise<string>;
|
||||
export function readlink(
|
||||
path: string | Uint8Array | URL,
|
||||
options: string | { encoding?: string | null } | null,
|
||||
options: "buffer" | { encoding: "buffer" },
|
||||
): Promise<Buffer>;
|
||||
export function readlink(
|
||||
path: string | Uint8Array | URL,
|
||||
options?: string | { encoding?: string | null } | null,
|
||||
): Promise<string | Buffer>;
|
||||
export function utimes(
|
||||
path: string | Uint8Array | URL,
|
||||
@@ -275,7 +279,22 @@ declare module "fs/promises" {
|
||||
path: string | Uint8Array | URL,
|
||||
options?: import("node:fs").StatFsOptions,
|
||||
): Promise<import("node:fs").StatsFs | import("node:fs").BigIntStatsFs>;
|
||||
export function realpath(path: string | URL): Promise<string>;
|
||||
export function realpath<U extends { readonly __untyped: never }>(
|
||||
path: string | Uint8Array | URL,
|
||||
options: U,
|
||||
): Promise<string | Buffer>;
|
||||
export function realpath(
|
||||
path: string | Uint8Array | URL,
|
||||
options?: BufferEncoding | { encoding?: BufferEncoding | null } | null,
|
||||
): Promise<string>;
|
||||
export function realpath(
|
||||
path: string | Uint8Array | URL,
|
||||
options: "buffer" | { encoding: "buffer" },
|
||||
): Promise<Buffer>;
|
||||
export function realpath(
|
||||
path: string | Uint8Array | URL,
|
||||
options?: string | { encoding?: string | null } | null,
|
||||
): Promise<string | Buffer>;
|
||||
/* Node's promise lstat never reads throwIfNoEntry: a missing entry always
|
||||
* rejects, so the result never carries the undefined arm. */
|
||||
export function lstat(path: string | URL): Promise<import("node:fs").Stats>;
|
||||
|
||||
+43
-6
@@ -224,17 +224,21 @@ declare module "node:fs" {
|
||||
options: string | { encoding?: string | null } | null,
|
||||
callback: (err: NodeJS.ErrnoException | null, target: string | Buffer) => void,
|
||||
): void;
|
||||
export function readlinkSync(
|
||||
export function readlinkSync<U extends { readonly __untyped: never }>(
|
||||
path: string | Uint8Array | URL,
|
||||
options: "buffer" | { encoding: "buffer" },
|
||||
): Buffer;
|
||||
options: U,
|
||||
): string | Buffer;
|
||||
export function readlinkSync(
|
||||
path: string | Uint8Array | URL,
|
||||
options?: BufferEncoding | { encoding?: BufferEncoding | null } | null,
|
||||
): string;
|
||||
export function readlinkSync(
|
||||
path: string | Uint8Array | URL,
|
||||
options: string | { encoding?: string | null } | null,
|
||||
options: "buffer" | { encoding: "buffer" },
|
||||
): Buffer;
|
||||
export function readlinkSync(
|
||||
path: string | Uint8Array | URL,
|
||||
options?: string | { encoding?: string | null } | null,
|
||||
): string | Buffer;
|
||||
export function chownSync(path: string | URL, uid: number, gid: number): void;
|
||||
export function lchownSync(path: string | URL, uid: number, gid: number): void;
|
||||
@@ -727,9 +731,42 @@ declare module "node:fs" {
|
||||
export function fstatSync(fd: number, options: StatSyncOptions): Stats | BigIntStats;
|
||||
/* realpath(3) — resolves symlinks, `.`/`..`, throwing Node's fs error
|
||||
* shapes for missing paths. */
|
||||
export function realpathSync(path: string | URL): string;
|
||||
/* The encoding options decide the result: a literal "buffer" answers a
|
||||
* Buffer, a known string encoding a string, and an answer the checker
|
||||
* cannot prove -- an untyped argument, or a getter typed string -- the
|
||||
* union Node's runtime can produce. The first overload matches only an
|
||||
* argument with no static type (any): its phantom member is never
|
||||
* satisfiable by a typed value. */
|
||||
export function realpathSync<U extends { readonly __untyped: never }>(
|
||||
path: string | URL,
|
||||
options: U,
|
||||
): string | Buffer;
|
||||
export function realpathSync(
|
||||
path: string | URL,
|
||||
options?: BufferEncoding | { encoding?: BufferEncoding | null } | null,
|
||||
): string;
|
||||
export function realpathSync(
|
||||
path: string | URL,
|
||||
options: "buffer" | { encoding: "buffer" },
|
||||
): Buffer;
|
||||
export function realpathSync(
|
||||
path: string | URL,
|
||||
options?: string | { encoding?: string | null } | null,
|
||||
): string | Buffer;
|
||||
export namespace realpathSync {
|
||||
function native(path: string | URL): string;
|
||||
function native<U extends { readonly __untyped: never }>(
|
||||
path: string | URL,
|
||||
options: U,
|
||||
): string | Buffer;
|
||||
function native(
|
||||
path: string | URL,
|
||||
options?: BufferEncoding | { encoding?: BufferEncoding | null } | null,
|
||||
): string;
|
||||
function native(path: string | URL, options: "buffer" | { encoding: "buffer" }): Buffer;
|
||||
function native(
|
||||
path: string | URL,
|
||||
options?: string | { encoding?: string | null } | null,
|
||||
): string | Buffer;
|
||||
}
|
||||
/* statfs(2)/statvfs(3) — the filesystem-capacity snapshot (the fields
|
||||
* Node's statfsSync reports; bavail × bsize is the free-space probe). */
|
||||
|
||||
Binary file not shown.
@@ -68,7 +68,20 @@ export class Client extends DispatcherBase {
|
||||
__sockNoRef: boolean;
|
||||
__sockReset: boolean;
|
||||
__sockBlocking: boolean;
|
||||
/** How many streamed request bodies are still being written. Kept apart
|
||||
* from __sockBlocking, which the response headers clear: the next
|
||||
* request must not be written into an unfinished body. A count, not a
|
||||
* flag, because a pump on a socket that is being replaced may finish
|
||||
* after a new one starts. */
|
||||
__bodyUploads: number;
|
||||
/** The streamed uploads in flight. A socket teardown aborts them and
|
||||
* frees the connection slot: a source that never yields another chunk
|
||||
* must not keep the client busy (and the pool's only slot) forever. */
|
||||
__uploads: { stream: AsyncIterable<Uint8Array | string> }[];
|
||||
__sockCounter: number;
|
||||
/** Resolvers waiting for the socket's next 'drain' (streamed request
|
||||
* bodies). The 'drain' listener in __onConnected flushes them. */
|
||||
__drainWaiters: (() => void)[];
|
||||
__parser: ResponseParser | null;
|
||||
__sockError: Error | null;
|
||||
// The parser timer, held as closures over its handle (a nullable timer
|
||||
@@ -180,7 +193,10 @@ export class Client extends DispatcherBase {
|
||||
this.__sockNoRef = false;
|
||||
this.__sockReset = false;
|
||||
this.__sockBlocking = false;
|
||||
this.__bodyUploads = 0;
|
||||
this.__uploads = [];
|
||||
this.__sockCounter = 0;
|
||||
this.__drainWaiters = [];
|
||||
this.__parser = null;
|
||||
this.__sockError = null;
|
||||
this.__timerCancel = null;
|
||||
@@ -211,7 +227,8 @@ export class Client extends DispatcherBase {
|
||||
|
||||
__busy(): boolean {
|
||||
return (
|
||||
(this.__socket !== null && (this.__sockReset || this.__sockBlocking)) ||
|
||||
(this.__socket !== null &&
|
||||
(this.__sockReset || this.__sockBlocking || this.__bodyUploads > 0)) ||
|
||||
this.__sizeCount() >= (this.__pipelining || 1) ||
|
||||
this.__pendingCount() > 0
|
||||
);
|
||||
@@ -413,6 +430,7 @@ export class Client extends DispatcherBase {
|
||||
this.__sockBlocking = false;
|
||||
this.__sockCounter = 0;
|
||||
this.__sockError = null;
|
||||
this.__flushDrainWaiters();
|
||||
const parser = new ResponseParser(this, socket);
|
||||
this.__parser = parser;
|
||||
socket.on("data", (chunk: Buffer) => {
|
||||
@@ -427,6 +445,9 @@ export class Client extends DispatcherBase {
|
||||
socket.on("close", () => {
|
||||
if (this.__socket === socket) this.__onSocketClose(socket);
|
||||
});
|
||||
socket.on("drain", () => {
|
||||
if (this.__socket === socket) this.__flushDrainWaiters();
|
||||
});
|
||||
if (channels.connected.hasSubscribers) {
|
||||
channels.connected.publish({ connectParams, connector: this.__connector, socket });
|
||||
}
|
||||
@@ -465,6 +486,7 @@ export class Client extends DispatcherBase {
|
||||
}
|
||||
|
||||
__onSocketError(socket: Socket, err: Error): void {
|
||||
this.__flushDrainWaiters();
|
||||
const parser = this.__parser;
|
||||
if (
|
||||
errorCode(err) === "ECONNRESET" &&
|
||||
@@ -514,10 +536,26 @@ export class Client extends DispatcherBase {
|
||||
if (request !== null && request !== undefined) this.__errorRequest(request, err);
|
||||
}
|
||||
this.__pendingIdx = this.__runningIdx;
|
||||
/* The socket is gone: abort any streamed upload it was still writing
|
||||
* and free its slot, so a stalled source cannot keep the connection
|
||||
* reserved (the request itself was failed above). */
|
||||
this.__abortUploads(err);
|
||||
this.emit("disconnect", this.__url, [this as Dispatcher], err);
|
||||
this.__resume(false);
|
||||
}
|
||||
|
||||
/** A socket teardown releases every upload it carried: the request was
|
||||
* failed above, the source is abandoned where it awaits its next chunk,
|
||||
* and the busy count is cleared so the pool can replace the connection.
|
||||
* (The normalized body stream keeps no destroy() the client could call;
|
||||
* a source that never yields again must not pin the slot.) */
|
||||
__abortUploads(err: Error): void {
|
||||
void err;
|
||||
if (this.__uploads.length === 0) return;
|
||||
this.__uploads = [];
|
||||
this.__bodyUploads = 0;
|
||||
}
|
||||
|
||||
__emitDrain(): void {
|
||||
this.__needDrain = 0;
|
||||
this.emit("drain", this.__url, [this as Dispatcher]);
|
||||
@@ -598,7 +636,8 @@ export class Client extends DispatcherBase {
|
||||
this.__connect();
|
||||
continue;
|
||||
}
|
||||
if (socket.destroyed || this.__sockReset || this.__sockBlocking) return;
|
||||
if (socket.destroyed || this.__sockReset || this.__sockBlocking || this.__bodyUploads > 0)
|
||||
return;
|
||||
if (this.__runningCount() > 0 && !request.idempotent) return;
|
||||
|
||||
if (!request.aborted && this.__write(request, socket)) {
|
||||
@@ -619,8 +658,10 @@ export class Client extends DispatcherBase {
|
||||
method === "PATCH" ||
|
||||
((this.__profile.major >= 7 || request.framedAsNode) &&
|
||||
(method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH"));
|
||||
// util.bodyLength: a missing body has length 0.
|
||||
let contentLength: number | null = body !== null ? body.length : 0;
|
||||
// util.bodyLength: a missing body has length 0, a streamed body has
|
||||
// whatever content-length the request declared (or none).
|
||||
let contentLength: number | null =
|
||||
request.bodyStream !== null ? request.contentLength : body !== null ? body.length : 0;
|
||||
if (contentLength === 0 && !expectsPayload) contentLength = null;
|
||||
const declared = request.contentLength;
|
||||
const sendsLength =
|
||||
@@ -666,6 +707,19 @@ export class Client extends DispatcherBase {
|
||||
if (channels.sendHeaders.hasSubscribers) {
|
||||
channels.sendHeaders.publish({ request: request.diagnosticView(), headers: header, socket });
|
||||
}
|
||||
if (request.bodyStream !== null) {
|
||||
// A streamed body: the socket stays blocked to other requests while
|
||||
// its chunks are written; chunked framing unless the request
|
||||
// declared a content-length.
|
||||
this.__bodyUploads += 1;
|
||||
if (request.contentLength !== null) {
|
||||
socket.write(`${header}content-length: ${request.contentLength}\r\n\r\n`);
|
||||
} else {
|
||||
socket.write(`${header}transfer-encoding: chunked\r\n\r\n`);
|
||||
}
|
||||
this.__streamBody(request, socket);
|
||||
return true;
|
||||
}
|
||||
if (body === null) {
|
||||
if (contentLength === 0) socket.write(`${header}content-length: 0\r\n\r\n`);
|
||||
else socket.write(`${header}\r\n`);
|
||||
@@ -680,6 +734,81 @@ export class Client extends DispatcherBase {
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Writes one chunk, resolving when the socket can take more. */
|
||||
__writeChunk(socket: Socket, chunk: Buffer): Promise<void> {
|
||||
if (socket.destroyed) return Promise.resolve();
|
||||
if (socket.write(chunk)) return Promise.resolve();
|
||||
return new Promise<void>((resolve) => {
|
||||
this.__drainWaiters.push(resolve);
|
||||
});
|
||||
}
|
||||
|
||||
__flushDrainWaiters(): void {
|
||||
const waiting = this.__drainWaiters;
|
||||
this.__drainWaiters = [];
|
||||
for (const resolve of waiting) resolve();
|
||||
}
|
||||
|
||||
/** Writes an async-iterable body chunk by chunk, waiting for the
|
||||
* socket's drain between writes. When the request declared a
|
||||
* content-length, the bytes written must be exactly that many: a stream
|
||||
* that writes more or fewer fails the request and destroys the
|
||||
* connection, so the excess can never be parsed as the next request on a
|
||||
* kept-alive connection. A source that fails is handled the same way, as
|
||||
* undici's writeBody does. */
|
||||
__streamBody(request: Request, socket: Socket): void {
|
||||
const stream = request.bodyStream;
|
||||
if (stream === null) return;
|
||||
const declared = request.contentLength;
|
||||
const chunked = declared === null;
|
||||
const upload = { stream };
|
||||
this.__uploads.push(upload);
|
||||
const pump = async (): Promise<void> => {
|
||||
let failed = false;
|
||||
let written = 0;
|
||||
try {
|
||||
for await (const chunk of stream) {
|
||||
if (request.aborted || socket.destroyed) break;
|
||||
const bytes = typeof chunk === "string" ? Buffer.from(chunk) : Buffer.from(chunk);
|
||||
if (bytes.length === 0) continue;
|
||||
if (declared !== null && written + bytes.length > declared) {
|
||||
throw new RequestContentLengthMismatchError();
|
||||
}
|
||||
if (chunked) {
|
||||
await this.__writeChunk(socket, Buffer.from(`${bytes.length.toString(16)}\r\n`));
|
||||
await this.__writeChunk(socket, bytes);
|
||||
await this.__writeChunk(socket, Buffer.from("\r\n"));
|
||||
} else {
|
||||
await this.__writeChunk(socket, bytes);
|
||||
}
|
||||
written += bytes.length;
|
||||
request.onBodySent(bytes);
|
||||
}
|
||||
if (!request.aborted && !socket.destroyed) {
|
||||
if (declared !== null && written !== declared) {
|
||||
throw new RequestContentLengthMismatchError();
|
||||
}
|
||||
if (chunked) await this.__writeChunk(socket, Buffer.from("0\r\n\r\n"));
|
||||
request.onRequestSent();
|
||||
}
|
||||
} catch (err) {
|
||||
failed = true;
|
||||
this.__errorRequest(request, err as Error);
|
||||
this.__destroySocket(socket, new InformationalError("aborted"));
|
||||
} finally {
|
||||
/* A teardown already dropped this upload's token (and the count);
|
||||
* the pump only keeps the books for an upload still registered. */
|
||||
const idx = this.__uploads.indexOf(upload);
|
||||
if (idx !== -1) {
|
||||
this.__uploads.splice(idx, 1);
|
||||
this.__bodyUploads -= 1;
|
||||
}
|
||||
if (!this.destroyed && (idx !== -1 || failed)) this.__resume(false);
|
||||
}
|
||||
};
|
||||
pump();
|
||||
}
|
||||
|
||||
// ResponseParser callbacks.
|
||||
|
||||
__onHeadersComplete(parser: ResponseParser, socket: Socket): number {
|
||||
@@ -766,6 +895,14 @@ export class Client extends DispatcherBase {
|
||||
this.__errorRequest(request, err as Error);
|
||||
}
|
||||
this.__queue[this.__runningIdx++] = null;
|
||||
if (this.__bodyUploads > 0) {
|
||||
// The response completed before the streamed upload did. The peer
|
||||
// cannot take the rest, and the next request must never be written
|
||||
// into the unfinished body: destroy the connection, as undici does
|
||||
// when a response completes while the socket is still writing.
|
||||
this.__destroySocket(socket, new InformationalError("reset"));
|
||||
return false;
|
||||
}
|
||||
if (!shouldKeepAlive) {
|
||||
this.__destroySocket(socket, new InformationalError("reset"));
|
||||
return false;
|
||||
|
||||
@@ -26,8 +26,16 @@ function tlsSecureVersion(value: string | undefined, what: "minimum" | "maximum"
|
||||
/** undici types an ALPN list as string[] or Buffer[]; node:tls takes a
|
||||
* string list or one length-prefixed view. A buffer list is normalized into
|
||||
* that wire form — the same list tls reads from either representation. */
|
||||
function tlsAlpnProtocols(value: string[] | Uint8Array[] | undefined) {
|
||||
function tlsAlpnProtocols(value: string[] | Uint8Array[] | Uint8Array | undefined) {
|
||||
if (value === undefined) return undefined;
|
||||
/* node:tls accepts the already-encoded, length-prefixed protocol list as
|
||||
* one Buffer or Uint8Array; such a value is already the wire form and
|
||||
* only a LIST of protocols needs normalizing. */
|
||||
if (!Array.isArray(value)) return value;
|
||||
return tlsAlpnList(value);
|
||||
}
|
||||
|
||||
function tlsAlpnList(value: string[] | Uint8Array[]) {
|
||||
const strings: string[] = [];
|
||||
let views = false;
|
||||
for (let i = 0; i < value.length; i++) {
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
// undici 7.x's EnvHttpProxyAgent (lib/dispatcher/env-http-proxy-agent.js):
|
||||
// a dispatcher that picks, per request, between one Agent that goes
|
||||
// straight at the origin and a ProxyAgent per scheme, from the proxy
|
||||
// settings the constructor gives or the environment holds. NO_PROXY lists
|
||||
// the hosts that bypass the proxy; each entry is a hostname, an optional
|
||||
// `:port`, and `*` alone means never proxy.
|
||||
//
|
||||
// The agent the request takes is decided from the request origin's host
|
||||
// and port exactly as undici decides it, including the IPv6 brackets and
|
||||
// the scheme's default port. `noProxy` given to the constructor is fixed;
|
||||
// without it, the environment is re-read on every request, so a program
|
||||
// that changes NO_PROXY changes the routing.
|
||||
import { Agent } from "./agent.ts";
|
||||
import { Dispatcher, DispatcherBase } from "./dispatcher.ts";
|
||||
import { ProxyAgent, type ProxyAgentOptions } from "./proxy-agent.ts";
|
||||
import type { DispatchHandlers, DispatchOptions, Profile } from "./types.ts";
|
||||
|
||||
/** undici's EnvHttpProxyAgent.Options. */
|
||||
export interface EnvHttpProxyAgentOptions extends Omit<ProxyAgentOptions, "uri"> {
|
||||
/** Overrides http_proxy / HTTP_PROXY. */
|
||||
httpProxy?: string;
|
||||
/** Overrides https_proxy / HTTPS_PROXY. */
|
||||
httpsProxy?: string;
|
||||
/** Overrides no_proxy / NO_PROXY. */
|
||||
noProxy?: string;
|
||||
}
|
||||
|
||||
interface NoProxyEntry {
|
||||
hostname: string;
|
||||
port: number;
|
||||
}
|
||||
|
||||
const DEFAULT_PORTS: ReadonlyMap<string, number> = new Map([
|
||||
["http:", 80],
|
||||
["https:", 443],
|
||||
]);
|
||||
|
||||
function envValue(name: string): string | null {
|
||||
const value = process.env[name];
|
||||
return value === undefined ? null : value;
|
||||
}
|
||||
|
||||
export class EnvHttpProxyAgent extends DispatcherBase {
|
||||
__noProxyAgent: Dispatcher;
|
||||
__httpProxyAgent: Dispatcher;
|
||||
__httpsProxyAgent: Dispatcher;
|
||||
__noProxyValue: string;
|
||||
__noProxyEntries: NoProxyEntry[];
|
||||
__fixedNoProxy: string | undefined;
|
||||
__envNoProxy: string;
|
||||
|
||||
constructor(options: EnvHttpProxyAgentOptions, profile: Profile) {
|
||||
super(profile);
|
||||
const opts: EnvHttpProxyAgentOptions = options ?? {};
|
||||
// Everything but the three environment members belongs to the agents
|
||||
// this dispatcher builds, ProxyAgent's requestTls and proxyTls
|
||||
// included: a configured private trust store must reach the tunnel,
|
||||
// never be replaced by the system roots.
|
||||
const { httpProxy, httpsProxy, noProxy, ...agentOptions } = opts;
|
||||
this.__noProxyAgent = new Agent(agentOptions, profile);
|
||||
const http = httpProxy ?? envValue("http_proxy") ?? envValue("HTTP_PROXY");
|
||||
this.__httpProxyAgent =
|
||||
http !== null && http !== ""
|
||||
? new ProxyAgent({ ...agentOptions, uri: http }, profile, (o) => new Agent(o, profile))
|
||||
: this.__noProxyAgent;
|
||||
const https = httpsProxy ?? envValue("https_proxy") ?? envValue("HTTPS_PROXY");
|
||||
this.__httpsProxyAgent =
|
||||
https !== null && https !== ""
|
||||
? new ProxyAgent({ ...agentOptions, uri: https }, profile, (o) => new Agent(o, profile))
|
||||
: this.__httpProxyAgent;
|
||||
this.__fixedNoProxy = noProxy;
|
||||
this.__envNoProxy = "";
|
||||
this.__noProxyValue = "";
|
||||
this.__noProxyEntries = [];
|
||||
this.__parseNoProxy();
|
||||
}
|
||||
|
||||
__dispatch(options: DispatchOptions, handler: DispatchHandlers): boolean {
|
||||
const origin = options.origin;
|
||||
const url = new URL(origin === undefined ? "" : String(origin));
|
||||
const agent = this.__agentForURL(url);
|
||||
return agent.dispatch(options, handler);
|
||||
}
|
||||
|
||||
__close(): Promise<void> {
|
||||
const agents: Dispatcher[] = [];
|
||||
const add = (agent: Dispatcher): void => {
|
||||
if (!agents.includes(agent)) agents.push(agent);
|
||||
};
|
||||
add(this.__noProxyAgent);
|
||||
add(this.__httpProxyAgent);
|
||||
add(this.__httpsProxyAgent);
|
||||
return Promise.all(agents.map((agent) => agent.close())).then(() => undefined);
|
||||
}
|
||||
|
||||
__destroy(err: Error): Promise<void> {
|
||||
const agents: Dispatcher[] = [];
|
||||
const add = (agent: Dispatcher): void => {
|
||||
if (!agents.includes(agent)) agents.push(agent);
|
||||
};
|
||||
add(this.__noProxyAgent);
|
||||
add(this.__httpProxyAgent);
|
||||
add(this.__httpsProxyAgent);
|
||||
return Promise.all(agents.map((agent) => agent.destroy(err))).then(() => undefined);
|
||||
}
|
||||
|
||||
__agentForURL(url: URL): Dispatcher {
|
||||
let hostname = url.host.replace(/:\d*$/, "").toLowerCase();
|
||||
const port = Number.parseInt(url.port, 10) || DEFAULT_PORTS.get(url.protocol) || 0;
|
||||
if (!this.__shouldProxy(hostname, port)) return this.__noProxyAgent;
|
||||
if (url.protocol === "https:") return this.__httpsProxyAgent;
|
||||
return this.__httpProxyAgent;
|
||||
}
|
||||
|
||||
__shouldProxy(hostname: string, port: number): boolean {
|
||||
if (this.__fixedNoProxy === undefined && this.__noProxyValue !== this.__currentNoProxy()) {
|
||||
this.__parseNoProxy();
|
||||
}
|
||||
if (this.__noProxyEntries.length === 0) return true;
|
||||
if (this.__noProxyValue === "*") return false;
|
||||
for (const entry of this.__noProxyEntries) {
|
||||
if (entry.port !== 0 && entry.port !== port) continue;
|
||||
if (hostname === entry.hostname) return false;
|
||||
if (hostname.endsWith(`.${entry.hostname}`)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
__currentNoProxy(): string {
|
||||
this.__envNoProxy = envValue("no_proxy") ?? envValue("NO_PROXY") ?? "";
|
||||
return this.__envNoProxy;
|
||||
}
|
||||
|
||||
__parseNoProxy(): void {
|
||||
const value = this.__fixedNoProxy !== undefined ? this.__fixedNoProxy : this.__currentNoProxy();
|
||||
const entries: NoProxyEntry[] = [];
|
||||
for (const raw of value.split(/[,\s]/)) {
|
||||
if (raw === "") continue;
|
||||
const parsed = /^(.+):(\d+)$/.exec(raw);
|
||||
const host = parsed === null ? raw : parsed[1]!;
|
||||
const port = parsed === null ? 0 : Number.parseInt(parsed[2]!, 10);
|
||||
entries.push({ hostname: host.replace(/^\*?\./, "").toLowerCase(), port });
|
||||
}
|
||||
this.__noProxyValue = value;
|
||||
this.__noProxyEntries = entries;
|
||||
}
|
||||
}
|
||||
@@ -69,6 +69,11 @@ export interface ProxyAgentOptions extends Omit<AgentOptions, "interceptors"> {
|
||||
|
||||
export class ProxyAgent extends DispatcherBase {
|
||||
__agent: Dispatcher;
|
||||
/** The TLS options the tunnel applies to the origin and to the proxy;
|
||||
* kept so a dispatcher that builds this agent (EnvHttpProxyAgent) and
|
||||
* its tests can see what was forwarded. */
|
||||
__requestTls: ConnectorBuildOptions | undefined;
|
||||
__proxyTls: ConnectorBuildOptions | undefined;
|
||||
|
||||
constructor(
|
||||
options: ProxyAgentOptions | string,
|
||||
@@ -140,6 +145,8 @@ export class ProxyAgent extends DispatcherBase {
|
||||
"lookup",
|
||||
]);
|
||||
const requestTls = opts.requestTls;
|
||||
this.__requestTls = requestTls;
|
||||
this.__proxyTls = opts.proxyTls;
|
||||
const connect = tunnelConnector(
|
||||
proxy,
|
||||
proxyHeaders,
|
||||
|
||||
@@ -160,6 +160,14 @@ export class BodyReadable extends EventEmitter {
|
||||
});
|
||||
}
|
||||
|
||||
/** Readable's async iterator over the body chunks: each next() hands out
|
||||
* one buffered chunk, waits for the next one, and resolves done after
|
||||
* the end. Leaving the loop early destroys the body, as Readable's
|
||||
* iterator does. */
|
||||
[Symbol.asyncIterator](): AsyncIterableIterator<Buffer> {
|
||||
return new BodyIterator(this);
|
||||
}
|
||||
|
||||
/** True once text()/json()/arrayBuffer()/bytes()/blob()/dump() started
|
||||
* consuming the body. */
|
||||
get bodyUsed(): boolean {
|
||||
@@ -253,6 +261,126 @@ export class BodyReadable extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
/** One async iteration over a BodyReadable: it listens for the body's
|
||||
* events, hands a chunk straight to a waiting next(), queues what the
|
||||
* consumer has not asked for yet, and pauses the body once that queue
|
||||
* reaches the high-water mark, so a slow consumer cannot make the
|
||||
* iterator's queue grow without bound. Leaving the loop early destroys the
|
||||
* body, as Readable's iterator does. */
|
||||
class BodyIterator implements AsyncIterableIterator<Buffer> {
|
||||
__body: BodyReadable;
|
||||
__queue: Buffer[];
|
||||
__queuedBytes: number;
|
||||
/** The next() waiting for a chunk; null when none is outstanding. */
|
||||
__waiting: ((chunk: Buffer | null) => void) | null;
|
||||
__done: boolean;
|
||||
__failure: Error | null;
|
||||
__paused: boolean;
|
||||
__onData: (chunk: Buffer) => void;
|
||||
__onEnd: () => void;
|
||||
__onError: (err: Error) => void;
|
||||
__onClose: () => void;
|
||||
|
||||
constructor(body: BodyReadable) {
|
||||
this.__body = body;
|
||||
this.__queue = [];
|
||||
this.__queuedBytes = 0;
|
||||
this.__waiting = null;
|
||||
// A body whose end (or close) already fired has nothing left to read.
|
||||
// Resuming it would leave next() waiting for an event that cannot come.
|
||||
this.__done = body.readableEnded || body.destroyed;
|
||||
this.__failure = null;
|
||||
this.__paused = false;
|
||||
this.__onData = (chunk: Buffer): void => {
|
||||
if (this.__done) return;
|
||||
const waiting = this.__waiting;
|
||||
if (waiting !== null) {
|
||||
this.__waiting = null;
|
||||
waiting(chunk);
|
||||
return;
|
||||
}
|
||||
this.__queue.push(chunk);
|
||||
this.__queuedBytes += chunk.length;
|
||||
if (this.__queuedBytes >= HIGH_WATER_MARK && !this.__paused) {
|
||||
this.__paused = true;
|
||||
this.__body.pause();
|
||||
}
|
||||
};
|
||||
this.__onEnd = (): void => {
|
||||
this.__done = true;
|
||||
this.__wake(null);
|
||||
};
|
||||
this.__onError = (err: Error): void => {
|
||||
if (this.__failure === null) this.__failure = err;
|
||||
this.__done = true;
|
||||
this.__wake(null);
|
||||
};
|
||||
this.__onClose = (): void => {
|
||||
this.__done = true;
|
||||
this.__wake(null);
|
||||
};
|
||||
body.on("data", this.__onData);
|
||||
body.on("end", this.__onEnd);
|
||||
body.on("error", this.__onError);
|
||||
body.on("close", this.__onClose);
|
||||
// The data listener switches the body to flowing mode (BodyReadable's
|
||||
// newListener hook); pause until the consumer asks for a chunk.
|
||||
body.pause();
|
||||
}
|
||||
|
||||
[Symbol.asyncIterator](): AsyncIterableIterator<Buffer> {
|
||||
return this;
|
||||
}
|
||||
|
||||
next(): Promise<IteratorResult<Buffer>> {
|
||||
const chunk = this.__queue.shift();
|
||||
if (chunk !== undefined) {
|
||||
this.__queuedBytes -= chunk.length;
|
||||
if (this.__paused && this.__queuedBytes < HIGH_WATER_MARK) {
|
||||
this.__paused = false;
|
||||
this.__body.resume();
|
||||
}
|
||||
const value: IteratorResult<Buffer> = { done: false, value: chunk };
|
||||
return Promise.resolve<IteratorResult<Buffer>>(value);
|
||||
}
|
||||
if (this.__failure !== null) return Promise.reject(this.__failure);
|
||||
if (this.__done || this.__body.readableEnded || this.__body.destroyed) {
|
||||
const value: IteratorResult<Buffer> = { done: true, value: undefined };
|
||||
return Promise.resolve<IteratorResult<Buffer>>(value);
|
||||
}
|
||||
this.__body.resume();
|
||||
return new Promise<IteratorResult<Buffer>>((resolve, reject) => {
|
||||
this.__waiting = (chunk: Buffer | null): void => {
|
||||
if (chunk !== null) {
|
||||
const value: IteratorResult<Buffer> = { done: false, value: chunk };
|
||||
resolve(value);
|
||||
} else {
|
||||
this.next().then(resolve, reject);
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
return(): Promise<IteratorResult<Buffer>> {
|
||||
this.__body.removeListener("data", this.__onData);
|
||||
this.__body.removeListener("end", this.__onEnd);
|
||||
this.__body.removeListener("close", this.__onClose);
|
||||
// The error listener stays: destroy() reports its abort through
|
||||
// 'error', and an unobserved 'error' event throws.
|
||||
if (!this.__body.destroyed) this.__body.destroy();
|
||||
const value: IteratorResult<Buffer> = { done: true, value: undefined };
|
||||
return Promise.resolve<IteratorResult<Buffer>>(value);
|
||||
}
|
||||
|
||||
__wake(chunk: Buffer | null): void {
|
||||
const waiting = this.__waiting;
|
||||
if (waiting !== null) {
|
||||
this.__waiting = null;
|
||||
waiting(chunk);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 5.x decodes UTF-8 as-is; 7.x strips a leading byte-order mark first. */
|
||||
function decodeText(bytes: Buffer, profile: Profile): string {
|
||||
if (
|
||||
|
||||
@@ -20,6 +20,12 @@ export class Request {
|
||||
* the field definitely assigned when a project disables
|
||||
* strictPropertyInitialization. */
|
||||
body: Buffer | null = null;
|
||||
/** A streamed body: the request is written chunk by chunk (chunked
|
||||
* transfer encoding unless a content-length header was given). Null when
|
||||
* the body was a string or bytes. */
|
||||
bodyStream: AsyncIterable<Uint8Array | string> | null = null;
|
||||
/** Bytes handed to the wire so far, for onBodySent's running total. */
|
||||
bodyBytesSent: number = 0;
|
||||
/** Header name/value pairs in insertion order (host and content-length
|
||||
* are consumed into their own fields, like undici). */
|
||||
headerPairs: string[];
|
||||
@@ -98,9 +104,13 @@ export class Request {
|
||||
this.body =
|
||||
body.byteLength > 0 ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null;
|
||||
} else {
|
||||
throw new NotSupportedError(
|
||||
"scriptc's undici client sends string and byte bodies (string, Buffer, Uint8Array); a stream, an iterable, a Blob or a FormData body is not supported yet",
|
||||
);
|
||||
const stream = asyncIterableOf(body);
|
||||
if (stream === null) {
|
||||
throw new NotSupportedError(
|
||||
"scriptc's undici client sends string and byte bodies (string, Buffer, Uint8Array) and async-iterable bodies (for example Readable.from(...)); a Blob or a FormData body is not supported yet",
|
||||
);
|
||||
}
|
||||
this.bodyStream = stream;
|
||||
}
|
||||
|
||||
this.completed = false;
|
||||
@@ -188,10 +198,11 @@ export class Request {
|
||||
}
|
||||
|
||||
onBodySent(chunk: Buffer): void {
|
||||
this.bodyBytesSent += chunk.length;
|
||||
const cb = this.handler.onBodySent;
|
||||
if (cb !== undefined) {
|
||||
try {
|
||||
this.handler.onBodySent!(chunk.length, chunk.length);
|
||||
this.handler.onBodySent!(chunk.length, this.bodyBytesSent);
|
||||
} catch (err) {
|
||||
this.onError(err as Error);
|
||||
}
|
||||
@@ -323,3 +334,14 @@ function serverName(host: string | null): string | null {
|
||||
if (idx !== -1) name = name.slice(0, idx);
|
||||
return /^\d+\.\d+\.\d+\.\d+$/.test(name) ? null : name;
|
||||
}
|
||||
|
||||
/** The body as an async iterable, when it is one: a Node Readable, an
|
||||
* AsyncIterable of bytes or strings, or an async generator. The parameter
|
||||
* is untyped because the body's static type is unknown here; the protocol
|
||||
* method is the check. */
|
||||
// oxlint-disable-next-line typescript/no-explicit-any
|
||||
function asyncIterableOf(body: any): AsyncIterable<Uint8Array | string> | null {
|
||||
if (typeof body !== "object" || body === null) return null;
|
||||
const iterator = body[Symbol.asyncIterator];
|
||||
return typeof iterator === "function" ? body : null;
|
||||
}
|
||||
|
||||
@@ -13,9 +13,10 @@ export type IncomingHttpHeaders = Record<string, string | string[] | undefined>;
|
||||
* [name, value, ...] array. */
|
||||
export type UndiciHeaders = Record<string, string | string[] | undefined> | string[] | null;
|
||||
|
||||
/** The payloads the shim writes. Streams, iterables, Blob and FormData
|
||||
* bodies are outside the implemented subset. */
|
||||
export type RequestBody = string | Buffer | Uint8Array | null;
|
||||
/** The payloads the shim writes: strings and bytes with a known length,
|
||||
* and async iterables (a Node Readable, an async generator) written as a
|
||||
* stream. Blob and FormData bodies are outside the implemented subset. */
|
||||
export type RequestBody = string | Buffer | Uint8Array | AsyncIterable<Uint8Array | string> | null;
|
||||
|
||||
/** undici's Dispatcher.DispatchOptions. The method is any string, as it
|
||||
* is in 7.x's declarations (5.x's name nine). A dispatcher typed by a
|
||||
@@ -28,8 +29,9 @@ export interface DispatchOptions {
|
||||
path: string;
|
||||
method: string;
|
||||
/** undici-types declare streams and FormData here beside strings and
|
||||
* bytes; what is sent is RequestBody, and any other value is refused
|
||||
* where the request is made (request.ts). */
|
||||
* bytes; strings, bytes and async iterables are sent (a streamed body
|
||||
* with chunked framing), and any other value is refused where the
|
||||
* request is made (request.ts). */
|
||||
body?: unknown;
|
||||
headers?: UndiciHeaders;
|
||||
idempotent?: boolean;
|
||||
@@ -130,7 +132,9 @@ export interface ConnectorBuildOptions {
|
||||
maxVersion?: string;
|
||||
ciphers?: string;
|
||||
crl?: string | Buffer | (string | Buffer)[];
|
||||
ALPNProtocols?: string[] | Uint8Array[];
|
||||
/* node:tls also takes the already-encoded, length-prefixed list as one
|
||||
* Buffer/Uint8Array; undici forwards it to tls.connect unchanged. */
|
||||
ALPNProtocols?: string[] | Uint8Array[] | Uint8Array;
|
||||
localAddress?: string;
|
||||
/** any other field of the connect record is forwarded too */
|
||||
[option: string]: unknown;
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
// Programs whose installed undici is 7.x compile this module in its place
|
||||
// (see packages/compiler/src/frontend/package-shims.ts). It implements the
|
||||
// HTTP/1.1 client subset over node:net / node:tls: Dispatcher, Client, Pool,
|
||||
// Agent, request(), buildConnector, errors, the global dispatcher, fetch and
|
||||
// the diagnostics_channel publications. Anything else undici exports is not
|
||||
// Agent, ProxyAgent, EnvHttpProxyAgent, request(), buildConnector, errors, the
|
||||
// global dispatcher, fetch and the diagnostics_channel publications. Anything else undici exports is not
|
||||
// declared here, so using it is a compile-time error.
|
||||
import { Agent as CoreAgent } from "./core/agent.ts";
|
||||
import {
|
||||
@@ -19,7 +19,11 @@ import { Dispatcher } from "./core/dispatcher.ts";
|
||||
import type { ResponseData } from "./core/dispatcher.ts";
|
||||
import { installGlobalFetchDispatcher, undiciFetch } from "./core/fetch.ts";
|
||||
import type { UndiciFetchInit } from "./core/fetch.ts";
|
||||
import { EnvHttpProxyAgent as CoreEnvHttpProxyAgent } from "./core/env-http-proxy-agent.ts";
|
||||
import type { EnvHttpProxyAgentOptions } from "./core/env-http-proxy-agent.ts";
|
||||
import { Pool as CorePool, PoolStats as CorePoolStats } from "./core/pool.ts";
|
||||
import { ProxyAgent as CoreProxyAgent } from "./core/proxy-agent.ts";
|
||||
import type { ProxyAgentOptions } from "./core/proxy-agent.ts";
|
||||
import type {
|
||||
AgentOptions,
|
||||
ClientOptions,
|
||||
@@ -84,6 +88,26 @@ export declare namespace Agent {
|
||||
type DispatchOptions = import("./core/types.ts").DispatchOptions;
|
||||
}
|
||||
|
||||
export class ProxyAgent extends CoreProxyAgent {
|
||||
constructor(options: ProxyAgent.Options | string) {
|
||||
super(options, profile, (agentOptions: AgentOptions) => new Agent(agentOptions));
|
||||
}
|
||||
}
|
||||
|
||||
export declare namespace ProxyAgent {
|
||||
type Options = ProxyAgentOptions;
|
||||
}
|
||||
|
||||
export class EnvHttpProxyAgent extends CoreEnvHttpProxyAgent {
|
||||
constructor(options?: EnvHttpProxyAgent.Options) {
|
||||
super(options ?? {}, profile);
|
||||
}
|
||||
}
|
||||
|
||||
export declare namespace EnvHttpProxyAgent {
|
||||
type Options = EnvHttpProxyAgentOptions;
|
||||
}
|
||||
|
||||
export function buildConnector(options?: buildConnector.BuildOptions): buildConnector.connector {
|
||||
return coreBuildConnector(options ?? {});
|
||||
}
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
// Programs whose installed undici is 8.x compile this module in its place
|
||||
// (see packages/compiler/src/frontend/package-shims.ts). It implements the
|
||||
// HTTP/1.1 client subset over node:net / node:tls: Dispatcher, Client, Pool,
|
||||
// Agent, request(), buildConnector, errors, the global dispatcher, fetch and
|
||||
// the diagnostics_channel publications. Anything else undici exports is not
|
||||
// Agent, ProxyAgent, EnvHttpProxyAgent, request(), buildConnector, errors, the
|
||||
// global dispatcher, fetch and the diagnostics_channel publications. Anything else undici exports is not
|
||||
// declared here, so using it is a compile-time error.
|
||||
import { Agent as CoreAgent } from "./core/agent.ts";
|
||||
import {
|
||||
@@ -19,7 +19,11 @@ import { Dispatcher } from "./core/dispatcher.ts";
|
||||
import type { ResponseData } from "./core/dispatcher.ts";
|
||||
import { installGlobalFetchDispatcher, undiciFetch } from "./core/fetch.ts";
|
||||
import type { UndiciFetchInit } from "./core/fetch.ts";
|
||||
import { EnvHttpProxyAgent as CoreEnvHttpProxyAgent } from "./core/env-http-proxy-agent.ts";
|
||||
import type { EnvHttpProxyAgentOptions } from "./core/env-http-proxy-agent.ts";
|
||||
import { Pool as CorePool, PoolStats as CorePoolStats } from "./core/pool.ts";
|
||||
import { ProxyAgent as CoreProxyAgent } from "./core/proxy-agent.ts";
|
||||
import type { ProxyAgentOptions } from "./core/proxy-agent.ts";
|
||||
import type {
|
||||
AgentOptions,
|
||||
ClientOptions,
|
||||
@@ -84,6 +88,26 @@ export declare namespace Agent {
|
||||
type DispatchOptions = import("./core/types.ts").DispatchOptions;
|
||||
}
|
||||
|
||||
export class ProxyAgent extends CoreProxyAgent {
|
||||
constructor(options: ProxyAgent.Options | string) {
|
||||
super(options, profile, (agentOptions: AgentOptions) => new Agent(agentOptions));
|
||||
}
|
||||
}
|
||||
|
||||
export declare namespace ProxyAgent {
|
||||
type Options = ProxyAgentOptions;
|
||||
}
|
||||
|
||||
export class EnvHttpProxyAgent extends CoreEnvHttpProxyAgent {
|
||||
constructor(options?: EnvHttpProxyAgent.Options) {
|
||||
super(options ?? {}, profile);
|
||||
}
|
||||
}
|
||||
|
||||
export declare namespace EnvHttpProxyAgent {
|
||||
type Options = EnvHttpProxyAgentOptions;
|
||||
}
|
||||
|
||||
export function buildConnector(options?: buildConnector.BuildOptions): buildConnector.connector {
|
||||
return coreBuildConnector(options ?? {});
|
||||
}
|
||||
|
||||
@@ -127,6 +127,9 @@ export function emitFunction(emitter: LlEmitter, fn: IrFunction): string {
|
||||
emitter.frames = [];
|
||||
emitter.scopes = [];
|
||||
emitter.unwindCleanups.clear();
|
||||
emitter.unwindChainBlocks.length = 0;
|
||||
emitter.unwindScopeChains.clear();
|
||||
emitter.unwindTerminators.clear();
|
||||
emitter.unwindReleases.length = 0;
|
||||
emitter.unwindReleaseLabels.clear();
|
||||
emitter.jumpTargets = [];
|
||||
@@ -816,6 +819,20 @@ export function emitFunction(emitter: LlEmitter, fn: IrFunction): string {
|
||||
emitter.releaseScope(cleanup.entries);
|
||||
B.terminate(cleanup.terminator);
|
||||
}
|
||||
// The many-binding cleanup chain ends each block in the block it
|
||||
// continues to; LLVM would otherwise sink the blocks' release calls into
|
||||
// shared successors and choose each operand with a phi.
|
||||
B.unmergedCalls = true;
|
||||
for (const block of emitter.unwindChainBlocks) {
|
||||
B.startBlock(block.label);
|
||||
emitter.releaseScope(block.entries);
|
||||
B.br(block.next);
|
||||
}
|
||||
B.unmergedCalls = false;
|
||||
for (const [terminator, label] of emitter.unwindTerminators) {
|
||||
B.startBlock(label);
|
||||
B.terminate(terminator);
|
||||
}
|
||||
|
||||
if (emitter.usesLandingPads && emitter.currentUnwindAbi)
|
||||
B.entryAllocas.push(`${UNWIND_SLOT} = alloca { ptr, i32 }`);
|
||||
|
||||
@@ -59,6 +59,7 @@ import {
|
||||
} from "./map-number-lookup.js";
|
||||
import { RUNTIME_ABI_MARKER } from "../runtime-abi.js";
|
||||
import { bytesOfText, type TextPart, textOfPart } from "../../text-parts.js";
|
||||
import { FunctionTexts } from "./function-texts.js";
|
||||
import { threadSlotsBlockDefinitions } from "./thread-slots.js";
|
||||
import {
|
||||
ABSENT_FIELD_PAYLOAD,
|
||||
@@ -570,7 +571,11 @@ function siteUses(def: string): SiteUse[] {
|
||||
* partition the LLVM helper could reuse (native-codegen.ts). Named by its
|
||||
* function, a site keeps its name wherever its function lands. A site
|
||||
* another function or a helper also names keeps its number. */
|
||||
function nameSitesByOwner(emitter: LlEmitter, fnDefs: TextPart[]): Map<string, string> {
|
||||
function nameSitesByOwner(
|
||||
emitter: LlEmitter,
|
||||
fnDefs: TextPart[],
|
||||
spill?: (text: string) => TextPart,
|
||||
): Map<string, string> {
|
||||
const owner = new Map<string, number>();
|
||||
const usesOf: (SiteUse[] | undefined)[] = [];
|
||||
fnDefs.forEach((part, index) => {
|
||||
@@ -612,41 +617,59 @@ function nameSitesByOwner(emitter: LlEmitter, fnDefs: TextPart[]): Map<string, s
|
||||
if (parts.length === 0) return;
|
||||
parts.push(def.slice(from));
|
||||
const text = parts.join("");
|
||||
const rewritten: TextPart = typeof original === "string" ? text : bytesOfText(text);
|
||||
// A spilled module keeps the rewritten text on disk too: only its range
|
||||
// stays in memory.
|
||||
const rewritten: TextPart =
|
||||
spill !== undefined ? spill(text) : typeof original === "string" ? text : bytesOfText(text);
|
||||
fnDefs[index] = rewritten;
|
||||
if (emitter.fnDefText.get(fn.name) === original) emitter.fnDefText.set(fn.name, rewritten);
|
||||
});
|
||||
return renames;
|
||||
}
|
||||
|
||||
/** The emitted function texts past this many characters are kept as UTF-8
|
||||
* bytes, off the V8 heap: on a large program they are most of the heap the
|
||||
* build holds while it emits (see `emitModuleParts`). A program whose text
|
||||
* stays under it keeps the strings and pays no re-decoding. */
|
||||
/** The emitted function texts past this many characters leave the V8 heap: on
|
||||
* a large program they are most of the heap the build holds while it emits
|
||||
* (see `emitModuleParts`). They are written to a temporary file, and only
|
||||
* their byte ranges stay in memory. A program whose text stays under the
|
||||
* threshold keeps its strings and touches no file. */
|
||||
const OFF_HEAP_TEXT_CHARS = 16 * 1024 * 1024;
|
||||
|
||||
export function emitModuleParts(emitter: LlEmitter): TextPart[] {
|
||||
// Function bodies first (the literal/unit/fn-value tables fill as they
|
||||
// emit), then the file assembles around them — the runtime ABI’s order.
|
||||
const chunks = emitter.targetOptions.functionChunks ?? 1;
|
||||
let texts: FunctionTexts | null = null;
|
||||
const fnDefs: TextPart[] =
|
||||
(chunks > 1 ? emitFunctionsInChunks(emitter, chunks) : null) ??
|
||||
emitFunctionsOnWorkers(emitter, emitter.targetOptions.functionWorkers ?? 1) ??
|
||||
[];
|
||||
if (fnDefs.length === 0) {
|
||||
// A function's whole text is built once and then held until the file is
|
||||
// written; on a very large program that holding is the heap's peak, and a
|
||||
// 2 GB heap cannot hold the text beside the typed IR. Past the threshold,
|
||||
// every text emitted so far and every later one is kept as UTF-8 bytes,
|
||||
// which V8 does not count in its heap; the passes that read a text then
|
||||
// decode it one at a time.
|
||||
// written; on a very large program that holding is the heap's peak. Past
|
||||
// the threshold every text emitted so far and every later one is written
|
||||
// to a temporary file, and the passes that read a text read it back one at
|
||||
// a time (FunctionTexts). A build with a pass that reads the module's
|
||||
// whole text after the emission (the unwinding bridge, the CPU-copy
|
||||
// passes) keeps the texts on the heap instead, as it always has: those
|
||||
// passes need the text as it was emitted, before its entry alignment.
|
||||
const spill = !emitter.keepsWholeText();
|
||||
const offHeapChars = emitter.targetOptions.offHeapTextChars ?? OFF_HEAP_TEXT_CHARS;
|
||||
let chars = 0;
|
||||
let offHeap = false;
|
||||
for (const fn of emitter.mod.functions) {
|
||||
const def = emitter.emitFunction(fn);
|
||||
chars += def.length;
|
||||
if (!offHeap && chars >= offHeapChars) {
|
||||
if (spill && texts === null && chars >= offHeapChars) {
|
||||
texts = new FunctionTexts();
|
||||
for (let i = 0; i < fnDefs.length; i++) {
|
||||
const spilled = texts.add(textOfPart(fnDefs[i]!));
|
||||
fnDefs[i] = spilled;
|
||||
emitter.fnDefText.set(emitter.mod.functions[i]!.name, spilled);
|
||||
}
|
||||
}
|
||||
// Without a spill, a very large text is kept as UTF-8 bytes past the
|
||||
// threshold, which V8 does not count in its heap.
|
||||
if (!spill && !offHeap && chars >= offHeapChars) {
|
||||
offHeap = true;
|
||||
for (const [name, part] of emitter.fnDefText) {
|
||||
if (typeof part === "string") emitter.fnDefText.set(name, bytesOfText(part));
|
||||
@@ -656,14 +679,17 @@ export function emitModuleParts(emitter: LlEmitter): TextPart[] {
|
||||
if (converted !== undefined) fnDefs[i] = converted;
|
||||
}
|
||||
}
|
||||
const part = offHeap ? bytesOfText(def) : def;
|
||||
const part: TextPart = texts !== null ? texts.add(def) : offHeap ? bytesOfText(def) : def;
|
||||
fnDefs.push(part);
|
||||
emitter.fnDefText.set(fn.name, part);
|
||||
relieveHeapPressure();
|
||||
}
|
||||
}
|
||||
emitter.selectStacklessAsync(fnDefs);
|
||||
const siteNames = nameSitesByOwner(emitter, fnDefs);
|
||||
const store = texts;
|
||||
const spillText = store === null ? undefined : (text: string): TextPart => store.add(text);
|
||||
emitter.selectStacklessAsync(fnDefs, spillText);
|
||||
const siteNames = nameSitesByOwner(emitter, fnDefs, spillText);
|
||||
if (store !== null) store.finish();
|
||||
const errorViews: string[] = [];
|
||||
for (const property of ERROR_READER_PROPERTIES) {
|
||||
const reader = errorReaderName(property);
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
VOID,
|
||||
type IrExpr,
|
||||
type IrFunction,
|
||||
type IrLocal,
|
||||
type IrModule,
|
||||
type IrStmt,
|
||||
type IrType,
|
||||
@@ -262,6 +263,56 @@ test("a statement's throw sites share the releases of the values it holds", () =
|
||||
expect(growth).toBeLessThan(3 * (stringReleases(medium!) - stringReleases(small!)));
|
||||
});
|
||||
|
||||
/** `n` owned string bindings, each followed by a may-throw call: every call
|
||||
* site sees one more live binding than the previous site, the shape of a
|
||||
* factory that declares a binding between two concatenations. */
|
||||
function wideModule(n: number): IrModule {
|
||||
const module = moduleFor([]);
|
||||
const work = module.functions[1]!;
|
||||
const locals: IrLocal[] = [];
|
||||
const body: IrStmt[] = [];
|
||||
for (let i = 0; i < n; i++) {
|
||||
locals.push({ id: `w${i}`, name: `w${i}`, type: STRING, mutable: true });
|
||||
const owned: IrExpr = {
|
||||
kind: "strConcat",
|
||||
left: literal("x"),
|
||||
right: literal("y"),
|
||||
type: STRING,
|
||||
loc,
|
||||
};
|
||||
body.push({ kind: "varDecl", localId: `w${i}`, init: owned, loc });
|
||||
body.push(call());
|
||||
}
|
||||
work.locals = [...work.locals, ...locals];
|
||||
// The param rebinds moduleFor appends stay: they make the parameters owned.
|
||||
work.body = [...body, ...work.body];
|
||||
return module;
|
||||
}
|
||||
|
||||
test("throw sites with many live bindings release from a shared chain", () => {
|
||||
// Few live bindings keep one cleanup block per site.
|
||||
const few = workBody(emitLlvmModule(wideModule(8)));
|
||||
expect(few).not.toMatch(/^exc\.release\d+:$/m);
|
||||
const releases = (n: number) => stringReleases(workBody(emitLlvmModule(wideModule(n))));
|
||||
// Each site adds one binding and continues into the previous site's
|
||||
// releases: the calls grow with the bindings, not with their square.
|
||||
const small = releases(100);
|
||||
const medium = releases(200);
|
||||
const large = releases(400);
|
||||
expect(medium - small).toBeGreaterThan(0);
|
||||
expect(large - medium).toBeLessThan(2.5 * (medium - small));
|
||||
// Whichever statement values each site also holds add a few per site; the
|
||||
// bindings alone would be one per site. The old emission wrote the whole
|
||||
// live list at every site: quadratic, about 20,000 calls at 200 bindings.
|
||||
expect(large).toBeLessThan(6 * 400);
|
||||
// The chain keeps every release in its own block with the no-merge mark.
|
||||
const blocks = [
|
||||
...workBody(emitLlvmModule(wideModule(200))).matchAll(/^exc\.release\d+:\n((?: [^\n]*\n)+)/gm),
|
||||
];
|
||||
expect(blocks.length).toBeGreaterThan(0);
|
||||
for (const block of blocks) expect(block[1]!).toMatch(/br label %exc\.(?:release|cleanup)\d+\n$/);
|
||||
});
|
||||
|
||||
test("detached exit defines the runtime opt-in symbol only when requested", () => {
|
||||
const module = moduleFor([call()]);
|
||||
const plain = emitLlvmModule(module);
|
||||
|
||||
@@ -3,7 +3,7 @@ import { loopEntryInlines } from "./loop-entry-versions.js";
|
||||
import { alignFunctionEntries } from "./function-alignment.js";
|
||||
import type { FunctionLayout } from "./function-layout.js";
|
||||
import type { CompilationTiming } from "../../timing.js";
|
||||
import { bytesOfText, type TextPart, textOfPart } from "../../text-parts.js";
|
||||
import { bytesOfText, releaseTextParts, type TextPart, textOfPart } from "../../text-parts.js";
|
||||
import { relieveHeapPressure } from "../../heap-pressure.js";
|
||||
import { analyzeFrameEscapes, type FrameEscapes } from "./frame-escapes.js";
|
||||
import { wasmBoundsChecks } from "./wasm-modules.js";
|
||||
@@ -1158,15 +1158,21 @@ function verifyRetriedEmission(
|
||||
}
|
||||
|
||||
export function emitLlvmModule(input: IrModule, options: LlvmTargetOptions = {}): string {
|
||||
return emitModuleText(input, options).map(textOfPart).join("\n");
|
||||
const parts = emitModuleText(input, options);
|
||||
const text = parts.map(textOfPart).join("\n");
|
||||
releaseTextParts(parts);
|
||||
return text;
|
||||
}
|
||||
|
||||
/** emitLlvmModule's text as parts that concatenate to it, without the copy
|
||||
* that joining them makes: a large program's text is 150 MB. */
|
||||
export function emitLlvmModuleParts(input: IrModule, options: LlvmTargetOptions = {}): string[] {
|
||||
return emitModuleText(input, options).flatMap((part, index) =>
|
||||
const parts = emitModuleText(input, options);
|
||||
const out = parts.flatMap((part, index) =>
|
||||
index === 0 ? [textOfPart(part)] : ["\n", textOfPart(part)],
|
||||
);
|
||||
releaseTextParts(parts);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Keep large translation units below the host's single-string limit. */
|
||||
@@ -2183,11 +2189,29 @@ export class LlEmitter {
|
||||
/** Scope slots dominate every throw site. Share their exceptional cleanup
|
||||
* for identical live bindings and handlers; statement temporaries stay at
|
||||
* their own throw sites because their SSA values are path-dependent,
|
||||
* unless a site holds many of them (unwindReleases). */
|
||||
* unless a site holds many of them (unwindReleases). A live list longer
|
||||
* than UNWIND_CHAIN_MIN_VALUES bindings releases from a shared chain
|
||||
* instead (unwindChainBlocks): a throw site adds only a block for the bindings
|
||||
* declared since the previous site rather than one full release sequence
|
||||
* per site. */
|
||||
readonly unwindCleanups = new Map<
|
||||
string,
|
||||
{ label: string; entries: LlScopeEntry[]; terminator: string }
|
||||
>();
|
||||
/** The blocks of the many-binding cleanup chain (emitUnwind), in creation
|
||||
* order: each releases its bindings in order and branches to `next`. */
|
||||
readonly unwindChainBlocks: { label: string; entries: LlScopeEntry[]; next: string }[] = [];
|
||||
/** A scope's chain blocks by the block they continue to: each entry
|
||||
* releases the scope's first `count` bindings and then continues. A throw
|
||||
* site whose scope has grown since releases only the new bindings and
|
||||
* continues into the previous chain. */
|
||||
readonly unwindScopeChains = new Map<
|
||||
LlScopeEntry[],
|
||||
Map<string, { count: number; label: string }[]>
|
||||
>();
|
||||
/** The block ending a chain (the handler branch or the dummy return), by
|
||||
* its terminator text. */
|
||||
readonly unwindTerminators = new Map<string, string>();
|
||||
/** The shared release blocks of throw sites that hold more than
|
||||
* UNWIND_CHAIN_MIN_VALUES statement values (emitUnwind), in creation
|
||||
* order: each releases one value and branches to `next`. */
|
||||
@@ -3565,14 +3589,18 @@ export class LlEmitter {
|
||||
}
|
||||
|
||||
emit(): string {
|
||||
return this.emitParts().map(textOfPart).join("\n");
|
||||
const parts = this.emitParts();
|
||||
const text = parts.map(textOfPart).join("\n");
|
||||
releaseTextParts(parts);
|
||||
return text;
|
||||
}
|
||||
emitParts(): TextPart[] {
|
||||
const parts = emitParts(this);
|
||||
const bridged = this.unwindAbi.size > 0 ? bridgePlainUnwindCalls(parts) : parts;
|
||||
// The CPU-copy passes read whole functions across a part, so a build that
|
||||
// copies code (`--cpu-dispatch`) decodes its text as it always did;
|
||||
// other builds keep the function texts as bytes when they are large.
|
||||
// copies code (`--cpu-dispatch`) decodes its text as it always did. A
|
||||
// large module keeps its function texts in a temporary file only when no
|
||||
// such pass runs (keepsWholeText).
|
||||
const out =
|
||||
this.cpuCopies === null
|
||||
? this.keepCopyBodiesOutOfLine
|
||||
@@ -3710,6 +3738,21 @@ export class LlEmitter {
|
||||
``,
|
||||
];
|
||||
}
|
||||
/** Whether a pass after the emission reads the module's whole text: the
|
||||
* unwinding bridge and the CPU-copy passes rewrite every function they see,
|
||||
* and they need each text as it was emitted. A build with one keeps the
|
||||
* texts on the heap; otherwise a large module's texts are written to a
|
||||
* temporary file as they are emitted (FunctionTexts). */
|
||||
keepsWholeText(): boolean {
|
||||
// An ELF worker executable rewrites every thread-local access in the
|
||||
// module's text, so it reads each function whole, as the passes above do.
|
||||
return (
|
||||
this.unwindAbi.size > 0 ||
|
||||
this.cpuCopies !== null ||
|
||||
this.keepCopyBodiesOutOfLine ||
|
||||
this.executableTls
|
||||
);
|
||||
}
|
||||
emitModuleParts(): TextPart[] {
|
||||
return emitModuleParts(this);
|
||||
}
|
||||
@@ -3893,7 +3936,7 @@ export class LlEmitter {
|
||||
* through the resolution procedure, which never parks the body: a promise
|
||||
* it holds is adopted by a reaction on it (scr_promise_resolve_dyn). The
|
||||
* runtime traps if a stackless body ever parks. */
|
||||
selectStacklessAsync(fnDefs: TextPart[]): void {
|
||||
selectStacklessAsync(fnDefs: TextPart[], keepText?: (text: string) => TextPart): void {
|
||||
if (!this.stacklessAsyncAllowed) return;
|
||||
const parks = this.parkingFunctions();
|
||||
if (parks === null) return;
|
||||
@@ -3925,7 +3968,8 @@ export class LlEmitter {
|
||||
this.stacklessAsync.delete(fn.name);
|
||||
return;
|
||||
}
|
||||
const part = bytesOfText(coroText);
|
||||
// A spilled module keeps the coroutine body on disk with the rest.
|
||||
const part = keepText === undefined ? bytesOfText(coroText) : keepText(coroText);
|
||||
fnDefs[index] = part;
|
||||
this.fnDefText.set(fn.name, part);
|
||||
});
|
||||
@@ -5309,15 +5353,16 @@ export class LlEmitter {
|
||||
? "ret i1 false"
|
||||
: "ret ptr null";
|
||||
}
|
||||
// Copy the entries now: later declarations extend these lexical scopes.
|
||||
// Release order and the handler are part of the shared block's identity.
|
||||
// Copy the scopes now: later declarations extend these lexical scopes.
|
||||
// Their bindings release in releaseScope's order: each scope's bindings
|
||||
// in declaration order, its arena list after them.
|
||||
const liveScopes: LlScopeEntry[][] = [];
|
||||
const entries: LlScopeEntry[] = [];
|
||||
let key = terminator;
|
||||
for (let i = this.scopes.length - 1; i >= scopeDepth; i--) {
|
||||
for (const entry of this.scopes[i]!) {
|
||||
entries.push(entry);
|
||||
key += `\0${entry.slot}\0${entry.boxed ? "@scr_box_release" : releaseSym(this.shapeHost, entry.type)}`;
|
||||
}
|
||||
const scope = this.scopes[i]!;
|
||||
liveScopes.push(scope);
|
||||
for (const entry of scope) if (entry.arena !== true) entries.push(entry);
|
||||
for (const entry of scope) if (entry.arena === true) entries.push(entry);
|
||||
}
|
||||
if (entries.length === 0 && !chained) {
|
||||
if (
|
||||
@@ -5333,14 +5378,88 @@ export class LlEmitter {
|
||||
this.B.terminate(terminator);
|
||||
return;
|
||||
}
|
||||
let cleanup = this.unwindCleanups.get(key);
|
||||
if (!cleanup) {
|
||||
cleanup = { label: this.B.newLabel("exc.cleanup"), entries, terminator };
|
||||
this.unwindCleanups.set(key, cleanup);
|
||||
let cleanup: string;
|
||||
const chainedScopes =
|
||||
entries.length > UNWIND_CHAIN_MIN_VALUES && !entries.some((entry) => entry.arena === true);
|
||||
if (!chainedScopes) {
|
||||
// Few live bindings: one block releases them all and ends in the
|
||||
// handler (or the dummy return). Release order and the handler are
|
||||
// part of the block's identity.
|
||||
let key = terminator;
|
||||
for (const entry of entries)
|
||||
key += `\0${entry.slot}\0${entry.boxed ? "@scr_box_release" : releaseSym(this.shapeHost, entry.type)}`;
|
||||
let shared = this.unwindCleanups.get(key);
|
||||
if (!shared) {
|
||||
shared = { label: this.B.newLabel("exc.cleanup"), entries, terminator };
|
||||
this.unwindCleanups.set(key, shared);
|
||||
}
|
||||
cleanup = shared.label;
|
||||
} else {
|
||||
// Many live bindings: release from the shared chain, so a site adds
|
||||
// only the bindings declared since the previous site rather than one
|
||||
// full release sequence per site.
|
||||
cleanup = this.unwindScopeChain(liveScopes, 0, terminator);
|
||||
}
|
||||
// The shared blocks end in the cleanup, which is then the scope's
|
||||
// releases (none for a function without bindings) and the terminator.
|
||||
this.B.br(chained ? this.unwindReleaseChain(frameDepth, cleanup.label) : cleanup.label);
|
||||
this.B.br(chained ? this.unwindReleaseChain(frameDepth, cleanup) : cleanup);
|
||||
}
|
||||
|
||||
/** The head of the shared blocks that release the live scopes from
|
||||
* `depth` outward, innermost first, and then end with `terminator`.
|
||||
*
|
||||
* A scope's bindings live in its scope array, which only ever gains
|
||||
* entries at the end, so the release of an earlier throw site is a prefix
|
||||
* of a later site's. Each block releases the bindings a site added since
|
||||
* the last block at that scope and continues into the previous chain; a
|
||||
* function that declares a binding between every two throw sites emits
|
||||
* one block per site instead of one full release sequence per site.
|
||||
* Scopes with arena lists keep the single-block cleanup (emitUnwind):
|
||||
* their lists drop after all the scope's bindings, which a prefix chain
|
||||
* cannot order across sites. */
|
||||
private unwindScopeChain(
|
||||
scopes: readonly LlScopeEntry[][],
|
||||
depth: number,
|
||||
terminator: string,
|
||||
): string {
|
||||
const next =
|
||||
depth + 1 < scopes.length
|
||||
? this.unwindScopeChain(scopes, depth + 1, terminator)
|
||||
: this.unwindTerminator(terminator);
|
||||
const scope = scopes[depth]!;
|
||||
if (scope.length === 0) return next;
|
||||
let byNext = this.unwindScopeChains.get(scope);
|
||||
if (byNext === undefined) {
|
||||
byNext = new Map();
|
||||
this.unwindScopeChains.set(scope, byNext);
|
||||
}
|
||||
let chains = byNext.get(next);
|
||||
if (chains === undefined) {
|
||||
chains = [];
|
||||
byNext.set(next, chains);
|
||||
}
|
||||
let previous: { count: number; label: string } | undefined;
|
||||
for (const chain of chains)
|
||||
if (chain.count <= scope.length && (previous === undefined || chain.count > previous.count))
|
||||
previous = chain;
|
||||
if (previous !== undefined && previous.count === scope.length) return previous.label;
|
||||
const label = this.B.newLabel("exc.release");
|
||||
this.unwindChainBlocks.push({
|
||||
label,
|
||||
entries: scope.slice(previous?.count ?? 0),
|
||||
next: previous?.label ?? next,
|
||||
});
|
||||
chains.push({ count: scope.length, label });
|
||||
return label;
|
||||
}
|
||||
|
||||
/** The label of the block that only ends the chain: the handler branch or
|
||||
* the dummy return, shared by every chain with the same terminator. */
|
||||
private unwindTerminator(terminator: string): string {
|
||||
let label = this.unwindTerminators.get(terminator);
|
||||
if (label === undefined) {
|
||||
label = this.B.newLabel("exc.cleanup");
|
||||
this.unwindTerminators.set(terminator, label);
|
||||
}
|
||||
return label;
|
||||
}
|
||||
|
||||
/** The label of the shared blocks that release the statement frames from
|
||||
|
||||
@@ -128,7 +128,7 @@ export function emitDynamicExpr(
|
||||
// compile time.
|
||||
const t = B.tmp();
|
||||
const name =
|
||||
e.fnName !== undefined && e.fnName !== ""
|
||||
e.fnName !== undefined
|
||||
? e.fnName
|
||||
: e.value.kind === "closure" && e.value.adapts !== true
|
||||
? host.closureNameOf(e.value.fnName)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { bytesOfText, type TextPart, textOfPart } from "../../text-parts.js";
|
||||
import { bytesOfText, isFileTextPart, type TextPart, textOfPart } from "../../text-parts.js";
|
||||
|
||||
/** The alignment of every emitted function's entry. Each definition pads to
|
||||
* it, so a change in one function's size cannot move another function's code
|
||||
@@ -6,12 +6,13 @@ import { bytesOfText, type TextPart, textOfPart } from "../../text-parts.js";
|
||||
* the alignment, and the timing, they had before the change. */
|
||||
export const FUNCTION_ENTRY_ALIGNMENT = 64;
|
||||
|
||||
/** Adds the entry alignment to every function definition in `parts`, after
|
||||
* its parameter list (where LLVM's grammar puts it, ahead of the attribute
|
||||
* group and the personality). A definition that already names an alignment
|
||||
* keeps it, so aligning a region the emitter already aligned is a no-op. */
|
||||
export function alignFunctionEntries(parts: TextPart[]): TextPart[] {
|
||||
const align = (line: string): string => {
|
||||
/** `text` with the entry alignment added to each of its function definitions,
|
||||
* after the parameter list (where LLVM's grammar puts it, ahead of the
|
||||
* attribute group and the personality). A definition that already names an
|
||||
* alignment keeps it, so aligning text that is already aligned is a no-op. */
|
||||
export function alignFunctionText(text: string): string {
|
||||
if (!text.includes("define ")) return text;
|
||||
return text.replace(/^define .*$/gm, (line) => {
|
||||
const open = line.indexOf("(", line.indexOf("@"));
|
||||
if (open < 0) return line;
|
||||
let depth = 0;
|
||||
@@ -24,15 +25,22 @@ export function alignFunctionEntries(parts: TextPart[]): TextPart[] {
|
||||
}
|
||||
}
|
||||
return line;
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** Adds the entry alignment to every function definition in `parts`. A file
|
||||
* part is skipped: the module's own function texts are aligned as they are
|
||||
* written to their file (`FunctionTexts.add`), so the text it names has the
|
||||
* alignment already. */
|
||||
export function alignFunctionEntries(parts: TextPart[]): TextPart[] {
|
||||
// Replace in place: the self-compiled compiler emits hundreds of
|
||||
// megabytes of definitions, and mapping into a second array would keep
|
||||
// every original string alive beside its aligned copy until the pass ends.
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const part = parts[i]!;
|
||||
if (isFileTextPart(part)) continue;
|
||||
const text = textOfPart(part);
|
||||
if (!text.includes("define ")) continue;
|
||||
const aligned = text.replace(/^define .*$/gm, (line) => align(line));
|
||||
const aligned = alignFunctionText(text);
|
||||
if (aligned === text) continue;
|
||||
parts[i] = typeof part === "string" ? aligned : bytesOfText(aligned);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
/* A large module's function texts kept on disk while the module emits. */
|
||||
import { closeSync, lstatSync, mkdtempSync, openSync, rmSync, statSync, writeSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { type FileTextPart, setTemporaryDirectoryReleaser } from "../../text-parts.js";
|
||||
import { alignFunctionText } from "./function-alignment.js";
|
||||
|
||||
/** The stores whose temporary files may still be on disk: a build that ends
|
||||
* without writing its parts (an error, a cached artifact, a pass that reads
|
||||
* the text from the parts) removes them at exit. */
|
||||
const live: FunctionTexts[] = [];
|
||||
/** Each store whose directory has not been released, with the device and inode
|
||||
* it was created as: the exit cleanup removes a directory only while it is
|
||||
* still that directory, never a path something else has taken since. */
|
||||
const owned = new Map<string, { dev: number; ino: number }>();
|
||||
|
||||
/** Whether `dir` is still the directory recorded as `identity` (not a link,
|
||||
* not a replacement). */
|
||||
function stillOwned(dir: string, identity: { dev: number; ino: number }): boolean {
|
||||
const info = lstatSync(dir, { throwIfNoEntry: false });
|
||||
return (
|
||||
info !== undefined &&
|
||||
info.isDirectory() &&
|
||||
!info.isSymbolicLink() &&
|
||||
info.dev === identity.dev &&
|
||||
info.ino === identity.ino
|
||||
);
|
||||
}
|
||||
|
||||
// A release removes a directory once: the release says so, and the exit
|
||||
// cleanup no longer knows the path.
|
||||
setTemporaryDirectoryReleaser((dir) => {
|
||||
const identity = owned.get(dir);
|
||||
if (identity === undefined) return false;
|
||||
owned.delete(dir);
|
||||
return stillOwned(dir, identity);
|
||||
});
|
||||
let hooked = false;
|
||||
|
||||
function removeAll(): void {
|
||||
for (const texts of live.splice(0)) texts.dispose();
|
||||
for (const [dir, identity] of [...owned]) {
|
||||
owned.delete(dir);
|
||||
if (stillOwned(dir, identity)) rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** A module's function texts in a temporary file: each text is written as it
|
||||
* is emitted, and only its byte range stays on the heap. On a large program
|
||||
* the text is most of the memory a build holds while it emits (940 MB of the
|
||||
* compiler's own program), and the whole-module passes read it back a text at
|
||||
* a time instead. The texts are stored aligned (`alignFunctionText`), so the
|
||||
* final alignment pass skips them. */
|
||||
export class FunctionTexts {
|
||||
private readonly dir: string;
|
||||
private readonly file: string;
|
||||
private fd: number;
|
||||
private size = 0;
|
||||
|
||||
constructor() {
|
||||
this.dir = mkdtempSync(join(tmpdir(), "scriptc-emit-text-"));
|
||||
this.file = join(this.dir, "functions.ll");
|
||||
this.fd = openSync(this.file, "w");
|
||||
const info = statSync(this.dir);
|
||||
owned.set(this.dir, { dev: info.dev, ino: info.ino });
|
||||
live.push(this);
|
||||
if (!hooked) {
|
||||
hooked = true;
|
||||
try {
|
||||
process.once("exit", removeAll);
|
||||
} catch {
|
||||
// A host without process events releases the file when it is written.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes `text` after the texts already stored, and answers its range. */
|
||||
add(text: string): FileTextPart {
|
||||
const bytes = Buffer.from(alignFunctionText(text), "utf8");
|
||||
for (let offset = 0; offset < bytes.length;) {
|
||||
offset += writeSync(this.fd, bytes, offset, bytes.length - offset);
|
||||
}
|
||||
const part: FileTextPart = {
|
||||
file: this.file,
|
||||
offset: this.size,
|
||||
length: bytes.length,
|
||||
temporary: true,
|
||||
};
|
||||
this.size += bytes.length;
|
||||
return part;
|
||||
}
|
||||
|
||||
/** Stops writing: every text the module keeps is in the file. */
|
||||
finish(): void {
|
||||
if (this.fd < 0) return;
|
||||
closeSync(this.fd);
|
||||
this.fd = -1;
|
||||
}
|
||||
|
||||
/** Removes the file (and stops writing). */
|
||||
dispose(): void {
|
||||
this.finish();
|
||||
const identity = owned.get(this.dir);
|
||||
owned.delete(this.dir);
|
||||
if (identity !== undefined && stillOwned(this.dir, identity))
|
||||
rmSync(this.dir, { recursive: true, force: true });
|
||||
const at = live.indexOf(this);
|
||||
if (at >= 0) live.splice(at, 1);
|
||||
}
|
||||
}
|
||||
@@ -194,6 +194,28 @@ export function emitFilesystemLibCall(host: LlvmEmitterContext, e: LibCallExpr):
|
||||
// The value form reports DEP0187 on a next tick, so the loop runs even when
|
||||
// nothing else in the program is asynchronous.
|
||||
if (e.fn === "fs.existsSyncValue") host.usesTimers = true;
|
||||
if (e.fn === "fsp.realpathDyn") {
|
||||
// fs.promises.realpath(path, options): getOptions reads the members,
|
||||
// then the binding resolves with the one encoding read the promise
|
||||
// entry point performs (Node's fsp form passes options.encoding to the
|
||||
// binding directly). settled_ref turns a pending getter exception into
|
||||
// the promise's rejection and keeps the answer it returned otherwise.
|
||||
const args = e.args.map((a) => host.emitExpr(a));
|
||||
host.declare(`declare ptr @scr_fs_realpath_value(ptr, ptr, i1 zeroext)`);
|
||||
const value = B.tmp();
|
||||
B.line(
|
||||
`${value} = call ptr @scr_fs_realpath_value(ptr ${args[0]!.name}, ptr ${args[1]!.name}, i1 true)`,
|
||||
);
|
||||
host.declare(`declare ptr @scr_promise_settled_ref(ptr, ptr, ptr, ptr)`);
|
||||
host.declare(`declare ptr @scr_dyn_retain_v(ptr)`);
|
||||
host.declare(`declare void @scr_dyn_release_v(ptr)`);
|
||||
host.declare(`declare void @scr_dyn_trace_v(ptr, ptr, ptr)`);
|
||||
const promise = B.tmp();
|
||||
B.line(
|
||||
`${promise} = call ptr @scr_promise_settled_ref(ptr ${value}, ptr @scr_dyn_retain_v, ptr @scr_dyn_release_v, ptr @scr_dyn_trace_v)`,
|
||||
);
|
||||
return host.own({ name: promise, type: e.type });
|
||||
}
|
||||
const alwaysThrowSym = FS_ALWAYS_THROW_SYMS[e.fn];
|
||||
if (alwaysThrowSym !== undefined) {
|
||||
return emitAlwaysThrowLibCall(host, e, alwaysThrowSym);
|
||||
|
||||
@@ -2350,6 +2350,7 @@ export const LIB_FN_SYMS: Record<string, string> = {
|
||||
"process.onWarning": "scr_process_on_warning",
|
||||
"process.offWarning": "scr_process_off_warning",
|
||||
"process.emit": "scr_process_emit_named",
|
||||
"process.emitSignal": "scr_process_emit_signal",
|
||||
"process.emitError": "scr_process_emit_error",
|
||||
"process.emitWarning": "scr_process_emit_warning",
|
||||
"process.emitWarningText": "scr_process_emit_warning_text",
|
||||
|
||||
@@ -4,7 +4,7 @@ import type { IrExpr, IrModule, IrStmt } from "../../ir/ir.js";
|
||||
import { eachStringField } from "../../ir/fields.generated.js";
|
||||
import { eachNodeOfKinds, type IrNodeIndex } from "../../ir/node-index.js";
|
||||
import { InternalCompilerError } from "../../errors.js";
|
||||
import { flatText, bytesOfText, type TextPart, textOfPart } from "../../text-parts.js";
|
||||
import { flatText, bytesOfPart, bytesOfText, type TextPart, textOfPart } from "../../text-parts.js";
|
||||
|
||||
/** The kinds of every recorded node, for eachNodeOfKinds over whole bodies. */
|
||||
const EVERY_KIND: ReadonlySet<string> = new Set();
|
||||
@@ -643,7 +643,7 @@ export function bridgePlainUnwindCalls(parts: TextPart[]): TextPart[] {
|
||||
? prefix
|
||||
: typeof first === "string"
|
||||
? `${prefix}${first}`
|
||||
: Buffer.concat([Buffer.from(prefix, "utf8"), Buffer.from(first.subarray(0))]);
|
||||
: Buffer.concat([Buffer.from(prefix, "utf8"), Buffer.from(bytesOfPart(first))]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ import {
|
||||
type NativeProfileMatch,
|
||||
type NativeProfileOptions,
|
||||
} from "./native-profile.js";
|
||||
import { type TextPart, writeTextParts } from "../text-parts.js";
|
||||
import { bytesOfPart, isFileTextPart, type TextPart, writeTextParts } from "../text-parts.js";
|
||||
import { ensureExecutable } from "../executable-mode.js";
|
||||
|
||||
import {
|
||||
@@ -112,7 +112,7 @@ export function isLlvmFile(llvm: LlvmInput): llvm is LlvmFile {
|
||||
export function llvmInputBytes(llvm: LlvmInput): number {
|
||||
if (isLlvmFile(llvm)) return llvm.bytes;
|
||||
return (typeof llvm === "string" ? [llvm] : llvm).reduce(
|
||||
(bytes, part) => bytes + Buffer.byteLength(part),
|
||||
(bytes, part) => bytes + (isFileTextPart(part) ? part.length : Buffer.byteLength(part)),
|
||||
0,
|
||||
);
|
||||
}
|
||||
@@ -361,7 +361,7 @@ function cacheKey(
|
||||
if (isLlvmFile(options.llvm)) updateHashFromFile(hash, options.llvm.file);
|
||||
else
|
||||
for (const part of typeof options.llvm === "string" ? [options.llvm] : options.llvm)
|
||||
hash.update(part);
|
||||
hash.update(isFileTextPart(part) ? bytesOfPart(part) : part);
|
||||
return (
|
||||
hash
|
||||
.update("\0")
|
||||
|
||||
@@ -54,6 +54,7 @@ import type { IslandModule, IslandPackage, NodeIslandSet } from "../node-islands
|
||||
import {
|
||||
classifyDiagnostic,
|
||||
classifyMarker,
|
||||
classifyRefusal,
|
||||
isIslandReasonCode,
|
||||
} from "../node-islands/classify.js";
|
||||
import { packageDirOf, packageVersionOf } from "../node-islands/origin.js";
|
||||
@@ -1481,12 +1482,25 @@ function refusalIslands(
|
||||
// A refusal whose directory cannot be resolved has nothing to island;
|
||||
// the fatal diagnostic keeps it visible.
|
||||
if (dir === null) continue;
|
||||
// The class and reason the island report gives this refusal: both paths
|
||||
// name one island the same way (a createRequire refusal is the runtime
|
||||
// class, rule R1.2, reason dynamic-require).
|
||||
const classified = classifyRefusal(entry.detail ?? "", {
|
||||
package: entry.package,
|
||||
kind: "offender",
|
||||
diag: null,
|
||||
});
|
||||
grown.set(entry.package, {
|
||||
name: entry.package,
|
||||
version: packageVersionOf(dir),
|
||||
dir,
|
||||
class: "packaging",
|
||||
reason: entry.detail ?? "its static compilation was refused",
|
||||
class: classified?.class ?? "packaging",
|
||||
// A classified rule names the reason id; every other refusal keeps its
|
||||
// own detail, which names the construct.
|
||||
reason:
|
||||
classified !== null && classified.rule !== null
|
||||
? classified.reason
|
||||
: (entry.detail ?? "its static compilation was refused"),
|
||||
});
|
||||
}
|
||||
return grown.size === known.size ? null : grown;
|
||||
|
||||
@@ -66,12 +66,39 @@ export function analyzeWithFrontend(
|
||||
functionsSkipped: 0,
|
||||
};
|
||||
|
||||
// A refused package the auto policy islands on a build's first load is
|
||||
// not a coverage blocker: the build runs it in Node (executable/
|
||||
// prepare.ts refusalIslands), and the island section below reports it
|
||||
// with the class classifyRefusal gives. Only the refusals the build
|
||||
// keeps fatal stay SC2013 here.
|
||||
// The same installed-directory check prepare.ts applies before it
|
||||
// islands a refusal: a package Node cannot resolve from the import site
|
||||
// has nothing to island, so its refusal stays fatal.
|
||||
const installedDirOf = (fromFile: string, name: string): string | null => {
|
||||
const js =
|
||||
resolveBareModule(fromFile, name, "js-only") ??
|
||||
resolveBareModule(fromFile, name, "js-only", "require");
|
||||
if (js === null) return null;
|
||||
return packageDirOf(js.typesFile)?.dir ?? js.workspaceDir ?? null;
|
||||
};
|
||||
const islandedRefusal = (entry: { package: string; status: string }): boolean => {
|
||||
if (
|
||||
policy.mode !== "auto" ||
|
||||
entry.status !== "refused" ||
|
||||
policy.forcedNative.has(entry.package) ||
|
||||
policy.unloaded.has(entry.package)
|
||||
)
|
||||
return false;
|
||||
const site = fe.npmImportSites.get(entry.package);
|
||||
return site !== undefined && installedDirOf(site.file, entry.package) !== null;
|
||||
};
|
||||
const preflight = [
|
||||
...fe.preflight,
|
||||
...fe.npmStatic
|
||||
.filter(
|
||||
(entry) =>
|
||||
entry.status === "refused" &&
|
||||
!islandedRefusal(entry) &&
|
||||
!Object.keys(opts.externalTypes ?? {}).some(
|
||||
(specifier) => packageNameOfSpecifier(specifier) === entry.package,
|
||||
),
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import * as ts from "./ts7/syntax.js";
|
||||
import { exportCallOf } from "./npm-static-rewrite-syntax.js";
|
||||
|
||||
/** A module whose whole export is an esbuild getter table:
|
||||
*
|
||||
* var T = {};
|
||||
* __export(T, { name: () => value, ... });
|
||||
* module.exports = T; // or module.exports = __toCommonJS(T);
|
||||
*
|
||||
* `__export` installs one enumerable getter per entry on T, so Node's
|
||||
* `require()` answers those names with the getter's return expression
|
||||
* evaluated per read, exactly like the plain member exports
|
||||
* (`exports.name = value`) the checker models. The checker sees only
|
||||
* `module.exports = <identifier>`, so every consumer of a require binding
|
||||
* that asks the checker for the member (the member symbol, the runtime
|
||||
* member census) needs this shape recognized from the syntax. */
|
||||
export interface CjsGetterTable {
|
||||
/** The export names in table order (Node's own-key order after the
|
||||
* enumerable getters are defined), with the expression each getter
|
||||
* returns. The recognizer admits only the esbuild shape, where every
|
||||
* entry's getter is a zero-parameter function returning one expression,
|
||||
* so the value is never null. */
|
||||
entries: Map<string, ts.Expression>;
|
||||
/** The `module.exports = …` assignment that installs the table (the
|
||||
* KEPT one: Node keeps the last whole-export assignment). */
|
||||
install: ts.BinaryExpression;
|
||||
/** The identifier the table was defined on (`T` above). */
|
||||
target: string;
|
||||
}
|
||||
|
||||
function unparen(expr: ts.Expression): ts.Expression {
|
||||
let e = expr;
|
||||
while (ts.isParenthesizedExpression(e)) e = e.expression;
|
||||
return e;
|
||||
}
|
||||
|
||||
/** True for the `module.exports` property access. */
|
||||
function isModuleExportsAccess(expr: ts.Expression): boolean {
|
||||
return (
|
||||
ts.isPropertyAccessExpression(expr) &&
|
||||
!expr.questionDotToken &&
|
||||
ts.isIdentifier(expr.expression) &&
|
||||
expr.expression.text === "module" &&
|
||||
ts.isIdentifier(expr.name) &&
|
||||
expr.name.text === "exports"
|
||||
);
|
||||
}
|
||||
|
||||
/** The getter-table target identifier an install value names: the
|
||||
* identifier itself, or esbuild's `__toCommonJS(T)` (helper counter
|
||||
* suffixes included). Null for every other value. */
|
||||
function installTargetOf(rhs: ts.Expression): string | null {
|
||||
const e = unparen(rhs);
|
||||
if (ts.isIdentifier(e)) return e.text;
|
||||
if (
|
||||
ts.isCallExpression(e) &&
|
||||
ts.isIdentifier(e.expression) &&
|
||||
/^__toCommonJS\d*$/.test(e.expression.text) &&
|
||||
e.arguments.nodes.length === 1
|
||||
) {
|
||||
const target = unparen(e.arguments.nodes[0]!);
|
||||
if (ts.isIdentifier(target)) return target.text;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The esbuild getter-table whole export of a JavaScript module, or null.
|
||||
* Pure syntax (no checker, no disk), so the program analysis and the
|
||||
* lowering share one answer. */
|
||||
export function cjsGetterTableOf(sf: ts.SourceFile): CjsGetterTable | null {
|
||||
// Every esbuild getter table spells the helper: skip the statement walk
|
||||
// (and every ordinary CommonJS file) on the source bytes alone.
|
||||
if (!sf.text.includes("__export")) return null;
|
||||
// Node keeps the LAST whole-export assignment, so the table must be the
|
||||
// value it installs. `0 && (module.exports = { ... })` (the dead
|
||||
// annotation esbuild emits for Node's lexer) is not an assignment.
|
||||
let install: ts.BinaryExpression | null = null;
|
||||
for (const stmt of sf.statements.nodes) {
|
||||
if (!ts.isExpressionStatement(stmt)) continue;
|
||||
const e = stmt.expression;
|
||||
if (
|
||||
ts.isBinaryExpression(e) &&
|
||||
e.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
|
||||
isModuleExportsAccess(e.left)
|
||||
)
|
||||
install = e;
|
||||
}
|
||||
if (install === null) return null;
|
||||
const target = installTargetOf(install.right);
|
||||
if (target === null) return null;
|
||||
const entries = new Map<string, ts.Expression>();
|
||||
let sawTable = false;
|
||||
for (const stmt of sf.statements.nodes) {
|
||||
if (!ts.isExpressionStatement(stmt) || !ts.isCallExpression(stmt.expression)) continue;
|
||||
const table = exportCallOf(stmt.expression);
|
||||
if (table === null || table.target !== target) continue;
|
||||
// The esbuild shape: every entry a zero-parameter getter returning one
|
||||
// expression. Anything else is a different `__export` user, which the
|
||||
// ordinary (checker-visible) export paths own.
|
||||
if (table.entries.some(([, value]) => value === null)) return null;
|
||||
sawTable = true;
|
||||
for (const [name, value] of table.entries) entries.set(name, value!);
|
||||
}
|
||||
return sawTable ? { entries, install, target } : null;
|
||||
}
|
||||
@@ -70,6 +70,12 @@ export interface ImportElisionOptions {
|
||||
/** `preserveValueImports` (removed in TypeScript 5.5): a binding that names
|
||||
* a value stays whether or not the file uses it. */
|
||||
preserveValueImports: boolean;
|
||||
/** `experimentalDecorators`: legacy decorator emit. */
|
||||
experimentalDecorators: boolean;
|
||||
/** `emitDecoratorMetadata`: the legacy emit serializes design types, and
|
||||
* a class a serialized type names is a VALUE reference — tsc marks that
|
||||
* alias referenced (markAliasReferenced), so its import is kept. */
|
||||
emitDecoratorMetadata: boolean;
|
||||
}
|
||||
|
||||
export interface ImportElision {
|
||||
@@ -607,6 +613,168 @@ function elideCandidates(
|
||||
mark(alias, inExport);
|
||||
}
|
||||
|
||||
// ---- design-type metadata value references ----
|
||||
// `emitDecoratorMetadata` serializes design types into `__metadata`
|
||||
// arguments, and a class a serialized type names is read as a VALUE
|
||||
// there: tsc marks that alias referenced, so its import stays even when
|
||||
// the name appears only in types. The scan follows the serializer's
|
||||
// shape — a rest parameter's element type, a getter's setter parameters,
|
||||
// and a union only when every constituent serializes alike (otherwise
|
||||
// the emit names Object and references no value).
|
||||
if (options.experimentalDecorators && options.emitDecoratorMetadata)
|
||||
markDecoratorMetadataReferences();
|
||||
|
||||
function markDecoratorMetadataReferences(): void {
|
||||
ts.walkPreorder(sf, (node) => {
|
||||
if (!ts.isClassLikeDeclaration(node)) return;
|
||||
const members = node.members.nodes;
|
||||
const constructor = members.find(
|
||||
(member): member is ts.ConstructorDeclaration =>
|
||||
ts.isConstructorDeclaration(member) && member.body !== undefined,
|
||||
);
|
||||
const classDecorated =
|
||||
decoratorsOf(node).length > 0 ||
|
||||
(constructor !== undefined &&
|
||||
constructor.parameters.nodes.some((parameter) => decoratorsOf(parameter).length > 0));
|
||||
if (classDecorated && constructor !== undefined)
|
||||
for (const parameter of constructor.parameters.nodes) markParameterReferences(parameter);
|
||||
for (const member of members) {
|
||||
const parameters =
|
||||
(member as { parameters?: ts.NodeArray<ts.ParameterDeclaration> }).parameters?.nodes ??
|
||||
[];
|
||||
if (
|
||||
decoratorsOf(member).length === 0 &&
|
||||
!parameters.some((parameter) => decoratorsOf(parameter).length > 0)
|
||||
)
|
||||
continue;
|
||||
if (ts.isPropertyDeclaration(member)) {
|
||||
markTypeReferences(member.type);
|
||||
} else if (ts.isMethodDeclaration(member)) {
|
||||
markTypeReferences(member.type);
|
||||
for (const parameter of member.parameters.nodes) markParameterReferences(parameter);
|
||||
} else if (ts.isGetAccessorDeclaration(member) || ts.isSetAccessorDeclaration(member)) {
|
||||
const setter = members.find(
|
||||
(candidate): candidate is ts.SetAccessorDeclaration =>
|
||||
ts.isSetAccessorDeclaration(candidate) &&
|
||||
candidate.name.getText() === member.name.getText(),
|
||||
);
|
||||
if (setter !== undefined)
|
||||
for (const parameter of setter.parameters.nodes) markParameterReferences(parameter);
|
||||
else if (ts.isGetAccessorDeclaration(member)) markTypeReferences(member.type);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function decoratorsOf(node: ts.Node): ts.Decorator[] {
|
||||
return (
|
||||
((node as { modifiers?: ts.NodeArray<ts.Node> }).modifiers?.nodes ?? []) as ts.Node[]
|
||||
).filter((modifier): modifier is ts.Decorator => modifier.kind === ts.SyntaxKind.Decorator);
|
||||
}
|
||||
|
||||
/** A parameter's design:paramtypes entry: its annotation, or a rest
|
||||
* parameter's element type (getRestParameterElementType). */
|
||||
function markParameterReferences(parameter: ts.ParameterDeclaration): void {
|
||||
const type = parameter.type;
|
||||
if (parameter.dotDotDotToken === undefined) {
|
||||
markTypeReferences(type);
|
||||
return;
|
||||
}
|
||||
if (type === undefined) return;
|
||||
if (ts.isArrayTypeNode(type)) markTypeReferences(type.elementType);
|
||||
else if (ts.isTypeReferenceNode(type)) {
|
||||
const name = ts.isIdentifier(type.typeName) ? type.typeName.text : null;
|
||||
if ((name === "Array" || name === "ReadonlyArray") && type.typeArguments !== undefined)
|
||||
markTypeReferences(type.typeArguments.nodes[0]);
|
||||
}
|
||||
}
|
||||
|
||||
function markTypeReferences(type: ts.TypeNode | undefined): void {
|
||||
let node = type;
|
||||
while (node !== undefined && ts.isParenthesizedTypeNode(node)) node = node.type;
|
||||
if (node === undefined) return;
|
||||
switch (node.kind) {
|
||||
case ts.SyntaxKind.TypeReference:
|
||||
if (isClassValueReference(node as ts.TypeReferenceNode))
|
||||
markEntityHead((node as ts.TypeReferenceNode).typeName, false);
|
||||
return;
|
||||
case ts.SyntaxKind.TypeOperator:
|
||||
if ((node as ts.TypeOperatorNode).operator === ts.SyntaxKind.ReadonlyKeyword)
|
||||
markTypeReferences((node as ts.TypeOperatorNode).type);
|
||||
return;
|
||||
case ts.SyntaxKind.UnionType:
|
||||
case ts.SyntaxKind.IntersectionType:
|
||||
case ts.SyntaxKind.ConditionalType: {
|
||||
const parts: readonly ts.TypeNode[] =
|
||||
node.kind === ts.SyntaxKind.ConditionalType
|
||||
? [
|
||||
(node as ts.ConditionalTypeNode).trueType,
|
||||
(node as ts.ConditionalTypeNode).falseType,
|
||||
]
|
||||
: (node as ts.UnionTypeNode).types.nodes;
|
||||
let name: ts.EntityName | null = null;
|
||||
const isIntersection = node.kind === ts.SyntaxKind.IntersectionType;
|
||||
for (const raw of parts) {
|
||||
let part = raw;
|
||||
while (ts.isParenthesizedTypeNode(part)) part = part.type;
|
||||
// The serializer reads never and unknown the way tsc's metadata
|
||||
// serializer does: `never` is skipped in a union and answers
|
||||
// void 0 (naming no value) in an intersection; `unknown` answers
|
||||
// Object in a union and is skipped in an intersection.
|
||||
if (part.kind === ts.SyntaxKind.NeverKeyword) {
|
||||
if (isIntersection) return;
|
||||
continue;
|
||||
}
|
||||
if (part.kind === ts.SyntaxKind.UnknownKeyword && isIntersection) continue;
|
||||
if (!ts.isTypeReferenceNode(part) || !isClassValueReference(part)) return;
|
||||
if (name === null) name = part.typeName;
|
||||
else if (name.getText() !== part.typeName.getText()) return;
|
||||
}
|
||||
if (name !== null) markEntityHead(name, false);
|
||||
return;
|
||||
}
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the type reference names a class VALUE the emit reads: a class
|
||||
* reached through a value import (a type-only import has no run-time
|
||||
* binding; tsc serializes that one as Function). */
|
||||
function isClassValueReference(reference: ts.TypeReferenceNode): boolean {
|
||||
let head: ts.Node = reference.typeName;
|
||||
while (ts.isQualifiedName(head)) head = (head as ts.QualifiedName).left;
|
||||
if (!ts.isIdentifier(head)) return false;
|
||||
const symbol = checker.resolveName(head.text, ALL_MEANINGS, head, false);
|
||||
if (symbol === undefined) return false;
|
||||
if (aliasOf(symbol, head.text) === undefined) return false;
|
||||
if ((symbol.flags & ts.SymbolFlags.Alias) !== 0) {
|
||||
const declaration = symbol.declarations?.[0];
|
||||
if (declaration !== undefined && isTypeOnlyImport(declaration as unknown as ts.Node))
|
||||
return false;
|
||||
}
|
||||
// A namespace member (`dep.Dep`) names its class through the QUALIFIED
|
||||
// name: tsc emits the member read and keeps the namespace import.
|
||||
if (ts.isQualifiedName(reference.typeName)) {
|
||||
const member = checker.getSymbolAtLocation(reference.typeName);
|
||||
if (member === undefined) return false;
|
||||
const memberTarget = targetOf(member) ?? member;
|
||||
return (memberTarget.flags & ts.SymbolFlags.Class) !== 0;
|
||||
}
|
||||
const target = targetOf(symbol);
|
||||
return ((target ?? symbol).flags & ts.SymbolFlags.Class) !== 0;
|
||||
}
|
||||
|
||||
function isTypeOnlyImport(declaration: ts.Node): boolean {
|
||||
let node: ts.Node = declaration;
|
||||
while (ts.isImportSpecifier(node) || ts.isImportClause(node) || ts.isNamespaceImport(node)) {
|
||||
if ((node as { isTypeOnly?: boolean }).isTypeOnly === true) return true;
|
||||
if (node.parent === undefined) break;
|
||||
node = node.parent;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---- export lists and `export default name` ----
|
||||
const droppedExports = new Set<ts.ExportSpecifier>();
|
||||
const inlinedExports: string[] = [];
|
||||
@@ -897,6 +1065,8 @@ export function importElisionOptions(
|
||||
unused === 2 ||
|
||||
(typeof unused === "string" && /^(?:preserve|error)$/i.test(unused)),
|
||||
preserveValueImports: options["preserveValueImports"] === true,
|
||||
experimentalDecorators: options["experimentalDecorators"] === true,
|
||||
emitDecoratorMetadata: options["emitDecoratorMetadata"] === true,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -347,6 +347,27 @@ test("JavaScript drops the diagnostic of discarded negation chains of a void-typ
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
const DISCARDED_VOID_AND_COMMA = `var cancelTimeout = (handle) => {
|
||||
void handle;
|
||||
};
|
||||
const root = { timeoutHandle: -1 };
|
||||
let timeoutHandle = root.timeoutHandle;
|
||||
-1 !== timeoutHandle &&
|
||||
((root.timeoutHandle = -1), cancelTimeout(timeoutHandle));
|
||||
console.log(root.timeoutHandle);`;
|
||||
|
||||
test("JavaScript drops the diagnostic of a void call in a guarded comma nobody reads", () => {
|
||||
// The shape react-dom's prepareFreshStack writes: the `&&` right operand is
|
||||
// the whole expression statement, so both the comma and its right operand
|
||||
// answer nothing.
|
||||
expect(
|
||||
diagnostics(
|
||||
DISCARDED_VOID_AND_COMMA,
|
||||
'import * as library from "./library.js"; console.log(library);',
|
||||
),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
test("a consumed negation chain of a void-typed callback keeps the diagnostic", () => {
|
||||
const kept = diagnostics(
|
||||
`/** @param {() => void} callback */
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
type ChildEvalStep,
|
||||
encodingNameValue,
|
||||
lowerChildArgsArg,
|
||||
lowerDynamicInput,
|
||||
windowsOnlyOption,
|
||||
withChildArgsCheck,
|
||||
} from "./child-process.js";
|
||||
@@ -122,6 +123,9 @@ export function lowerExecSyncCall(
|
||||
// empty stdin — immediate EOF), Node's exact reading of the member.
|
||||
let input: IrExpr = emptyStr;
|
||||
let hasInput: IrExpr = boolLit(false, loc);
|
||||
// A checked-dynamic input's stdio[0] refusal: Node raises it after every
|
||||
// other option is known, so it rides the launch's checks.
|
||||
let inputCheck: IrStmt | null = null;
|
||||
let cwd: IrExpr = emptyStr;
|
||||
let hasEnv: IrExpr = boolLit(false, loc);
|
||||
let envPairs: IrExpr = emptyPairs;
|
||||
@@ -330,17 +334,18 @@ export function lowerExecSyncCall(
|
||||
optionSteps.push(5);
|
||||
break;
|
||||
case "input": {
|
||||
// string | undefined, Node's exact member semantics: the
|
||||
// undefined arm means the option is ABSENT (no stdin pipe),
|
||||
// "" pipes EMPTY stdin (the child reads immediate EOF). A
|
||||
// union-typed value re-reads for the presence test (the
|
||||
// readOpt discipline), so only pure reads qualify — the
|
||||
// `options?.input` shape verbatim.
|
||||
// Node's exact member semantics: the undefined arm means the
|
||||
// option is ABSENT (no stdin pipe), "" pipes EMPTY stdin (the
|
||||
// child reads immediate EOF). A union-typed value re-reads for
|
||||
// the presence test (the readOpt discipline), so only pure reads
|
||||
// qualify — the `options?.input` shape verbatim. A
|
||||
// checked-dynamic value follows Node's stdio[0] rule: truthy
|
||||
// means present (a string carries the text; anything else is
|
||||
// refused after the launch's other checks), falsy means absent.
|
||||
if (lowerer.typeOf(m.value).flags & ts.TypeFlags.Undefined) {
|
||||
// `input: undefined` — Node treats the member as absent.
|
||||
break;
|
||||
}
|
||||
optionSteps.push(3, 4);
|
||||
const it = lowerer.mapTypeOf(lowerer.typeOf(m.value));
|
||||
const uTag = it?.kind === "union" ? lowerer.armTag(it.unionId, UNDEFINED_T) : -1;
|
||||
const sTag = it?.kind === "union" ? lowerer.armTag(it.unionId, STRING) : -1;
|
||||
@@ -352,6 +357,7 @@ export function lowerExecSyncCall(
|
||||
"the undefined test re-reads the expression — bind the input to a const first",
|
||||
);
|
||||
}
|
||||
optionSteps.push(3, 4);
|
||||
const read = lowerer.lowerExpr(m.value);
|
||||
hasInput = {
|
||||
kind: "unionIsTag",
|
||||
@@ -387,7 +393,36 @@ export function lowerExecSyncCall(
|
||||
};
|
||||
break;
|
||||
}
|
||||
input = lowerer.lowerExprExpecting(m.value, STRING);
|
||||
// The LOWERED value decides a checked-dynamic member: `any` has
|
||||
// no mapped type of its own, and an assertion keeps the value's
|
||||
// own kind. Node's stdio[0] rule applies there (see
|
||||
// lowerDynamicInput), with the type refusal raised only after the
|
||||
// launch's other checks.
|
||||
const readValue = lowerer.lowerExpr(m.value);
|
||||
if (readValue.type.kind === "dyn") {
|
||||
const dynamic = lowerDynamicInput(lowerer, m.value, readValue, loc);
|
||||
optionSteps.push({
|
||||
effect: {
|
||||
kind: "seqExpr",
|
||||
stmts: dynamic.stmts,
|
||||
result: numLit(0, loc),
|
||||
type: F64,
|
||||
loc,
|
||||
},
|
||||
});
|
||||
input = dynamic.input;
|
||||
hasInput = dynamic.hasInput;
|
||||
inputCheck = dynamic.check;
|
||||
break;
|
||||
}
|
||||
if (isUnitType(readValue.type)) {
|
||||
// A null or undefined value is an ABSENT option; the expression
|
||||
// still evaluates for its side effects.
|
||||
if (!isSafeToDiscard(readValue)) optionSteps.push({ effect: readValue });
|
||||
break;
|
||||
}
|
||||
optionSteps.push(3, 4);
|
||||
input = lowerer.coerceInto(m.value, readValue, STRING);
|
||||
hasInput = boolLit(true, loc);
|
||||
break;
|
||||
}
|
||||
@@ -763,6 +798,7 @@ export function lowerExecSyncCall(
|
||||
order,
|
||||
shellAdaptArgs ?? undefined,
|
||||
shellPathRef ?? undefined,
|
||||
inputCheck === null ? undefined : [inputCheck],
|
||||
);
|
||||
};
|
||||
if (condEnvSpread !== null && optionSteps.some((step) => typeof step === "object")) {
|
||||
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
type SrcLoc,
|
||||
UNDEFINED_T,
|
||||
VOID,
|
||||
isUnitType,
|
||||
arrayOf,
|
||||
funcOf,
|
||||
typeKey,
|
||||
@@ -95,6 +96,97 @@ export function armedMaxBuffer(value: IrExpr | null, sync: boolean): ChildMaxBuf
|
||||
return value === null ? undefined : { value, arm: true, sync };
|
||||
}
|
||||
|
||||
/** Node's `input` member for a CHECKED-DYNAMIC value (an `any`/`unknown`
|
||||
* member). Node moves a truthy input into stdio[0] and leaves a falsy one
|
||||
* absent — `""`, 0, NaN, false, null and undefined all pipe no input — so
|
||||
* the rule is truthiness, not nullishness; a truthy value that is not a
|
||||
* string throws Node's ERR_INVALID_ARG_TYPE under the "options.stdio[0]"
|
||||
* name. (A truthy view is accepted by Node; the byte-input form adds that
|
||||
* arm.)
|
||||
*
|
||||
* The returned statements read the member ONCE into hidden locals — the
|
||||
* caller emits them where the member sits, so its side effects run in
|
||||
* Node's option order. `check` is the type refusal: Node raises it only
|
||||
* after every other option is known (and after the file, argument, cwd,
|
||||
* shell, environment and maxBuffer checks), so the caller passes it to
|
||||
* withChildArgsCheck, which emits it after those checks and before the
|
||||
* launch. */
|
||||
export function lowerDynamicInput(
|
||||
lowerer: Lowerer,
|
||||
node: ts.Expression,
|
||||
read: IrExpr,
|
||||
loc: SrcLoc,
|
||||
): { stmts: IrStmt[]; input: IrExpr; hasInput: IrExpr; check: IrStmt } {
|
||||
const value = lowerer.declareHiddenLocal("%dynInputValue", read.type);
|
||||
const present = lowerer.declareHiddenLocal("%dynInputPresent", BOOL);
|
||||
const text = lowerer.declareHiddenLocal("%dynInputText", STRING);
|
||||
const valueRef = (): IrExpr => varRef(value.id, read.type, loc);
|
||||
const isString = (negated: boolean): IrExpr => ({
|
||||
kind: "dynTest",
|
||||
test: "string",
|
||||
value: valueRef(),
|
||||
type: BOOL,
|
||||
loc,
|
||||
...(negated ? { negated: true as const } : {}),
|
||||
});
|
||||
return {
|
||||
stmts: [
|
||||
{ kind: "varDecl", localId: value.id, init: read, loc },
|
||||
{
|
||||
kind: "varDecl",
|
||||
localId: present.id,
|
||||
init: { kind: "dynTest", test: "truthy", value: valueRef(), type: BOOL, loc },
|
||||
loc,
|
||||
},
|
||||
{
|
||||
kind: "varDecl",
|
||||
localId: text.id,
|
||||
init: {
|
||||
kind: "ternary",
|
||||
cond: isString(false),
|
||||
then: lowerer.coerceInto(node, valueRef(), STRING),
|
||||
else_: { kind: "strLit", value: "", type: STRING, loc },
|
||||
type: STRING,
|
||||
loc,
|
||||
},
|
||||
loc,
|
||||
},
|
||||
],
|
||||
input: varRef(text.id, STRING, loc),
|
||||
hasInput: varRef(present.id, BOOL, loc),
|
||||
check: {
|
||||
kind: "if",
|
||||
cond: {
|
||||
kind: "logical",
|
||||
op: "&&",
|
||||
left: varRef(present.id, BOOL, loc),
|
||||
right: isString(true),
|
||||
type: BOOL,
|
||||
loc,
|
||||
},
|
||||
then: [
|
||||
{
|
||||
kind: "exprStmt",
|
||||
expr: {
|
||||
kind: "libCall",
|
||||
fn: "error.propTypeThrow",
|
||||
args: [
|
||||
strLit("options.stdio[0]", loc),
|
||||
strLit("of type string or an instance of Buffer, TypedArray, or DataView", loc),
|
||||
valueRef(),
|
||||
],
|
||||
type: VOID,
|
||||
loc,
|
||||
},
|
||||
loc,
|
||||
},
|
||||
],
|
||||
else_: null,
|
||||
loc,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Node checks what a child launch hands to the operating system before
|
||||
* it starts a process (normalizeSpawnArguments and normalizeExecArgs): a
|
||||
* NUL in the file or command, an argument, `cwd` or an environment key or
|
||||
@@ -139,6 +231,10 @@ export function withChildArgsCheck(
|
||||
* an embedded NUL under the option's own name, between the working
|
||||
* directory and the environment. */
|
||||
shellPath?: IrExpr,
|
||||
/** Checks Node raises only once every other option is known, after the
|
||||
* file, argument, cwd, shell, environment and maxBuffer checks and before
|
||||
* the launch — the captured-stdin value's stdio[0] type refusal. */
|
||||
beforeLaunch?: readonly IrStmt[],
|
||||
): IrExpr {
|
||||
const passes = (e: IrExpr | undefined, mayBeEmpty: boolean): boolean =>
|
||||
e === undefined ||
|
||||
@@ -182,7 +278,14 @@ export function withChildArgsCheck(
|
||||
sourceOrder.filter(
|
||||
(step) => typeof step === "number" && step > 2 && evaluates(launch.args[step]!),
|
||||
).length > 1);
|
||||
if (fileAndArgsPass && optionsPass && !limited && !ordered && shellPath === undefined)
|
||||
if (
|
||||
fileAndArgsPass &&
|
||||
optionsPass &&
|
||||
!limited &&
|
||||
!ordered &&
|
||||
shellPath === undefined &&
|
||||
(beforeLaunch === undefined || beforeLaunch.length === 0)
|
||||
)
|
||||
return launch;
|
||||
const stmts: IrStmt[] = [];
|
||||
const hold = (value: IrExpr): IrExpr => {
|
||||
@@ -323,20 +426,50 @@ export function withChildArgsCheck(
|
||||
// step, before the checks, and they and the launch read the local.
|
||||
let limit = limited ? held.maxBuffer : undefined;
|
||||
if (limit !== undefined && ownLimitHeld !== undefined) limit = { ...limit, value: ownLimitHeld };
|
||||
// The captured-stdin refusal (beforeLaunch) runs where Node runs it: after
|
||||
// the file, argument, cwd, shell, environment and maxBuffer checks. The
|
||||
// limit is validated just before it and armed only after it passes, so a
|
||||
// refusal never leaves a limit behind for another capture.
|
||||
const preLaunch = beforeLaunch ?? [];
|
||||
const checkLimit = (): void => {
|
||||
if (limit !== undefined) stmts.push(maxBufferCall(limit.value, false));
|
||||
};
|
||||
const armLimit = (): void => {
|
||||
if (limit !== undefined && limit.arm) stmts.push(maxBufferCall(limit.value, true));
|
||||
};
|
||||
const splitLimit = preLaunch.length > 0;
|
||||
if (shellPath !== undefined) {
|
||||
// The runtime-`shell` form always runs the checks, in Node's order: the
|
||||
// shell path is validated under "options.shell" after cwd and before the
|
||||
// environment, so a string carrying a NUL byte is refused instead of
|
||||
// truncating the exec path.
|
||||
stmts.push(checkFileCwd(), checkShellNul(), checkEnv());
|
||||
if (limit !== undefined) stmts.push(maxBufferCall(limit.value, limit.arm));
|
||||
if (!splitLimit) {
|
||||
if (limit !== undefined) stmts.push(maxBufferCall(limit.value, limit.arm));
|
||||
} else {
|
||||
checkLimit();
|
||||
stmts.push(...preLaunch);
|
||||
armLimit();
|
||||
}
|
||||
} else if (limit === undefined) {
|
||||
// Reached with nothing to check only for an `effect`'s order.
|
||||
if (!(fileAndArgsPass && optionsPass)) stmts.push(checkAll());
|
||||
stmts.push(...preLaunch);
|
||||
} else if (fileAndArgsPass && optionsPass) {
|
||||
stmts.push(maxBufferCall(limit.value, limit.arm));
|
||||
if (!splitLimit) stmts.push(maxBufferCall(limit.value, limit.arm));
|
||||
else {
|
||||
checkLimit();
|
||||
stmts.push(...preLaunch);
|
||||
armLimit();
|
||||
}
|
||||
} else if (limit.sync || limitPasses) {
|
||||
stmts.push(checkAll(), maxBufferCall(limit.value, limit.arm));
|
||||
stmts.push(checkAll());
|
||||
if (!splitLimit) stmts.push(maxBufferCall(limit.value, limit.arm));
|
||||
else {
|
||||
checkLimit();
|
||||
stmts.push(...preLaunch);
|
||||
armLimit();
|
||||
}
|
||||
} else {
|
||||
// exec and execFile, callback or promisified, where the limit and a
|
||||
// launch value can both be refused. The limit is validated first and
|
||||
@@ -352,6 +485,7 @@ export function withChildArgsCheck(
|
||||
} else {
|
||||
stmts.push(maxBufferCall(value, false), checkAll());
|
||||
}
|
||||
stmts.push(...preLaunch);
|
||||
if (limit.arm) stmts.push(maxBufferCall(value, true));
|
||||
}
|
||||
const result = { ...launch, args: [...(adaptArgs === undefined ? args : adaptArgs(args))] };
|
||||
@@ -613,10 +747,14 @@ export function lowerSpawnSyncCall(lowerer: Lowerer, expr: ts.CallExpression, lo
|
||||
let shell: IrExpr = boolLit(false, loc);
|
||||
let extOptions = false; // cwd, input, or shell present: the extended entry point
|
||||
let plain = true; // no behavior-changing option: the historical libCall
|
||||
// A union-typed `input` is read once into a hidden local that its
|
||||
// presence test and its value share, so a getter or a call in the
|
||||
// member runs exactly once, as the options object's evaluation does.
|
||||
let inputRead: { id: string; init: IrExpr } | null = null;
|
||||
// A union-typed or checked-dynamic `input` is read once into hidden
|
||||
// locals that its presence test and its value share, so a getter or a
|
||||
// call in the member runs exactly once, as the options object's
|
||||
// evaluation does. `inputStage` holds the member's statements (emitted
|
||||
// where it sits); `inputCheck` holds Node's stdio[0] refusal, raised
|
||||
// only after the launch's other checks.
|
||||
let inputStage: IrStmt[] | null = null;
|
||||
let inputCheck: IrStmt[] | null = null;
|
||||
// The options whose values reach the call, in source order: the
|
||||
// extended entry point's prelude evaluates them in this order. `stdio`
|
||||
// stands for a tuple whose slots resolve at the call.
|
||||
@@ -908,7 +1046,7 @@ export function lowerSpawnSyncCall(lowerer: Lowerer, expr: ts.CallExpression, lo
|
||||
if (it?.kind === "union" && uTag >= 0 && sTag >= 0) {
|
||||
const readValue = lowerer.lowerExpr(m.value);
|
||||
const slot = lowerer.declareHiddenLocal("%spawnSyncInput", readValue.type);
|
||||
inputRead = { id: slot.id, init: readValue };
|
||||
inputStage = [{ kind: "varDecl", localId: slot.id, init: readValue, loc }];
|
||||
const read: IrExpr = varRef(slot.id, readValue.type, loc);
|
||||
hasInput = {
|
||||
kind: "unionIsTag",
|
||||
@@ -947,7 +1085,33 @@ export function lowerSpawnSyncCall(lowerer: Lowerer, expr: ts.CallExpression, lo
|
||||
plain = false;
|
||||
break;
|
||||
}
|
||||
input = lowerer.lowerExprExpecting(m.value, STRING);
|
||||
// The LOWERED value decides a checked-dynamic member: `any` has
|
||||
// no mapped type of its own, and an assertion keeps the value's
|
||||
// own kind. Node's stdio[0] rule applies there (see
|
||||
// lowerDynamicInput), with the type refusal raised only after the
|
||||
// launch's other checks.
|
||||
const read = lowerer.lowerExpr(m.value);
|
||||
if (read.type.kind === "dyn") {
|
||||
const dynamic = lowerDynamicInput(lowerer, m.value, read, loc);
|
||||
inputStage = dynamic.stmts;
|
||||
inputCheck = [dynamic.check];
|
||||
input = dynamic.input;
|
||||
hasInput = dynamic.hasInput;
|
||||
optionOrder.push("input");
|
||||
extOptions = true;
|
||||
plain = false;
|
||||
break;
|
||||
}
|
||||
if (isUnitType(read.type)) {
|
||||
// A null or undefined value is an ABSENT option; the expression
|
||||
// still evaluates for its side effects.
|
||||
if (read.kind !== "unitLit") inputStage = [{ kind: "exprStmt", expr: read, loc }];
|
||||
optionOrder.push("input");
|
||||
extOptions = true;
|
||||
plain = false;
|
||||
break;
|
||||
}
|
||||
input = lowerer.coerceInto(m.value, read, STRING);
|
||||
optionOrder.push("input");
|
||||
hasInput = boolLit(true, loc);
|
||||
extOptions = true;
|
||||
@@ -1054,8 +1218,7 @@ export function lowerSpawnSyncCall(lowerer: Lowerer, expr: ts.CallExpression, lo
|
||||
outModeArg = bind("%spawnSyncStdoutMode", outMode);
|
||||
errModeArg = bind("%spawnSyncStderrMode", errMode);
|
||||
} else if (option === "input") {
|
||||
if (inputRead !== null)
|
||||
prelude.push({ kind: "varDecl", localId: inputRead.id, init: inputRead.init, loc });
|
||||
if (inputStage !== null) prelude.push(...inputStage);
|
||||
else inputArg = bind("%spawnSyncInput", input);
|
||||
} else if (option === "windowsHide") {
|
||||
const value = windowsHideValues.shift();
|
||||
@@ -1122,6 +1285,10 @@ export function lowerSpawnSyncCall(lowerer: Lowerer, expr: ts.CallExpression, lo
|
||||
maxBuffer: armedMaxBuffer(maxBufferArg, true),
|
||||
}),
|
||||
loc,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
inputCheck ?? undefined,
|
||||
);
|
||||
return prelude.length === 0
|
||||
? call
|
||||
|
||||
@@ -45,6 +45,7 @@ import { type Lowerer } from "../lowerer.js";
|
||||
import { type BuiltinModuleFn } from "../surfaces.js";
|
||||
import { type ParamShape } from "../call-signatures.js";
|
||||
import {
|
||||
BOOL,
|
||||
BYTES_U8,
|
||||
DYN,
|
||||
F64,
|
||||
@@ -394,6 +395,54 @@ export function lowerBuiltinModuleCall(
|
||||
if (bi.module === "fs/promises" && bi.member === "mkdir" && expr.arguments.nodes.length === 2) {
|
||||
return lowerFsPromisesMkdirCall(lowerer, expr, loc);
|
||||
}
|
||||
// fs.promises.realpath(path, options): the synchronous form's option
|
||||
// ladder and resolution, settled into a promise. A getter's throw is the
|
||||
// promise's rejection, which is how Node's async entry point reports it.
|
||||
if (
|
||||
bi.module === "fs/promises" &&
|
||||
bi.member === "realpath" &&
|
||||
expr.arguments.nodes.length === 2 &&
|
||||
!expr.arguments.nodes.some(ts.isSpreadElement)
|
||||
) {
|
||||
return {
|
||||
kind: "libCall",
|
||||
fn: "fsp.realpathDyn",
|
||||
args: [
|
||||
lowerer.lowerExprExpecting(expr.arguments.nodes[0]!, DYN),
|
||||
lowerer.lowerExprExpecting(expr.arguments.nodes[1]!, DYN),
|
||||
],
|
||||
type: { kind: "promise", inner: DYN },
|
||||
loc,
|
||||
};
|
||||
}
|
||||
// realpathSync(path[, options]) and its .native: the options carry the
|
||||
// encoding, so the result is a string or a Buffer (DYN). The value form
|
||||
// (fs.realpathSync stored as a function) lowers to the same runtime call.
|
||||
if (
|
||||
bi.module === "fs" &&
|
||||
(bi.member === "realpathSync" || bi.member === "realpathSync.native") &&
|
||||
expr.arguments.nodes.length === 2 &&
|
||||
!expr.arguments.nodes.some(ts.isSpreadElement)
|
||||
) {
|
||||
const call: IrExpr = {
|
||||
kind: "libCall",
|
||||
fn: "fs.realpathValue",
|
||||
args: [
|
||||
lowerer.lowerExprExpecting(expr.arguments.nodes[0]!, DYN),
|
||||
lowerer.lowerExprExpecting(expr.arguments.nodes[1]!, DYN),
|
||||
{ kind: "boolLit", value: bi.member === "realpathSync.native", type: BOOL, loc },
|
||||
],
|
||||
type: DYN,
|
||||
loc,
|
||||
};
|
||||
/* The call's static type decides how its value is read: a plain or
|
||||
* utf8 call is a string, `{ encoding: "buffer" }` a Buffer (the dyn
|
||||
* result casts to it), and an untyped call stays dynamic. */
|
||||
const staticType = lowerer.mapTypeOf(lowerer.typeOf(expr));
|
||||
if (staticType?.kind === "string") return lowerer.coerceToExpected(call, STRING);
|
||||
if (staticType?.kind === "bytes") return lowerer.coerceToExpected(call, BYTES_U8);
|
||||
return call;
|
||||
}
|
||||
if (bi.module === "fs" && bi.member === "rmSync" && expr.arguments.nodes.length === 2) {
|
||||
return lowerFsRemoveCall(lowerer, expr, loc, false);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { voidThunkValue } from "../void-thunk.js";
|
||||
import { keyedHelperName } from "../stable-names.js";
|
||||
import { stdinKeypressListener } from "./readline.js";
|
||||
import { envSnapshotHelper, lowerProcessLoadEnvFile } from "./environment.js";
|
||||
@@ -1336,21 +1337,21 @@ export function processDataMemberValue(
|
||||
* what `process.<member>` read as a value answers, and what the same member
|
||||
* of a stored process object answers (node-value-reads.ts), so the two are
|
||||
* one function. Null for the members that are call-only or have no
|
||||
* lowering. `js` is whether the read is in a JavaScript source; `held` is
|
||||
* whether the member is built for a stored process object, not spelled. */
|
||||
* lowering. `held` is whether the member is built for a stored process
|
||||
* object, not spelled. */
|
||||
export function processFunctionMemberValue(
|
||||
lowerer: Lowerer,
|
||||
member: string,
|
||||
loc: SrcLoc,
|
||||
js: boolean,
|
||||
held = false,
|
||||
): IrExpr | null {
|
||||
if (member === "hrtime") {
|
||||
return { kind: "libCall", fn: "process.hrtimeValue", args: [], type: DYN, loc };
|
||||
}
|
||||
// A stored process.nextTick in JavaScript (`cond ? setImmediate :
|
||||
// process.nextTick`): the interned builtin function value.
|
||||
if (member === "nextTick" && js) return builtinFunctionValue("process.nextTick", loc);
|
||||
// A stored process.nextTick (`cond ? setImmediate : process.nextTick`):
|
||||
// the interned builtin function value, the same function the direct call
|
||||
// runs.
|
||||
if (member === "nextTick") return builtinFunctionValue("process.nextTick", loc);
|
||||
if (member === "getBuiltinModule") {
|
||||
// Keep the native loader's argument validation when the function is
|
||||
// stored. The declaration's string signature must not insert a checked
|
||||
@@ -1703,12 +1704,7 @@ export function lowerProcessProperty(
|
||||
return strLit(`v${NODE_COMPAT_VERSION}`, loc);
|
||||
}
|
||||
{
|
||||
const value = processFunctionMemberValue(
|
||||
lowerer,
|
||||
member,
|
||||
loc,
|
||||
isJsSourceFile(ts.getSourceFileOfNode(expr)),
|
||||
);
|
||||
const value = processFunctionMemberValue(lowerer, member, loc);
|
||||
if (value !== null) return value;
|
||||
}
|
||||
if (member === "argv") {
|
||||
@@ -2273,11 +2269,21 @@ export function lowerProcessMethodCall(
|
||||
return { kind: "libCall", fn: "stdin.onKeypress", args: [listener, onceKp], type: VOID, loc };
|
||||
}
|
||||
const cb = lowerer.lowerExpr(call.arguments.nodes[1]!);
|
||||
if (cb.type.kind !== "func" || cb.type.ret.kind !== "void" || cb.type.params.length > 1) {
|
||||
if (cb.type.kind !== "func" || cb.type.params.length > 1) {
|
||||
lowerer.unsupported(
|
||||
"SC1090",
|
||||
call.arguments.nodes[1]!,
|
||||
"stdin listeners with more than one parameter or a return value",
|
||||
"stdin listeners with more than one parameter",
|
||||
);
|
||||
}
|
||||
// Node ignores a listener's return value: an async listener registers
|
||||
// through a void thunk that drops the promise it answers.
|
||||
const listener = voidThunkValue(lowerer, cb, loc);
|
||||
if (listener === null) {
|
||||
lowerer.unsupported(
|
||||
"SC1090",
|
||||
call.arguments.nodes[1]!,
|
||||
"stdin listeners that are not function values",
|
||||
);
|
||||
}
|
||||
const param = cb.type.params[0];
|
||||
@@ -2297,7 +2303,7 @@ export function lowerProcessMethodCall(
|
||||
`data listeners whose parameter is not 'Uint8Array' or 'string' (got '${lowerer.fmt(param)}')`,
|
||||
);
|
||||
}
|
||||
return { kind: "libCall", fn: "stdin.onData", args: [cb, onceArg], type: VOID, loc };
|
||||
return { kind: "libCall", fn: "stdin.onData", args: [listener, onceArg], type: VOID, loc };
|
||||
}
|
||||
if (event === "end" || event === "readable") {
|
||||
if (param !== undefined) {
|
||||
@@ -2310,7 +2316,7 @@ export function lowerProcessMethodCall(
|
||||
return {
|
||||
kind: "libCall",
|
||||
fn: event === "end" ? "stdin.onEnd" : "stdin.onReadable",
|
||||
args: [cb, onceArg],
|
||||
args: [listener, onceArg],
|
||||
type: VOID,
|
||||
loc,
|
||||
};
|
||||
@@ -2322,7 +2328,7 @@ export function lowerProcessMethodCall(
|
||||
`error listeners whose parameter is not 'Error' (got '${lowerer.fmt(param)}')`,
|
||||
);
|
||||
}
|
||||
return { kind: "libCall", fn: "stdin.onError", args: [cb, onceArg], type: VOID, loc };
|
||||
return { kind: "libCall", fn: "stdin.onError", args: [listener, onceArg], type: VOID, loc };
|
||||
}
|
||||
if (access.name.text === "write" && ts.isPropertyAccessExpression(access.expression)) {
|
||||
const stream = lowerer.stdlibGlobalMember(access.expression, "process");
|
||||
@@ -2935,15 +2941,6 @@ export function lowerProcessMethodCall(
|
||||
// family (Node's emit prints the default report as well), and the
|
||||
// rejection families (their listeners take a promise).
|
||||
if (member === "emit") {
|
||||
// Island code's listeners live in Node's own `process`; the native
|
||||
// registries are not the ones an emit would have to reach.
|
||||
if (lowerer.nodeIslands !== null) {
|
||||
lowerer.unsupported(
|
||||
"SC1090",
|
||||
call,
|
||||
"process.emit in a program with Node islands (the listeners belong to Node's process)",
|
||||
);
|
||||
}
|
||||
const eventArg = call.arguments.nodes[0];
|
||||
// Node answers false for a missing event (`process.emit()`).
|
||||
if (eventArg === undefined) return boolLit(false, loc);
|
||||
@@ -2956,6 +2953,17 @@ export function lowerProcessMethodCall(
|
||||
);
|
||||
}
|
||||
const name = eventArg.text;
|
||||
// In a program with Node islands the exception families' listeners
|
||||
// live in Node's own process object, so a native dispatch would miss
|
||||
// them (the stance this branch kept before signals lowered). The signal
|
||||
// family dispatches the native registry the compiler owns.
|
||||
if (lowerer.nodeIslands !== null && !name.startsWith("SIG")) {
|
||||
lowerer.unsupported(
|
||||
"SC1090",
|
||||
call,
|
||||
"process.emit in a program with Node islands (the listeners belong to Node's process)",
|
||||
);
|
||||
}
|
||||
if (name === "error") {
|
||||
// Node's EventEmitter throws when 'error' is emitted and no 'error'
|
||||
// listener is registered, and `process.on("error", ...)` has no
|
||||
@@ -2988,7 +2996,29 @@ export function lowerProcessMethodCall(
|
||||
? dispatch
|
||||
: { kind: "seqExpr", stmts, result: dispatch, type: BOOL, loc };
|
||||
}
|
||||
if (UNSUPPORTED_PROCESS_EVENTS.has(name) || name.startsWith("SIG")) {
|
||||
// process.emit('SIG…'): dispatch the signal's registered listeners
|
||||
// synchronously, as Node's EventEmitter emit does. A signal listener
|
||||
// takes (name, number) in this runtime and receives no emit arguments,
|
||||
// so extra arguments are refused rather than silently dropped.
|
||||
if (name.startsWith("SIG")) {
|
||||
if (rest.length > 0) {
|
||||
lowerer.unsupported(
|
||||
"SC1090",
|
||||
call,
|
||||
`process.emit('${name}', ...) (a signal listener receives no arguments)`,
|
||||
);
|
||||
}
|
||||
const signal = lowerer.coerceToExpected(lowerer.lowerExpr(eventArg), STRING);
|
||||
if (signal.type.kind !== "string" && signal.type.kind !== "dyn") {
|
||||
lowerer.noLowering("process signal event name that is not a string", eventArg);
|
||||
}
|
||||
const value =
|
||||
signal.type.kind === "string"
|
||||
? signal
|
||||
: { kind: "dynCheck" as const, value: signal, type: STRING, loc };
|
||||
return { kind: "libCall", fn: "process.emitSignal", args: [value], type: BOOL, loc };
|
||||
}
|
||||
if (UNSUPPORTED_PROCESS_EVENTS.has(name)) {
|
||||
lowerer.unsupported(
|
||||
"SC1090",
|
||||
call,
|
||||
|
||||
@@ -222,6 +222,12 @@ export function lowerSearchParamsNew(
|
||||
* already the entry). */
|
||||
type ValueOf = { value: IrExpr; coerce: (raw: IrExpr) => IrExpr; coerces: boolean };
|
||||
|
||||
/** A key stored as an array index (`"0"`, `"12"`): Node enumerates these
|
||||
* ascending ahead of every other key. */
|
||||
function isIndexKey(key: string): boolean {
|
||||
return /^(?:0|[1-9][0-9]*)$/.test(key) && Number(key) < 4294967295;
|
||||
}
|
||||
|
||||
function lowerSearchParamsInit(lowerer: Lowerer, arg: ts.Expression, loc: SrcLoc): IrExpr {
|
||||
let inner = arg;
|
||||
while (ts.isParenthesizedExpression(inner)) inner = inner.expression;
|
||||
@@ -239,13 +245,12 @@ function lowerSearchParamsInit(lowerer: Lowerer, arg: ts.Expression, loc: SrcLoc
|
||||
return { kind: "libCall", fn: "sp.new", args: [], type: SEARCH_PARAMS_T, loc };
|
||||
}
|
||||
// The object-literal init: fold `{ a: "1", b: "2" }` into nested
|
||||
// sp.with calls over the empty list. The order is Node's
|
||||
// Reflect.ownKeys order for the literal rather than its source order:
|
||||
// its integer index keys ascending first, then the other string keys in
|
||||
// source order (`{ length: 2, 0: "a", 1: "b" }` answers
|
||||
// `0=a&1=b&length=2`). Only plain property assignments (tsc's
|
||||
// index-signature contextual type already rejects spreads' surprises,
|
||||
// but keep the fence tight).
|
||||
// sp.with calls over the empty list, and a spread of a closed record into
|
||||
// the entries it copies. The order is Node's Reflect.ownKeys order for
|
||||
// the merged literal rather than its source order: its integer index
|
||||
// keys ascending first, then the other string keys in creation order
|
||||
// (`{ length: 2, 0: "a", 1: "b" }` answers `0=a&1=b&length=2`). Only
|
||||
// plain property assignments and spreads of closed records lower here.
|
||||
if (ts.isObjectLiteralExpression(arg)) {
|
||||
let acc: IrExpr = { kind: "libCall", fn: "sp.new", args: [], type: SEARCH_PARAMS_T, loc };
|
||||
// Each value is a USVString. A typed value lowers into the string
|
||||
@@ -274,18 +279,109 @@ function lowerSearchParamsInit(lowerer: Lowerer, arg: ts.Expression, loc: SrcLoc
|
||||
coerces: true,
|
||||
};
|
||||
};
|
||||
const pairs: { key: string; keyLoc: SrcLoc; value: ValueOf }[] = [];
|
||||
for (const prop of arg.properties.nodes) {
|
||||
/** One property the literal writes: its key, the location for its
|
||||
* diagnostic, and its value. */
|
||||
type LiteralPair = { key: string; keyLoc: SrcLoc; value: ValueOf };
|
||||
/** A spread of a CLOSED record: the source expression, evaluated once
|
||||
* at the spread's position, and the declared fields that bound what the
|
||||
* fold accepts. The copy itself is the runtime's own-property copy. */
|
||||
type SpreadGroup = {
|
||||
source: { id: string; type: IrType };
|
||||
decl: IrStmt;
|
||||
};
|
||||
type Part = { pair: LiteralPair } | { group: SpreadGroup };
|
||||
const pairs: LiteralPair[] = [];
|
||||
// The literal's parts in SOURCE order: Node evaluates them in this
|
||||
// order (a spread copies its source's fields where it stands), and only
|
||||
// then does the constructor append entries in the merged record's key
|
||||
// order.
|
||||
const parts: Part[] = [];
|
||||
let hasSpread = false;
|
||||
// One property of the init literal, in source order. A property of an
|
||||
// object literal the init spreads enters here in place: Node evaluates
|
||||
// that literal, and copies its properties, where the spread stands.
|
||||
const addProperty = (prop: ts.ObjectLiteralElementLike): void => {
|
||||
// `{ model }` appends the binding's value under its own name, like
|
||||
// the `{ model: model }` spelling.
|
||||
if (ts.isShorthandPropertyAssignment(prop)) {
|
||||
const key = (prop.name as ts.Identifier | ts.StringLiteral).text;
|
||||
pairs.push({
|
||||
const pair: LiteralPair = {
|
||||
key,
|
||||
keyLoc: locOf(prop.name),
|
||||
value: valueOf(prop.name, () => lowerer.lowerShorthandValue(prop)),
|
||||
});
|
||||
continue;
|
||||
};
|
||||
pairs.push(pair);
|
||||
parts.push({ pair });
|
||||
return;
|
||||
}
|
||||
if (ts.isSpreadAssignment(prop)) {
|
||||
let inner = prop.expression;
|
||||
while (ts.isParenthesizedExpression(inner)) inner = inner.expression;
|
||||
if (ts.isObjectLiteralExpression(inner)) {
|
||||
// An inline literal source is evaluated here, as JavaScript
|
||||
// evaluates it, and its own properties are copied into the merge:
|
||||
// computed keys, nested spreads and accessors all come through the
|
||||
// checked-dynamic object the literal builds, so a later entry
|
||||
// replaces its keys in place like any other spread's.
|
||||
const lowered = lowerDynObjectLiteral(lowerer, inner);
|
||||
const local = lowerer.declareHiddenLocal("%spSpread", DYN);
|
||||
hasSpread = true;
|
||||
parts.push({
|
||||
group: {
|
||||
source: { id: local.id, type: DYN },
|
||||
decl: { kind: "varDecl", localId: local.id, init: lowered, loc: locOf(prop) },
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
// A spread of a CLOSED record whose keys no other entry names: the
|
||||
// source evaluates once at the spread's position, its present
|
||||
// fields are copied there, and the merged object appends them in
|
||||
// the order the source enumerates its keys. Anything else — an
|
||||
// index signature (keys only known at run time), a tuple, an
|
||||
// accessor record — stays outside the fold.
|
||||
//
|
||||
// The spread copies the value's own enumerable fields, so the
|
||||
// shape is the one the lowered value has.
|
||||
const src = lowerer.lowerExpr(prop.expression);
|
||||
const shape = src.type.kind === "record" ? lowerer.shapes.get(src.type.shapeId) : undefined;
|
||||
if (
|
||||
src.type.kind !== "record" ||
|
||||
!shape ||
|
||||
shape.tuple ||
|
||||
shape.indexValue !== undefined ||
|
||||
shape.accessorOrder !== undefined ||
|
||||
shape.fields.some((field) => field.name.startsWith("%"))
|
||||
) {
|
||||
lowerer.unsupported(
|
||||
"SC1090",
|
||||
prop,
|
||||
"URLSearchParams record inits with spreads of anything but a closed record of strings",
|
||||
);
|
||||
}
|
||||
// A spread copies the source's own enumerable fields, so this
|
||||
// surface reads the record's key order.
|
||||
const type: IrType & { kind: "record" } = src.type;
|
||||
lowerer.keyOrder.observe(type);
|
||||
const fields = shape.fields
|
||||
.filter((field) => !field.name.startsWith("%"))
|
||||
.map((field) => ({ name: field.name, type: field.type }));
|
||||
for (const field of fields) {
|
||||
if (field.type.kind !== "string" && !lowerer.dynConvertible(field.type))
|
||||
lowerer.unsupported(
|
||||
"SC1090",
|
||||
prop,
|
||||
"URLSearchParams record inits whose spread source holds a non-string field",
|
||||
);
|
||||
}
|
||||
const local = lowerer.declareHiddenLocal("%spSpread", type);
|
||||
const group: SpreadGroup = {
|
||||
source: { id: local.id, type },
|
||||
decl: { kind: "varDecl", localId: local.id, init: src, loc: locOf(prop) },
|
||||
};
|
||||
hasSpread = true;
|
||||
parts.push({ group });
|
||||
return;
|
||||
}
|
||||
if (!ts.isPropertyAssignment(prop) || prop.name === undefined) {
|
||||
lowerer.unsupported(
|
||||
@@ -308,17 +404,102 @@ function lowerSearchParamsInit(lowerer: Lowerer, arg: ts.Expression, loc: SrcLoc
|
||||
"non-literal keys in a URLSearchParams record init",
|
||||
);
|
||||
}
|
||||
pairs.push({
|
||||
const pair: LiteralPair = {
|
||||
key,
|
||||
keyLoc: locOf(prop.name),
|
||||
value: valueOf(prop.initializer, () => lowerer.lowerExpr(prop.initializer)),
|
||||
});
|
||||
}
|
||||
};
|
||||
pairs.push(pair);
|
||||
parts.push({ pair });
|
||||
};
|
||||
for (const prop of arg.properties.nodes) addProperty(prop);
|
||||
// Reflect.ownKeys order: the integer index keys ascending, then the
|
||||
// other string keys in source order. (tsc rejects a literal that names
|
||||
// one property twice, so every key here is distinct.)
|
||||
const isIndexKey = (key: string): boolean =>
|
||||
/^(?:0|[1-9][0-9]*)$/.test(key) && Number(key) < 4294967295;
|
||||
if (hasSpread) {
|
||||
// Node builds the literal's object in SOURCE order: a property stores
|
||||
// its value where it stands, and a spread copies the source's own
|
||||
// enumerable properties there. The constructor then appends in the
|
||||
// merged object's own-key order (integer index keys ascending, then
|
||||
// creation order), and a later part that names an existing key
|
||||
// overwrites it in place. Building that object in the checked-dynamic
|
||||
// tree answers all of it through the runtime's record enumeration,
|
||||
// including keys a spread source holds beyond its declared type (a
|
||||
// value converted from dynamic data keeps them).
|
||||
const stmts: IrStmt[] = [];
|
||||
const merged = lowerer.declareHiddenLocal("%spMerge", DYN);
|
||||
stmts.push({
|
||||
kind: "varDecl",
|
||||
localId: merged.id,
|
||||
init: { kind: "dynObjLit", fields: [], type: DYN, loc },
|
||||
loc,
|
||||
});
|
||||
for (const part of parts) {
|
||||
if ("pair" in part) {
|
||||
const pair = part.pair;
|
||||
const value = pair.value.value;
|
||||
stmts.push({
|
||||
kind: "exprStmt",
|
||||
expr: {
|
||||
kind: "libCall",
|
||||
fn: "dyn.keySet",
|
||||
args: [
|
||||
varRef(merged.id, DYN, loc),
|
||||
{ kind: "strLit", value: pair.key, type: STRING, loc: pair.keyLoc },
|
||||
value.type.kind === "dyn"
|
||||
? value
|
||||
: { kind: "dynFrom", value, type: DYN, loc: value.loc },
|
||||
],
|
||||
type: VOID,
|
||||
loc: pair.keyLoc,
|
||||
},
|
||||
loc,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const group = part.group;
|
||||
stmts.push(group.decl);
|
||||
// The spread's copy reads the live view of the source at this
|
||||
// position: an omitted optional field contributes no entry, a field
|
||||
// written after the conversion keeps its current value, and a write
|
||||
// a later initializer makes cannot reach the copy.
|
||||
stmts.push({
|
||||
kind: "exprStmt",
|
||||
expr: {
|
||||
kind: "libCall",
|
||||
fn: "dyn.copyDataProperties",
|
||||
args: [
|
||||
varRef(merged.id, DYN, loc),
|
||||
group.source.type.kind === "dyn"
|
||||
? varRef(group.source.id, group.source.type, group.decl.loc)
|
||||
: {
|
||||
kind: "dynFrom",
|
||||
value: varRef(group.source.id, group.source.type, group.decl.loc),
|
||||
liveRef: true,
|
||||
type: DYN,
|
||||
loc: group.decl.loc,
|
||||
},
|
||||
],
|
||||
type: DYN,
|
||||
loc: group.decl.loc,
|
||||
},
|
||||
loc,
|
||||
});
|
||||
}
|
||||
return {
|
||||
kind: "seqExpr",
|
||||
stmts,
|
||||
result: {
|
||||
kind: "libCall",
|
||||
fn: "sp.newChecked",
|
||||
args: [varRef(merged.id, DYN, loc)],
|
||||
type: SEARCH_PARAMS_T,
|
||||
loc,
|
||||
},
|
||||
type: SEARCH_PARAMS_T,
|
||||
loc,
|
||||
};
|
||||
}
|
||||
const indexed = pairs.map((pair, source) => ({ pair, source }));
|
||||
const ordered = [
|
||||
...indexed
|
||||
|
||||
@@ -45,6 +45,7 @@ import {
|
||||
type InlineRequire,
|
||||
} from "./cjs-inline-require.js";
|
||||
import { isCjsExportsIdentifier, isCjsModuleExports } from "./cjs-exports-object.js";
|
||||
import { isRebindableRequireDecl } from "./rebindable-requires.js";
|
||||
import { usesCjsTopLevelThis } from "./lower-node-module.js";
|
||||
import { v8CalleeText } from "./expressions/narrowing.js";
|
||||
import { cjsAccessorValue } from "./lower-exprs.js";
|
||||
@@ -190,12 +191,20 @@ export function cjsExportsObjectModules(lowerer: Lowerer): Set<ts.SourceFile> {
|
||||
if (ts.isCallExpression(node)) {
|
||||
const req = inlineNamespaceRequireOf(lowerer, node);
|
||||
if (req === null) return undefined;
|
||||
// The initializer of a module binding is the binding, not a value.
|
||||
// The initializer of a module binding is the binding, not a value —
|
||||
// except a binding the file reassigns: that one stores the module's
|
||||
// value in checked-dynamic storage, so every read through it is a
|
||||
// read of the module's exports object (rebindable-requires.ts).
|
||||
let outer: ts.Node = node;
|
||||
while (outer.parent !== undefined && ts.isParenthesizedExpression(outer.parent))
|
||||
outer = outer.parent;
|
||||
if (ts.isVariableDeclaration(outer.parent!) && outer.parent.initializer === outer)
|
||||
if (ts.isVariableDeclaration(outer.parent!) && outer.parent.initializer === outer) {
|
||||
if (isRebindableRequireDecl(lowerer, outer.parent)) {
|
||||
const bound = cjsNamespaceTargetOf(lowerer, req.dep);
|
||||
if (bound !== null) addValueUse(node, bound);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
if (ts.isExpressionStatement(outer.parent!)) return undefined;
|
||||
// `module.exports = require("./m")` forwards the module's table and
|
||||
// `l = require("./m")` binds a split or conditional alias: both read
|
||||
|
||||
@@ -37,6 +37,7 @@ import {
|
||||
splitRequireCallOf,
|
||||
} from "../program.js";
|
||||
import { createRequireCalleeFileOf } from "./builtins/module-bindings.js";
|
||||
import { cjsGetterTableOf } from "../cjs-getter-table.js";
|
||||
import { isCjsRequireGlobal } from "./lower-node-module.js";
|
||||
import {
|
||||
BOOL,
|
||||
@@ -612,6 +613,11 @@ export function cjsWholeExportValueOf(
|
||||
if (cjs?.kind === "table" && cjsExportDiscardReason(stmt) === null) kept = cjs.expr;
|
||||
}
|
||||
if (kept === null) return null;
|
||||
// esbuild's getter table is an export TABLE: `__export(T, {...})` defines
|
||||
// the members on T, and `module.exports = T` names it, so requiring
|
||||
// modules read its members like a `module.exports = {...}` table rather
|
||||
// than one whole value.
|
||||
if (cjsGetterTableOf(sf)?.install === kept) return null;
|
||||
let rhs: ts.Expression = kept.right;
|
||||
while (ts.isParenthesizedExpression(rhs)) rhs = rhs.expression;
|
||||
if (ts.isObjectLiteralExpression(rhs) || cjsExportTargetLiteral(rhs, sf) !== null) return null;
|
||||
@@ -1637,15 +1643,23 @@ export function cjsTableExportNamesOf(
|
||||
for (const name of innerNames) add(name);
|
||||
} else {
|
||||
const lit = table.obj ?? cjsExportTargetLiteral(rhs, dep);
|
||||
if (lit === null) return null;
|
||||
for (const prop of lit.properties.nodes) {
|
||||
if (ts.isSpreadAssignment(prop)) return null;
|
||||
const nameNode = prop.name;
|
||||
if (nameNode === undefined || ts.isComputedPropertyName(nameNode)) return null;
|
||||
if (!(ts.isIdentifier(nameNode) || ts.isStringLiteralLike(nameNode))) return null;
|
||||
// `__proto__: value` sets the prototype; it is not an own key.
|
||||
if (nameNode.text === "__proto__" && !ts.isShorthandPropertyAssignment(prop)) continue;
|
||||
add(nameNode.text);
|
||||
if (lit === null) {
|
||||
// esbuild's getter table (`var T = {}; __export(T, {...});
|
||||
// module.exports = T`): the getters are the exports object's own
|
||||
// enumerable keys, in table order.
|
||||
const getter = cjsGetterTableOf(dep);
|
||||
if (getter === null || getter.install !== table.expr) return null;
|
||||
for (const name of getter.entries.keys()) add(name);
|
||||
} else {
|
||||
for (const prop of lit.properties.nodes) {
|
||||
if (ts.isSpreadAssignment(prop)) return null;
|
||||
const nameNode = prop.name;
|
||||
if (nameNode === undefined || ts.isComputedPropertyName(nameNode)) return null;
|
||||
if (!(ts.isIdentifier(nameNode) || ts.isStringLiteralLike(nameNode))) return null;
|
||||
// `__proto__: value` sets the prototype; it is not an own key.
|
||||
if (nameNode.text === "__proto__" && !ts.isShorthandPropertyAssignment(prop)) continue;
|
||||
add(nameNode.text);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (let i = lastTable + 1; i < stmts.length; i++) {
|
||||
@@ -1854,10 +1868,16 @@ export function cjsRequireSnapshotBindingsOf(
|
||||
// exports object's member at this statement — the value Node
|
||||
// destructures, undefined included.
|
||||
const partial = lowerer.program.analysis.partialCjsCycleMembers.has(dep);
|
||||
// esbuild's getter table: every entry is a getter Node runs once at the
|
||||
// destructuring read, so the binding snapshots the value here even when
|
||||
// the getter returns a plain module-level binding nothing ever writes at
|
||||
// the export property (a later reassignment of that binding must not
|
||||
// reach the destructured copy).
|
||||
const getterTable = lowerer.getterTableOf(dep) !== null;
|
||||
for (const element of decl.name.elements.nodes) {
|
||||
const binding = cjsNamedBindingOf(lowerer, element);
|
||||
if (binding === null) continue;
|
||||
if (partial) {
|
||||
if (partial || getterTable) {
|
||||
bindings.set(element, binding);
|
||||
continue;
|
||||
}
|
||||
@@ -1939,9 +1959,42 @@ export function cjsExportValueByName(
|
||||
if ((ts.isFunctionDeclaration(d) || ts.isClassDeclaration(d)) && d.name !== undefined)
|
||||
if (declarationIsModuleLevel(lowerer, d)) return lowerer.lowerExpr(d.name);
|
||||
}
|
||||
// esbuild's getter table: a getter body that is not one module-level
|
||||
// identifier (`metaTag: () => pkgmeta.tag`) has no export symbol of its
|
||||
// own. Node runs the getter on every read, so the value is the returned
|
||||
// expression evaluated here, at the read site.
|
||||
const getterValue = lowerer.getterTableOf(dep)?.entries.get(key);
|
||||
if (getterValue !== undefined) return lowerer.lowerExpr(getterValue);
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The export symbol a member of a CommonJS require binding names when the
|
||||
* checker's module shape omits it: esbuild's getter table defines its
|
||||
* exports with `__export(T, { name: () => value })`, so the checker sees
|
||||
* only `module.exports = T` (an empty object) and resolves no member.
|
||||
* The getter's returned identifier is the module-level binding Node's
|
||||
* getter reads — the symbol a plain `exports.name = name` export resolves
|
||||
* to, which every member path (heritage, calls, reads) already handles.
|
||||
* Null for other members and for getter values that are not a single
|
||||
* identifier (those lower through cjsExportValueByName). */
|
||||
export function cjsTableMemberSymbolOf(
|
||||
lowerer: Lowerer,
|
||||
access: ts.PropertyAccessExpression,
|
||||
): ts.Symbol | null {
|
||||
if (access.questionDotToken !== undefined || !ts.isIdentifier(access.name)) return null;
|
||||
const recv = access.expression;
|
||||
if (!lowerer.cjsLocalModuleBindingOf(recv)) return null;
|
||||
const dep = ts.isIdentifier(recv)
|
||||
? lowerer.cjsModuleBindingDepOf(recv)
|
||||
: lowerer.cjsModuleRefDepOf(recv);
|
||||
if (dep === null) return null;
|
||||
const value = lowerer.getterTableOf(dep)?.entries.get(access.name.text);
|
||||
if (value === undefined || !ts.isIdentifier(value)) return null;
|
||||
const symbol = lowerer.checker.getSymbolAtLocation(value);
|
||||
if (symbol === undefined) return null;
|
||||
return symbol.flags & ts.SymbolFlags.Alias ? lowerer.checker.getAliasedSymbol(symbol) : symbol;
|
||||
}
|
||||
|
||||
/** The own property names of Object.prototype: a plain CommonJS exports
|
||||
* object answers reads of these through its prototype chain, so they are
|
||||
* not absent from it even though no export statement names them. */
|
||||
@@ -2021,6 +2074,11 @@ export function cjsModuleLacksExport(
|
||||
if (cjsExportsObjectIsProxy(target)) return false;
|
||||
if (lowerer.cjsModuleExportSymbol(target, name) !== undefined) return false;
|
||||
if (lowerer.cjsInFileExportMemberGlobals.get(target)?.has(name) === true) return false;
|
||||
// esbuild's getter table defines its entries as enumerable getters on the
|
||||
// exports object, so `require()` answers them like plain member exports;
|
||||
// Node's lexer does not see them (the ESM facade needs esbuild's dead
|
||||
// `0 && (module.exports = {...})` annotation), but a require read does.
|
||||
if (lowerer.getterTableOf(target)?.entries.has(name) === true) return false;
|
||||
return !lowerer.cjsNamespaceOf(target).names.has(name);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { expect, test } from "vitest";
|
||||
import { descendantClasses } from "./class-descendants.js";
|
||||
|
||||
test("a class listed under two names is reached once", () => {
|
||||
// A class is a child of both its base's own name and its generic family,
|
||||
// and a deeper class hangs off both of those names: every level would
|
||||
// double the walk if a visited name were not pruned.
|
||||
const children = new Map<string, string[]>([
|
||||
["Base", ["Level0", "Level0"]],
|
||||
["Level0", ["Level1", "Level1"]],
|
||||
["Level1", ["Level2", "Level2"]],
|
||||
["Level2", []],
|
||||
]);
|
||||
const reached = descendantClasses(children, "Base");
|
||||
expect(reached.sort()).toEqual(["Level0", "Level1", "Level2"]);
|
||||
});
|
||||
|
||||
test("a reconverging path does not revisit a class", () => {
|
||||
const children = new Map<string, string[]>([
|
||||
["A", ["B", "C"]],
|
||||
["B", ["D"]],
|
||||
["C", ["D"]],
|
||||
["D", ["E"]],
|
||||
["E", []],
|
||||
]);
|
||||
const reached = descendantClasses(children, "A");
|
||||
expect(reached.sort()).toEqual(["B", "C", "D", "E"]);
|
||||
expect(new Set(reached).size).toBe(reached.length);
|
||||
});
|
||||
|
||||
test("a long chain whose links carry two names stays linear", () => {
|
||||
const depth = 30;
|
||||
const children = new Map<string, string[]>();
|
||||
for (let level = 0; level < depth; level++)
|
||||
children.set(level === 0 ? "Base" : `Level${level - 1}`, [`Level${level}`, `Level${level}`]);
|
||||
children.set(`Level${depth - 1}`, []);
|
||||
const start = performance.now();
|
||||
const reached = descendantClasses(children, "Base");
|
||||
const elapsed = performance.now() - start;
|
||||
expect(reached.length).toBe(depth);
|
||||
// An unpruned walk follows every path: 2^30 visits for this map, which
|
||||
// exhausts the stack and the heap long before it finishes.
|
||||
expect(elapsed).toBeLessThan(1_000);
|
||||
});
|
||||
|
||||
test("the start class is never part of its own descendants", () => {
|
||||
const children = new Map<string, string[]>([
|
||||
["A", ["A", "B"]],
|
||||
["B", []],
|
||||
]);
|
||||
expect(descendantClasses(children, "A")).toEqual(["B"]);
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
/** The classes a reverse map of superclass edges reaches from `className`.
|
||||
*
|
||||
* The compiler's own map lists a class under every name `isSubclassOf`
|
||||
* recognizes as its superclass: its bases along the `base` chain and each
|
||||
* generic family. Two of those names can lead to the same class, so the walk
|
||||
* prunes a name before pushing its children — a path that reconverges must not
|
||||
* be explored again, or the walk grows with the number of paths (which is
|
||||
* exponential in the depth of a chain whose links carry two names) instead of
|
||||
* with the number of classes. */
|
||||
export function descendantClasses(
|
||||
children: ReadonlyMap<string, readonly string[]>,
|
||||
className: string,
|
||||
): string[] {
|
||||
const out: string[] = [];
|
||||
const seen = new Set<string>([className]);
|
||||
const stack = [...(children.get(className) ?? [])];
|
||||
while (stack.length > 0) {
|
||||
const name = stack.pop()!;
|
||||
if (seen.has(name)) continue;
|
||||
seen.add(name);
|
||||
out.push(name);
|
||||
for (const child of children.get(name) ?? []) stack.push(child);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { dynUndefinedExpr, helperLoc, nodeThrowExpr, numLit, varRef } from "../.
|
||||
import { classKeyHash, classValueSlot, classValueSlotBits } from "../../ir/class-key-index.js";
|
||||
import { classCaseBranches, isClassCaseDispatch } from "../../ir/class-case.js";
|
||||
import { constructedDynValue } from "./constructor-returns.js";
|
||||
import { descendantClasses } from "./class-descendants.js";
|
||||
import { eventTargetApiMembers, eventTargetInheritedMember } from "./lower-event-target.js";
|
||||
import {
|
||||
DATE_PROTOTYPE_METHOD_NAMES,
|
||||
@@ -2115,6 +2116,19 @@ export function groupStaticFieldBranches(
|
||||
return rebuilt ?? body;
|
||||
}
|
||||
|
||||
/** The superclasses `isSubclassOf` (lower-classes.ts) recognizes for `info`:
|
||||
* each class up its `base` chain, and each generic family of every class on
|
||||
* that chain. */
|
||||
function superclassNames(info: ClassInfo): string[] {
|
||||
const names: string[] = [];
|
||||
for (let c: ClassInfo | null = info; c !== null; c = c.base) {
|
||||
if (c.def.name !== info.def.name) names.push(c.def.name);
|
||||
for (let family = c.genericInstance?.family; family; family = family.base ?? undefined)
|
||||
names.push(family.def.name);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
/** A static field a class value can write: one per class the value can hold
|
||||
* on which `name` is a static field of a class whose table is installed.
|
||||
* `own` says the class itself declares it. */
|
||||
@@ -2404,11 +2418,9 @@ export class ClassDynamicDispatch {
|
||||
* compiled code that reads the field sees what reflection sees. */
|
||||
private branchComputedStaticWrites(lowerer: Lowerer): boolean {
|
||||
if (this.staticTablesInstalled.size === 0) return false;
|
||||
const names = new Set<string>();
|
||||
for (const className of this.staticTablesInstalled) {
|
||||
const info = lowerer.classes.get(className);
|
||||
if (info) for (const field of staticTableFields(lowerer, info)) names.add(field.name);
|
||||
}
|
||||
// The field names the installed tables list, built once and only when a
|
||||
// dispatch actually has a wave to scan.
|
||||
let names: Set<string> | null = null;
|
||||
const index = this.waveIndex(lowerer);
|
||||
let changed = false;
|
||||
for (const dispatch of this.computed.values()) {
|
||||
@@ -2420,11 +2432,21 @@ export class ClassDynamicDispatch {
|
||||
const scan = `${index.boxed}:${index.tables}`;
|
||||
if (this.computedScans.get(dispatch) === scan) continue;
|
||||
this.computedScans.set(dispatch, scan);
|
||||
if (names === null) {
|
||||
names = new Set<string>();
|
||||
for (const className of this.staticTablesInstalled) {
|
||||
const info = lowerer.classes.get(className);
|
||||
if (info) for (const field of staticTableFields(lowerer, info)) names.add(field.name);
|
||||
}
|
||||
}
|
||||
const reflect = fn.params.some((param) => param.localId === "p.reflectReceiver");
|
||||
const loc = fn.loc;
|
||||
const value = varRef("p.0", DYN, loc);
|
||||
const stored = varRef("p.1", DYN, loc);
|
||||
const keyRead = varRef(dispatch.keyLocal, STRING, loc);
|
||||
// The branches go in after the statement that computes the key's string,
|
||||
// if any: one copy of the body for the wave instead of one per branch.
|
||||
const branches: IrStmt[] = [];
|
||||
for (const keyClass of this.boxedConstructors)
|
||||
for (const name of names) {
|
||||
if (index.writeKeys.get(name)?.has(keyClass) !== true) continue;
|
||||
@@ -2553,15 +2575,19 @@ export class ClassDynamicDispatch {
|
||||
actual: target.actual,
|
||||
ready: false,
|
||||
});
|
||||
// After the statement that computes the key's string, if any.
|
||||
const at = fn.body.findIndex(
|
||||
(statement) =>
|
||||
statement.kind === "varDecl" && statement.localId === dispatch.keyLocal,
|
||||
);
|
||||
fn.body = [...fn.body.slice(0, at + 1), branch, ...fn.body.slice(at + 1)];
|
||||
branches.push(branch);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (branches.length > 0) {
|
||||
const at =
|
||||
fn.body.findIndex(
|
||||
(statement) => statement.kind === "varDecl" && statement.localId === dispatch.keyLocal,
|
||||
) + 1;
|
||||
// Successive insertions at the same index left the branches in reverse
|
||||
// order; keep that order in one pass over the body.
|
||||
fn.body = [...fn.body.slice(0, at), ...branches.reverse(), ...fn.body.slice(at)];
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
@@ -2734,9 +2760,17 @@ export class ClassDynamicDispatch {
|
||||
loc: at,
|
||||
});
|
||||
const match = matches ?? keyIs;
|
||||
// The wave index already holds each boxed class's installed descendants in
|
||||
// installation order (the per-pair subclass walk's answer), so a helper
|
||||
// visits its own classes instead of every installed table.
|
||||
const index = this.waveIndex(lowerer);
|
||||
// After the key's conversion, which leads the helper's body; the branches
|
||||
// are spliced in together at the end (one shift of the body, not one per
|
||||
// branch, and successive insertions at this index reversed their order).
|
||||
const at = isStaticKeyConversion(helper.body[0]) ? 1 : 0;
|
||||
const added: IrStmt[] = [];
|
||||
for (const keyClass of this.boxedConstructors)
|
||||
for (const actual of [keyClass, ...this.staticTablesInstalled]) {
|
||||
if (actual !== keyClass && !lowerer.isSubclassOf(actual, keyClass)) continue;
|
||||
for (const actual of [keyClass, ...(index.descendants.get(keyClass) ?? [])]) {
|
||||
const info = lowerer.classes.get(actual);
|
||||
if (!info || !this.staticTablesInstalled.has(actual)) continue;
|
||||
for (let owner: ClassInfo | null = info; owner; owner = owner.base) {
|
||||
@@ -2745,8 +2779,6 @@ export class ClassDynamicDispatch {
|
||||
const id = `${helper.name}\0${keyClass}\0${actual}\0${field.name}`;
|
||||
if (this.computedStaticWrites.has(id)) continue;
|
||||
this.computedStaticWrites.add(id);
|
||||
// After the key's conversion, which leads the helper's body.
|
||||
const at = isStaticKeyConversion(helper.body[0]) ? 1 : 0;
|
||||
const branch: IrStmt = {
|
||||
kind: "if",
|
||||
cond: {
|
||||
@@ -2781,11 +2813,24 @@ export class ClassDynamicDispatch {
|
||||
};
|
||||
this.staticFieldBranches.set(branch, { value: target, keyClass, actual, ready: true });
|
||||
this.fenceBranches.add(branch);
|
||||
helper.body.splice(at, 0, branch);
|
||||
added.push(branch);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (added.length > 0) {
|
||||
// The batch is one branch per class and static field, so a large program
|
||||
// reaches tens of thousands of entries: spreading them into splice()
|
||||
// passes them as call arguments and overflows the engine's argument
|
||||
// limit. Assemble the body instead, in the order successive insertions
|
||||
// at this index left.
|
||||
const body: IrStmt[] = [];
|
||||
for (let index = 0; index < at && index < helper.body.length; index++)
|
||||
body.push(helper.body[index]!);
|
||||
for (let index = added.length - 1; index >= 0; index--) body.push(added[index]!);
|
||||
for (let index = at; index < helper.body.length; index++) body.push(helper.body[index]!);
|
||||
helper.body = body;
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
@@ -3131,20 +3176,39 @@ export class ClassDynamicDispatch {
|
||||
const add = (info: ClassInfo | null): void => {
|
||||
if (info) candidates.set(info.def.name, info);
|
||||
};
|
||||
// A boxed class's descendants are found by walking a reverse map of the
|
||||
// chain `isSubclassOf` follows (each class's bases and generic families)
|
||||
// instead of testing every class in the program against every boxed
|
||||
// class, which grew with the product of the two.
|
||||
const children = new Map<string, string[]>();
|
||||
const order = new Map<string, number>();
|
||||
for (const other of lowerer.classes.values()) {
|
||||
order.set(other.def.name, order.size);
|
||||
for (const parent of superclassNames(other)) {
|
||||
let list = children.get(parent);
|
||||
if (list === undefined) children.set(parent, (list = []));
|
||||
list.push(other.def.name);
|
||||
}
|
||||
}
|
||||
const descendants = (className: string): string[] =>
|
||||
// The scan this replaces visited classes in declaration order.
|
||||
descendantClasses(children, className).sort(
|
||||
(left, right) => (order.get(left) ?? 0) - (order.get(right) ?? 0),
|
||||
);
|
||||
for (const name of this.boxedConstructors) {
|
||||
const info = lowerer.classes.get(name);
|
||||
if (!info) continue;
|
||||
add(info);
|
||||
for (let base = info.base; base; base = base.base) add(base);
|
||||
for (const other of lowerer.classes.values()) {
|
||||
if (other === info || !lowerer.isSubclassOf(other.def.name, info.def.name)) continue;
|
||||
for (const otherName of descendants(info.def.name)) {
|
||||
const other = lowerer.classes.get(otherName);
|
||||
// A slot typed with the boxed class can only hold a descendant this
|
||||
// build retains (classCanBeConstructed). A descendant whose
|
||||
// constructor the reachable graph dropped has no instance and no
|
||||
// class value to reflect on, and installing its table would name its
|
||||
// class value — pulling its declaration-time code into a library
|
||||
// graph that does not reach it.
|
||||
if (lowerer.classCanBeConstructed(other)) add(other);
|
||||
if (other !== undefined && lowerer.classCanBeConstructed(other)) add(other);
|
||||
}
|
||||
}
|
||||
// Ancestors install first: a table links to its base's, so the base's
|
||||
|
||||
@@ -219,18 +219,20 @@ export function narrowUnionToClassUnion(
|
||||
if (sourceTag < 0) return null;
|
||||
plan.push({ sourceTag, targetTag, arm });
|
||||
}
|
||||
// A dropped arm that is a unit type (undefined, void, null) is not a
|
||||
// stranded class: an untyped JavaScript read can still hold it where the
|
||||
// checker narrowed to the class arms (three.js hands a possibly-undefined
|
||||
// `geometry.attributes.uv` to a parameter the checker types as the class
|
||||
// pair). Keep the stored union for those; only a dropped non-unit arm is
|
||||
// the Map-beside-classes case this helper answers.
|
||||
// A retag is needed only when an arm the checker dropped changes the
|
||||
// union's representation (a Map beside node classes). A dropped unit arm
|
||||
// (undefined, void, null) does not: an untyped JavaScript read can still
|
||||
// hold it where the checker narrowed to the class arms (three.js hands a
|
||||
// possibly-undefined `geometry.attributes.uv` to a parameter the checker
|
||||
// types as the class pair), and retagging it would trap. Decline only
|
||||
// when every dropped arm is a unit; a dropped non-unit arm keeps the
|
||||
// retag even when a unit is dropped beside it.
|
||||
const kept = new Set(plan.map((entry) => entry.sourceTag));
|
||||
for (let tag = 0; tag < sourceArms.length; tag++) {
|
||||
if (kept.has(tag)) continue;
|
||||
const arm = sourceArms[tag]!;
|
||||
if (arm.kind === "undefinedT" || arm.kind === "void" || arm.kind === "nullT") return null;
|
||||
}
|
||||
const dropsNonUnit = sourceArms.some(
|
||||
(arm, tag) =>
|
||||
!kept.has(tag) && arm.kind !== "undefinedT" && arm.kind !== "void" && arm.kind !== "nullT",
|
||||
);
|
||||
if (!dropsNonUnit) return null;
|
||||
const loc = value.loc;
|
||||
const key = `union.classUnion:${value.type.unionId}:${target.unionId}`;
|
||||
let helper = lowerer.valueHelpers.get(key);
|
||||
|
||||
@@ -154,7 +154,10 @@ export function lowerCodeGenerationCall(
|
||||
stmts.push({ kind: "exprStmt", expr: receiver, loc: locOf(receiverNode) });
|
||||
}
|
||||
for (const operand of indirectEvalPrefix(expr.expression)) {
|
||||
stmts.push({ kind: "exprStmt", expr: lowerer.lowerExpr(operand), loc: locOf(operand) });
|
||||
// The operands are evaluated for their effects and discarded; a unit
|
||||
// value (`void 0` in `(void 0, eval)(...)`) has no standalone IR value,
|
||||
// so it lowers as a statement, which discards it exactly.
|
||||
stmts.push(lowerer.lowerExprStatement(operand));
|
||||
}
|
||||
const argNodes = expr.arguments?.nodes ?? [];
|
||||
if (kind === "Function" && argNodes.some((arg) => ts.isSpreadElement(arg))) {
|
||||
|
||||
@@ -0,0 +1,663 @@
|
||||
/* `emitDecoratorMetadata` design-type serialization.
|
||||
*
|
||||
* TypeScript's legacy emit appends `__metadata(key, value)` entries to a
|
||||
* decorated declaration's decorator array, after the member decorators and
|
||||
* the `__param` entries:
|
||||
*
|
||||
* __decorate([
|
||||
* dec, __param(0, pdec),
|
||||
* __metadata("design:type", Function),
|
||||
* __metadata("design:paramtypes", [Dep, String]),
|
||||
* __metadata("design:returntype", void 0)
|
||||
* ], C.prototype, "m", null);
|
||||
*
|
||||
* `__metadata(k, v)` is `Reflect.metadata(k, v)` when the global carries the
|
||||
* function (the reflect-metadata polyfill) and undefined otherwise, which
|
||||
* the helper's falsy check skips. Reverse application therefore runs the
|
||||
* metadata decorators first.
|
||||
*
|
||||
* The serialization below follows tsc's createRuntimeTypeSerializer
|
||||
* (transformers/ts.ts): design:type is the declared type annotation (Object
|
||||
* when there is none), paramtypes is the parameter list's annotations with a
|
||||
* rest parameter narrowed to its element type, returntype is a method's
|
||||
* annotation (Promise for an unannotated async method, void 0 otherwise).
|
||||
* A type serializes to a global constructor token (String, Number, Boolean,
|
||||
* Array, Function, Object, Promise, Symbol, BigInt or a runtime class such
|
||||
* as Date), to the class value a type names, to `void 0`, or to Object:
|
||||
*
|
||||
* - void, undefined, never, null: `void 0`;
|
||||
* - function and constructor types: Function; array and tuple types: Array;
|
||||
* - a predicate type: Boolean (void 0 for `asserts`);
|
||||
* - literal types: Number, String, Boolean by the literal's kind;
|
||||
* - enums: Number for a numeric enum, String for a string enum, Object for
|
||||
* a mixed one;
|
||||
* - interfaces, type aliases, type parameters, `any`, `unknown`, `object`,
|
||||
* intersections and type literals: Object;
|
||||
* - a union or conditional type: the constituents' serialization when they
|
||||
* all agree (ignoring never, and null/undefined under a project that
|
||||
* turns strictNullChecks off), else Object;
|
||||
* - a type reference to a class or other value: that value. The reference
|
||||
* is evaluated where tsc evaluates it — at the class statement, before
|
||||
* the decorators apply — so a later declaration throws its ReferenceError
|
||||
* there, exactly as the `__metadata("design:type", Dep)` call does.
|
||||
*
|
||||
* Whether a file emits metadata is its tsconfig's `emitDecoratorMetadata`
|
||||
* with `experimentalDecorators`: TypeWorldDifferences.decoratorMetadataFiles. */
|
||||
|
||||
import * as ts from "../ts7/adapter.js";
|
||||
import { DYN, STRING, type IrExpr, type SrcLoc } from "../../ir/ir.js";
|
||||
import { dynUndefinedExpr, nodeThrowExpr, varRef } from "../../ir/build.js";
|
||||
import { locOf } from "../program.js";
|
||||
import { builtinGlobalValue } from "./expressions/property-access.js";
|
||||
import { builtinNamespaceValue } from "./builtin-namespaces.js";
|
||||
import { jsSpecialGlobalValue } from "./global-values.js";
|
||||
import { classValueRef, type ClassInfo } from "./lower-classes.js";
|
||||
import type { Lowerer } from "./lowerer.js";
|
||||
|
||||
/** Whether the file holding `node` is compiled with `emitDecoratorMetadata`. */
|
||||
export function wantsDecoratorMetadata(lowerer: Lowerer, node: ts.Node): boolean {
|
||||
return lowerer.decoratorMetadataFiles?.has(ts.getSourceFileOfNode(node).fileName) === true;
|
||||
}
|
||||
|
||||
/** The design-type value of one serialization, before it is materialized:
|
||||
* `void 0`, a named global constructor or class (`String`, `Date`, `Dep`),
|
||||
* a compiled class value, or an ambient declaration's value expression. Two
|
||||
* unions agree when their keys agree, which is tsc's
|
||||
* equateSerializedTypeNodes for the expression shapes this emit produces. */
|
||||
type MetaToken =
|
||||
| { k: "void" }
|
||||
| { k: "global"; name: string }
|
||||
| { k: "class"; info: ClassInfo; blame: ts.Node; spelled: string }
|
||||
| { k: "entity"; node: ts.EntityName };
|
||||
|
||||
function tokenKey(token: MetaToken): string {
|
||||
switch (token.k) {
|
||||
case "void":
|
||||
return "void 0";
|
||||
case "global":
|
||||
return token.name;
|
||||
case "class":
|
||||
// tsc compares the emitted entity name's text, so an alias spelling
|
||||
// differs from the class's own name (`Dep | D` is Object).
|
||||
return token.spelled;
|
||||
case "entity":
|
||||
return entityNameText(token.node);
|
||||
}
|
||||
}
|
||||
|
||||
function entityNameText(node: ts.EntityName): string {
|
||||
return ts.isIdentifier(node) ? node.text : `${entityNameText(node.left)}.${node.right.text}`;
|
||||
}
|
||||
|
||||
const OBJ: MetaToken = { k: "global", name: "Object" };
|
||||
const VOID: MetaToken = { k: "void" };
|
||||
|
||||
/** Global constructors a design type may name directly, with the value the
|
||||
* program's own read of the name produces. Includes the runtime's interned
|
||||
* constructors and the primitive constructors' typed closures. */
|
||||
function globalTokenForName(name: string): MetaToken | null {
|
||||
switch (name) {
|
||||
case "String":
|
||||
case "Number":
|
||||
case "Boolean":
|
||||
case "Array":
|
||||
case "ReadonlyArray":
|
||||
case "Function":
|
||||
case "Object":
|
||||
case "Promise":
|
||||
case "Symbol":
|
||||
case "BigInt":
|
||||
return { k: "global", name: name === "ReadonlyArray" ? "Array" : name };
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The value a named global constructor or class serializes to. */
|
||||
function materializeGlobal(lowerer: Lowerer, name: string, loc: SrcLoc): IrExpr {
|
||||
const direct = builtinGlobalValue(name, loc);
|
||||
if (direct !== null) return lowerer.coerceToExpected(direct, DYN);
|
||||
const special = jsSpecialGlobalValue(lowerer, name, loc, false);
|
||||
if (special !== null) return lowerer.coerceToExpected(special, DYN);
|
||||
return dynUndefinedExpr(loc);
|
||||
}
|
||||
|
||||
function skipParens(node: ts.TypeNode): ts.TypeNode {
|
||||
while (ts.isParenthesizedTypeNode(node)) node = node.type;
|
||||
return node;
|
||||
}
|
||||
|
||||
function identifierName(node: ts.TypeNode): string | null {
|
||||
return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) ? node.typeName.text : null;
|
||||
}
|
||||
|
||||
function typeToken(lowerer: Lowerer, node: ts.TypeNode | undefined, container: ts.Node): MetaToken {
|
||||
if (node === undefined) return OBJ;
|
||||
node = skipParens(node);
|
||||
switch (node.kind) {
|
||||
case ts.SyntaxKind.VoidKeyword:
|
||||
case ts.SyntaxKind.UndefinedKeyword:
|
||||
case ts.SyntaxKind.NeverKeyword:
|
||||
return VOID;
|
||||
case ts.SyntaxKind.FunctionType:
|
||||
case ts.SyntaxKind.ConstructorType:
|
||||
return { k: "global", name: "Function" };
|
||||
case ts.SyntaxKind.ArrayType:
|
||||
case ts.SyntaxKind.TupleType:
|
||||
return { k: "global", name: "Array" };
|
||||
case ts.SyntaxKind.TypePredicate:
|
||||
return (node as ts.TypePredicateNode).assertsModifier !== undefined
|
||||
? VOID
|
||||
: { k: "global", name: "Boolean" };
|
||||
case ts.SyntaxKind.BooleanKeyword:
|
||||
return { k: "global", name: "Boolean" };
|
||||
case ts.SyntaxKind.TemplateLiteralType:
|
||||
case ts.SyntaxKind.StringKeyword:
|
||||
return { k: "global", name: "String" };
|
||||
case ts.SyntaxKind.NumberKeyword:
|
||||
return { k: "global", name: "Number" };
|
||||
case ts.SyntaxKind.ObjectKeyword:
|
||||
return OBJ;
|
||||
case ts.SyntaxKind.BigIntKeyword:
|
||||
return { k: "global", name: "BigInt" };
|
||||
case ts.SyntaxKind.SymbolKeyword:
|
||||
return { k: "global", name: "Symbol" };
|
||||
case ts.SyntaxKind.LiteralType:
|
||||
return literalToken((node as ts.LiteralTypeNode).literal);
|
||||
case ts.SyntaxKind.TypeReference:
|
||||
return typeReferenceToken(lowerer, node as ts.TypeReferenceNode, container);
|
||||
case ts.SyntaxKind.IntersectionType:
|
||||
return unionToken(lowerer, (node as ts.IntersectionTypeNode).types.nodes, true, container);
|
||||
case ts.SyntaxKind.UnionType:
|
||||
return unionToken(lowerer, (node as ts.UnionTypeNode).types.nodes, false, container);
|
||||
case ts.SyntaxKind.ConditionalType: {
|
||||
const conditional = node as ts.ConditionalTypeNode;
|
||||
return unionToken(lowerer, [conditional.trueType, conditional.falseType], false, container);
|
||||
}
|
||||
case ts.SyntaxKind.TypeOperator:
|
||||
// Only `readonly T` keeps the operand; `keyof` and `unique` are Object.
|
||||
return (node as ts.TypeOperatorNode).operator === ts.SyntaxKind.ReadonlyKeyword
|
||||
? typeToken(lowerer, (node as ts.TypeOperatorNode).type, container)
|
||||
: OBJ;
|
||||
default:
|
||||
// Type queries, indexed accesses, mapped types, type literals, `any`,
|
||||
// `unknown`, `this`, import types: Object.
|
||||
return OBJ;
|
||||
}
|
||||
}
|
||||
|
||||
function literalToken(literal: ts.LiteralTypeNode["literal"]): MetaToken {
|
||||
switch (literal.kind) {
|
||||
case ts.SyntaxKind.StringLiteral:
|
||||
case ts.SyntaxKind.NoSubstitutionTemplateLiteral:
|
||||
return { k: "global", name: "String" };
|
||||
case ts.SyntaxKind.NumericLiteral:
|
||||
return { k: "global", name: "Number" };
|
||||
case ts.SyntaxKind.BigIntLiteral:
|
||||
return { k: "global", name: "BigInt" };
|
||||
case ts.SyntaxKind.TrueKeyword:
|
||||
case ts.SyntaxKind.FalseKeyword:
|
||||
return { k: "global", name: "Boolean" };
|
||||
case ts.SyntaxKind.PrefixUnaryExpression:
|
||||
return literalToken(
|
||||
(literal as ts.PrefixUnaryExpression).operand as ts.LiteralTypeNode["literal"],
|
||||
);
|
||||
default:
|
||||
// A null literal type.
|
||||
return VOID;
|
||||
}
|
||||
}
|
||||
|
||||
/** tsc's serializeUnionOrIntersectionConstituents: every constituent
|
||||
* serializes alike or the answer is Object; `any` answers Object at once,
|
||||
* `unknown` answers Object in a union and is skipped in an intersection,
|
||||
* `never` is skipped in a union and answers `void 0` in an intersection. */
|
||||
function unionToken(
|
||||
lowerer: Lowerer,
|
||||
types: readonly ts.TypeNode[],
|
||||
isIntersection: boolean,
|
||||
container: ts.Node,
|
||||
): MetaToken {
|
||||
let result: MetaToken | undefined;
|
||||
for (const raw of types) {
|
||||
const node = skipParens(raw);
|
||||
if (node.kind === ts.SyntaxKind.NeverKeyword) {
|
||||
if (isIntersection) return VOID;
|
||||
continue;
|
||||
}
|
||||
if (node.kind === ts.SyntaxKind.UnknownKeyword) {
|
||||
if (!isIntersection) return OBJ;
|
||||
continue;
|
||||
}
|
||||
if (node.kind === ts.SyntaxKind.AnyKeyword) return OBJ;
|
||||
const token = typeToken(lowerer, node, container);
|
||||
if (token.k === "global" && token.name === "Object") return token;
|
||||
if (result === undefined) result = token;
|
||||
else if (tokenKey(result) !== tokenKey(token)) return OBJ;
|
||||
}
|
||||
return result ?? VOID;
|
||||
}
|
||||
|
||||
function typeReferenceToken(
|
||||
lowerer: Lowerer,
|
||||
node: ts.TypeReferenceNode,
|
||||
container: ts.Node,
|
||||
): MetaToken {
|
||||
const name = node.typeName;
|
||||
const setSymbol = lowerer.checker.getSymbolAtLocation(name);
|
||||
const aliased = setSymbol !== undefined && (setSymbol.flags & ts.SymbolFlags.Alias) !== 0;
|
||||
const symbol = aliased ? lowerer.checker.getAliasedSymbol(setSymbol) : setSymbol;
|
||||
// A type-only import has no run-time binding at all (tsc elides it): a
|
||||
// class reached through one — imported directly (`import type { Dep }`) or
|
||||
// as a member of a type-only namespace import (`import type * as ns`, then
|
||||
// `ns.Dep`) — serializes as Function, the one token whose value every
|
||||
// program has.
|
||||
const typeOnlyImport =
|
||||
setSymbol !== undefined &&
|
||||
((aliased && isTypeOnlyImportSymbol(setSymbol)) || isTypeOnlyNamespaceImport(lowerer, name));
|
||||
if (typeOnlyImport && symbol !== undefined && (symbol.flags & ts.SymbolFlags.Class) !== 0)
|
||||
return { k: "global", name: "Function" };
|
||||
if (symbol !== undefined) {
|
||||
const info = lowerer.classBySymbol.get(symbol);
|
||||
if (info !== undefined && info.decl !== null)
|
||||
return { k: "class", info, blame: container, spelled: entityNameText(name) };
|
||||
}
|
||||
const text = ts.isIdentifier(name) ? name.text : undefined;
|
||||
if (text !== undefined) {
|
||||
const global = globalTokenForName(text);
|
||||
if (global !== null) return global;
|
||||
}
|
||||
if (symbol !== undefined) {
|
||||
const flags = symbol.flags;
|
||||
if ((flags & ts.SymbolFlags.TypeParameter) !== 0) return OBJ;
|
||||
if ((flags & ts.SymbolFlags.Enum) !== 0) return enumToken(lowerer, symbol);
|
||||
if ((flags & ts.SymbolFlags.Interface) !== 0 && (flags & ts.SymbolFlags.Value) === 0)
|
||||
return OBJ;
|
||||
// An alias serializes as the type it names: a primitive, an array, a
|
||||
// callable or a literal union answers its global constructor, anything
|
||||
// else Object (a class reached only through an alias is Object too:
|
||||
// tsc's resolver does not name the aliased value).
|
||||
if ((flags & ts.SymbolFlags.TypeAlias) !== 0) return aliasToken(lowerer, symbol);
|
||||
if ((flags & (ts.SymbolFlags.Class | ts.SymbolFlags.ValueModule)) !== 0)
|
||||
return { k: "entity", node: name };
|
||||
if ((flags & ts.SymbolFlags.Value) !== 0) return { k: "entity", node: name };
|
||||
}
|
||||
return OBJ;
|
||||
}
|
||||
|
||||
/** Whether a qualified type name is reached through a namespace imported
|
||||
* type-only (`import type * as ns`): the namespace has no run-time binding,
|
||||
* so nothing the name resolves to can be read at the decoration site. */
|
||||
function isTypeOnlyNamespaceImport(lowerer: Lowerer, name: ts.EntityName): boolean {
|
||||
if (!ts.isQualifiedName(name)) return false;
|
||||
let root = name.left;
|
||||
while (ts.isQualifiedName(root)) root = root.left;
|
||||
if (!ts.isIdentifier(root)) return false;
|
||||
const symbol = lowerer.checker.getSymbolAtLocation(root);
|
||||
return symbol !== undefined && isTypeOnlyImportSymbol(symbol);
|
||||
}
|
||||
|
||||
/** Whether the import alias was spelled type-only (`import type …`,
|
||||
* `import { type X }`). */
|
||||
function isTypeOnlyImportSymbol(symbol: ts.Symbol): boolean {
|
||||
const declaration = symbol.declarations?.[0];
|
||||
if (declaration === undefined) return false;
|
||||
let node: ts.Node = declaration as unknown as ts.Node;
|
||||
for (let hop = 0; hop < 8; hop++) {
|
||||
if (ts.isImportSpecifier(node)) {
|
||||
if (node.isTypeOnly) return true;
|
||||
// The clause sits above the specifier's NamedImports; reach it through
|
||||
// the node guards rather than casting the parent chain, so the
|
||||
// compiler can compile itself here.
|
||||
const named = node.parent;
|
||||
const clause = named !== undefined && ts.isNamedImports(named) ? named.parent : undefined;
|
||||
return (
|
||||
clause !== undefined &&
|
||||
ts.isImportClause(clause) &&
|
||||
clause.phaseModifier === ts.SyntaxKind.TypeKeyword
|
||||
);
|
||||
}
|
||||
if (ts.isNamespaceImport(node)) {
|
||||
const clause = node.parent;
|
||||
return (
|
||||
clause !== undefined &&
|
||||
ts.isImportClause(clause) &&
|
||||
clause.phaseModifier === ts.SyntaxKind.TypeKeyword
|
||||
);
|
||||
}
|
||||
if (ts.isImportClause(node)) return node.phaseModifier === ts.SyntaxKind.TypeKeyword;
|
||||
if (ts.isImportEqualsDeclaration(node)) return node.isTypeOnly;
|
||||
if (node.parent === undefined) return false;
|
||||
node = node.parent;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** The token an alias's declared type serializes to (tsc resolves the alias
|
||||
* and answers by the type's kind). */
|
||||
function aliasToken(lowerer: Lowerer, symbol: ts.Symbol): MetaToken {
|
||||
const type = lowerer.checker.getDeclaredTypeOfSymbol(symbol);
|
||||
if (type.isUnionType()) {
|
||||
let numeric = 0;
|
||||
let string = 0;
|
||||
let boolean = 0;
|
||||
for (const part of ts.constituentTypes(type)) {
|
||||
if ((part.flags & ts.TypeFlags.NumberLiteral) !== 0) numeric++;
|
||||
else if ((part.flags & ts.TypeFlags.StringLiteral) !== 0) string++;
|
||||
else if ((part.flags & ts.TypeFlags.BooleanLiteral) !== 0) boolean++;
|
||||
else return OBJ;
|
||||
}
|
||||
if (numeric > 0 && string === 0 && boolean === 0) return { k: "global", name: "Number" };
|
||||
if (string > 0 && numeric === 0 && boolean === 0) return { k: "global", name: "String" };
|
||||
if (boolean > 0 && numeric === 0 && string === 0) return { k: "global", name: "Boolean" };
|
||||
return OBJ;
|
||||
}
|
||||
const flags = type.flags;
|
||||
if ((flags & ts.TypeFlags.StringLike) !== 0) return { k: "global", name: "String" };
|
||||
if ((flags & ts.TypeFlags.NumberLike) !== 0) return { k: "global", name: "Number" };
|
||||
if ((flags & ts.TypeFlags.BooleanLike) !== 0) return { k: "global", name: "Boolean" };
|
||||
if ((flags & ts.TypeFlags.BigIntLike) !== 0) return { k: "global", name: "BigInt" };
|
||||
if ((flags & ts.TypeFlags.ESSymbolLike) !== 0) return { k: "global", name: "Symbol" };
|
||||
if (lowerer.checker.isArrayType(type) || lowerer.checker.isTupleType(type))
|
||||
return { k: "global", name: "Array" };
|
||||
if (lowerer.checker.getCallSignatures(type).length > 0) return { k: "global", name: "Function" };
|
||||
return OBJ;
|
||||
}
|
||||
|
||||
/** A numeric enum serializes as Number, a string enum as String, a mixed one
|
||||
* as Object (the type's literal constituents decide). */
|
||||
function enumToken(lowerer: Lowerer, symbol: ts.Symbol): MetaToken {
|
||||
const type = lowerer.checker.getDeclaredTypeOfSymbol(symbol);
|
||||
let numeric = 0;
|
||||
let string = 0;
|
||||
for (const part of type.isUnionType() ? ts.constituentTypes(type) : [type]) {
|
||||
if ((part.flags & ts.TypeFlags.NumberLiteral) !== 0) numeric++;
|
||||
else if ((part.flags & ts.TypeFlags.StringLiteral) !== 0) string++;
|
||||
else return OBJ;
|
||||
}
|
||||
if (numeric > 0 && string === 0) return { k: "global", name: "Number" };
|
||||
if (string > 0 && numeric === 0) return { k: "global", name: "String" };
|
||||
return OBJ;
|
||||
}
|
||||
|
||||
/** Whether the class's declaration statement follows the decorated class in
|
||||
* the same module: the decoration event runs before it, so reading the value
|
||||
* throws the temporal-dead-zone ReferenceError. */
|
||||
function declaredAfterDecoration(token: Extract<MetaToken, { k: "class" }>): boolean {
|
||||
const declaration = token.info.decl;
|
||||
if (declaration === null) return false;
|
||||
if (ts.getSourceFileOfNode(declaration) !== ts.getSourceFileOfNode(token.blame)) return false;
|
||||
if (declaration.parent === undefined || !ts.isSourceFile(declaration.parent)) return false;
|
||||
return declaration.getStart() > token.blame.getStart();
|
||||
}
|
||||
|
||||
function materialize(lowerer: Lowerer, token: MetaToken, loc: SrcLoc): IrExpr {
|
||||
switch (token.k) {
|
||||
case "void":
|
||||
return dynUndefinedExpr(loc);
|
||||
case "global":
|
||||
return materializeGlobal(lowerer, token.name, loc);
|
||||
case "class":
|
||||
// tsc's `__metadata("design:type", Dep)` evaluates the class value
|
||||
// where the decoration array is built. A same-module class whose
|
||||
// statement has not run yet is in its temporal dead zone then, so
|
||||
// the read throws Node's ReferenceError (TypeScript does not flag
|
||||
// this synthesized reference, only the run-time error exists).
|
||||
if (declaredAfterDecoration(token))
|
||||
return nodeThrowExpr(
|
||||
5,
|
||||
"",
|
||||
`Cannot access '${token.spelled}' before initialization`,
|
||||
DYN,
|
||||
loc,
|
||||
);
|
||||
return lowerer.coerceToExpected(classValueRef(lowerer, token.info, token.blame), DYN);
|
||||
case "entity": {
|
||||
if (!ts.isIdentifier(token.node)) return materializeGlobal(lowerer, "Object", loc);
|
||||
const value = lowerer.lowerExpr(token.node);
|
||||
return value.type.kind === "dyn" ? value : lowerer.coerceToExpected(value, DYN);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A rest parameter's element type (tsc's getRestParameterElementType): the
|
||||
* element of `T[]`, the argument of `Array<T>`/`ReadonlyArray<T>`, else
|
||||
* undefined (which serializes to Object). */
|
||||
function restElementType(type: ts.TypeNode | undefined): ts.TypeNode | undefined {
|
||||
if (type === undefined) return undefined;
|
||||
if (ts.isArrayTypeNode(type)) return type.elementType;
|
||||
if (ts.isTypeReferenceNode(type)) {
|
||||
const name = identifierName(type);
|
||||
if (name === "Array" || name === "ReadonlyArray") return type.typeArguments?.nodes[0];
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function serializeParameter(
|
||||
lowerer: Lowerer,
|
||||
parameter: ts.ParameterDeclaration,
|
||||
container: ts.Node,
|
||||
): MetaToken {
|
||||
if (parameter.dotDotDotToken !== undefined)
|
||||
return typeToken(lowerer, restElementType(parameter.type), container);
|
||||
return typeToken(lowerer, parameter.type, container);
|
||||
}
|
||||
|
||||
/** The parameters a decorated declaration's design:paramtypes covers: a
|
||||
* class's first constructor with a body; a getter's setter partner's
|
||||
* parameters (tsc's getParametersOfDecoratedDeclaration); else the
|
||||
* declaration's own. A `this` parameter is not serialized. */
|
||||
function parameterTokens(
|
||||
lowerer: Lowerer,
|
||||
node: ts.ClassElement,
|
||||
container: ts.ClassLikeDeclaration,
|
||||
): MetaToken[] {
|
||||
let parameters: readonly ts.ParameterDeclaration[] = [];
|
||||
if (ts.isConstructorDeclaration(node) || ts.isMethodDeclaration(node)) {
|
||||
parameters = node.parameters.nodes;
|
||||
} else if (ts.isGetAccessorDeclaration(node) || ts.isSetAccessorDeclaration(node)) {
|
||||
const pair = accessorPair(container, node);
|
||||
parameters =
|
||||
pair.setter?.parameters.nodes ??
|
||||
(ts.isSetAccessorDeclaration(node) ? node.parameters.nodes : []);
|
||||
}
|
||||
const tokens: MetaToken[] = [];
|
||||
for (const parameter of parameters) {
|
||||
if (ts.isIdentifier(parameter.name) && parameter.name.text === "this") continue;
|
||||
tokens.push(serializeParameter(lowerer, parameter, container));
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
/** The getter and setter declarations of one accessor pair. */
|
||||
function accessorPair(
|
||||
container: ts.ClassLikeDeclaration,
|
||||
node: ts.GetAccessorDeclaration | ts.SetAccessorDeclaration,
|
||||
): { getter: ts.GetAccessorDeclaration | null; setter: ts.SetAccessorDeclaration | null } {
|
||||
const name = node.name.getText();
|
||||
let getter: ts.GetAccessorDeclaration | null = null;
|
||||
let setter: ts.SetAccessorDeclaration | null = null;
|
||||
for (const member of container.members.nodes) {
|
||||
if (member === node) continue;
|
||||
if (member.name?.getText() !== name) continue;
|
||||
if (ts.isGetAccessorDeclaration(member)) getter = member;
|
||||
else if (ts.isSetAccessorDeclaration(member)) setter = member;
|
||||
}
|
||||
return { getter, setter };
|
||||
}
|
||||
|
||||
/** The design:type value of an accessor pair (tsc's getAccessorTypeNode):
|
||||
* the setter's parameter type when there is a setter, else the getter's
|
||||
* return type. */
|
||||
function accessorTypeToken(
|
||||
lowerer: Lowerer,
|
||||
node: ts.GetAccessorDeclaration | ts.SetAccessorDeclaration,
|
||||
container: ts.ClassLikeDeclaration,
|
||||
): MetaToken {
|
||||
const pair = accessorPair(container, node);
|
||||
const ownSetter = ts.isSetAccessorDeclaration(node) ? node : pair.setter;
|
||||
const ownGetter = ts.isGetAccessorDeclaration(node) ? node : pair.getter;
|
||||
if (ownSetter !== null) return typeToken(lowerer, ownSetter.parameters.nodes[0]?.type, container);
|
||||
return typeToken(lowerer, ownGetter?.type, container);
|
||||
}
|
||||
|
||||
function isAsync(node: ts.Node): boolean {
|
||||
return ts.getModifiers(node)?.some((m) => m.kind === ts.SyntaxKind.AsyncKeyword) === true;
|
||||
}
|
||||
|
||||
/** The `__metadata(...)` decorator values of one decorated member, in tsc's
|
||||
* array order: design:type, design:paramtypes, design:returntype (a method
|
||||
* only; accessors get type and paramtypes). */
|
||||
export function declarationMetadata(
|
||||
lowerer: Lowerer,
|
||||
node: ts.ClassElement,
|
||||
container: ts.ClassLikeDeclaration,
|
||||
): IrExpr[] {
|
||||
const loc = locOf(node);
|
||||
const entries: IrExpr[] = [];
|
||||
const paramTypes = (): IrExpr => ({
|
||||
kind: "arrayLit",
|
||||
elems: parameterTokens(lowerer, node, container).map((token) =>
|
||||
materialize(lowerer, token, loc),
|
||||
),
|
||||
type: { kind: "array", elem: DYN },
|
||||
loc,
|
||||
});
|
||||
if (ts.isPropertyDeclaration(node)) {
|
||||
entries.push(
|
||||
metadataDecoratorValue(
|
||||
lowerer,
|
||||
"design:type",
|
||||
materialize(lowerer, typeToken(lowerer, node.type, container), loc),
|
||||
loc,
|
||||
),
|
||||
);
|
||||
return entries;
|
||||
}
|
||||
if (ts.isMethodDeclaration(node)) {
|
||||
entries.push(
|
||||
metadataDecoratorValue(
|
||||
lowerer,
|
||||
"design:type",
|
||||
materializeGlobal(lowerer, "Function", loc),
|
||||
loc,
|
||||
),
|
||||
);
|
||||
entries.push(metadataDecoratorValue(lowerer, "design:paramtypes", paramTypes(), loc));
|
||||
const ret =
|
||||
node.type !== undefined
|
||||
? materialize(lowerer, typeToken(lowerer, node.type, container), loc)
|
||||
: isAsync(node)
|
||||
? materializeGlobal(lowerer, "Promise", loc)
|
||||
: dynUndefinedExpr(loc);
|
||||
entries.push(metadataDecoratorValue(lowerer, "design:returntype", ret, loc));
|
||||
return entries;
|
||||
}
|
||||
// Get/set accessors: design:type and the setter's parameter list, no
|
||||
// design:returntype (tsc's shouldAddReturnTypeMetadata is methods-only).
|
||||
entries.push(
|
||||
metadataDecoratorValue(
|
||||
lowerer,
|
||||
"design:type",
|
||||
materialize(
|
||||
lowerer,
|
||||
accessorTypeToken(
|
||||
lowerer,
|
||||
node as ts.GetAccessorDeclaration | ts.SetAccessorDeclaration,
|
||||
container,
|
||||
),
|
||||
loc,
|
||||
),
|
||||
loc,
|
||||
),
|
||||
);
|
||||
entries.push(metadataDecoratorValue(lowerer, "design:paramtypes", paramTypes(), loc));
|
||||
return entries;
|
||||
}
|
||||
|
||||
/** `design:paramtypes` for a decorated class: the first constructor with a
|
||||
* body's parameters. tsc emits no class metadata when there is none. */
|
||||
export function classMetadata(lowerer: Lowerer, decl: ts.ClassLikeDeclaration): IrExpr[] {
|
||||
const constructor = decl.members.nodes.find(
|
||||
(member): member is ts.ConstructorDeclaration =>
|
||||
ts.isConstructorDeclaration(member) && member.body !== undefined,
|
||||
);
|
||||
if (constructor === undefined) return [];
|
||||
const loc = locOf(decl);
|
||||
const tokens = parameterTokens(lowerer, constructor, decl);
|
||||
const value: IrExpr = {
|
||||
kind: "arrayLit",
|
||||
elems: tokens.map((token) => materialize(lowerer, token, loc)),
|
||||
type: { kind: "array", elem: DYN },
|
||||
loc,
|
||||
};
|
||||
return [metadataDecoratorValue(lowerer, "design:paramtypes", value, loc)];
|
||||
}
|
||||
|
||||
/** One `__metadata(key, value)` decorator value: the value argument is
|
||||
* evaluated first (tsc passes it to the helper), then the program's
|
||||
* `Reflect.metadata` when it has one. Undefined when the program never
|
||||
* loaded a metadata polyfill, so the decoration array skips it. */
|
||||
export function metadataDecoratorValue(
|
||||
lowerer: Lowerer,
|
||||
key: string,
|
||||
value: IrExpr,
|
||||
loc: SrcLoc,
|
||||
): IrExpr {
|
||||
// A paramtypes value is an array literal; the helper takes it as an
|
||||
// ordinary value, so it crosses into the checked-dynamic tree here.
|
||||
value = lowerer.coerceToExpected(value, DYN);
|
||||
const valueLocal = lowerer.declareHiddenLocal("metaval", DYN);
|
||||
const fnLocal = lowerer.declareHiddenLocal("metadatafn", DYN);
|
||||
const namespace = builtinNamespaceValue(lowerer, "Reflect", loc);
|
||||
if (namespace === null) {
|
||||
return {
|
||||
kind: "seqExpr",
|
||||
stmts: [{ kind: "varDecl", localId: valueLocal.id, init: value, loc }],
|
||||
result: dynUndefinedExpr(loc),
|
||||
type: DYN,
|
||||
loc,
|
||||
};
|
||||
}
|
||||
const call: IrExpr = {
|
||||
kind: "dynCall",
|
||||
callee: varRef(fnLocal.id, DYN, loc),
|
||||
calleeName: "Reflect.metadata",
|
||||
args: [
|
||||
lowerer.coerceToExpected({ kind: "strLit", value: key, type: STRING, loc }, DYN),
|
||||
varRef(valueLocal.id, DYN, loc),
|
||||
],
|
||||
type: DYN,
|
||||
loc,
|
||||
};
|
||||
return {
|
||||
kind: "seqExpr",
|
||||
stmts: [
|
||||
{ kind: "varDecl", localId: valueLocal.id, init: value, loc },
|
||||
{
|
||||
kind: "varDecl",
|
||||
localId: fnLocal.id,
|
||||
init: {
|
||||
kind: "dynKeyGet",
|
||||
value: namespace,
|
||||
key: { kind: "strLit", value: "metadata", type: STRING, loc },
|
||||
type: DYN,
|
||||
loc,
|
||||
},
|
||||
loc,
|
||||
},
|
||||
],
|
||||
// `Reflect.metadata && Reflect.metadata(k, v)`: a program without the
|
||||
// polyfill contributes undefined (the helper's typeof guard).
|
||||
result: {
|
||||
kind: "logical",
|
||||
op: "&&",
|
||||
left: varRef(fnLocal.id, DYN, loc),
|
||||
right: call,
|
||||
type: DYN,
|
||||
loc,
|
||||
},
|
||||
type: DYN,
|
||||
loc,
|
||||
};
|
||||
}
|
||||
@@ -229,6 +229,28 @@ export function lowerIdentifierExpr(lowerer: Lowerer, expr: ts.Identifier, loc:
|
||||
}
|
||||
}
|
||||
|
||||
// A member read through a CommonJS require binding names an esbuild
|
||||
// getter-table entry whose body is not one module-level identifier
|
||||
// (`metaTag: () => meta.tag`): the checker gives the member no symbol, so
|
||||
// the read is the getter's returned expression evaluated here — Node runs
|
||||
// the getter on every read. Identifier entries resolve through
|
||||
// resolveValueSymbol like plain member exports.
|
||||
{
|
||||
const parent = expr.parent;
|
||||
if (
|
||||
parent !== undefined &&
|
||||
ts.isPropertyAccessExpression(parent) &&
|
||||
parent.name === expr &&
|
||||
!parent.questionDotToken
|
||||
) {
|
||||
const dep = ts.isIdentifier(parent.expression)
|
||||
? lowerer.cjsModuleBindingDepOf(parent.expression)
|
||||
: lowerer.cjsModuleRefDepOf(parent.expression);
|
||||
const value = dep === null ? undefined : lowerer.getterTableOf(dep)?.entries.get(expr.text);
|
||||
if (value !== undefined && !ts.isIdentifier(value)) return lowerer.lowerExpr(value);
|
||||
}
|
||||
}
|
||||
|
||||
// A module binding of a partial require() cycle used as a VALUE (an
|
||||
// initializer, an argument, an assignment source): it holds the exports
|
||||
// object its require answered, which a later module.exports replacement
|
||||
@@ -369,13 +391,14 @@ export function lowerIdentifierExpr(lowerer: Lowerer, expr: ts.Identifier, loc:
|
||||
);
|
||||
}
|
||||
if (projection?.kind === "builtin-function") {
|
||||
if (!isJsSourceFile(ts.getSourceFileOfNode(expr))) {
|
||||
const callable = lowerer.lowerBuiltinCallableValue(
|
||||
{ module: projection.module, member: projection.member },
|
||||
loc,
|
||||
);
|
||||
if (callable) return callable;
|
||||
}
|
||||
const callable = lowerer.lowerBuiltinCallableValue(
|
||||
{ module: projection.module, member: projection.member },
|
||||
loc,
|
||||
);
|
||||
if (callable)
|
||||
return isJsSourceFile(ts.getSourceFileOfNode(expr))
|
||||
? lowerer.checkedBuiltinValue(callable)
|
||||
: callable;
|
||||
lowerer.unsupported(
|
||||
"SC1090",
|
||||
expr,
|
||||
|
||||
@@ -5,7 +5,10 @@ import { dynUndefinedExpr, numLit, strLit, varRef } from "../../../ir/build.js";
|
||||
import { pathModuleSpreadSource } from "../lower-builtin-values.js";
|
||||
import { InternalCompilerError } from "../../../errors.js";
|
||||
import * as ts from "../../ts7/adapter.js";
|
||||
import { withoutParentheses } from "../../outer-expressions.js";
|
||||
import {
|
||||
withoutParentheses,
|
||||
withoutParenthesesAssertionsNonNull,
|
||||
} from "../../outer-expressions.js";
|
||||
import {
|
||||
BOOL,
|
||||
DYN,
|
||||
@@ -1006,6 +1009,18 @@ function viewContextOf(
|
||||
return lowerer.checker.getContextualType(outer) ?? contextual;
|
||||
}
|
||||
|
||||
/** Whether `node`, seen through parentheses and a non-null assertion, reads
|
||||
* a checked-dynamic dictionary through its string index signature: the key
|
||||
* may be missing at run time whatever the checker says the read has. */
|
||||
function isCheckedDictionaryReadNode(lowerer: Lowerer, node: ts.Node): boolean {
|
||||
if (!ts.isExpression(node)) return false;
|
||||
const read = withoutParenthesesAssertionsNonNull(node);
|
||||
return (
|
||||
(ts.isElementAccessExpression(read) || ts.isPropertyAccessExpression(read)) &&
|
||||
lowerer.dynIndexSignatureValueRead(read) !== null
|
||||
);
|
||||
}
|
||||
|
||||
export function lowerObjectLiteral(
|
||||
lowerer: Lowerer,
|
||||
expr: ts.ObjectLiteralExpression,
|
||||
@@ -2965,9 +2980,19 @@ export function lowerObjectLiteral(
|
||||
continue;
|
||||
}
|
||||
// A nested literal whose own fields widened for missing-element reads
|
||||
// keeps that layout in its parent field too.
|
||||
// keeps that layout in its parent field too. A checked-dynamic
|
||||
// dictionary read that the checker calls present can still answer a
|
||||
// missing key at run time, so the field keeps the undefined arm: JSON
|
||||
// drops the member and a probe observes it, as Node does.
|
||||
const checkedReadField =
|
||||
fieldType !== undefined &&
|
||||
value.type.kind === "dyn" &&
|
||||
isCheckedDictionaryReadNode(lowerer, valueNode)
|
||||
? lowerer.runtimeOptionalType(fieldType)
|
||||
: null;
|
||||
const promotedField = fieldType
|
||||
? (lowerer.runtimeOptionalWidening(value.type, fieldType) ??
|
||||
? (checkedReadField ??
|
||||
lowerer.runtimeOptionalWidening(value.type, fieldType) ??
|
||||
(lowerer.isRuntimeOptionalRecordVariant(value.type, fieldType) ? value.type : null))
|
||||
: null;
|
||||
if (promotedField && fieldType) {
|
||||
|
||||
@@ -230,10 +230,15 @@ function neverNullishCallee(lowerer: Lowerer, node: ts.Expression): boolean {
|
||||
function alwaysDefinedGlobal(lowerer: Lowerer, node: ts.Expression): boolean {
|
||||
let inner = node;
|
||||
while (ts.isParenthesizedExpression(inner)) inner = inner.expression;
|
||||
// The bare global's own spelling (`console?.log`) keeps its existing path.
|
||||
// The bare global's own spelling keeps its existing path, except the
|
||||
// process global itself: Node always defines it, so `process?.env.NODE_ENV`
|
||||
// is the plain read (an alias or `globalThis.process` was already admitted
|
||||
// below, through stdlibGlobalAliases).
|
||||
if (ts.isIdentifier(inner)) {
|
||||
const symbol = lowerer.resolveValueSymbol(inner);
|
||||
if (symbol === null || !lowerer.stdlibGlobalAliases.has(symbol)) return false;
|
||||
if (symbol === null) return false;
|
||||
const bareName = stdlibGlobalNameOf(lowerer, inner);
|
||||
if (bareName !== "process" && !lowerer.stdlibGlobalAliases.has(symbol)) return false;
|
||||
} else if (!ts.isPropertyAccessExpression(inner)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -7268,6 +7268,24 @@ const GLOBAL_FUNCTION_VALUES: ReadonlySet<string> = new Set([
|
||||
"queueMicrotask",
|
||||
]);
|
||||
|
||||
/** The builtin global function values a TypeScript source reads too: the
|
||||
* timer functions and the base64 helpers are one interned runtime function
|
||||
* per name, the same function the module member reads, so identity holds
|
||||
* across the spellings in TypeScript (`timers.setImmediate ===
|
||||
* globalThis.setImmediate`). */
|
||||
const TS_GLOBAL_FUNCTION_VALUES: ReadonlySet<string> = new Set([
|
||||
"atob",
|
||||
"btoa",
|
||||
"structuredClone",
|
||||
"setTimeout",
|
||||
"setInterval",
|
||||
"setImmediate",
|
||||
"clearTimeout",
|
||||
"clearInterval",
|
||||
"clearImmediate",
|
||||
"queueMicrotask",
|
||||
]);
|
||||
|
||||
/** A builtin function value: one interned runtime function per name. */
|
||||
export function builtinFunctionValue(name: string, loc: SrcLoc): IrExpr {
|
||||
return {
|
||||
@@ -7284,7 +7302,8 @@ export function builtinFunctionValue(name: string, loc: SrcLoc): IrExpr {
|
||||
* null when no lowering has a value for it (JavaScript reads answer by
|
||||
* node-value-reads.ts; TypeScript reads are fenced). */
|
||||
export function builtinGlobalValue(canonical: string, loc: SrcLoc, js = false): IrExpr | null {
|
||||
if (js && GLOBAL_FUNCTION_VALUES.has(canonical)) return builtinFunctionValue(canonical, loc);
|
||||
if (GLOBAL_FUNCTION_VALUES.has(canonical) && (js || TS_GLOBAL_FUNCTION_VALUES.has(canonical)))
|
||||
return builtinFunctionValue(canonical, loc);
|
||||
if (js && canonical === "Buffer")
|
||||
return { kind: "libCall", fn: "buffer.constructor", args: [], type: DYN, loc };
|
||||
if (GLOBAL_CONSTRUCTOR_VALUES.has(canonical)) {
|
||||
@@ -7316,6 +7335,9 @@ const BUILTIN_VALUE_REFLECTION: ReadonlySet<string> = new Set([
|
||||
"isExtensible",
|
||||
"isFrozen",
|
||||
"isSealed",
|
||||
// The runtime answers a function value's prototype edge (Function.prototype),
|
||||
// which is what reflect-metadata's target checks need.
|
||||
"getPrototypeOf",
|
||||
]);
|
||||
|
||||
/** The value `builtinGlobalValue` gives the stdlib global `expr` read at its
|
||||
|
||||
@@ -158,9 +158,10 @@ export function jsGlobalValueByName(
|
||||
|
||||
/** Globals whose values a TypeScript read keeps refused: the Array
|
||||
* constructor value has none of Array's static members (`o.Array.isArray`
|
||||
* would read undefined), and the timer values lack the
|
||||
* util.promisify.custom getter Node's util.inspect lists. */
|
||||
const UNTYPED_UNMODELED: ReadonlySet<string> = new Set(["Array", "setTimeout", "setImmediate"]);
|
||||
* would read undefined). The timer values read as their interned runtime
|
||||
* functions in TypeScript now; they lack the promisify.custom getter Node
|
||||
* carries, which only an inspect of the value observes. */
|
||||
const UNTYPED_UNMODELED: ReadonlySet<string> = new Set(["Array"]);
|
||||
|
||||
/** The value a TypeScript source reads for the declared global `name` at
|
||||
* `node` when the checker types the slot it flows into as any or unknown
|
||||
|
||||
@@ -565,3 +565,283 @@ test("constructor parameter decorators on a function-local class are refused", a
|
||||
].join("\n");
|
||||
expect(await refusalCodes(source, legacyTsconfig)).toContain("SC1090");
|
||||
});
|
||||
|
||||
const metadataTsconfig = {
|
||||
compilerOptions: { ...legacyTsconfig.compilerOptions, emitDecoratorMetadata: true },
|
||||
};
|
||||
|
||||
/** The `design:*` keys of the `Reflect.metadata(k, v)` values the lowering
|
||||
* emitted, in evaluation order. */
|
||||
function metadataKeys(init: IrFunction): string[] {
|
||||
const keys: string[] = [];
|
||||
for (const e of exprs(init)) {
|
||||
if (e.kind !== "dynCall" || e.calleeName !== "Reflect.metadata") continue;
|
||||
// The key crosses into the checked-dynamic tree (dynFrom around the
|
||||
// string literal).
|
||||
let key: IrExpr = e.args[0]!;
|
||||
while (key.kind === "dynFrom") key = key.value;
|
||||
if (key.kind === "strLit") keys.push(key.value);
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
test("design-type metadata evaluates after the parameter decorators and applies first", async () => {
|
||||
const source = [
|
||||
"class Dep {}",
|
||||
"function dec(..._a: any[]): any { return undefined; }",
|
||||
"function pdec(..._a: any[]): any { return undefined; }",
|
||||
"class Box {",
|
||||
" @dec",
|
||||
" run(@pdec x: Dep): Dep { return x; }",
|
||||
"}",
|
||||
"console.log(new Box().run(new Dep()) instanceof Dep);",
|
||||
"",
|
||||
].join("\n");
|
||||
const mod = await lower(source, metadataTsconfig);
|
||||
const init = initFunction(mod);
|
||||
const stmts = statements(init);
|
||||
expect(metadataKeys(init)).toEqual(["design:type", "design:paramtypes", "design:returntype"]);
|
||||
// tsc's array order is [member decorators, __param entries, __metadata
|
||||
// entries]: the metadata values evaluate last...
|
||||
const firstMetadata = stmts.findIndex(
|
||||
(s) => s.kind === "varDecl" && s.localId.startsWith("legacymeta"),
|
||||
);
|
||||
const lastParameter = stmts.reduce(
|
||||
(last, s, i) => (s.kind === "varDecl" && s.localId.startsWith("legacyparam") ? i : last),
|
||||
-1,
|
||||
);
|
||||
expect(lastParameter).toBeGreaterThanOrEqual(0);
|
||||
expect(firstMetadata).toBeGreaterThan(lastParameter);
|
||||
// ...and apply before the parameter decorators.
|
||||
const metadataApplication = stmts.findIndex(
|
||||
(s) =>
|
||||
s.kind === "varDecl" &&
|
||||
s.localId.startsWith("legacyres") &&
|
||||
JSON.stringify(s.init).includes("legacymeta"),
|
||||
);
|
||||
const parameterApplication = stmts.findIndex(
|
||||
(s) =>
|
||||
s.kind === "exprStmt" &&
|
||||
JSON.stringify(s.expr).includes('"legacymeta"') === false &&
|
||||
JSON.stringify(s.expr).includes('"decorator"') === true &&
|
||||
JSON.stringify(s.expr).includes('"numLit"') === true,
|
||||
);
|
||||
expect(metadataApplication).toBeGreaterThanOrEqual(0);
|
||||
expect(parameterApplication).toBeGreaterThan(metadataApplication);
|
||||
});
|
||||
|
||||
test("a decorated class's constructor parameters serialize as design:paramtypes", async () => {
|
||||
const source = [
|
||||
"class Dep {}",
|
||||
"function make(): (target: any) => any {",
|
||||
" return (target: any): any => { return undefined; };",
|
||||
"}",
|
||||
"@make()",
|
||||
"class Service { constructor(dep: Dep, ...rest: string[]) { void dep; void rest; } }",
|
||||
"console.log(new Service(new Dep()) instanceof Service);",
|
||||
"",
|
||||
].join("\n");
|
||||
const mod = await lower(source, metadataTsconfig);
|
||||
const init = initFunction(mod);
|
||||
expect(metadataKeys(init)).toEqual(["design:paramtypes"]);
|
||||
});
|
||||
|
||||
test("no design-type metadata exists without emitDecoratorMetadata", async () => {
|
||||
const source = [
|
||||
"class Dep {}",
|
||||
"function dec(..._a: any[]): any { return undefined; }",
|
||||
"class Box { @dec p: Dep = new Dep(); }",
|
||||
"console.log(new Box().p instanceof Dep);",
|
||||
"",
|
||||
].join("\n");
|
||||
const mod = await lower(source, legacyTsconfig);
|
||||
expect(metadataKeys(initFunction(mod))).toEqual([]);
|
||||
});
|
||||
|
||||
test("a design type naming a later class throws the temporal-dead-zone ReferenceError", async () => {
|
||||
const source = [
|
||||
"function dec(..._a: any[]): any { return undefined; }",
|
||||
"class Early { @dec late: Later = null as any; }",
|
||||
"class Later {}",
|
||||
"",
|
||||
].join("\n");
|
||||
const mod = await lower(source, metadataTsconfig);
|
||||
const throws = exprs(initFunction(mod)).filter(
|
||||
(e): e is Extract<IrExpr, { kind: "libCall" }> =>
|
||||
e.kind === "libCall" && e.fn === "error.nodeThrow",
|
||||
);
|
||||
expect(throws).toHaveLength(1);
|
||||
const kind = throws[0]!.args[0]!;
|
||||
const message = throws[0]!.args[2]!;
|
||||
expect(kind.kind === "numLit" ? kind.value : -1).toBe(5);
|
||||
expect(message.kind === "strLit" ? message.value : "").toBe(
|
||||
"Cannot access 'Later' before initialization",
|
||||
);
|
||||
});
|
||||
|
||||
test("a design type keeps a value import the file names only in the type position", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "scriptc-legacy-decorators-import-"));
|
||||
try {
|
||||
const entry = join(dir, "main.ts");
|
||||
await writeFile(join(dir, "dep.ts"), "export class Dep {}\n");
|
||||
await writeFile(
|
||||
entry,
|
||||
[
|
||||
'import { Dep } from "./dep.js";',
|
||||
"function dec(..._a: any[]): any { return undefined; }",
|
||||
"class Box { @dec dep!: Dep; }",
|
||||
"console.log(new Box() !== undefined);",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
await writeFile(join(dir, "tsconfig.json"), JSON.stringify(metadataTsconfig));
|
||||
const result = await compile(entry, {
|
||||
outDir: dir,
|
||||
outPath: join(dir, "main.ir.json"),
|
||||
outputKind: "ir",
|
||||
});
|
||||
if (!result.ok) throw new Error(result.diagnostics.map((d) => d.message).join("\n"));
|
||||
const mod = deserializeModule(await readFile(join(dir, "main.ir.json"), "utf8"));
|
||||
// The dependency module is part of the program: its class value is what
|
||||
// the emitted design:type reads.
|
||||
expect(
|
||||
mod.functions.filter((fn) => fn.name.startsWith("%init.")).length,
|
||||
).toBeGreaterThanOrEqual(2);
|
||||
expect(JSON.stringify(initFunction(mod).body)).toContain('"classRef"');
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("a decorated intersection annotation keeps its metadata-only class import", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "scriptc-legacy-decorators-intersection-"));
|
||||
try {
|
||||
const entry = join(dir, "main.ts");
|
||||
await writeFile(join(dir, "dep.ts"), "export class Dep {}\n");
|
||||
await writeFile(
|
||||
entry,
|
||||
[
|
||||
'import { Dep } from "./dep.js";',
|
||||
"function dec(..._a: any[]): any { return undefined; }",
|
||||
"class Box { @dec p!: Dep & unknown; }",
|
||||
"console.log(new Box() !== undefined);",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
await writeFile(join(dir, "tsconfig.json"), JSON.stringify(metadataTsconfig));
|
||||
const result = await compile(entry, {
|
||||
outDir: dir,
|
||||
outPath: join(dir, "main.ir.json"),
|
||||
outputKind: "ir",
|
||||
});
|
||||
if (!result.ok) throw new Error(result.diagnostics.map((d) => d.message).join("\n"));
|
||||
const mod = deserializeModule(await readFile(join(dir, "main.ir.json"), "utf8"));
|
||||
// `unknown` is skipped in the intersection, so the design:type is the
|
||||
// imported class value: the dependency module and its initialization
|
||||
// stay in the program.
|
||||
expect(
|
||||
mod.functions.filter((fn) => fn.name.startsWith("%init.")).length,
|
||||
).toBeGreaterThanOrEqual(2);
|
||||
expect(JSON.stringify(initFunction(mod).body)).toContain('"classRef"');
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("a namespace import used only by a decorated annotation is kept", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "scriptc-legacy-decorators-ns-"));
|
||||
try {
|
||||
const entry = join(dir, "main.ts");
|
||||
await writeFile(join(dir, "dep.ts"), "export class Dep {}\n");
|
||||
await writeFile(
|
||||
entry,
|
||||
[
|
||||
'import * as dep from "./dep.js";',
|
||||
"function dec(..._a: any[]): any { return undefined; }",
|
||||
"class Box { @dec p: dep.Dep = new dep.Dep(); }",
|
||||
"console.log(new Box().p instanceof dep.Dep);",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
await writeFile(join(dir, "tsconfig.json"), JSON.stringify(metadataTsconfig));
|
||||
const result = await compile(entry, {
|
||||
outDir: dir,
|
||||
outPath: join(dir, "main.ir.json"),
|
||||
outputKind: "ir",
|
||||
});
|
||||
if (!result.ok) throw new Error(result.diagnostics.map((d) => d.message).join("\n"));
|
||||
const mod = deserializeModule(await readFile(join(dir, "main.ir.json"), "utf8"));
|
||||
// The dependency module stays in the program (the namespace import is a
|
||||
// value import), and design:type carries the imported class value.
|
||||
expect(
|
||||
mod.functions.filter((fn) => fn.name.startsWith("%init.")).length,
|
||||
).toBeGreaterThanOrEqual(2);
|
||||
expect(JSON.stringify(initFunction(mod).body)).toContain('"classRef"');
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("a type-only imported class serializes as Function", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "scriptc-legacy-decorators-typeonly-"));
|
||||
try {
|
||||
const entry = join(dir, "main.ts");
|
||||
await writeFile(join(dir, "dep.ts"), "export class Dep {}\n");
|
||||
await writeFile(
|
||||
entry,
|
||||
[
|
||||
'import type { Dep } from "./dep.js";',
|
||||
"function dec(..._a: any[]): any { return undefined; }",
|
||||
"class Box { @dec p!: Dep; }",
|
||||
"console.log(new Box() !== undefined);",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
await writeFile(join(dir, "tsconfig.json"), JSON.stringify(metadataTsconfig));
|
||||
const result = await compile(entry, {
|
||||
outDir: dir,
|
||||
outPath: join(dir, "main.ir.json"),
|
||||
outputKind: "ir",
|
||||
});
|
||||
if (!result.ok) throw new Error(result.diagnostics.map((d) => d.message).join("\n"));
|
||||
const mod = deserializeModule(await readFile(join(dir, "main.ir.json"), "utf8"));
|
||||
const body = JSON.stringify(initFunction(mod).body);
|
||||
expect(body).toContain('"Function"');
|
||||
expect(body).not.toContain('"classRef"');
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("a class in a type-only namespace import serializes as Function", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "scriptc-legacy-decorators-typeonly-ns-"));
|
||||
try {
|
||||
const entry = join(dir, "main.ts");
|
||||
await writeFile(join(dir, "dep.ts"), "export class Dep {}\n");
|
||||
await writeFile(
|
||||
entry,
|
||||
[
|
||||
'import type * as dep from "./dep.js";',
|
||||
"function dec(..._a: any[]): any { return undefined; }",
|
||||
"class Box { @dec p!: dep.Dep; }",
|
||||
"console.log(new Box() !== undefined);",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
await writeFile(join(dir, "tsconfig.json"), JSON.stringify(metadataTsconfig));
|
||||
const result = await compile(entry, {
|
||||
outDir: dir,
|
||||
outPath: join(dir, "main.ir.json"),
|
||||
outputKind: "ir",
|
||||
});
|
||||
if (!result.ok) throw new Error(result.diagnostics.map((d) => d.message).join("\n"));
|
||||
const mod = deserializeModule(await readFile(join(dir, "main.ir.json"), "utf8"));
|
||||
// The namespace import is type-only, so no namespace value exists at the
|
||||
// decoration site: tsc serializes the class as Function, not `dep.Dep`.
|
||||
const body = JSON.stringify(initFunction(mod).body);
|
||||
expect(body).toContain('"Function"');
|
||||
expect(body).not.toContain('"classRef"');
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1127,6 +1127,8 @@ export function checkedNativeCallableValue(
|
||||
fn.valueName ?? display.slice(display.lastIndexOf(".") + 1),
|
||||
);
|
||||
if (fn.valueNameMainThreadOnly) lowerer.builtinCallableValueMainThreadNames.add(fnName);
|
||||
if (fn.valueLength !== undefined)
|
||||
lowerer.builtinCallableValueLengths.set(fnName, fn.valueLength);
|
||||
const params = valueParams.map((_, index) => ({
|
||||
localId: `arg.${index}`,
|
||||
name: `arg${index}`,
|
||||
@@ -1192,7 +1194,11 @@ export function checkedNativeCallableValue(
|
||||
const call: IrExpr = {
|
||||
kind: "libCall",
|
||||
fn: callee,
|
||||
args: [...args, ...(fn.checked?.args ?? []).map((value) => boolLit(value, loc))],
|
||||
args: [
|
||||
...(fn.checked?.leadingArgs ?? []).map((value) => boolLit(value, loc)),
|
||||
...args,
|
||||
...(fn.checked?.args ?? []).map((value) => boolLit(value, loc)),
|
||||
],
|
||||
type: result,
|
||||
loc,
|
||||
};
|
||||
@@ -1232,7 +1238,8 @@ function checkedTwinSignature(fn: BuiltinModuleFn): {
|
||||
type: DYN,
|
||||
}));
|
||||
const funcType = funcTypeFromParamShapes(shapes, result);
|
||||
const key = `checked:${callee}:${JSON.stringify(fn.checked?.args ?? [])}:${typeKey(funcType)}`;
|
||||
const leading = fn.checked?.leadingArgs;
|
||||
const key = `checked:${callee}:${leading === undefined ? "" : `${JSON.stringify(leading)}:`}${JSON.stringify(fn.checked?.args ?? [])}:${typeKey(funcType)}`;
|
||||
return { callee, result, funcType, key };
|
||||
}
|
||||
|
||||
|
||||
@@ -280,6 +280,7 @@ import {
|
||||
registerLinkedHelper,
|
||||
} from "./record-links.js";
|
||||
import { lowerPrototypeReflectionCall, lowerReflectCall } from "./builtins/reflection.js";
|
||||
import { builtinNamespaceValue } from "./builtin-namespaces.js";
|
||||
import {
|
||||
lowerAbsenceProbe,
|
||||
nullishBranches,
|
||||
@@ -848,6 +849,25 @@ function lowerVoidTruthinessCall(
|
||||
return stmts.length === 0 ? call : { kind: "seqExpr", stmts, result: call, type: DYN, loc };
|
||||
}
|
||||
|
||||
/** The ES2015 `Reflect` statics. Any other member a package adds to the
|
||||
* global object (reflect-metadata's metadata API) reaches the program at run
|
||||
* time through the namespace value's checked-dynamic property. */
|
||||
const REFLECT_BUILTIN_MEMBERS: ReadonlySet<string> = new Set([
|
||||
"apply",
|
||||
"construct",
|
||||
"defineProperty",
|
||||
"deleteProperty",
|
||||
"get",
|
||||
"getOwnPropertyDescriptor",
|
||||
"getPrototypeOf",
|
||||
"has",
|
||||
"isExtensible",
|
||||
"ownKeys",
|
||||
"preventExtensions",
|
||||
"set",
|
||||
"setPrototypeOf",
|
||||
]);
|
||||
|
||||
function lowerOrdinaryCall(lowerer: Lowerer, expr: ts.CallExpression): IrExpr {
|
||||
refuseOwnCallPrototype(lowerer, expr);
|
||||
// node:cluster's own event registration (`cluster.on('exit', ...)`) is a
|
||||
@@ -873,6 +893,48 @@ function lowerOrdinaryCall(lowerer: Lowerer, expr: ts.CallExpression): IrExpr {
|
||||
if (text) return text;
|
||||
}
|
||||
const loc = locOf(expr);
|
||||
// A member an installed package adds to the global Reflect (reflect-metadata
|
||||
// adds the metadata API): the ES2015 members keep their lowerings, and every
|
||||
// other member is a runtime property of the global object the compiled
|
||||
// module graph mutates. Calling it through the shared Reflect namespace
|
||||
// value keeps the package's own implementation in play.
|
||||
if (
|
||||
process.env["SCRIPTC_DEBUG_REFLECT"] === "1" &&
|
||||
ts.getTextOfNode(expr.expression).startsWith("Reflect.")
|
||||
)
|
||||
console.error(
|
||||
"REFLECT-DBG",
|
||||
ts.getTextOfNode(expr.expression),
|
||||
stdlibGlobalNameOf(lowerer, (expr.expression as ts.PropertyAccessExpression).expression),
|
||||
lowerer.stdlibGlobalMember(expr.expression as ts.PropertyAccessExpression, "Reflect"),
|
||||
);
|
||||
if (
|
||||
expr.questionDotToken === undefined &&
|
||||
ts.isPropertyAccessExpression(expr.expression) &&
|
||||
expr.expression.questionDotToken === undefined &&
|
||||
!expr.arguments.nodes.some(ts.isSpreadElement) &&
|
||||
stdlibGlobalNameOf(lowerer, expr.expression.expression) === "Reflect" &&
|
||||
!REFLECT_BUILTIN_MEMBERS.has(expr.expression.name.text)
|
||||
) {
|
||||
const namespace = builtinNamespaceValue(lowerer, "Reflect", loc);
|
||||
if (namespace !== null) {
|
||||
const callee: IrExpr = {
|
||||
kind: "dynKeyGet",
|
||||
value: namespace,
|
||||
key: { kind: "strLit", value: expr.expression.name.text, type: STRING, loc },
|
||||
type: DYN,
|
||||
loc,
|
||||
};
|
||||
return {
|
||||
kind: "dynCall",
|
||||
callee,
|
||||
calleeName: `Reflect.${expr.expression.name.text}`,
|
||||
args: expr.arguments.nodes.map((arg) => lowerer.lowerExprExpecting(arg, DYN)),
|
||||
type: DYN,
|
||||
loc,
|
||||
};
|
||||
}
|
||||
}
|
||||
// A JavaScript source calling a member that resizes, grows or detaches a
|
||||
// buffer is the mutableBuffers fact (buffers.ts, t262-dc §2.4). The
|
||||
// receiver may be a checked-dynamic value, so the callee's name decides;
|
||||
@@ -7123,7 +7185,14 @@ function lowerUnionToStringCall(
|
||||
call: ts.CallExpression,
|
||||
access: ts.PropertyAccessExpression,
|
||||
): IrExpr | null {
|
||||
if (call.questionDotToken || access.questionDotToken) return null;
|
||||
// An optional step the chain already guarded (`s?.toString()`,
|
||||
// `chunk?.toString()` on a `Buffer | string | undefined` slot) arrives
|
||||
// with its receiver proven non-nullish.
|
||||
if (
|
||||
(call.questionDotToken && !lowerer.chainHandled.has(call)) ||
|
||||
(access.questionDotToken && !lowerer.chainHandled.has(access))
|
||||
)
|
||||
return null;
|
||||
if (access.name.text !== "toString") return null;
|
||||
// `.toString("utf8")` on `string | Buffer` (a Buffer's default decode;
|
||||
// String.prototype.toString ignores its arguments): the same helper.
|
||||
@@ -7131,7 +7200,13 @@ function lowerUnionToStringCall(
|
||||
const utf8Arg =
|
||||
args.length === 1 && ts.isStringLiteralLike(args[0]!) && /^utf-?8$/i.test(args[0].text);
|
||||
if (args.length !== 0 && !utf8Arg) return null;
|
||||
const recvT = lowerer.mapTypeOf(lowerer.typeOf(access.expression));
|
||||
const rawRecvTs = lowerer.typeOf(access.expression);
|
||||
const recvTs =
|
||||
(access.questionDotToken !== undefined && lowerer.chainHandled.has(access)) ||
|
||||
(call.questionDotToken !== undefined && lowerer.chainHandled.has(call))
|
||||
? lowerer.checker.getNonNullableType(rawRecvTs)
|
||||
: rawRecvTs;
|
||||
const recvT = lowerer.mapTypeOf(recvTs);
|
||||
if (recvT?.kind !== "union") return null;
|
||||
if (!lowerer.isStdlibMember(access)) return null;
|
||||
const def = lowerer.unions.get(recvT.unionId);
|
||||
@@ -11366,6 +11441,21 @@ function lowerObjectStaticCall(
|
||||
locOf(call),
|
||||
);
|
||||
}
|
||||
if (value.type.kind === "record" && member.startsWith("is")) {
|
||||
// A record's integrity state is its frozen bit: a frozen record is
|
||||
// neither extensible nor sealable further.
|
||||
const loc = locOf(call);
|
||||
const frozen: IrExpr = {
|
||||
kind: "libCall",
|
||||
fn: "record.isFrozen",
|
||||
args: [value],
|
||||
type: BOOL,
|
||||
loc,
|
||||
};
|
||||
return member === "isExtensible"
|
||||
? { kind: "unary", op: "!", operand: frozen, type: BOOL, loc }
|
||||
: frozen;
|
||||
}
|
||||
if (member === "preventExtensions" || member === "seal") {
|
||||
const integrity = lowerClassIntegrity(lowerer, call, member, value);
|
||||
if (integrity) return integrity;
|
||||
@@ -11379,12 +11469,16 @@ function lowerObjectStaticCall(
|
||||
loc: locOf(call),
|
||||
};
|
||||
}
|
||||
if (value.type.kind === "dyn") {
|
||||
if (
|
||||
value.type.kind === "dyn" ||
|
||||
(value.type.kind === "union" && lowerer.dynConvertible(value.type))
|
||||
) {
|
||||
// The kind is only known at runtime: the queries refuse a native
|
||||
// handle or a promise, whose integrity state scriptc does not track
|
||||
// (Object.preventExtensions and Object.seal do not change it, so any
|
||||
// answer would be invented). The static arms above keep the plain
|
||||
// queries for the kinds whose state is modeled.
|
||||
const boxed = value.type.kind === "dyn" ? value : lowerer.coerceToExpected(value, DYN);
|
||||
const operation = {
|
||||
preventExtensions: "dyn.preventExtensions",
|
||||
isExtensible: "dyn.isExtensibleQuery",
|
||||
@@ -11396,7 +11490,7 @@ function lowerObjectStaticCall(
|
||||
return {
|
||||
kind: "libCall",
|
||||
fn,
|
||||
args: [value],
|
||||
args: [boxed],
|
||||
type: member.startsWith("is") ? BOOL : DYN,
|
||||
loc: locOf(call),
|
||||
};
|
||||
|
||||
@@ -74,6 +74,11 @@ import { staticsEvaluationStatementOf } from "../class-statics-position.js";
|
||||
import { inertReadOf } from "./inert-reads.js";
|
||||
import { withoutParentheses } from "../outer-expressions.js";
|
||||
import { lowerZlibStreamNew, zlibClassName, zlibStreamModeOf } from "./builtins/compression.js";
|
||||
import {
|
||||
classMetadata,
|
||||
declarationMetadata,
|
||||
wantsDecoratorMetadata,
|
||||
} from "./decorator-metadata.js";
|
||||
import { everyStmtList } from "../../ir/traverse.js";
|
||||
import {
|
||||
type BuiltinClassRef,
|
||||
@@ -81,7 +86,11 @@ import {
|
||||
builtinClassRefOf,
|
||||
} from "./builtins/class-values.js";
|
||||
import type { FnCtx, Lowerer } from "./lowerer.js";
|
||||
import { inlineNamespaceRequireOf, lowerWithInlineRequireInit } from "./cjs-inline-require.js";
|
||||
import {
|
||||
cjsTableMemberSymbolOf,
|
||||
inlineNamespaceRequireOf,
|
||||
lowerWithInlineRequireInit,
|
||||
} from "./cjs-inline-require.js";
|
||||
import {
|
||||
BIGINT_BYTES_NAMES,
|
||||
BOOL,
|
||||
@@ -650,6 +659,14 @@ export function storedClassValueType(
|
||||
if (ts.isPropertyAccessExpression(expression) && !expression.questionDotToken) {
|
||||
const member = nsMemberIdentOf(lowerer, expression);
|
||||
if (member) return storedClassValueType(lowerer, member, visiting);
|
||||
// A member of a CommonJS require binding over esbuild's getter table:
|
||||
// the checker types it `any`, so the entry's own value binding — the
|
||||
// class its getter returns — is the class the access holds. The plain
|
||||
// `exports.name = name` spelling types as the class constructor and
|
||||
// needs no such step.
|
||||
const entry = cjsTableMemberSymbolOf(lowerer, expression);
|
||||
const info = entry ? lowerer.classBySymbol.get(entry) : undefined;
|
||||
if (info) return { kind: "classval", className: info.def.name };
|
||||
}
|
||||
if (expression.kind === ts.SyntaxKind.ThisKeyword) {
|
||||
const stored = lowerer.resolveThis();
|
||||
@@ -3002,7 +3019,10 @@ export function collectClassShapeInner(
|
||||
// `extends events.EventEmitter` — the namespace-member spelling of
|
||||
// the ambient emitter base resolves like the named import.
|
||||
if (t && ts.isPropertyAccessExpression(t.expression) && ts.isIdentifier(t.expression.name)) {
|
||||
const memberSym = lowerer.checker.getSymbolAtLocation(t.expression.name);
|
||||
const memberSym =
|
||||
lowerer.checker.getSymbolAtLocation(t.expression.name) ??
|
||||
cjsTableMemberSymbolOf(lowerer, t.expression) ??
|
||||
undefined;
|
||||
const resolved =
|
||||
memberSym && memberSym.flags & ts.SymbolFlags.Alias
|
||||
? lowerer.checker.getAliasedSymbol(memberSym)
|
||||
@@ -4478,8 +4498,11 @@ export function collectClassShapeInner(
|
||||
);
|
||||
if (!isParamProp) {
|
||||
// Non-keyword modifiers (parameter decorators) are rejected
|
||||
// by tsc under standard decorators; defensive.
|
||||
if (p.modifiers?.nodes.length) lowerer.unsupported("SC1090", p, "this parameter form");
|
||||
// by tsc under standard decorators; under
|
||||
// `experimentalDecorators` they are legal and belong to the
|
||||
// decoration event (legacyCtorParameters), not to the fields.
|
||||
if (p.modifiers?.nodes.some((m) => m.kind !== ts.SyntaxKind.Decorator) === true)
|
||||
lowerer.unsupported("SC1090", p, "this parameter form");
|
||||
continue;
|
||||
}
|
||||
// tsc rejects binding patterns (TS1187) and rest params
|
||||
@@ -7031,6 +7054,11 @@ function lowerLegacyParameterApplications(
|
||||
targetValue: IrExpr,
|
||||
keyValue: IrExpr | null,
|
||||
at: SrcLoc,
|
||||
/** `emitDecoratorMetadata` values: tsc's `__metadata` entries follow the
|
||||
* `__param` entries in the array, so they EVALUATE after the parameter
|
||||
* decorator expressions and APPLY before them. A class's design:paramtypes
|
||||
* entry is a class decorator: it receives the class value alone. */
|
||||
metadata: readonly IrExpr[] = [],
|
||||
): IrStmt[] {
|
||||
const stmts: IrStmt[] = [];
|
||||
const targetLocal = lowerer.declareHiddenLocal("legacyparamtarget", DYN);
|
||||
@@ -7064,6 +7092,37 @@ function lowerLegacyParameterApplications(
|
||||
});
|
||||
callees.push({ localId: callee.id, index: entry.index });
|
||||
}
|
||||
// The metadata entries evaluate after every parameter decorator expression
|
||||
// (they follow the __param entries in tsc's array).
|
||||
const metadataCallees: string[] = [];
|
||||
for (const value of metadata) {
|
||||
const callee = lowerer.declareHiddenLocal("legacymeta", DYN);
|
||||
stmts.push({ kind: "varDecl", localId: callee.id, init: value, loc: at });
|
||||
metadataCallees.push(callee.id);
|
||||
}
|
||||
// ...and apply before them, in reverse array order. Each application is
|
||||
// skipped when its decorator is falsy, as tsc's helper skips a falsy
|
||||
// array entry (Reflect.metadata is undefined without the polyfill).
|
||||
for (let i = metadataCallees.length - 1; i >= 0; i--)
|
||||
stmts.push({
|
||||
kind: "exprStmt",
|
||||
expr: {
|
||||
kind: "logical",
|
||||
op: "&&",
|
||||
left: { kind: "varRef", localId: metadataCallees[i]!, type: DYN, loc: at },
|
||||
right: {
|
||||
kind: "dynCall",
|
||||
callee: { kind: "varRef", localId: metadataCallees[i]!, type: DYN, loc: at },
|
||||
calleeName: "decorator",
|
||||
args: [{ kind: "varRef", localId: targetId, type: DYN, loc: at }],
|
||||
type: DYN,
|
||||
loc: at,
|
||||
},
|
||||
type: DYN,
|
||||
loc: at,
|
||||
},
|
||||
loc: at,
|
||||
});
|
||||
for (let i = callees.length - 1; i >= 0; i--) {
|
||||
const p = callees[i]!;
|
||||
stmts.push({
|
||||
@@ -7103,6 +7162,7 @@ function lowerLegacyConstructorDecorations(lowerer: Lowerer, info: ClassInfo): I
|
||||
classValueRef(lowerer, info, info.decl),
|
||||
null,
|
||||
loc,
|
||||
wantsDecoratorMetadata(lowerer, info.decl) ? classMetadata(lowerer, info.decl) : [],
|
||||
);
|
||||
} catch (e) {
|
||||
if (!(e instanceof PoisonError)) throw e;
|
||||
@@ -7286,7 +7346,17 @@ function lowerLegacyMemberDecorations(lowerer: Lowerer, info: ClassInfo): IrStmt
|
||||
});
|
||||
paramCallees.push({ localId: callee.id, index: parameter.index });
|
||||
}
|
||||
if (entry.kind === "method" && entry.decorators.length === 0) {
|
||||
// `emitDecoratorMetadata` design-type entries follow the __param
|
||||
// entries in tsc's array: evaluated after every decorator expression
|
||||
// and applied before them, in reverse array order.
|
||||
const metaCallees: string[] = [];
|
||||
if (wantsDecoratorMetadata(lowerer, entry.member))
|
||||
for (const value of declarationMetadata(lowerer, entry.member, info.decl)) {
|
||||
const callee = lowerer.declareHiddenLocal("legacymeta", DYN);
|
||||
stmts.push({ kind: "varDecl", localId: callee.id, init: value, loc: at });
|
||||
metaCallees.push(callee.id);
|
||||
}
|
||||
if (entry.kind === "method" && entry.decorators.length === 0 && metaCallees.length === 0) {
|
||||
// Only parameter decorators: they receive the prototype, the key
|
||||
// and the index; the member's own descriptor is unchanged, so no
|
||||
// descriptor object or definition is needed.
|
||||
@@ -7338,6 +7408,50 @@ function lowerLegacyMemberDecorations(lowerer: Lowerer, info: ClassInfo): IrStmt
|
||||
},
|
||||
loc: at,
|
||||
});
|
||||
// The design-type decorators apply before the parameter decorators
|
||||
// (tsc's array order is [member decorators, __param entries,
|
||||
// __metadata entries], applied in reverse), each skipped when
|
||||
// falsy, as the helper skips a falsy array entry.
|
||||
for (let i = metaCallees.length - 1; i >= 0; i--) {
|
||||
const calleeRef = varRef(metaCallees[i]!, DYN, at);
|
||||
const previous = varRef(descriptorId, DYN, at);
|
||||
const result = lowerer.declareHiddenLocal("legacyres", DYN);
|
||||
stmts.push({
|
||||
kind: "varDecl",
|
||||
localId: result.id,
|
||||
init: {
|
||||
kind: "logical",
|
||||
op: "||",
|
||||
left: {
|
||||
kind: "logical",
|
||||
op: "&&",
|
||||
left: calleeRef,
|
||||
right: {
|
||||
kind: "logical",
|
||||
op: "||",
|
||||
left: {
|
||||
kind: "dynCall",
|
||||
callee: calleeRef,
|
||||
calleeName: "decorator",
|
||||
args: [target(at), key(at), previous],
|
||||
type: DYN,
|
||||
loc: at,
|
||||
},
|
||||
right: previous,
|
||||
type: DYN,
|
||||
loc: at,
|
||||
},
|
||||
type: DYN,
|
||||
loc: at,
|
||||
},
|
||||
right: previous,
|
||||
type: DYN,
|
||||
loc: at,
|
||||
},
|
||||
loc: at,
|
||||
});
|
||||
descriptorId = result.id;
|
||||
}
|
||||
// Parameter decorators apply first (reverse parameter order, and
|
||||
// within one parameter reverse source order); __param ignores the
|
||||
// descriptor and its undefined result leaves `r` alone.
|
||||
@@ -7459,17 +7573,26 @@ function lowerLegacyMemberDecorations(lowerer: Lowerer, info: ClassInfo): IrStmt
|
||||
}
|
||||
// tsc passes the accumulated result (initially undefined) as the
|
||||
// decorator's third argument and keeps a truthy return; after the
|
||||
// reverse applications a truthy result is defined on the target.
|
||||
// reverse applications a truthy result is defined on the target. The
|
||||
// design-type entries follow the member decorators in the array, so
|
||||
// they apply first.
|
||||
const propertyChain = [
|
||||
...callees.map((c) => ({ localId: c.localId, loc: locOf(c.decorator) })),
|
||||
...metaCallees.map((localId) => ({ localId, loc: at })),
|
||||
];
|
||||
let resultId: string | null = null;
|
||||
for (let i = callees.length - 1; i >= 0; i--) {
|
||||
const d = callees[i]!.decorator;
|
||||
const dLoc = locOf(d);
|
||||
const callee = callees[i]!.localId;
|
||||
const calleeRef: IrExpr = { kind: "varRef", localId: callee, type: DYN, loc: dLoc };
|
||||
for (let i = propertyChain.length - 1; i >= 0; i--) {
|
||||
const dLoc = propertyChain[i]!.loc;
|
||||
const previous: IrExpr =
|
||||
resultId === null
|
||||
? dynUndefinedExpr(dLoc)
|
||||
: { kind: "varRef", localId: resultId, type: DYN, loc: dLoc };
|
||||
const calleeRef: IrExpr = {
|
||||
kind: "varRef",
|
||||
localId: propertyChain[i]!.localId,
|
||||
type: DYN,
|
||||
loc: dLoc,
|
||||
};
|
||||
const result = lowerer.declareHiddenLocal("legacyres", DYN);
|
||||
stmts.push({
|
||||
kind: "varDecl",
|
||||
@@ -7838,17 +7961,25 @@ function lowerClassDecoration(lowerer: Lowerer, info: ClassInfo): IrStmt[] {
|
||||
}
|
||||
// 1b. LEGACY constructor parameter decorators evaluate after the class
|
||||
// decorator expressions and apply before them (tsc's `__param` entries
|
||||
// follow the class decorators in the array).
|
||||
if (cd.legacy === true && info.legacyConstructorDecorations !== undefined)
|
||||
stmts.push(
|
||||
...lowerLegacyParameterApplications(
|
||||
lowerer,
|
||||
info.legacyConstructorDecorations,
|
||||
classValueRef(lowerer, info, info.decl),
|
||||
null,
|
||||
loc,
|
||||
),
|
||||
);
|
||||
// follow the class decorators in the array). `emitDecoratorMetadata`
|
||||
// appends a `design:paramtypes` entry after them.
|
||||
if (cd.legacy === true) {
|
||||
const parameters = info.legacyConstructorDecorations ?? [];
|
||||
const metadata = wantsDecoratorMetadata(lowerer, info.decl)
|
||||
? classMetadata(lowerer, info.decl)
|
||||
: [];
|
||||
if (parameters.length > 0 || metadata.length > 0)
|
||||
stmts.push(
|
||||
...lowerLegacyParameterApplications(
|
||||
lowerer,
|
||||
parameters,
|
||||
classValueRef(lowerer, info, info.decl),
|
||||
null,
|
||||
loc,
|
||||
metadata,
|
||||
),
|
||||
);
|
||||
}
|
||||
// 1c. STANDARD semantics: the heritage is read after every decorator
|
||||
// factory evaluated and before the class exists, so a cycle class read
|
||||
// there throws its ReferenceError at this point, exactly where Node
|
||||
|
||||
@@ -712,7 +712,12 @@ function lowerExprInner(lowerer: Lowerer, expr: ts.Expression): IrExpr {
|
||||
// the record's own missing-key read does. The armed value only
|
||||
// serves non-hot uses.
|
||||
const declared = assertedDictionaryReadType(lowerer, expr.expression);
|
||||
const armed = declared === null ? null : lowerer.withUndefinedArmOf(declared);
|
||||
// The dictionary crossed the checker through a cast, so a present
|
||||
// cell may hold null whatever the index value type says: the raw
|
||||
// value keeps the null arm beside the undefined one, and String(),
|
||||
// templates, equality and JSON observe it as Node does.
|
||||
const withNull = declared === null ? null : (lowerer.withNullArmOf(declared) ?? declared);
|
||||
const armed = withNull === null ? null : (lowerer.withUndefinedArmOf(withNull) ?? withNull);
|
||||
return armed !== null ? lowerer.coerceToExpected(inner, armed) : inner;
|
||||
}
|
||||
if (asserted !== null && numericAssertionType(lowerer, asserted))
|
||||
|
||||
@@ -23,11 +23,7 @@ import { collectRebindableFunctions, isRebindableFunction } from "./rebindable-f
|
||||
import { collectRebindableRequireDecls, isRebindableRequireDecl } from "./rebindable-requires.js";
|
||||
import { bindingSource } from "../binding-source.js";
|
||||
import type { Lowerer } from "./lowerer.js";
|
||||
import {
|
||||
sharedInitFlagStores,
|
||||
sharedModulePlans,
|
||||
sharedModuleRegistrations,
|
||||
} from "./lower-shared-modules.js";
|
||||
import { sharedModulePlans, sharedModuleRegistrations } from "./lower-shared-modules.js";
|
||||
import { dirname as dirnamePath, resolve as resolvePath } from "node:path";
|
||||
import {
|
||||
packageNameOfPath,
|
||||
@@ -5329,7 +5325,6 @@ export function lowerFileInit(
|
||||
stmt,
|
||||
deferred ? [deferred] : lowerer.lowerStmts([stmt]),
|
||||
);
|
||||
if (lowerer.sharedInitFlags.size > 0) stmtIr.push(...sharedInitFlagStores(lowerer, stmt));
|
||||
// Mixin instantiations created while THIS statement lowered (a class
|
||||
// expression's heritage is such a call) evaluate at this statement,
|
||||
// so their declaration-time code lands here, before the statement's
|
||||
|
||||
@@ -10768,16 +10768,12 @@ function lowerClientHeadersOption(
|
||||
"each header must be a `name: value` entry whose key is a literal (or a string-literal-typed const: [PORTLESS_HEADER])",
|
||||
);
|
||||
}
|
||||
/* A NUL in the name is Node's ERR_INVALID_HTTP_TOKEN at construction;
|
||||
* it is also this lowering's in-band array marker, so a user-written
|
||||
* key carrying one is refused rather than read as a marked name. */
|
||||
if (key.includes("\u0000")) {
|
||||
lowerer.noLowering(
|
||||
"header names containing a NUL byte",
|
||||
prop,
|
||||
"header names cannot contain a NUL",
|
||||
);
|
||||
}
|
||||
/* A NUL in the name is Node's ERR_INVALID_HTTP_TOKEN, raised by the
|
||||
* call the header belongs to; the runtime checks names per entry, in
|
||||
* property order, as Node does. The marked request-header pairs array
|
||||
* cannot carry such a name as a pair name (a leading NUL is its array
|
||||
* marker), so the statement path below sends it as a sentinel VALUE
|
||||
* instead. */
|
||||
const raw = lowerer.lowerExpr(prop.initializer);
|
||||
if (
|
||||
raw.type.kind === "array" &&
|
||||
@@ -10807,8 +10803,18 @@ function lowerClientHeadersOption(
|
||||
out.push({ kind: "strLit", value: pairName(key), type: STRING, loc });
|
||||
out.push({ kind: "strLit", value: "\u0000", type: STRING, loc });
|
||||
};
|
||||
/* A request header name carrying a NUL, or an empty one, is Node's
|
||||
* ERR_INVALID_HTTP_TOKEN at construction; it travels as a sentinel pair
|
||||
* value, because a pair name could read as the array marker (a marked
|
||||
* empty name is exactly the sentinel's own name). So the pairs array is
|
||||
* built by pushes even when every value is known. */
|
||||
const needsNameSentinel = (key: string): boolean => key === "" || key.includes("\u0000");
|
||||
const hasNameSentinel = markArrays && entries.some((e) => needsNameSentinel(e.key));
|
||||
/* Every value known at compile time packs into the literal pairs array. */
|
||||
if (entries.every((e) => e.value.type.kind !== "array" || e.value.kind === "arrayLit")) {
|
||||
if (
|
||||
!hasNameSentinel &&
|
||||
entries.every((e) => e.value.type.kind !== "array" || e.value.kind === "arrayLit")
|
||||
) {
|
||||
const elems: IrExpr[] = [];
|
||||
for (const entry of entries) {
|
||||
const raw = entry.value;
|
||||
@@ -10841,9 +10847,10 @@ function lowerClientHeadersOption(
|
||||
}
|
||||
return { kind: "arrayLit", elems, type: arrayOf(STRING), loc };
|
||||
}
|
||||
/* An array-valued header whose elements are only known at run time: the
|
||||
* pairs array is built by pushes so the elements keep their place in the
|
||||
* header order (a property after it still lands after its lines). */
|
||||
/* An array-valued header whose elements are only known at run time, or
|
||||
* an invalid NUL or empty name's sentinel: the pairs array is built by pushes so
|
||||
* the elements keep their place in the header order (a property after it
|
||||
* still lands after its lines). */
|
||||
const pairsT = arrayOf(STRING);
|
||||
const out = lowerer.declareHiddenLocal("%httpHeaderPairs", pairsT);
|
||||
const outRef = (): IrExpr => ({ kind: "varRef", localId: out.id, type: pairsT, loc });
|
||||
@@ -10869,6 +10876,19 @@ function lowerClientHeadersOption(
|
||||
];
|
||||
for (const entry of entries) {
|
||||
const raw = entry.value;
|
||||
if (markArrays && needsNameSentinel(entry.key)) {
|
||||
/* The runtime raises Node's ERR_INVALID_HTTP_TOKEN when it checks
|
||||
* the entries, in property order, before any header is stored. The
|
||||
* rejected name rides as the sentinel pair's VALUE, never as a pair
|
||||
* name, so it cannot be read as the array marker. The value still
|
||||
* evaluates, as Node evaluates the whole headers object. */
|
||||
stmts.push({ kind: "exprStmt", expr: raw, loc });
|
||||
stmts.push(
|
||||
push({ kind: "strLit", value: "\u0000", type: STRING, loc }),
|
||||
push({ kind: "strLit", value: entry.key, type: STRING, loc }),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (raw.type.kind !== "array") {
|
||||
let value = raw;
|
||||
if (value.type.kind === "f64") {
|
||||
|
||||
@@ -560,12 +560,15 @@ export function sharedModulePlans(lowerer: Lowerer): SharedModulePlan[] {
|
||||
const flag = `%g.shared.${plans.length}.${e.name}%initialized`;
|
||||
lowerer.globalsList.push({ id: flag, name: "%initialized", type: BOOL, mutable: true });
|
||||
e.flag = flag;
|
||||
let stmt: ts.Node | undefined = e.ident.parent;
|
||||
while (stmt !== undefined && !ts.isVariableStatement(stmt)) stmt = stmt.parent;
|
||||
if (stmt !== undefined) {
|
||||
const list = lowerer.sharedInitFlags.get(stmt as ts.Statement) ?? [];
|
||||
// The flag publishes with the declarator that initializes the binding:
|
||||
// a later declarator of the same statement can call island code, which
|
||||
// must then read the earlier binding's value. Export aliases of one
|
||||
// declaration share its ident, so they publish together.
|
||||
const decl = e.ident.parent;
|
||||
if (decl !== undefined && ts.isVariableDeclaration(decl)) {
|
||||
const list = lowerer.sharedInitFlags.get(decl) ?? [];
|
||||
list.push(flag);
|
||||
lowerer.sharedInitFlags.set(stmt as ts.Statement, list);
|
||||
lowerer.sharedInitFlags.set(decl, list);
|
||||
}
|
||||
}
|
||||
plans.push({ sf, path, exports });
|
||||
@@ -584,11 +587,11 @@ export function sharedModulePlans(lowerer: Lowerer): SharedModulePlan[] {
|
||||
return plans;
|
||||
}
|
||||
|
||||
/** The flag stores after a shared module's declaration statement. */
|
||||
export function sharedInitFlagStores(lowerer: Lowerer, stmt: ts.Statement): IrStmt[] {
|
||||
const flags = lowerer.sharedInitFlags.get(stmt);
|
||||
/** The flag stores after a shared module's variable declarator ran. */
|
||||
export function sharedInitFlagStores(lowerer: Lowerer, decl: ts.VariableDeclaration): IrStmt[] {
|
||||
const flags = lowerer.sharedInitFlags.get(decl);
|
||||
if (flags === undefined) return [];
|
||||
const loc = locOf(stmt);
|
||||
const loc = locOf(decl);
|
||||
return flags.map((flag) => ({
|
||||
kind: "assign",
|
||||
localId: flag,
|
||||
|
||||
@@ -3326,6 +3326,29 @@ export function npmMemberFence(lowerer: Lowerer, access: ts.PropertyAccessExpres
|
||||
// that declares the member: a data shape's member is data the program
|
||||
// holds, a value shape's member still has nothing to read from.
|
||||
const member = lowerer.checker.getSymbolAtLocation(access.name);
|
||||
// A member a package declares inside `declare global` (reflect-metadata's
|
||||
// metadata API on Reflect, for one) is a GLOBAL, not a package value: its
|
||||
// runtime home is the global object the program's own modules mutate, so
|
||||
// it has a representation without the package's implementation.
|
||||
const globalAugmentationMember =
|
||||
member !== undefined &&
|
||||
member.declarations !== undefined &&
|
||||
member.declarations.length > 0 &&
|
||||
member.declarations.every((declaration) => {
|
||||
for (
|
||||
let node: ts.Node | undefined = declaration.parent;
|
||||
node !== undefined;
|
||||
node = node.parent
|
||||
)
|
||||
if (
|
||||
ts.isModuleDeclaration(node) &&
|
||||
ts.isIdentifier(node.name) &&
|
||||
node.name.text === "global"
|
||||
)
|
||||
return true;
|
||||
return false;
|
||||
});
|
||||
if (globalAugmentationMember) return;
|
||||
pkg = lowerer.npmPackageOfSymbol(member);
|
||||
if (pkg !== null && member && packageMemberIsData(member, lowerer.checker, ctx)) return;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { funcTypeFromParamShapes } from "./call-signatures.js";
|
||||
import {
|
||||
cjsEsModuleStampObjectWrite,
|
||||
cjsExportStatementObjectWrites,
|
||||
cjsExportsObjectRef,
|
||||
lowerCjsExportsObjectWrite,
|
||||
} from "./cjs-exports-object-value.js";
|
||||
import { lowerStaticPrivateAssignment } from "./private-statics.js";
|
||||
@@ -444,6 +445,7 @@ import { fenceX509KeyWalk } from "./builtins/x509.js";
|
||||
import { classGeneratorIterable } from "./class-iterables.js";
|
||||
import { iterableUnionOf, lowerForOfIterable } from "./iterable-values.js";
|
||||
import { refuseDefinedEnvWrite } from "./builtins/environment.js";
|
||||
import { sharedInitFlagStores } from "./lower-shared-modules.js";
|
||||
|
||||
interface UsingRegistration {
|
||||
acquire: IrStmt[];
|
||||
@@ -3051,7 +3053,8 @@ export function lowerVarStatement(lowerer: Lowerer, stmt: ts.VariableStatement):
|
||||
// A require binding earlier code can read is initialized from here on
|
||||
// (require-initialization.ts).
|
||||
const initialized = requireInitFlagStmt(lowerer, decl);
|
||||
return initialized ? [...lowered, initialized] : lowered;
|
||||
const sharedFlags = sharedInitFlagStores(lowerer, decl);
|
||||
return [...lowered, ...(initialized ? [initialized] : []), ...sharedFlags];
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3108,27 +3111,50 @@ function lowerRequireDeclaration(
|
||||
});
|
||||
}
|
||||
// A require binding the file reassigns: the module's value is stored in
|
||||
// the checked-dynamic global collectGlobals registered, and the
|
||||
// assignment replaces it (rebindable-requires.ts).
|
||||
// the checked-dynamic storage the binding owns, and the assignment
|
||||
// replaces it (rebindable-requires.ts). A top-level binding stores it in
|
||||
// the module global collectGlobals registered; a `var` inside a function
|
||||
// (React's development jsx-runtime reassigns its IIFE's require result)
|
||||
// stores it in the function-scoped hoisted slot.
|
||||
if (ts.isIdentifier(decl.name) && isRebindableRequireDecl(lowerer, decl)) {
|
||||
const symbol = lowerer.checker.getSymbolAtLocation(decl.name);
|
||||
const global = symbol === undefined ? undefined : lowerer.globalsBySymbol.get(symbol);
|
||||
const stored =
|
||||
global === undefined ? null : requireReboundValue(lowerer, decl, decl.name, spec);
|
||||
if (global === undefined || stored === null) {
|
||||
lowerer.unsupported(
|
||||
"SC1090",
|
||||
decl,
|
||||
`reassigning '${decl.name.text}', a require() binding whose module value has no static representation`,
|
||||
);
|
||||
// A declaration in a block at the module's top level owns no global and
|
||||
// no function slot; it keeps the alias plumbing, and the assignment
|
||||
// keeps its own named refusal.
|
||||
const nested = global === undefined && nestedRequireRebindPosition(decl);
|
||||
if (global !== undefined || nested) {
|
||||
const stored =
|
||||
symbol === undefined ? null : requireReboundValue(lowerer, decl, decl.name, spec);
|
||||
if (stored === null) {
|
||||
lowerer.unsupported(
|
||||
"SC1090",
|
||||
decl,
|
||||
`reassigning '${decl.name.text}', a require() binding whose module value has no static representation`,
|
||||
);
|
||||
}
|
||||
if (global !== undefined) {
|
||||
out.push({
|
||||
kind: "assign",
|
||||
localId: global.id,
|
||||
value: stored!,
|
||||
loc: locOf(decl),
|
||||
});
|
||||
return out;
|
||||
}
|
||||
lowerer.runtimeOptionalBindingTypes.set(symbol!, DYN);
|
||||
lowerer.jsWidenedBindings.add(symbol!);
|
||||
const local = hoistVarBinding(lowerer, symbol!, decl.name, stored!.type);
|
||||
if (local.type.kind !== "dyn") {
|
||||
lowerer.unsupported(
|
||||
"SC1090",
|
||||
decl,
|
||||
`reassigning '${decl.name.text}', a require() binding the function reads before its declaration`,
|
||||
);
|
||||
}
|
||||
out.push({ kind: "assign", localId: local.id, value: stored!, loc: locOf(decl) });
|
||||
return out;
|
||||
}
|
||||
out.push({
|
||||
kind: "assign",
|
||||
localId: global!.id,
|
||||
value: stored!,
|
||||
loc: locOf(decl),
|
||||
});
|
||||
return out;
|
||||
}
|
||||
// Snapshot bindings and nested patterns evaluate in pattern order,
|
||||
// immediately after the required module has initialized.
|
||||
@@ -3255,6 +3281,17 @@ function lowerRequireDeclaration(
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Whether a declaration sits inside a function body (its rebound require
|
||||
* storage is a function-scoped local) rather than at the module's top
|
||||
* level (where collectGlobals registered a module global). */
|
||||
function nestedRequireRebindPosition(decl: ts.VariableDeclaration): boolean {
|
||||
for (let node: ts.Node | undefined = decl.parent; node !== undefined; node = node.parent) {
|
||||
if (ts.isFunctionLike(node)) return true;
|
||||
if (ts.isSourceFile(node)) return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function lowerVarDeclarator(
|
||||
lowerer: Lowerer,
|
||||
stmt: ts.VariableStatement,
|
||||
@@ -18406,6 +18443,16 @@ function requireReboundValue(
|
||||
const boxed = lowerer.moduleNamespaceDyn(ns);
|
||||
if (boxed !== null) return boxed;
|
||||
}
|
||||
// A table module's real `module.exports` object: the pre-pass gives one to
|
||||
// every module a rebound require names (cjs-exports-object-value.ts), so
|
||||
// the binding stores the object Node's require answers — the identity
|
||||
// every require of the module sees, extensible and in write order. A
|
||||
// module whose export a condition chooses between static tables (React's
|
||||
// index.js) hands out the chosen table's object the same way.
|
||||
if (dep !== null) {
|
||||
const object = cjsExportsObjectRef(lowerer, dep, locOf(decl));
|
||||
if (object !== null) return object;
|
||||
}
|
||||
// A module whose exports are one object literal (`module.exports = { … }`)
|
||||
// has no first-class exports object in the lowering, so a checked-dynamic
|
||||
// object built from its export table answers every member read as the
|
||||
|
||||
@@ -3846,6 +3846,15 @@ function unboxDynStage(lowerer: Lowerer, v: IrExpr, node: ts.Expression): IrExpr
|
||||
};
|
||||
}
|
||||
|
||||
/** Whether the class declares (or inherits) a zero-parameter
|
||||
* `[Symbol.asyncIterator]`, which makes its instances async iterables a
|
||||
* pipeline source may be. */
|
||||
function classDeclaresAsyncIterator(lowerer: Lowerer, className: string): boolean {
|
||||
const info = lowerer.classes.get(className);
|
||||
const open = info === undefined ? null : lowerer.findMethodOn(info, "sym:asyncIterator");
|
||||
return open !== null && open.sig.abstract !== true && open.sig.params.length === 0;
|
||||
}
|
||||
|
||||
/** A pipeline whose first stage is checked-dynamic, lowered with that
|
||||
* stage already evaluated: `expr` is the stream it unboxes to, or, when
|
||||
* `iterable` is set, the value to pump as an iterable source. */
|
||||
@@ -3870,6 +3879,30 @@ function lowerDynSourcePipeline(
|
||||
if (pipelineStageFunction(lowerer, node) !== null) return null;
|
||||
if (iterableSourceType(lowerer, node) !== null || isValueStream(lowerer, node)) return null;
|
||||
let value = lowerer.lowerExpr(node);
|
||||
// A class instance whose class declares its own [Symbol.asyncIterator]
|
||||
// is an async iterable, and Node's pipeline pumps it like any other
|
||||
// iterable source. It takes the same checked-dynamic iterable path an
|
||||
// untyped source takes (`stream.dynIterableSource` steps it), because
|
||||
// the pump is the one already lowered for untyped iterables.
|
||||
if (value.type.kind === "object" && classDeclaresAsyncIterator(lowerer, value.type.className)) {
|
||||
const held = lowerer.declareHiddenLocal("%pipelineSource", DYN);
|
||||
const ref = varRef(held.id, DYN, loc);
|
||||
const iterable = build({ expr: ref, iterable: true });
|
||||
return {
|
||||
kind: "seqExpr",
|
||||
stmts: [
|
||||
{
|
||||
kind: "varDecl",
|
||||
localId: held.id,
|
||||
init: { kind: "dynFrom", value, type: DYN, loc },
|
||||
loc,
|
||||
},
|
||||
],
|
||||
result: iterable,
|
||||
type: iterable.type,
|
||||
loc,
|
||||
};
|
||||
}
|
||||
// A Set, a Map or a generator object is iterated through its
|
||||
// checked-dynamic value.
|
||||
if (BOXED_SOURCE_KINDS.has(value.type.kind) && lowerer.dynConvertible(value.type)) {
|
||||
|
||||
@@ -5,7 +5,7 @@ import { programCreatesWrappers, routeWrapperConsumers } from "./primitive-wrapp
|
||||
import type { DiagnosticCode } from "../../diagnostics/codes.js";
|
||||
import { markInferredFactChecks, shapeOverlayFileNames } from "../shape-inference/index.js";
|
||||
import { npmStaticPackageOfPath } from "../npm-static.js";
|
||||
import { globalMemberValue } from "./global-values.js";
|
||||
import { globalMemberValue, jsGlobalValueByName } from "./global-values.js";
|
||||
import { unionNarrowFailureMessage } from "./union-narrow.js";
|
||||
import {
|
||||
arrayClassFieldsFn,
|
||||
@@ -463,6 +463,7 @@ import {
|
||||
VOID,
|
||||
} from "../../ir/ir.js";
|
||||
import { provenanceActive } from "../provenance-registry.js";
|
||||
import { cjsGetterTableOf, type CjsGetterTable } from "../cjs-getter-table.js";
|
||||
import {
|
||||
canonicalBuiltinModule,
|
||||
type StartupCrash,
|
||||
@@ -516,6 +517,7 @@ import {
|
||||
type SymbolProvenance,
|
||||
type TypeMapperCtx,
|
||||
UnionRegistry,
|
||||
withNullArm as withNullArmCanonical,
|
||||
withUndefinedArm as withUndefinedArmCanonical,
|
||||
} from "../type-mapper.js";
|
||||
import {
|
||||
@@ -1343,6 +1345,9 @@ export interface LowerOptions {
|
||||
* sets `experimentalDecorators`, which take the legacy decorator order,
|
||||
* calling convention and descriptor rules. */
|
||||
legacyDecoratorFiles?: ReadonlySet<string> | undefined;
|
||||
/** LoadResult.typeWorld.decoratorMetadataFiles: the files whose tsconfig
|
||||
* also sets `emitDecoratorMetadata`. */
|
||||
decoratorMetadataFiles?: ReadonlySet<string> | undefined;
|
||||
/** Coverage: additionally lower the unreached remainder (bodies nothing
|
||||
* on the entry path reaches) in a throwaway pass and report its
|
||||
* diagnostics and stats under `unreached` — the whole-program analysis
|
||||
@@ -1556,6 +1561,8 @@ export interface LowererMode {
|
||||
parameterPropertiesFirst?: ReadonlySet<string> | undefined;
|
||||
/** LoadResult.typeWorld.legacyDecoratorFiles. */
|
||||
legacyDecoratorFiles?: ReadonlySet<string> | undefined;
|
||||
/** LoadResult.typeWorld.decoratorMetadataFiles. */
|
||||
decoratorMetadataFiles?: ReadonlySet<string> | undefined;
|
||||
/** Names of bodies a prior reachability pass reached; null lowers everything. */
|
||||
reachable?: ReadonlySet<string> | null;
|
||||
/** Coverage remainder: lower ONLY bodies outside `reachable`, skip the
|
||||
@@ -2027,6 +2034,7 @@ function lowerToIrWithIslands(
|
||||
dependencyJs: options.dependencyJs,
|
||||
parameterPropertiesFirst: options.parameterPropertiesFirst,
|
||||
legacyDecoratorFiles: options.legacyDecoratorFiles,
|
||||
decoratorMetadataFiles: options.decoratorMetadataFiles,
|
||||
targetPlatform,
|
||||
define: options.define,
|
||||
startupCrash,
|
||||
@@ -2065,6 +2073,7 @@ function lowerToIrWithIslands(
|
||||
dependencyJs: options.dependencyJs,
|
||||
parameterPropertiesFirst: options.parameterPropertiesFirst,
|
||||
legacyDecoratorFiles: options.legacyDecoratorFiles,
|
||||
decoratorMetadataFiles: options.decoratorMetadataFiles,
|
||||
targetPlatform,
|
||||
define: options.define,
|
||||
startupCrash,
|
||||
@@ -2200,6 +2209,7 @@ function lowerToIrWithIslands(
|
||||
dependencyJs: options.dependencyJs,
|
||||
parameterPropertiesFirst: options.parameterPropertiesFirst,
|
||||
legacyDecoratorFiles: options.legacyDecoratorFiles,
|
||||
decoratorMetadataFiles: options.decoratorMetadataFiles,
|
||||
...(general
|
||||
? {
|
||||
generalNodeStreams: true,
|
||||
@@ -2298,6 +2308,7 @@ function lowerToIrWithIslands(
|
||||
dependencyJs: options.dependencyJs,
|
||||
parameterPropertiesFirst: options.parameterPropertiesFirst,
|
||||
legacyDecoratorFiles: options.legacyDecoratorFiles,
|
||||
decoratorMetadataFiles: options.decoratorMetadataFiles,
|
||||
targetPlatform,
|
||||
define: options.define,
|
||||
startupCrash,
|
||||
@@ -2394,6 +2405,7 @@ function lowerToIrWithIslands(
|
||||
dependencyJs: options.dependencyJs,
|
||||
parameterPropertiesFirst: options.parameterPropertiesFirst,
|
||||
legacyDecoratorFiles: options.legacyDecoratorFiles,
|
||||
decoratorMetadataFiles: options.decoratorMetadataFiles,
|
||||
...(generalNodeStreams ? { generalNodeStreams: true } : {}),
|
||||
...(dynNodeStreams ? { dynNodeStreams: true } : {}),
|
||||
reachable,
|
||||
@@ -2657,6 +2669,7 @@ function lowerToIrWithIslands(
|
||||
dependencyJs: options.dependencyJs,
|
||||
parameterPropertiesFirst: options.parameterPropertiesFirst,
|
||||
legacyDecoratorFiles: options.legacyDecoratorFiles,
|
||||
decoratorMetadataFiles: options.decoratorMetadataFiles,
|
||||
...(general ? { generalNodeStreams: true } : {}),
|
||||
...(general && dyn ? { dynNodeStreams: true } : {}),
|
||||
reachable,
|
||||
@@ -5077,6 +5090,17 @@ export class Lowerer {
|
||||
if (actual.kind !== "union" || this.armTag(actual.unionId, UNDEFINED_T) < 0) return null;
|
||||
const present = this.stripUndefinedArm(actual);
|
||||
if (typeEquals(present, expected)) return actual;
|
||||
// A checked-dynamic dictionary read can hold a null cell whatever its
|
||||
// index value type or the assertion says. A slot typed as the read
|
||||
// without its unit arms widens to the value it actually receives, so
|
||||
// the storage keeps the null arm beside the undefined one.
|
||||
const arms = this.unions.get(actual.unionId)?.arms;
|
||||
const data = arms?.filter((arm) => arm.kind !== "nullT" && arm.kind !== "undefinedT");
|
||||
if (arms !== undefined && data !== undefined && data.length > 0 && data.length < arms.length) {
|
||||
const dataOnly: IrType =
|
||||
data.length === 1 ? data[0]! : { kind: "union", unionId: this.unions.intern(data) };
|
||||
if (typeEquals(dataOnly, expected)) return actual;
|
||||
}
|
||||
// Only a bare expected arm gains runtime-optional storage. A slot that
|
||||
// already admits undefined keeps its own checked representation.
|
||||
if (expected.kind === "union" && this.armTag(expected.unionId, UNDEFINED_T) >= 0) return null;
|
||||
@@ -5849,7 +5873,7 @@ export class Lowerer {
|
||||
* `start:end:file`: refused when the lowered program gives a function its
|
||||
* own `call` or `apply` (refuseForwardsToOwnCall). */
|
||||
readonly receiverForwardSites = new Set<string>();
|
||||
readonly sharedInitFlags = new Map<ts.Statement, string[]>();
|
||||
readonly sharedInitFlags = new Map<ts.VariableDeclaration, string[]>();
|
||||
/** Per-directory answers of experimental-import.ts's declaration-file test. */
|
||||
readonly experimentalFiles = new Map<string, boolean>();
|
||||
/** Interned LifetimeRegion.run helpers, by callback type key. */
|
||||
@@ -6890,6 +6914,7 @@ export class Lowerer {
|
||||
"dependencyJs",
|
||||
"parameterPropertiesFirst",
|
||||
"legacyDecoratorFiles",
|
||||
"decoratorMetadataFiles",
|
||||
"libraryCallbacks",
|
||||
"ffiBindingSymbols",
|
||||
"ffiErrorSymbols",
|
||||
@@ -7027,6 +7052,10 @@ export class Lowerer {
|
||||
"cjsInFileExportMemberGlobals",
|
||||
"cjsWholeExportSymbols",
|
||||
"cjsLiveMemberExports",
|
||||
// Each module's esbuild getter-table export is a pure function of the
|
||||
// module's source text: recognized on first use and read again when a
|
||||
// unit replays.
|
||||
"cjsGetterTables",
|
||||
"cjsNamespaceTargets",
|
||||
"cjsReceiverProofs",
|
||||
"cjsExportsShapes",
|
||||
@@ -7437,6 +7466,9 @@ export class Lowerer {
|
||||
/** The files whose tsconfig sets `experimentalDecorators`
|
||||
* (LoadResult.typeWorld.legacyDecoratorFiles). */
|
||||
readonly legacyDecoratorFiles: ReadonlySet<string> | null;
|
||||
/** The files whose tsconfig sets `emitDecoratorMetadata`
|
||||
* (LoadResult.typeWorld.decoratorMetadataFiles). */
|
||||
readonly decoratorMetadataFiles: ReadonlySet<string> | null;
|
||||
private readonly checkedJsFiles = new Map<ts.SourceFile, boolean>();
|
||||
/** Outbound native bindings by their source-level ambient name. */
|
||||
readonly ffiImports: readonly IrFfiImport[];
|
||||
@@ -8107,6 +8139,7 @@ export class Lowerer {
|
||||
this.dependencyJs = mode.dependencyJs ?? null;
|
||||
this.parameterPropertiesFirst = mode.parameterPropertiesFirst ?? null;
|
||||
this.legacyDecoratorFiles = mode.legacyDecoratorFiles ?? null;
|
||||
this.decoratorMetadataFiles = mode.decoratorMetadataFiles ?? null;
|
||||
this.reachable = mode.reachable ?? null;
|
||||
this.remainder = mode.remainder ?? false;
|
||||
this.coverageReached = mode.coverageReached ?? false;
|
||||
@@ -8710,6 +8743,25 @@ export class Lowerer {
|
||||
* function of the module graph, shared by every namespace key census. */
|
||||
private readonly runtimeExports = new Map<ts.SourceFile, Set<string>>();
|
||||
|
||||
/** Each module's esbuild getter-table whole export (cjs-getter-table.ts),
|
||||
* recognized once. Null entries are files without the shape. */
|
||||
private readonly cjsGetterTables = new Map<ts.SourceFile, CjsGetterTable | null>();
|
||||
|
||||
/** The esbuild getter-table whole export of a module
|
||||
* (`var T = {}; __export(T, { name: () => value }); module.exports =
|
||||
* T` / `= __toCommonJS(T)`), or null. Node's `require()` answers its
|
||||
* entries like plain member exports, which the checker does not model
|
||||
* (`module.exports` names an identifier), so the require-binding paths
|
||||
* resolve members through this shape from the syntax. */
|
||||
getterTableOf(sf: ts.SourceFile): CjsGetterTable | null {
|
||||
let table = this.cjsGetterTables.get(sf);
|
||||
if (table === undefined) {
|
||||
table = cjsGetterTableOf(sf);
|
||||
this.cjsGetterTables.set(sf, table);
|
||||
}
|
||||
return table;
|
||||
}
|
||||
|
||||
cjsNamespaceOf(dep: ts.SourceFile): {
|
||||
names: ReadonlySet<string>;
|
||||
assignedLater: ReadonlySet<string> | "all";
|
||||
@@ -9725,9 +9777,22 @@ export class Lowerer {
|
||||
// any-typed namespace can recover the same property symbols an
|
||||
// ordinary direct require receives from checker inference.
|
||||
const root = exports?.get("export=" as ts.__String);
|
||||
return root
|
||||
? this.checker.getPropertyOfType(this.checker.getTypeOfSymbol(root), name)
|
||||
: undefined;
|
||||
if (root) {
|
||||
const member = this.checker.getPropertyOfType(this.checker.getTypeOfSymbol(root), name);
|
||||
if (member !== undefined) return member;
|
||||
}
|
||||
// esbuild's getter table: `module.exports` names an identifier the
|
||||
// checker types as an empty object, so the export map has no member.
|
||||
// The getter's returned expression is the exported value, and an
|
||||
// identifier there names the module-level binding Node's getter reads
|
||||
// — the same symbol a plain `exports.name = name` export answers with.
|
||||
const value = this.getterTableOf(sf)?.entries.get(name);
|
||||
if (value !== undefined && ts.isIdentifier(value)) {
|
||||
const symbol = this.checker.getSymbolAtLocation(value);
|
||||
if (symbol !== undefined)
|
||||
return symbol.flags & ts.SymbolFlags.Alias ? this.checker.getAliasedSymbol(symbol) : symbol;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** The local VALUE symbol behind a CJS export-table property symbol —
|
||||
@@ -10885,6 +10950,67 @@ export class Lowerer {
|
||||
* TypeScript's default indexed-access type is a useful source annotation,
|
||||
* but it is not a runtime proof; promoting only the affected slots keeps
|
||||
* the rest of the dense ABI unchanged. */
|
||||
/** Whether `JSON.stringify` can answer undefined for its root: an untyped
|
||||
* root (a JavaScript parameter has no mapping yet), an instance of a class
|
||||
* with a toJSON method, or a checked-dictionary read the checker calls
|
||||
* present (a missing key answers undefined; `read!` performs no check). */
|
||||
jsonStringifyMayAnswerUndefined(e: ts.CallExpression): boolean {
|
||||
const argNode = e.arguments.nodes[0];
|
||||
if (!argNode || ts.isSpreadElement(argNode)) return false;
|
||||
const root = this.typeOf(argNode);
|
||||
const mapped = this.mapTypeOf(root);
|
||||
if (
|
||||
mapped?.kind === "dyn" ||
|
||||
(mapped === null && (root.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) !== 0) ||
|
||||
(mapped?.kind === "union" && this.armTag(mapped.unionId, UNDEFINED_T) >= 0) ||
|
||||
(mapped?.kind === "object" &&
|
||||
this.findMethodOn(this.classes.get(mapped.className) ?? null, "toJSON") !== null)
|
||||
)
|
||||
return true;
|
||||
const readRoot = withoutParenthesesAssertionsNonNull(argNode);
|
||||
return (
|
||||
(ts.isElementAccessExpression(readRoot) || ts.isPropertyAccessExpression(readRoot)) &&
|
||||
(this.dynIndexSignatureValueRead(readRoot) !== null ||
|
||||
(ts.isElementAccessExpression(readRoot) &&
|
||||
this.optionalIndexSignatureRead(readRoot) !== null))
|
||||
);
|
||||
}
|
||||
|
||||
/** An unannotated binding initialized by a `JSON.stringify` that may answer
|
||||
* undefined keeps `string | undefined`: the checker types the call
|
||||
* `string`, but the absent root's result is stored as it runs, and a
|
||||
* `string` slot would trap at the declaration. A module-level binding
|
||||
* widens its global storage the same way. */
|
||||
analyzeJsonStringifyBindings(parts: FileParts[]): void {
|
||||
for (const { sf } of parts) {
|
||||
if (!ts.sourceTextIncludes(sf, "stringify")) continue;
|
||||
ts.walkPreorder(sf, (node) => {
|
||||
if (!ts.isVariableDeclaration(node) || node.type || !node.initializer) return undefined;
|
||||
if (!ts.isIdentifier(node.name)) return undefined;
|
||||
let init: ts.Expression = node.initializer;
|
||||
while (ts.isParenthesizedExpression(init)) init = init.expression;
|
||||
// The syntactic guard keeps every other call's arguments out of the
|
||||
// type queries below: an object literal passed elsewhere must keep
|
||||
// the layout ordinary lowering gives it.
|
||||
if (
|
||||
!ts.isCallExpression(init) ||
|
||||
!ts.isPropertyAccessExpression(init.expression) ||
|
||||
init.expression.name.text !== "stringify" ||
|
||||
!this.isStdlibGlobal(init.expression.expression, "JSON")
|
||||
)
|
||||
return undefined;
|
||||
if (!this.jsonStringifyMayAnswerUndefined(init)) return undefined;
|
||||
const symbol = this.checker.getSymbolAtLocation(node.name);
|
||||
if (!symbol) return undefined;
|
||||
const widened = this.withUndefinedArm(STRING);
|
||||
this.runtimeOptionalBindingTypes.set(symbol, widened);
|
||||
const global = this.globalOf(node.name);
|
||||
if (global && !typeEquals(global.type, widened)) global.type = widened;
|
||||
return undefined;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** A Date's `toJSON()` answers null for an invalid date while the lib
|
||||
* types say `string`: unannotated bindings initialized by such a call,
|
||||
* and object-literal fields holding one, keep `string | null`. */
|
||||
@@ -12468,6 +12594,9 @@ export class Lowerer {
|
||||
// reads the result as text (jsonResultTextOnly).
|
||||
if (!jsonResultTextOnly(this, e) && jsonStringifyRootMaybeUndefined(this, rootNode))
|
||||
return true;
|
||||
// A checked dictionary read the checker calls present: a missing
|
||||
// key answers undefined.
|
||||
if (!jsonResultTextOnly(this, e) && this.jsonStringifyMayAnswerUndefined(e)) return true;
|
||||
}
|
||||
if (
|
||||
ts.isCallExpression(e) &&
|
||||
@@ -15455,6 +15584,7 @@ export class Lowerer {
|
||||
for (const symbol of this.jsWidenedBindings)
|
||||
this.runtimeOptionalBindingTypes.set(symbol, DYN);
|
||||
this.analyzeDateJsonResults(parts);
|
||||
this.analyzeJsonStringifyBindings(parts);
|
||||
this.analyzeGuardedRecordReadGlobals(parts);
|
||||
this.analyzeJsWidenedBindings(parts);
|
||||
this.widenRetypedOperatorBindings(parts);
|
||||
@@ -16306,6 +16436,7 @@ export class Lowerer {
|
||||
for (const symbol of this.jsWidenedBindings)
|
||||
this.runtimeOptionalBindingTypes.set(symbol, DYN);
|
||||
this.analyzeDateJsonResults(parts);
|
||||
this.analyzeJsonStringifyBindings(parts);
|
||||
this.analyzeGuardedRecordReadGlobals(parts);
|
||||
this.analyzeJsWidenedBindings(parts);
|
||||
this.widenRetypedOperatorBindings(parts);
|
||||
@@ -21811,6 +21942,14 @@ export class Lowerer {
|
||||
return type;
|
||||
}
|
||||
|
||||
/** IR-level `t | null` through the shared canonicalizer. Null when the
|
||||
* type cannot take the arm. A checked-dynamic dictionary read answers a
|
||||
* null cell whatever the index value type says, so the read's value type
|
||||
* keeps it beside the undefined arm. */
|
||||
withNullArmOf(t: IrType): IrType | null {
|
||||
return withNullArmCanonical(t, this.unions);
|
||||
}
|
||||
|
||||
/** The join of two IR arm types under the union-mapping rules
|
||||
* (mergePromiseArms), or null when they have none. The checker sometimes
|
||||
* types a conditional by ONE arm: a union of module namespace types
|
||||
@@ -22471,6 +22610,16 @@ export class Lowerer {
|
||||
* miss (process.env reads). "undefined" sorts last among all arm typeKeys,
|
||||
* so the sorted pair is always [t, undefined]. */
|
||||
withUndefinedArm(t: IrType): IrType {
|
||||
// Already admits undefined (its own arm or a union that carries one):
|
||||
// adding it again would intern a union with two undefined arms, which no
|
||||
// checked conversion accepts.
|
||||
if (t.kind === "undefinedT") return t;
|
||||
if (
|
||||
t.kind === "union" &&
|
||||
(this.unions.get(t.unionId)?.arms ?? []).some((a) => a.kind === "undefinedT")
|
||||
) {
|
||||
return t;
|
||||
}
|
||||
const arms = sortArms([t, UNDEFINED_T]);
|
||||
return { kind: "union", unionId: this.unions.intern(arms) };
|
||||
}
|
||||
@@ -26107,8 +26256,15 @@ export class Lowerer {
|
||||
}
|
||||
// Members that are global objects (`require("stream/web").ReadableStream
|
||||
// === globalThis.ReadableStream`) read in JavaScript sources as their
|
||||
// global spelling does.
|
||||
if (isJsSourceFile(ts.getSourceFileOfNode(expr))) {
|
||||
// global spelling does. The timer and base64 members answer the same
|
||||
// interned function values in TypeScript: the module member and the
|
||||
// global are one function in Node, so identity across the spellings has
|
||||
// to hold there too.
|
||||
if (
|
||||
isJsSourceFile(ts.getSourceFileOfNode(expr)) ||
|
||||
bi.module === "timers" ||
|
||||
(bi.module === "buffer" && (bi.member === "atob" || bi.member === "btoa"))
|
||||
) {
|
||||
const global = globalMemberValue(this, bi, expr, loc);
|
||||
if (global) return global;
|
||||
}
|
||||
@@ -26180,6 +26336,17 @@ export class Lowerer {
|
||||
lowerBuiltinCallableValue(bi: { module: string; member: string }, loc: SrcLoc): IrExpr | null {
|
||||
const assertion = assertFunctionValue(bi, loc);
|
||||
if (assertion) return assertion;
|
||||
// A module member that is the same function as a global (the timer
|
||||
// functions and the base64 helpers) answers the global's interned
|
||||
// value in TypeScript too: the named import, the module member and the
|
||||
// global spelling are one function in Node.
|
||||
if (
|
||||
bi.module === "timers" ||
|
||||
(bi.module === "buffer" && (bi.member === "atob" || bi.member === "btoa"))
|
||||
) {
|
||||
const global = jsGlobalValueByName(this, bi.member, loc);
|
||||
if (global) return global;
|
||||
}
|
||||
if (bi.module === "util" && bi.member === "types") return utilTypesModuleValue(this, loc);
|
||||
// util.inspect: the function custom inspect methods receive, one
|
||||
// identity per thread.
|
||||
|
||||
@@ -302,7 +302,7 @@ function defineNodeObject(lowerer: Lowerer, name: string, helper: string, node:
|
||||
// process.nextTick`, and a call through the stored object runs it);
|
||||
// the refusing function the spelled read answers otherwise.
|
||||
const real =
|
||||
name === "process" ? processFunctionMemberValue(lowerer, member, loc, true, true) : null;
|
||||
name === "process" ? processFunctionMemberValue(lowerer, member, loc, true) : null;
|
||||
descriptor = [
|
||||
field("value", dyn(real ?? memberFunctionFence(lowerer, display, member, kind, node, loc))),
|
||||
field("writable", dyn(boolLit(true, loc))),
|
||||
|
||||
@@ -8,33 +8,52 @@
|
||||
* storage. A top-level `var`/`let` the file assigns instead keeps its own
|
||||
* module global, checked-dynamic: the declaration still evaluates the
|
||||
* require (the dependency's run-once %init at its position) and stores the
|
||||
* module's value in that global, and reads and writes of the binding alias
|
||||
* the global. An ES import binding and a `const` require binding stay
|
||||
* immutable, exactly as Node makes them. */
|
||||
* module's value in that storage, and reads and writes of the binding alias
|
||||
* it. A `var` the file assigns inside a function (React's development
|
||||
* jsx-runtime does this in its IIFE) keeps the function's hoisted
|
||||
* checked-dynamic slot the same way. The stored value is the module's real
|
||||
* `module.exports` object, the one every require of it answers. An ES
|
||||
* import binding and a `const` require binding stay immutable, exactly as
|
||||
* Node makes them. */
|
||||
import * as ts from "../ts7/adapter.js";
|
||||
import { isJsSourceFile, requireSpecOf } from "../program.js";
|
||||
import type { Lowerer } from "./lowerer.js";
|
||||
|
||||
/** Top-level JavaScript `var`/`let` declarations initialized from a
|
||||
* `require()` call whose binding an assignment in the same file writes,
|
||||
* recorded for the queries below. */
|
||||
/** JavaScript `var`/`let` declarations initialized from a `require()` call
|
||||
* whose binding an assignment in the same file writes, recorded for the
|
||||
* queries below: the module's top level, and a function body's `var`. */
|
||||
export function collectRebindableRequireDecls(
|
||||
lowerer: Lowerer,
|
||||
sf: ts.SourceFile,
|
||||
): Set<ts.VariableDeclaration> {
|
||||
const found = new Set<ts.VariableDeclaration>();
|
||||
if (!isJsSourceFile(sf)) return found;
|
||||
const byName = new Map<string, ts.VariableDeclaration>();
|
||||
for (const stmt of sf.statements.nodes) {
|
||||
if (!ts.isVariableStatement(stmt)) continue;
|
||||
if ((stmt.declarationList.flags & ts.NodeFlags.Const) !== 0) continue;
|
||||
for (const decl of stmt.declarationList.declarations.nodes) {
|
||||
// Keyed by symbol, so a nested binding of the same name never stands in
|
||||
// for the outer one. The supported positions are the module's top level
|
||||
// (a module global) and a function body's `var` (the function-scoped
|
||||
// hoisted slot): React's development jsx-runtime reassigns the local its
|
||||
// IIFE declares from require("react"). A block-scoped `let` and a
|
||||
// declaration in a block at the module's top level keep the assignment's
|
||||
// existing named refusal.
|
||||
const bySymbol = new Map<ts.Symbol, ts.VariableDeclaration>();
|
||||
ts.walkPreorder(sf, (node) => {
|
||||
if (!ts.isVariableStatement(node)) return undefined;
|
||||
const flags = node.declarationList.flags;
|
||||
if ((flags & ts.NodeFlags.Const) !== 0) return undefined;
|
||||
if (
|
||||
!ts.isSourceFile(node.parent) &&
|
||||
(!insideFunctionBody(node) || (flags & ts.NodeFlags.Let) !== 0)
|
||||
)
|
||||
return undefined;
|
||||
for (const decl of node.declarationList.declarations.nodes) {
|
||||
if (!ts.isIdentifier(decl.name) || decl.initializer === undefined) continue;
|
||||
if (requireSpecOf(decl.initializer) === null) continue;
|
||||
byName.set(decl.name.text, decl);
|
||||
const symbol = lowerer.checker.getSymbolAtLocation(decl.name);
|
||||
if (symbol !== undefined) bySymbol.set(symbol, decl);
|
||||
}
|
||||
}
|
||||
if (byName.size === 0) return found;
|
||||
return undefined;
|
||||
});
|
||||
if (bySymbol.size === 0) return found;
|
||||
ts.walkPreorder(sf, (node) => {
|
||||
if (
|
||||
!ts.isBinaryExpression(node) ||
|
||||
@@ -42,16 +61,24 @@ export function collectRebindableRequireDecls(
|
||||
!ts.isIdentifier(node.left)
|
||||
)
|
||||
return undefined;
|
||||
const decl = byName.get(node.left.text);
|
||||
if (!decl || found.has(decl)) return undefined;
|
||||
const symbol = lowerer.checker.getSymbolAtLocation(node.left);
|
||||
if (symbol && symbol.declarations.includes(decl)) found.add(decl);
|
||||
const decl = symbol === undefined ? undefined : bySymbol.get(symbol);
|
||||
if (decl !== undefined) found.add(decl);
|
||||
return undefined;
|
||||
});
|
||||
for (const decl of found) lowerer.rebindableRequireDecls.add(decl);
|
||||
return found;
|
||||
}
|
||||
|
||||
/** Whether `node` sits inside a function body (an IIFE included). */
|
||||
function insideFunctionBody(node: ts.Node): boolean {
|
||||
for (let current: ts.Node | undefined = node; current !== undefined; current = current.parent) {
|
||||
if (ts.isSourceFile(current)) return false;
|
||||
if (ts.isFunctionLike(current)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Whether `decl` is a require binding the program assigns. */
|
||||
export function isRebindableRequireDecl(lowerer: Lowerer, decl: ts.VariableDeclaration): boolean {
|
||||
return lowerer.rebindableRequireDecls.has(decl);
|
||||
|
||||
@@ -862,9 +862,17 @@ export interface BuiltinModuleFn {
|
||||
/** The runtime entry point an untyped caller's adapter calls with every
|
||||
* argument as given, when it validates them itself (resolve's last-first
|
||||
* walk) or the value has no typed form (`only`: parse's record result,
|
||||
* format's untyped pathObject). `args` are constants passed after the
|
||||
* arguments (the win32 flag of an entry both path families share). */
|
||||
checked?: { fn: IrLibFn; args: readonly boolean[]; result?: IrType; only?: true };
|
||||
* format's untyped pathObject). `leadingArgs` are constants passed before
|
||||
* the arguments (a shared entry point's mode flag); `args` are constants
|
||||
* passed after them (the win32 flag of an entry both path families
|
||||
* share). */
|
||||
checked?: {
|
||||
fn: IrLibFn;
|
||||
leadingArgs?: readonly boolean[];
|
||||
args: readonly boolean[];
|
||||
result?: IrType;
|
||||
only?: true;
|
||||
};
|
||||
/** The function value's `name` when it is not the member's
|
||||
* (`process.cwd` is Node's `wrappedCwd`). */
|
||||
valueName?: string;
|
||||
@@ -1722,22 +1730,162 @@ function buildBuiltinModuleFns(): BuiltinModuleFnTable {
|
||||
fn: "crypto.randomBytes",
|
||||
params: [F64],
|
||||
result: BYTES_U8,
|
||||
valueParams: exactValueParams(F64),
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.randomBytesAnyCb",
|
||||
args: [],
|
||||
result: DYN,
|
||||
only: true,
|
||||
},
|
||||
valueLength: 2,
|
||||
},
|
||||
// The crypto utility surface is special-cased for overloads and
|
||||
// string/Buffer splits in lowerCryptoModuleCall. These rows carry the
|
||||
// canonical signatures for manifest projection and fallback dispatch.
|
||||
createHash: { fn: "crypto.hashNew", params: [STRING], result: CRYPTOHASH_T },
|
||||
createHmac: { fn: "crypto.hmacNewStr", params: [STRING, STRING], result: CRYPTOHMAC_T },
|
||||
createHash: {
|
||||
fn: "crypto.hashNew",
|
||||
params: [STRING],
|
||||
result: CRYPTOHASH_T,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.hashNewAny",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 2,
|
||||
},
|
||||
createHmac: {
|
||||
fn: "crypto.hmacNewStr",
|
||||
params: [STRING, STRING],
|
||||
result: CRYPTOHMAC_T,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.hmacNewAny",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 3,
|
||||
},
|
||||
// createMac is special-cased in lowerCryptoModuleCall (any-value
|
||||
// key and options); this row carries its canonical signature.
|
||||
createMac: { fn: "crypto.macNewDyn", params: [DYN, DYN, DYN], result: DYN },
|
||||
secureHeapUsed: { fn: "crypto.secureHeapUsed", params: [], result: DYN },
|
||||
hash: { fn: "crypto.hashDigestStr", params: [STRING, STRING, STRING], result: STRING },
|
||||
timingSafeEqual: { fn: "crypto.timingSafeEqual", params: [BYTES_U8, BYTES_U8], result: BOOL },
|
||||
randomFillSync: { fn: "crypto.randomFill", params: [BYTES_U8, F64, F64], result: BYTES_U8 },
|
||||
getRandomValues: { fn: "crypto.getRandomValues", params: [BYTES_U8], result: BYTES_U8 },
|
||||
randomInt: { fn: "crypto.randomInt", params: [F64, F64], result: F64 },
|
||||
createMac: {
|
||||
fn: "crypto.macNewDyn",
|
||||
params: [DYN, DYN, DYN],
|
||||
result: DYN,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.macNewDyn",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 3,
|
||||
},
|
||||
secureHeapUsed: {
|
||||
fn: "crypto.secureHeapUsed",
|
||||
params: [],
|
||||
result: DYN,
|
||||
valueParams: [],
|
||||
checked: {
|
||||
fn: "crypto.secureHeapUsed",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 0,
|
||||
},
|
||||
hash: {
|
||||
fn: "crypto.hashDigestStr",
|
||||
params: [STRING, STRING, STRING],
|
||||
result: STRING,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.hashOneshotAny",
|
||||
args: [],
|
||||
result: DYN,
|
||||
only: true,
|
||||
},
|
||||
valueLength: 3,
|
||||
},
|
||||
timingSafeEqual: {
|
||||
fn: "crypto.timingSafeEqual",
|
||||
params: [BYTES_U8, BYTES_U8],
|
||||
result: BOOL,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.timingSafeEqualDyn",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueName: "",
|
||||
valueLength: 0,
|
||||
},
|
||||
randomFillSync: {
|
||||
fn: "crypto.randomFill",
|
||||
params: [BYTES_U8, F64, F64],
|
||||
result: BYTES_U8,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.randomFillSyncDyn",
|
||||
args: [],
|
||||
result: DYN,
|
||||
only: true,
|
||||
},
|
||||
valueLength: 1,
|
||||
},
|
||||
getRandomValues: {
|
||||
fn: "crypto.getRandomValues",
|
||||
params: [BYTES_U8],
|
||||
result: BYTES_U8,
|
||||
valueParams: [{ mode: "required", type: DYN }],
|
||||
checked: {
|
||||
fn: "crypto.getRandomValuesDyn",
|
||||
args: [],
|
||||
result: DYN,
|
||||
only: true,
|
||||
},
|
||||
valueLength: 1,
|
||||
},
|
||||
randomInt: {
|
||||
fn: "crypto.randomInt",
|
||||
params: [F64, F64],
|
||||
result: F64,
|
||||
valueParams: [
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.randomIntAnyCb",
|
||||
args: [],
|
||||
result: DYN,
|
||||
only: true,
|
||||
},
|
||||
valueLength: 3,
|
||||
},
|
||||
randomFill: { fn: "crypto.randomFillCb", params: [], result: VOID },
|
||||
randomUUIDv7: {
|
||||
fn: "crypto.randomUUIDv7",
|
||||
@@ -1745,67 +1893,548 @@ function buildBuiltinModuleFns(): BuiltinModuleFnTable {
|
||||
result: STRING,
|
||||
valueParams: [{ mode: "optional", type: DYN, defaultValue: undefined }],
|
||||
},
|
||||
createSecretKey: { fn: "crypto.createSecretKey", params: [DYN, DYN], result: DYN },
|
||||
generateKeySync: { fn: "crypto.generateKeySync", params: [DYN, DYN], result: DYN },
|
||||
createSecretKey: {
|
||||
fn: "crypto.createSecretKey",
|
||||
params: [DYN, DYN],
|
||||
result: DYN,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.createSecretKey",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 2,
|
||||
},
|
||||
generateKeySync: {
|
||||
fn: "crypto.generateKeySync",
|
||||
params: [DYN, DYN],
|
||||
result: DYN,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.generateKeySync",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 2,
|
||||
},
|
||||
generateKey: { fn: "crypto.generateKeyCb", params: [], result: VOID },
|
||||
// Asymmetric keys and signatures (lowerPkiCall): checked-dynamic
|
||||
// arguments, results converted to the call site's type.
|
||||
createPrivateKey: { fn: "crypto.createPrivateKey", params: [DYN], result: DYN },
|
||||
createPublicKey: { fn: "crypto.createPublicKey", params: [DYN], result: DYN },
|
||||
createPrivateKey: {
|
||||
fn: "crypto.createPrivateKey",
|
||||
params: [DYN],
|
||||
result: DYN,
|
||||
valueParams: [{ mode: "required", type: DYN }],
|
||||
checked: {
|
||||
fn: "crypto.createPrivateKey",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 1,
|
||||
},
|
||||
createPublicKey: {
|
||||
fn: "crypto.createPublicKey",
|
||||
params: [DYN],
|
||||
result: DYN,
|
||||
valueParams: [{ mode: "required", type: DYN }],
|
||||
checked: {
|
||||
fn: "crypto.createPublicKey",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 1,
|
||||
},
|
||||
// Special-cased (lowerParsePKCS12): the parsed bundle's parts compose
|
||||
// the result record, whose X509Certificate members are records built
|
||||
// from the certificates' DER.
|
||||
parsePKCS12: { fn: "crypto.parsePKCS12", params: [], result: VOID },
|
||||
createSign: { fn: "crypto.createSign", params: [DYN, DYN], result: DYN },
|
||||
createVerify: { fn: "crypto.createVerify", params: [DYN, DYN], result: DYN },
|
||||
generateKeyPairSync: { fn: "crypto.generateKeyPairSync", params: [], result: DYN },
|
||||
generateKeyPair: { fn: "crypto.generateKeyPairCb", params: [], result: VOID },
|
||||
sign: { fn: "crypto.signOneshot", params: [], result: DYN },
|
||||
verify: { fn: "crypto.verifyOneshot", params: [], result: DYN },
|
||||
publicEncrypt: { fn: "crypto.publicEncrypt", params: [], result: DYN },
|
||||
privateDecrypt: { fn: "crypto.privateDecrypt", params: [], result: DYN },
|
||||
privateEncrypt: { fn: "crypto.privateEncrypt", params: [], result: DYN },
|
||||
publicDecrypt: { fn: "crypto.publicDecrypt", params: [], result: DYN },
|
||||
diffieHellman: { fn: "crypto.diffieHellman", params: [], result: DYN },
|
||||
encapsulate: { fn: "crypto.encapsulate", params: [], result: DYN },
|
||||
decapsulate: { fn: "crypto.decapsulate", params: [], result: DYN },
|
||||
createSign: {
|
||||
fn: "crypto.createSign",
|
||||
params: [DYN, DYN],
|
||||
result: DYN,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.createSign",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 2,
|
||||
},
|
||||
createVerify: {
|
||||
fn: "crypto.createVerify",
|
||||
params: [DYN, DYN],
|
||||
result: DYN,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.createVerify",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 2,
|
||||
},
|
||||
generateKeyPairSync: {
|
||||
fn: "crypto.generateKeyPairSync",
|
||||
params: [],
|
||||
result: DYN,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.generateKeyPairSync",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 2,
|
||||
},
|
||||
generateKeyPair: {
|
||||
fn: "crypto.generateKeyPairCb",
|
||||
params: [],
|
||||
result: VOID,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.generateKeyPairCb",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 3,
|
||||
},
|
||||
sign: {
|
||||
fn: "crypto.signOneshot",
|
||||
params: [],
|
||||
result: DYN,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.signOneshotMaybe",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueName: "signOneShot",
|
||||
valueLength: 4,
|
||||
},
|
||||
verify: {
|
||||
fn: "crypto.verifyOneshot",
|
||||
params: [],
|
||||
result: DYN,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.verifyOneshotMaybe",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueName: "verifyOneShot",
|
||||
valueLength: 5,
|
||||
},
|
||||
publicEncrypt: {
|
||||
fn: "crypto.publicEncrypt",
|
||||
params: [],
|
||||
result: DYN,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.publicEncrypt",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueName: "",
|
||||
valueLength: 2,
|
||||
},
|
||||
privateDecrypt: {
|
||||
fn: "crypto.privateDecrypt",
|
||||
params: [],
|
||||
result: DYN,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.privateDecrypt",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueName: "",
|
||||
valueLength: 2,
|
||||
},
|
||||
privateEncrypt: {
|
||||
fn: "crypto.privateEncrypt",
|
||||
params: [],
|
||||
result: DYN,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.privateEncrypt",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueName: "",
|
||||
valueLength: 2,
|
||||
},
|
||||
publicDecrypt: {
|
||||
fn: "crypto.publicDecrypt",
|
||||
params: [],
|
||||
result: DYN,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.publicDecrypt",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueName: "",
|
||||
valueLength: 2,
|
||||
},
|
||||
diffieHellman: {
|
||||
fn: "crypto.diffieHellman",
|
||||
params: [],
|
||||
result: DYN,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.diffieHellman",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 2,
|
||||
},
|
||||
encapsulate: {
|
||||
fn: "crypto.encapsulate",
|
||||
params: [],
|
||||
result: DYN,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.encapsulate",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 2,
|
||||
},
|
||||
decapsulate: {
|
||||
fn: "crypto.decapsulate",
|
||||
params: [],
|
||||
result: DYN,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.decapsulate",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 3,
|
||||
},
|
||||
pbkdf2Sync: {
|
||||
fn: "crypto.pbkdf2",
|
||||
params: [BYTES_U8, BYTES_U8, F64, F64, STRING],
|
||||
result: BYTES_U8,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.pbkdf2Any",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 5,
|
||||
},
|
||||
pbkdf2: {
|
||||
fn: "crypto.pbkdf2Cb",
|
||||
params: [],
|
||||
result: VOID,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.pbkdf2AnyCb",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 6,
|
||||
},
|
||||
pbkdf2: { fn: "crypto.pbkdf2Cb", params: [], result: VOID },
|
||||
hkdfSync: {
|
||||
fn: "crypto.hkdf",
|
||||
params: [STRING, BYTES_U8, BYTES_U8, BYTES_U8, F64],
|
||||
result: DYN,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.hkdfAny",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 5,
|
||||
},
|
||||
hkdf: {
|
||||
fn: "crypto.hkdfCb",
|
||||
params: [],
|
||||
result: VOID,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.hkdfAnyCb",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 6,
|
||||
},
|
||||
scryptSync: {
|
||||
fn: "crypto.scrypt",
|
||||
params: [BYTES_U8, BYTES_U8, F64, DYN],
|
||||
result: BYTES_U8,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.scryptAny",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 3,
|
||||
},
|
||||
scrypt: {
|
||||
fn: "crypto.scryptCb",
|
||||
params: [],
|
||||
result: VOID,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
{ mode: "required", type: DYN },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.scryptAnyCb",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 4,
|
||||
},
|
||||
hkdf: { fn: "crypto.hkdfCb", params: [], result: VOID },
|
||||
scryptSync: { fn: "crypto.scrypt", params: [BYTES_U8, BYTES_U8, F64, DYN], result: BYTES_U8 },
|
||||
scrypt: { fn: "crypto.scryptCb", params: [], result: VOID },
|
||||
// Checked-dynamic arguments; the result is a native Cipheriv or
|
||||
// Decipheriv handle (lowerCryptoModuleCall).
|
||||
createCipheriv: { fn: "crypto.cipherNew", params: [BOOL, DYN, DYN, DYN, DYN], result: DYN },
|
||||
createDecipheriv: { fn: "crypto.cipherNew", params: [BOOL, DYN, DYN, DYN, DYN], result: DYN },
|
||||
createCipheriv: {
|
||||
fn: "crypto.cipherNew",
|
||||
params: [BOOL, DYN, DYN, DYN, DYN],
|
||||
result: DYN,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.cipherNew",
|
||||
leadingArgs: [false],
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 4,
|
||||
},
|
||||
createDecipheriv: {
|
||||
fn: "crypto.cipherNew",
|
||||
params: [BOOL, DYN, DYN, DYN, DYN],
|
||||
result: DYN,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.cipherNew",
|
||||
leadingArgs: [true],
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 4,
|
||||
},
|
||||
// A checked-dynamic curve name; the result is a native ECDH handle
|
||||
// (lowerCreateEcdh).
|
||||
createECDH: { fn: "crypto.ecdhNew", params: [DYN], result: DYN },
|
||||
createECDH: {
|
||||
fn: "crypto.ecdhNew",
|
||||
params: [DYN],
|
||||
result: DYN,
|
||||
valueParams: [{ mode: "required", type: DYN }],
|
||||
checked: {
|
||||
fn: "crypto.ecdhNew",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 1,
|
||||
},
|
||||
// Checked-dynamic arguments; the result is a native DiffieHellman or
|
||||
// DiffieHellmanGroup handle (lowerCreateDiffieHellman and
|
||||
// lowerGetDiffieHellman).
|
||||
createDiffieHellman: { fn: "crypto.dhNew", params: [DYN, DYN, DYN, DYN], result: DYN },
|
||||
getDiffieHellman: { fn: "crypto.dhGroupNew", params: [DYN], result: DYN },
|
||||
createDiffieHellmanGroup: { fn: "crypto.dhGroupNew", params: [DYN], result: DYN },
|
||||
createDiffieHellman: {
|
||||
fn: "crypto.dhNew",
|
||||
params: [DYN, DYN, DYN, DYN],
|
||||
result: DYN,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.dhNew",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 4,
|
||||
},
|
||||
getDiffieHellman: {
|
||||
fn: "crypto.dhGroupNew",
|
||||
params: [DYN],
|
||||
result: DYN,
|
||||
valueParams: [{ mode: "required", type: DYN }],
|
||||
checked: {
|
||||
fn: "crypto.dhGroupNew",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueName: "createDiffieHellmanGroup",
|
||||
valueLength: 1,
|
||||
},
|
||||
createDiffieHellmanGroup: {
|
||||
fn: "crypto.dhGroupNew",
|
||||
params: [DYN],
|
||||
result: DYN,
|
||||
valueParams: [{ mode: "required", type: DYN }],
|
||||
checked: {
|
||||
fn: "crypto.dhGroupNew",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueName: "createDiffieHellmanGroup",
|
||||
valueLength: 1,
|
||||
},
|
||||
// Prime checks and generation (lowerPrimeCall): checked-dynamic
|
||||
// arguments, results converted to the call site's type.
|
||||
checkPrimeSync: { fn: "crypto.checkPrimeSync", params: [], result: DYN },
|
||||
checkPrimeSync: {
|
||||
fn: "crypto.checkPrimeSync",
|
||||
params: [],
|
||||
result: DYN,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.checkPrimeSync",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 1,
|
||||
},
|
||||
// Checked-dynamic arguments, the result converted to the call site's
|
||||
// type (lowerPrimeCall).
|
||||
getCipherInfo: { fn: "crypto.getCipherInfo", params: [], result: DYN },
|
||||
getCipherInfo: {
|
||||
fn: "crypto.getCipherInfo",
|
||||
params: [],
|
||||
result: DYN,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.getCipherInfo",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 2,
|
||||
},
|
||||
// Node's message and error for every engine but "dynamic".
|
||||
setEngine: { fn: "crypto.setEngine", params: [], result: VOID },
|
||||
setEngine: {
|
||||
fn: "crypto.setEngine",
|
||||
params: [],
|
||||
result: VOID,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.setEngine",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 2,
|
||||
},
|
||||
checkPrime: { fn: "crypto.checkPrimeCb", params: [], result: VOID },
|
||||
generatePrimeSync: { fn: "crypto.generatePrimeSync", params: [], result: DYN },
|
||||
generatePrimeSync: {
|
||||
fn: "crypto.generatePrimeSync",
|
||||
params: [],
|
||||
result: DYN,
|
||||
valueParams: [
|
||||
{ mode: "required", type: DYN },
|
||||
{ mode: "optional", type: DYN, defaultValue: undefined },
|
||||
],
|
||||
checked: {
|
||||
fn: "crypto.generatePrimeSync",
|
||||
args: [],
|
||||
only: true,
|
||||
},
|
||||
valueLength: 1,
|
||||
},
|
||||
generatePrime: { fn: "crypto.generatePrimeCb", params: [], result: VOID },
|
||||
},
|
||||
zlib: {
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
/* A void-returning thunk over a function value.
|
||||
*
|
||||
* JavaScript ignores a listener's return value: `stream.on("data", async
|
||||
* (chunk) => …)` registers like the synchronous form, and the promise the
|
||||
* listener answers is dropped (a rejection surfaces as the program's own
|
||||
* unhandledRejection, exactly Node). A runtime callback slot typed as a
|
||||
* void function cannot hold a function whose signature returns something,
|
||||
* so the frontend wraps the value in a small lifted function that calls it
|
||||
* and discards the result. */
|
||||
import { VOID, type IrExpr, type IrFunction, type IrType, type SrcLoc } from "../../ir/ir.js";
|
||||
import { keyedHelperName } from "./stable-names.js";
|
||||
import type { Lowerer } from "./lowerer.js";
|
||||
|
||||
/** `value` as a void-returning listener: the value itself when it already
|
||||
* answers void, else a thunk (a lifted function capturing it, calling it
|
||||
* with the same arguments and discarding the result). The returned
|
||||
* expression owns its value. Null when `value` is not a function value. */
|
||||
export function voidThunkValue(lowerer: Lowerer, value: IrExpr, loc: SrcLoc): IrExpr | null {
|
||||
if (value.type.kind !== "func") return null;
|
||||
const fnType = value.type;
|
||||
if (fnType.ret.kind === "void") return value;
|
||||
// The thunk captures the listener: captures are boxed locals of the
|
||||
// creating function, read as values by the lifted body.
|
||||
const slot = lowerer.declareHiddenLocal("%thunk.target", fnType, true);
|
||||
slot.boxed = true;
|
||||
const fnName = keyedHelperName(
|
||||
lowerer,
|
||||
"%void.thunk",
|
||||
`${lowerer.fmt(fnType)}@${loc.file}:${loc.start}`,
|
||||
);
|
||||
const hasChunk = fnType.params.length > 0;
|
||||
const chunkType: IrType = hasChunk ? fnType.params[0]! : { kind: "dyn" };
|
||||
const chunkParam = { localId: "%thunk.chunk", name: "%thunk.chunk", type: chunkType };
|
||||
const captureParam = { localId: slot.id, name: slot.id, type: fnType };
|
||||
const call: IrExpr = {
|
||||
kind: "callValue",
|
||||
callee: { kind: "varRef", localId: slot.id, type: fnType, loc },
|
||||
args: hasChunk ? [{ kind: "varRef", localId: chunkParam.localId, type: chunkType, loc }] : [],
|
||||
type: fnType.ret,
|
||||
loc,
|
||||
};
|
||||
const lifted: IrFunction = {
|
||||
name: fnName,
|
||||
sourceName: "<void thunk>",
|
||||
params: hasChunk ? [chunkParam] : [],
|
||||
returnType: VOID,
|
||||
locals: [
|
||||
{ ...captureParam, id: slot.id, boxed: true, mutable: true },
|
||||
...(hasChunk
|
||||
? [{ id: chunkParam.localId, name: chunkParam.name, type: chunkType, mutable: true }]
|
||||
: []),
|
||||
],
|
||||
captures: [captureParam],
|
||||
body: [
|
||||
{ kind: "exprStmt", expr: call, loc },
|
||||
{ kind: "return", value: null, loc },
|
||||
],
|
||||
loc,
|
||||
};
|
||||
// A generic instantiation lowers the same site again with the same key: a
|
||||
// listener whose signature does not mention the type parameter shares the
|
||||
// helper name, and its body is the same thunk. Register one function per
|
||||
// name, asked through the lifted-function index (not a scan of the list).
|
||||
if (lowerer.liftedFnNamed(fnName) === undefined) lowerer.liftedFns.push(lifted);
|
||||
const thunkType: IrType = { kind: "func", params: hasChunk ? [chunkType] : [], ret: VOID };
|
||||
return {
|
||||
kind: "seqExpr",
|
||||
stmts: [{ kind: "varDecl", localId: slot.id, init: value, loc }],
|
||||
result: { kind: "closure", fnName, captures: [slot.id], type: thunkType, loc },
|
||||
type: thunkType,
|
||||
loc,
|
||||
};
|
||||
}
|
||||
@@ -421,7 +421,7 @@ export function viewObservedRecordCopies(lowerer: Lowerer, functions: IrFunction
|
||||
// pairs are settled together.
|
||||
const observed = survivingPairs(lowerer, functions, candidates);
|
||||
if (observed.size === 0) return 0;
|
||||
const views = new Map<IrExpr & { kind: "call" }, IrType>();
|
||||
const views = new Map<IrExpr, IrType>();
|
||||
for (const site of sites) {
|
||||
if (site.call === undefined || !site.aliasable) continue;
|
||||
if (!observed.has(pairOf(site))) continue;
|
||||
@@ -434,10 +434,17 @@ export function viewObservedRecordCopies(lowerer: Lowerer, functions: IrFunction
|
||||
fn.body = transformStmtList(fn.body, {
|
||||
stmt: (stmt) => stmt,
|
||||
expr: (expr) => {
|
||||
const target = views.get(expr as IrExpr & { kind: "call" });
|
||||
if (target === undefined) return expr;
|
||||
// The map holds the copy-helper calls this pass rewrites and is
|
||||
// probed with every expression of the program: the probe is an
|
||||
// identity lookup, not a claim that the expression is a call. It
|
||||
// reads through the expression's own union type and tests the
|
||||
// discriminant; an asserted subtype here would be a checked
|
||||
// conversion in the native compiler, which throws for the other arms
|
||||
// the probe visits.
|
||||
const target = views.get(expr);
|
||||
if (target === undefined || expr.kind !== "call") return expr;
|
||||
rewritten++;
|
||||
const call = expr as IrExpr & { kind: "call" };
|
||||
const call = expr;
|
||||
return {
|
||||
kind: "dynCheck",
|
||||
value: { kind: "dynFrom", value: call.args[0]!, liveRef: true, type: DYN, loc: call.loc },
|
||||
|
||||
@@ -210,8 +210,10 @@ function getterReturnOf(fn: ts.Node): ts.Expression | null {
|
||||
|
||||
/** The `__export(IDENT, { name: () => value, ... })` call's parts, or null.
|
||||
* Every property must be a `name: <function>` assignment (identifier or
|
||||
* string-literal name) — anything else is not the esbuild table. */
|
||||
function exportCallOf(
|
||||
* string-literal name) — anything else is not the esbuild table. Shared
|
||||
* with the program-level getter-table recognizer (cjs-getter-table.ts),
|
||||
* which needs the same shape without the rewrite host. */
|
||||
export function exportCallOf(
|
||||
call: ts.CallExpression,
|
||||
): { target: string; entries: [string, ts.Expression | null][] } | null {
|
||||
if (calleeNameOf(call) !== "__export") return null;
|
||||
|
||||
@@ -1450,6 +1450,7 @@ function loadFrontend(
|
||||
dependencyJs: l.dependencyJs,
|
||||
parameterPropertiesFirst: l.parameterPropertiesFirst,
|
||||
legacyDecoratorFiles: l.typeWorld?.legacyDecoratorFiles,
|
||||
decoratorMetadataFiles: l.typeWorld?.decoratorMetadataFiles,
|
||||
externalTypes: l.externalTypes,
|
||||
externalTypeSpecifiersByFile: l.externalTypeSpecifiersByFile,
|
||||
});
|
||||
|
||||
@@ -746,9 +746,11 @@ export interface TypeWorldDifferences {
|
||||
projectSources: ReadonlySet<string> | null;
|
||||
/** Every file whose tsconfig sets `experimentalDecorators`: its classes
|
||||
* and their decorators take the legacy calling convention, evaluation
|
||||
* order and descriptor rules (lowering reads the set through LowerOptions).
|
||||
* A file compiled with `emitDecoratorMetadata` is still refused (SC0016). */
|
||||
* order and descriptor rules (lowering reads the set through LowerOptions). */
|
||||
legacyDecoratorFiles: ReadonlySet<string>;
|
||||
/** The files whose tsconfig also sets `emitDecoratorMetadata`: their
|
||||
* decorated declarations carry the design-type metadata decorators. */
|
||||
decoratorMetadataFiles: ReadonlySet<string>;
|
||||
/** The project's `module` setting, or null. */
|
||||
projectModule: string | null;
|
||||
}
|
||||
@@ -1600,8 +1602,6 @@ function entryPackageProgramRoots7(
|
||||
* programs whose sources name the global (programNamesTemporal7). */
|
||||
const TEMPORAL_LIB = "lib.esnext.temporal.d.ts";
|
||||
|
||||
const DECORATORS: ReadonlySet<ts.SyntaxKind> = new Set([ts.SyntaxKind.Decorator]);
|
||||
|
||||
/** True when a program source (user code or compiled npm JavaScript)
|
||||
* contains the temporal global's name as a whole word. A cheap syntactic
|
||||
* scan of the implementation files root discovery already materialized; a
|
||||
@@ -2437,8 +2437,7 @@ function loadProgram7(
|
||||
// with its own support.
|
||||
const parameterPropertiesFirst = new Set<string>();
|
||||
const legacyDecoratorFiles = new Set<string>();
|
||||
let metadataDecorators = 0;
|
||||
let firstMetadataDecorator: ts.Node | null = null;
|
||||
const decoratorMetadataFiles = new Set<string>();
|
||||
for (const sf of program.getImplementationSourceFiles()) {
|
||||
if (sf.isDeclarationFile || !/\.(?:[mc]?ts|tsx)$/.test(sf.fileName)) continue;
|
||||
const dialect = dialectOf(sf.fileName);
|
||||
@@ -2449,31 +2448,7 @@ function loadProgram7(
|
||||
// the lowering's class-statement order and calling convention follow
|
||||
// the file's dialect, and only files with the setting have one.
|
||||
legacyDecoratorFiles.add(sf.fileName);
|
||||
if (dialect.legacyDecorators !== "all") continue;
|
||||
ts.walkPreorder(
|
||||
sf,
|
||||
(node) => {
|
||||
metadataDecorators++;
|
||||
firstMetadataDecorator ??= node;
|
||||
},
|
||||
DECORATORS,
|
||||
);
|
||||
}
|
||||
if (firstMetadataDecorator !== null) {
|
||||
const at: ts.Node = firstMetadataDecorator;
|
||||
config.diags.push(
|
||||
unfollowedSettingDiag(
|
||||
'"emitDecoratorMetadata"',
|
||||
'this project sets "emitDecoratorMetadata", and scriptc does not emit the design-type metadata it asks for yet',
|
||||
{
|
||||
file: ts.getSourceFileOfNode(at).fileName,
|
||||
start: ts.tokenStartOfNode(at),
|
||||
end: at.end,
|
||||
},
|
||||
metadataDecorators,
|
||||
'remove "emitDecoratorMetadata" from the tsconfig until metadata support lands, or drop the decorators it covers',
|
||||
),
|
||||
);
|
||||
if (dialect.legacyDecorators === "all") decoratorMetadataFiles.add(sf.fileName);
|
||||
}
|
||||
const entry = program.getSourceFile(entryPath);
|
||||
if (!entry) throw new Error(`could not load ${entryPath}`);
|
||||
@@ -2517,6 +2492,7 @@ function loadProgram7(
|
||||
projectCheckJs: config.checkJs ?? false,
|
||||
projectSources,
|
||||
legacyDecoratorFiles,
|
||||
decoratorMetadataFiles,
|
||||
projectModule: config.module ?? null,
|
||||
},
|
||||
externalTypes,
|
||||
@@ -4552,6 +4528,19 @@ function voidCallResultReadDiags7(
|
||||
if (ts.isExpressionStatement(parent) || ts.isVoidExpression(parent)) return true;
|
||||
if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === ts.SyntaxKind.CommaToken)
|
||||
return parent.left === node || valueDropped(parent);
|
||||
// `a && b`, `a || b` and `a ?? b` answer their right operand's value when
|
||||
// they evaluate it, so a right operand whose whole expression is dropped
|
||||
// is dropped too. The left operand's value is read as the condition.
|
||||
if (ts.isBinaryExpression(parent)) {
|
||||
const kind = parent.operatorToken.kind;
|
||||
if (
|
||||
parent.right === node &&
|
||||
(kind === ts.SyntaxKind.AmpersandAmpersandToken ||
|
||||
kind === ts.SyntaxKind.BarBarToken ||
|
||||
kind === ts.SyntaxKind.QuestionQuestionToken)
|
||||
)
|
||||
return valueDropped(parent);
|
||||
}
|
||||
if (
|
||||
ts.isConditionalExpression(parent) &&
|
||||
(parent.whenTrue === node || parent.whenFalse === node)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Ts7Wire, type Ts7WireIo } from "./rpc-wire.js";
|
||||
import { processHasExited } from "./process-exit.js";
|
||||
import { TS7_FILE_SYSTEM_CALLBACKS } from "./rpc-filesystem.js";
|
||||
import { CHECKER_SERVER_IDLE_EXIT, CHECKER_SERVER_MEMORY } from "./checker-server.js";
|
||||
import { useNativeJsonValueEnd } from "./semantic-json.js";
|
||||
@@ -65,6 +66,11 @@ export class NativeTs7Process implements Ts7WireIo {
|
||||
private handle: number;
|
||||
readonly pid: number;
|
||||
|
||||
/** Whether the server has exited: the compiled process never reaps the
|
||||
* server while the transport is open, so the probe reads its state rather
|
||||
* than signalling it (process-exit.ts). */
|
||||
readonly serverExited = (): boolean => processHasExited(this.pid);
|
||||
|
||||
/** With `handle`, a connection to a shared checker server (attachNativeTs7Process). With
|
||||
* `librariesFromDisk`, the server reads its default library files from the disk
|
||||
* (checkerReadsLibrariesFromDisk). */
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { expect, test } from "vitest";
|
||||
import { processHasExited } from "./process-exit.js";
|
||||
|
||||
test("a running process has not exited", () => {
|
||||
expect(processHasExited(process.pid)).toBe(false);
|
||||
});
|
||||
|
||||
test("a process that finished has exited, reaped or not", () => {
|
||||
const child = spawnSync("sh", ["-c", "exit 0"]);
|
||||
expect(child.pid).toBeGreaterThan(0);
|
||||
// The child is gone and reaped: no entry to read, or none to signal.
|
||||
expect(processHasExited(child.pid!)).toBe(true);
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
/* Whether a TypeScript server process has exited.
|
||||
*
|
||||
* The protocol's end-of-stream error asks this once, so a crashed helper is
|
||||
* named instead of reading as framing damage. A completed process its parent
|
||||
* has not reaped keeps its pid as a zombie, and a signal-0 probe still reports
|
||||
* it as present, so the probe reads the process state where the host exposes
|
||||
* one: Linux's /proc, `ps` elsewhere POSIX. Windows has no zombies, so signal 0
|
||||
* answers exactly there. A probe that cannot run answers "exited" only when
|
||||
* the process is provably gone; an inconclusive probe costs the hint, never a
|
||||
* wrong claim. */
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
export function processHasExited(pid: number): boolean {
|
||||
if (process.platform === "win32") {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return false;
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (process.platform === "linux") {
|
||||
try {
|
||||
const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
|
||||
// After the parenthesized command name, the state is the first field.
|
||||
const state = stat.slice(stat.lastIndexOf(")") + 2, stat.lastIndexOf(")") + 3);
|
||||
return state === "Z" || state === "X";
|
||||
} catch {
|
||||
// No such process: the probe found no entry to read.
|
||||
return true;
|
||||
}
|
||||
}
|
||||
const result = spawnSync("ps", ["-o", "state=", "-p", String(pid)], {
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
});
|
||||
if (result.error !== undefined || result.stdout === null) return false;
|
||||
// `ps` exits non-zero when it found no such process; a zombie's state
|
||||
// starts with Z.
|
||||
if (result.status !== 0) return true;
|
||||
const state = result.stdout.trim();
|
||||
return state === "" || state.startsWith("Z");
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import { expect, test } from "vitest";
|
||||
import { Ts7FifoIo } from "./rpc-process.js";
|
||||
import { Ts7Wire } from "./rpc-wire.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const posix = process.platform !== "win32";
|
||||
@@ -33,6 +34,25 @@ test.skipIf(!posix)("a FIFO server echoes, and exits when its transport closes",
|
||||
expect(alive(io.pid)).toBe(false);
|
||||
});
|
||||
|
||||
test.skipIf(!posix)("an end-of-stream error names a server that crashed", async () => {
|
||||
const io = new Ts7FifoIo("/bin/cat", []);
|
||||
try {
|
||||
process.kill(io.pid, "SIGKILL");
|
||||
// The supervisor that parents the server keeps it unreaped, so wait for
|
||||
// the state probe to see it rather than for a signal-0 answer.
|
||||
const deadline = Date.now() + 5000;
|
||||
while (!io.serverExited() && Date.now() < deadline)
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 20));
|
||||
expect(io.serverExited()).toBe(true);
|
||||
const wire = new Ts7Wire(io);
|
||||
expect(() => wire.read()).toThrow(
|
||||
`unexpected end of stream: the TypeScript server process (pid ${io.pid}) has exited`,
|
||||
);
|
||||
} finally {
|
||||
io.close();
|
||||
}
|
||||
});
|
||||
|
||||
test.skipIf(!posix)("a missing FIFO server fails at construction and tracks nothing", () => {
|
||||
const before = process.listenerCount("exit");
|
||||
expect(() => new Ts7FifoIo("/nonexistent/scriptc-ts7-server", [])).toThrow(
|
||||
|
||||
@@ -4,6 +4,7 @@ import { closeSync, constants, mkdtempSync, openSync, readSync, rmSync, writeSyn
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { Ts7Wire, type Ts7WireIo } from "./rpc-wire.js";
|
||||
import { processHasExited } from "./process-exit.js";
|
||||
import { ensureExecutable } from "../../executable-mode.js";
|
||||
|
||||
// Node's public spawn API does not expose synchronous pipe descriptors, so
|
||||
@@ -65,6 +66,13 @@ class Ts7NamedPipeIo implements Ts7WireIo {
|
||||
return this.child.pid;
|
||||
}
|
||||
|
||||
/** The server is this process's child; Windows has no zombies, so a
|
||||
* signal-0 probe answers exactly (see process-exit.ts). */
|
||||
readonly serverExited = (): boolean => {
|
||||
const pid = this.pid;
|
||||
return pid !== undefined && processHasExited(pid);
|
||||
};
|
||||
|
||||
constructor(executable: string, args: string[]) {
|
||||
const pipe = `\\\\.\\pipe\\scriptc-ts7-${process.pid}-${randomUUID()}`;
|
||||
this.child = spawn(executable, [...args, "--pipe", pipe], {
|
||||
@@ -242,6 +250,11 @@ export class Ts7FifoIo implements Ts7WireIo {
|
||||
/** The server's process ID, for tests: this process never signals it. */
|
||||
readonly pid: number;
|
||||
|
||||
/** Whether the server has exited. The supervisor that parents it keeps it
|
||||
* unreaped while this transport is open, so the probe reads the process
|
||||
* state rather than signalling it (process-exit.ts). */
|
||||
readonly serverExited = (): boolean => processHasExited(this.pid);
|
||||
|
||||
constructor(executable: string, args: string[]) {
|
||||
const directory = mkdtempSync(join(tmpdir(), "scriptc-ts7-"));
|
||||
const input = join(directory, "in");
|
||||
|
||||
@@ -57,6 +57,59 @@ describe("TypeScript MessagePack wire framing", () => {
|
||||
expect(io.closes()).toBe(1);
|
||||
});
|
||||
|
||||
test("names the server process when the transport reports its exit", () => {
|
||||
const io = memory();
|
||||
const wire = new Ts7Wire({ ...io.io, pid: 4242, serverExited: () => true });
|
||||
expect(() => wire.read()).toThrow(
|
||||
"unexpected end of stream: the TypeScript server process (pid 4242) has exited",
|
||||
);
|
||||
});
|
||||
|
||||
test("keeps the plain message when the server was alive or the probe failed", () => {
|
||||
const probes = [
|
||||
() => false,
|
||||
() => {
|
||||
throw new Error("no process table");
|
||||
},
|
||||
];
|
||||
for (const serverExited of probes) {
|
||||
const io = memory();
|
||||
const wire = new Ts7Wire({ ...io.io, pid: 4242, serverExited });
|
||||
expect(() => wire.read()).toThrow(/unexpected end of stream$/);
|
||||
}
|
||||
});
|
||||
|
||||
test("waits briefly for a closed channel's server exit to become observable", () => {
|
||||
const io = memory();
|
||||
let probes = 0;
|
||||
const wire = new Ts7Wire({
|
||||
...io.io,
|
||||
pid: 4242,
|
||||
// The pipe closed a moment before the process was reaped.
|
||||
serverExited: () => ++probes > 2,
|
||||
});
|
||||
const start = performance.now();
|
||||
expect(() => wire.read()).toThrow(
|
||||
"unexpected end of stream: the TypeScript server process (pid 4242) has exited",
|
||||
);
|
||||
expect(probes).toBeGreaterThan(2);
|
||||
expect(performance.now() - start).toBeGreaterThanOrEqual(15);
|
||||
});
|
||||
|
||||
test("a server that never exits keeps the plain message, and the wait is bounded", () => {
|
||||
const io = memory();
|
||||
const wire = new Ts7Wire({ ...io.io, pid: 4242, serverExited: () => false });
|
||||
const start = performance.now();
|
||||
expect(() => wire.read()).toThrow(/unexpected end of stream$/);
|
||||
expect(performance.now() - start).toBeLessThan(1_000);
|
||||
});
|
||||
|
||||
test("does not name a process the transport cannot identify", () => {
|
||||
const io = memory();
|
||||
const wire = new Ts7Wire({ ...io.io, serverExited: () => true });
|
||||
expect(() => wire.read()).toThrow(/unexpected end of stream$/);
|
||||
});
|
||||
|
||||
test("coalesces small frames and keeps large payloads on the direct path", () => {
|
||||
const channel = memory();
|
||||
const transfer = channel.io.write;
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
/** The pinned TypeScript 7 synchronous API uses MessagePack triples:
|
||||
* [message kind, binary method name, binary payload]. Keep framing separate
|
||||
* from process creation so the same client runs in Node and native scriptc. */
|
||||
/** A closing channel can race the server's teardown: the end-of-stream error
|
||||
* asks the transport again for a moment, bounded well under a quarter second,
|
||||
* so a crashed helper is still named without stalling on a live one. */
|
||||
const SERVER_EXIT_RETRIES = 20;
|
||||
const SERVER_EXIT_RETRY_MS = 10;
|
||||
const serverExitWait = new Int32Array(new SharedArrayBuffer(4));
|
||||
|
||||
export const TS7_REQUEST = 1;
|
||||
export const TS7_CALLBACK_RESPONSE = 2;
|
||||
export const TS7_CALLBACK_ERROR = 3;
|
||||
@@ -21,6 +28,10 @@ export interface Ts7WireIo {
|
||||
* that process's resident memory to decide whether to keep the server for
|
||||
* the next load (services.ts). */
|
||||
readonly pid?: number | undefined;
|
||||
/** Whether the server process has exited, where the transport can tell.
|
||||
* A read that meets end of stream asks once for the error message; a
|
||||
* transport that cannot tell leaves it out. */
|
||||
readonly serverExited?: (() => boolean) | undefined;
|
||||
read: (buffer: Uint8Array, offset: number, length: number) => number;
|
||||
write: (buffer: Uint8Array, offset: number, length: number) => number;
|
||||
close: () => void;
|
||||
@@ -119,13 +130,42 @@ export class Ts7Wire {
|
||||
throw new Ts7ProtocolError(message);
|
||||
}
|
||||
|
||||
/** Whether the transport's server has exited, asked again a few times for a
|
||||
* channel that closed before the process's teardown became observable: the
|
||||
* wait is bounded, so a live server whose channel broke cannot stall the
|
||||
* error. */
|
||||
private serverExited(): boolean {
|
||||
const probe = this.io.serverExited;
|
||||
if (probe === undefined) return false;
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
try {
|
||||
if (probe()) return true;
|
||||
} catch {
|
||||
// The probe cannot mask the end of stream it describes.
|
||||
return false;
|
||||
}
|
||||
if (attempt >= SERVER_EXIT_RETRIES) return false;
|
||||
Atomics.wait(serverExitWait, 0, 0, SERVER_EXIT_RETRY_MS);
|
||||
}
|
||||
}
|
||||
|
||||
/** The end-of-stream message. A transport that can tell its server is gone
|
||||
* names the process, so a crashed helper does not read as framing damage. */
|
||||
private endOfStream(): string {
|
||||
const message = "unexpected end of stream";
|
||||
if (this.io.serverExited === undefined) return message;
|
||||
const pid = this.io.pid;
|
||||
if (pid === undefined || !this.serverExited()) return message;
|
||||
return `${message}: the TypeScript server process (pid ${pid}) has exited`;
|
||||
}
|
||||
|
||||
private readByte(): number {
|
||||
if (this.inputOffset === this.inputLength) {
|
||||
const count = this.io.read(this.input, 0, this.input.length);
|
||||
if (!Number.isSafeInteger(count) || count < 0 || count > this.input.length) {
|
||||
this.fail("invalid read count");
|
||||
}
|
||||
if (count === 0) this.fail("unexpected end of stream");
|
||||
if (count === 0) this.fail(this.endOfStream());
|
||||
this.inputOffset = 0;
|
||||
this.inputLength = count;
|
||||
}
|
||||
@@ -172,7 +212,7 @@ export class Ts7Wire {
|
||||
const count = this.io.read(this.input, 0, take);
|
||||
if (!Number.isSafeInteger(count) || count < 0 || count > take)
|
||||
this.fail("invalid read count");
|
||||
if (count === 0) this.fail("unexpected end of stream");
|
||||
if (count === 0) this.fail(this.endOfStream());
|
||||
offset += count;
|
||||
}
|
||||
}
|
||||
@@ -191,7 +231,7 @@ export class Ts7Wire {
|
||||
const count = this.io.read(result, offset, length - offset);
|
||||
if (!Number.isSafeInteger(count) || count < 0 || count > length - offset)
|
||||
this.fail("invalid read count");
|
||||
if (count === 0) this.fail("unexpected end of stream");
|
||||
if (count === 0) this.fail(this.endOfStream());
|
||||
offset += count;
|
||||
} else {
|
||||
result[offset++] = this.readByte();
|
||||
|
||||
@@ -10817,6 +10817,10 @@ export function withUndefinedArm(t: IrType, unions: UnionRegistry): IrType | nul
|
||||
return withUnitArm(t, "undefinedT", unions);
|
||||
}
|
||||
|
||||
export function withNullArm(t: IrType, unions: UnionRegistry): IrType | null {
|
||||
return withUnitArm(t, "nullT", unions);
|
||||
}
|
||||
|
||||
/** A record property declared `?:` whose mapped type is the checked-dynamic
|
||||
* slot. Only such a field's shape carries an ABSENT state of its own (the
|
||||
* absent marker); every other optional property maps to an undefined-armed
|
||||
|
||||
@@ -197,7 +197,7 @@ import {
|
||||
import { type IrModule, type SrcLoc } from "./ir/ir.js";
|
||||
import { jsObjectModelFact, moduleRuntimeFeatures } from "./ir/runtime-features.js";
|
||||
import { serializeModuleParts } from "./ir/serialize.js";
|
||||
import { readTextParts, type TextPart, writeTextParts } from "./text-parts.js";
|
||||
import { isFileTextPart, readTextParts, type TextPart, writeTextParts } from "./text-parts.js";
|
||||
import { validateModule } from "./ir/validate.js";
|
||||
import { compilerOwnedFileRoots } from "./frontend/dts-paths.js";
|
||||
import { loadProgramWithServices } from "./frontend/program-node.js";
|
||||
@@ -3143,7 +3143,11 @@ async function compileLibraryTracked(
|
||||
output_bytes:
|
||||
typeof ll === "string"
|
||||
? Buffer.byteLength(ll)
|
||||
: ll.reduce((bytes, part) => bytes + Buffer.byteLength(part), 0),
|
||||
: ll.reduce(
|
||||
(bytes, part) =>
|
||||
bytes + (isFileTextPart(part) ? part.length : Buffer.byteLength(part)),
|
||||
0,
|
||||
),
|
||||
});
|
||||
await writeTextParts(llvmPath, ll);
|
||||
timing("llvm-write");
|
||||
|
||||
@@ -878,6 +878,7 @@ const MAY_THROW_LIB_FNS_PART_3: readonly IrLibFn[] = [
|
||||
"process.emitWarning",
|
||||
// A listener the emit reaches may throw; the exception is the call's.
|
||||
"process.emit",
|
||||
"process.emitSignal",
|
||||
"process.emitError",
|
||||
// cpuUsage(prev)'s field validation: negative/non-finite prev fields
|
||||
// throw Node's ERR_INVALID_ARG_VALUE RangeError, catchably.
|
||||
|
||||
@@ -155,6 +155,10 @@ export const fspSignatures = defineLibFnSignatures({
|
||||
},
|
||||
"fsp.stat": { argTypes: [STRING], result: { kind: "promise", inner: STATS_T } },
|
||||
"fsp.realpath": { argTypes: [STRING], result: { kind: "promise", inner: STRING } },
|
||||
/** `fs.promises.realpath(path, options)`: the synchronous option ladder
|
||||
* behind a settled promise. A getter's throw becomes the promise's
|
||||
* rejection, as Node's async entry point rejects rather than throws. */
|
||||
"fsp.realpathDyn": { argTypes: [DYN, DYN], result: { kind: "promise", inner: DYN } },
|
||||
"fsp.lstat": { argTypes: [STRING], result: { kind: "promise", inner: STATS_T } },
|
||||
/** fs.promises.stat/lstat(path, options): bigint and throwIfNoEntry are
|
||||
* read at run time by the ladder the synchronous forms use; the call's
|
||||
|
||||
@@ -383,6 +383,10 @@ export const processSignatures = defineLibFnSignatures({
|
||||
* event name and its argument vector arrive as checked values; the
|
||||
* result is whether any listener existed. */
|
||||
"process.emit": { argTypes: [DYN, DYN], result: BOOL },
|
||||
/** process.emit('SIG…'): dispatch the signal's registered listeners
|
||||
* synchronously, as Node's EventEmitter emit does, and answer whether any
|
||||
* existed. */
|
||||
"process.emitSignal": { argTypes: [STRING], result: BOOL },
|
||||
/** process.emit('error', ...): no listener can be registered for it, so
|
||||
* the runtime throws Node's unhandled-error contract. */
|
||||
"process.emitError": { argTypes: [DYN], result: VOID },
|
||||
|
||||
@@ -132,6 +132,7 @@ const DYN_ASYNC_LIB_FNS: ReadonlySet<IrLibFn> = new Set([
|
||||
// unit's deferred warning queue.
|
||||
"process.finalization",
|
||||
"process.emit",
|
||||
"process.emitSignal",
|
||||
"process.emitError",
|
||||
"process.emitWarning",
|
||||
"process.emitWarningText",
|
||||
@@ -1002,6 +1003,7 @@ const PROCESS_EVENT_LIB_FNS: ReadonlySet<IrLibFn> = new Set([
|
||||
"process.onBeforeExit",
|
||||
"process.onExit",
|
||||
"process.onSignal",
|
||||
"process.emitSignal",
|
||||
"process.prependBeforeExit",
|
||||
"process.prependExit",
|
||||
"process.prependSignal",
|
||||
@@ -2322,6 +2324,7 @@ const RUNTIME_FEATURE_RULES = {
|
||||
"buffer.byteLenValue",
|
||||
"buffer.allocValue",
|
||||
"fs.realpathValue",
|
||||
"fsp.realpathDyn",
|
||||
"buffer.constructor",
|
||||
"buffer.installValue",
|
||||
"buffer.staticValue",
|
||||
|
||||
@@ -42,6 +42,10 @@ const LIB_MODE_REFUSED_PREFIXES: readonly [string, string][] = [
|
||||
["spawnRes.", "the child_process surface"],
|
||||
["process.on", "process signal/exit listeners"],
|
||||
["process.off", "process signal/exit listeners"],
|
||||
// process.nextTick lowers to scr_next_tick in scr_async.c, a unit library
|
||||
// links exclude. Left unrefused it passed this gate and produced an archive
|
||||
// with an undefined reference that failed only at embedder link time.
|
||||
["process.nextTick", "the microtask surface (process.nextTick)"],
|
||||
// The flags object lives in a gated runtime unit (scr_process_features.c)
|
||||
// that library archives do not carry. A flag read by name
|
||||
// (process.features.tls) is a constant and links nothing.
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
/* Compiled on Windows: a Node-island program's modules are named by paths that
|
||||
* exist there. The collector walks each module's real path one component at a
|
||||
* time; starting that walk at the separator built the rooted "\C:\…" spelling,
|
||||
* which is not the file and failed the read. Linux and macOS keep their own
|
||||
* spelling and are covered by the rest of the suite. */
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterAll, expect, test } from "vitest";
|
||||
import { compile } from "../index.js";
|
||||
import { NODE_BRIDGE_ABI } from "./libnode.js";
|
||||
|
||||
const dirs: string[] = [];
|
||||
afterAll(() => {
|
||||
for (const dir of dirs) rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test.skipIf(process.platform !== "win32")("a Node-island program compiles on Windows", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "scriptc-island-win-"));
|
||||
dirs.push(dir);
|
||||
const pack = join(dir, "pack");
|
||||
mkdirSync(pack);
|
||||
writeFileSync(join(pack, "libnode.dll"), "lib");
|
||||
writeFileSync(join(pack, "libscr_node_bridge.dll"), "bridge");
|
||||
writeFileSync(
|
||||
join(pack, "manifest.json"),
|
||||
JSON.stringify({
|
||||
nodeVersion: "24.22.0",
|
||||
bridgeAbi: NODE_BRIDGE_ABI,
|
||||
files: { "libnode.dll": {}, "libscr_node_bridge.dll": {} },
|
||||
}),
|
||||
);
|
||||
writeFileSync(join(dir, "helper.cjs"), "exports.answer = () => 42;\n");
|
||||
writeFileSync(
|
||||
join(dir, "main.ts"),
|
||||
'import { callSync } from "@scriptc/node";\nconsole.log(callSync<number>("./helper.cjs", "answer"));\n',
|
||||
);
|
||||
const previous = process.env["SCRIPTC_LIBNODE"];
|
||||
process.env["SCRIPTC_LIBNODE"] = pack;
|
||||
try {
|
||||
const outPath = join(dir, "main.ir.json");
|
||||
const result = await compile(join(dir, "main.ts"), { outDir: dir, outPath, outputKind: "ir" });
|
||||
expect(result.ok ? [] : result.diagnostics.map((d) => `${d.code}: ${d.message}`)).toEqual([]);
|
||||
} finally {
|
||||
if (previous === undefined) delete process.env["SCRIPTC_LIBNODE"];
|
||||
else process.env["SCRIPTC_LIBNODE"] = previous;
|
||||
}
|
||||
});
|
||||
@@ -1,9 +1,10 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdirSync, mkdtempSync, realpathSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { dirname, join, posix as posixPath, win32 as win32Path } from "node:path";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { clearVirtualSources, setVirtualSource } from "../frontend/input-tracker.js";
|
||||
import { walkedPath } from "./modules.js";
|
||||
import {
|
||||
ModuleSpecifierScans,
|
||||
NodeIslandModuleCollector,
|
||||
@@ -693,3 +694,42 @@ describe("modules the program provides", () => {
|
||||
).toEqual(["./plugin.mjs"]);
|
||||
});
|
||||
});
|
||||
|
||||
test("a path walk keeps the volume root in Windows spellings", () => {
|
||||
// The walk behind a collected module's real path starts at the path's own
|
||||
// root; starting at the separator built "\C:\..." on Windows, a path that
|
||||
// does not exist there.
|
||||
expect(walkedPath("C:\\Users\\maintainer\\tla\\helper.cjs", win32Path)).toBe(
|
||||
"C:\\Users\\maintainer\\tla\\helper.cjs",
|
||||
);
|
||||
expect(walkedPath("c:/Users/a", win32Path)).toBe("c:\\Users\\a");
|
||||
expect(walkedPath("\\\\server\\share\\a", win32Path)).toBe("\\\\server\\share\\a");
|
||||
expect(walkedPath("/home/a/b", posixPath)).toBe("/home/a/b");
|
||||
for (const path of ["C:\\Users\\a", "c:/Users/a", "\\\\server\\share\\a"])
|
||||
expect(walkedPath(path, win32Path).startsWith("\\C:")).toBe(false);
|
||||
});
|
||||
|
||||
test("the walk placed() uses keeps drive and network roots", () => {
|
||||
// placed() hands walkedPath() the real path of each component; the walk
|
||||
// itself is what must keep the root, so it is checked here with a visit
|
||||
// that records every component it resolves.
|
||||
const seen: string[] = [];
|
||||
walkedPath("C:\\Users\\maintainer\\tla\\helper.cjs", win32Path, (lexical) => {
|
||||
seen.push(lexical);
|
||||
return lexical;
|
||||
});
|
||||
expect(seen).toEqual([
|
||||
"C:\\Users",
|
||||
"C:\\Users\\maintainer",
|
||||
"C:\\Users\\maintainer\\tla",
|
||||
"C:\\Users\\maintainer\\tla\\helper.cjs",
|
||||
]);
|
||||
const unc: string[] = [];
|
||||
walkedPath("\\\\server\\share\\a\\b", win32Path, (lexical) => {
|
||||
unc.push(lexical);
|
||||
return lexical;
|
||||
});
|
||||
expect(unc[0]).toBe("\\\\server\\share\\a");
|
||||
expect(unc[unc.length - 1]).toBe("\\\\server\\share\\a\\b");
|
||||
for (const lexical of [...seen, ...unc]) expect(lexical.startsWith("\\C:")).toBe(false);
|
||||
});
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import { builtinModules } from "node:module";
|
||||
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
||||
import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
|
||||
import {
|
||||
isVirtualSource,
|
||||
trackedAccessibleEntries,
|
||||
@@ -167,6 +167,26 @@ function importTargets(value: unknown): string[] {
|
||||
return [];
|
||||
}
|
||||
|
||||
/** The path a root-first walk of `path` reaches through `api`, keeping the
|
||||
* path's own root: a drive path stays on its volume ("C:\\Users\\a"), a network
|
||||
* path keeps its share, and neither becomes the rooted "\\C:" spelling a walk
|
||||
* from `api.sep` would build. */
|
||||
export function walkedPath(
|
||||
path: string,
|
||||
api: { resolve: typeof resolve; parse: typeof parse; join: typeof join; sep: string },
|
||||
visit?: (lexical: string) => string,
|
||||
): string {
|
||||
const resolved = api.resolve(path);
|
||||
const root = api.parse(resolved).root;
|
||||
let real: string = root;
|
||||
for (const part of resolved.slice(root.length).split(api.sep)) {
|
||||
if (part === "") continue;
|
||||
const lexical = api.join(real, part);
|
||||
real = visit === undefined ? lexical : visit(lexical);
|
||||
}
|
||||
return real;
|
||||
}
|
||||
|
||||
function portable(path: string): string {
|
||||
return sep === "/" ? path : path.split(sep).join("/");
|
||||
}
|
||||
@@ -352,15 +372,14 @@ export class NodeIslandModuleCollector {
|
||||
* that is a symbolic link (a linked directory on the way, or the file
|
||||
* itself), so that the path resolves inside the tree as it does here. */
|
||||
private placed(path: string): string {
|
||||
let real: string = sep;
|
||||
for (const part of resolve(path).split(sep)) {
|
||||
if (part === "") continue;
|
||||
const lexical = join(real, part);
|
||||
// walkedPath keeps the path's own root, so a drive path stays on its
|
||||
// volume ("C:\Users\…") and never becomes the rooted "\C:\Users\…"
|
||||
// spelling, which is a different path (and unreadable).
|
||||
return walkedPath(path, { resolve, parse, join, sep }, (lexical) => {
|
||||
const target = trackedRealpath(lexical) ?? lexical;
|
||||
if (target !== lexical) this.links.set(lexical, target);
|
||||
real = target;
|
||||
}
|
||||
return real;
|
||||
return target;
|
||||
});
|
||||
}
|
||||
|
||||
/** The real path of the file an absolute or relative `specifier` names
|
||||
|
||||
@@ -783,6 +783,12 @@ export const PROGRAM_SCANS: readonly ProgramScan[] = [
|
||||
"",
|
||||
"held-constructor-values",
|
||||
),
|
||||
scan(
|
||||
"frontend/cjs-getter-table.ts#cjsGetterTableOf",
|
||||
1,
|
||||
"prefilter",
|
||||
"an esbuild getter table's module has to spell `__export`; the walk behind it decides the shape from the module's syntax tree (the `__export(T, {...})` call and the kept `module.exports = T`), one module at a time",
|
||||
),
|
||||
scan(
|
||||
"frontend/fork-target.ts#namesChildProcess",
|
||||
4,
|
||||
@@ -1030,9 +1036,9 @@ export const PROGRAM_SCANS: readonly ProgramScan[] = [
|
||||
),
|
||||
scan(
|
||||
"frontend/lowering/lowerer.ts#Lowerer",
|
||||
1,
|
||||
2,
|
||||
"prefilter",
|
||||
"analyzeDateJsonResults: a toJSON call spells `toJSON`; the result types individual bindings",
|
||||
"analyzeDateJsonResults spells `toJSON` and analyzeJsonStringifyBindings spells `stringify`; each decides the result types of individual bindings",
|
||||
),
|
||||
scan(
|
||||
"frontend/lowering/native-ffi.ts#validateFfiImports",
|
||||
|
||||
@@ -1,28 +1,104 @@
|
||||
import { createReadStream } from "node:fs";
|
||||
import { open } from "node:fs/promises";
|
||||
import { closeSync, createReadStream, openSync, readSync, rmSync } from "node:fs";
|
||||
import { type FileHandle, open } from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
import { StringDecoder } from "node:string_decoder";
|
||||
|
||||
/** The longest part readTextParts returns, far below the engine's string
|
||||
* limit. */
|
||||
const TEXT_PART_LENGTH = 64 * 1024 * 1024;
|
||||
|
||||
/** One part of compiler text: a string, or the UTF-8 bytes of one, which a
|
||||
* large build keeps off the V8 heap (`TextPart` in the LLVM emitter). */
|
||||
export type TextPart = string | Uint8Array;
|
||||
/** A range of a file's bytes. A large build's function texts are written to a
|
||||
* temporary file as they are emitted, and only their ranges stay on the heap
|
||||
* (function-texts.ts in the LLVM backend). */
|
||||
export interface FileTextPart {
|
||||
readonly file: string;
|
||||
/** The range's first byte in `file`. */
|
||||
readonly offset: number;
|
||||
/** The range's length in bytes. */
|
||||
readonly length: number;
|
||||
/** The file is a build's temporary copy: `releaseTextParts` removes the
|
||||
* directory that holds it once the parts are written. */
|
||||
readonly temporary?: boolean;
|
||||
}
|
||||
|
||||
/** One part of compiler text: a string, the UTF-8 bytes of one (which a large
|
||||
* build keeps off the V8 heap), or a range of a file (`FileTextPart`). */
|
||||
export type TextPart = string | Uint8Array | FileTextPart;
|
||||
|
||||
/** Whether a part is a range of a file. The check must not read a record
|
||||
* member off the union: `(part as FileTextPart).file` is a checked conversion,
|
||||
* and probing a byte part that way traps ("not representable in the target
|
||||
* union") instead of answering false — the self-built compiler tripped over
|
||||
* exactly this when it emitted a large module, and so does a cast to a record
|
||||
* with an optional field. A byte part is the only object arm that is a typed
|
||||
* array, so exclude it by that test instead. */
|
||||
export function isFileTextPart(part: TextPart): part is FileTextPart {
|
||||
return typeof part === "object" && part !== null && !(part instanceof Uint8Array);
|
||||
}
|
||||
|
||||
/** A file part's bytes. */
|
||||
export function readPartBytes(part: FileTextPart): Buffer {
|
||||
const bytes = Buffer.allocUnsafe(part.length);
|
||||
const fd = openSync(part.file, "r");
|
||||
try {
|
||||
for (let done = 0; done < part.length;) {
|
||||
const read = readSync(fd, bytes, done, part.length - done, part.offset + done);
|
||||
if (read <= 0)
|
||||
throw new Error(
|
||||
`text part: ${part.file} ended at byte ${part.offset + done} of ${part.offset + part.length}`,
|
||||
);
|
||||
done += read;
|
||||
}
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/** A part as text: a byte part is its UTF-8 decoding (the emitter writes
|
||||
* ASCII, which round-trips exactly). */
|
||||
* ASCII, which round-trips exactly), and a file part is its range decoded the
|
||||
* same way. */
|
||||
export function textOfPart(part: TextPart): string {
|
||||
return typeof part === "string" ? part : Buffer.from(part.subarray(0)).toString("utf8");
|
||||
if (typeof part === "string") return part;
|
||||
if (isFileTextPart(part)) return readPartBytes(part).toString("utf8");
|
||||
return Buffer.from(part.subarray(0)).toString("utf8");
|
||||
}
|
||||
|
||||
/** A part's bytes: a string encoded as UTF-8, a byte part as it is, a file
|
||||
* part read from its file. */
|
||||
export function bytesOfPart(part: TextPart): Uint8Array {
|
||||
if (typeof part === "string") return Buffer.from(part, "utf8");
|
||||
if (isFileTextPart(part)) return readPartBytes(part);
|
||||
return part;
|
||||
}
|
||||
|
||||
/** Whether a part's text contains `needle` (ASCII), without decoding a byte
|
||||
* part. */
|
||||
export function partIncludes(part: TextPart, needle: string): boolean {
|
||||
if (typeof part === "string") return part.includes(needle);
|
||||
if (isFileTextPart(part)) return readPartBytes(part).includes(needle);
|
||||
return Buffer.from(part.subarray(0)).includes(needle);
|
||||
}
|
||||
|
||||
/** Tells a part's owner that its directory is being released, and whether the
|
||||
* owner still has it: the module that made a temporary directory records it,
|
||||
* and a directory that has been released already — or replaced since by
|
||||
* another process or a link — is not removed a second time. */
|
||||
let releaseTemporaryDirectory: (dir: string) => boolean = () => true;
|
||||
|
||||
export function setTemporaryDirectoryReleaser(release: (dir: string) => boolean): void {
|
||||
releaseTemporaryDirectory = release;
|
||||
}
|
||||
|
||||
/** The directories of the temporary files the parts name, once each. */
|
||||
export function releaseTextParts(parts: readonly TextPart[]): void {
|
||||
const dirs = new Set<string>();
|
||||
for (const part of parts)
|
||||
if (isFileTextPart(part) && part.temporary === true) dirs.add(dirname(part.file));
|
||||
for (const dir of dirs)
|
||||
if (releaseTemporaryDirectory(dir)) rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
/** Text as a part kept off the V8 heap. */
|
||||
export function bytesOfText(text: string): Uint8Array {
|
||||
return Buffer.from(text, "utf8");
|
||||
@@ -41,43 +117,83 @@ export function flatText(text: string): string {
|
||||
* Programs past the engine's string limit arrive as many parts, and writing
|
||||
* each part separately is several times slower than writing the same bytes in
|
||||
* a few large chunks. Batches stay far below the limit. A part that arrives
|
||||
* as bytes is written as it is. */
|
||||
* as bytes is written as it is, and a file part is copied from its file
|
||||
* range: the temporary file a large build's function texts live in leaves the
|
||||
* disk once the parts are written. */
|
||||
export async function writeTextParts(
|
||||
path: string,
|
||||
text: TextPart | readonly TextPart[],
|
||||
mode = 0o666,
|
||||
): Promise<void> {
|
||||
const file = await open(path, "w", mode);
|
||||
// Every file part of one build names the same file, and the ranges are
|
||||
// copied one after another: the source stays open while they are written.
|
||||
const sources = new Map<string, FileHandle>();
|
||||
try {
|
||||
const write = async (chunk: TextPart): Promise<void> => {
|
||||
const bytes = typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk;
|
||||
for (let offset = 0; offset < bytes.length;) {
|
||||
const { bytesWritten } = await file.write(bytes, offset, bytes.length - offset);
|
||||
const writeBytes = async (bytes: Uint8Array, length = bytes.length): Promise<void> => {
|
||||
for (let offset = 0; offset < length;) {
|
||||
const { bytesWritten } = await file.write(bytes, offset, length - offset);
|
||||
offset += bytesWritten;
|
||||
}
|
||||
};
|
||||
if (!Array.isArray(text)) return await write(text as TextPart);
|
||||
// A byte part and the newline around it arrive as separate parts, so the
|
||||
// batch holds bytes: a string part is encoded into it, and each batch is
|
||||
// one write.
|
||||
let batch: Uint8Array[] = [];
|
||||
let length = 0;
|
||||
const flush = async (): Promise<void> => {
|
||||
if (batch.length === 0) return;
|
||||
await write(batch.length === 1 ? batch[0]! : Buffer.concat(batch));
|
||||
batch = [];
|
||||
length = 0;
|
||||
// A range is copied in chunks: a function's text can be large, and the
|
||||
// write holds one chunk of it at a time.
|
||||
const rangeChunk = 4 * 1024 * 1024;
|
||||
const writeRange = async (part: FileTextPart): Promise<void> => {
|
||||
let source = sources.get(part.file);
|
||||
if (source === undefined) {
|
||||
source = await open(part.file, "r");
|
||||
sources.set(part.file, source);
|
||||
}
|
||||
const buffer = Buffer.allocUnsafe(Math.min(part.length, rangeChunk));
|
||||
for (let done = 0; done < part.length;) {
|
||||
const want = Math.min(buffer.length, part.length - done);
|
||||
const { bytesRead } = await source.read(buffer, 0, want, part.offset + done);
|
||||
if (bytesRead <= 0)
|
||||
throw new Error(
|
||||
`text part: ${part.file} ended at byte ${part.offset + done} of ${part.offset + part.length}`,
|
||||
);
|
||||
await writeBytes(buffer, bytesRead);
|
||||
done += bytesRead;
|
||||
}
|
||||
};
|
||||
for (const part of text) {
|
||||
const bytes = typeof part === "string" ? Buffer.from(part, "utf8") : part;
|
||||
batch.push(bytes);
|
||||
length += bytes.byteLength;
|
||||
if (length >= 16 * 1024 * 1024) await flush();
|
||||
const write = async (chunk: TextPart): Promise<void> => {
|
||||
if (isFileTextPart(chunk)) return await writeRange(chunk);
|
||||
await writeBytes(typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk);
|
||||
};
|
||||
if (!Array.isArray(text)) await write(text as TextPart);
|
||||
else {
|
||||
// A byte part and the newline around it arrive as separate parts, so
|
||||
// the batch holds bytes: a string part is encoded into it, and each
|
||||
// batch is one write.
|
||||
let batch: Uint8Array[] = [];
|
||||
let length = 0;
|
||||
const flush = async (): Promise<void> => {
|
||||
if (batch.length === 0) return;
|
||||
await writeBytes(batch.length === 1 ? batch[0]! : Buffer.concat(batch));
|
||||
batch = [];
|
||||
length = 0;
|
||||
};
|
||||
for (const part of text) {
|
||||
if (isFileTextPart(part)) {
|
||||
// The range keeps its place in the file's order: the batch before it
|
||||
// is written first.
|
||||
await flush();
|
||||
await writeRange(part);
|
||||
continue;
|
||||
}
|
||||
const bytes = typeof part === "string" ? Buffer.from(part, "utf8") : part;
|
||||
batch.push(bytes);
|
||||
length += bytes.byteLength;
|
||||
if (length >= 16 * 1024 * 1024) await flush();
|
||||
}
|
||||
await flush();
|
||||
}
|
||||
await flush();
|
||||
} finally {
|
||||
await file.close();
|
||||
for (const source of sources.values()) await source.close();
|
||||
}
|
||||
releaseTextParts(Array.isArray(text) ? text : [text as TextPart]);
|
||||
}
|
||||
|
||||
/** Reads a text artifact as parts of at most `partLength` UTF-16 units:
|
||||
|
||||
@@ -37,3 +37,89 @@ bump({ a: 1 }, "a", 2);
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// A checked-dynamic dictionary answers a missing key with undefined, and a
|
||||
// present cell may hold null whatever the checker's index value says (the
|
||||
// record crossed the checker through a cast). A non-numeric use of the
|
||||
// asserted read therefore keeps both unit arms: String() and templates print
|
||||
// the value, equality compares it, and JSON omits an undefined member or
|
||||
// writes a null one. A root read goes through the runtime walker, which
|
||||
// answers undefined for an absent root and "null" for a null one.
|
||||
test("a null-bearing asserted dictionary read keeps both unit arms", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "scriptc-asserted-dict-null-"));
|
||||
try {
|
||||
const entry = join(dir, "main.ts");
|
||||
const outPath = join(dir, "main.ir");
|
||||
await writeFile(
|
||||
entry,
|
||||
`
|
||||
function probe(target: unknown): void {
|
||||
const record = target as Record<string, number | null>;
|
||||
console.log(String(record["missing"]!), JSON.stringify(record["missing"]!));
|
||||
console.log(JSON.stringify({ k: record["missing"]! }), record["missing"]! + 1);
|
||||
}
|
||||
probe({});
|
||||
`,
|
||||
);
|
||||
const result = await compile(entry, { outDir: dir, outPath, outputKind: "ir" });
|
||||
expect(result.ok, JSON.stringify(result.diagnostics)).toBe(true);
|
||||
const ir = JSON.parse(await readFile(outPath, "utf8")) as {
|
||||
unions: { id: string; arms: { kind: string }[] }[];
|
||||
records: { fields: { name: string; type: { kind: string; unionId?: string } }[] }[];
|
||||
};
|
||||
const field = ir.records
|
||||
.flatMap((record) => record.fields)
|
||||
.find((candidate) => candidate.name === "k");
|
||||
expect(field?.type.kind).toBe("union");
|
||||
const union = ir.unions.find((candidate) => candidate.id === field?.type.unionId);
|
||||
expect(union?.arms.map((arm) => arm.kind).sort()).toEqual(["f64", "nullT", "undefinedT"]);
|
||||
const text = JSON.stringify(ir);
|
||||
// The root read keeps its absent root for the walker.
|
||||
expect(text).toContain('"fn":"json.stringifyReplacer"');
|
||||
// Numeric uses stay on the inline ToNumber conversion.
|
||||
expect(text).toContain('"fn":"js.toNumberOrNaN"');
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// JSON.stringify answers undefined exactly when its root is absent. A
|
||||
// callback or function the checker types `string` widens its return slot to
|
||||
// keep that answer instead of trapping at the return, for the asserted read
|
||||
// and for the plain one. An object member's result is always the text: its
|
||||
// field drops or serializes on its own.
|
||||
test("a JSON result's return slot widens when the root may be absent", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "scriptc-json-return-slot-"));
|
||||
try {
|
||||
const entry = join(dir, "main.ts");
|
||||
const outPath = join(dir, "main.ir");
|
||||
await writeFile(
|
||||
entry,
|
||||
`
|
||||
const raw: Record<string, unknown> = {};
|
||||
const record = raw as Record<string, number | null>;
|
||||
function member(bang: boolean): string {
|
||||
return JSON.stringify({ k: bang ? record["missing"]! : record["missing"] });
|
||||
}
|
||||
function root(bang: boolean): string {
|
||||
return bang ? JSON.stringify(record["missing"]!) : JSON.stringify(record["missing"]);
|
||||
}
|
||||
console.log(member(true), root(false));
|
||||
`,
|
||||
);
|
||||
const result = await compile(entry, { outDir: dir, outPath, outputKind: "ir" });
|
||||
expect(result.ok, JSON.stringify(result.diagnostics)).toBe(true);
|
||||
const ir = JSON.parse(await readFile(outPath, "utf8")) as {
|
||||
functions: { name: string; returnType: { kind: string; unionId?: string } }[];
|
||||
unions: { id: string; arms: { kind: string }[] }[];
|
||||
};
|
||||
const member = ir.functions.find((fn) => fn.name === "member");
|
||||
expect(member?.returnType.kind).toBe("string");
|
||||
const root = ir.functions.find((fn) => fn.name === "root");
|
||||
expect(root?.returnType.kind).toBe("union");
|
||||
const union = ir.unions.find((candidate) => candidate.id === root?.returnType.unionId);
|
||||
expect(union?.arms.map((arm) => arm.kind).sort()).toEqual(["string", "undefinedT"]);
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -606,6 +606,8 @@ describe.each(ts7TestServers())("import elision ($name)", (server) => {
|
||||
preserveConstEnums: false,
|
||||
preserveImportEdges: false,
|
||||
preserveValueImports: false,
|
||||
experimentalDecorators: false,
|
||||
emitDecoratorMetadata: false,
|
||||
...options,
|
||||
});
|
||||
program.dispose();
|
||||
@@ -845,6 +847,8 @@ test("verbatimModuleSyntax selects Node's rule; the removed options are still re
|
||||
preserveConstEnums: false,
|
||||
preserveImportEdges: false,
|
||||
preserveValueImports: false,
|
||||
experimentalDecorators: false,
|
||||
emitDecoratorMetadata: false,
|
||||
});
|
||||
expect(importElisionOptions({ isolatedModules: true })?.preserveConstEnums).toBe(true);
|
||||
expect(importElisionOptions({ importsNotUsedAsValues: "preserve" })?.preserveImportEdges).toBe(
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { expect, test } from "vitest";
|
||||
import { analyze } from "../src/index.js";
|
||||
|
||||
/* The static-field fence helpers get one branch per class and static field: a
|
||||
* `delete` or `Object.defineProperty` on a class value must be refused for
|
||||
* every class it can hold that lists the field. A program with a few hundred
|
||||
* inheriting classes and two hundred fields produces a batch of tens of
|
||||
* thousands of branches, so the batch is assembled into the helper's body
|
||||
* without spreading it into a call, which would pass each branch as an
|
||||
* argument and overflow the engine's argument limit. */
|
||||
const dir = join(import.meta.dirname, "../../node_modules/.cache/scriptc-tests/static-fence-batch");
|
||||
|
||||
test("a large static-field fence batch compiles", () => {
|
||||
const classes = 350;
|
||||
const fields = 200;
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
mkdirSync(dir, { recursive: true });
|
||||
writeFileSync(
|
||||
join(dir, "package.json"),
|
||||
JSON.stringify({ name: "fence", private: true, type: "module" }),
|
||||
);
|
||||
const lines = ["class Base {"];
|
||||
for (let field = 0; field < fields; field++) lines.push(` static f${field} = ${field};`);
|
||||
lines.push("}");
|
||||
for (let index = 0; index < classes; index++) lines.push(`class S${index} extends Base {}`);
|
||||
lines.push("const boxed: any = Base;", "delete boxed.f1;");
|
||||
for (let index = 0; index < classes; index++) lines.push(`new S${index}();`);
|
||||
lines.push("console.log(Base.f0);");
|
||||
const entry = join(dir, "main.ts");
|
||||
writeFileSync(entry, lines.join("\n") + "\n");
|
||||
|
||||
const result = analyze(entry, {});
|
||||
expect(result.coverage.preflightFailed, JSON.stringify(result.coverage.diagnostics)).toBe(false);
|
||||
expect(result.coverage.diagnostics).toEqual([]);
|
||||
expect(result.coverage.stats.statementsFailed).toBe(0);
|
||||
|
||||
// The fence helper carries one branch per class and field, so the batch is
|
||||
// as large as this program makes it (classes × fields, tens of thousands).
|
||||
expect(classes * fields).toBeGreaterThan(65_535);
|
||||
}, 600_000);
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user