@uniweb/build 1.23.3 → 1.23.5

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uniweb/build",
3
- "version": "1.23.3",
3
+ "version": "1.23.5",
4
4
  "description": "Build tooling for the Uniweb Component Web Platform",
5
5
  "type": "module",
6
6
  "exports": {
@@ -59,13 +59,13 @@
59
59
  "yaml": "^2.5.0",
60
60
  "@uniweb/projections": "~1.2.17",
61
61
  "@uniweb/content-reader": "~1.5.10",
62
- "@uniweb/schemas": "~1.7.4",
63
- "@uniweb/theming": "~1.3.2",
64
62
  "@uniweb/content-writer": "~1.3.2",
65
- "@uniweb/semantic-parser": "~1.13.4"
63
+ "@uniweb/semantic-parser": "~1.13.4",
64
+ "@uniweb/schemas": "~1.7.4",
65
+ "@uniweb/theming": "~1.3.2"
66
66
  },
67
67
  "optionalDependencies": {
68
- "@uniweb/runtime": "~1.6.3"
68
+ "@uniweb/runtime": "~1.6.4"
69
69
  },
70
70
  "peerDependencies": {
71
71
  "vite": "^5.0.0 || ^6.0.0 || ^7.0.0",
@@ -74,7 +74,7 @@
74
74
  "@tailwindcss/vite": "^4.0.0",
75
75
  "@vitejs/plugin-react": "^4.0.0 || ^5.0.0",
76
76
  "vite-plugin-svgr": "^4.0.0",
77
- "@uniweb/runtime": "~1.6.3",
77
+ "@uniweb/runtime": "~1.6.4",
78
78
  "@uniweb/core": "~1.6.12"
79
79
  },
80
80
  "peerDependenciesMeta": {
@@ -0,0 +1,153 @@
1
+ /**
2
+ * The worker a local run of a compute function happens in (`compute-run.js`). It takes away, before
3
+ * the file loads, what §"What it can't do" of the public contract says a function doesn't have:
4
+ *
5
+ * - Node's globals (`process`, `Buffer`, `setImmediate`, …), since it runs with the web's;
6
+ * - the network: `fetch`, `XMLHttpRequest`, `WebSocket` and `EventSource` throw;
7
+ * - the built-in prototypes' writability: each is frozen, and a module is strict, so a write to
8
+ * one throws, including an assignment like `error.name = 'X'`.
9
+ *
10
+ * Then it imports the file as written, parses the input inside this realm, calls the function, and
11
+ * posts back what came of it. The worker is the time limit's means too: the parent ends it.
12
+ *
13
+ * ⛔ Not a security boundary. It runs a developer's own file on their machine, to show them what it
14
+ * would do under the contract's rules; it doesn't contain code that tries to get out.
15
+ *
16
+ * @module
17
+ */
18
+
19
+ import { parentPort, workerData } from 'node:worker_threads'
20
+
21
+ // What this module needs, kept before the globals go.
22
+ const post = parentPort.postMessage.bind(parentPort)
23
+ const cpu = typeof process.threadCpuUsage === 'function' ? process.threadCpuUsage.bind(process) : null
24
+ const now = performance.now.bind(performance)
25
+
26
+ const { source, exportName, inputText } = workerData
27
+
28
+ // No top-level await: a promise that never settles is reported by the parent, not by Node.
29
+ main()
30
+
31
+ async function main() {
32
+ // Load the module loader while Node's globals are still there: it reads them itself.
33
+ await import('data:text/javascript,')
34
+
35
+ // The language's own prototypes, frozen. A write to one throws in a module, which is strict.
36
+ const INTRINSICS = [
37
+ 'Object', 'Function', 'Array', 'String', 'Number', 'Boolean', 'Symbol', 'BigInt', 'Date', 'RegExp',
38
+ 'Error', 'EvalError', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError', 'AggregateError',
39
+ 'Map', 'Set', 'WeakMap', 'WeakSet', 'WeakRef', 'FinalizationRegistry', 'Promise', 'Iterator',
40
+ 'ArrayBuffer', 'SharedArrayBuffer', 'DataView',
41
+ 'Int8Array', 'Uint8Array', 'Uint8ClampedArray', 'Int16Array', 'Uint16Array', 'Int32Array', 'Uint32Array',
42
+ 'Float16Array', 'Float32Array', 'Float64Array', 'BigInt64Array', 'BigUint64Array',
43
+ ]
44
+ const unnamed = (() => {
45
+ const gen = function* () {}
46
+ const agen = async function* () {}
47
+ return [
48
+ Object.getPrototypeOf(Int8Array).prototype,
49
+ Object.getPrototypeOf(gen),
50
+ Object.getPrototypeOf(gen).prototype,
51
+ Object.getPrototypeOf(agen),
52
+ Object.getPrototypeOf(agen).prototype,
53
+ Object.getPrototypeOf(Object.getPrototypeOf(agen).prototype),
54
+ Object.getPrototypeOf(async function () {}),
55
+ Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())),
56
+ Object.getPrototypeOf([][Symbol.iterator]()),
57
+ Object.getPrototypeOf(new Map()[Symbol.iterator]()),
58
+ Object.getPrototypeOf(new Set()[Symbol.iterator]()),
59
+ Object.getPrototypeOf(''[Symbol.iterator]()),
60
+ Object.getPrototypeOf(/x/[Symbol.matchAll]('')),
61
+ ]
62
+ })()
63
+ for (const p of [...INTRINSICS.map((name) => globalThis[name]?.prototype), ...unnamed]) {
64
+ if (p) Object.freeze(p)
65
+ }
66
+
67
+ // The network's globals throw, and Node's go: in that order, since replacing a network global
68
+ // loads Node's implementation of it, which reads Node's globals.
69
+ const NODE_ONLY = ['process', 'Buffer', 'global', 'setImmediate', 'clearImmediate', 'require', 'module', 'exports', '__dirname', '__filename']
70
+ const NETWORK = ['fetch', 'XMLHttpRequest', 'WebSocket', 'EventSource']
71
+ for (const name of NETWORK) {
72
+ Object.defineProperty(globalThis, name, {
73
+ configurable: true,
74
+ writable: true,
75
+ value: function () {
76
+ throw new TypeError(`${name} is not available: a compute function has no network.`)
77
+ },
78
+ })
79
+ }
80
+ for (const name of NODE_ONLY) {
81
+ try {
82
+ delete globalThis[name]
83
+ } catch {}
84
+ }
85
+
86
+ const report = (outcome) => post(outcome)
87
+
88
+ let mod
89
+ try {
90
+ mod = await import(`data:text/javascript,${encodeURIComponent(source)}`)
91
+ } catch (err) {
92
+ report({ kind: 'load-failed', message: messageOf(err) })
93
+ }
94
+
95
+ if (mod) {
96
+ const fn = mod[exportName]
97
+ if (typeof fn !== 'function') {
98
+ report({ kind: 'not-exported', exports: Object.keys(mod).filter((k) => typeof mod[k] === 'function').sort() })
99
+ } else {
100
+ const input = JSON.parse(inputText)
101
+ const cpuAt = cpu?.()
102
+ const at = now()
103
+ let outcome
104
+ try {
105
+ const answer = await fn(input)
106
+ outcome = answerOutcome(answer)
107
+ } catch (err) {
108
+ outcome = { kind: 'threw', message: messageOf(err), isError: err instanceof Error }
109
+ }
110
+ outcome.wallMs = now() - at
111
+ if (cpuAt) {
112
+ const used = cpu(cpuAt)
113
+ outcome.cpuMs = (used.user + used.system) / 1000
114
+ }
115
+ report(outcome)
116
+ }
117
+ }
118
+ }
119
+
120
+ function answerOutcome(answer) {
121
+ if (answer === null || typeof answer !== 'object' || Array.isArray(answer)) {
122
+ return { kind: 'not-object', got: answer === null ? 'null' : Array.isArray(answer) ? 'an array' : typeof answer }
123
+ }
124
+ let text
125
+ try {
126
+ text = JSON.stringify(answer)
127
+ } catch (err) {
128
+ return { kind: 'not-json', message: messageOf(err) }
129
+ }
130
+ // What reaches the caller is the JSON, so judge that: a Date becomes a string, a Map `{}`.
131
+ const sent = text === undefined ? undefined : JSON.parse(text)
132
+ if (sent === null || typeof sent !== 'object' || Array.isArray(sent)) {
133
+ return { kind: 'not-object', got: `${describe(answer)}, which becomes ${sent === undefined ? 'nothing' : JSON.stringify(sent).slice(0, 40)} as JSON` }
134
+ }
135
+ if (Object.prototype.toString.call(answer) !== '[object Object]') {
136
+ return { kind: 'not-object', got: `${describe(answer)}, which becomes ${text.slice(0, 40)} as JSON` }
137
+ }
138
+ return { kind: 'answered', text }
139
+ }
140
+
141
+ function describe(value) {
142
+ const tag = Object.prototype.toString.call(value).slice(8, -1)
143
+ return `a ${tag}`
144
+ }
145
+
146
+ function messageOf(err) {
147
+ if (err instanceof Error) return `${err.name}: ${err.message}`
148
+ try {
149
+ return `threw a value that is not an Error: ${JSON.stringify(err)}`
150
+ } catch {
151
+ return 'threw a value that is not an Error'
152
+ }
153
+ }
@@ -0,0 +1,158 @@
1
+ /**
2
+ * ⭐ A LOCAL RUN OF ONE COMPUTE FUNCTION, under the rules the public contract states for where it
3
+ * runs: the web's globals and not Node's, no network, frozen built-in prototypes, a JSON input, an
4
+ * answer that is a plain JSON object of bounded size, and a short time per call.
5
+ *
6
+ * A test that imports the file runs it in Node, which allows all of those; this run doesn't, so a
7
+ * developer meets a failure here rather than in a run whose console output is discarded.
8
+ *
9
+ * ⚖️ It enforces the rules, not a copy of the platform's runner, which enforces them its own way.
10
+ * A function that passes here keeps the contract; that is the claim, and no more.
11
+ *
12
+ * The limits are the platform's as of this writing (`LIMITS`). The time a call takes is measured
13
+ * and compared with the budget, never cut at it, since this machine is not the one that runs it;
14
+ * only a call that runs past `LIMITS.wallMs` is stopped.
15
+ *
16
+ * @module
17
+ */
18
+
19
+ import { readFileSync } from 'node:fs'
20
+ import { Worker } from 'node:worker_threads'
21
+ import { checkComputeSource } from './compute.js'
22
+
23
+ export const LIMITS = Object.freeze({
24
+ inputBytes: 1024 * 1024,
25
+ answerBytes: 256 * 1024,
26
+ cpuMs: 50,
27
+ wallMs: 5000,
28
+ })
29
+
30
+ // An assignment to a property a frozen built-in prototype has (`error.name = 'X'`), or an addition
31
+ // to a frozen prototype itself.
32
+ const FROZEN = /Cannot assign to read only property|object is not extensible/
33
+ const FROZEN_HINT =
34
+ '. The built-in prototypes are frozen, so assigning a property one of them has throws, as does adding to one.' +
35
+ " Define the property instead: in an object literal, with Object.defineProperty, or as a class field (`class GradingError extends Error { name = 'GradingError' }`)."
36
+
37
+ const WORKER = new URL('./compute-run-worker.js', import.meta.url)
38
+
39
+ /**
40
+ * Run `exportName` from the compute file at `file` on `inputText`.
41
+ *
42
+ * @param {object} p
43
+ * @param {string} p.file - the compute file
44
+ * @param {string} p.exportName - the function to call
45
+ * @param {string} p.inputText - the input, as JSON text
46
+ * @returns {Promise<{
47
+ * ok: boolean,
48
+ * answer?: object,
49
+ * failure?: string,
50
+ * problems?: string[],
51
+ * warnings: string[],
52
+ * wallMs?: number,
53
+ * cpuMs?: number,
54
+ * }>} `ok` with the parsed `answer`, or not, with `failure` saying why in a sentence (and
55
+ * `problems` when the file itself can't be registered). `warnings` are the build's, and the
56
+ * budget's when the call took longer than it.
57
+ */
58
+ export async function runComputeFunction({ file, exportName, inputText }) {
59
+ const source = readFileSync(file, 'utf8')
60
+ const { exports, problems, warnings } = await checkComputeSource(source)
61
+ if (problems.length) {
62
+ return { ok: false, failure: 'The file can\'t be registered, so it doesn\'t run:', problems, warnings }
63
+ }
64
+ if (!exports.includes(exportName)) {
65
+ return {
66
+ ok: false,
67
+ failure: `The file doesn't export \`${exportName}\`. It exports ${exports.map((e) => `\`${e}\``).join(', ')}.`,
68
+ warnings,
69
+ }
70
+ }
71
+
72
+ const inputBytes = Buffer.byteLength(inputText)
73
+ if (inputBytes > LIMITS.inputBytes) {
74
+ return { ok: false, failure: `The input is ${kib(inputBytes)}, over the ${kib(LIMITS.inputBytes)} an input may be.`, warnings }
75
+ }
76
+ let input
77
+ try {
78
+ input = JSON.parse(inputText)
79
+ } catch (err) {
80
+ return { ok: false, failure: `The input isn't JSON: ${err.message}`, warnings }
81
+ }
82
+ if (input === null || typeof input !== 'object' || Array.isArray(input)) {
83
+ return { ok: false, failure: 'The input is JSON but not an object: a function takes the object its integration\'s mapping writes.', warnings }
84
+ }
85
+
86
+ const outcome = await inWorker({ source, exportName, inputText })
87
+ const timing = { wallMs: outcome.wallMs, cpuMs: outcome.cpuMs }
88
+ const over = timingWarning(timing)
89
+ const all = over ? [...warnings, over] : warnings
90
+
91
+ switch (outcome.kind) {
92
+ case 'answered': {
93
+ const bytes = Buffer.byteLength(outcome.text)
94
+ if (bytes > LIMITS.answerBytes) {
95
+ return { ok: false, failure: `The answer is ${kib(bytes)}, over the ${kib(LIMITS.answerBytes)} an answer may be.`, warnings: all, ...timing }
96
+ }
97
+ return { ok: true, answer: JSON.parse(outcome.text), warnings: all, ...timing }
98
+ }
99
+ case 'threw':
100
+ return {
101
+ ok: false,
102
+ failure: outcome.isError
103
+ ? `It threw ${outcome.message}${FROZEN.test(outcome.message) ? FROZEN_HINT : ''}`
104
+ : `It ${outcome.message}. Throw an Error with a message a person can read.`,
105
+ warnings: all,
106
+ ...timing,
107
+ }
108
+ case 'not-object':
109
+ return { ok: false, failure: `It returned ${outcome.got}, not an object: an answer is a JSON object, or a promise of one.`, warnings: all, ...timing }
110
+ case 'not-json':
111
+ return { ok: false, failure: `Its answer can't be written as JSON: ${outcome.message}`, warnings: all, ...timing }
112
+ case 'load-failed':
113
+ return { ok: false, failure: `The file failed as it loaded: ${outcome.message}`, warnings: all }
114
+ case 'not-exported':
115
+ return { ok: false, failure: `The file doesn't export \`${exportName}\` as a function.`, warnings: all }
116
+ case 'timed-out':
117
+ return { ok: false, failure: `It was still running after ${LIMITS.wallMs / 1000} s, and was stopped.`, warnings: all, wallMs: LIMITS.wallMs }
118
+ case 'unsettled':
119
+ return { ok: false, failure: 'It returned a promise that never settles.', warnings: all }
120
+ case 'crashed':
121
+ default:
122
+ return { ok: false, failure: `The run stopped: ${outcome.message}`, warnings: all }
123
+ }
124
+ }
125
+
126
+ function inWorker(workerData) {
127
+ return new Promise((resolve) => {
128
+ // The function's console goes to stderr, here only: where it runs, it is discarded.
129
+ const worker = new Worker(WORKER, { workerData, stdout: true, stderr: true })
130
+ worker.stdout.pipe(process.stderr, { end: false })
131
+ worker.stderr.pipe(process.stderr, { end: false })
132
+ let settled = false
133
+ const settle = (outcome) => {
134
+ if (settled) return
135
+ settled = true
136
+ clearTimeout(timer)
137
+ worker.terminate()
138
+ resolve(outcome)
139
+ }
140
+ const timer = setTimeout(() => settle({ kind: 'timed-out' }), LIMITS.wallMs)
141
+ worker.once('message', settle)
142
+ worker.once('error', (err) => settle({ kind: 'crashed', message: err?.message || String(err) }))
143
+ worker.once('exit', () => settle({ kind: 'unsettled' }))
144
+ })
145
+ }
146
+
147
+ function timingWarning({ wallMs, cpuMs }) {
148
+ const spent = cpuMs ?? wallMs
149
+ if (spent == null || spent <= LIMITS.cpuMs) return null
150
+ return (
151
+ `the call took ${Math.round(spent)} ms${cpuMs != null ? ' of CPU' : ''}, more than the ${LIMITS.cpuMs} ms one call may take where it runs. ` +
152
+ 'This machine is not that one, so measure again, but a function this slow is likely to be stopped there.'
153
+ )
154
+ }
155
+
156
+ function kib(bytes) {
157
+ return bytes >= 1024 * 1024 ? `${(bytes / 1024 / 1024).toFixed(1)} MiB` : `${Math.ceil(bytes / 1024)} KiB`
158
+ }