Skip to content

Commit da341c0

Browse files
committed
feat(runtime): ns:interop builtin modules, interop globals as compat
Add the ns:interop and ns:interop/android builtin modules and move escapeException onto ns:runtime, per rfcs#58 ("interop and runtime helpers", adoption step 0). - ns:interop: frozen and empty on Android (none of the cross-platform native-memory members exist here). - ns:interop/android: long, byte, short, char, float, double and newArray (the function Array.create has always been). - ns:runtime: gains escapeException. The natives move from being set on the global (template casts, Interop::Init, ArrayHelper::Init) to binding factories in NsBuiltinModules.cpp. The legacy globals are now assembled by interop-globals.js, an internal-tier builtin run eagerly at the point the interop global was installed: it requires ns:runtime and ns:interop/android and assigns their functions, so interop.escapeException, the cast globals and Array.create are the module exports themselves, with the same writable/enumerable/configurable attributes as before.
1 parent e15d21a commit da341c0

22 files changed

Lines changed: 417 additions & 81 deletions

‎docs/ns-builtin-modules.md‎

Lines changed: 77 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -95,13 +95,22 @@ Node's single-quoted style.
9595

9696
### `ns:runtime`
9797

98-
Runtime-level configuration. Keys, value domains, and scope are defined and
99-
validated natively; the module surface is a thin frozen wrapper.
98+
Runtime-level configuration and runtime plumbing. Keys, value domains, and
99+
scope are defined and validated natively; the module surface is a thin frozen
100+
wrapper.
100101

101102
| export | description |
102103
|---|---|
103104
| `setConfig(key, value)` | Sets a runtime config key. Throws `TypeError` on an unknown key, an invalid value, or (for process-wide keys) when called from a worker isolate. |
104105
| `getConfig(key)` | Returns the current value of a config key. Throws `TypeError` on an unknown key. Readable from any isolate. |
106+
| `escapeException(x)` | Returns an `Error` branded so that, when it is thrown back across a native callback boundary, the native caller receives the original native exception `x` carries rather than the runtime's wrapper exception. Idempotent: a branded error is returned unchanged. Throws `TypeError` when called with no argument. The global `interop.escapeException` is this same function (see [Legacy globals](#legacy-globals)). |
107+
108+
*Platform note (Android):* the original exception is the Java throwable `x`
109+
wraps, or its `nativeException`; a Java `catch` of the concrete type then
110+
matches instead of receiving a `com.tns.NativeScriptException`. A branded error
111+
with no underlying throwable escapes as a `com.tns.NativeScriptException`
112+
carrying the JS message and stack, as an unbranded one does, but bypasses
113+
`discardUncaughtJsExceptions`.
105114

106115
Config keys:
107116

@@ -170,6 +179,53 @@ a release build that cannot be diagnosed.
170179
`TNS.esm`, `TNS.fetch`, `TNS.registry` — so `adb logcat -s TNS.esm` can filter
171180
them without matching message text.
172181

182+
### `ns:interop`
183+
184+
The cross-platform interop surface: working with native values, as opposed to
185+
finding native symbols. It exists on every platform with whatever members that
186+
platform supports, so a feature check (`"Pointer" in interop`) is how portable
187+
code asks; a member a platform lacks is absent, never present-but-throwing.
188+
189+
On Android the namespace is **empty**: Android has none of the native-memory
190+
members iOS exports here (`Pointer`, `Reference`, `sizeof`, …). It is still a
191+
frozen module, so `import * as interop from "ns:interop"` resolves everywhere.
192+
193+
### `ns:interop/android`
194+
195+
Java-specific interop helpers. Android only: on other platforms the specifier
196+
is not registered and fails like any unknown builtin.
197+
198+
| export | description |
199+
|---|---|
200+
| `long(x)`, `byte(x)`, `short(x)`, `char(x)`, `float(x)`, `double(x)` | Mark a JS value as the named Java primitive, for overload resolution and argument conversion: `method(long("123456789012"))` picks the `long` overload and passes the full 64-bit value. Each takes exactly one argument. |
201+
| `newArray(type, length)` | Creates a Java array of `length` elements. `type` is a primitive type name (`"int"`, `"char"`, `"boolean"`, …), a fully qualified Java class name (`"java.lang.String"`), or a Java class constructor (`java.lang.String`). Throws on any other arity, a non-integer or negative length, or a class name that does not resolve. |
202+
203+
```js
204+
import { long, newArray } from "ns:interop/android";
205+
206+
const bytes = newArray("byte", 1024); // byte[1024]
207+
const names = newArray(java.lang.String, 3); // String[3]
208+
someJavaObject.setTimestamp(long(Date.now()));
209+
```
210+
211+
### Legacy globals
212+
213+
Before these modules existed the same functions were reachable only as
214+
globals, and app code and `@nativescript/core` read them at module top level.
215+
They remain, installed before any app code runs, as **aliases of the module
216+
exports** — the very same function objects, per realm:
217+
218+
| global | module export |
219+
|---|---|
220+
| `interop.escapeException` | `ns:runtime`'s `escapeException` |
221+
| `long`, `byte`, `short`, `char`, `float`, `double` (Android) | `ns:interop/android`'s members of those names |
222+
| `Array.create` (Android) | `ns:interop/android`'s `newArray` |
223+
224+
The global `interop` object, the cast globals and `Array.create` are ordinary
225+
writable, enumerable, configurable data properties. On Android the global
226+
`interop` has exactly one member, `escapeException`; it is a plain object, not
227+
the `ns:interop` namespace. New code should import from the modules.
228+
173229
### `ns:module`
174230

175231
The module-loader control surface: import-map vocabulary, registry
@@ -729,16 +785,19 @@ resolvers read the same table differently:
729785
- The **`ns:`/`node:` resolver** — the app-facing one, behind `require()`,
730786
`import` and `import()` — serves only rows *not* marked internal-only. An
731787
internal-only specifier fails exactly as a name absent from the table does.
732-
Seven rows are public today: `ns:module`, `ns:runtime`, `ns:util`,
733-
`node:module`, `node:url`, `node:util`, `node:worker_threads`.
788+
Nine rows are public today: `ns:interop`, `ns:interop/android`, `ns:module`,
789+
`ns:runtime`, `ns:util`, `node:module`, `node:url`, `node:util`,
790+
`node:worker_threads`.
734791
- The **internal require** builtins receive (previous section) is the only
735-
thing that can name an internal-only row. Six rows are marked that way:
792+
thing that can name an internal-only row. Seven rows are marked that way:
736793
`internal/broadcast-channel`, `internal/dom-exception`, `internal/events`,
737-
`internal/message-channel`, `internal/message-event`,
738-
`internal/worker-events`. Their exports carry capabilities app code must not
739-
hold — listener-accounting hook keys, the error-reporter setter, the key a
740-
worker's rebuilt error travels under, base classes that must be the
741-
runtime's own rather than whatever a global currently names.
794+
`internal/interop-globals`, `internal/message-channel`,
795+
`internal/message-event`, `internal/worker-events`. Their exports carry
796+
capabilities app code must not hold — listener-accounting hook keys, the
797+
error-reporter setter, the key a worker's rebuilt error travels under, base
798+
classes that must be the runtime's own rather than whatever a global
799+
currently names — or, for `internal/interop-globals`, install the legacy
800+
globals.
742801
- Builtins with **no row at all** (the intrinsics snapshot, the require
743802
factory, the console formatter) are invoked straight from their native call
744803
sites. There is no specifier that could reach them and nothing to mark.
@@ -777,8 +836,14 @@ internal require is a fixed parameter of the builtin function wrapper
777836
The files under `js/` that are *not* in the public registry — `primordials.js`,
778837
`require-factory.js`, `inspect.js`, `json-helper.js`, `events.js`,
779838
`error-events.js`, `structured-clone.js`, `blob-url.js`, `performance.js`,
780-
`weak-ref.js` — are the internal builtins: each is run from its own native call
781-
site and none is named in the registry table.
839+
`weak-ref.js`, `interop-globals.js` — are the internal builtins: each is run
840+
from its own native call site and none is named in the public registry.
841+
842+
`interop-globals.js` is the [legacy globals](#legacy-globals) layer. It runs
843+
eagerly from `Runtime::PrepareV8Runtime` in every isolate, requires
844+
`ns:runtime` and `ns:interop/android` through the internal require and assigns
845+
their functions to the globals, so the compat knowledge lives only in that
846+
consumer and neither module refers to it.
782847
783848
Per-realm builtin state — the exports objects, the synthetic modules, the
784849
in-progress set that produces the circular-require error, the cached `format`,

‎test-app/app/src/main/assets/app/mainpage.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ require('./tests/testInspect');
103103
// The ns:/node: builtin modules
104104
require('./tests/testNsUtil');
105105
require('./tests/testNsRuntime');
106+
require('./tests/testNsInterop');
106107
require('./tests/testNsModule');
107108
// Remote-module security gate (debug builds allow remote modules outright)
108109
require('./tests/testRemoteModuleSecurity');
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
// Static `import` of the interop builtins, so the ES module resolve callback
2+
// handles a specifier with a path segment (`ns:interop/android`).
3+
import interopDefault from "ns:interop";
4+
import androidDefault, { long, newArray } from "ns:interop/android";
5+
import { escapeException } from "ns:runtime";
6+
7+
export { interopDefault, androidDefault, long, newArray, escapeException };
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// The compat globals are assembled per isolate, so a worker's globals must be
2+
// its own module instance's functions.
3+
onmessage = function () {
4+
var android = require("ns:interop/android");
5+
var runtime = require("ns:runtime");
6+
postMessage({
7+
casts: ["long", "byte", "short", "char", "float", "double"].every(function (name) {
8+
return globalThis[name] === android[name];
9+
}),
10+
newArray: Array.create === android.newArray,
11+
escapeException: interop.escapeException === runtime.escapeException,
12+
arrayLength: android.newArray("int", 4).length,
13+
});
14+
};
Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
var CAST_NAMES = ["long", "byte", "short", "char", "float", "double"];
2+
3+
describe("ns:interop", function () {
4+
var nsInterop = require("ns:interop");
5+
6+
// Android has none of the cross-platform interop members iOS exports.
7+
it("is an empty frozen namespace", function () {
8+
expect(Object.isFrozen(nsInterop)).toBe(true);
9+
expect(Object.keys(nsInterop)).toEqual([]);
10+
});
11+
12+
it("is a singleton across require calls", function () {
13+
expect(require("ns:interop")).toBe(nsInterop);
14+
});
15+
});
16+
17+
describe("ns:interop/android", function () {
18+
var android = require("ns:interop/android");
19+
20+
it("exposes exactly the declared surface, frozen", function () {
21+
expect(Object.isFrozen(android)).toBe(true);
22+
expect(Object.keys(android).sort()).toEqual(
23+
["byte", "char", "double", "float", "long", "newArray", "short"]);
24+
Object.keys(android).forEach(function (name) {
25+
expect(typeof android[name]).toBe("function");
26+
});
27+
});
28+
29+
it("is a singleton across require calls", function () {
30+
expect(require("ns:interop/android")).toBe(android);
31+
});
32+
33+
it("backs the cast globals with the same function objects", function () {
34+
CAST_NAMES.forEach(function (name) {
35+
expect(globalThis[name]).toBe(android[name]);
36+
});
37+
});
38+
39+
it("backs Array.create with newArray", function () {
40+
expect(Array.create).toBe(android.newArray);
41+
});
42+
43+
it("keeps the globals ordinary writable, enumerable, configurable properties", function () {
44+
CAST_NAMES.forEach(function (name) {
45+
var descriptor = Object.getOwnPropertyDescriptor(globalThis, name);
46+
expect(descriptor.writable).toBe(true);
47+
expect(descriptor.enumerable).toBe(true);
48+
expect(descriptor.configurable).toBe(true);
49+
});
50+
var create = Object.getOwnPropertyDescriptor(Array, "create");
51+
expect(create.writable).toBe(true);
52+
expect(create.enumerable).toBe(true);
53+
expect(create.configurable).toBe(true);
54+
});
55+
56+
it("marks numbers for Java overload resolution", function () {
57+
var n = new com.tns.tests.NumericConversionTest();
58+
expect(n.method5(android.long("123456789012"))).toBe("long=123456789012");
59+
expect(n.method5(android.float(1.23))).toBe("float=1.23");
60+
expect(n.method5(android.double(1))).toBe("double=1.0");
61+
expect(n.method2(android.double(65536 + 2))).toBe("double=65538.0");
62+
expect(n.method2(android.byte(65536 + 2))).toBe("float=2.0");
63+
expect(n.method2(android.short(65536 + 2))).toBe("float=2.0");
64+
});
65+
66+
it("rejects a cast with the wrong arity", function () {
67+
expect(function () {
68+
android.long();
69+
}).toThrow();
70+
});
71+
72+
it("creates Java arrays from a primitive type name or a class", function () {
73+
var ints = android.newArray("int", 3);
74+
expect(ints.length).toBe(3);
75+
expect(ints.getClass().getName()).toBe("[I");
76+
77+
var strings = android.newArray(java.lang.String, 2);
78+
expect(strings.length).toBe(2);
79+
expect(strings.getClass().getName()).toBe("[Ljava.lang.String;");
80+
});
81+
82+
it("rejects bad newArray arguments", function () {
83+
expect(function () {
84+
android.newArray("int");
85+
}).toThrow();
86+
expect(function () {
87+
android.newArray("int", -1);
88+
}).toThrow();
89+
});
90+
91+
it("resolves through a static import", function (done) {
92+
import("~/testNsInteropImport.mjs").then(function (module) {
93+
expect(module.interopDefault).toBe(require("ns:interop"));
94+
expect(module.androidDefault).toBe(android);
95+
expect(module.long).toBe(android.long);
96+
expect(module.newArray).toBe(android.newArray);
97+
expect(module.escapeException).toBe(require("ns:runtime").escapeException);
98+
done();
99+
}, function (error) {
100+
fail("static import of ns:interop/android should resolve: " + error);
101+
done();
102+
});
103+
});
104+
105+
it("resolves through a dynamic import", function (done) {
106+
import("ns:interop/android").then(function (namespace) {
107+
expect(namespace.default).toBe(android);
108+
expect(namespace.long).toBe(android.long);
109+
expect(namespace.newArray).toBe(android.newArray);
110+
done();
111+
}, function (error) {
112+
fail("dynamic import of ns:interop/android should resolve: " + error);
113+
done();
114+
});
115+
});
116+
117+
it("gives a worker its own instance behind its own globals", function (done) {
118+
var worker = new Worker("./nsInteropWorker.js");
119+
worker.onmessage = function (msg) {
120+
expect(msg.data).toEqual({
121+
casts: true,
122+
newArray: true,
123+
escapeException: true,
124+
arrayLength: 4,
125+
});
126+
worker.terminate();
127+
done();
128+
};
129+
worker.onerror = function (error) {
130+
fail("worker failed: " + error.message);
131+
worker.terminate();
132+
done();
133+
};
134+
worker.postMessage("go");
135+
});
136+
});
137+
138+
describe("interop global", function () {
139+
it("holds exactly ns:runtime's escapeException", function () {
140+
expect(Object.keys(interop)).toEqual(["escapeException"]);
141+
expect(interop.escapeException).toBe(require("ns:runtime").escapeException);
142+
});
143+
144+
it("is an ordinary writable, enumerable, configurable global", function () {
145+
var descriptor = Object.getOwnPropertyDescriptor(globalThis, "interop");
146+
expect(descriptor.writable).toBe(true);
147+
expect(descriptor.enumerable).toBe(true);
148+
expect(descriptor.configurable).toBe(true);
149+
});
150+
});

‎test-app/app/src/main/assets/app/tests/testNsRuntime.js‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,13 @@ describe("ns:runtime", function () {
55
expect(Object.isFrozen(runtime)).toBe(true);
66
expect(typeof runtime.setConfig).toBe("function");
77
expect(typeof runtime.getConfig).toBe("function");
8+
expect(typeof runtime.escapeException).toBe("function");
89
});
910

1011
// The export set is public API, declared alongside docs/ns-builtin-modules.md
1112
// — all of them change together.
1213
it("exposes exactly the declared surface", function () {
13-
expect(Object.keys(runtime).sort()).toEqual(["getConfig", "setConfig"]);
14+
expect(Object.keys(runtime).sort()).toEqual(["escapeException", "getConfig", "setConfig"]);
1415
});
1516

1617
it("rejects unknown keys", function () {

‎test-app/runtime/CMakeLists.txt‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,13 +76,16 @@ set(RUNTIME_BUILTIN_JS
7676
${RUNTIME_BUILTIN_JS_DIR}/error-events.js
7777
${RUNTIME_BUILTIN_JS_DIR}/events.js
7878
${RUNTIME_BUILTIN_JS_DIR}/inspect.js
79+
${RUNTIME_BUILTIN_JS_DIR}/interop-globals.js
7980
${RUNTIME_BUILTIN_JS_DIR}/json-helper.js
8081
${RUNTIME_BUILTIN_JS_DIR}/message-channel.js
8182
${RUNTIME_BUILTIN_JS_DIR}/message-event.js
8283
${RUNTIME_BUILTIN_JS_DIR}/node-module.js
8384
${RUNTIME_BUILTIN_JS_DIR}/node-url.js
8485
${RUNTIME_BUILTIN_JS_DIR}/node-util.js
8586
${RUNTIME_BUILTIN_JS_DIR}/node-worker-threads.js
87+
${RUNTIME_BUILTIN_JS_DIR}/ns-interop-android.js
88+
${RUNTIME_BUILTIN_JS_DIR}/ns-interop.js
8689
${RUNTIME_BUILTIN_JS_DIR}/ns-module.js
8790
${RUNTIME_BUILTIN_JS_DIR}/ns-runtime.js
8891
${RUNTIME_BUILTIN_JS_DIR}/ns-util.js

‎test-app/runtime/src/main/cpp/ArrayHelper.cpp‎

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
#include "ArgConverter.h"
44
#include "NativeScriptException.h"
55
#include "Runtime.h"
6+
#include <mutex>
67
#include <sstream>
78

89
using namespace v8;
@@ -12,27 +13,23 @@ using namespace tns;
1213
ArrayHelper::ArrayHelper() {
1314
}
1415

15-
void ArrayHelper::Init(const Local<Context>& context) {
16+
void ArrayHelper::ResolveRuntimeMethods() {
1617
JEnv env;
1718

1819
RUNTIME_CLASS = env.FindClass("com/tns/Runtime");
1920
NS_CHECK(RUNTIME_CLASS != nullptr);
2021

2122
CREATE_ARRAY_HELPER = env.GetStaticMethodID(RUNTIME_CLASS, "createArrayHelper", "(Ljava/lang/String;I)Ljava/lang/Object;");
2223
NS_CHECK(CREATE_ARRAY_HELPER != nullptr);
24+
}
25+
26+
MaybeLocal<Function> ArrayHelper::CreateNewArray(Local<Context> context) {
27+
// Every isolate's binding gets here, workers on their own threads.
28+
static std::once_flag resolved;
29+
std::call_once(resolved, ResolveRuntimeMethods);
2330

2431
auto isolate = v8::Isolate::GetCurrent();
25-
auto global = context->Global();
26-
auto arr = global->Get(context, ArgConverter::ConvertToV8String(isolate, "Array"));
27-
28-
if (!arr.IsEmpty()) {
29-
Local<Value> arrVal;
30-
auto success = arr.ToLocal(&arrVal);
31-
if (success) {
32-
auto arrayObj = arrVal.As<Object>();
33-
arrayObj->Set(context, ArgConverter::ConvertToV8String(isolate, "create"), FunctionTemplate::New(isolate, CreateJavaArrayCallback)->GetFunction(context).ToLocalChecked());
34-
}
35-
}
32+
return FunctionTemplate::New(isolate, CreateJavaArrayCallback)->GetFunction(context);
3633
}
3734

3835
void ArrayHelper::CreateJavaArrayCallback(const FunctionCallbackInfo<Value>& info) {

0 commit comments

Comments
 (0)