-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathpyodide.js
More file actions
202 lines (190 loc) · 7.62 KB
/
pyodide.js
File metadata and controls
202 lines (190 loc) · 7.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
import { createProgress, writeFile } from './_utils.js';
import { getFormat, loader, loadProgress, registerJSModule, run, runAsync, runEvent } from './_python.js';
import { stdio } from './_io.js';
import { IDBMapSync, isArray, fixedRelative } from '../utils.js';
const type = 'pyodide';
const toJsOptions = { dict_converter: Object.fromEntries };
const { stringify } = JSON;
const { apply } = Reflect;
const FunctionPrototype = Function.prototype;
// REQUIRES INTEGRATION TEST
/* c8 ignore start */
const overrideMethod = method => function (...args) {
return apply(method, this, args);
};
let pyproxy, to_js;
const override = intercept => {
const proxies = new WeakMap;
const patch = args => {
for (let arg, i = 0; i < args.length; i++) {
switch (typeof(arg = args[i])) {
case 'object':
if (arg === null) break;
// falls through
case 'function': {
if (pyproxy in arg && !arg[pyproxy].shared?.gcRegistered) {
intercept = false;
let proxy = proxies.get(arg)?.deref();
if (!proxy) {
proxy = to_js(arg);
const wr = new WeakRef(proxy);
proxies.set(arg, wr);
proxies.set(proxy, wr);
}
args[i] = proxy;
intercept = true;
}
break;
}
}
}
};
// the patch
Object.defineProperties(FunctionPrototype, {
apply: {
value(context, args) {
if (intercept) patch(args);
return apply(this, context, args);
}
},
call: {
value(context, ...args) {
if (intercept) patch(args);
return apply(this, context, args);
}
}
});
};
const progress = createProgress('py');
const indexURLs = new WeakMap();
export default {
type,
module: (version = '0.27.7') =>
`https://cdn.jsdelivr.net/pyodide/v${version}/full/pyodide.mjs`,
async engine({ loadPyodide, version }, config, url, baseURL) {
progress('Loading Pyodide');
let { packages, index_urls } = config;
if (packages) packages = packages.map(fixedRelative, baseURL);
progress('Loading Storage');
const indexURL = url.slice(0, url.lastIndexOf('/'));
// each pyodide version shares its own cache
const storage = new IDBMapSync(`${indexURL}@${version}`);
const options = { indexURL };
const save = config.packages_cache !== 'never';
await storage.sync();
// packages_cache = 'never' means: erase the whole DB
if (!save) storage.clear();
// otherwise check if cache is known
else if (packages) {
// packages_cache = 'passthrough' means: do not use micropip.install
if (config.packages_cache === 'passthrough') {
options.packages = packages;
packages = null;
storage.clear();
}
else {
packages = packages.sort();
// packages are uniquely stored as JSON key
const key = stringify(packages);
if (storage.has(key)) {
const blob = new Blob(
[storage.get(key)],
{ type: 'application/json' },
);
// this should be used to bootstrap loadPyodide
options.lockFileURL = URL.createObjectURL(blob);
// versions are not currently understood by pyodide when
// a lockFileURL is used instead of micropip.install(packages)
// https://github.com/pyodide/pyodide/issues/5135#issuecomment-2441038644
// https://github.com/pyscript/pyscript/issues/2245
options.packages = packages.map(name => name.split(/[>=<]=/)[0]);
packages = null;
}
}
}
progress('Loaded Storage');
const { stderr, stdout, get } = stdio();
const interpreter = await get(
loadPyodide({ stderr, stdout, ...options }),
);
if (config.debug) interpreter.setDebug(true);
const py_imports = importPackages.bind(interpreter);
if (index_urls) indexURLs.set(interpreter, index_urls);
loader.set(interpreter, py_imports);
await loadProgress(this, progress, interpreter, config, baseURL);
// if cache wasn't know, import and freeze it for the next time
if (packages) await py_imports(packages, storage, save);
await storage.close();
if (options.lockFileURL) URL.revokeObjectURL(options.lockFileURL);
progress('Loaded Pyodide');
if (config.experimental_create_proxy === 'auto') {
interpreter.runPython([
'import js',
'from pyodide.ffi import to_js',
'o=js.Object.fromEntries',
'js.experimental_create_proxy=lambda r:to_js(r,dict_converter=o)'
].join(';'), { globals: interpreter.toPy({}) });
to_js = globalThis.experimental_create_proxy;
delete globalThis.experimental_create_proxy;
[pyproxy] = Reflect.ownKeys(to_js).filter(
k => (
typeof k === 'symbol' &&
String(k) === 'Symbol(pyproxy.attrs)'
)
);
override(true);
}
return interpreter;
},
registerJSModule,
run: overrideMethod(run),
runAsync: overrideMethod(runAsync),
runEvent: overrideMethod(runEvent),
transform: (interpreter, value) => apply(transform, interpreter, [value]),
writeFile: (interpreter, path, buffer, url) => {
const format = getFormat(path, url);
if (format) {
return interpreter.unpackArchive(buffer, format, {
extractDir: path.slice(0, -1)
});
}
const { FS, PATH, _module: { PATH_FS } } = interpreter;
return writeFile({ FS, PATH, PATH_FS }, path, buffer);
},
};
function transform(value) {
const { ffi: { PyProxy } } = this;
if (value && typeof value === 'object') {
if (value instanceof PyProxy) return value.toJs(toJsOptions);
// I believe this case is for LiteralMap which is not a PyProxy
// and yet it needs to be re-converted to something useful.
if (value instanceof Map) return new Map([...value.entries()]);
if (isArray(value)) return value.map(transform, this);
}
return value;
}
// exposed utility to import packages via polyscript.lazy_py_modules
async function importPackages(packages, storage, save = false) {
// temporary patch/fix console.log which is used
// not only by Pyodide but by micropip too and there's
// no way to intercept those calls otherwise
const { log } = console;
const _log = (detail, ...rest) => {
log(detail, ...rest);
console.log = log;
progress(detail);
console.log = _log;
};
console.log = _log;
await this.loadPackage('micropip');
const micropip = this.pyimport('micropip');
if (indexURLs.has(this)) micropip.set_index_urls(indexURLs.get(this));
await micropip.install(packages, { keep_going: true });
console.log = log;
if (save && (storage instanceof IDBMapSync)) {
const frozen = micropip.freeze();
storage.set(stringify(packages), frozen);
}
micropip.destroy();
}
/* c8 ignore stop */