@pyscript/core 0.1.18 → 0.1.19
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/dist/core.js +2 -2
- package/dist/core.js.map +1 -1
- package/dist/error-87e0706c.js +2 -0
- package/dist/error-87e0706c.js.map +1 -0
- package/package.json +2 -1
- package/src/config.js +102 -0
- package/src/core.js +83 -105
- package/src/fetch.js +3 -0
- package/src/plugins/error.js +1 -1
- package/src/plugins.js +1 -1
- package/types/config.d.ts +3 -0
- package/types/core.d.ts +1 -2
- package/types/fetch.d.ts +1 -0
- package/types/plugins/error.d.ts +1 -1
- package/dist/error-91f1c2f6.js +0 -2
- package/dist/error-91f1c2f6.js.map +0 -1
@@ -0,0 +1,2 @@
|
|
1
|
+
import{hooks as e}from"./core.js";function o(e){const o=document.createElement("div");o.className="py-error",o.textContent=e,o.style.cssText="\n border: 1px solid red;\n background: #ffdddd;\n color: black;\n font-family: courier, monospace;\n white-space: pre;\n overflow-x: auto;\n padding: 8px;\n margin-top: 8px;\n ",document.body.append(o)}e.onBeforeRun.add((function n(r){e.onBeforeRun.delete(n);const{stderr:t}=r.io;r.io.stderr=(e,...n)=>(o(e.message||e),t(e,...n)),addEventListener("error",(({message:e})=>{e.startsWith("Uncaught PythonError")&&o(e)}))}));export{o as notify};
|
2
|
+
//# sourceMappingURL=error-87e0706c.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"error-87e0706c.js","sources":["../src/plugins/error.js"],"sourcesContent":["// PyScript Error Plugin\nimport { hooks } from \"../core.js\";\n\nhooks.onBeforeRun.add(function override(pyScript) {\n // be sure this override happens only once\n hooks.onBeforeRun.delete(override);\n\n // trap generic `stderr` to propagate to it regardless\n const { stderr } = pyScript.io;\n\n // override it with our own logic\n pyScript.io.stderr = (error, ...rest) => {\n notify(error.message || error);\n // let other plugins or stderr hook, if any, do the rest\n return stderr(error, ...rest);\n };\n\n // be sure uncaught Python errors are also visible\n addEventListener(\"error\", ({ message }) => {\n if (message.startsWith(\"Uncaught PythonError\")) notify(message);\n });\n});\n\n// Error hook utilities\n\n// Custom function to show notifications\nexport function notify(message) {\n const div = document.createElement(\"div\");\n div.className = \"py-error\";\n div.textContent = message;\n div.style.cssText = `\n border: 1px solid red;\n background: #ffdddd;\n color: black;\n font-family: courier, monospace;\n white-space: pre;\n overflow-x: auto;\n padding: 8px;\n margin-top: 8px;\n `;\n document.body.append(div);\n}\n"],"names":["notify","message","div","document","createElement","className","textContent","style","cssText","body","append","hooks","onBeforeRun","add","override","pyScript","delete","stderr","io","error","rest","addEventListener","startsWith"],"mappings":"kCA0BO,SAASA,EAAOC,GACnB,MAAMC,EAAMC,SAASC,cAAc,OACnCF,EAAIG,UAAY,WAChBH,EAAII,YAAcL,EAClBC,EAAIK,MAAMC,QAAU,6MAUpBL,SAASM,KAAKC,OAAOR,EACzB,CAtCAS,EAAMC,YAAYC,KAAI,SAASC,EAASC,GAEpCJ,EAAMC,YAAYI,OAAOF,GAGzB,MAAMG,OAAEA,GAAWF,EAASG,GAG5BH,EAASG,GAAGD,OAAS,CAACE,KAAUC,KAC5BpB,EAAOmB,EAAMlB,SAAWkB,GAEjBF,EAAOE,KAAUC,IAI5BC,iBAAiB,SAAS,EAAGpB,cACrBA,EAAQqB,WAAW,yBAAyBtB,EAAOC,EAAQ,GAEvE"}
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "@pyscript/core",
|
3
|
-
"version": "0.1.
|
3
|
+
"version": "0.1.19",
|
4
4
|
"type": "module",
|
5
5
|
"description": "PyScript",
|
6
6
|
"module": "./index.js",
|
@@ -21,6 +21,7 @@
|
|
21
21
|
"scripts": {
|
22
22
|
"server": "npx static-handler --cors --coep --coop --corp .",
|
23
23
|
"build": "node rollup/stdlib.cjs && node rollup/plugins.cjs && rm -rf dist && rollup --config rollup/core.config.js && npm run ts",
|
24
|
+
"size": "echo -e \"\\033[1mdist/*.js file size\\033[0m\"; for js in $(ls dist/*.js); do echo -e \"\\033[2m$js:\\033[0m $(cat $js | brotli | wc -c) bytes\"; done",
|
24
25
|
"ts": "tsc -p ."
|
25
26
|
},
|
26
27
|
"keywords": [
|
package/src/config.js
ADDED
@@ -0,0 +1,102 @@
|
|
1
|
+
/**
|
2
|
+
* This file parses a generic <py-config> or config attribute
|
3
|
+
* to use as base config for all py-script elements, importing
|
4
|
+
* also a queue of plugins *before* the interpreter (if any) resolves.
|
5
|
+
*/
|
6
|
+
import { $ } from "basic-devtools";
|
7
|
+
|
8
|
+
import allPlugins from "./plugins.js";
|
9
|
+
import { robustFetch as fetch, getText } from "./fetch.js";
|
10
|
+
import { ErrorCode } from "./exceptions.js";
|
11
|
+
|
12
|
+
const badURL = (url, expected = "") => {
|
13
|
+
let message = `(${ErrorCode.BAD_CONFIG}): Invalid URL: ${url}`;
|
14
|
+
if (expected) message += `\nexpected ${expected} content`;
|
15
|
+
throw new Error(message);
|
16
|
+
};
|
17
|
+
|
18
|
+
/**
|
19
|
+
* Given a string, returns its trimmed content as text,
|
20
|
+
* fetching it from a file if the content is a URL.
|
21
|
+
* @param {string} config either JSON, TOML, or a file to fetch
|
22
|
+
* @returns {{json: boolean, toml: boolean, text: string}}
|
23
|
+
*/
|
24
|
+
const configDetails = async (config) => {
|
25
|
+
let text = config?.trim();
|
26
|
+
// we only support an object as root config
|
27
|
+
let url = "",
|
28
|
+
toml = false,
|
29
|
+
json = /^{/.test(text) && /}$/.test(text);
|
30
|
+
// handle files by extension (relaxing urls parts after)
|
31
|
+
if (!json && /\.(\w+)(?:\?\S*)?$/.test(text)) {
|
32
|
+
const ext = RegExp.$1;
|
33
|
+
if (ext === "json" && type !== "toml") json = true;
|
34
|
+
else if (ext === "toml" && type !== "json") toml = true;
|
35
|
+
else badURL(text, type);
|
36
|
+
url = text;
|
37
|
+
text = (await fetch(url).then(getText)).trim();
|
38
|
+
}
|
39
|
+
return { json, toml: toml || (!json && !!text), text, url };
|
40
|
+
};
|
41
|
+
|
42
|
+
const syntaxError = (type, url, { message }) => {
|
43
|
+
let str = `(${ErrorCode.BAD_CONFIG}): Invalid ${type}`;
|
44
|
+
if (url) str += ` @ ${url}`;
|
45
|
+
return new SyntaxError(`${str}\n${message}`);
|
46
|
+
};
|
47
|
+
|
48
|
+
// find the shared config for all py-script elements
|
49
|
+
let config, plugins, parsed, error, type;
|
50
|
+
let pyConfig = $("py-config");
|
51
|
+
if (pyConfig) config = pyConfig.getAttribute("src") || pyConfig.textContent;
|
52
|
+
else {
|
53
|
+
pyConfig = $('script[type="py"][config]');
|
54
|
+
if (pyConfig) config = pyConfig.getAttribute("config");
|
55
|
+
}
|
56
|
+
if (pyConfig) type = pyConfig.getAttribute("type");
|
57
|
+
|
58
|
+
// catch possible fetch errors
|
59
|
+
try {
|
60
|
+
const { json, toml, text, url } = await configDetails(config);
|
61
|
+
config = text;
|
62
|
+
if (json || type === "json") {
|
63
|
+
try {
|
64
|
+
parsed = JSON.parse(text);
|
65
|
+
} catch (e) {
|
66
|
+
error = syntaxError("JSON", url, e);
|
67
|
+
}
|
68
|
+
} else if (toml || type === "toml") {
|
69
|
+
try {
|
70
|
+
const { parse } = await import(
|
71
|
+
/* webpackIgnore: true */
|
72
|
+
"https://cdn.jsdelivr.net/npm/@webreflection/toml-j0.4/toml.js"
|
73
|
+
);
|
74
|
+
parsed = parse(text);
|
75
|
+
} catch (e) {
|
76
|
+
error = syntaxError("TOML", url, e);
|
77
|
+
}
|
78
|
+
}
|
79
|
+
} catch (e) {
|
80
|
+
error = e;
|
81
|
+
}
|
82
|
+
|
83
|
+
// parse all plugins and optionally ignore only
|
84
|
+
// those flagged as "undesired" via `!` prefix
|
85
|
+
const toBeAwaited = [];
|
86
|
+
for (const [key, value] of Object.entries(allPlugins)) {
|
87
|
+
if (error) {
|
88
|
+
if (key === "error") {
|
89
|
+
// show on page the config is broken, meaning that
|
90
|
+
// it was not possible to disable error plugin neither
|
91
|
+
// as that part wasn't correctly parsed anyway
|
92
|
+
value().then(({ notify }) => notify(error.message));
|
93
|
+
}
|
94
|
+
} else if (!parsed?.plugins?.includes(`!${key}`)) {
|
95
|
+
toBeAwaited.push(value());
|
96
|
+
}
|
97
|
+
}
|
98
|
+
|
99
|
+
// assign plugins as Promise.all only if needed
|
100
|
+
if (toBeAwaited.length) plugins = Promise.all(toBeAwaited);
|
101
|
+
|
102
|
+
export { config, plugins, error };
|
package/src/core.js
CHANGED
@@ -1,12 +1,7 @@
|
|
1
1
|
/*! (c) PyScript Development Team */
|
2
2
|
|
3
3
|
import "@ungap/with-resolvers";
|
4
|
-
import { $ } from "basic-devtools";
|
5
4
|
import { define, XWorker } from "polyscript";
|
6
|
-
import sync from "./sync.js";
|
7
|
-
|
8
|
-
import stdlib from "./stdlib.js";
|
9
|
-
import plugins from "./plugins.js";
|
10
5
|
|
11
6
|
// TODO: this is not strictly polyscript related but handy ... not sure
|
12
7
|
// we should factor this utility out a part but this works anyway.
|
@@ -14,29 +9,21 @@ import { queryTarget } from "../node_modules/polyscript/esm/script-handler.js";
|
|
14
9
|
import { dedent, dispatch } from "../node_modules/polyscript/esm/utils.js";
|
15
10
|
import { Hook } from "../node_modules/polyscript/esm/worker/hooks.js";
|
16
11
|
|
17
|
-
import
|
12
|
+
import sync from "./sync.js";
|
13
|
+
import stdlib from "./stdlib.js";
|
14
|
+
import { config, plugins, error } from "./config.js";
|
15
|
+
import { robustFetch as fetch, getText } from "./fetch.js";
|
18
16
|
|
19
17
|
const { assign, defineProperty, entries } = Object;
|
20
18
|
|
21
|
-
const
|
19
|
+
const TYPE = "py";
|
22
20
|
|
23
21
|
// allows lazy element features on code evaluation
|
24
22
|
let currentElement;
|
25
23
|
|
26
24
|
// create a unique identifier when/if needed
|
27
25
|
let id = 0;
|
28
|
-
const getID = (prefix =
|
29
|
-
|
30
|
-
// find the shared config for all py-script elements
|
31
|
-
let config;
|
32
|
-
let pyConfig = $("py-config");
|
33
|
-
if (pyConfig) config = pyConfig.getAttribute("src") || pyConfig.textContent;
|
34
|
-
else {
|
35
|
-
pyConfig = $('script[type="py"]');
|
36
|
-
config = pyConfig?.getAttribute("config");
|
37
|
-
}
|
38
|
-
|
39
|
-
if (/^https?:\/\//.test(config)) config = await fetch(config).then(getText);
|
26
|
+
const getID = (prefix = TYPE) => `${prefix}-${id++}`;
|
40
27
|
|
41
28
|
// generic helper to disambiguate between custom element and script
|
42
29
|
const isScript = ({ tagName }) => tagName === "SCRIPT";
|
@@ -70,7 +57,7 @@ const fetchSource = async (tag, io, asText) => {
|
|
70
57
|
if (asText) return dedent(tag.textContent);
|
71
58
|
|
72
59
|
console.warn(
|
73
|
-
|
60
|
+
`Deprecated: use <script type="${TYPE}"> for an always safe content parsing:\n`,
|
74
61
|
tag.innerHTML,
|
75
62
|
);
|
76
63
|
|
@@ -140,92 +127,82 @@ const workerHooks = {
|
|
140
127
|
[...hooks.codeAfterRunWorkerAsync].map(dedent).join("\n"),
|
141
128
|
};
|
142
129
|
|
143
|
-
// avoid running further script if the previous one had
|
144
|
-
// some import that would inevitably delay its execution
|
145
|
-
let queuePlugins;
|
146
|
-
|
147
130
|
// define the module as both `<script type="py">` and `<py-script>`
|
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
|
-
// this grants queued results when first script/tag has plugins
|
184
|
-
// and the second one *might* rely on first tag execution
|
185
|
-
if (toBeAwaited.length) {
|
186
|
-
const all = Promise.all(toBeAwaited);
|
187
|
-
queuePlugins = queuePlugins ? queuePlugins.then(() => all) : all;
|
188
|
-
}
|
189
|
-
|
190
|
-
if (queuePlugins) await queuePlugins;
|
191
|
-
|
192
|
-
// allows plugins to do whatever they want with the element
|
193
|
-
// before regular stuff happens in here
|
194
|
-
for (const callback of hooks.onInterpreterReady)
|
195
|
-
callback(pyodide, element);
|
196
|
-
|
197
|
-
if (isScript(element)) {
|
198
|
-
const {
|
199
|
-
attributes: { async: isAsync, target },
|
200
|
-
} = element;
|
201
|
-
const hasTarget = !!target?.value;
|
202
|
-
const show = hasTarget
|
203
|
-
? queryTarget(target.value)
|
204
|
-
: document.createElement("script-py");
|
205
|
-
|
206
|
-
if (!hasTarget) {
|
207
|
-
const { head, body } = document;
|
208
|
-
if (head.contains(element)) body.append(show);
|
209
|
-
else element.after(show);
|
131
|
+
// but only if the config didn't throw an error
|
132
|
+
error ||
|
133
|
+
define(TYPE, {
|
134
|
+
config,
|
135
|
+
env: `${TYPE}-script`,
|
136
|
+
interpreter: "pyodide",
|
137
|
+
...workerHooks,
|
138
|
+
onWorkerReady(_, xworker) {
|
139
|
+
assign(xworker.sync, sync);
|
140
|
+
},
|
141
|
+
onBeforeRun(pyodide, element) {
|
142
|
+
currentElement = element;
|
143
|
+
bootstrapNodeAndPlugins(pyodide, element, before, "onBeforeRun");
|
144
|
+
},
|
145
|
+
onBeforeRunAsync(pyodide, element) {
|
146
|
+
currentElement = element;
|
147
|
+
bootstrapNodeAndPlugins(
|
148
|
+
pyodide,
|
149
|
+
element,
|
150
|
+
before,
|
151
|
+
"onBeforeRunAsync",
|
152
|
+
);
|
153
|
+
},
|
154
|
+
onAfterRun(pyodide, element) {
|
155
|
+
bootstrapNodeAndPlugins(pyodide, element, after, "onAfterRun");
|
156
|
+
},
|
157
|
+
onAfterRunAsync(pyodide, element) {
|
158
|
+
bootstrapNodeAndPlugins(pyodide, element, after, "onAfterRunAsync");
|
159
|
+
},
|
160
|
+
async onInterpreterReady(pyodide, element) {
|
161
|
+
if (shouldRegister) {
|
162
|
+
shouldRegister = false;
|
163
|
+
registerModule(pyodide);
|
210
164
|
}
|
211
|
-
if (!show.id) show.id = getID();
|
212
165
|
|
213
|
-
//
|
214
|
-
|
215
|
-
|
216
|
-
|
217
|
-
//
|
218
|
-
|
219
|
-
|
220
|
-
|
221
|
-
)
|
222
|
-
|
223
|
-
|
224
|
-
|
225
|
-
|
226
|
-
|
227
|
-
|
228
|
-
|
166
|
+
// ensure plugins are bootstrapped already
|
167
|
+
if (plugins) await plugins;
|
168
|
+
|
169
|
+
// allows plugins to do whatever they want with the element
|
170
|
+
// before regular stuff happens in here
|
171
|
+
for (const callback of hooks.onInterpreterReady)
|
172
|
+
callback(pyodide, element);
|
173
|
+
|
174
|
+
if (isScript(element)) {
|
175
|
+
const {
|
176
|
+
attributes: { async: isAsync, target },
|
177
|
+
} = element;
|
178
|
+
const hasTarget = !!target?.value;
|
179
|
+
const show = hasTarget
|
180
|
+
? queryTarget(target.value)
|
181
|
+
: document.createElement("script-py");
|
182
|
+
|
183
|
+
if (!hasTarget) {
|
184
|
+
const { head, body } = document;
|
185
|
+
if (head.contains(element)) body.append(show);
|
186
|
+
else element.after(show);
|
187
|
+
}
|
188
|
+
if (!show.id) show.id = getID();
|
189
|
+
|
190
|
+
// allows the code to retrieve the target element via
|
191
|
+
// document.currentScript.target if needed
|
192
|
+
defineProperty(element, "target", { value: show });
|
193
|
+
|
194
|
+
// notify before the code runs
|
195
|
+
dispatch(element, TYPE);
|
196
|
+
pyodide[`run${isAsync ? "Async" : ""}`](
|
197
|
+
await fetchSource(element, pyodide.io, true),
|
198
|
+
);
|
199
|
+
} else {
|
200
|
+
// resolve PyScriptElement to allow connectedCallback
|
201
|
+
element._pyodide.resolve(pyodide);
|
202
|
+
}
|
203
|
+
console.debug("[pyscript/main] PyScript Ready");
|
204
|
+
},
|
205
|
+
});
|
229
206
|
|
230
207
|
class PyScriptElement extends HTMLElement {
|
231
208
|
constructor() {
|
@@ -249,14 +226,15 @@ class PyScriptElement extends HTMLElement {
|
|
249
226
|
this.srcCode = await fetchSource(this, io, !this.childElementCount);
|
250
227
|
this.replaceChildren();
|
251
228
|
// notify before the code runs
|
252
|
-
dispatch(this,
|
229
|
+
dispatch(this, TYPE);
|
253
230
|
runner(this.srcCode);
|
254
231
|
this.style.display = "block";
|
255
232
|
}
|
256
233
|
}
|
257
234
|
}
|
258
235
|
|
259
|
-
|
236
|
+
// define py-script only if the config didn't throw an error
|
237
|
+
error || customElements.define("py-script", PyScriptElement);
|
260
238
|
|
261
239
|
/**
|
262
240
|
* A `Worker` facade able to bootstrap on the worker thread only a PyScript module.
|
package/src/fetch.js
CHANGED
package/src/plugins/error.js
CHANGED
@@ -24,7 +24,7 @@ hooks.onBeforeRun.add(function override(pyScript) {
|
|
24
24
|
// Error hook utilities
|
25
25
|
|
26
26
|
// Custom function to show notifications
|
27
|
-
function notify(message) {
|
27
|
+
export function notify(message) {
|
28
28
|
const div = document.createElement("div");
|
29
29
|
div.className = "py-error";
|
30
30
|
div.textContent = message;
|
package/src/plugins.js
CHANGED
package/types/core.d.ts
CHANGED
package/types/fetch.d.ts
CHANGED
package/types/plugins/error.d.ts
CHANGED
@@ -1 +1 @@
|
|
1
|
-
export
|
1
|
+
export function notify(message: any): void;
|
package/dist/error-91f1c2f6.js
DELETED
@@ -1,2 +0,0 @@
|
|
1
|
-
import{hooks as e}from"./core.js";function n(e){const n=document.createElement("div");n.className="py-error",n.textContent=e,n.style.cssText="\n border: 1px solid red;\n background: #ffdddd;\n color: black;\n font-family: courier, monospace;\n white-space: pre;\n overflow-x: auto;\n padding: 8px;\n margin-top: 8px;\n ",document.body.append(n)}e.onBeforeRun.add((function o(r){e.onBeforeRun.delete(o);const{stderr:t}=r.io;r.io.stderr=(e,...o)=>(n(e.message||e),t(e,...o)),addEventListener("error",(({message:e})=>{e.startsWith("Uncaught PythonError")&&n(e)}))}));
|
2
|
-
//# sourceMappingURL=error-91f1c2f6.js.map
|
@@ -1 +0,0 @@
|
|
1
|
-
{"version":3,"file":"error-91f1c2f6.js","sources":["../src/plugins/error.js"],"sourcesContent":["// PyScript Error Plugin\nimport { hooks } from \"../core.js\";\n\nhooks.onBeforeRun.add(function override(pyScript) {\n // be sure this override happens only once\n hooks.onBeforeRun.delete(override);\n\n // trap generic `stderr` to propagate to it regardless\n const { stderr } = pyScript.io;\n\n // override it with our own logic\n pyScript.io.stderr = (error, ...rest) => {\n notify(error.message || error);\n // let other plugins or stderr hook, if any, do the rest\n return stderr(error, ...rest);\n };\n\n // be sure uncaught Python errors are also visible\n addEventListener(\"error\", ({ message }) => {\n if (message.startsWith(\"Uncaught PythonError\")) notify(message);\n });\n});\n\n// Error hook utilities\n\n// Custom function to show notifications\nfunction notify(message) {\n const div = document.createElement(\"div\");\n div.className = \"py-error\";\n div.textContent = message;\n div.style.cssText = `\n border: 1px solid red;\n background: #ffdddd;\n color: black;\n font-family: courier, monospace;\n white-space: pre;\n overflow-x: auto;\n padding: 8px;\n margin-top: 8px;\n `;\n document.body.append(div);\n}\n"],"names":["notify","message","div","document","createElement","className","textContent","style","cssText","body","append","hooks","onBeforeRun","add","override","pyScript","delete","stderr","io","error","rest","addEventListener","startsWith"],"mappings":"kCA0BA,SAASA,EAAOC,GACZ,MAAMC,EAAMC,SAASC,cAAc,OACnCF,EAAIG,UAAY,WAChBH,EAAII,YAAcL,EAClBC,EAAIK,MAAMC,QAAU,6MAUpBL,SAASM,KAAKC,OAAOR,EACzB,CAtCAS,EAAMC,YAAYC,KAAI,SAASC,EAASC,GAEpCJ,EAAMC,YAAYI,OAAOF,GAGzB,MAAMG,OAAEA,GAAWF,EAASG,GAG5BH,EAASG,GAAGD,OAAS,CAACE,KAAUC,KAC5BpB,EAAOmB,EAAMlB,SAAWkB,GAEjBF,EAAOE,KAAUC,IAI5BC,iBAAiB,SAAS,EAAGpB,cACrBA,EAAQqB,WAAW,yBAAyBtB,EAAOC,EAAQ,GAEvE"}
|