uniweb 1.34.5 → 1.34.7

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",
3
- "version": "1.34.5",
3
+ "version": "1.34.7",
4
4
  "description": "Create structured Vite + React sites with content/code separation",
5
5
  "type": "module",
6
6
  "bin": {
@@ -41,15 +41,15 @@
41
41
  "js-yaml": "^4.3.2",
42
42
  "prompts": "^2.4.2",
43
43
  "tar": "^7.5.21",
44
- "@uniweb/core": "~1.6.12",
45
- "@uniweb/semantic-parser": "~1.13.4",
46
44
  "@uniweb/content-writer": "~1.3.2",
47
- "@uniweb/schemas": "~1.7.4"
45
+ "@uniweb/core": "~1.6.13",
46
+ "@uniweb/schemas": "~1.7.4",
47
+ "@uniweb/semantic-parser": "~1.13.5"
48
48
  },
49
49
  "peerDependencies": {
50
50
  "@uniweb/content-reader": "~1.5.10",
51
- "@uniweb/semantic-parser": "~1.13.4",
52
- "@uniweb/build": "~1.23.4"
51
+ "@uniweb/semantic-parser": "~1.13.5",
52
+ "@uniweb/build": "~1.23.6"
53
53
  },
54
54
  "peerDependenciesMeta": {
55
55
  "@uniweb/build": {
@@ -103,7 +103,7 @@ integrations: # by a mapping the foundation declares in src/mappi
103
103
  - **Applied once**, when a backend is started from the site: its own, a clone's of a template, or one started again after it was destroyed. Then the operator changes these in the backend's administration. An edited file is pushed and pulled with the site, and reaches no backend already running: once the site's has started, a push or publish that sends a change says so, and so does `uniweb status`.
104
104
  - A type not listed stays closed. Name types as `queries.yml` does: `@/vehicle` for the foundation's own, sent in its scope.
105
105
  - A build, a push and `uniweb doctor` refuse a malformed file, naming the key; a push refuses whole. A type none of the site's foundations declares only warns: a backend started from the site leaves that line out, and the publish says so. `where`, `sort` and `limit` are the backend's to judge, and one it refuses is left out the same way.
106
- - An integration's `channel`/`trigger` pairs: `file`+`manual`, `feed`+`on_fetch`, `email` or `http` + `on_create`/`on_match`/`on_change`/`manual`. `enabled: true` only on `file` or `feed`; an address, URL or key is never the file's (the owner gives it in the administration). An `http` line may name a `reply` mapping (named as `mapping` is) and, with it, `reply_about: section.field`. A mapping (`src/mappings/`, one per file, `model: '@/vehicle'` plus its rules) registers with the foundation; the build refuses one naming no `model`, or an `@/x` type (its `model`, or a `follow` line's `model`) or `keys_from` the foundation does not define. A library's mappings (its `mappings/`, named in its scope) are carried by `mappings: ['@acme/x']` in the foundation's `main.js`; `register` sends them from the library first, and the site names them in full.
106
+ - An integration's `channel`/`trigger` pairs: `file`+`manual`, `feed`+`on_fetch`, `email` or `http` + `on_create`/`on_match`/`on_change`/`manual`. `enabled: true` only on `file` or `feed` (or an `http` line naming a `vendor`); an address, URL or key is never the file's (the owner gives it in the administration). An `http` line may name a `reply` mapping (named as `mapping` is) and, with it, `reply_about: section.field`. A mapping (`src/mappings/`, one per file, `model: '@/vehicle'` plus its rules) registers with the foundation; the build refuses one naming no `model`, or an `@/x` type (its `model`, or a `follow` line's `model`) or `keys_from` the foundation does not define. A library's mappings (its `mappings/`, named in its scope) are carried by `mappings: ['@acme/x']` in the foundation's `main.js`; `register` sends them from the library first, and the site names them in full. An `http` line may name `vendor: '@/courses#grade'` in place of an address: a function in a compute file (`src/compute/<name>.js`, or a library's `compute/` carried by `compute: ['@acme/x']` in `main.js`), run by the platform; only such a line may also take `enabled: true`. A compute file is one plain module of named function exports with no imports, sent as written; a call takes `input` (what `mapping` wrote), returns a JSON object read by `reply`, and changes nothing outside itself. `uniweb compute run courses#grade --input in.json` runs one under the rules it runs by (no Node globals, no network, frozen built-ins), which a test in Node doesn't. The full rules are in the docs' Compute Functions page.
107
107
  - A team's `all: edit` reaches the entries once the member confirms it is them (below); a team's `add` and `members: edit` need no confirming. Who is in a team, and roles, are never the file's.
108
108
  - A static build carries none of it. A pull writes it back here, never into `site.yml`.
109
109
 
@@ -131,7 +131,7 @@ Image attributes: `{width=800 height=600 loading=lazy fit=cover position=center
131
131
 
132
132
  **Section links:** `page:about#team` → `/about#section-team`; `page:/#features` → a homepage section. The id is the file name without its number (`2-features.md` → `features`) or `id:` in frontmatter.
133
133
 
134
- **Where media lives.** `./x` is beside the page, `/x` is in `public/`; both reach a static build and a published site. Keep a page's media beside it, and in `public/` what belongs to the whole site: the favicon, fonts. **Only a static host gives a file a fixed address** at the site root. A site published with Uniweb serves a file that something names from an address the upload gives it, and nothing at `/x` — so for a file other sites or scripts fetch by URL, keep it somewhere with its own address and add a page whose `redirect:` goes there. A static build copies `public/` whole and adds its own copy of each file a page names there. `uniweb push` uploads a file beside a page wherever the page is (mounted directories included); a file outside the site and its mounts is not uploaded — put that in `public/`. There is no `assets/` directory for media; a build stops on a `/x` only `assets/` holds.
134
+ **Where media lives.** `./x` is beside the page, `/x` is in `public/`; both reach a static build and a published site. Keep a page's media beside it, and in `public/` what belongs to the whole site: the favicon, fonts. **Only a static host gives a file a fixed address** at the site root. A site published with Uniweb serves a file that something names from an address the upload gives it, and nothing at `/x` — so for a file other sites or scripts fetch by URL, keep it somewhere with its own address and add a page whose `redirect:` goes there. A static build copies `public/` whole, a photo's location included, and adds its own copy of each file a page names there: keep a phone's photos beside their page. **A picture is made ready before it is stored or shipped:** `uniweb push` and `uniweb publish` upload, and a static build copies, a PNG, JPEG or GIF as a WebP when that is at least 10% smaller (a TIFF or HEIC always), turned upright and without its location and camera data; a WebP stays one, without that data. The favicon, the touch icon, the site's card and its social images go up in their own format, without their location and camera data; a static build serves them from `public/` as they are. A picture keeps its pixels, so add one no wider than a page shows it; a HEIC from a phone that can't be converted here goes up as it is, with a note: export it as JPEG. `uniweb push` uploads a file beside a page wherever the page is (mounted directories included); a file outside the site and its mounts is not uploaded — put that in `public/`. There is no `assets/` directory for media; a build stops on a `/x` only `assets/` holds.
135
135
 
136
136
  **Placement** (`{placement=left|right|wide|full}`) on an image or video, or on a table's caption line, which follows the table after a blank line (`: Plans and prices {placement=wide #tbl-plans}`, which also sets caption and id; with no blank line it becomes a row). It's the author's intent, honoured by kit's `<Render>`, `<Prose>` and `<Article>` and ignored by other components; a section type declares which it honours in `meta.js` (`sequence: { placement: true }`) and the build warns on a mismatch.
137
137
 
@@ -40,7 +40,7 @@ import {
40
40
  fetchOrgs as fetchOrgsImpl,
41
41
  createOrg as createOrgImpl
42
42
  } from '../utils/registry-orgs.js'
43
- import { uploadFoundationCode } from '../utils/code-upload.js'
43
+ import { uploadFoundationCode, uploadVendorFile } from '../utils/code-upload.js'
44
44
  import { uploadSiteAssets } from '../utils/asset-upload.js'
45
45
 
46
46
  /**
@@ -664,6 +664,19 @@ export class BackendClient {
664
664
  })
665
665
  }
666
666
 
667
+ /**
668
+ * Deliver one registered compute file, addressed by its bytes' sha256 (`vendor-uploads`).
669
+ * Thin pass-through to utils/code-upload.js with this client's origin + token.
670
+ * @param {object} opts - { name, file }
671
+ */
672
+ async uploadVendorFile(opts) {
673
+ return uploadVendorFile({
674
+ apiBase: this.origin,
675
+ token: await this.token(),
676
+ ...opts
677
+ })
678
+ }
679
+
667
680
  /**
668
681
  * GET /dev/registry/data-schemas/{scope}/{name} — a Model declaration, or
669
682
  * null on 404 (the caller then says to register the foundation that defines it). Accepts `@scope/name`
@@ -102,14 +102,16 @@ export function typesNamedBy(mapping) {
102
102
  * names, with its definition
103
103
  * @param {Record<string, object|null>} [o.mappings] - the foundation's built `_mappings`: its own
104
104
  * (`@/x`) and the library ones its main.js carries (in full)
105
+ * @param {Record<string, object|null>} [o.vendors] - the foundation's built `_compute`: its own
106
+ * (`@/x`) and the library compute files its main.js carries (in full)
105
107
  * @param {string} o.foundationDir
106
- * @returns {Promise<Array<{ dir: string, scope: string, refs: string[], mappings: string[] }>>}
107
- * `mappings`: the library mappings it carries from that library, in full
108
+ * @returns {Promise<Array<{ dir: string, scope: string, refs: string[], mappings: string[], vendors: string[] }>>}
109
+ * `mappings`, `vendors`: the library mappings and compute files it carries from that library, in full
108
110
  * @throws {Error} `code: 'BUILD_TOO_OLD'` when the installed `@uniweb/build` can't tell
109
111
  */
110
- export async function typesFromLibraries({ schemas, mappings, foundationDir }) {
112
+ export async function typesFromLibraries({ schemas, mappings, vendors, foundationDir }) {
111
113
  const build = await import('@uniweb/build')
112
- const { workspaceTypeFiles, workspaceMappingFiles, packageTypeScope, classifyPackage, isSchemasPackage, routedSchema, resolveFoundationSrcPath } = build
114
+ const { workspaceTypeFiles, workspaceMappingFiles, workspaceComputeFiles, packageTypeScope, classifyPackage, isSchemasPackage, routedSchema, resolveFoundationSrcPath } = build
113
115
  if ([workspaceTypeFiles, packageTypeScope, routedSchema].some((fn) => typeof fn !== 'function')) {
114
116
  throw Object.assign(new Error('the installed @uniweb/build cannot tell which library defines a type'), { code: 'BUILD_TOO_OLD' })
115
117
  }
@@ -127,7 +129,7 @@ export async function typesFromLibraries({ schemas, mappings, foundationDir }) {
127
129
  if (classifyPackage(dir) === 'foundation' || !isSchemasPackage(dir)) continue
128
130
  const scope = await packageTypeScope(dir, 'schemas')
129
131
  if (!scope) continue
130
- if (!byDir.has(dir)) byDir.set(dir, { dir, scope, refs: [], mappings: [] })
132
+ if (!byDir.has(dir)) byDir.set(dir, { dir, scope, refs: [], mappings: [], vendors: [] })
131
133
  byDir.get(dir).refs.push(ref)
132
134
  }
133
135
  // ⭐ The library mappings its main.js carries (`mappings: ['@acme/x']`, `_mappings` keys in full),
@@ -143,9 +145,25 @@ export async function typesFromLibraries({ schemas, mappings, foundationDir }) {
143
145
  if (classifyPackage(dir) === 'foundation' || !isSchemasPackage(dir)) continue
144
146
  const scope = await packageTypeScope(dir, 'schemas')
145
147
  if (!scope) continue
146
- if (!byDir.has(dir)) byDir.set(dir, { dir, scope, refs: [], mappings: [] })
148
+ if (!byDir.has(dir)) byDir.set(dir, { dir, scope, refs: [], mappings: [], vendors: [] })
147
149
  byDir.get(dir).mappings.push(ref)
148
150
  }
149
151
  }
152
+ // ⭐ And the library compute files its main.js carries (`compute: ['@lib/x']`, `_compute` keys in
153
+ // full), found and registered the same way; their library's call is followed by their upload.
154
+ if (typeof workspaceComputeFiles === 'function') {
155
+ for (const ref of Object.keys(vendors || {})) {
156
+ if (!/^@[^/]+\/./.test(ref) || ref.startsWith('@uniweb/')) continue
157
+ const files = await workspaceComputeFiles(ref, foundationDir).catch(() => [])
158
+ if (files.length !== 1) continue
159
+ const dir = packageDirOf(files[0])
160
+ if (!dir || real(dir) === own) continue
161
+ if (classifyPackage(dir) === 'foundation' || !isSchemasPackage(dir)) continue
162
+ const scope = await packageTypeScope(dir, 'schemas')
163
+ if (!scope) continue
164
+ if (!byDir.has(dir)) byDir.set(dir, { dir, scope, refs: [], mappings: [], vendors: [] })
165
+ byDir.get(dir).vendors.push(ref)
166
+ }
167
+ }
150
168
  return referencedFirst([...byDir.values()], schemas || {}, mappings || {})
151
169
  }
@@ -18,6 +18,7 @@ import { existsSync, readFileSync } from 'node:fs'
18
18
  import { basename } from 'node:path'
19
19
  import { resolveAssetPath } from '@uniweb/build/site'
20
20
  import { servedFingerprint } from '@uniweb/build/uwx'
21
+ import { prepareImage, isPreparableImage } from '@uniweb/build/images'
21
22
  import { contentTypeFor } from '../utils/code-upload.js'
22
23
  import { humanBytes } from '../utils/bytes.js'
23
24
 
@@ -27,11 +28,14 @@ import { humanBytes } from '../utils/bytes.js'
27
28
  * @param {string} siteDir - the site root (site-root refs resolve under public/)
28
29
  * @param {Array<string|{ ref: string, path: string, contentType?: string }>} refs - site-root local
29
30
  * asset refs (`/images/x.png`), or files already located (a file record's)
30
- * @param {{ siteUuid?: string|null, onProgress?: (m: string) => void, warn?: (m: string) => void }} [opts]
31
+ * @param {{ siteUuid?: string|null, onProgress?: (m: string) => void, warn?: (m: string) => void, recorded?: Record<string, object> }} [opts]
31
32
  * `siteUuid` is the owner the uploaded bytes are charged to. Callers create the
32
33
  * site before uploading precisely so this is set — an unowned upload is charged
33
34
  * and cannot be freed, because freeing means deleting the owning entity.
34
- * @returns {Promise<{ map: Record<string,string>, ids: Record<string,{id:string,ext:string}>, missing: string[], served: string[], failed: Array<{path:string,status:number,detail?:string}> }>}
35
+ * `recorded` is this backend's asset map from `sync.json`, which says what each ref was stored as.
36
+ * `keepFormat` names the pictures other software fetches by their address, which keep their format
37
+ * and lose only their location and camera data (`prepareImage`'s `keepFormat`).
38
+ * @returns {Promise<{ map: Record<string,string>, ids: Record<string,{id:string,ext:string,source?:string,size?:number}>, missing: string[], served: string[], failed: Array<{path:string,status:number,detail?:string}> }>}
35
39
  * `map` is ref → serve URL for refs that resolved AND uploaded. The two failure
36
40
  * kinds are reported SEPARATELY because callers must treat them differently:
37
41
  * `missing` is a ref with no file under the site — an authoring mistake, already
@@ -47,7 +51,7 @@ export async function uploadSiteMedia(
47
51
  client,
48
52
  siteDir,
49
53
  refs,
50
- { siteUuid = null, onProgress, warn } = {}
54
+ { siteUuid = null, onProgress, warn, recorded = {}, keepFormat = new Set() } = {}
51
55
  ) {
52
56
  if (!refs?.length) return { map: {}, ids: {}, missing: [], served: [], failed: [] }
53
57
 
@@ -74,18 +78,56 @@ export async function uploadSiteMedia(
74
78
  continue
75
79
  }
76
80
  const bytes = readFileSync(resolved)
77
- files.push({
81
+ const declared = typeof item === 'object' ? item.contentType : null
82
+ const file = {
78
83
  path: ref.replace(/^\/+/, ''), // bookkeeping key into the plan (must be unique)
79
- content_type: (typeof item === 'object' && item.contentType) || contentTypeFor(basename(resolved)),
84
+ content_type: declared || contentTypeFor(basename(resolved)),
80
85
  size: bytes.length,
81
- sha256: createHash('sha256').update(bytes).digest('hex'),
86
+ sha256: sha256(bytes),
82
87
  localUrl: ref, // the rewrite key — the original content ref
83
88
  diskPath: resolved
84
- })
89
+ }
90
+ // ⭐ A picture is prepared before it is stored (`prepareImage`). Not a file record's file, which
91
+ // declares its own type: that is a download, kept as its author gave it. A picture other software
92
+ // fetches by its address (`keepFormat`: the favicon, the touch icon, the site's card and its social
93
+ // images) keeps its format, since a home screen takes a PNG and a link preview a JPEG or PNG, and
94
+ // loses only its location and camera data. ⛔ Until 2026-11-12 those went up as they were, so a
95
+ // phone's photo made a social image kept where it was taken, on its page too.
96
+ const ext = extOf(resolved)
97
+ const prepare = !declared && isPreparableImage(ext)
98
+ const options = { keepFormat: keepFormat.has(ref) }
99
+ files.push(prepare ? await preparedFile(file, bytes, ext, recorded?.[ref], warn, options) : file)
85
100
  }
86
101
  if (!files.length) return { map: {}, ids: {}, missing, served, failed: [] }
87
102
 
88
- const result = await client.uploadSiteAssets({ files, siteUuid, onProgress })
103
+ let result = await client.uploadSiteAssets({ files, siteUuid, onProgress })
104
+ // A recorded preparation the backend no longer holds, whose file now prepares to other bytes
105
+ // (the rule changed since): prepared anew, and planned again.
106
+ const stale = (result.failed || []).filter((f) => f.stale)
107
+ if (stale.length) {
108
+ const again = []
109
+ for (const f of stale) {
110
+ const was = files.find((x) => x.path === f.path)
111
+ if (!was) continue
112
+ const bytes = readFileSync(was.diskPath)
113
+ const file = {
114
+ path: was.key,
115
+ content_type: contentTypeFor(basename(was.diskPath)),
116
+ size: bytes.length,
117
+ sha256: sha256(bytes),
118
+ localUrl: was.localUrl,
119
+ diskPath: was.diskPath
120
+ }
121
+ again.push(await preparedFile(file, bytes, extOf(was.diskPath), null, warn, { keepFormat: was.keepFormat }))
122
+ }
123
+ const retry = await client.uploadSiteAssets({ files: again, siteUuid, onProgress })
124
+ result = {
125
+ ...result,
126
+ failed: [...result.failed.filter((f) => !f.stale), ...(retry.failed || [])],
127
+ assetsByLocalUrl: { ...result.assetsByLocalUrl, ...retry.assetsByLocalUrl }
128
+ }
129
+ for (const f of again) files[files.findIndex((x) => x.localUrl === f.localUrl)] = f
130
+ }
89
131
  const failed = [...(result.failed || [])]
90
132
  for (const f of failed)
91
133
  warn?.(`local-media: upload failed for ${f.path} (HTTP ${f.status})`)
@@ -104,10 +146,14 @@ export async function uploadSiteMedia(
104
146
  // id beside it (`info.preview`, `seo.image`, a section param); the header of
105
147
  // `@uniweb/build`'s asset-map.js says why a hash and not the URL.
106
148
  if (entry.id) {
149
+ // A prepared picture also records the file it was made from and its stored size, so the next
150
+ // push reuses it rather than preparing the file again (`preparedFile`).
151
+ const sent = files.find((f) => f.localUrl === ref)
107
152
  ids[ref] = {
108
153
  id: entry.id,
109
154
  ext: entry.ext || '',
110
- ...(entry.serveUrl ? { served: servedFingerprint(entry.serveUrl) } : {})
155
+ ...(entry.serveUrl ? { served: servedFingerprint(entry.serveUrl) } : {}),
156
+ ...(sent?.source ? { source: sent.source, size: sent.size } : {})
111
157
  }
112
158
  }
113
159
  // The backend's canonical serve URL, READ — never composed. An entry without
@@ -135,6 +181,72 @@ export async function uploadSiteMedia(
135
181
  return { map, ids, missing, served, failed }
136
182
  }
137
183
 
184
+ const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex')
185
+ const extOf = (path) => (basename(path).match(/\.([^.]+)$/)?.[1] || '').toLowerCase()
186
+
187
+ /**
188
+ * The plan entry for a picture a page shows, stored as `prepareImage` makes it. Three cases, by what
189
+ * this backend's asset map records for the ref:
190
+ *
191
+ * - **Prepared before, from these same bytes** (`source` is their hash): planned by the identity it
192
+ * recorded, with no bytes, so nothing is prepared again. The backend still holding it, the plan
193
+ * says so and nothing moves. If it doesn't, `load` prepares the file again. So a change to the
194
+ * rule never prepares, uploads or charges an unchanged picture again, and its pages don't change.
195
+ * - **Stored as it is, before pictures were prepared** (no `source`, and the id is these bytes'
196
+ * hash, the asset plan's content address): left as it is, and its source recorded.
197
+ * - **New or changed:** prepared now.
198
+ *
199
+ * @param {object} file - the plan entry for the file as it is
200
+ * @param {Buffer} bytes - the file
201
+ * @param {string} ext - its extension
202
+ * @param {object|undefined|null} prior - its entry in the asset map
203
+ * @param {(m: string) => void} [warn]
204
+ * @param {{ keepFormat?: boolean }} [options] - a picture other software fetches by its address
205
+ */
206
+ async function preparedFile(file, bytes, ext, prior, warn, { keepFormat = false } = {}) {
207
+ const source = file.sha256
208
+ const key = file.path
209
+ if (prior?.source === source && prior.id && prior.ext && Number.isInteger(prior.size)) {
210
+ return {
211
+ ...file,
212
+ key,
213
+ path: storedPath(key, ext, prior.ext),
214
+ content_type: contentTypeFor(`x.${prior.ext}`),
215
+ size: prior.size,
216
+ sha256: prior.id,
217
+ source,
218
+ keepFormat,
219
+ load: async () => (await prepareImage(bytes, ext, { keepFormat })).bytes
220
+ }
221
+ }
222
+ if (prior && !prior.source && prior.id === source) return { ...file, key, source }
223
+
224
+ const prepared = await prepareImage(bytes, ext, { keepFormat })
225
+ if (prepared.unreadable) {
226
+ warn?.(`local-media: ${file.localUrl} is uploaded as it is: it can't be converted here, and some browsers can't show it`)
227
+ }
228
+ return {
229
+ ...file,
230
+ key,
231
+ path: storedPath(key, ext, prepared.ext),
232
+ content_type: contentTypeFor(`x.${prepared.ext}`),
233
+ size: prepared.bytes.length,
234
+ sha256: sha256(prepared.bytes),
235
+ bytes: prepared.bytes,
236
+ source,
237
+ keepFormat
238
+ }
239
+ }
240
+
241
+ /**
242
+ * The plan's key for a prepared file. The backend types an upload by its extension, so a picture
243
+ * stored as a WebP goes by one ending in `.webp`: its own key with the extension added, which keeps
244
+ * it apart from every other file's.
245
+ */
246
+ function storedPath(key, ext, storedExt) {
247
+ return storedExt === ext ? key : `${key}.${storedExt}`
248
+ }
249
+
138
250
  // ─── Asset-plan refusals ──────────────────────────────────────────────────────
139
251
  //
140
252
  // There is deliberately NO status-based refusal predicate here, and re-adding
@@ -0,0 +1,164 @@
1
+ /**
2
+ * `uniweb compute run <file>#<function>` — run one compute function on this machine, under the rules
3
+ * it runs by on the platform: the web's globals and not Node's, no network, frozen built-in
4
+ * prototypes, a JSON object in and a JSON object out, each within its size, and a short time per
5
+ * call. The run itself is `@uniweb/build`'s `runComputeFunction`.
6
+ *
7
+ * ⭐ WHY A VERB, when a test can import the file: a test runs it in Node, which allows everything
8
+ * those rules take away, and where it runs its console output is discarded. So a function that
9
+ * passes its tests can fail every call there with nothing to go on. This run fails it here.
10
+ *
11
+ * The file is named as an integration names it, or by its path:
12
+ *
13
+ * uniweb compute run courses#grade --input answers.json a file of this package's compute/
14
+ * uniweb compute run @acme/grading#score --input in.json a library's, by its full name
15
+ * uniweb compute run src/compute/courses.js#grade --input - < in.json a path; stdin
16
+ *
17
+ * Exit 0 with the answer on stdout, or 1 with why on stderr. `--json` prints one object, either way.
18
+ */
19
+
20
+ import { existsSync, readFileSync } from 'node:fs'
21
+ import { join, resolve } from 'node:path'
22
+ // Imported statically, so a project's older @uniweb/build is named as such (`importProjectCommand`).
23
+ import {
24
+ classifyPackage,
25
+ isSchemasPackage,
26
+ resolveFoundationSrcPath,
27
+ ownComputeFiles,
28
+ workspaceComputeFiles,
29
+ runComputeFunction,
30
+ COMPUTE_DIR,
31
+ } from '@uniweb/build'
32
+
33
+ const colors = {
34
+ reset: '\x1b[0m',
35
+ bright: '\x1b[1m',
36
+ dim: '\x1b[2m',
37
+ red: '\x1b[31m',
38
+ yellow: '\x1b[33m',
39
+ green: '\x1b[32m',
40
+ }
41
+
42
+ const USAGE = 'uniweb compute run <file>#<function> --input <file.json | -> [--json]'
43
+
44
+ /**
45
+ * @param {string[]} args
46
+ * @returns {Promise<{ exitCode: number }>}
47
+ */
48
+ export async function compute(args = []) {
49
+ const [sub, ...rest] = args
50
+ if (sub !== 'run') {
51
+ fail(sub ? `\`uniweb vendor ${sub}\` is not a command. ${USAGE}` : USAGE)
52
+ return { exitCode: 1 }
53
+ }
54
+ return run(rest)
55
+ }
56
+
57
+ async function run(args) {
58
+ const json = args.includes('--json')
59
+ const inputAt = args.indexOf('--input')
60
+ const inline = args.find((a) => a.startsWith('--input='))
61
+ const inputPath = inline ? inline.slice('--input='.length) : inputAt >= 0 ? args[inputAt + 1] : null
62
+ const positional = args.filter((a, i) => !a.startsWith('--') && !(inputAt >= 0 && i === inputAt + 1))
63
+ const say = (failure, extra = {}) => {
64
+ if (json) process.stdout.write(JSON.stringify({ ok: false, failure, warnings: [], ...extra }) + '\n')
65
+ else fail(failure)
66
+ return { exitCode: 1 }
67
+ }
68
+
69
+ if (positional.length !== 1 || !positional[0].includes('#')) {
70
+ return say(`Name the function as \`<file>#<function>\`, as an integration does. ${USAGE}`)
71
+ }
72
+ if ((inputAt >= 0 || inline) && (!inputPath || (inputPath.startsWith('--') && inputPath !== '-'))) return say('`--input` takes a JSON file, or `-` for stdin.')
73
+
74
+ const ref = positional[0]
75
+ const hash = ref.lastIndexOf('#')
76
+ const fileRef = ref.slice(0, hash)
77
+ const exportName = ref.slice(hash + 1)
78
+ if (!fileRef || !exportName) return say(`Name the function as \`<file>#<function>\`, as an integration does. ${USAGE}`)
79
+
80
+ const located = await locate(fileRef)
81
+ if (located.error) return say(located.error)
82
+
83
+ // ⛔ stdin only when asked for, with `-`: an agent's or a script's stdin is often a pipe that
84
+ // never closes, and reading it unasked would wait forever.
85
+ let inputText
86
+ if (!inputPath) {
87
+ return say('Give the function its input: `--input <file.json>`, or `--input -` to read it from stdin.')
88
+ } else if (inputPath === '-') {
89
+ inputText = await readStdin()
90
+ } else {
91
+ if (!existsSync(inputPath)) return say(`There is no file \`${inputPath}\` to read the input from.`)
92
+ inputText = readFileSync(inputPath, 'utf8')
93
+ }
94
+
95
+ const result = await runComputeFunction({ file: located.file, exportName, inputText })
96
+
97
+ if (json) {
98
+ process.stdout.write(JSON.stringify(result) + '\n')
99
+ return { exitCode: result.ok ? 0 : 1 }
100
+ }
101
+
102
+ for (const w of result.warnings) process.stderr.write(`${colors.yellow}⚠${colors.reset} ${w}\n`)
103
+ if (result.ok) {
104
+ process.stdout.write(JSON.stringify(result.answer, null, 2) + '\n')
105
+ } else {
106
+ fail(result.failure)
107
+ for (const p of result.problems || []) process.stderr.write(` - ${p}\n`)
108
+ }
109
+ if (result.wallMs != null) {
110
+ const time = result.cpuMs != null ? `${fmt(result.cpuMs)} ms of CPU` : `${fmt(result.wallMs)} ms`
111
+ process.stderr.write(`${colors.dim}${ref}: ${time} on this machine, which is not where it runs.${colors.reset}\n`)
112
+ }
113
+ return { exitCode: result.ok ? 0 : 1 }
114
+ }
115
+
116
+ /**
117
+ * The compute file `fileRef` names: a path (holding a `/` or ending `.js`), a full name
118
+ * `@scope/name` found in the workspace, or a name of this package's own (`name` or `@/name`).
119
+ */
120
+ async function locate(fileRef) {
121
+ const cwd = process.cwd()
122
+ if (!fileRef.startsWith('@') && (fileRef.includes('/') || fileRef.endsWith('.js'))) {
123
+ const file = resolve(cwd, fileRef)
124
+ return existsSync(file) ? { file } : { error: `There is no file \`${fileRef}\`.` }
125
+ }
126
+
127
+ const own = fileRef.startsWith('@/') ? fileRef.slice(2) : fileRef.startsWith('@') ? null : fileRef
128
+ const isFoundation = classifyPackage(cwd) === 'foundation'
129
+ const srcDir = isFoundation ? resolveFoundationSrcPath(cwd) : cwd
130
+
131
+ if (own !== null) {
132
+ if (!isFoundation && !isSchemasPackage(cwd)) {
133
+ return { error: `\`${fileRef}\` is a compute file of this package, and this is not a foundation or a library. Run it from one, or give the file's path.` }
134
+ }
135
+ const found = ownComputeFiles(srcDir).find((v) => v.name === own)
136
+ if (found) return { file: found.file }
137
+ const shown = isFoundation ? `src/${COMPUTE_DIR}` : COMPUTE_DIR
138
+ const tried = join(shown, `${own}.js`)
139
+ return { error: `There is no compute file \`${own}\`: \`${tried}\` isn't there${own.startsWith('_') ? ', and a name starting with `_` is left out' : ''}.` }
140
+ }
141
+
142
+ const files = await workspaceComputeFiles(fileRef, srcDir)
143
+ if (files.length === 1) return { file: files[0] }
144
+ if (files.length > 1) return { error: `\`${fileRef}\` is defined by ${files.length} packages: ${files.join(', ')}.` }
145
+ return { error: `No package here defines \`${fileRef}\`. Run it from the library that defines it, or give the file's path.` }
146
+ }
147
+
148
+ function readStdin() {
149
+ return new Promise((done, failed) => {
150
+ let text = ''
151
+ process.stdin.setEncoding('utf8')
152
+ process.stdin.on('data', (chunk) => (text += chunk))
153
+ process.stdin.on('end', () => done(text))
154
+ process.stdin.on('error', failed)
155
+ })
156
+ }
157
+
158
+ function fail(message) {
159
+ process.stderr.write(`${colors.red}✗${colors.reset} ${message}\n`)
160
+ }
161
+
162
+ function fmt(ms) {
163
+ return ms < 10 ? ms.toFixed(2) : String(Math.round(ms))
164
+ }
@@ -594,10 +594,13 @@ export async function publish(args = []) {
594
594
  say.dim(`This publish creates the site in ${describeWorkspace(ws.workspace)} (${SOURCE_LABEL[ws.source]}).`)
595
595
  }
596
596
 
597
- // 2. Build the site data (link mode): dist/site-content.json (+ per-locale)
598
- // and dist/data/*. No media is processed: 4b uploads it from the site's
599
- // own files. Spawn the SAME CLI binary so the inner build can't resolve to
600
- // a different installed version.
597
+ // 2. Build the site data (link mode): dist/site-content.json (+ per-locale),
598
+ // read back only for the languages to make live; the content itself goes
599
+ // over the sync wire, built from source. No compiled data files: every
600
+ // record has a data schema and a push sends it as an entity
601
+ // (`site/build-site-data.js`, "Does NOT emit"). No media is processed:
602
+ // step 4 uploads it from the site's own files. Spawn the SAME CLI binary
603
+ // so the inner build can't resolve to a different installed version.
601
604
  //
602
605
  // ⛔ *This listed `dist/assets/*` until 2026-10-22; the link build has made
603
606
  // no media copies since 2026-10-19 (`site/build-site-data.js`, "Does NOT
@@ -788,7 +791,11 @@ export async function publish(args = []) {
788
791
  {
789
792
  siteUuid: site.uuid,
790
793
  onProgress: (m) => say.dim(` ${m}`),
791
- warn: (m) => say.dim(`! ${m}`)
794
+ warn: (m) => say.dim(`! ${m}`),
795
+ // What each picture was stored as, so an unchanged one is not prepared again.
796
+ recorded: readBackendState(siteDir, client.origin).assets || {},
797
+ // The pictures other software fetches (favicon, touch icon, card, social images): in their format.
798
+ keepFormat: new Set(probe.outsideAssets || [])
792
799
  }
793
800
  )
794
801
  // A ref whose bytes did not land must NOT be published: the content would go
@@ -516,6 +516,8 @@ export async function push(args = [], deps = {}) {
516
516
  let created = null
517
517
  if (!output && !dryRun) {
518
518
  let mediaRefs = []
519
+ // The pictures other software fetches (favicon, touch icon, card, social images): uploaded as they are.
520
+ let outsideRefs = new Set()
519
521
  let refusals = []
520
522
  let held = null
521
523
  try {
@@ -531,6 +533,7 @@ export async function push(args = [], deps = {}) {
531
533
  })
532
534
  // Site-root media, and each file record's file (`@uniweb/file` — `{ ref, path, contentType }`).
533
535
  mediaRefs = [...(probe.localAssets || []), ...(probe.localFiles || [])]
536
+ outsideRefs = new Set(probe.outsideAssets || [])
534
537
  refusals = probe.refusals || []
535
538
  held = probe
536
539
  } catch (err) {
@@ -573,7 +576,10 @@ export async function push(args = [], deps = {}) {
573
576
  {
574
577
  siteUuid: site.uuid,
575
578
  onProgress: (m) => note(` ${m}`),
576
- warn: (m) => note(`! ${m}`)
579
+ warn: (m) => note(`! ${m}`),
580
+ // What each picture was stored as, so an unchanged one is not prepared again.
581
+ recorded: readBackendState(siteDir, client.origin).assets || {},
582
+ keepFormat: outsideRefs
577
583
  }
578
584
  )
579
585
  // Bytes that did not land must not be pushed around: the content would go
@@ -83,6 +83,10 @@ import {
83
83
  buildMappingMap,
84
84
  ownMappingFiles,
85
85
  loadMappingFile,
86
+ ownComputeFiles,
87
+ readComputeFile,
88
+ computeFileDigest,
89
+ resolveFoundationSrcPath,
86
90
  readFoundationName,
87
91
  checkFoundationName,
88
92
  checkRegistrationScope,
@@ -286,6 +290,68 @@ async function libraryMappingsWanted(lib, own) {
286
290
  return out
287
291
  }
288
292
 
293
+ /**
294
+ * The compute files a package defines in `dir`'s `compute/` (`foundation/compute.js`), keyed `@/<name>`
295
+ * as `buildRegistryPackage` and `buildSchemaOnlyPackage` take them: each one's exports, the `sha256`
296
+ * and `size` of its bytes as on disk, and its file. Read at register, so what registers is what goes
297
+ * up after.
298
+ *
299
+ * @param {string} dir - a library's root, or a foundation's source root
300
+ * @param {object} [o]
301
+ * @param {Set<string>|null} [o.only] - the `@/x` to keep (a library's, the ones a foundation carries)
302
+ * @param {string} [o.shownIn] - the folder as its errors name it
303
+ * @throws {Error} naming a file that cannot be registered (the build refuses it first)
304
+ */
305
+ async function vendorFilesIn(dir, { only = null, shownIn = 'compute' } = {}) {
306
+ const out = {}
307
+ const found = []
308
+ for (const { name, file } of ownComputeFiles(dir)) {
309
+ const ref = `@/${name}`
310
+ if (only && !only.has(ref)) continue
311
+ const { exports, problems } = await readComputeFile(file)
312
+ if (problems.length) found.push(...problems.map((p) => `${shownIn}/${name}.js ${p}`))
313
+ else out[ref] = { exports, ...computeFileDigest(file), file }
314
+ }
315
+ if (found.length) throw new Error(found.join('\n '))
316
+ return out
317
+ }
318
+
319
+ /**
320
+ * Upload each compute file a call just registered, by its bytes' sha256 (`vendor-uploads`): after the
321
+ * call that registered it, and before the foundation that names it is taken, where the order allows.
322
+ * A file the registry already stores is not sent again.
323
+ *
324
+ * @param {object[]} entities - the call's `@uniweb/vendor-schema` artifacts, names in full
325
+ * @param {Object<string, { file: string }>} files - `@/<name>` → its file (`vendorFilesIn`)
326
+ * @param {object} o
327
+ * @param {BackendClient} o.client
328
+ * @returns {Promise<boolean>} false when one could not be delivered, which is said already
329
+ */
330
+ async function uploadVendorFiles(entities, files, { client }) {
331
+ const vendors = entities.filter((e) => e.model === '@uniweb/vendor-schema')
332
+ if (!vendors.length) return true
333
+ info(`Delivering ${vendors.length} compute file(s) …`)
334
+ for (const entity of vendors) {
335
+ const file = files[`@/${entity.name.slice(entity.name.indexOf('/') + 1)}`]?.file
336
+ if (!file) continue
337
+ try {
338
+ const { version, uploaded } = await client.uploadVendorFile({ name: entity.name, file })
339
+ log(` ${colors.dim}${entity.name}${version != null ? `@${version}` : ''} (${uploaded ? `${entity.size} bytes` : 'already stored'})${colors.reset}`)
340
+ } catch (err) {
341
+ if (err.status >= 400 && err.status < 500 && err.detail) {
342
+ error(`Compute file refused: HTTP ${err.status}`)
343
+ log(` ${err.detail}`)
344
+ if (err.code) log(` ${colors.dim}(${err.code})${colors.reset}`)
345
+ } else {
346
+ error(`Could not deliver the compute file ${entity.name}: ${err.message}`)
347
+ log(` ${colors.dim}It is registered, and a site that calls it waits for it: re-run \`uniweb register\` to deliver it.${colors.reset}`)
348
+ }
349
+ return false
350
+ }
351
+ }
352
+ return true
353
+ }
354
+
289
355
  /** A mapping's reverse `follow` lines' `model`s, as written. */
290
356
  function followModelsOf(decl) {
291
357
  const out = []
@@ -311,11 +377,13 @@ function followModelsOf(decl) {
311
377
  * @param {BackendClient} o.client
312
378
  * @param {object} o.exporter - the `.uwx` envelope's exporter
313
379
  * @param {string} o.at - its folder as the person sees it
380
+ * @param {boolean} [o.upload] - whether to upload its compute files after the call (not on --schema-only)
314
381
  * @returns {Promise<{ names: string[], body: object|null }|null>} the names sent and the registry's
315
382
  * answer; null when the release stops, which is said already
316
383
  */
317
- async function registerLibraryTypes(lib, { client, exporter, at }) {
384
+ async function registerLibraryTypes(lib, { client, exporter, at, upload = true }) {
318
385
  let doc
386
+ let vendorFiles = {}
319
387
  try {
320
388
  // The types the foundation names from it, and no other of its files: those may be another
321
389
  // package's to register, or a copy of one the foundation defines (`library-types.js`).
@@ -341,9 +409,14 @@ async function registerLibraryTypes(lib, { client, exporter, at }) {
341
409
  }
342
410
  }
343
411
  }
412
+ // ⭐ The compute files it carries from here, as on disk: registered in this call, uploaded after it.
413
+ vendorFiles = (lib.vendors || []).length
414
+ ? await vendorFilesIn(lib.dir, { only: new Set(lib.vendors.map(own).filter(Boolean)) })
415
+ : {}
344
416
  doc = buildSchemaOnlyPackage({
345
417
  schemas: Object.fromEntries(Object.entries(all).filter(([key]) => wanted.has(key))),
346
418
  mappings,
419
+ vendors: vendorFiles,
347
420
  scope: lib.scope,
348
421
  exporter
349
422
  })
@@ -353,7 +426,9 @@ async function registerLibraryTypes(lib, { client, exporter, at }) {
353
426
  }
354
427
  const names = doc.entities.map((e) => e.name)
355
428
  const typeNames = doc.entities.filter((e) => e.model === '@uniweb/data-schema').map((e) => e.name)
356
- info(`Registering ${(lib.mappings || []).length ? 'the data schemas and mappings' : 'the data schemas'} in ${at} (${names.join(', ')}) …`)
429
+ const vendorNames = doc.entities.filter((e) => e.model === '@uniweb/vendor-schema').map((e) => e.name)
430
+ const kinds = ['the data schemas', (lib.mappings || []).length && 'mappings', vendorNames.length && 'compute files'].filter(Boolean)
431
+ info(`Registering ${kinds.length > 1 ? `${kinds.slice(0, -1).join(', ')} and ${kinds.at(-1)}` : kinds[0]} in ${at} (${names.join(', ')}) …`)
357
432
  let res
358
433
  try {
359
434
  res = await client.register(JSON.stringify(doc, null, 2))
@@ -373,11 +448,13 @@ async function registerLibraryTypes(lib, { client, exporter, at }) {
373
448
  if (names.length === typeNames.length && answers.length === names.length && answers.every((a) => a?.unchanged === true)) {
374
449
  log(` ${colors.dim}Unchanged: the registry holds them as they are.${colors.reset}`)
375
450
  } else {
376
- const mappingCount = names.length - typeNames.length
451
+ const mappingCount = names.length - typeNames.length - vendorNames.length
377
452
  success(
378
- `Registered ${[typeNames.length && `${typeNames.length} data schema(s)`, mappingCount && `${mappingCount} mapping(s)`].filter(Boolean).join(' and ')} under ${lib.scope}, from ${at}`
453
+ `Registered ${[typeNames.length && `${typeNames.length} data schema(s)`, mappingCount && `${mappingCount} mapping(s)`, vendorNames.length && `${vendorNames.length} compute file(s)`].filter(Boolean).join(' and ')} under ${lib.scope}, from ${at}`
379
454
  )
380
455
  }
456
+ // Its compute files' bytes, before the foundation that names them is taken (not on --schema-only).
457
+ if (upload && !(await uploadVendorFiles(doc.entities, vendorFiles, { client }))) return null
381
458
  return { names, body }
382
459
  }
383
460
  const member = await memberOfScope(res, lib.scope, client)
@@ -388,10 +465,10 @@ async function registerLibraryTypes(lib, { client, exporter, at }) {
388
465
  const held = await Promise.all(
389
466
  lib.refs.map((ref) => client.readDataSchema(ref).catch(() => undefined))
390
467
  )
391
- // A mapping isn't read back here: the foundation's own register is refused, naming the mapping
392
- // and its library, when the registry doesn't hold it.
468
+ // A mapping or a compute file isn't read back here: the foundation's own register is refused,
469
+ // naming it and its library, when the registry doesn't hold it.
393
470
  if (held.every(Boolean)) {
394
- const taken = [...lib.refs, ...(lib.mappings || [])]
471
+ const taken = [...lib.refs, ...(lib.mappings || []), ...(lib.vendors || [])]
395
472
  const one = taken.length === 1
396
473
  info(
397
474
  `${taken.join(', ')} ${one ? 'is' : 'are'} registered under ${lib.scope}, whose members change ${one ? 'it' : 'them'}: the foundation is released against ${one ? 'it' : 'them'} as registered.`
@@ -899,19 +976,24 @@ async function runRegister(args = []) {
899
976
  let schema = null
900
977
  let schemas = null
901
978
  let mappings = null
979
+ // `@/<name>` → { exports, sha256, size, file }: the compute files this package defines, read from
980
+ // disk here, registered in its call and uploaded after it.
981
+ let vendorFiles = {}
902
982
  if (standalone) {
903
983
  try {
904
984
  schemas = await collectStandaloneSchemas(targetDir)
905
985
  // A library's mappings, beside its types (`mappings/`): registered with them, after them.
906
986
  mappings = await buildMappingMap(targetDir, { ownTypes: Object.keys(schemas || {}), shownIn: 'mappings' })
987
+ // And its compute files (`compute/`), after those.
988
+ vendorFiles = await vendorFilesIn(targetDir)
907
989
  } catch (err) {
908
990
  error(`Could not read the schemas package: ${err.message}`)
909
991
  return { exitCode: 2 }
910
992
  }
911
- if ((!schemas || Object.keys(schemas).length === 0) && Object.keys(mappings || {}).length === 0) {
912
- error('No data schemas or mappings found in this package.')
993
+ if ((!schemas || Object.keys(schemas).length === 0) && Object.keys(mappings || {}).length === 0 && Object.keys(vendorFiles).length === 0) {
994
+ error('No data schemas, mappings or compute files found in this package.')
913
995
  log(
914
- ` ${colors.dim}Expected a package that exports schemas (getSchema / schemas), or a schemas/ or mappings/ directory of *.yml files.${colors.reset}`
996
+ ` ${colors.dim}Expected a package that exports schemas (getSchema / schemas), or a schemas/ or mappings/ directory of *.yml files, or a compute/ directory of *.js files.${colors.reset}`
915
997
  )
916
998
  return { exitCode: 2 }
917
999
  }
@@ -980,6 +1062,17 @@ async function runRegister(args = []) {
980
1062
  error(`Could not read ${schemaPath}: ${err.message}`)
981
1063
  return { exitCode: 2 }
982
1064
  }
1065
+ // Its own compute files (`src/compute/`), read from disk as they will go up: the build listed
1066
+ // them in `_compute`, and the bytes' sha256 and size are taken now.
1067
+ const own = Object.keys(schema._compute || {}).filter((ref) => ref.startsWith('@/'))
1068
+ if (own.length) {
1069
+ try {
1070
+ vendorFiles = await vendorFilesIn(resolveFoundationSrcPath(targetDir), { only: new Set(own), shownIn: 'src/compute' })
1071
+ } catch (err) {
1072
+ error(`Could not read the foundation's compute files: ${err.message}`)
1073
+ return { exitCode: 2 }
1074
+ }
1075
+ }
983
1076
  }
984
1077
 
985
1078
  // ⭐ The types it names that a library defines: registered from the library before the
@@ -990,6 +1083,7 @@ async function runRegister(args = []) {
990
1083
  fromLibraries = await typesFromLibraries({
991
1084
  schemas: schema?.dataSchemas || {},
992
1085
  mappings: schema?._mappings || {},
1086
+ vendors: schema?._compute || {},
993
1087
  foundationDir: targetDir
994
1088
  })
995
1089
  } catch (err) {
@@ -1049,14 +1143,15 @@ async function runRegister(args = []) {
1049
1143
  let doc
1050
1144
  try {
1051
1145
  doc = standalone
1052
- ? buildSchemaOnlyPackage({ schemas, mappings, scope, exporter })
1146
+ ? buildSchemaOnlyPackage({ schemas, mappings, vendors: vendorFiles, scope, exporter })
1053
1147
  : buildRegistryPackage({
1054
1148
  schema,
1055
1149
  foundationDir: targetDir,
1056
1150
  scope,
1057
1151
  exporter,
1058
1152
  digest,
1059
- runtime
1153
+ runtime,
1154
+ vendors: vendorFiles
1060
1155
  })
1061
1156
  } catch (err) {
1062
1157
  error(`Could not assemble the .uwx: ${err.message}`)
@@ -1084,10 +1179,15 @@ async function runRegister(args = []) {
1084
1179
  if (definedMappings.length) {
1085
1180
  log(` ${colors.dim}mappings ${standalone ? 'registered' : 'defined'}: ${definedMappings.join(', ')}${colors.reset}`)
1086
1181
  }
1182
+ const definedVendors = doc.entities.filter((e) => e.model === '@uniweb/vendor-schema').map((e) => e.name)
1183
+ if (definedVendors.length) {
1184
+ log(` ${colors.dim}compute files ${standalone ? 'registered' : 'defined'}: ${definedVendors.join(', ')}${colors.reset}`)
1185
+ }
1087
1186
  for (const lib of fromLibraries) {
1088
1187
  const taken = [
1089
1188
  lib.refs.length && `data schemas ${lib.refs.join(', ')}`,
1090
- (lib.mappings || []).length && `mappings ${lib.mappings.join(', ')}`
1189
+ (lib.mappings || []).length && `mappings ${lib.mappings.join(', ')}`,
1190
+ (lib.vendors || []).length && `compute files ${lib.vendors.join(', ')}`
1091
1191
  ].filter(Boolean).join('; ')
1092
1192
  log(
1093
1193
  ` ${colors.dim}from ${shownAt(lib.dir)}: ${taken} — ${isPreview ? 'would be registered' : 'registered'} from there first${colors.reset}`
@@ -1109,6 +1209,13 @@ async function runRegister(args = []) {
1109
1209
  log(json)
1110
1210
  log('')
1111
1211
  info(`Dry run — would submit to ${client.origin}`)
1212
+ if (definedVendors.length && !args.includes('--schema-only')) {
1213
+ log('')
1214
+ info(`Would then deliver ${definedVendors.length} compute file(s), as written:`)
1215
+ for (const e of doc.entities.filter((x) => x.model === '@uniweb/vendor-schema')) {
1216
+ log(` ${colors.dim}${e.name} ${e.size} bytes sha256 ${e.sha256}${colors.reset}`)
1217
+ }
1218
+ }
1112
1219
  if (!standalone && !args.includes('--schema-only')) {
1113
1220
  const distFiles = collectDistFiles(join(targetDir, 'dist'))
1114
1221
  log('')
@@ -1139,7 +1246,7 @@ async function runRegister(args = []) {
1139
1246
  // The libraries' types first: the registry checks a foundation's types when it takes it.
1140
1247
  const fromLibrariesSent = []
1141
1248
  for (const lib of fromLibraries) {
1142
- const sent = await registerLibraryTypes(lib, { client, exporter, at: shownAt(lib.dir) })
1249
+ const sent = await registerLibraryTypes(lib, { client, exporter, at: shownAt(lib.dir), upload: !args.includes('--schema-only') })
1143
1250
  if (!sent) {
1144
1251
  await sayWhatToRegisterFirst({ schema, defined, targetDir, client })
1145
1252
  return { exitCode: 1 }
@@ -1217,11 +1324,18 @@ async function runRegister(args = []) {
1217
1324
  if (!alreadyRegistered) {
1218
1325
  success(
1219
1326
  standalone
1220
- ? `Registered ${[defined.length && `${defined.length} data schema(s)`, definedMappings.length && `${definedMappings.length} mapping(s)`].filter(Boolean).join(' and ')}${scope ? ` under ${scope}` : ''}`
1327
+ ? `Registered ${[defined.length && `${defined.length} data schema(s)`, definedMappings.length && `${definedMappings.length} mapping(s)`, definedVendors.length && `${definedVendors.length} compute file(s)`].filter(Boolean).join(' and ')}${scope ? ` under ${scope}` : ''}`
1221
1328
  : `Registered ${registeredName}@${schema._self.version}${defined.length ? ` + ${defined.length} data schema(s)` : ''}`
1222
1329
  )
1223
1330
  }
1224
1331
 
1332
+ // ⭐ The compute files this call registered: their bytes go up now, addressed by sha256, so a
1333
+ // re-run after the foundation's 409 (no versions in it) still delivers them. --schema-only
1334
+ // skips them as it skips the code.
1335
+ if (!args.includes('--schema-only')) {
1336
+ if (!(await uploadVendorFiles(doc.entities, vendorFiles, { client }))) return { exitCode: 1 }
1337
+ }
1338
+
1225
1339
  // Phase 2 — deliver the foundation's code (plan → PUT-per-file, entry
1226
1340
  // last; contract: foundation-code-upload.md). Schemas-
1227
1341
  // only packages have no dist; --schema-only skips deliberately.
@@ -1328,29 +1442,32 @@ async function runRegister(args = []) {
1328
1442
  // shape is tolerated as a fallback. Names from doc.entities are the spine, so
1329
1443
  // the porcelain always reports WHICH names landed even if a field is absent.
1330
1444
  const minted = {}
1331
- const addMint = (e) => {
1445
+ // A compute file's id is its `artifact_uuid`; a type's and the foundation's, `payload_model_uuid`.
1446
+ const addMint = (e, idKey = 'payload_model_uuid') => {
1332
1447
  if (!e || typeof e !== 'object') return
1333
1448
  const reg = e.registered ?? e
1334
1449
  if (reg.name)
1335
1450
  minted[reg.name] = {
1336
- uuid: reg.payload_model_uuid ?? null,
1451
+ uuid: reg[idKey] ?? null,
1337
1452
  version: reg.version ?? null,
1338
1453
  unchanged: e.unchanged === true
1339
1454
  }
1340
1455
  }
1341
1456
  if (parsedBody && typeof parsedBody === 'object') {
1342
1457
  if (Array.isArray(parsedBody.data_schemas))
1343
- parsedBody.data_schemas.forEach(addMint)
1458
+ parsedBody.data_schemas.forEach((e) => addMint(e))
1459
+ if (Array.isArray(parsedBody.vendors)) parsedBody.vendors.forEach((e) => addMint(e, 'artifact_uuid'))
1344
1460
  if (parsedBody.foundation_schema) addMint(parsedBody.foundation_schema)
1345
1461
  }
1346
1462
  for (const sent of fromLibrariesSent) {
1347
- if (Array.isArray(sent.body?.data_schemas)) sent.body.data_schemas.forEach(addMint)
1463
+ if (Array.isArray(sent.body?.data_schemas)) sent.body.data_schemas.forEach((e) => addMint(e))
1464
+ if (Array.isArray(sent.body?.vendors)) sent.body.vendors.forEach((e) => addMint(e, 'artifact_uuid'))
1348
1465
  }
1349
1466
  const names = [
1350
1467
  // A library's types, registered first (and none for one registered by its own scope's members).
1351
1468
  ...fromLibrariesSent.flatMap((sent) => sent.names),
1352
1469
  ...doc.entities
1353
- .filter((e) => e.model === '@uniweb/data-schema')
1470
+ .filter((e) => e.model === '@uniweb/data-schema' || e.model === '@uniweb/vendor-schema')
1354
1471
  .map((e) => e.name),
1355
1472
  // The foundation-schema entity carries its `@scope/name` under `info`, not a
1356
1473
  // top-level `name` (that's the foundation-schema shape).
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "generatedAt": "2026-11-12T02:19:05.439Z",
3
+ "generatedAt": "2026-11-12T22:48:58.824Z",
4
4
  "packages": {
5
5
  "@uniweb/api": {
6
6
  "version": "1.7.0"
7
7
  },
8
8
  "@uniweb/build": {
9
- "version": "1.23.4"
9
+ "version": "1.23.6"
10
10
  },
11
11
  "@uniweb/content-reader": {
12
12
  "version": "1.5.10"
@@ -15,7 +15,7 @@
15
15
  "version": "1.3.2"
16
16
  },
17
17
  "@uniweb/core": {
18
- "version": "1.6.12"
18
+ "version": "1.6.13"
19
19
  },
20
20
  "@uniweb/frame-bridge": {
21
21
  "version": "1.0.4"
@@ -36,7 +36,7 @@
36
36
  "version": "1.2.17"
37
37
  },
38
38
  "@uniweb/runtime": {
39
- "version": "1.6.3"
39
+ "version": "1.6.5"
40
40
  },
41
41
  "@uniweb/scene": {
42
42
  "version": "1.0.1"
@@ -48,7 +48,7 @@
48
48
  "version": "1.1.3"
49
49
  },
50
50
  "@uniweb/semantic-parser": {
51
- "version": "1.13.4"
51
+ "version": "1.13.5"
52
52
  },
53
53
  "@uniweb/snapshot": {
54
54
  "version": "1.1.2"
package/src/index.js CHANGED
@@ -1066,6 +1066,13 @@ async function main() {
1066
1066
  return
1067
1067
  }
1068
1068
 
1069
+ // Handle compute command — run a compute function locally (dynamic import — depends on @uniweb/build)
1070
+ if (command === 'compute') {
1071
+ const { compute } = await importProjectCommand('./commands/compute.js')
1072
+ const result = await compute(args.slice(1))
1073
+ await exitWhenDrained(result?.exitCode ?? 0)
1074
+ }
1075
+
1069
1076
  // Handle families command — the standard section families this CLI ships with
1070
1077
  if (command === 'families') {
1071
1078
  const { families } = await import('./commands/families.js')
@@ -2289,6 +2296,33 @@ Record files keep their \`$uuid\`: it is the record's own id, not a backend's.
2289
2296
 
2290
2297
  To duplicate a project:
2291
2298
  cp -r my-site my-site-2 && cd my-site-2 && uniweb forget --all
2299
+ `,
2300
+ compute: `
2301
+ ${colors.cyan}${colors.bright}uniweb compute run${colors.reset} ${colors.dim}— Run a compute function on this machine, under the rules it runs by${colors.reset}
2302
+
2303
+ ${colors.bright}Usage:${colors.reset}
2304
+ uniweb compute run <file>#<function> --input <file.json>
2305
+ uniweb compute run <file>#<function> --input - < input.json
2306
+ uniweb compute run <file>#<function> --input <file.json> --json
2307
+
2308
+ ${colors.bright}<file>${colors.reset} is named as an integration names it, or by its path:
2309
+ courses src/compute/courses.js in a foundation, compute/courses.js in a library
2310
+ @acme/grading a library's file, found in the workspace
2311
+ src/compute/courses.js a path
2312
+
2313
+ ${colors.bright}What it enforces:${colors.reset}
2314
+ The web's globals and not Node's (no process, Buffer, require), no network
2315
+ (fetch throws), frozen built-in prototypes, a JSON object in and a JSON
2316
+ object out, each within its size. A call still running after 5 s is stopped,
2317
+ and one that takes longer than a call may where it runs is warned of.
2318
+
2319
+ A pass means the function keeps the contract. It is not the platform's
2320
+ runner. The function's console output is shown here; where it runs, it is
2321
+ discarded.
2322
+
2323
+ ${colors.bright}Output:${colors.reset}
2324
+ The answer on stdout, exit 0; or why it failed on stderr, exit 1.
2325
+ --json prints one object either way: { ok, answer | failure, warnings, wallMs, cpuMs }.
2292
2326
  `,
2293
2327
  families: `
2294
2328
  ${colors.cyan}${colors.bright}uniweb families${colors.reset} ${colors.dim}— The standard section families${colors.reset}
@@ -2456,6 +2490,7 @@ ${colors.bright}Commands:${colors.reset}
2456
2490
  inspect <path> Inspect parsed content shape of a markdown file or folder
2457
2491
  docs Generate component documentation
2458
2492
  families List the standard section families (for meta.js family:)
2493
+ compute run <f#fn> Run a compute function locally, under the rules it runs by
2459
2494
  template list List the official templates (for create --template)
2460
2495
  doctor Diagnose project configuration issues
2461
2496
  validate Check your content against your foundation's data schemas
@@ -206,6 +206,20 @@ export async function uploadSiteAssets({
206
206
  continue
207
207
  }
208
208
 
209
+ // The bytes to send: held, read from the file, or made again. A file a push prepared before
210
+ // is planned by the identity it recorded, with no bytes; when the backend no longer holds them,
211
+ // `load` prepares the file again, which must give the recorded bytes. Bytes that differ (the
212
+ // rule changed since) are `stale`, for the caller to plan as a new preparation.
213
+ let body = src.bytes
214
+ if (!body && typeof src.load === 'function') {
215
+ body = await src.load()
216
+ if (createHash('sha256').update(body).digest('hex') !== src.sha256) {
217
+ failed.push({ path: src.path, status: 0, detail: 'prepares to other bytes than recorded', stale: true })
218
+ continue
219
+ }
220
+ }
221
+ if (!body) body = readFileSync(src.diskPath)
222
+
209
223
  const headers = { ...(up.headers || {}), 'x-uniweb-sha256': src.sha256 }
210
224
  // Direct-mode PUTs are authed requests to the backend; presigned URLs are
211
225
  // self-signed, so a foreign auth header can break the SigV4 target. This is
@@ -228,7 +242,7 @@ export async function uploadSiteAssets({
228
242
  putRes = await fetchWithRetry(new URL(up.url, origin), {
229
243
  method: up.method || 'PUT',
230
244
  headers,
231
- body: src.bytes ?? readFileSync(src.diskPath)
245
+ body
232
246
  }, { timeoutMs: 120_000, retryOnStatus: isTransientStatus })
233
247
  } catch (err) {
234
248
  failed.push({ path: src.path, status: 0, detail: err.message })
@@ -392,3 +392,74 @@ export async function uploadFoundationCode({
392
392
 
393
393
  return { mode: plan.mode || 'direct', uploaded, stored, failed, verified, serveBase }
394
394
  }
395
+
396
+ /**
397
+ * Deliver one compute file — the phase after its `@uniweb/vendor-schema` artifact registered
398
+ * (`foundation/compute.js` in `@uniweb/build`). One call, then at most one PUT:
399
+ *
400
+ * POST {apiBase}/dev/registry/vendor-uploads { name, sha256, size }
401
+ * → { mode, version, present: true } already stored: nothing to send
402
+ * → { mode, version, present: false, method, url, headers } PUT the bytes there
403
+ *
404
+ * ⭐ ADDRESSED BY ITS `sha256`, NOT A VERSION. The registry finds the registered version of `name`
405
+ * holding those bytes, so a re-run after a partial upload — when the foundation's own call comes back
406
+ * `409` with no versions in it — still knows where the file goes. A file no registered version holds
407
+ * is refused `404`, and one whose `size` disagrees `422`, each with a `detail` sentence naming it.
408
+ *
409
+ * The file is sent exactly as on disk: nothing is built, so its bytes are what registered. The PUT is
410
+ * the one `uploadFoundationCode` makes — retried, `x-uniweb-sha256` on it, a bearer only in `direct`
411
+ * mode — and a stored version is never overwritten.
412
+ *
413
+ * @param {object} opts
414
+ * @param {string} opts.apiBase
415
+ * @param {string} opts.token
416
+ * @param {string} opts.name - `@scope/name`, as registered
417
+ * @param {string} opts.file - the file on disk
418
+ * @returns {Promise<{ name: string, version: number|null, uploaded: boolean, mode: string }>}
419
+ * @throws {Error} with `status`, `detail` and `code` when the call or the PUT is refused
420
+ */
421
+ export async function uploadVendorFile({ apiBase, token, name, file }) {
422
+ const bytes = readFileSync(file)
423
+ const sha256 = createHash('sha256').update(bytes).digest('hex')
424
+ const origin = apiBase.replace(/\/$/, '')
425
+ const res = await fetch(`${origin}/dev/registry/vendor-uploads`, {
426
+ method: 'POST',
427
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
428
+ body: JSON.stringify({ name, sha256, size: bytes.length })
429
+ })
430
+ if (!res.ok) throw await refusal(res, `vendor-uploads for ${name}`)
431
+ const target = await res.json()
432
+ const version = target.version ?? null
433
+ const mode = target.mode || 'direct'
434
+ if (target.present === true) return { name, version, uploaded: false, mode }
435
+ if (!target.url) {
436
+ throw Object.assign(new Error(`vendor-uploads for ${name}: the reply gave no upload URL`), { status: 0 })
437
+ }
438
+ const put = await fetchWithRetry(new URL(target.url, origin), {
439
+ method: target.method || 'PUT',
440
+ headers: {
441
+ ...(target.headers || {}),
442
+ ...(mode === 'direct' ? { Authorization: `Bearer ${token}` } : {}),
443
+ 'x-uniweb-sha256': sha256
444
+ },
445
+ body: bytes
446
+ }, { timeoutMs: 120_000, retryOnStatus: isTransientStatus })
447
+ if (!put.ok) throw await refusal(put, `uploading ${name}`)
448
+ return { name, version, uploaded: true, mode }
449
+ }
450
+
451
+ /** A refused response as an Error carrying its status and, from problem+json, `detail` and `code`. */
452
+ async function refusal(res, what) {
453
+ const body = await res.text().catch(() => '')
454
+ let problem = null
455
+ try {
456
+ problem = JSON.parse(body)
457
+ } catch {
458
+ problem = null
459
+ }
460
+ const detail = typeof problem?.detail === 'string' ? problem.detail : null
461
+ return Object.assign(
462
+ new Error(`${what}: HTTP ${res.status}${detail ? ` — ${detail}` : body ? ` — ${body.slice(0, 300)}` : ''}`),
463
+ { status: res.status, detail, code: typeof problem?.code === 'string' ? problem.code : null }
464
+ )
465
+ }