@node-ctypes/python 0.3.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +58 -196
- package/dist/bootstrap.js +102 -21
- package/dist/buffers.js +93 -13
- package/dist/conversions.js +239 -68
- package/dist/executor.js +12 -5
- package/dist/native.d.ts +6 -12
- package/dist/native.js +7 -7
- package/dist/objects.d.ts +2 -1
- package/dist/objects.js +9 -37
- package/dist/platform.js +3 -0
- package/dist/runtime.d.ts +2 -2
- package/dist/runtime.js +465 -233
- package/dist/scheduler.js +452 -153
- package/package.json +6 -2
package/README.md
CHANGED
|
@@ -1,42 +1,27 @@
|
|
|
1
1
|
# node-python (`@node-ctypes/python`)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@node-ctypes/python)
|
|
4
|
+
[](https://www.npmjs.com/package/@node-ctypes/python)
|
|
5
|
+
[](https://www.python.org/)
|
|
6
|
+
[](https://github.com/dmazzella/node-python/actions/workflows/ci.yml)
|
|
7
|
+
[](https://opensource.org/licenses/MIT)
|
|
8
|
+
|
|
9
|
+
**Typed embedded CPython for Node.js**, powered by
|
|
4
10
|
[node-ctypes](https://www.npmjs.com/package/node-ctypes).
|
|
5
|
-
|
|
6
|
-
Python runs in-process, not in a subprocess or sandbox.
|
|
11
|
+
Python runs in-process (not in a subprocess or sandbox) with zero custom native addon to compile.
|
|
7
12
|
|
|
8
|
-
|
|
13
|
+
- **Node.js 24+**, ESM, TypeScript declarations.
|
|
14
|
+
- **CPython 3.12+**, including **free-threaded builds (`3.13t` / `3.14t`, `Py_GIL_DISABLED`)** on Windows, Linux and macOS (x64 & ARM64).
|
|
15
|
+
- **Non-blocking by default**: Python calls, `exec`, `eval` and `import` run on a dedicated native `Executor` thread, with bidirectional `asyncio`, async iterators, `AbortSignal` cancellation, shared memoryviews and native `JsProxy` objects.
|
|
9
16
|
|
|
10
|
-
|
|
11
|
-
- Python 3.12+ with a shared library matching Node.js architecture and Python ABI.
|
|
12
|
-
- Windows, Linux or macOS.
|
|
17
|
+
---
|
|
13
18
|
|
|
14
|
-
|
|
15
|
-
Debian/Ubuntu install the matching `libpython3.x` package; with pyenv use
|
|
16
|
-
`PYTHON_CONFIGURE_OPTS=--enable-shared`.
|
|
17
|
-
Install optional Python dependencies into the selected interpreter's environment.
|
|
18
|
-
Neither Python nor its packages are bundled.
|
|
19
|
+
## Quick start
|
|
19
20
|
|
|
20
21
|
```sh
|
|
21
22
|
npm install @node-ctypes/python
|
|
22
23
|
```
|
|
23
24
|
|
|
24
|
-
To build from source, run from this directory:
|
|
25
|
-
|
|
26
|
-
```sh
|
|
27
|
-
npm install
|
|
28
|
-
npm run build
|
|
29
|
-
npm test
|
|
30
|
-
npm pack
|
|
31
|
-
```
|
|
32
|
-
|
|
33
|
-
Install the resulting tarball into your application with
|
|
34
|
-
`npm install /path/to/node-ctypes-python-0.1.0.tgz`.
|
|
35
|
-
The runtime dependency is published `node-ctypes` (`^2.10.0`); no custom native
|
|
36
|
-
bridge, core patch or JavaScript worker is required.
|
|
37
|
-
|
|
38
|
-
## Quick start
|
|
39
|
-
|
|
40
25
|
```typescript
|
|
41
26
|
import { Python, kwargs } from "@node-ctypes/python";
|
|
42
27
|
|
|
@@ -58,173 +43,50 @@ try {
|
|
|
58
43
|
}
|
|
59
44
|
```
|
|
60
45
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
`Python.initialize({ executable, library, stdin, stdout, stderr, synchronousCallbacks, switchInterval })`
|
|
64
|
-
returns the runtime singleton. Options apply to the first initialization.
|
|
65
|
-
|
|
66
|
-
- `executable`, or `PYTHON`, selects the interpreter; an explicit choice never
|
|
67
|
-
falls back. Otherwise discovery tries installed Python commands.
|
|
68
|
-
- `library`, or `PYTHON_LIBRARY`, overrides shared-library discovery. The selected
|
|
69
|
-
interpreter supplies `sys.path`, including virtualenv paths. Each discovery
|
|
70
|
-
probe has a 10-second timeout.
|
|
71
|
-
- `stdin: false` leaves standard input to Node.js. `stdout` and `stderr` accept
|
|
72
|
-
`"inherit"` (default), `"node"`, `"console"` or a text callback. `"console"`
|
|
73
|
-
sends whole lines to `console.log` / `console.error` (a line without its newline
|
|
74
|
-
on `flush()` or at finalization). Without a console, as in an Electron renderer
|
|
75
|
-
or a packaged GUI app on Windows, Python's `sys.stdout` and `sys.stderr` are
|
|
76
|
-
`None` and `"inherit"` discards the output, as `pythonw` does: use `"console"`
|
|
77
|
-
(DevTools) or a callback (e.g. a log file).
|
|
78
|
-
- `synchronousCallbacks: true` enables native callback dispatch during
|
|
79
|
-
interruptible synchronous Python waits. It requires an available SIGURG wakeup
|
|
80
|
-
on POSIX, or Windows Python 3.14+ with its interrupt event available.
|
|
81
|
-
Unsupported configurations fail explicitly; the default is `false`.
|
|
82
|
-
- `switchInterval` sets the GIL switch interval in milliseconds
|
|
83
|
-
(`sys.setswitchinterval`). The default is `5`, as in CPython. Every Python call
|
|
84
|
-
acquires the GIL on the Node.js thread, so while Python threads run CPU-bound
|
|
85
|
-
code each call can stall the event loop for several intervals: on Windows we
|
|
86
|
-
measured stalls of 150–250 ms with the default. `0.5` reduced them to under
|
|
87
|
-
50 ms, but slowed two contending CPU-bound Python threads by 40% or more.
|
|
88
|
-
To keep the main thread free without that cost, host Python in a worker
|
|
89
|
-
(`examples/worker.ts`).
|
|
90
|
-
|
|
91
|
-
Native objects are always enabled; there is no `nativeObjects` mode.
|
|
92
|
-
Free-threaded builds require their matching executable and shared library;
|
|
93
|
-
an ABI3t compatibility DLL alone does not enable free threading.
|
|
94
|
-
|
|
95
|
-
## API and execution model
|
|
96
|
-
|
|
97
|
-
| API | Purpose |
|
|
98
|
-
| ------------------------------------------------ | ------------------------------------------------------ |
|
|
99
|
-
| `Python.initialize(options)` | Initialize the singleton asynchronously |
|
|
100
|
-
| `python.main`, `python.builtins` | Live module proxies |
|
|
101
|
-
| `python.version`, `.executable`, `.library` | Selected interpreter information |
|
|
102
|
-
| `await python.exec(code)` | Execute statements in `__main__` |
|
|
103
|
-
| `await python.eval<T>(expression)` | Evaluate and deeply convert the result |
|
|
104
|
-
| `await python.import<T>(name)` | Import a live module, including dotted names |
|
|
105
|
-
| `python.module(name, members)` | Register JavaScript members as a Python module |
|
|
106
|
-
| `python.toPython<T>(value)` | Create an explicitly disposable Python proxy |
|
|
107
|
-
| `python.run(operation, { signal })` | Await a Python operation or awaitable, with abort |
|
|
108
|
-
| `await python.with(manager, body)` / `asyncWith` | Run a context manager, including exception suppression |
|
|
109
|
-
| `python.stats()` | Inspect shared-reference and scheduler counters |
|
|
110
|
-
| `await python.finalize()` | Drain accepted native calls and close the runtime |
|
|
111
|
-
|
|
112
|
-
Exports also include `PythonError`, `Tuple`, `kwargs`, `byReference` and
|
|
113
|
-
`cancellable`. Types and generics describe the dynamic API; they do not validate
|
|
114
|
-
Python types at runtime.
|
|
115
|
-
|
|
116
|
-
**Calls are asynchronous; live access is synchronous.** Python functions, methods,
|
|
117
|
-
classes and builtins return Promises, including `await new cls(...)`.
|
|
118
|
-
Calls, imports, `exec` and `eval` execute in order on one native thread (a
|
|
119
|
-
node-ctypes `Executor`) without occupying a waiting libuv worker. Arguments and
|
|
120
|
-
results are converted on Node.js, so thousands of concurrent calls (e.g.
|
|
121
|
-
`Promise.all` over an array) hold Node.js while they are submitted and while
|
|
122
|
-
their results are converted: pass the data to one Python call instead, or host
|
|
123
|
-
Python in a worker (`examples/worker.ts`). Attributes, indices, assignment, enumeration, ordinary iteration, conversion and
|
|
124
|
-
disposal remain synchronous and can block Node.js. Native initialization and
|
|
125
|
-
finalization also run synchronously on the hosting Node.js thread.
|
|
126
|
-
|
|
127
|
-
Python coroutine results are automatically awaited through a separate asyncio
|
|
128
|
-
thread. Async iterators work in both directions. An async JavaScript callback
|
|
129
|
-
must be awaited from Python; a synchronous Python callback cannot return a
|
|
130
|
-
JavaScript Promise. `cancellable(fn)` adds an `AbortSignal` to callbacks that
|
|
131
|
-
cooperate with Python cancellation.
|
|
132
|
-
|
|
133
|
-
`python.run(operation, { signal })` accepts the Promise of a call, `exec`,
|
|
134
|
-
`eval` or `import`, or a Python awaitable, and rejects with `signal.reason`
|
|
135
|
-
on abort (`AbortSignal.timeout(ms)` for time limits). A queued operation is
|
|
136
|
-
skipped; running Python code receives one `KeyboardInterrupt`, so `finally`
|
|
137
|
-
blocks run and `except Exception` does not swallow it. On CPython 3.12 only,
|
|
138
|
-
a one-line loop that starts a `try` block (`try:` followed by `while True: ...`)
|
|
139
|
-
skips that `finally` when interrupted; put the loop body on its own line.
|
|
140
|
-
Native calls are
|
|
141
|
-
interrupted only when they return; asyncio work is cancelled. Synchronous proxy
|
|
142
|
-
access and JavaScript work cannot be aborted.
|
|
143
|
-
|
|
144
|
-
### Values, memory and lifetime
|
|
145
|
-
|
|
146
|
-
- Scalars convert naturally; Python integers outside JavaScript's safe range
|
|
147
|
-
become bigints. Arrays, `Tuple`, objects/Maps and Sets copy to Python containers.
|
|
148
|
-
Dates become UTC datetimes; Temporal conversions require runtime support.
|
|
149
|
-
- Other Python objects remain live proxies. `eval()` and `proxy.toJS()` perform
|
|
150
|
-
deep conversion; ordinary call results use shallow conversion. Circular copies
|
|
151
|
-
are rejected; use live proxies or `byReference()` instead.
|
|
152
|
-
- Arbitrary JavaScript instances remain shared references. `byReference(value)`
|
|
153
|
-
also shares ordinary containers. Python attributes take precedence over dict keys.
|
|
154
|
-
- Buffer/Uint8Array values copy to Python bytes; other typed arrays, ArrayBuffers
|
|
155
|
-
and DataViews expose shared memoryviews. `byReference(buffer)` shares writable
|
|
156
|
-
memory. `proxy.toTypedArray()` requires a C-contiguous Python buffer and copies
|
|
157
|
-
read-only buffers. Do not detach, transfer or resize shared backing memory.
|
|
158
|
-
- Release owned proxies with `[Symbol.dispose]()` when practical, including
|
|
159
|
-
`PythonError.exception`. GC is nondeterministic. Disposal drops the reference
|
|
160
|
-
immediately; on free-threaded builds CPython may run the object's destructor
|
|
161
|
-
later, when the thread that created it next runs Python code. `PythonError` exposes `type`,
|
|
162
|
-
`traceback`, `exception` and, when available, the original JavaScript `cause`.
|
|
163
|
-
|
|
164
|
-
Only one JavaScript thread per process may host Python. A Node.js worker can
|
|
165
|
-
isolate synchronous access and conversions, but must finalize before terminating.
|
|
166
|
-
Wait for application work and Python threads before finalization; do not finalize
|
|
167
|
-
inside a Python callback. Repeated finalization is harmless; restart and
|
|
168
|
-
subinterpreters are not supported. Never use Python proxies or Python-backed
|
|
169
|
-
memory afterward.
|
|
170
|
-
|
|
171
|
-
Closing rejects new calls and drains accepted native operations, not every
|
|
172
|
-
pending coroutine: remaining awaits are rejected during teardown. Cleanup also
|
|
173
|
-
runs on normal `beforeExit`; `process.exit()` is not orderly finalization.
|
|
174
|
-
Shutdown can wait for Python threads and has no overall timeout.
|
|
175
|
-
Execute trusted Python code only.
|
|
176
|
-
|
|
177
|
-
## Examples and tests
|
|
178
|
-
|
|
179
|
-
Run examples directly, for example `node examples/basics.ts`.
|
|
180
|
-
They cover usage in more detail than this overview:
|
|
181
|
-
|
|
182
|
-
| Example | Focus |
|
|
183
|
-
| --------------------------------------------- | --------------------------------------------- |
|
|
184
|
-
| [basics.ts](./examples/basics.ts) | Values, live objects, errors and conversions |
|
|
185
|
-
| [callbacks.ts](./examples/callbacks.ts) | JavaScript callbacks and constructors |
|
|
186
|
-
| [threads.ts](./examples/threads.ts) | Python threads and cross-thread callbacks |
|
|
187
|
-
| [async.ts](./examples/async.ts) | Await, cancellation and async iteration |
|
|
188
|
-
| [module.ts](./examples/module.ts) | JavaScript modules and local Python imports |
|
|
189
|
-
| [worker.ts](./examples/worker.ts) | Hosting Python in a Node.js worker |
|
|
190
|
-
| [cryptography.ts](./examples/cryptography.ts) | Python cryptography integration |
|
|
191
|
-
| [lxml.ts](./examples/lxml.ts) | XML parsing, XPath, XSLT and canonicalization |
|
|
192
|
-
|
|
193
|
-
Optional packages are needed only for the corresponding examples and must be
|
|
194
|
-
installed in the selected interpreter. Set `PYTHON` to that executable if it
|
|
195
|
-
differs from the one found automatically. The suite regression-tests callbacks
|
|
196
|
-
and missing-package diagnostics; other example scenarios are manual.
|
|
46
|
+
To build from source, see [Getting started](guides/getting-started.md#building-from-source).
|
|
197
47
|
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
48
|
+
## Supported platforms
|
|
49
|
+
|
|
50
|
+
| Operating system | x64 | ARM64 |
|
|
51
|
+
| ---------------- | --- | ----- |
|
|
52
|
+
| Windows | ✅ | ✅ |
|
|
53
|
+
| macOS | ✅ | ✅ |
|
|
54
|
+
| Linux | ✅ | ✅ |
|
|
55
|
+
|
|
56
|
+
Node.js 24 or later and shared CPython 3.12+ (including free-threaded builds). Verified in Electron and under `NODE_CTYPES_NO_EXTERNAL_BUFFERS=1` (mirror mode).
|
|
57
|
+
|
|
58
|
+
---
|
|
59
|
+
|
|
60
|
+
## Guides
|
|
61
|
+
|
|
62
|
+
- [Getting started](guides/getting-started.md) — installation, requirements, interpreter discovery and `Python.initialize()` options
|
|
63
|
+
- [Execution model](guides/execution-model.md) — the Python executor, synchronous live access, worker hosting, `stats()` and `finalize()`
|
|
64
|
+
- [Values, memory and lifetime](guides/values-and-memory.md) — conversions, `Tuple`, `kwargs`, `Date` and `Temporal`, `byReference()`, shared buffers and disposal
|
|
65
|
+
- [Callbacks, modules and JsProxy](guides/callbacks-and-modules.md) — JavaScript functions, classes, `python.module()`, `JsProxy` and cross-thread callbacks
|
|
66
|
+
- [Async, cancellation and context managers](guides/async-and-cancellation.md) — `asyncio`, bidirectional async iterators, `python.run()`, `cancellable()`, `with()` and `asyncWith()`
|
|
67
|
+
- [Errors and limits](guides/errors.md) — `PythonError`, exception propagation, `KeyboardInterrupt` and runtime limits
|
|
68
|
+
- [Electron and free-threaded Python](guides/electron-and-free-threading.md) — Electron main/renderer integration, mirror mode and `Py_GIL_DISABLED` builds (`3.13t` / `3.14t`)
|
|
69
|
+
- [Building, testing and internals](guides/contributing.md) — test suites, mirror-mode and stress tests, CI and release workflow
|
|
70
|
+
|
|
71
|
+
Implementation diagrams and ownership invariants (in Italian): [FLOWS.md](FLOWS.md).
|
|
72
|
+
|
|
73
|
+
---
|
|
74
|
+
|
|
75
|
+
## Examples
|
|
76
|
+
|
|
77
|
+
Runnable TypeScript examples live in `examples/`; see the [index](examples/README.md).
|
|
78
|
+
|
|
79
|
+
- [basics.ts](examples/basics.ts) — values, live proxies, errors, conversions and context managers
|
|
80
|
+
- [callbacks.ts](examples/callbacks.ts) — JavaScript callbacks, constructors and `JsProxy`
|
|
81
|
+
- [threads.ts](examples/threads.ts) — Python threads and cross-thread JavaScript callbacks
|
|
82
|
+
- [async.ts](examples/async.ts) — `asyncio`, `python.run()` cancellation and async iterators
|
|
83
|
+
- [module.ts](examples/module.ts) — JavaScript modules (`python.module`) and local Python imports
|
|
84
|
+
- [worker.ts](examples/worker.ts) — hosting CPython inside a Node.js worker
|
|
85
|
+
- [cryptography.ts](examples/cryptography.ts) — Python `cryptography` integration
|
|
86
|
+
- [lxml.ts](examples/lxml.ts) — XML parsing, XPath, XSLT and canonicalization
|
|
87
|
+
|
|
88
|
+
---
|
|
89
|
+
|
|
90
|
+
## License
|
|
207
91
|
|
|
208
|
-
|
|
209
|
-
CPython. Typechecks include sources, examples and test helpers.
|
|
210
|
-
`test:backlog` checks queued ownership, every outcome and shutdown under load.
|
|
211
|
-
`test:stress` adds a 60-second mixed workload; set `NODE_PYTHON_STRESS_SECONDS`
|
|
212
|
-
to change its duration. Both are opt-in, force GC in isolated children and report
|
|
213
|
-
memory/latency diagnostics, not performance or leak-certification guarantees.
|
|
214
|
-
The runtime does not impose application backpressure.
|
|
215
|
-
|
|
216
|
-
Two manual checks run in Electron's main process after `npm run build`
|
|
217
|
-
(`electron <file>`, with `ELECTRON_RUN_AS_NODE` unset):
|
|
218
|
-
[tests/electron/main.mjs](./tests/electron/main.mjs) prints a JSON report of
|
|
219
|
-
calls, a free UI thread during a long call and bursts of calls;
|
|
220
|
-
[tests/electron/ui/main.mjs](./tests/electron/ui/main.mjs) opens a window that
|
|
221
|
-
charts frame times and main-process IPC latency while bursts run in the main
|
|
222
|
-
process or in the renderer (`--auto` runs both, prints the table and quits).
|
|
223
|
-
|
|
224
|
-
The [CI workflow](./.github/workflows/ci.yml) runs `npm test` with Python
|
|
225
|
-
3.12, 3.13, 3.14, 3.14t and 3.15 on Windows, Linux and macOS. It is discovered only when
|
|
226
|
-
this package is a repository root, not while nested in another repository.
|
|
227
|
-
Pushing a `v<version>` tag that matches `package.json` publishes to npm once the
|
|
228
|
-
whole matrix passes (npm Trusted Publishing; versions with a `-` go to `next`).
|
|
229
|
-
For implementation diagrams and ownership invariants, see [FLOWS.md](./FLOWS.md)
|
|
230
|
-
(Italian).
|
|
92
|
+
[MIT](LICENSE).
|
package/dist/bootstrap.js
CHANGED
|
@@ -1,3 +1,55 @@
|
|
|
1
|
+
var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
|
|
2
|
+
if (value !== null && value !== void 0) {
|
|
3
|
+
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
|
|
4
|
+
var dispose, inner;
|
|
5
|
+
if (async) {
|
|
6
|
+
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
|
|
7
|
+
dispose = value[Symbol.asyncDispose];
|
|
8
|
+
}
|
|
9
|
+
if (dispose === void 0) {
|
|
10
|
+
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
|
|
11
|
+
dispose = value[Symbol.dispose];
|
|
12
|
+
if (async) inner = dispose;
|
|
13
|
+
}
|
|
14
|
+
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
|
|
15
|
+
if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
|
|
16
|
+
env.stack.push({ value: value, dispose: dispose, async: async });
|
|
17
|
+
}
|
|
18
|
+
else if (async) {
|
|
19
|
+
env.stack.push({ async: true });
|
|
20
|
+
}
|
|
21
|
+
return value;
|
|
22
|
+
};
|
|
23
|
+
var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
|
|
24
|
+
return function (env) {
|
|
25
|
+
function fail(e) {
|
|
26
|
+
env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
|
|
27
|
+
env.hasError = true;
|
|
28
|
+
}
|
|
29
|
+
var r, s = 0;
|
|
30
|
+
function next() {
|
|
31
|
+
while (r = env.stack.pop()) {
|
|
32
|
+
try {
|
|
33
|
+
if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
|
|
34
|
+
if (r.dispose) {
|
|
35
|
+
var result = r.dispose.call(r.value);
|
|
36
|
+
if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
|
|
37
|
+
}
|
|
38
|
+
else s |= 1;
|
|
39
|
+
}
|
|
40
|
+
catch (e) {
|
|
41
|
+
fail(e);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
|
|
45
|
+
if (env.hasError) throw env.error;
|
|
46
|
+
}
|
|
47
|
+
return next();
|
|
48
|
+
};
|
|
49
|
+
})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
|
|
50
|
+
var e = new Error(message);
|
|
51
|
+
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
52
|
+
});
|
|
1
53
|
// Copyright (c) 2026 Damiano Mazzella. MIT License (see LICENSE).
|
|
2
54
|
import { Tuple } from "./values.js";
|
|
3
55
|
export function definePython(builtins, module, source, filename) {
|
|
@@ -38,26 +90,55 @@ export class PythonBootstrap {
|
|
|
38
90
|
javascriptCode;
|
|
39
91
|
mainThread;
|
|
40
92
|
constructor(builtins, importModule) {
|
|
41
|
-
const
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
93
|
+
const env_1 = { stack: [], error: void 0, hasError: false };
|
|
94
|
+
try {
|
|
95
|
+
const types = __addDisposableResource(env_1, importModule("types"), false);
|
|
96
|
+
const collections = __addDisposableResource(env_1, importModule("collections"), false);
|
|
97
|
+
const module = (this.module = types.ModuleType("_node_ctypes"));
|
|
98
|
+
const threading = __addDisposableResource(env_1, importModule("threading"), false);
|
|
99
|
+
const weakref = __addDisposableResource(env_1, importModule("weakref"), false);
|
|
100
|
+
module.threading = threading;
|
|
101
|
+
module.weakref = weakref;
|
|
102
|
+
module._main = this.mainThread = threading.get_ident();
|
|
103
|
+
const execution = __addDisposableResource(env_1, builtins.list([null]), false);
|
|
104
|
+
module._execution = execution;
|
|
105
|
+
const deque = __addDisposableResource(env_1, collections.deque, false);
|
|
106
|
+
const released = __addDisposableResource(env_1, deque(), false);
|
|
107
|
+
module._released = released;
|
|
108
|
+
module._op = null;
|
|
109
|
+
definePython(builtins, module, CALLABLE, "<node-python callables>");
|
|
110
|
+
this.wrap = module.wrap;
|
|
111
|
+
const wrapCode = __addDisposableResource(env_1, this.wrap.__code__, false);
|
|
112
|
+
const consts = __addDisposableResource(env_1, wrapCode.co_consts, false);
|
|
113
|
+
let javascriptCode;
|
|
114
|
+
for (const value of consts) {
|
|
115
|
+
if (javascriptCode === undefined && typeof value === "function" && builtins.getattr(value, "co_name", null) === "javascript") {
|
|
116
|
+
javascriptCode = value;
|
|
117
|
+
}
|
|
118
|
+
else if (value !== null && (typeof value === "object" || typeof value === "function") && Symbol.dispose in value) {
|
|
119
|
+
value[Symbol.dispose]();
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
if (!javascriptCode)
|
|
123
|
+
throw new Error("Python callable adapter has no javascript code object");
|
|
124
|
+
this.javascriptCode = javascriptCode;
|
|
125
|
+
module.JAVASCRIPT_CODE = this.javascriptCode;
|
|
126
|
+
const jsProxy = __addDisposableResource(env_1, builtins.type("JsProxy", Tuple.of(builtins.object), {
|
|
127
|
+
__module__: "_node_ctypes",
|
|
128
|
+
__slots__: Tuple.of("_id", "__weakref__"),
|
|
129
|
+
__doc__: "A JavaScript object used by reference: attributes, items, len(),\n iteration (also async for), await (promises), dir(), repr().",
|
|
130
|
+
}), false);
|
|
131
|
+
module.JsProxy = jsProxy;
|
|
132
|
+
const asyncIter = __addDisposableResource(env_1, builtins.type("_JsAsyncIterator", Tuple.of(builtins.object), { __module__: "_node_ctypes" }), false);
|
|
133
|
+
module._JsAsyncIterator = asyncIter;
|
|
134
|
+
this.objectType = module.JsProxy;
|
|
135
|
+
}
|
|
136
|
+
catch (e_1) {
|
|
137
|
+
env_1.error = e_1;
|
|
138
|
+
env_1.hasError = true;
|
|
139
|
+
}
|
|
140
|
+
finally {
|
|
141
|
+
__disposeResources(env_1);
|
|
142
|
+
}
|
|
62
143
|
}
|
|
63
144
|
}
|
package/dist/buffers.js
CHANGED
|
@@ -1,3 +1,55 @@
|
|
|
1
|
+
var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
|
|
2
|
+
if (value !== null && value !== void 0) {
|
|
3
|
+
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
|
|
4
|
+
var dispose, inner;
|
|
5
|
+
if (async) {
|
|
6
|
+
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
|
|
7
|
+
dispose = value[Symbol.asyncDispose];
|
|
8
|
+
}
|
|
9
|
+
if (dispose === void 0) {
|
|
10
|
+
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
|
|
11
|
+
dispose = value[Symbol.dispose];
|
|
12
|
+
if (async) inner = dispose;
|
|
13
|
+
}
|
|
14
|
+
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
|
|
15
|
+
if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
|
|
16
|
+
env.stack.push({ value: value, dispose: dispose, async: async });
|
|
17
|
+
}
|
|
18
|
+
else if (async) {
|
|
19
|
+
env.stack.push({ async: true });
|
|
20
|
+
}
|
|
21
|
+
return value;
|
|
22
|
+
};
|
|
23
|
+
var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
|
|
24
|
+
return function (env) {
|
|
25
|
+
function fail(e) {
|
|
26
|
+
env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
|
|
27
|
+
env.hasError = true;
|
|
28
|
+
}
|
|
29
|
+
var r, s = 0;
|
|
30
|
+
function next() {
|
|
31
|
+
while (r = env.stack.pop()) {
|
|
32
|
+
try {
|
|
33
|
+
if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
|
|
34
|
+
if (r.dispose) {
|
|
35
|
+
var result = r.dispose.call(r.value);
|
|
36
|
+
if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
|
|
37
|
+
}
|
|
38
|
+
else s |= 1;
|
|
39
|
+
}
|
|
40
|
+
catch (e) {
|
|
41
|
+
fail(e);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
|
|
45
|
+
if (env.hasError) throw env.error;
|
|
46
|
+
}
|
|
47
|
+
return next();
|
|
48
|
+
};
|
|
49
|
+
})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
|
|
50
|
+
var e = new Error(message);
|
|
51
|
+
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
52
|
+
});
|
|
1
53
|
const TYPED = {
|
|
2
54
|
b: "Int8Array",
|
|
3
55
|
B: "Uint8Array",
|
|
@@ -13,24 +65,41 @@ const TYPED = {
|
|
|
13
65
|
};
|
|
14
66
|
const SIZED = { l4: "i", l8: "q", L4: "I", L8: "Q", n4: "i", n8: "q", N4: "I", N8: "Q", P8: "Q", P4: "I" };
|
|
15
67
|
export class PythonBuffers {
|
|
16
|
-
#
|
|
17
|
-
#
|
|
18
|
-
#
|
|
68
|
+
#memoryview;
|
|
69
|
+
#bytearray;
|
|
70
|
+
#cChar;
|
|
71
|
+
#addressof;
|
|
72
|
+
#mul;
|
|
19
73
|
#byteorder;
|
|
20
74
|
#bufferError;
|
|
21
75
|
constructor(builtins, importModule, bufferError) {
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
76
|
+
const env_1 = { stack: [], error: void 0, hasError: false };
|
|
77
|
+
try {
|
|
78
|
+
this.#memoryview = builtins.memoryview;
|
|
79
|
+
this.#bytearray = builtins.bytearray;
|
|
80
|
+
const ctypes = __addDisposableResource(env_1, importModule("ctypes"), false);
|
|
81
|
+
this.#cChar = ctypes.c_char;
|
|
82
|
+
this.#addressof = ctypes.addressof;
|
|
83
|
+
const operator = __addDisposableResource(env_1, importModule("operator"), false);
|
|
84
|
+
this.#mul = operator.mul;
|
|
85
|
+
const sys = __addDisposableResource(env_1, importModule("sys"), false);
|
|
86
|
+
this.#byteorder = sys.byteorder;
|
|
87
|
+
this.#bufferError = bufferError;
|
|
88
|
+
}
|
|
89
|
+
catch (e_1) {
|
|
90
|
+
env_1.error = e_1;
|
|
91
|
+
env_1.hasError = true;
|
|
92
|
+
}
|
|
93
|
+
finally {
|
|
94
|
+
__disposeResources(env_1);
|
|
95
|
+
}
|
|
27
96
|
}
|
|
28
97
|
memory(address, size, format, keep) {
|
|
29
|
-
const owner = size ? this.#
|
|
98
|
+
const owner = size ? this.#mul(this.#cChar, size).from_address(address) : this.#bytearray();
|
|
30
99
|
try {
|
|
31
100
|
if (size)
|
|
32
101
|
owner._node_ctypes_keep = keep;
|
|
33
|
-
const view = this.#
|
|
102
|
+
const view = this.#memoryview(owner);
|
|
34
103
|
try {
|
|
35
104
|
if (!size)
|
|
36
105
|
return view.cast(format);
|
|
@@ -51,7 +120,7 @@ export class PythonBuffers {
|
|
|
51
120
|
}
|
|
52
121
|
}
|
|
53
122
|
export(target) {
|
|
54
|
-
const view = this.#
|
|
123
|
+
const view = this.#memoryview(target);
|
|
55
124
|
try {
|
|
56
125
|
if (!view.c_contiguous)
|
|
57
126
|
this.#bufferError("toTypedArray() needs a C-contiguous buffer");
|
|
@@ -67,8 +136,19 @@ export class PythonBuffers {
|
|
|
67
136
|
return [name, null, 0n, 0, null];
|
|
68
137
|
const bytes = view.format === "B" ? null : view.cast("B");
|
|
69
138
|
try {
|
|
70
|
-
const
|
|
71
|
-
|
|
139
|
+
const env_2 = { stack: [], error: void 0, hasError: false };
|
|
140
|
+
try {
|
|
141
|
+
const arrayType = __addDisposableResource(env_2, this.#mul(this.#cChar, size), false);
|
|
142
|
+
const holder = arrayType.from_buffer(bytes ?? view);
|
|
143
|
+
return [name, holder, BigInt(this.#addressof(holder)), size, null];
|
|
144
|
+
}
|
|
145
|
+
catch (e_2) {
|
|
146
|
+
env_2.error = e_2;
|
|
147
|
+
env_2.hasError = true;
|
|
148
|
+
}
|
|
149
|
+
finally {
|
|
150
|
+
__disposeResources(env_2);
|
|
151
|
+
}
|
|
72
152
|
}
|
|
73
153
|
finally {
|
|
74
154
|
bytes?.[Symbol.dispose]();
|