@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 +6 -6
- package/src/foundation/compute-run-worker.js +153 -0
- package/src/foundation/compute-run.js +158 -0
- package/src/foundation/compute.js +418 -0
- package/src/foundation/library-compute.js +94 -0
- package/src/foundation/shared-types.js +15 -0
- package/src/index.js +3 -1
- package/src/schema.js +23 -2
- package/src/site/config.js +6 -40
- package/src/site/foundation-imports.js +127 -0
- package/src/utils/classify-package.js +5 -4
- package/src/uwx/blueprint-file.js +30 -3
- package/src/uwx/blueprint.js +81 -8
- package/src/uwx/registry-package.js +56 -11
- package/src/utils/foundation-resolution-check.js +0 -195
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A foundation's or library's compute functions — `compute/<name>.js`, one plain-JS module per file:
|
|
3
|
+
* small pure functions a backend's integration calls by `file#export`, run outside every backend.
|
|
4
|
+
*
|
|
5
|
+
* ⚖️ TWO WORDS, ONE THING. In the foundation it is its compute: the `compute/` folder and `main.js`'s
|
|
6
|
+
* `compute:`. To an integration it stands where an outside vendor's address would, so `blueprint.yml`
|
|
7
|
+
* names one with `vendor:`, and the registry's wire keeps that word too (`@uniweb/vendor-schema`,
|
|
8
|
+
* `vendor-uploads`, the foundation-schema's `vendors.refs`).
|
|
9
|
+
*
|
|
10
|
+
* ```js
|
|
11
|
+
* // src/compute/courses.js
|
|
12
|
+
* export function grade(input) {
|
|
13
|
+
* …
|
|
14
|
+
* return { points, max }
|
|
15
|
+
* }
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* ⭐ THE FILE IS SHIPPED AS WRITTEN. Nothing is built, bundled or minified: the bytes on disk are
|
|
19
|
+
* what registers (their `sha256` and `size`) and what is uploaded. So the file must stand alone, and
|
|
20
|
+
* the build refuses what would stop it:
|
|
21
|
+
*
|
|
22
|
+
* - a file that does not parse as an ES module;
|
|
23
|
+
* - an `import` (static or dynamic) or an `export … from`: one file is the whole unit;
|
|
24
|
+
* - a default export: an integration names a function by its name, `file#export`;
|
|
25
|
+
* - a named export that is not a function, or whose name is not a JavaScript identifier;
|
|
26
|
+
* - a file that exports no function.
|
|
27
|
+
*
|
|
28
|
+
* And it WARNS, never refuses, of a function that writes to something declared outside itself at
|
|
29
|
+
* the top of the file — `keys[input.quiz] = …`, `cache.set(…)`, `count++` — since a call must change
|
|
30
|
+
* nothing outside itself: one running copy serves many calls, from many sites. Building a table
|
|
31
|
+
* once, at the top of the file, is fine. The check reads names, so a write through another name for
|
|
32
|
+
* the same object gets past it.
|
|
33
|
+
*
|
|
34
|
+
* It also WARNS of a name the file uses but never declares that isn't there when it runs: Node's
|
|
35
|
+
* (`process`, `Buffer`, `require`, …), since it runs with the standard web globals, and the
|
|
36
|
+
* network's (`fetch`, …), which throws there. A test that imports the file runs it in Node, where
|
|
37
|
+
* these work, so the build is where a developer hears of them. Only a warning: a use guarded by
|
|
38
|
+
* `typeof` is fine.
|
|
39
|
+
*
|
|
40
|
+
* The limits on a file's size and its number of exports are the registry's to state, and its
|
|
41
|
+
* refusal names them; the build doesn't restate them.
|
|
42
|
+
*
|
|
43
|
+
* Compute files are editor-time only: they ride in `schema.json` as `_compute` (each file's `exports`) and
|
|
44
|
+
* never reach a page.
|
|
45
|
+
*
|
|
46
|
+
* @module
|
|
47
|
+
*/
|
|
48
|
+
|
|
49
|
+
import { createHash } from 'node:crypto'
|
|
50
|
+
import { existsSync, readdirSync, readFileSync } from 'node:fs'
|
|
51
|
+
import { basename, extname, join } from 'node:path'
|
|
52
|
+
|
|
53
|
+
/** The folder, under a foundation's source root or a library's root. */
|
|
54
|
+
export const COMPUTE_DIR = 'compute'
|
|
55
|
+
|
|
56
|
+
const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The compute files a package defines, by name, sorted. A `.js` file is one by being there; a name
|
|
60
|
+
* with a leading `_` is left out.
|
|
61
|
+
*
|
|
62
|
+
* @param {string} srcDir - a foundation's source root, or a library's root
|
|
63
|
+
* @returns {{ name: string, file: string }[]}
|
|
64
|
+
*/
|
|
65
|
+
export function ownComputeFiles(srcDir) {
|
|
66
|
+
const dir = join(srcDir, COMPUTE_DIR)
|
|
67
|
+
if (!existsSync(dir)) return []
|
|
68
|
+
return readdirSync(dir)
|
|
69
|
+
.sort()
|
|
70
|
+
.filter((file) => extname(file) === '.js' && !file.startsWith('_'))
|
|
71
|
+
.map((file) => ({ name: basename(file, '.js'), file: join(dir, file) }))
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* What registers for one file: its bytes' digest and length, as on disk.
|
|
76
|
+
*
|
|
77
|
+
* @param {string} file
|
|
78
|
+
* @returns {{ sha256: string, size: number }}
|
|
79
|
+
*/
|
|
80
|
+
export function computeFileDigest(file) {
|
|
81
|
+
const bytes = readFileSync(file)
|
|
82
|
+
return { sha256: createHash('sha256').update(bytes).digest('hex'), size: bytes.length }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Read and check one compute file.
|
|
87
|
+
*
|
|
88
|
+
* @param {string} file
|
|
89
|
+
* @returns {Promise<{ exports: string[], problems: string[], warnings: string[] }>}
|
|
90
|
+
*/
|
|
91
|
+
export async function readComputeFile(file) {
|
|
92
|
+
const source = readFileSync(file, 'utf8')
|
|
93
|
+
return checkComputeSource(source)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Check a compute module's source. Exported for tests.
|
|
98
|
+
*
|
|
99
|
+
* @param {string} source
|
|
100
|
+
* @returns {Promise<{ exports: string[], problems: string[], warnings: string[] }>}
|
|
101
|
+
*/
|
|
102
|
+
export async function checkComputeSource(source) {
|
|
103
|
+
const { parseAst } = await import('vite')
|
|
104
|
+
let ast
|
|
105
|
+
try {
|
|
106
|
+
ast = parseAst(source)
|
|
107
|
+
} catch (err) {
|
|
108
|
+
return { exports: [], problems: [`does not parse as a JavaScript module: ${String(err?.message || err).split('\n')[0]}`], warnings: [] }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const problems = []
|
|
112
|
+
const exported = new Map() // exported name → local name
|
|
113
|
+
const topFunctions = new Set() // top-level names bound to a function
|
|
114
|
+
const topNames = new Set() // every top-level binding
|
|
115
|
+
|
|
116
|
+
for (const node of ast.body) {
|
|
117
|
+
const decl = node.type === 'ExportNamedDeclaration' ? node.declaration : node
|
|
118
|
+
if (decl?.type === 'FunctionDeclaration' && decl.id) {
|
|
119
|
+
topFunctions.add(decl.id.name)
|
|
120
|
+
topNames.add(decl.id.name)
|
|
121
|
+
} else if (decl?.type === 'ClassDeclaration' && decl.id) {
|
|
122
|
+
topNames.add(decl.id.name)
|
|
123
|
+
} else if (decl?.type === 'VariableDeclaration') {
|
|
124
|
+
for (const d of decl.declarations) {
|
|
125
|
+
for (const name of patternNames(d.id)) topNames.add(name)
|
|
126
|
+
if (d.id.type === 'Identifier' && isFunctionNode(d.init) && decl.kind === 'const') topFunctions.add(d.id.name)
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
for (const node of ast.body) {
|
|
132
|
+
switch (node.type) {
|
|
133
|
+
case 'ImportDeclaration':
|
|
134
|
+
problems.push(`imports \`${node.source.value}\`: a compute file has no imports. Keep a helper inside the file; a function that needs a package is a real service, reached at its address.`)
|
|
135
|
+
break
|
|
136
|
+
case 'ExportAllDeclaration':
|
|
137
|
+
problems.push(`re-exports \`${node.source.value}\`: a compute file has no imports, so it exports only functions it defines.`)
|
|
138
|
+
break
|
|
139
|
+
case 'ExportDefaultDeclaration':
|
|
140
|
+
problems.push('has a default export: an integration names a function by its name, `file#export`. Export each function by name.')
|
|
141
|
+
break
|
|
142
|
+
case 'ExportNamedDeclaration': {
|
|
143
|
+
if (node.source) {
|
|
144
|
+
problems.push(`re-exports from \`${node.source.value}\`: a compute file has no imports, so it exports only functions it defines.`)
|
|
145
|
+
break
|
|
146
|
+
}
|
|
147
|
+
const decl = node.declaration
|
|
148
|
+
if (decl?.type === 'FunctionDeclaration') {
|
|
149
|
+
exported.set(decl.id.name, decl.id.name)
|
|
150
|
+
} else if (decl?.type === 'VariableDeclaration') {
|
|
151
|
+
for (const d of decl.declarations) {
|
|
152
|
+
if (d.id.type !== 'Identifier') {
|
|
153
|
+
problems.push('exports a destructured binding: export each function by name.')
|
|
154
|
+
} else if (decl.kind !== 'const' || !isFunctionNode(d.init)) {
|
|
155
|
+
problems.push(`exports \`${d.id.name}\`, which is not a function: a compute file exports only functions. Keep a table or a constant unexported.`)
|
|
156
|
+
} else {
|
|
157
|
+
exported.set(d.id.name, d.id.name)
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
} else if (decl) {
|
|
161
|
+
problems.push(`exports a ${decl.type === 'ClassDeclaration' ? 'class' : 'value'}, which is not a function: a compute file exports only functions.`)
|
|
162
|
+
}
|
|
163
|
+
for (const spec of node.specifiers || []) {
|
|
164
|
+
const local = spec.local.name ?? spec.local.value
|
|
165
|
+
const name = spec.exported.name ?? spec.exported.value
|
|
166
|
+
if (name === 'default') {
|
|
167
|
+
problems.push('has a default export: an integration names a function by its name, `file#export`. Export each function by name.')
|
|
168
|
+
} else if (!topFunctions.has(local)) {
|
|
169
|
+
problems.push(`exports \`${name}\`, which is not a function the file defines: a compute file exports only functions.`)
|
|
170
|
+
} else {
|
|
171
|
+
exported.set(name, local)
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
break
|
|
175
|
+
}
|
|
176
|
+
default:
|
|
177
|
+
break
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
for (const name of exported.keys()) {
|
|
182
|
+
if (!IDENTIFIER.test(name)) {
|
|
183
|
+
problems.push(`exports \`${name}\`, which is not a JavaScript name: an integration names it as \`file#${name}\`.`)
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// Dynamic `import()` anywhere in the file.
|
|
188
|
+
walk(ast, (node) => {
|
|
189
|
+
if (node.type === 'ImportExpression') {
|
|
190
|
+
problems.push('calls `import()`: a compute file has no imports. Keep a helper inside the file; a function that needs a package is a real service, reached at its address.')
|
|
191
|
+
}
|
|
192
|
+
})
|
|
193
|
+
|
|
194
|
+
const exports = [...exported.keys()].filter((n) => IDENTIFIER.test(n)).sort()
|
|
195
|
+
if (!exports.length && !problems.length) {
|
|
196
|
+
problems.push('exports no function: export each function an integration calls by name, `export function grade(input) { … }`.')
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
return { exports, problems: [...new Set(problems)], warnings: [...missingGlobals(ast), ...callWrites(ast, topNames)] }
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Read and check every compute file a package defines.
|
|
204
|
+
*
|
|
205
|
+
* @param {string} srcDir - a foundation's source root, or a library's root
|
|
206
|
+
* @param {object} [opts]
|
|
207
|
+
* @param {string} [opts.shownIn] - the folder as its messages name it (a library's is `compute`)
|
|
208
|
+
* @returns {Promise<{ map: Object<string, { exports: string[] }>, warnings: string[] }>}
|
|
209
|
+
* `{ '@/<name>': { exports } }`
|
|
210
|
+
* @throws {Error} naming every file that cannot be registered, and why
|
|
211
|
+
*/
|
|
212
|
+
export async function buildComputeMap(srcDir, { shownIn = `src/${COMPUTE_DIR}` } = {}) {
|
|
213
|
+
const files = ownComputeFiles(srcDir)
|
|
214
|
+
const map = {}
|
|
215
|
+
const found = []
|
|
216
|
+
const warnings = []
|
|
217
|
+
for (const { name, file } of files) {
|
|
218
|
+
const at = `${shownIn}/${basename(file)}`
|
|
219
|
+
const { exports, problems, warnings: w } = await readComputeFile(file)
|
|
220
|
+
if (problems.length) found.push(...problems.map((p) => `${at} ${p}`))
|
|
221
|
+
else map[`@/${name}`] = { exports }
|
|
222
|
+
warnings.push(...w.map((x) => `${at}: ${x}`))
|
|
223
|
+
}
|
|
224
|
+
if (found.length) {
|
|
225
|
+
throw new Error(
|
|
226
|
+
found.length === 1
|
|
227
|
+
? `[uniweb] ${found[0]}`
|
|
228
|
+
: `[uniweb] compute files that cannot be registered:\n${found.map((f) => ` - ${f}`).join('\n')}`
|
|
229
|
+
)
|
|
230
|
+
}
|
|
231
|
+
return { map, warnings }
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// --- the missing-globals check ------------------------------------------------------------------
|
|
235
|
+
|
|
236
|
+
const NODE_ONLY = ['process', 'Buffer', 'require', 'module', 'exports', '__dirname', '__filename', 'global', 'setImmediate', 'clearImmediate']
|
|
237
|
+
const NETWORK = ['fetch', 'XMLHttpRequest', 'WebSocket', 'EventSource']
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Each name from `NODE_ONLY` or `NETWORK` the file reads without declaring it anywhere. A name the
|
|
241
|
+
* file declares, at any depth, is taken as its own; a property name (`x.process`, `{ fetch: … }`)
|
|
242
|
+
* is not a use.
|
|
243
|
+
*/
|
|
244
|
+
function missingGlobals(ast) {
|
|
245
|
+
const declared = new Set()
|
|
246
|
+
walk(ast, (node) => {
|
|
247
|
+
if (node.type === 'VariableDeclarator') for (const n of patternNames(node.id)) declared.add(n)
|
|
248
|
+
else if ((node.type === 'FunctionDeclaration' || node.type === 'ClassDeclaration' || node.type === 'FunctionExpression' || node.type === 'ClassExpression') && node.id) declared.add(node.id.name)
|
|
249
|
+
if (isFunctionNode(node) || node.type === 'FunctionDeclaration') for (const p of node.params) for (const n of patternNames(p)) declared.add(n)
|
|
250
|
+
if (node.type === 'CatchClause' && node.param) for (const n of patternNames(node.param)) declared.add(n)
|
|
251
|
+
})
|
|
252
|
+
const used = new Set()
|
|
253
|
+
const visit = (node, parent, key) => {
|
|
254
|
+
if (!node || typeof node.type !== 'string') return
|
|
255
|
+
if (node.type === 'Identifier' && !isPropertyName(parent, key)) used.add(node.name)
|
|
256
|
+
for (const k of Object.keys(node)) {
|
|
257
|
+
if (k === 'type' || k === 'start' || k === 'end') continue
|
|
258
|
+
const child = node[k]
|
|
259
|
+
if (Array.isArray(child)) for (const c of child) visit(c, node, k)
|
|
260
|
+
else if (child && typeof child.type === 'string') visit(child, node, k)
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
visit(ast, null, null)
|
|
264
|
+
const out = []
|
|
265
|
+
for (const name of NODE_ONLY) {
|
|
266
|
+
if (used.has(name) && !declared.has(name)) {
|
|
267
|
+
out.push(`uses \`${name}\`, which is Node's: a compute function runs with the standard web globals (\`JSON\`, \`Math\`, \`Intl\`, \`Date\`, \`crypto.subtle\`), not in Node, so it isn't there.`)
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
for (const name of NETWORK) {
|
|
271
|
+
if (used.has(name) && !declared.has(name)) {
|
|
272
|
+
out.push(`uses \`${name}\`, which throws where it runs: a compute function has no network. A function that needs the network is a real service, reached at its address.`)
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
return out
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** Whether an Identifier at `parent[key]` names a property or a label, not a binding. */
|
|
279
|
+
function isPropertyName(parent, key) {
|
|
280
|
+
if (!parent) return false
|
|
281
|
+
switch (parent.type) {
|
|
282
|
+
case 'MemberExpression':
|
|
283
|
+
return key === 'property' && !parent.computed
|
|
284
|
+
case 'Property':
|
|
285
|
+
return key === 'key' && !parent.computed && !parent.shorthand
|
|
286
|
+
case 'MethodDefinition':
|
|
287
|
+
case 'PropertyDefinition':
|
|
288
|
+
return key === 'key' && !parent.computed
|
|
289
|
+
case 'LabeledStatement':
|
|
290
|
+
case 'BreakStatement':
|
|
291
|
+
case 'ContinueStatement':
|
|
292
|
+
return key === 'label'
|
|
293
|
+
case 'MetaProperty':
|
|
294
|
+
return true
|
|
295
|
+
case 'ExportSpecifier':
|
|
296
|
+
return key === 'exported'
|
|
297
|
+
default:
|
|
298
|
+
return false
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// --- the call-writes check -----------------------------------------------------------------------
|
|
303
|
+
|
|
304
|
+
const MUTATORS = new Set(['set', 'add', 'delete', 'clear', 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse', 'fill', 'copyWithin'])
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Each place a function writes to a binding declared at the top of the file, by name: an
|
|
308
|
+
* assignment or `++`/`--` whose target is that binding or a member of it, a mutating method call on
|
|
309
|
+
* it (`cache.set(…)`, `list.push(…)`), or `Object.assign` onto it. A name the function declares
|
|
310
|
+
* itself (a parameter, a `let`, a nested function) shadows the top-level one.
|
|
311
|
+
*/
|
|
312
|
+
function callWrites(ast, topNames) {
|
|
313
|
+
const found = new Set()
|
|
314
|
+
const visit = (node, shadowed, inFunction) => {
|
|
315
|
+
if (!node || typeof node.type !== 'string') return
|
|
316
|
+
if (isFunctionNode(node) || node.type === 'FunctionDeclaration') {
|
|
317
|
+
const local = new Set(shadowed)
|
|
318
|
+
for (const p of node.params) for (const n of patternNames(p)) local.add(n)
|
|
319
|
+
if (node.id?.name && node.type !== 'FunctionDeclaration') local.add(node.id.name)
|
|
320
|
+
for (const n of declaredIn(node.body)) local.add(n)
|
|
321
|
+
visit(node.body, local, true)
|
|
322
|
+
return
|
|
323
|
+
}
|
|
324
|
+
if (inFunction) {
|
|
325
|
+
let target = null
|
|
326
|
+
if (node.type === 'AssignmentExpression') target = node.left
|
|
327
|
+
else if (node.type === 'UpdateExpression') target = node.argument
|
|
328
|
+
else if (node.type === 'UnaryExpression' && node.operator === 'delete') target = node.argument
|
|
329
|
+
else if (node.type === 'CallExpression' && node.callee.type === 'MemberExpression') {
|
|
330
|
+
const prop = node.callee.computed ? null : node.callee.property.name
|
|
331
|
+
if (prop && MUTATORS.has(prop)) target = node.callee.object
|
|
332
|
+
if (prop === 'assign' && rootName(node.callee.object) === 'Object' && node.arguments[0]) target = node.arguments[0]
|
|
333
|
+
}
|
|
334
|
+
const name = target && rootName(target)
|
|
335
|
+
if (name && topNames.has(name) && !shadowed.has(name)) found.add(name)
|
|
336
|
+
}
|
|
337
|
+
for (const key of Object.keys(node)) {
|
|
338
|
+
if (key === 'type' || key === 'start' || key === 'end') continue
|
|
339
|
+
const child = node[key]
|
|
340
|
+
if (Array.isArray(child)) for (const c of child) visit(c, shadowed, inFunction)
|
|
341
|
+
else if (child && typeof child.type === 'string') visit(child, shadowed, inFunction)
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
visit(ast, new Set(), false)
|
|
345
|
+
return [...found].map(
|
|
346
|
+
(name) =>
|
|
347
|
+
`a function writes to \`${name}\`, which is declared at the top of the file, so it outlives the call. ` +
|
|
348
|
+
'A call must change nothing outside itself: one running copy serves many calls, from many sites. ' +
|
|
349
|
+
'Build a table once at the top of the file, and keep what a call computes inside the call.'
|
|
350
|
+
)
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
function rootName(node) {
|
|
354
|
+
let at = node
|
|
355
|
+
while (at && (at.type === 'MemberExpression' || at.type === 'ChainExpression')) {
|
|
356
|
+
at = at.type === 'ChainExpression' ? at.expression : at.object
|
|
357
|
+
}
|
|
358
|
+
return at?.type === 'Identifier' ? at.name : null
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** The names a function body declares at any depth that is still its own (not a nested function's). */
|
|
362
|
+
function declaredIn(body) {
|
|
363
|
+
const out = new Set()
|
|
364
|
+
const visit = (node) => {
|
|
365
|
+
if (!node || typeof node.type !== 'string') return
|
|
366
|
+
if (node.type === 'VariableDeclaration') {
|
|
367
|
+
for (const d of node.declarations) for (const n of patternNames(d.id)) out.add(n)
|
|
368
|
+
}
|
|
369
|
+
if (node.type === 'FunctionDeclaration' && node.id) {
|
|
370
|
+
out.add(node.id.name)
|
|
371
|
+
return
|
|
372
|
+
}
|
|
373
|
+
if (node.type === 'ClassDeclaration' && node.id) out.add(node.id.name)
|
|
374
|
+
if (node.type === 'CatchClause' && node.param) for (const n of patternNames(node.param)) out.add(n)
|
|
375
|
+
if (isFunctionNode(node)) return
|
|
376
|
+
for (const key of Object.keys(node)) {
|
|
377
|
+
if (key === 'type' || key === 'start' || key === 'end') continue
|
|
378
|
+
const child = node[key]
|
|
379
|
+
if (Array.isArray(child)) child.forEach(visit)
|
|
380
|
+
else if (child && typeof child.type === 'string') visit(child)
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
visit(body)
|
|
384
|
+
return out
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function patternNames(p) {
|
|
388
|
+
if (!p) return []
|
|
389
|
+
switch (p.type) {
|
|
390
|
+
case 'Identifier':
|
|
391
|
+
return [p.name]
|
|
392
|
+
case 'AssignmentPattern':
|
|
393
|
+
return patternNames(p.left)
|
|
394
|
+
case 'RestElement':
|
|
395
|
+
return patternNames(p.argument)
|
|
396
|
+
case 'ArrayPattern':
|
|
397
|
+
return p.elements.flatMap(patternNames)
|
|
398
|
+
case 'ObjectPattern':
|
|
399
|
+
return p.properties.flatMap((prop) => patternNames(prop.type === 'RestElement' ? prop : prop.value))
|
|
400
|
+
default:
|
|
401
|
+
return []
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
function isFunctionNode(node) {
|
|
406
|
+
return node?.type === 'ArrowFunctionExpression' || node?.type === 'FunctionExpression'
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
function walk(node, fn) {
|
|
410
|
+
if (!node || typeof node.type !== 'string') return
|
|
411
|
+
fn(node)
|
|
412
|
+
for (const key of Object.keys(node)) {
|
|
413
|
+
if (key === 'type' || key === 'start' || key === 'end') continue
|
|
414
|
+
const child = node[key]
|
|
415
|
+
if (Array.isArray(child)) for (const c of child) walk(c, fn)
|
|
416
|
+
else if (child && typeof child.type === 'string') walk(child, fn)
|
|
417
|
+
}
|
|
418
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ⭐ A LIBRARY'S COMPUTE FILES, CARRIED BY A FOUNDATION THAT NAMES THEM — as a library's mappings are
|
|
3
|
+
* (`library-mappings.js`). A library may hold `compute/` beside its `schemas/` and `mappings/`, under
|
|
4
|
+
* its scope, and a foundation carries one by naming it in full in its `main.js`:
|
|
5
|
+
*
|
|
6
|
+
* ```js
|
|
7
|
+
* export default {
|
|
8
|
+
* name: '@shop/storefront',
|
|
9
|
+
* compute: ['@acme/grading'],
|
|
10
|
+
* }
|
|
11
|
+
* ```
|
|
12
|
+
*
|
|
13
|
+
* The build reads each from the library that defines it (`workspaceComputeFiles`), checks it as a
|
|
14
|
+
* foundation's own is checked, and keeps its exports in `_compute` under its full name. `register`
|
|
15
|
+
* names it in the foundation's vendor refs, and registers and uploads it from the library first.
|
|
16
|
+
*
|
|
17
|
+
* A name no package here defines only warns: it may be registered already, and the registry judges.
|
|
18
|
+
*
|
|
19
|
+
* @module
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import { basename } from 'node:path'
|
|
23
|
+
import { parseSchemaRef } from '@uniweb/schemas/format'
|
|
24
|
+
import { workspaceComputeFiles } from './shared-types.js'
|
|
25
|
+
import { COMPUTE_DIR, readComputeFile } from './compute.js'
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The library compute files a foundation's `main.js` names.
|
|
29
|
+
*
|
|
30
|
+
* @param {*} names - `main.js`'s `compute:`, as written
|
|
31
|
+
* @param {object} p
|
|
32
|
+
* @param {string} p.srcDir - the foundation's source root
|
|
33
|
+
* @param {string|null} p.ownScope - the foundation's scope, when its name gives one
|
|
34
|
+
* @returns {Promise<{ map: Object<string, { exports: string[] }|null>, warnings: string[] }>}
|
|
35
|
+
* `map`: full name → its exports, or null when no package here defines it
|
|
36
|
+
* @throws {Error} naming each one that cannot be carried, and why
|
|
37
|
+
*/
|
|
38
|
+
export async function resolveLibraryCompute(names, { srcDir, ownScope = null }) {
|
|
39
|
+
if (names === undefined) return { map: {}, warnings: [] }
|
|
40
|
+
if (!Array.isArray(names) || names.some((n) => typeof n !== 'string')) {
|
|
41
|
+
throw new Error(
|
|
42
|
+
"[uniweb] main.js: `compute` lists the library compute files the foundation carries, each named in full — `compute: ['@acme/grading']`."
|
|
43
|
+
)
|
|
44
|
+
}
|
|
45
|
+
const map = {}
|
|
46
|
+
const warnings = []
|
|
47
|
+
const found = []
|
|
48
|
+
for (const name of names) {
|
|
49
|
+
const at = `main.js: \`compute\` names \`${name}\``
|
|
50
|
+
let scope
|
|
51
|
+
try {
|
|
52
|
+
;({ scope } = parseSchemaRef(name))
|
|
53
|
+
} catch {
|
|
54
|
+
found.push(`${at}, which is not a compute file's full name, \`'@scope/<name>'\`.`)
|
|
55
|
+
continue
|
|
56
|
+
}
|
|
57
|
+
if (!scope || name.startsWith('@/')) {
|
|
58
|
+
found.push(`${at}: a compute file of the foundation's own is a file in src/${COMPUTE_DIR}/, and is not listed. List a library's, in full.`)
|
|
59
|
+
continue
|
|
60
|
+
}
|
|
61
|
+
if (ownScope && `@${String(ownScope).replace(/^@/, '')}` === `@${scope}`) {
|
|
62
|
+
found.push(`${at}, in the foundation's own scope: a compute file of its own is a file in src/${COMPUTE_DIR}/.`)
|
|
63
|
+
continue
|
|
64
|
+
}
|
|
65
|
+
const files = await workspaceComputeFiles(name, srcDir)
|
|
66
|
+
if (files.length > 1) {
|
|
67
|
+
found.push(`${at}, which ${files.length} packages define: ${files.join(', ')}. Keep one.`)
|
|
68
|
+
continue
|
|
69
|
+
}
|
|
70
|
+
if (!files.length) {
|
|
71
|
+
warnings.push(
|
|
72
|
+
`${at}, which no package here defines, so the build can't check it. \`uniweb register\` names it, and the registry refuses the foundation unless it is registered under @${scope}.`
|
|
73
|
+
)
|
|
74
|
+
map[name] = null
|
|
75
|
+
continue
|
|
76
|
+
}
|
|
77
|
+
const shown = `${COMPUTE_DIR}/${basename(files[0])} (for ${name})`
|
|
78
|
+
const { exports, problems, warnings: w } = await readComputeFile(files[0])
|
|
79
|
+
if (problems.length) {
|
|
80
|
+
found.push(...problems.map((p) => `${shown} ${p}`))
|
|
81
|
+
continue
|
|
82
|
+
}
|
|
83
|
+
warnings.push(...w.map((x) => `${shown}: ${x}`))
|
|
84
|
+
map[name] = { exports }
|
|
85
|
+
}
|
|
86
|
+
if (found.length) {
|
|
87
|
+
throw new Error(
|
|
88
|
+
found.length === 1
|
|
89
|
+
? `[uniweb] ${found[0]}`
|
|
90
|
+
: `[uniweb] library compute files the foundation cannot carry:\n${found.map((f) => ` - ${f}`).join('\n')}`
|
|
91
|
+
)
|
|
92
|
+
}
|
|
93
|
+
return { map, warnings }
|
|
94
|
+
}
|
|
@@ -25,6 +25,7 @@ import { workspaceRootOf } from '../site/workspace-extension.js'
|
|
|
25
25
|
import { classifyPackage, isSchemasPackage } from '../utils/classify-package.js'
|
|
26
26
|
import { librariesOf } from './libraries.js'
|
|
27
27
|
import { MAPPINGS_DIR, ownMappingFiles } from './mappings.js'
|
|
28
|
+
import { COMPUTE_DIR, ownComputeFiles } from './compute.js'
|
|
28
29
|
|
|
29
30
|
const real = (path) => {
|
|
30
31
|
try {
|
|
@@ -195,6 +196,20 @@ export async function workspaceMappingFiles(ref, fromDir) {
|
|
|
195
196
|
return workspaceDeclarationFiles(ref, fromDir, MAPPINGS_DIR, ownMappingFiles)
|
|
196
197
|
}
|
|
197
198
|
|
|
199
|
+
/**
|
|
200
|
+
* ⭐ A COMPUTE FILE ANOTHER PACKAGE DEFINES, found by the rule `workspaceMappingFiles` finds a mapping
|
|
201
|
+
* by: a foundation whose name gives the scope and whose own `compute/` holds it, or a library of that
|
|
202
|
+
* scope that holds `compute/` (`foundation/compute.js`). A foundation names one in its `main.js`
|
|
203
|
+
* (`compute: ['@acme/grading']`).
|
|
204
|
+
*
|
|
205
|
+
* @param {string} ref - `@scope/name`
|
|
206
|
+
* @param {string} fromDir - the foundation (its source folder) or site asking
|
|
207
|
+
* @returns {Promise<string[]>} the files that define it, each once; the caller refuses more than one
|
|
208
|
+
*/
|
|
209
|
+
export async function workspaceComputeFiles(ref, fromDir) {
|
|
210
|
+
return workspaceDeclarationFiles(ref, fromDir, COMPUTE_DIR, ownComputeFiles)
|
|
211
|
+
}
|
|
212
|
+
|
|
198
213
|
/** The files of the packages a package may read that define `ref` in their `folder`. */
|
|
199
214
|
async function workspaceDeclarationFiles(ref, fromDir, folder, ownFiles) {
|
|
200
215
|
const m = /^(@[^/]+)\/(.+)$/.exec(ref || '')
|
package/src/index.js
CHANGED
|
@@ -98,8 +98,10 @@ export { classifyPackage, isExtensionPackage, isSchemasPackage } from './utils/c
|
|
|
98
98
|
export { collectStandaloneSchemas, routedSchema } from './resolve-data-schema.js'
|
|
99
99
|
|
|
100
100
|
// One name in a scope is one type: the names a workspace's packages define twice
|
|
101
|
-
export { typesDefinedTwice, packageTypeScope, workspaceTypeFiles, workspaceMappingFiles } from './foundation/shared-types.js'
|
|
101
|
+
export { typesDefinedTwice, packageTypeScope, workspaceTypeFiles, workspaceMappingFiles, workspaceComputeFiles } from './foundation/shared-types.js'
|
|
102
102
|
export { buildMappingMap, ownMappingFiles, loadMappingFile } from './foundation/mappings.js'
|
|
103
|
+
export { buildComputeMap, ownComputeFiles, readComputeFile, computeFileDigest, COMPUTE_DIR } from './foundation/compute.js'
|
|
104
|
+
export { runComputeFunction, LIMITS as COMPUTE_LIMITS } from './foundation/compute-run.js'
|
|
103
105
|
|
|
104
106
|
// Default export is the combined Vite plugin
|
|
105
107
|
export { default } from './vite-foundation-plugin.js'
|
package/src/schema.js
CHANGED
|
@@ -1421,6 +1421,26 @@ export async function buildSchema(srcDir, sectionPaths, derivedSupports = null,
|
|
|
1421
1421
|
Object.assign(mappings, map)
|
|
1422
1422
|
}
|
|
1423
1423
|
|
|
1424
|
+
// Its compute functions — every file in its `compute/` folder (`foundation/compute.js`), shipped
|
|
1425
|
+
// as written — and the library ones its main.js carries (`compute: ['@acme/x']`), in full.
|
|
1426
|
+
// Editor-time: `_compute` holds each file's exports, never on a page.
|
|
1427
|
+
const compute = {}
|
|
1428
|
+
{
|
|
1429
|
+
const { buildComputeMap } = await import('./foundation/compute.js')
|
|
1430
|
+
const own = await buildComputeMap(srcDir)
|
|
1431
|
+
for (const warning of own.warnings) console.warn(`[uniweb] ${warning}`)
|
|
1432
|
+
Object.assign(compute, own.map)
|
|
1433
|
+
}
|
|
1434
|
+
if (foundationConfig.compute !== undefined) {
|
|
1435
|
+
const { resolveLibraryCompute } = await import('./foundation/library-compute.js')
|
|
1436
|
+
const { map, warnings } = await resolveLibraryCompute(foundationConfig.compute, {
|
|
1437
|
+
srcDir,
|
|
1438
|
+
ownScope: splitFoundationName(foundationNameOf({ config: foundationConfig, pkg: identity }).name || '').scope,
|
|
1439
|
+
})
|
|
1440
|
+
for (const warning of warnings) console.warn(`[uniweb] ${warning}`)
|
|
1441
|
+
Object.assign(compute, map)
|
|
1442
|
+
}
|
|
1443
|
+
|
|
1424
1444
|
// Discover layouts from src/layouts/
|
|
1425
1445
|
const layouts = await discoverLayoutsInPath(srcDir)
|
|
1426
1446
|
// The layout a page that names none renders with — the entry gets the same answer
|
|
@@ -1453,8 +1473,8 @@ export async function buildSchema(srcDir, sectionPaths, derivedSupports = null,
|
|
|
1453
1473
|
|
|
1454
1474
|
// Build _self, stripping the raw extension boolean in favor of normalized role, and the
|
|
1455
1475
|
// declared `defaultLayout` in favor of the resolved one (`resolveDefaultLayout`)
|
|
1456
|
-
// `mappings` goes to `_mappings` with the foundation's own, each fact once.
|
|
1457
|
-
const { extension: _ext, defaultLayout: _declaredLayout, mappings: _libraryMappings, ...configWithoutExtension } = foundationConfig
|
|
1476
|
+
// `mappings` goes to `_mappings` with the foundation's own, and `compute` to `_compute`, each fact once.
|
|
1477
|
+
const { extension: _ext, defaultLayout: _declaredLayout, mappings: _libraryMappings, compute: _libraryCompute, ...configWithoutExtension } = foundationConfig
|
|
1458
1478
|
|
|
1459
1479
|
// `supports` is the one identity field the build knows better than the file.
|
|
1460
1480
|
// `identity.supports` is already normalized (absent stays absent, `[]` stays
|
|
@@ -1504,6 +1524,7 @@ export async function buildSchema(srcDir, sectionPaths, derivedSupports = null,
|
|
|
1504
1524
|
// Layout metadata (full, for editor)
|
|
1505
1525
|
...(Object.keys(dataSchemas).length > 0 && { dataSchemas }),
|
|
1506
1526
|
...(Object.keys(mappings).length > 0 && { _mappings: mappings }),
|
|
1527
|
+
...(Object.keys(compute).length > 0 && { _compute: compute }),
|
|
1507
1528
|
...(Object.keys(layouts).length > 0 && { _layouts: layouts }),
|
|
1508
1529
|
...components,
|
|
1509
1530
|
}
|
package/src/site/config.js
CHANGED
|
@@ -35,7 +35,7 @@ import { jsxExtensionGuard } from '../jsx-extension.js'
|
|
|
35
35
|
import { foundationScopeDefine } from '../foundation/scope-define.js'
|
|
36
36
|
import { resolveModuleUrl, resolveExtensionUrls } from './extension-urls.js'
|
|
37
37
|
import { resolveFoundationSrcPath } from '../utils/foundation-source-root.js'
|
|
38
|
-
import {
|
|
38
|
+
import { foundationImportsPlugin } from './foundation-imports.js'
|
|
39
39
|
import { detectFoundationType } from './foundation-ref.js'
|
|
40
40
|
import { librariesOf } from '../foundation/libraries.js'
|
|
41
41
|
import { libraryImports } from '../foundation/library-imports.js'
|
|
@@ -288,19 +288,6 @@ export async function defineSiteConfig(options = {}) {
|
|
|
288
288
|
)
|
|
289
289
|
}
|
|
290
290
|
|
|
291
|
-
// Do we and vite agree on which directory that was? Two resolutions run
|
|
292
|
-
// here — ours by path, vite's by the bare specifier below
|
|
293
|
-
// (`alias['#foundation'] = foundationInfo.name`) — and when they diverge
|
|
294
|
-
// the quiet outcome is worse than the loud one: a stale entry in vite's
|
|
295
|
-
// directory builds the WRONG foundation and reports success.
|
|
296
|
-
const agreement = checkFoundationResolution({
|
|
297
|
-
name: foundationInfo.name,
|
|
298
|
-
generatedInto: srcDir,
|
|
299
|
-
generatedEntry: entryPath,
|
|
300
|
-
siteRoot,
|
|
301
|
-
})
|
|
302
|
-
if (!agreement.ok) console.warn(`\n${agreement.message}\n`)
|
|
303
|
-
|
|
304
291
|
// Code the foundation's stylesheet names no `@source` for: here is where its classes go
|
|
305
292
|
// missing, in a site build and under `uniweb dev`, while its own build has them all.
|
|
306
293
|
const unread = unreadFolders(join(srcDir, 'styles.css'))
|
|
@@ -401,32 +388,11 @@ export async function defineSiteConfig(options = {}) {
|
|
|
401
388
|
// Point #foundation at a virtual noop module.
|
|
402
389
|
alias['#foundation'] = '\0__foundation-noop__'
|
|
403
390
|
} else if (foundationInfo.type !== 'url') {
|
|
404
|
-
// Bundled mode:
|
|
405
|
-
//
|
|
406
|
-
//
|
|
407
|
-
//
|
|
408
|
-
|
|
409
|
-
// lookup disagree with ours (the whole reason
|
|
410
|
-
// `uniweb:ensure-foundation-entry` now runs `checkFoundationResolution`).
|
|
411
|
-
// Collapsing the two by aliasing to the path looks like it deletes that bug
|
|
412
|
-
// class. It does not:
|
|
413
|
-
//
|
|
414
|
-
// A vite alias is PREFIX replacement, so `#foundation/styles` — which the
|
|
415
|
-
// site's own `entry.js` imports — becomes `<path>/styles`, a filesystem
|
|
416
|
-
// path. That bypasses the foundation's `exports` map, and the map is where
|
|
417
|
-
// `./styles` → `./styles.css` lives (along with `./dist` and
|
|
418
|
-
// `./dist/styles`). Measured 2026-09-01 on a stock marketing scaffold:
|
|
419
|
-
// `[vite:load-fallback] Could not load <path>/src/styles (imported by
|
|
420
|
-
// entry.js): ENOENT`. A HEALTHY project fails to build.
|
|
421
|
-
//
|
|
422
|
-
// Splitting it — exact `#foundation` → path, `#foundation/*` → name — is
|
|
423
|
-
// worse still: on a diverged tree the entry would come from one directory
|
|
424
|
-
// and the stylesheet from another, which is a state neither consistent
|
|
425
|
-
// option can reach.
|
|
426
|
-
//
|
|
427
|
-
// ⇒ **The name is load-bearing because the exports map is.** Detecting the
|
|
428
|
-
// disagreement is the correct shape; eliminating it costs the exports map.
|
|
429
|
-
alias['#foundation'] = foundationInfo.name
|
|
391
|
+
// Bundled mode: `#foundation` and `#foundation/<sub>` are read from the folder
|
|
392
|
+
// `detectFoundationType` found, through that folder's own exports map
|
|
393
|
+
// (`foundation-imports.js`), never through node_modules, where a package
|
|
394
|
+
// manager may hold a stale copy of it.
|
|
395
|
+
plugins.push(foundationImportsPlugin(foundationInfo.path))
|
|
430
396
|
}
|
|
431
397
|
|
|
432
398
|
// Virtual module plugin for the noop foundation stub
|