pyodide 0.19.1 → 0.20.0-alpha.1
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/api.ts +459 -0
- package/compat.ts +146 -0
- package/index.test-d.ts +20 -20
- package/load-package.ts +402 -0
- package/{module.js → module.ts} +21 -13
- package/package.json +13 -6
- package/pyodide.ts +309 -0
- package/pyodide.umd.ts +3 -0
- package/rollup.config.js +16 -4
- package/test/conftest.js +1 -1
- package/tsconfig.json +8 -6
- package/api.js +0 -421
- package/load-pyodide.js +0 -426
- package/pyodide.js +0 -302
package/api.ts
ADDED
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
import { Module, API, Hiwire } from "./module";
|
|
2
|
+
import { loadPackage, loadedPackages } from "./load-package";
|
|
3
|
+
import { isPyProxy, PyBuffer, PyProxy, TypedArray } from "./pyproxy.gen";
|
|
4
|
+
import { PythonError } from "./error_handling.gen";
|
|
5
|
+
export { loadPackage, loadedPackages, isPyProxy };
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* An alias to the Python :py:mod:`pyodide` package.
|
|
9
|
+
*
|
|
10
|
+
* You can use this to call functions defined in the Pyodide Python package
|
|
11
|
+
* from JavaScript.
|
|
12
|
+
*/
|
|
13
|
+
export let pyodide_py: PyProxy; // actually defined in loadPyodide (see pyodide.js)
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
*
|
|
17
|
+
* An alias to the global Python namespace.
|
|
18
|
+
*
|
|
19
|
+
* For example, to access a variable called ``foo`` in the Python global
|
|
20
|
+
* scope, use ``pyodide.globals.get("foo")``
|
|
21
|
+
*/
|
|
22
|
+
export let globals: PyProxy; // actually defined in loadPyodide (see pyodide.js)
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
*
|
|
26
|
+
* The Pyodide version.
|
|
27
|
+
*
|
|
28
|
+
* It can be either the exact release version (e.g. ``0.1.0``), or
|
|
29
|
+
* the latest release version followed by the number of commits since, and
|
|
30
|
+
* the git hash of the current commit (e.g. ``0.1.0-1-bd84646``).
|
|
31
|
+
*/
|
|
32
|
+
export let version: string = ""; // actually defined in loadPyodide (see pyodide.js)
|
|
33
|
+
|
|
34
|
+
let runPythonPositionalGlobalsDeprecationWarned = false;
|
|
35
|
+
/**
|
|
36
|
+
* Runs a string of Python code from JavaScript.
|
|
37
|
+
*
|
|
38
|
+
* The last part of the string may be an expression, in which case, its value is
|
|
39
|
+
* returned.
|
|
40
|
+
*
|
|
41
|
+
* .. admonition:: Positional globals argument :class: warning
|
|
42
|
+
*
|
|
43
|
+
* In Pyodide v0.19, this function took the globals parameter as a
|
|
44
|
+
* positional argument rather than as a named argument. In v0.20 this will
|
|
45
|
+
* still work but it is deprecated. It will be removed in v0.21.
|
|
46
|
+
*
|
|
47
|
+
* @param code Python code to evaluate
|
|
48
|
+
* @param options
|
|
49
|
+
* @param options.globals An optional Python dictionary to use as the globals.
|
|
50
|
+
* Defaults to :any:`pyodide.globals`. Uses the Python API
|
|
51
|
+
* :any:`pyodide.eval_code` to evaluate the code.
|
|
52
|
+
* @returns The result of the Python code translated to JavaScript. See the
|
|
53
|
+
* documentation for :any:`pyodide.eval_code` for more info.
|
|
54
|
+
*/
|
|
55
|
+
export function runPython(
|
|
56
|
+
code: string,
|
|
57
|
+
options: { globals?: PyProxy } = {}
|
|
58
|
+
): any {
|
|
59
|
+
if (API.isPyProxy(options)) {
|
|
60
|
+
options = { globals: options as PyProxy };
|
|
61
|
+
if (!runPythonPositionalGlobalsDeprecationWarned) {
|
|
62
|
+
console.warn(
|
|
63
|
+
"Passing a PyProxy as the second argument to runPython is deprecated. Use 'runPython(code, {globals : some_dict})' instead."
|
|
64
|
+
);
|
|
65
|
+
runPythonPositionalGlobalsDeprecationWarned = true;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (!options.globals) {
|
|
69
|
+
options.globals = API.globals;
|
|
70
|
+
}
|
|
71
|
+
return API.pyodide_py.eval_code(code, options.globals);
|
|
72
|
+
}
|
|
73
|
+
API.runPython = runPython;
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Inspect a Python code chunk and use :js:func:`pyodide.loadPackage` to install
|
|
77
|
+
* any known packages that the code chunk imports. Uses the Python API
|
|
78
|
+
* :func:`pyodide.find\_imports` to inspect the code.
|
|
79
|
+
*
|
|
80
|
+
* For example, given the following code as input
|
|
81
|
+
*
|
|
82
|
+
* .. code-block:: python
|
|
83
|
+
*
|
|
84
|
+
* import numpy as np x = np.array([1, 2, 3])
|
|
85
|
+
*
|
|
86
|
+
* :js:func:`loadPackagesFromImports` will call
|
|
87
|
+
* ``pyodide.loadPackage(['numpy'])``.
|
|
88
|
+
*
|
|
89
|
+
* @param code The code to inspect.
|
|
90
|
+
* @param messageCallback The ``messageCallback`` argument of
|
|
91
|
+
* :any:`pyodide.loadPackage` (optional).
|
|
92
|
+
* @param errorCallback The ``errorCallback`` argument of
|
|
93
|
+
* :any:`pyodide.loadPackage` (optional).
|
|
94
|
+
* @async
|
|
95
|
+
*/
|
|
96
|
+
export async function loadPackagesFromImports(
|
|
97
|
+
code: string,
|
|
98
|
+
messageCallback?: (msg: string) => void,
|
|
99
|
+
errorCallback?: (err: string) => void
|
|
100
|
+
) {
|
|
101
|
+
let pyimports = API.pyodide_py.find_imports(code);
|
|
102
|
+
let imports;
|
|
103
|
+
try {
|
|
104
|
+
imports = pyimports.toJs();
|
|
105
|
+
} finally {
|
|
106
|
+
pyimports.destroy();
|
|
107
|
+
}
|
|
108
|
+
if (imports.length === 0) {
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
let packageNames = API._import_name_to_package_name;
|
|
113
|
+
let packages: Set<string> = new Set();
|
|
114
|
+
for (let name of imports) {
|
|
115
|
+
if (packageNames.has(name)) {
|
|
116
|
+
packages.add(packageNames.get(name));
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
if (packages.size) {
|
|
120
|
+
await loadPackage(Array.from(packages), messageCallback, errorCallback);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Runs Python code using `PyCF_ALLOW_TOP_LEVEL_AWAIT
|
|
126
|
+
* <https://docs.python.org/3/library/ast.html?highlight=pycf_allow_top_level_await#ast.PyCF_ALLOW_TOP_LEVEL_AWAIT>`_.
|
|
127
|
+
*
|
|
128
|
+
* For example:
|
|
129
|
+
*
|
|
130
|
+
* .. code-block:: pyodide
|
|
131
|
+
*
|
|
132
|
+
* let result = await pyodide.runPythonAsync(`
|
|
133
|
+
* from js import fetch
|
|
134
|
+
* response = await fetch("./packages.json")
|
|
135
|
+
* packages = await response.json()
|
|
136
|
+
* # If final statement is an expression, its value is returned to JavaScript
|
|
137
|
+
* len(packages.packages.object_keys())
|
|
138
|
+
* `);
|
|
139
|
+
* console.log(result); // 79
|
|
140
|
+
*
|
|
141
|
+
* .. admonition:: Python imports :class: warning
|
|
142
|
+
*
|
|
143
|
+
* Since pyodide 0.18.0, you must call :js:func:`loadPackagesFromImports` to
|
|
144
|
+
* import any python packages referenced via `import` statements in your
|
|
145
|
+
* code. This function will no longer do it for you.
|
|
146
|
+
*
|
|
147
|
+
* .. admonition:: Positional globals argument :class: warning
|
|
148
|
+
*
|
|
149
|
+
* In Pyodide v0.19, this function took the globals parameter as a
|
|
150
|
+
* positional argument rather than as a named argument. In v0.20 this will
|
|
151
|
+
* still work but it is deprecated. It will be removed in v0.21.
|
|
152
|
+
*
|
|
153
|
+
* @param code Python code to evaluate
|
|
154
|
+
* @param options
|
|
155
|
+
* @param options.globals An optional Python dictionary to use as the globals.
|
|
156
|
+
* Defaults to :any:`pyodide.globals`. Uses the Python API
|
|
157
|
+
* :any:`pyodide.eval_code_async` to evaluate the code.
|
|
158
|
+
* @returns The result of the Python code translated to JavaScript.
|
|
159
|
+
* @async
|
|
160
|
+
*/
|
|
161
|
+
export async function runPythonAsync(
|
|
162
|
+
code: string,
|
|
163
|
+
options: { globals?: PyProxy } = {}
|
|
164
|
+
): Promise<any> {
|
|
165
|
+
if (API.isPyProxy(options)) {
|
|
166
|
+
options = { globals: options as PyProxy };
|
|
167
|
+
if (!runPythonPositionalGlobalsDeprecationWarned) {
|
|
168
|
+
console.warn(
|
|
169
|
+
"Passing a PyProxy as the second argument to runPython is deprecated. Use 'runPythonAsync(code, {globals : some_dict})' instead."
|
|
170
|
+
);
|
|
171
|
+
runPythonPositionalGlobalsDeprecationWarned = true;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
if (!options.globals) {
|
|
175
|
+
options.globals = API.globals;
|
|
176
|
+
}
|
|
177
|
+
return await API.pyodide_py.eval_code_async(code, options.globals);
|
|
178
|
+
}
|
|
179
|
+
API.runPythonAsync = runPythonAsync;
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Registers the JavaScript object ``module`` as a JavaScript module named
|
|
183
|
+
* ``name``. This module can then be imported from Python using the standard
|
|
184
|
+
* Python import system. If another module by the same name has already been
|
|
185
|
+
* imported, this won't have much effect unless you also delete the imported
|
|
186
|
+
* module from ``sys.modules``. This calls the {any}`pyodide_py` API
|
|
187
|
+
* :func:`pyodide.register_js_module`.
|
|
188
|
+
*
|
|
189
|
+
* @param name Name of the JavaScript module to add
|
|
190
|
+
* @param module JavaScript object backing the module
|
|
191
|
+
*/
|
|
192
|
+
export function registerJsModule(name: string, module: object) {
|
|
193
|
+
API.pyodide_py.register_js_module(name, module);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Tell Pyodide about Comlink.
|
|
198
|
+
* Necessary to enable importing Comlink proxies into Python.
|
|
199
|
+
*/
|
|
200
|
+
export function registerComlink(Comlink: any) {
|
|
201
|
+
API._Comlink = Comlink;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Unregisters a JavaScript module with given name that has been previously
|
|
206
|
+
* registered with :js:func:`pyodide.registerJsModule` or
|
|
207
|
+
* :func:`pyodide.register_js_module`. If a JavaScript module with that name
|
|
208
|
+
* does not already exist, will throw an error. Note that if the module has
|
|
209
|
+
* already been imported, this won't have much effect unless you also delete
|
|
210
|
+
* the imported module from ``sys.modules``. This calls the :any:`pyodide_py` API
|
|
211
|
+
* :func:`pyodide.unregister_js_module`.
|
|
212
|
+
*
|
|
213
|
+
* @param name Name of the JavaScript module to remove
|
|
214
|
+
*/
|
|
215
|
+
export function unregisterJsModule(name: string) {
|
|
216
|
+
API.pyodide_py.unregister_js_module(name);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Convert the JavaScript object to a Python object as best as possible.
|
|
221
|
+
*
|
|
222
|
+
* This is similar to :any:`JsProxy.to_py` but for use from JavaScript. If the
|
|
223
|
+
* object is immutable or a :any:`PyProxy`, it will be returned unchanged. If
|
|
224
|
+
* the object cannot be converted into Python, it will be returned unchanged.
|
|
225
|
+
*
|
|
226
|
+
* See :ref:`type-translations-jsproxy-to-py` for more information.
|
|
227
|
+
*
|
|
228
|
+
* @param obj
|
|
229
|
+
* @param options
|
|
230
|
+
* @returns The object converted to Python.
|
|
231
|
+
*/
|
|
232
|
+
export function toPy(
|
|
233
|
+
obj: any,
|
|
234
|
+
{
|
|
235
|
+
depth,
|
|
236
|
+
defaultConverter,
|
|
237
|
+
}: {
|
|
238
|
+
/**
|
|
239
|
+
* Optional argument to limit the depth of the conversion.
|
|
240
|
+
*/
|
|
241
|
+
depth: number;
|
|
242
|
+
/**
|
|
243
|
+
* Optional argument to convert objects with no default conversion. See the
|
|
244
|
+
* documentation of :any:`JsProxy.to_py`.
|
|
245
|
+
*/
|
|
246
|
+
defaultConverter?: (
|
|
247
|
+
value: any,
|
|
248
|
+
converter: (value: any) => any,
|
|
249
|
+
cacheConversion: (input: any, output: any) => any
|
|
250
|
+
) => any;
|
|
251
|
+
} = { depth: -1 }
|
|
252
|
+
): any {
|
|
253
|
+
// No point in converting these, it'd be dumb to proxy them so they'd just
|
|
254
|
+
// get converted back by `js2python` at the end
|
|
255
|
+
switch (typeof obj) {
|
|
256
|
+
case "string":
|
|
257
|
+
case "number":
|
|
258
|
+
case "boolean":
|
|
259
|
+
case "bigint":
|
|
260
|
+
case "undefined":
|
|
261
|
+
return obj;
|
|
262
|
+
}
|
|
263
|
+
if (!obj || API.isPyProxy(obj)) {
|
|
264
|
+
return obj;
|
|
265
|
+
}
|
|
266
|
+
let obj_id = 0;
|
|
267
|
+
let py_result = 0;
|
|
268
|
+
let result = 0;
|
|
269
|
+
try {
|
|
270
|
+
obj_id = Hiwire.new_value(obj);
|
|
271
|
+
try {
|
|
272
|
+
py_result = Module.js2python_convert(obj_id, { depth, defaultConverter });
|
|
273
|
+
} catch (e) {
|
|
274
|
+
if (e instanceof Module._PropagatePythonError) {
|
|
275
|
+
Module._pythonexc2js();
|
|
276
|
+
}
|
|
277
|
+
throw e;
|
|
278
|
+
}
|
|
279
|
+
if (Module._JsProxy_Check(py_result)) {
|
|
280
|
+
// Oops, just created a JsProxy. Return the original object.
|
|
281
|
+
return obj;
|
|
282
|
+
// return Module.pyproxy_new(py_result);
|
|
283
|
+
}
|
|
284
|
+
result = Module._python2js(py_result);
|
|
285
|
+
if (result === 0) {
|
|
286
|
+
Module._pythonexc2js();
|
|
287
|
+
}
|
|
288
|
+
} finally {
|
|
289
|
+
Hiwire.decref(obj_id);
|
|
290
|
+
Module._Py_DecRef(py_result);
|
|
291
|
+
}
|
|
292
|
+
return Hiwire.pop_value(result);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Imports a module and returns it.
|
|
297
|
+
*
|
|
298
|
+
* .. admonition:: Warning
|
|
299
|
+
* :class: warning
|
|
300
|
+
*
|
|
301
|
+
* This function has a completely different behavior than the old removed pyimport function!
|
|
302
|
+
*
|
|
303
|
+
* ``pyimport`` is roughly equivalent to:
|
|
304
|
+
*
|
|
305
|
+
* .. code-block:: js
|
|
306
|
+
*
|
|
307
|
+
* pyodide.runPython(`import ${pkgname}; ${pkgname}`);
|
|
308
|
+
*
|
|
309
|
+
* except that the global namespace will not change.
|
|
310
|
+
*
|
|
311
|
+
* Example:
|
|
312
|
+
*
|
|
313
|
+
* .. code-block:: js
|
|
314
|
+
*
|
|
315
|
+
* let sysmodule = pyodide.pyimport("sys");
|
|
316
|
+
* let recursionLimit = sys.getrecursionlimit();
|
|
317
|
+
*
|
|
318
|
+
* @param mod_name The name of the module to import
|
|
319
|
+
* @returns A PyProxy for the imported module
|
|
320
|
+
*/
|
|
321
|
+
export function pyimport(mod_name: string): PyProxy {
|
|
322
|
+
return API.importlib.import_module(mod_name);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* Unpack an archive into a target directory.
|
|
327
|
+
*
|
|
328
|
+
* @param buffer The archive as an ArrayBuffer or TypedArray.
|
|
329
|
+
* @param format The format of the archive. Should be one of the formats recognized by `shutil.unpack_archive`.
|
|
330
|
+
* By default the options are 'bztar', 'gztar', 'tar', 'zip', and 'wheel'. Several synonyms are accepted for each format, e.g.,
|
|
331
|
+
* for 'gztar' any of '.gztar', '.tar.gz', '.tgz', 'tar.gz' or 'tgz' are considered to be synonyms.
|
|
332
|
+
*
|
|
333
|
+
* @param extract_dir The directory to unpack the archive into. Defaults to the working directory.
|
|
334
|
+
*/
|
|
335
|
+
export function unpackArchive(
|
|
336
|
+
buffer: TypedArray,
|
|
337
|
+
format: string,
|
|
338
|
+
extract_dir?: string
|
|
339
|
+
) {
|
|
340
|
+
if (!API._util_module) {
|
|
341
|
+
API._util_module = pyimport("pyodide._util");
|
|
342
|
+
}
|
|
343
|
+
API._util_module.unpack_buffer_archive.callKwargs(buffer, {
|
|
344
|
+
format,
|
|
345
|
+
extract_dir,
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* @private
|
|
351
|
+
*/
|
|
352
|
+
API.saveState = () => API.pyodide_py._state.save_state();
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* @private
|
|
356
|
+
*/
|
|
357
|
+
API.restoreState = (state: any) => API.pyodide_py._state.restore_state(state);
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* Sets the interrupt buffer to be `interrupt_buffer`. This is only useful when
|
|
361
|
+
* Pyodide is used in a webworker. The buffer should be a `SharedArrayBuffer`
|
|
362
|
+
* shared with the main browser thread (or another worker). To request an
|
|
363
|
+
* interrupt, a `2` should be written into `interrupt_buffer` (2 is the posix
|
|
364
|
+
* constant for SIGINT).
|
|
365
|
+
*/
|
|
366
|
+
export function setInterruptBuffer(interrupt_buffer: TypedArray) {
|
|
367
|
+
API.interrupt_buffer = interrupt_buffer;
|
|
368
|
+
Module._set_pyodide_callback(!!interrupt_buffer);
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* Throws a KeyboardInterrupt error if a KeyboardInterrupt has been requested
|
|
373
|
+
* via the interrupt buffer.
|
|
374
|
+
*
|
|
375
|
+
* This can be used to enable keyboard interrupts during execution of JavaScript
|
|
376
|
+
* code, just as ``PyErr_CheckSignals`` is used to enable keyboard interrupts
|
|
377
|
+
* during execution of C code.
|
|
378
|
+
*/
|
|
379
|
+
export function checkInterrupt() {
|
|
380
|
+
if (API.interrupt_buffer[0] === 2) {
|
|
381
|
+
API.interrupt_buffer[0] = 0;
|
|
382
|
+
Module._PyErr_SetInterrupt();
|
|
383
|
+
API.runPython("");
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
export type PyodideInterface = {
|
|
388
|
+
globals: typeof globals;
|
|
389
|
+
FS: typeof FS;
|
|
390
|
+
pyodide_py: typeof pyodide_py;
|
|
391
|
+
version: typeof version;
|
|
392
|
+
loadPackage: typeof loadPackage;
|
|
393
|
+
loadPackagesFromImports: typeof loadPackagesFromImports;
|
|
394
|
+
loadedPackages: typeof loadedPackages;
|
|
395
|
+
isPyProxy: typeof isPyProxy;
|
|
396
|
+
runPython: typeof runPython;
|
|
397
|
+
runPythonAsync: typeof runPythonAsync;
|
|
398
|
+
registerJsModule: typeof registerJsModule;
|
|
399
|
+
unregisterJsModule: typeof unregisterJsModule;
|
|
400
|
+
setInterruptBuffer: typeof setInterruptBuffer;
|
|
401
|
+
checkInterrupt: typeof checkInterrupt;
|
|
402
|
+
toPy: typeof toPy;
|
|
403
|
+
pyimport: typeof pyimport;
|
|
404
|
+
unpackArchive: typeof unpackArchive;
|
|
405
|
+
registerComlink: typeof registerComlink;
|
|
406
|
+
PythonError: typeof PythonError;
|
|
407
|
+
PyBuffer: typeof PyBuffer;
|
|
408
|
+
};
|
|
409
|
+
|
|
410
|
+
/**
|
|
411
|
+
* An alias to the `Emscripten File System API
|
|
412
|
+
* <https://emscripten.org/docs/api_reference/Filesystem-API.html>`_.
|
|
413
|
+
*
|
|
414
|
+
* This provides a wide range of POSIX-`like` file/device operations, including
|
|
415
|
+
* `mount
|
|
416
|
+
* <https://emscripten.org/docs/api_reference/Filesystem-API.html#FS.mount>`_
|
|
417
|
+
* which can be used to extend the in-memory filesystem with features like `persistence
|
|
418
|
+
* <https://emscripten.org/docs/api_reference/Filesystem-API.html#persistent-data>`_.
|
|
419
|
+
*
|
|
420
|
+
* While all the file systems implementations are enabled, only the default
|
|
421
|
+
* ``MEMFS`` is guaranteed to work in all runtime settings. The implementations
|
|
422
|
+
* are available as members of ``FS.filesystems``:
|
|
423
|
+
* ``IDBFS``, ``NODEFS``, ``PROXYFS``, ``WORKERFS``.
|
|
424
|
+
*/
|
|
425
|
+
export let FS: any;
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* @private
|
|
429
|
+
*/
|
|
430
|
+
export function makePublicAPI(): PyodideInterface {
|
|
431
|
+
FS = Module.FS;
|
|
432
|
+
let namespace = {
|
|
433
|
+
globals,
|
|
434
|
+
FS,
|
|
435
|
+
pyodide_py,
|
|
436
|
+
version,
|
|
437
|
+
loadPackage,
|
|
438
|
+
loadPackagesFromImports,
|
|
439
|
+
loadedPackages,
|
|
440
|
+
isPyProxy,
|
|
441
|
+
runPython,
|
|
442
|
+
runPythonAsync,
|
|
443
|
+
registerJsModule,
|
|
444
|
+
unregisterJsModule,
|
|
445
|
+
setInterruptBuffer,
|
|
446
|
+
checkInterrupt,
|
|
447
|
+
toPy,
|
|
448
|
+
pyimport,
|
|
449
|
+
unpackArchive,
|
|
450
|
+
registerComlink,
|
|
451
|
+
PythonError,
|
|
452
|
+
PyBuffer,
|
|
453
|
+
_module: Module,
|
|
454
|
+
_api: API,
|
|
455
|
+
};
|
|
456
|
+
|
|
457
|
+
API.public_api = namespace;
|
|
458
|
+
return namespace;
|
|
459
|
+
}
|
package/compat.ts
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
// Detect if we're in node
|
|
2
|
+
declare var process: any;
|
|
3
|
+
|
|
4
|
+
export const IN_NODE =
|
|
5
|
+
typeof process !== "undefined" &&
|
|
6
|
+
process.release &&
|
|
7
|
+
process.release.name === "node" &&
|
|
8
|
+
typeof process.browser ===
|
|
9
|
+
"undefined"; /* This last condition checks if we run the browser shim of process */
|
|
10
|
+
|
|
11
|
+
let nodePathMod: any;
|
|
12
|
+
let nodeFetch: any;
|
|
13
|
+
let nodeVmMod: any;
|
|
14
|
+
/** @private */
|
|
15
|
+
export let nodeFsPromisesMod: any;
|
|
16
|
+
|
|
17
|
+
declare var globalThis: {
|
|
18
|
+
importScripts: (url: string) => void;
|
|
19
|
+
document?: any;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* If we're in node, it's most convenient to import various node modules on
|
|
24
|
+
* initialization. Otherwise, this does nothing.
|
|
25
|
+
* @private
|
|
26
|
+
*/
|
|
27
|
+
export async function initNodeModules() {
|
|
28
|
+
if (!IN_NODE) {
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
// @ts-ignore
|
|
32
|
+
nodePathMod = (await import(/* webpackIgnore: true */ "path")).default;
|
|
33
|
+
nodeFsPromisesMod = await import(/* webpackIgnore: true */ "fs/promises");
|
|
34
|
+
// @ts-ignore
|
|
35
|
+
nodeFetch = (await import(/* webpackIgnore: true */ "node-fetch")).default;
|
|
36
|
+
// @ts-ignore
|
|
37
|
+
nodeVmMod = (await import(/* webpackIgnore: true */ "vm")).default;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Load a binary file, only for use in Node. If the path explicitly is a URL,
|
|
42
|
+
* then fetch from a URL, else load from the file system.
|
|
43
|
+
* @param indexURL base path to resolve relative paths
|
|
44
|
+
* @param path the path to load
|
|
45
|
+
* @returns An ArrayBuffer containing the binary data
|
|
46
|
+
* @private
|
|
47
|
+
*/
|
|
48
|
+
async function node_loadBinaryFile(
|
|
49
|
+
indexURL: string,
|
|
50
|
+
path: string
|
|
51
|
+
): Promise<Uint8Array> {
|
|
52
|
+
if (path.includes("://")) {
|
|
53
|
+
let response = await nodeFetch(path);
|
|
54
|
+
if (!response.ok) {
|
|
55
|
+
throw new Error(`Failed to load '${path}': request failed.`);
|
|
56
|
+
}
|
|
57
|
+
return await response.arrayBuffer();
|
|
58
|
+
} else {
|
|
59
|
+
const data = await nodeFsPromisesMod.readFile(`${indexURL}${path}`);
|
|
60
|
+
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Load a binary file, only for use in browser. Resolves relative paths against
|
|
66
|
+
* indexURL.
|
|
67
|
+
*
|
|
68
|
+
* @param indexURL base path to resolve relative paths
|
|
69
|
+
* @param path the path to load
|
|
70
|
+
* @returns A Uint8Array containing the binary data
|
|
71
|
+
* @private
|
|
72
|
+
*/
|
|
73
|
+
async function browser_loadBinaryFile(
|
|
74
|
+
indexURL: string,
|
|
75
|
+
path: string
|
|
76
|
+
): Promise<Uint8Array> {
|
|
77
|
+
// @ts-ignore
|
|
78
|
+
const base = new URL(indexURL, location);
|
|
79
|
+
const url = new URL(path, base);
|
|
80
|
+
// @ts-ignore
|
|
81
|
+
let response = await fetch(url);
|
|
82
|
+
if (!response.ok) {
|
|
83
|
+
throw new Error(`Failed to load '${url}': request failed.`);
|
|
84
|
+
}
|
|
85
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** @private */
|
|
89
|
+
export let _loadBinaryFile: (
|
|
90
|
+
indexURL: string,
|
|
91
|
+
path: string
|
|
92
|
+
) => Promise<Uint8Array>;
|
|
93
|
+
if (IN_NODE) {
|
|
94
|
+
_loadBinaryFile = node_loadBinaryFile;
|
|
95
|
+
} else {
|
|
96
|
+
_loadBinaryFile = browser_loadBinaryFile;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Currently loadScript is only used once to load `pyodide.asm.js`.
|
|
101
|
+
* @param url
|
|
102
|
+
* @async
|
|
103
|
+
* @private
|
|
104
|
+
*/
|
|
105
|
+
export let loadScript: (url: string) => Promise<void>;
|
|
106
|
+
|
|
107
|
+
if (globalThis.document) {
|
|
108
|
+
// browser
|
|
109
|
+
loadScript = async (url) => await import(/* webpackIgnore: true */ url);
|
|
110
|
+
} else if (globalThis.importScripts) {
|
|
111
|
+
// webworker
|
|
112
|
+
loadScript = async (url) => {
|
|
113
|
+
// This is async only for consistency
|
|
114
|
+
try {
|
|
115
|
+
// use importScripts in classic web worker
|
|
116
|
+
globalThis.importScripts(url);
|
|
117
|
+
} catch (e) {
|
|
118
|
+
// importScripts throws TypeError in a module type web worker, use import instead
|
|
119
|
+
if (e instanceof TypeError) {
|
|
120
|
+
await import(url);
|
|
121
|
+
} else {
|
|
122
|
+
throw e;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
} else if (IN_NODE) {
|
|
127
|
+
loadScript = nodeLoadScript;
|
|
128
|
+
} else {
|
|
129
|
+
throw new Error("Cannot determine runtime environment");
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Load a text file and executes it as Javascript
|
|
134
|
+
* @param url The path to load. May be a url or a relative file system path.
|
|
135
|
+
* @private
|
|
136
|
+
*/
|
|
137
|
+
async function nodeLoadScript(url: string) {
|
|
138
|
+
if (url.includes("://")) {
|
|
139
|
+
// If it's a url, load it with fetch then eval it.
|
|
140
|
+
nodeVmMod.runInThisContext(await (await nodeFetch(url)).text());
|
|
141
|
+
} else {
|
|
142
|
+
// Otherwise, hopefully it is a relative path we can load from the file
|
|
143
|
+
// system.
|
|
144
|
+
await import(nodePathMod.resolve(url));
|
|
145
|
+
}
|
|
146
|
+
}
|
package/index.test-d.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { expectType, expectAssignable } from "tsd";
|
|
2
2
|
import {
|
|
3
3
|
loadPyodide,
|
|
4
|
-
Py2JsResult,
|
|
5
4
|
PyProxy,
|
|
6
5
|
PyProxyWithLength,
|
|
7
6
|
PyProxyWithGet,
|
|
@@ -14,13 +13,12 @@ import {
|
|
|
14
13
|
PyProxyCallable,
|
|
15
14
|
PyBuffer,
|
|
16
15
|
TypedArray,
|
|
17
|
-
} from "
|
|
16
|
+
} from "./pyodide";
|
|
18
17
|
|
|
19
18
|
async function main() {
|
|
20
|
-
let pyodide = await loadPyodide(
|
|
21
|
-
expectType<Promise<typeof pyodide>>(
|
|
22
|
-
|
|
23
|
-
);
|
|
19
|
+
let pyodide = await loadPyodide();
|
|
20
|
+
expectType<Promise<typeof pyodide>>(loadPyodide({ indexURL: "blah" }));
|
|
21
|
+
expectType<Promise<typeof pyodide>>(loadPyodide({ fullStdLib: true }));
|
|
24
22
|
|
|
25
23
|
expectType<Promise<typeof pyodide>>(
|
|
26
24
|
loadPyodide({
|
|
@@ -34,18 +32,20 @@ async function main() {
|
|
|
34
32
|
|
|
35
33
|
expectType<PyProxy>(pyodide.globals);
|
|
36
34
|
|
|
37
|
-
let x:
|
|
35
|
+
let x: any;
|
|
38
36
|
expectType<boolean>(pyodide.isPyProxy(x));
|
|
39
37
|
if (pyodide.isPyProxy(x)) {
|
|
40
38
|
expectType<PyProxy>(x);
|
|
41
39
|
} else {
|
|
42
|
-
expectType<
|
|
40
|
+
expectType<any>(x);
|
|
43
41
|
}
|
|
44
42
|
|
|
45
43
|
let px: PyProxy = <PyProxy>{};
|
|
46
44
|
|
|
47
|
-
expectType<
|
|
48
|
-
expectType<
|
|
45
|
+
expectType<any>(pyodide.runPython("1+1"));
|
|
46
|
+
expectType<any>(pyodide.runPython("1+1", { globals: px }));
|
|
47
|
+
expectType<Promise<any>>(pyodide.runPythonAsync("1+1"));
|
|
48
|
+
expectType<Promise<any>>(pyodide.runPythonAsync("1+1", { globals: px }));
|
|
49
49
|
|
|
50
50
|
expectType<Promise<void>>(pyodide.loadPackagesFromImports("import some_pkg"));
|
|
51
51
|
expectType<Promise<void>>(
|
|
@@ -80,10 +80,10 @@ async function main() {
|
|
|
80
80
|
expectType<void>(pyodide.unregisterJsModule("blah"));
|
|
81
81
|
|
|
82
82
|
pyodide.setInterruptBuffer(new Int32Array(1));
|
|
83
|
-
expectType<
|
|
83
|
+
expectType<any>(pyodide.toPy({}));
|
|
84
84
|
expectType<string>(pyodide.version);
|
|
85
85
|
|
|
86
|
-
expectType<
|
|
86
|
+
expectType<any>(px.x);
|
|
87
87
|
expectType<PyProxy>(px.copy());
|
|
88
88
|
expectType<void>(px.destroy("blah"));
|
|
89
89
|
expectType<void>(px.destroy());
|
|
@@ -98,7 +98,7 @@ async function main() {
|
|
|
98
98
|
|
|
99
99
|
if (px.supportsGet()) {
|
|
100
100
|
expectType<PyProxyWithGet>(px);
|
|
101
|
-
expectType<(x: any) =>
|
|
101
|
+
expectType<(x: any) => any>(px.get);
|
|
102
102
|
}
|
|
103
103
|
|
|
104
104
|
if (px.supportsHas()) {
|
|
@@ -118,7 +118,7 @@ async function main() {
|
|
|
118
118
|
|
|
119
119
|
if (px.isAwaitable()) {
|
|
120
120
|
expectType<PyProxyAwaitable>(px);
|
|
121
|
-
expectType<
|
|
121
|
+
expectType<any>(await px);
|
|
122
122
|
}
|
|
123
123
|
|
|
124
124
|
if (px.isBuffer()) {
|
|
@@ -141,22 +141,22 @@ async function main() {
|
|
|
141
141
|
|
|
142
142
|
if (px.isCallable()) {
|
|
143
143
|
expectType<PyProxyCallable>(px);
|
|
144
|
-
expectType<
|
|
145
|
-
expectAssignable<(...args: any[]) =>
|
|
144
|
+
expectType<any>(px(1, 2, 3));
|
|
145
|
+
expectAssignable<(...args: any[]) => any>(px);
|
|
146
146
|
}
|
|
147
147
|
|
|
148
148
|
if (px.isIterable()) {
|
|
149
149
|
expectType<PyProxyIterable>(px);
|
|
150
150
|
for (let x of px) {
|
|
151
|
-
expectType<
|
|
151
|
+
expectType<any>(x);
|
|
152
152
|
}
|
|
153
153
|
let it = px[Symbol.iterator]();
|
|
154
|
-
expectAssignable<{ done?:
|
|
154
|
+
expectAssignable<{ done?: any; value: any }>(it.next());
|
|
155
155
|
}
|
|
156
156
|
|
|
157
157
|
if (px.isIterator()) {
|
|
158
158
|
expectType<PyProxyIterator>(px);
|
|
159
|
-
expectAssignable<{ done?:
|
|
160
|
-
expectAssignable<{ done?:
|
|
159
|
+
expectAssignable<{ done?: any; value: any }>(px.next());
|
|
160
|
+
expectAssignable<{ done?: any; value: any }>(px.next(22));
|
|
161
161
|
}
|
|
162
162
|
}
|