diff --git a/build.gradle b/build.gradle index 566df0962..29c3da2ea 100644 --- a/build.gradle +++ b/build.gradle @@ -386,6 +386,12 @@ task copyReadme(type: Copy) { into "$DIST_PATH" } +task copyTypes(type: Copy) { + from "$rootDir/types" + include "*.d.ts" + into "$DIST_PATH/types" +} + task createNpmPackage(type: Exec) { doFirst { workingDir "$DIST_PATH" @@ -422,7 +428,8 @@ copyProjectTemplate.dependsOn(verifyJsParserPackage) copyPackageJson.dependsOn(copyProjectTemplate) setPackageVersionInPackageJsonFile.dependsOn(copyPackageJson) copyReadme.dependsOn(setPackageVersionInPackageJsonFile) -createNpmPackage.dependsOn(copyReadme) +copyTypes.dependsOn(copyReadme) +createNpmPackage.dependsOn(copyTypes) task createPackage { println "CCache version: " + getCCacheVersion() diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index c98e4be82..da76abf75 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -620,6 +620,85 @@ workers for the change to reach them.** A worker started after the `configureLoader` call resolves through the new vocabulary; a live worker never observes a later reconfiguration. +### `ns:url` + +The runtime's own `URL` and `URLSearchParams`, reachable by specifier, plus +the two path/URL converters. Its export set is exactly `node:url`'s, so that +shim re-exports every member unchanged. **Experimental.** + +| export | description | +|---|---| +| `URL` | The runtime's `URL` constructor: the very function the global of that name was created with, so `require("ns:url").URL === globalThis.URL` unless the app has reassigned the global. `toJSON()` returns `href`, as WHATWG specifies, so `JSON.stringify(url)` is the href string. | +| `URLSearchParams` | Likewise the runtime's `URLSearchParams` constructor. | +| `fileURLToPath(url)` | Converts a `file:` URL (a string, or any object with a string `href`, so a `URL` from another realm works) to an absolute path, percent-decoding it. | +| `pathToFileURL(path)` | Converts an absolute path to a `file:` URL, returning this module's `URL`. | + +`URLPattern` stays a global only: Node's `node:url` has no counterpart, and +nothing in the module needs it. + +The module exists so that typed code can name the URL classes without +depending on what `globalThis.URL` resolves to in the program's type +environment. The iOS runtime's `types/ns-url.d.ts` declares it, along with +the global `URL` and `URLSearchParams`; Android adds nothing to that surface, +so this package ships no declaration of its own for it. + +The converters parse through the module's own `URL`, so `file://localhost/x` is +accepted (the URL spec folds a `localhost` authority to none) while any other +host throws, and the query and fragment are never part of the path. +`fileURLToPath` rejects a non-`file:` scheme and rejects `%2F` in the path +rather than decoding a separator into it. `pathToFileURL` returns a real `URL` +and requires an **absolute** path: Node resolves a relative one against the +process working directory, and there is no such thing here. + +```js +const { fileURLToPath, pathToFileURL } = require("ns:url"); + +fileURLToPath("file:///app/src/main.js"); // "/app/src/main.js" +fileURLToPath("file://localhost/app/a.js"); // "/app/a.js" +fileURLToPath("file:///app/a.js?v=2#frag"); // "/app/a.js" + +pathToFileURL("/app/my file.js").href; // "file:///app/my%20file.js" +``` + +Its `TypeError` messages are Node's: + +| condition | message | +|---|---| +| argument is neither a string nor a URL-like object, or is unparseable | `The "path" argument must be of type string or an instance of URL.` | +| non-`file:` scheme | `The URL must be of scheme file` | +| a host other than `localhost` or empty | `File URL host must be "localhost" or empty` | +| `%2F` in the path | `File URL path must not include encoded / characters` | +| `pathToFileURL` given a non-string | `The "path" argument must be of type string.` | +| `pathToFileURL` given a relative path | `The "path" argument must be an absolute path.` | + +### `ns:worker_threads` + +The runtime's own `Worker`, reachable by specifier; the `node:worker_threads` +shim adapts it. **Experimental.** + +| export | description | +|---|---| +| `Worker` | The runtime's `Worker` constructor: the very function the global of that name was created with, so `require("ns:worker_threads").Worker === globalThis.Worker` unless the app has reassigned the global. Its constructor options — `android.priority` and Node's `resourceLimits` — are described in [worker-threads.md](worker-threads.md#worker-options). | + +```js +import { Worker } from "ns:worker_threads"; + +const worker = new Worker("./heavy.js", { + android: { priority: "lessFavorable" }, + resourceLimits: { maxOldGenerationSizeMb: 64 }, +}); +``` + +The module exists so that typed code can name the runtime's constructor and +its options without depending on what `globalThis.Worker` resolves to in the +program's type environment. The iOS runtime's `types/ns-worker-threads.d.ts` +declares the module, its cross-platform options and the global `Worker`; this +package's `types/ns-worker-threads-android.d.ts` adds `android` (and the +deprecated `androidPriority`) to both the module's and the global +`WorkerOptions`, merging with those declarations rather than restating them. +Cross-platform code can pass `ios` and `android` together: each runtime reads +its own object and ignores the other's. + ### `node:` compatibility shims The same registry serves the `node:` scheme with **compatibility shims** so @@ -659,38 +738,9 @@ unmodified where a shim exists: | module | exports | notes | |---|---|---| | `node:util` | `inspect`, `format`, `TextEncoder`, `TextDecoder` | Re-exports `ns:util`'s members unchanged (`nodeUtil.inspect === nsUtil.inspect`) from a **distinct, separately frozen module object**. `TextEncoder`/`TextDecoder` are the globals of those names, as they are in Node. Documented as partial. | -| `node:url` | `fileURLToPath`, `pathToFileURL` | Node-strict converters between `file:` URLs and paths. Documented as partial — no `URL`/`URLSearchParams` re-exports (both are globals), no legacy `url.parse`/`format`/`resolve`. | +| `node:url` | `URL`, `URLSearchParams`, `fileURLToPath`, `pathToFileURL` | Re-exports `ns:url`'s members unchanged (`nodeUrl.fileURLToPath === nsUrl.fileURLToPath`) from a **distinct, separately frozen module object**; the converters are Node-strict and throw Node's messages. Documented as partial — no legacy `url.parse`/`format`/`resolve`, and no `URLPattern` (Node's `node:url` has none). | | `node:module` | `createRequire` | Re-exports `ns:module`'s `createRequire` unchanged from a **distinct, separately frozen module object**. `createPumpingRequire` is deliberately absent: it has no Node counterpart, so code written against this shim keeps running on Node. `require.resolve`/`.cache`/`.main` are not implemented, and neither is any other `node:module` member (`Module`, `builtinModules`, `isBuiltin`, `register`, `syncBuiltinESMExports`). Documented as partial. | -| `node:worker_threads` | the messaging and thread surface — see [worker-threads.md](worker-threads.md) | The channel half (`MessagePort`, `MessageChannel`, `BroadcastChannel`, `receiveMessageOnPort`) is the real implementation, the same objects the globals of those names hold; the thread half is a bridge over the runtime's own `Worker`. It has no `ns:` counterpart — the surface tracks Node's, so there is nothing for a standard module to own. The one place it breaks the absent-not-throwing rule below is deliberate: `postMessageToThread` and `moveMessagePortToContext` are present and throw an `Error` naming themselves, because silently missing thread-addressed messaging reads as a delivery bug rather than as an unsupported call. Documented as partial. | - -`node:url`'s parsing goes through the URL intrinsic, so `file://localhost/x` is -accepted (the URL spec folds a `localhost` authority to none) while any other -host throws, and the query and fragment are never part of the path. -`fileURLToPath` rejects a non-`file:` scheme and rejects `%2F` in the path -rather than decoding a separator into it. `pathToFileURL` returns a real `URL` -and requires an **absolute** path: Node resolves a relative one against the -process working directory, and there is no such thing here. - -```js -const { fileURLToPath, pathToFileURL } = require("node:url"); - -fileURLToPath("file:///app/src/main.js"); // "/app/src/main.js" -fileURLToPath("file://localhost/app/a.js"); // "/app/a.js" -fileURLToPath("file:///app/a.js?v=2#frag"); // "/app/a.js" - -pathToFileURL("/app/my file.js").href; // "file:///app/my%20file.js" -``` - -Its `TypeError` messages are Node's: - -| condition | message | -|---|---| -| argument is neither a string nor a URL-like object, or is unparseable | `The "path" argument must be of type string or an instance of URL.` | -| non-`file:` scheme | `The URL must be of scheme file` | -| a host other than `localhost` or empty | `File URL host must be "localhost" or empty` | -| `%2F` in the path | `File URL path must not include encoded / characters` | -| `pathToFileURL` given a non-string | `The "path" argument must be of type string.` | -| `pathToFileURL` given a relative path | `The "path" argument must be an absolute path.` | +| `node:worker_threads` | the messaging and thread surface — see [worker-threads.md](worker-threads.md) | The channel half (`MessagePort`, `MessageChannel`, `BroadcastChannel`, `receiveMessageOnPort`) is the real implementation, the same objects the globals of those names hold; the thread half is a bridge over the `Worker` that `ns:worker_threads` exports. The channel half has no `ns:` counterpart — its surface tracks Node's, so there is nothing for a standard module to own. The one place it breaks the absent-not-throwing rule below is deliberate: `postMessageToThread` and `moveMessagePortToContext` are present and throw an `Error` naming themselves, because silently missing thread-addressed messaging reads as a delivery bug rather than as an unsupported call. Documented as partial. | ## Loading ES modules @@ -976,9 +1026,9 @@ resolvers read the same table differently: - The **`ns:`/`node:` resolver** — the app-facing one, behind `require()`, `import` and `import()` — serves only rows *not* marked internal-only. An internal-only specifier fails exactly as a name absent from the table does. - Nine rows are public today: `ns:interop`, `ns:interop/android`, `ns:module`, - `ns:runtime`, `ns:util`, `node:module`, `node:url`, `node:util`, - `node:worker_threads`. + Eleven rows are public today: `ns:interop`, `ns:interop/android`, + `ns:module`, `ns:runtime`, `ns:url`, `ns:util`, `ns:worker_threads`, + `node:module`, `node:url`, `node:util`, `node:worker_threads`. - The **internal require** builtins receive (previous section) is the only thing that can name an internal-only row. Seven rows are marked that way: `internal/broadcast-channel`, `internal/dom-exception`, `internal/events`, @@ -1103,6 +1153,11 @@ implicit port's message queue disabled until the worker entry finishes evaluating — including after a pending top-level await settles. Messages sent before that stay buffered. -Unlike iOS, Android ships no `.d.ts` declarations for the `ns:` modules; the -`.d.ts` files in this repo describe the Android platform classes, not this -surface. +Android's `.d.ts` declarations for the `ns:` modules live in `types/` and +cover only what this runtime adds to them (today, `ns:worker_threads`'s +`android` option). The iOS runtime's `types/` is the source of truth for the +shared surface: two `declare module` blocks that both declare the same value +conflict, so these files declare only new names and merge into the iOS ones. +A program that includes only the Android types therefore sees the additions +but not the shared exports. The other `.d.ts` files in this repo describe the +Android platform classes, not this surface. diff --git a/docs/worker-threads.md b/docs/worker-threads.md index f899d0f1f..a2939304a 100644 --- a/docs/worker-threads.md +++ b/docs/worker-threads.md @@ -49,12 +49,12 @@ means deliberately unsupported. | `markAsUncloneable(obj)` | real | Brands `obj` so serializing it at all is a `DataCloneError`, in `structuredClone` and every `postMessage` alike. | | `setEnvironmentData(key, value)` | real, deviates | Clones and stores process-wide. No per-thread snapshot — see below. Passing `undefined` (or omitting the value) deletes the key. | | `getEnvironmentData(key)` | real, deviates | Deserializes a fresh copy per read, on any isolate. | -| `resourceLimits` | shim | Always `{}`; the runtime imposes no per-worker limits and reports none. | +| `resourceLimits` | shim | Always `{}`. The export reports nothing; the `resourceLimits` constructor option is real — see [Worker options](#worker-options). | | `SHARE_ENV` | shim | Exported so the spelling resolves, but inert — see below. | | `threadName` | shim | Always `undefined`. | | `workerData` | shim | Always `null` — see below. | | `parentPort` | shim | `null` on the main isolate. Inside a worker, a `MessagePort`-shaped `EventTarget` over the worker's existing parent channel: `postMessage` forwards to the global `postMessage`, `message`/`messageerror` are re-dispatched from the worker global scope, `start()` and `close()` are no-ops. It is **not** a real port: not transferable, no queue of its own. | -| `Worker` | shim | A class over the runtime's global `Worker` with a small Node-style emitter (`on`/`once`/`off`/`removeListener`) for `message`, `messageerror`, `error`, `online` and `exit`. An `error` listener receives the worker's error rebuilt as an `Error` (see below). `postMessage(value, transfer)` and `terminate()` forward. `online` is emitted off a microtask after construction, not from the thread. `exit` (always code `0`) fires exactly once, when the thread has ended, whether the worker was terminated or ended by its own `close()`; `terminate()` resolves at the same point. Unsupported options throw a `TypeError` naming the option: `workerData`, `env`, `eval`, `transferList`, and `stdin`/`stdout`/`stderr` when explicitly truthy. The runtime's own `Worker` options (`androidPriority`) ride along untouched — the native constructor ignores keys it does not know. | +| `Worker` | shim | A class over the runtime's `Worker` (the one [`ns:worker_threads`](ns-builtin-modules.md#nsworker_threads) exports) with a small Node-style emitter (`on`/`once`/`off`/`removeListener`) for `message`, `messageerror`, `error`, `online` and `exit`. An `error` listener receives the worker's error rebuilt as an `Error` (see below). `postMessage(value, transfer)` and `terminate()` forward. `online` is emitted off a microtask after construction, not from the thread. `exit` (always code `0`) fires exactly once, when the thread has ended, whether the worker was terminated or ended by its own `close()`; `terminate()` resolves at the same point. Unsupported options throw a `TypeError` naming the option: `workerData`, `env`, `eval`, `transferList`, and `stdin`/`stdout`/`stderr` when explicitly truthy. The runtime's own `Worker` options (`android`, `resourceLimits` and the deprecated `androidPriority`) ride along untouched — the native constructor ignores keys it does not know. | | `postMessageToThread` | throws | `Error: postMessageToThread is not supported in this runtime`. | | `moveMessagePortToContext` | throws | `Error: moveMessagePortToContext is not supported in this runtime`. | | `locks` | absent | Web Locks are not implemented; the property does not exist. | @@ -271,6 +271,48 @@ it has no way out: a `message` event hands it over in `event.ports`, while close such a port as soon as it arrives, so its sibling learns the channel is gone instead of queueing into a port nothing can ever read. +## Worker options + +The runtime's `Worker` constructor takes two options of its own, and the +`node:worker_threads` shim passes both through unchanged. Unknown keys inside +either object are ignored, so a later runtime can add more without breaking an +older one, and cross-platform code can pass the iOS runtime's `ios` object +alongside `android`. `null` for either object means the same as leaving it +out. The constructor is also exported by the +[`ns:worker_threads`](ns-builtin-modules.md#nsworker_threads) builtin, whose +type declarations describe both options and merge them into the global +`WorkerOptions`. + +### `android.priority` + +The worker thread's `android.os.Process` priority: one of the +`THREAD_PRIORITY_*` constants by camelCase name (`lowest`, `background`, +`lessFavorable`, `default`, `moreFavorable`, `foreground`, `display`, +`urgentDisplay`, `video`, `audio`, `urgentAudio`) or a nice value. A number +outside -20..19 is clamped into it; `NaN`, any other type and an unknown name +throw a `TypeError`, as does an `android` that is not an object. Omitted, the +thread runs at `background` (nice 10). Lowering a nice value below 0 may need +a privilege the app does not hold. + +The top-level `androidPriority` is the deprecated spelling: it takes the same +values (a `NaN` there means `default`), logs a deprecation warning once per +process, and loses to `android.priority` when both are given. + +### `resourceLimits` + +Node's shape, in megabytes: + +| key | effect | +|---|---| +| `maxOldGenerationSizeMb` | Caps the worker isolate's old generation. | +| `maxYoungGenerationSizeMb` | Caps the worker isolate's young generation. | +| `jsDispatchTableSizeMb` | NativeScript extension: the isolate's JS dispatch table reservation, a whole number from 1 to 256. Worker isolates reserve 64 MB when it is omitted; the main isolate keeps V8's default. With a V8 build that cannot size the table, passing it throws an `Error`. | + +A value that is not a number throws a `TypeError`; a non-finite one, one worth +less than a byte or one too large to hold in bytes throws a `RangeError`. +Node's `stackSizeMb` and `codeRangeSizeMb` are ignored, like any other key the +runtime does not know. + ## Worker messages The runtime's own `Worker` and the worker global scope are `EventTarget`s that diff --git a/package.json b/package.json index ae1bd0a6b..55f062584 100644 --- a/package.json +++ b/package.json @@ -6,6 +6,7 @@ "type": "git", "url": "https://github.com/NativeScript/android.git" }, + "types": "./types/index.d.ts", "files": [ "**/*" ], diff --git a/test-app/app/src/main/assets/app/mainpage.js b/test-app/app/src/main/assets/app/mainpage.js index ff48fe958..a0d90cf51 100644 --- a/test-app/app/src/main/assets/app/mainpage.js +++ b/test-app/app/src/main/assets/app/mainpage.js @@ -131,6 +131,8 @@ require('./tests/testNsUtil'); require('./tests/testNsRuntime'); require('./tests/testNsInterop'); require('./tests/testNsModule'); +require('./tests/testNsUrl'); +require('./tests/testNsWorkerThreads'); // Remote-module security gate (debug builds allow remote modules outright) require('./tests/testRemoteModuleSecurity'); // The ES module loader: require(esm) interop and the createRequire factories diff --git a/test-app/app/src/main/assets/app/tests/nsUrlIdentityWorker.js b/test-app/app/src/main/assets/app/tests/nsUrlIdentityWorker.js new file mode 100644 index 000000000..a97110b9f --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/nsUrlIdentityWorker.js @@ -0,0 +1,10 @@ +// Reassigns the global before the module is first required in this realm, so +// a module that merely read `globalThis.URL` would report the impostor. +var original = globalThis.URL; +globalThis.URL = function Impostor() {}; +var nsUrl = require("ns:url"); +postMessage({ + isOriginal: nsUrl.URL === original, + isImpostor: nsUrl.URL === globalThis.URL, + frozen: Object.isFrozen(nsUrl), +}); diff --git a/test-app/app/src/main/assets/app/tests/nsWorkerThreadsIdentityWorker.js b/test-app/app/src/main/assets/app/tests/nsWorkerThreadsIdentityWorker.js new file mode 100644 index 000000000..28a42de9c --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/nsWorkerThreadsIdentityWorker.js @@ -0,0 +1,10 @@ +// Reassigns the global before the module is first required in this realm, so +// a module that merely read `globalThis.Worker` would report the impostor. +var original = globalThis.Worker; +globalThis.Worker = function Impostor() {}; +var nsWorkerThreads = require("ns:worker_threads"); +postMessage({ + isOriginal: nsWorkerThreads.Worker === original, + isImpostor: nsWorkerThreads.Worker === globalThis.Worker, + frozen: Object.isFrozen(nsWorkerThreads), +}); diff --git a/test-app/app/src/main/assets/app/tests/testNodeUrlModule.js b/test-app/app/src/main/assets/app/tests/testNodeUrlModule.js index b41081c0d..71b236667 100644 --- a/test-app/app/src/main/assets/app/tests/testNodeUrlModule.js +++ b/test-app/app/src/main/assets/app/tests/testNodeUrlModule.js @@ -12,10 +12,12 @@ describe("node:url", function () { var required = require("node:url"); expect(Object.isFrozen(required)).toBe(true); - expect(Object.keys(required).sort()).toEqual(["fileURLToPath", "pathToFileURL"]); - // The shim converts between paths and file URLs; it is not a place to - // reach the URL intrinsic from. - expect(required.URL).toBeUndefined(); + expect(Object.keys(required).sort()).toEqual([ + "URL", + "URLSearchParams", + "fileURLToPath", + "pathToFileURL", + ]); expect(require("node:url")).toBe(required); Promise.all([import("node:url"), import("node:url")]).then(function (results) { diff --git a/test-app/app/src/main/assets/app/tests/testNsUrl.js b/test-app/app/src/main/assets/app/tests/testNsUrl.js new file mode 100644 index 000000000..cc873c62a --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/testNsUrl.js @@ -0,0 +1,80 @@ +describe("ns:url", function () { + var nsUrl = require("ns:url"); + + it("exposes frozen exports", function () { + expect(Object.isFrozen(nsUrl)).toBe(true); + expect(typeof nsUrl.URL).toBe("function"); + expect(typeof nsUrl.URLSearchParams).toBe("function"); + expect(typeof nsUrl.fileURLToPath).toBe("function"); + expect(typeof nsUrl.pathToFileURL).toBe("function"); + }); + + // The export set is public API, declared in the iOS runtime's + // types/ns-url.d.ts and in docs/ns-builtin-modules.md; all of them must + // change together. + it("exposes exactly the declared surface", function () { + expect(Object.keys(nsUrl).sort()).toEqual([ + "URL", + "URLSearchParams", + "fileURLToPath", + "pathToFileURL", + ]); + }); + + it("exports the URL and URLSearchParams the globals hold", function () { + expect(nsUrl.URL).toBe(globalThis.URL); + expect(nsUrl.URLSearchParams).toBe(globalThis.URLSearchParams); + }); + + it("leaves URLPattern a global only", function () { + expect(typeof globalThis.URLPattern).toBe("function"); + expect("URLPattern" in nsUrl).toBe(false); + }); + + it("is a singleton per realm", function () { + expect(require("ns:url")).toBe(nsUrl); + }); + + it("resolves to the same module object through import", function (done) { + import("ns:url").then(function (ns) { + expect(ns.default).toBe(nsUrl); + expect(ns.URL).toBe(nsUrl.URL); + expect(ns.fileURLToPath).toBe(nsUrl.fileURLToPath); + done(); + }).catch(function (error) { + fail("import rejected: " + String((error && error.message) || error)); + done(); + }); + }); + + it("converts between paths and file URLs with its own URL", function () { + var url = nsUrl.pathToFileURL("/foo/bar baz.txt"); + expect(url instanceof nsUrl.URL).toBe(true); + expect(url.href).toBe("file:///foo/bar%20baz.txt"); + expect(nsUrl.fileURLToPath(url)).toBe("/foo/bar baz.txt"); + }); + + it("is re-exported member for member by a distinct, frozen node:url", function () { + var shim = require("node:url"); + expect(shim).not.toBe(nsUrl); + expect(Object.isFrozen(shim)).toBe(true); + expect(Object.keys(shim).sort()).toEqual(Object.keys(nsUrl).sort()); + Object.keys(nsUrl).forEach(function (name) { + expect(shim[name]).toBe(nsUrl[name]); + }); + }); + + it("hands a worker realm its own URL, not whatever the global names", function (done) { + var worker = new Worker("./nsUrlIdentityWorker.js"); + worker.onmessage = function (event) { + expect(event.data).toEqual({ isOriginal: true, isImpostor: false, frozen: true }); + worker.terminate(); + done(); + }; + worker.onerror = function (event) { + worker.terminate(); + fail("worker error: " + event.message); + done(); + }; + }); +}); diff --git a/test-app/app/src/main/assets/app/tests/testNsWorkerThreads.js b/test-app/app/src/main/assets/app/tests/testNsWorkerThreads.js new file mode 100644 index 000000000..d9f023f06 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/testNsWorkerThreads.js @@ -0,0 +1,87 @@ +describe("ns:worker_threads", function () { + var nsWorkerThreads = require("ns:worker_threads"); + + it("exposes frozen exports", function () { + expect(Object.isFrozen(nsWorkerThreads)).toBe(true); + expect(typeof nsWorkerThreads.Worker).toBe("function"); + }); + + // The export set is public API, declared in the iOS runtime's + // types/ns-worker-threads.d.ts and in docs/ns-builtin-modules.md; all of + // them must change together. + it("exposes exactly the declared surface", function () { + expect(Object.keys(nsWorkerThreads).sort()).toEqual(["Worker"]); + }); + + it("exports the Worker the global holds", function () { + expect(nsWorkerThreads.Worker).toBe(globalThis.Worker); + }); + + it("is a singleton per realm", function () { + expect(require("ns:worker_threads")).toBe(nsWorkerThreads); + }); + + it("resolves to the same module object through import", function (done) { + import("ns:worker_threads").then(function (ns) { + expect(ns.default).toBe(nsWorkerThreads); + expect(ns.Worker).toBe(nsWorkerThreads.Worker); + done(); + }).catch(function (error) { + fail("import rejected: " + String((error && error.message) || error)); + done(); + }); + }); + + it("is a distinct module object from the node:worker_threads shim", function () { + var shim = require("node:worker_threads"); + expect(shim).not.toBe(nsWorkerThreads); + expect(Object.isFrozen(shim)).toBe(true); + }); + + // Cross-platform code passes both platforms' option objects; each runtime + // reads its own and ignores the other's. + it("constructs a worker with the runtime's options, ignoring the iOS ones", function (done) { + var worker = new nsWorkerThreads.Worker("./workerOptionsPriorityWorker.js", { + android: { priority: "lessFavorable" }, + ios: { priority: "utility" }, + resourceLimits: { maxOldGenerationSizeMb: 64 }, + }); + var settled = false; + var finish = function () { + if (settled) { + return; + } + settled = true; + worker.terminate(); + done(); + }; + worker.onmessage = function (event) { + try { + expect(event.data.priority).toBe(1); + } finally { + finish(); + } + }; + worker.onerror = function (event) { + try { + expect(String(event.message)).toBe(""); + } finally { + finish(); + } + }; + }); + + it("hands a worker realm its own constructor, not whatever the global names", function (done) { + var worker = new Worker("./nsWorkerThreadsIdentityWorker.js"); + worker.onmessage = function (event) { + expect(event.data).toEqual({ isOriginal: true, isImpostor: false, frozen: true }); + worker.terminate(); + done(); + }; + worker.onerror = function (event) { + worker.terminate(); + fail("worker error: " + event.message); + done(); + }; + }); +}); diff --git a/test-app/app/src/main/assets/app/tests/testURLImpl.js b/test-app/app/src/main/assets/app/tests/testURLImpl.js index 680cc876d..bfc5576eb 100644 --- a/test-app/app/src/main/assets/app/tests/testURLImpl.js +++ b/test-app/app/src/main/assets/app/tests/testURLImpl.js @@ -110,5 +110,11 @@ describe("URL", function () { expect(new URL("https://XN--BCHER-KVA.example/").hostname).toBe("xn--bcher-kva.example"); expect(() => new URL("https://a\u200Db.example/")).toThrowError(TypeError); }); + + it("serializes to JSON as its href", function () { + const url = new URL("https://x.test/a?b#c"); + expect(url.toJSON()).toBe(url.href); + expect(JSON.stringify(url)).toBe(JSON.stringify(url.href)); + expect(JSON.stringify({ u: url })).toBe(JSON.stringify({ u: url.href })); }); - \ No newline at end of file +}); diff --git a/test-app/app/src/main/assets/app/tests/testURLSearchParamsImpl.js b/test-app/app/src/main/assets/app/tests/testURLSearchParamsImpl.js index ca29dbdb7..fdae913fc 100644 --- a/test-app/app/src/main/assets/app/tests/testURLSearchParamsImpl.js +++ b/test-app/app/src/main/assets/app/tests/testURLSearchParamsImpl.js @@ -657,14 +657,38 @@ describe("Test URLSearchParams ", function () { expect(keys.indexOf("_searchParams")).toBe(-1); expect(keys.indexOf("_searchParamsSource")).toBe(-1); - const serialized = JSON.stringify(url); - expect(serialized.indexOf("_searchParams")).toBe(-1); - expect(serialized.indexOf("_searchParamsSource")).toBe(-1); - for (const key in url) { expect(key).not.toBe("_searchParams"); expect(key).not.toBe("_searchParamsSource"); } }); + it("Test URL.searchParams deletes only the matching pair when given a value", function(){ + const url = new URL("https://x.test/?a=1&a=2"); + url.searchParams.delete("a", "1"); + expect(url.search).toBe("?a=2"); + expect(url.searchParams.getAll("a")).toEqual(["2"]); + }); + + it("Test URL.searchParams deletes every pair of the name when given no value", function(){ + const url = new URL("https://x.test/?a=1&a=2"); + url.searchParams.delete("a"); + expect(url.search).toBe(""); + expect(url.searchParams.getAll("a")).toEqual([]); + }); + + it("Test URL.searchParams applies a query change made while coercing arguments", function(){ + const delUrl = new URL("https://x.test/?a=1&b=2"); + delUrl.searchParams.delete("a", { toString() { delUrl.search = "?a=1&b=3"; return "1"; } }); + expect(delUrl.search).toBe("?b=3"); + + const appendUrl = new URL("https://x.test/?a=1"); + appendUrl.searchParams.append("b", { toString() { appendUrl.search = "?c=3"; return "2"; } }); + expect(appendUrl.search).toBe("?c=3&b=2"); + + const setUrl = new URL("https://x.test/?a=1"); + setUrl.searchParams.set({ toString() { setUrl.search = "?c=3"; return "a"; } }, "2"); + expect(setUrl.search).toBe("?c=3&a=2"); + }); + }); diff --git a/test-app/runtime/CMakeLists.txt b/test-app/runtime/CMakeLists.txt index a19bd052b..d5937c294 100644 --- a/test-app/runtime/CMakeLists.txt +++ b/test-app/runtime/CMakeLists.txt @@ -102,7 +102,9 @@ set(RUNTIME_BUILTIN_JS ${RUNTIME_BUILTIN_JS_DIR}/ns-interop.js ${RUNTIME_BUILTIN_JS_DIR}/ns-module.js ${RUNTIME_BUILTIN_JS_DIR}/ns-runtime.js + ${RUNTIME_BUILTIN_JS_DIR}/ns-url.js ${RUNTIME_BUILTIN_JS_DIR}/ns-util.js + ${RUNTIME_BUILTIN_JS_DIR}/ns-worker-threads.js ${RUNTIME_BUILTIN_JS_DIR}/performance.js ${RUNTIME_BUILTIN_JS_DIR}/primordials.js ${RUNTIME_BUILTIN_JS_DIR}/require-factory.js diff --git a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp index 74279aaaa..11d31a1f0 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp @@ -23,6 +23,7 @@ #include "ModuleInternal.h" #include "SimpleProfiler.h" #include "Runtime.h" +#include "RuntimeState.h" #include "WorkerMessage.h" #include "WorkerWrapper.h" #include @@ -1651,6 +1652,49 @@ bool ParseWorkerResourceLimits(Isolate *isolate, Local context, } // namespace +namespace { + +/* + * The constructor template InitWorkerConstructor put on the global template. + * A template's function is cached per context, so instantiating it again + * yields the very function the global was created with. + */ +struct WorkerConstructorState { + Global constructor; +}; + +} // namespace + +void CallbackHandlers::InitWorkerConstructor(Isolate *isolate, + Local globalTemplate) { + Local workerFuncTemplate = + FunctionTemplate::New(isolate, CallbackHandlers::NewThreadCallback); + Local prototype = workerFuncTemplate->PrototypeTemplate(); + + prototype->Set(ArgConverter::ConvertToV8String(isolate, "postMessage"), + FunctionTemplate::New(isolate, + CallbackHandlers::WorkerObjectPostMessageCallback)); + prototype->Set(ArgConverter::ConvertToV8String(isolate, "terminate"), + FunctionTemplate::New(isolate, + CallbackHandlers::WorkerObjectTerminateCallback)); + + globalTemplate->Set(ArgConverter::ConvertToV8String(isolate, "Worker"), workerFuncTemplate); + + if (auto *state = RuntimeState::For(isolate)) { + state->constructor.Reset(isolate, workerFuncTemplate); + } +} + +MaybeLocal CallbackHandlers::WorkerConstructor(Local context) { + Isolate *isolate = v8::Isolate::GetCurrent(); + auto *state = RuntimeState::For(isolate); + if (state == nullptr || state->constructor.IsEmpty()) { + isolate->ThrowError("The Worker constructor is not available in this runtime"); + return MaybeLocal(); + } + return state->constructor.Get(isolate)->GetFunction(context); +} + void CallbackHandlers::NewThreadCallback(const v8::FunctionCallbackInfo &args) { try { if (!args.IsConstructCall()) { diff --git a/test-app/runtime/src/main/cpp/CallbackHandlers.h b/test-app/runtime/src/main/cpp/CallbackHandlers.h index f58a19db7..cac625498 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.h +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.h @@ -164,6 +164,22 @@ namespace tns { static void NewThreadCallback(const v8::FunctionCallbackInfo &args); + /* + * Installs the `Worker` constructor on `globalTemplate` and keeps its + * template for WorkerConstructor. + */ + static void InitWorkerConstructor(v8::Isolate *isolate, + v8::Local globalTemplate); + + /* + * The Worker constructor of `context`: the function the template + * InitWorkerConstructor installed produces for it, which is the object + * the global of that name was created with, whatever + * `globalThis.Worker` names by now. Empty, with an exception pending, + * when the runtime is tearing down. + */ + static v8::MaybeLocal WorkerConstructor(v8::Local context); + /* * parent -> worker messaging * Fired when a Worker instance's postMessage is called. diff --git a/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp b/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp index d3f6de13d..6d652a6bd 100644 --- a/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp +++ b/test-app/runtime/src/main/cpp/NsBuiltinModules.cpp @@ -21,6 +21,8 @@ #include "StructuredSerialization.h" #include "TextEncoding.h" #include "TraceLog.h" +#include "URLImpl.h" +#include "URLSearchParamsImpl.h" #include "WrapperLifetime.h" #include "console/Console.h" #include "robin_hood.h" @@ -38,7 +40,9 @@ constexpr const char* kNodePrefix = "node:"; MaybeLocal NsInteropAndroidBinding(Local context); MaybeLocal NsModuleBinding(Local context); MaybeLocal NsRuntimeBinding(Local context); +MaybeLocal NsUrlBinding(Local context); MaybeLocal NsUtilBinding(Local context); +MaybeLocal NsWorkerThreadsBinding(Local context); struct Registration { const char* specifier; @@ -67,7 +71,9 @@ constexpr Registration kRegistry[] = { {"ns:interop/android", BuiltinId::kNsInteropAndroid, NsInteropAndroidBinding}, {"ns:module", BuiltinId::kNsModule, NsModuleBinding}, {"ns:runtime", BuiltinId::kNsRuntime, NsRuntimeBinding}, + {"ns:url", BuiltinId::kNsUrl, NsUrlBinding}, {"ns:util", BuiltinId::kNsUtil, NsUtilBinding}, + {"ns:worker_threads", BuiltinId::kNsWorkerThreads, NsWorkerThreadsBinding}, {"node:module", BuiltinId::kNodeModule, nullptr}, {"node:url", BuiltinId::kNodeUrl, nullptr}, {"node:util", BuiltinId::kNodeUtil, nullptr}, @@ -332,6 +338,45 @@ MaybeLocal NsRuntimeBinding(Local context) { return binding; } +/* + * URL and URLSearchParams for ns:url: the context's own, from the templates + * their Init installed, rather than whatever the globals name by the time the + * module is first required. + */ +MaybeLocal NsUrlBinding(Local context) { + Isolate* isolate = v8::Isolate::GetCurrent(); + Local binding = Object::New(isolate); + Local url; + Local searchParams; + if (!URLImpl::Constructor(context).ToLocal(&url) || + !URLSearchParamsImpl::Constructor(context).ToLocal(&searchParams) || + !binding->Set(context, ArgConverter::ConvertToV8String(isolate, "URL"), url) + .FromMaybe(false) || + !binding->Set(context, ArgConverter::ConvertToV8String(isolate, "URLSearchParams"), + searchParams) + .FromMaybe(false)) { + return MaybeLocal(); + } + return binding; +} + +/* + * The Worker constructor for ns:worker_threads: the context's own, from the + * template CallbackHandlers::InitWorkerConstructor installed, rather than + * whatever `globalThis.Worker` names by the time the module is first required. + */ +MaybeLocal NsWorkerThreadsBinding(Local context) { + Isolate* isolate = v8::Isolate::GetCurrent(); + Local binding = Object::New(isolate); + Local worker; + if (!CallbackHandlers::WorkerConstructor(context).ToLocal(&worker) || + !binding->Set(context, ArgConverter::ConvertToV8String(isolate, "Worker"), worker) + .FromMaybe(false)) { + return MaybeLocal(); + } + return binding; +} + /* * TextEncoder / TextDecoder for ns:util, read straight out of the * text-encoding builtin's per-isolate run, so the module's classes are the diff --git a/test-app/runtime/src/main/cpp/Runtime.cpp b/test-app/runtime/src/main/cpp/Runtime.cpp index a9d74baab..fdf465610 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -1082,11 +1082,8 @@ Isolate* Runtime::PrepareV8Runtime(const string& filesPath, FunctionTemplate::New(isolate, CallbackHandlers::RunOnMainThreadCallback)); FrameCallbacks::Init(isolate, globalTemplate); - globalTemplate->Set(ArgConverter::ConvertToV8String(isolate, "URL"), - URLImpl::GetCtor(isolate)); - globalTemplate->Set( - ArgConverter::ConvertToV8String(isolate, "URLSearchParams"), - URLSearchParamsImpl::GetCtor(isolate)); + URLImpl::Init(isolate, globalTemplate); + URLSearchParamsImpl::Init(isolate, globalTemplate); globalTemplate->Set(ArgConverter::ConvertToV8String(isolate, "URLPattern"), URLPatternImpl::GetCtor(isolate)); @@ -1117,28 +1114,7 @@ Isolate* Runtime::PrepareV8Runtime(const string& filesPath, * may be created from the main thread or from within other workers * (mirroring the iOS runtime). */ - { - Local workerFuncTemplate = - FunctionTemplate::New(isolate, CallbackHandlers::NewThreadCallback); - Local prototype = workerFuncTemplate->PrototypeTemplate(); - - /* - * Attach methods from the EventTarget interface (postMessage, terminate) to - * the Worker object prototype - */ - auto postMessageFuncTemplate = FunctionTemplate::New( - isolate, CallbackHandlers::WorkerObjectPostMessageCallback); - auto terminateWorkerFuncTemplate = FunctionTemplate::New( - isolate, CallbackHandlers::WorkerObjectTerminateCallback); - - prototype->Set(ArgConverter::ConvertToV8String(isolate, "postMessage"), - postMessageFuncTemplate); - prototype->Set(ArgConverter::ConvertToV8String(isolate, "terminate"), - terminateWorkerFuncTemplate); - - globalTemplate->Set(ArgConverter::ConvertToV8String(isolate, "Worker"), - workerFuncTemplate); - } + CallbackHandlers::InitWorkerConstructor(isolate, globalTemplate); // Unhandled-promise-rejection tracker; fed by the SetPromiseRejectCallback // above and drained via an event-loop task once per looper turn. diff --git a/test-app/runtime/src/main/cpp/URLImpl.cpp b/test-app/runtime/src/main/cpp/URLImpl.cpp index cc44c7d11..ac1339043 100644 --- a/test-app/runtime/src/main/cpp/URLImpl.cpp +++ b/test-app/runtime/src/main/cpp/URLImpl.cpp @@ -6,9 +6,24 @@ #include +#include "RuntimeState.h" + using namespace tns; using namespace ada; +namespace { + +/* + * The constructor template Init put on the global template. A template's + * function is cached per context, so instantiating it again yields the very + * function the global was created with. + */ +struct URLConstructorState { + v8::Global constructor; +}; + +} // namespace + URLImpl::URLImpl(url_aggregator url) : url_(std::move(url)) {} URLImpl *URLImpl::GetPointer(v8::Local object) { @@ -26,6 +41,25 @@ url_aggregator *URLImpl::GetURL() { return &this->url_; } +void URLImpl::Init(v8::Isolate *isolate, v8::Local globalTemplate) { + v8::Local ctorTmpl = GetCtor(isolate); + globalTemplate->Set(ArgConverter::ConvertToV8String(isolate, "URL"), ctorTmpl); + + if (auto *state = RuntimeState::For(isolate)) { + state->constructor.Reset(isolate, ctorTmpl); + } +} + +v8::MaybeLocal URLImpl::Constructor(v8::Local context) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + auto *state = RuntimeState::For(isolate); + if (state == nullptr || state->constructor.IsEmpty()) { + isolate->ThrowError("The URL constructor is not available in this runtime"); + return v8::MaybeLocal(); + } + return state->constructor.Get(isolate)->GetFunction(context); +} + v8::Local URLImpl::GetCtor(v8::Isolate *isolate) { v8::Local ctorTmpl = v8::FunctionTemplate::New(isolate, Ctor); ctorTmpl->SetClassName(ArgConverter::ConvertToV8String(isolate, "URL")); @@ -79,6 +113,10 @@ v8::Local URLImpl::GetCtor(v8::Isolate *isolate) { tmpl->Set(ArgConverter::ConvertToV8String(isolate, "toString"), v8::FunctionTemplate::New(isolate, &ToString)); + // WHATWG defines toJSON as the href serialization, the same as toString. + tmpl->Set(ArgConverter::ConvertToV8String(isolate, "toJSON"), + v8::FunctionTemplate::New(isolate, &ToString)); + ctorTmpl->Set(ArgConverter::ConvertToV8String(isolate, "canParse"), v8::FunctionTemplate::New(isolate, &CanParse)); diff --git a/test-app/runtime/src/main/cpp/URLImpl.h b/test-app/runtime/src/main/cpp/URLImpl.h index 8ad166da3..3d45584b8 100644 --- a/test-app/runtime/src/main/cpp/URLImpl.h +++ b/test-app/runtime/src/main/cpp/URLImpl.h @@ -22,6 +22,20 @@ namespace tns { static v8::Local GetCtor(v8::Isolate *isolate); + /* + * Installs the `URL` constructor on `globalTemplate` and keeps its + * template for Constructor. + */ + static void Init(v8::Isolate *isolate, v8::Local globalTemplate); + + /* + * The URL constructor of `context`: the function Init's template + * produces for it, which is the object the global of that name was + * created with, whatever `globalThis.URL` names by now. Empty, with an + * exception pending, when the runtime is tearing down. + */ + static v8::MaybeLocal Constructor(v8::Local context); + static void Ctor(const v8::FunctionCallbackInfo &args); diff --git a/test-app/runtime/src/main/cpp/URLSearchParamsImpl.cpp b/test-app/runtime/src/main/cpp/URLSearchParamsImpl.cpp index c47afdf20..207a688d7 100644 --- a/test-app/runtime/src/main/cpp/URLSearchParamsImpl.cpp +++ b/test-app/runtime/src/main/cpp/URLSearchParamsImpl.cpp @@ -4,9 +4,21 @@ #include "URLSearchParamsImpl.h" +#include "RuntimeState.h" + using namespace ada; namespace tns { + namespace { + + // The constructor template Init put on the global template; see + // URLConstructorState in URLImpl.cpp. + struct URLSearchParamsConstructorState { + v8::Global constructor; + }; + + } // namespace + URLSearchParamsImpl::URLSearchParamsImpl(ada::url_search_params params) : params_(params) {} URLSearchParamsImpl *URLSearchParamsImpl::GetPointer(v8::Local object) { @@ -23,6 +35,28 @@ namespace tns { return static_cast(ptr); } + void URLSearchParamsImpl::Init(v8::Isolate *isolate, + v8::Local globalTemplate) { + v8::Local ctorTmpl = GetCtor(isolate); + globalTemplate->Set(ArgConverter::ConvertToV8String(isolate, "URLSearchParams"), + ctorTmpl); + + if (auto *state = RuntimeState::For(isolate)) { + state->constructor.Reset(isolate, ctorTmpl); + } + } + + v8::MaybeLocal URLSearchParamsImpl::Constructor( + v8::Local context) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + auto *state = RuntimeState::For(isolate); + if (state == nullptr || state->constructor.IsEmpty()) { + isolate->ThrowError("The URLSearchParams constructor is not available in this runtime"); + return v8::MaybeLocal(); + } + return state->constructor.Get(isolate)->GetFunction(context); + } + v8::Local URLSearchParamsImpl::GetCtor(v8::Isolate *isolate) { v8::Local ctorTmpl = v8::FunctionTemplate::New(isolate, Ctor); ctorTmpl->SetClassName(ArgConverter::ConvertToV8String(isolate, "URLSearchParams")); diff --git a/test-app/runtime/src/main/cpp/URLSearchParamsImpl.h b/test-app/runtime/src/main/cpp/URLSearchParamsImpl.h index d8f225ac2..5feeba46c 100644 --- a/test-app/runtime/src/main/cpp/URLSearchParamsImpl.h +++ b/test-app/runtime/src/main/cpp/URLSearchParamsImpl.h @@ -21,6 +21,15 @@ namespace tns { static v8::Local GetCtor(v8::Isolate *isolate); + /* + * Installs the `URLSearchParams` constructor on `globalTemplate` and + * keeps its template for Constructor. + */ + static void Init(v8::Isolate *isolate, v8::Local globalTemplate); + + /* The URLSearchParams constructor of `context`, as URLImpl::Constructor. */ + static v8::MaybeLocal Constructor(v8::Local context); + static void Ctor(const v8::FunctionCallbackInfo &args); static void Append(const v8::FunctionCallbackInfo &args); diff --git a/test-app/runtime/src/main/cpp/js/README.md b/test-app/runtime/src/main/cpp/js/README.md index cbf5ecdc3..f6aa9ef92 100644 --- a/test-app/runtime/src/main/cpp/js/README.md +++ b/test-app/runtime/src/main/cpp/js/README.md @@ -68,8 +68,9 @@ module.exports = somethingTheCallSiteNeeds; - `ns-module.js` is the `ns:module` loader-control surface and `ns-runtime.js` is the `ns:runtime` live config surface (`setConfig`/`getConfig`). - `node-module.js` re-exports `ns:module`'s `createRequire` as the `node:module` - shim, and `node-url.js` is the `node:url` shim (`fileURLToPath` / - `pathToFileURL`), the one shim with no `ns:` counterpart to adapt. + shim, and `node-url.js` re-exports `ns-url.js`'s `ns:url` (the runtime's + `URL` / `URLSearchParams` plus `fileURLToPath` / `pathToFileURL`) as the + `node:url` shim. - `ns-interop.js` is `ns:interop` (empty on Android) and `ns-interop-android.js` is `ns:interop/android` (the numeric casts and `newArray`). The legacy globals they back — `interop`, `long`…`double`, `Array.create` — are @@ -101,9 +102,10 @@ join by adding a row to `kLazyGlobals`. Two neighbours of that set are deliberately not in it. `worker-events.js` is **eager**: it defines the handler attributes on `Worker.prototype` and the worker global scope, which have to exist before app code assigns one. -`node-worker-threads.js` is a **public builtin module** (`node:worker_threads`) -rather than a lazy global — it is reached by specifier, so nothing places a -name for it. +`node-worker-threads.js` (`node:worker_threads`) and `ns-worker-threads.js` +(`ns:worker_threads`, the runtime's own `Worker`, which the shim wraps) are +**public builtin modules** rather than lazy globals — they are reached by +specifier, so nothing places a name for them. An **eager** file can also feed the tier: `events.js` (eager, `Events::Init`) exports `CustomEvent`, and the `CustomEvent` row reads it through the same diff --git a/test-app/runtime/src/main/cpp/js/blob-url.js b/test-app/runtime/src/main/cpp/js/blob-url.js index c75c4efd0..6620b3314 100644 --- a/test-app/runtime/src/main/cpp/js/blob-url.js +++ b/test-app/runtime/src/main/cpp/js/blob-url.js @@ -98,19 +98,35 @@ ObjectDefineProperty(URL.prototype, 'searchParams', { }); params._forEach = params.forEach; params._append = params.append; + // Arguments are coerced before resync so a toString that assigns + // url.search lands before the params are rebuilt from it. params.append = function (name, value) { + name = `${name}`; + value = `${value}`; resync(this); this._append(name, value); writeBack(this); }; params._delete = params.delete; - params.delete = function (name) { + params.delete = function (name, value) { + name = `${name}`; + // An undefined value means name-only deletion. + const hasValue = value !== undefined; + if (hasValue) { + value = `${value}`; + } resync(this); - this._delete(name); + if (hasValue) { + this._delete(name, value); + } else { + this._delete(name); + } writeBack(this); }; params._set = params.set; params.set = function (name, value) { + name = `${name}`; + value = `${value}`; resync(this); this._set(name, value); writeBack(this); diff --git a/test-app/runtime/src/main/cpp/js/node-url.js b/test-app/runtime/src/main/cpp/js/node-url.js index d499e1b64..7604c0e23 100644 --- a/test-app/runtime/src/main/cpp/js/node-url.js +++ b/test-app/runtime/src/main/cpp/js/node-url.js @@ -1,104 +1,16 @@ "use strict"; -// The `node:url` compatibility shim: the two path/URL converters -// (docs/ns-builtin-modules.md). Parsing goes through the URL intrinsic rather -// than a hand-rolled scan, so authority normalization (`file://localhost/x` -// has no host, per the URL spec), percent-decoding and path canonicalization -// all follow the spec instead of an approximation. +// The `node:url` compatibility shim over `ns:url` (docs/ns-builtin-modules.md). +// The two surfaces coincide today, so this only re-exports; any adaptation to +// Node's API belongs here, never in the standard module. -const { - decodeURIComponent, - ObjectFreeze, - StringPrototypeCharCodeAt, - StringPrototypeStartsWith, - TypeError, - URL, -} = primordials; - -const INVALID_ARG = - 'The "path" argument must be of type string or an instance of URL.'; - -function toUrl(input) { - let href; - if (typeof input === "string") { - href = input; - } else if (input !== null && typeof input === "object" && - typeof input.href === "string") { - // Duck-typed so a URL from another realm still works. - href = input.href; - } else { - throw new TypeError(INVALID_ARG); - } - - try { - return new URL(href); - } catch { - throw new TypeError(INVALID_ARG); - } -} - -function fileURLToPath(input) { - const url = toUrl(input); - - if (url.protocol !== "file:") { - throw new TypeError("The URL must be of scheme file"); - } - // The URL parser already folded a "localhost" authority to the empty host, - // so anything left here is a real remote host and names no local file. - if (url.hostname !== "") { - throw new TypeError('File URL host must be "localhost" or empty'); - } - - // `pathname` carries neither the query nor the fragment. - const pathname = url.pathname; - for (let i = 0; i < pathname.length; i++) { - if (pathname[i] !== "%") { - continue; - } - // %2F would decode to a separator and silently change the path's shape. - const third = StringPrototypeCharCodeAt(pathname, i + 2) | 0x20; - if (pathname[i + 1] === "2" && third === 102 /* 'f' */) { - throw new TypeError("File URL path must not include encoded / characters"); - } - } +const { ObjectFreeze } = primordials; +const { URL, URLSearchParams, fileURLToPath, pathToFileURL } = + require("ns:url"); - return decodeURIComponent(pathname); -} - -const kHexDigits = "0123456789ABCDEF"; - -// Percent-encode everything the URL parser would otherwise read as syntax (or -// reject), leaving `/` as the separator it is. Non-ASCII is left alone: the -// parser UTF-8 encodes it correctly on its own. -function encodePathChars(filepath) { - let encoded = ""; - for (let i = 0; i < filepath.length; i++) { - const char = filepath[i]; - const code = StringPrototypeCharCodeAt(filepath, i); - const mustEncode = - code < 0x21 || code === 0x7f || char === "%" || char === "?" || - char === "#" || char === "\\" || char === '"' || char === "<" || - char === ">" || char === "`" || char === "{" || char === "}"; - if (mustEncode) { - encoded += "%" + kHexDigits[(code >> 4) & 0xf] + kHexDigits[code & 0xf]; - } else { - encoded += char; - } - } - return encoded; -} - -function pathToFileURL(filepath) { - if (typeof filepath !== "string") { - throw new TypeError('The "path" argument must be of type string.'); - } - // Node resolves a relative path against the process working directory; there - // is no such thing here, so a relative path has no single correct answer. - if (!StringPrototypeStartsWith(filepath, "/")) { - throw new TypeError('The "path" argument must be an absolute path.'); - } - - return new URL("file://" + encodePathChars(filepath)); -} - -module.exports = ObjectFreeze({ fileURLToPath, pathToFileURL }); +module.exports = ObjectFreeze({ + URL, + URLSearchParams, + fileURLToPath, + pathToFileURL, +}); diff --git a/test-app/runtime/src/main/cpp/js/node-worker-threads.js b/test-app/runtime/src/main/cpp/js/node-worker-threads.js index 95d232b93..a71bcf0dd 100644 --- a/test-app/runtime/src/main/cpp/js/node-worker-threads.js +++ b/test-app/runtime/src/main/cpp/js/node-worker-threads.js @@ -59,9 +59,11 @@ function getCreateMessageEvent() { } const g = globalThis; -// The platform constructor this shim wraps, and the worker scope's channel -// back to its parent. -const NativeWorker = g.Worker; +// The platform constructor this shim wraps, taken from the standard module +// rather than from the global so an app that reassigns `globalThis.Worker` +// does not redirect the shim, and the worker scope's channel back to its +// parent. +const { Worker: NativeWorker } = require("ns:worker_threads"); const globalPostMessage = g.postMessage; const addEventListener = EventTarget.prototype.addEventListener; diff --git a/test-app/runtime/src/main/cpp/js/ns-url.js b/test-app/runtime/src/main/cpp/js/ns-url.js new file mode 100644 index 000000000..07d06ce8f --- /dev/null +++ b/test-app/runtime/src/main/cpp/js/ns-url.js @@ -0,0 +1,111 @@ +"use strict"; + +// The `ns:url` builtin module: the runtime's own URL and URLSearchParams, the +// very functions the globals of those names were created with, and the two +// path/URL converters. See docs/ns-builtin-modules.md for the contract. +// +// The converters parse through URL rather than a hand-rolled scan, so +// authority normalization (`file://localhost/x` has no host, per the URL +// spec), percent-decoding and path canonicalization all follow the spec +// instead of an approximation. + +const { URL, URLSearchParams } = binding; +const { + decodeURIComponent, + ObjectFreeze, + StringPrototypeCharCodeAt, + StringPrototypeStartsWith, + TypeError, +} = primordials; + +const INVALID_ARG = + 'The "path" argument must be of type string or an instance of URL.'; + +function toUrl(input) { + let href; + if (typeof input === "string") { + href = input; + } else if (input !== null && typeof input === "object" && + typeof input.href === "string") { + // Duck-typed so a URL from another realm still works. + href = input.href; + } else { + throw new TypeError(INVALID_ARG); + } + + try { + return new URL(href); + } catch { + throw new TypeError(INVALID_ARG); + } +} + +function fileURLToPath(input) { + const url = toUrl(input); + + if (url.protocol !== "file:") { + throw new TypeError("The URL must be of scheme file"); + } + // The URL parser already folded a "localhost" authority to the empty host, + // so anything left here is a real remote host and names no local file. + if (url.hostname !== "") { + throw new TypeError('File URL host must be "localhost" or empty'); + } + + // `pathname` carries neither the query nor the fragment. + const pathname = url.pathname; + for (let i = 0; i < pathname.length; i++) { + if (pathname[i] !== "%") { + continue; + } + // %2F would decode to a separator and silently change the path's shape. + const third = StringPrototypeCharCodeAt(pathname, i + 2) | 0x20; + if (pathname[i + 1] === "2" && third === 102 /* 'f' */) { + throw new TypeError("File URL path must not include encoded / characters"); + } + } + + return decodeURIComponent(pathname); +} + +const kHexDigits = "0123456789ABCDEF"; + +// Percent-encode everything the URL parser would otherwise read as syntax (or +// reject), leaving `/` as the separator it is. Non-ASCII is left alone: the +// parser UTF-8 encodes it correctly on its own. +function encodePathChars(filepath) { + let encoded = ""; + for (let i = 0; i < filepath.length; i++) { + const char = filepath[i]; + const code = StringPrototypeCharCodeAt(filepath, i); + const mustEncode = + code < 0x21 || code === 0x7f || char === "%" || char === "?" || + char === "#" || char === "\\" || char === '"' || char === "<" || + char === ">" || char === "`" || char === "{" || char === "}"; + if (mustEncode) { + encoded += "%" + kHexDigits[(code >> 4) & 0xf] + kHexDigits[code & 0xf]; + } else { + encoded += char; + } + } + return encoded; +} + +function pathToFileURL(filepath) { + if (typeof filepath !== "string") { + throw new TypeError('The "path" argument must be of type string.'); + } + // Node resolves a relative path against the process working directory; there + // is no such thing here, so a relative path has no single correct answer. + if (!StringPrototypeStartsWith(filepath, "/")) { + throw new TypeError('The "path" argument must be an absolute path.'); + } + + return new URL("file://" + encodePathChars(filepath)); +} + +exports.URL = URL; +exports.URLSearchParams = URLSearchParams; +exports.fileURLToPath = fileURLToPath; +exports.pathToFileURL = pathToFileURL; +ObjectFreeze(exports); diff --git a/test-app/runtime/src/main/cpp/js/ns-worker-threads.js b/test-app/runtime/src/main/cpp/js/ns-worker-threads.js new file mode 100644 index 000000000..488439bf3 --- /dev/null +++ b/test-app/runtime/src/main/cpp/js/ns-worker-threads.js @@ -0,0 +1,12 @@ +"use strict"; + +// The `ns:worker_threads` builtin module: the runtime's own Worker, the very +// function the global of that name was created with. See +// docs/ns-builtin-modules.md for the contract and docs/worker-threads.md for +// the constructor's options. + +const { Worker } = binding; +const { ObjectFreeze } = primordials; + +exports.Worker = Worker; +ObjectFreeze(exports); diff --git a/types/index.d.ts b/types/index.d.ts new file mode 100644 index 000000000..3c8a4f6f9 --- /dev/null +++ b/types/index.d.ts @@ -0,0 +1,23 @@ +// Type declarations for this runtime's additions to the public `ns:` builtin +// modules. +// +// The iOS runtime's package (@nativescript/ios, types/index.d.ts) is the +// source of truth for the cross-platform `ns:` modules. Two `declare module` +// blocks that both declare the same value conflict, so the files here never +// redeclare what those declare: each adds only the Android-specific names and +// merges into the iOS declarations. A program that includes only these files +// therefore sees the Android additions but not the shared surface (for +// instance `ns:worker_threads`'s `Worker`); include the iOS types as well for +// the whole module. +// +// `ns:` is not a resolvable package specifier, so these are ambient +// declarations: they apply program-wide once this file is in the TypeScript +// program. Pull it in with either +// +// /// +// +// or a tsconfig entry: +// +// { "include": ["node_modules/@nativescript/android/types/index.d.ts"] } + +/// diff --git a/types/ns-worker-threads-android.d.ts b/types/ns-worker-threads-android.d.ts new file mode 100644 index 000000000..74bf5c5c2 --- /dev/null +++ b/types/ns-worker-threads-android.d.ts @@ -0,0 +1,57 @@ +// Android's additions to `ns:worker_threads`. The iOS runtime's +// types/ns-worker-threads.d.ts (@nativescript/ios) owns the module itself: +// `Worker`, `WorkerOptions`, `resourceLimits` and the event shapes. This file +// declares only names that one does not, so the two merge whichever is read +// first. It must stay a script (no top-level import or export): as a module, +// the block below would become an augmentation and fail in a program without +// the iOS declarations. + +declare module "ns:worker_threads" { + /** + * An `android.os.Process` thread priority: one of its `THREAD_PRIORITY_*` + * constants by camelCase name, or a nice value. A number outside -20..19 is + * clamped into it; `NaN` throws a `TypeError`. Lowering a thread's nice + * value below 0 may need a privilege the app does not hold. + */ + export type WorkerAndroidPriority = + | "lowest" + | "background" + | "lessFavorable" + | "default" + | "moreFavorable" + | "foreground" + | "display" + | "urgentDisplay" + | "video" + | "audio" + | "urgentAudio" + | number; + + /** + * Android-specific worker options. A non-object value throws a + * `TypeError`; keys the runtime does not know are ignored. + */ + export interface WorkerAndroidOptions { + /** + * The worker thread's priority; `"background"` when omitted. A value + * that is neither a known name nor a number throws a `TypeError`. Wins + * over the deprecated top-level `androidPriority` when both are given. + */ + priority?: WorkerAndroidPriority; + } + + export interface WorkerOptions { + android?: WorkerAndroidOptions | null; + /** @deprecated Use `android.priority`, which wins when both are given. */ + androidPriority?: WorkerAndroidPriority; + } +} + +// The same members on the script-level `WorkerOptions`, which the iOS +// declarations and the DOM libs also merge into, so the options type-check on +// the global constructor too. +interface WorkerOptions { + android?: import("ns:worker_threads").WorkerAndroidOptions | null; + /** @deprecated Use `android.priority`, which wins when both are given. */ + androidPriority?: import("ns:worker_threads").WorkerAndroidPriority; +}