@uniweb/build 1.23.3 → 1.23.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uniweb/build",
3
- "version": "1.23.3",
3
+ "version": "1.23.4",
4
4
  "description": "Build tooling for the Uniweb Component Web Platform",
5
5
  "type": "module",
6
6
  "exports": {
@@ -60,9 +60,9 @@
60
60
  "@uniweb/projections": "~1.2.17",
61
61
  "@uniweb/content-reader": "~1.5.10",
62
62
  "@uniweb/schemas": "~1.7.4",
63
+ "@uniweb/semantic-parser": "~1.13.4",
63
64
  "@uniweb/theming": "~1.3.2",
64
- "@uniweb/content-writer": "~1.3.2",
65
- "@uniweb/semantic-parser": "~1.13.4"
65
+ "@uniweb/content-writer": "~1.3.2"
66
66
  },
67
67
  "optionalDependencies": {
68
68
  "@uniweb/runtime": "~1.6.3"
@@ -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 { checkFoundationResolution } from '../utils/foundation-resolution-check.js'
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: #foundation points to the actual package.
405
- //
406
- // ⛔ **A BARE SPECIFIER, NOT `foundationInfo.path` — and the obvious
407
- // "improvement" is measured and wrong.** We hold the resolved path right
408
- // here, and handing vite the *name* instead is what lets its node_modules
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
@@ -0,0 +1,127 @@
1
+ /**
2
+ * ⭐ A SITE READS ITS FOUNDATION FROM THE FOLDER ITS RESOLVER FOUND, WHATEVER A PACKAGE MANAGER
3
+ * INSTALLED. `#foundation` and `#foundation/<sub>` (what a site's `entry.js` imports) resolve
4
+ * through the foundation's own `exports` map, read in the directory `detectFoundationType`
5
+ * returned: `.` to its entry, `./styles` to its stylesheet. The package manager's copy of the
6
+ * foundation in `node_modules` is never read.
7
+ *
8
+ * Until 2026-11-12 the site handed Vite the foundation's NAME, so Vite found it a second time,
9
+ * through `node_modules`. Under pnpm a site's `file:` dependency on its foundation is a link only
10
+ * while site and foundation resolve the same versions of what they share; after any install that
11
+ * resolves them apart it is a copy, a snapshot of the foundation at that install. A checkout
12
+ * then built the snapshot, edits to the foundation did not reach the site, and the build said so
13
+ * only in a warning and reported success (measured on a project's six sites, 2026-11-11). A fresh
14
+ * clone stopped instead, at an entry the snapshot did not hold.
15
+ *
16
+ * Aliasing `#foundation` to the folder was measured once and failed (2026-09-01): an alias
17
+ * replaces a prefix, so `#foundation/styles` became `<folder>/styles` and skipped the exports
18
+ * map, where `./styles` names `./styles.css`. Resolving through the map keeps it.
19
+ *
20
+ * Like `library-imports.js`, which reads a library the foundation bundles from its folder too.
21
+ *
22
+ * @module @uniweb/build/site/foundation-imports
23
+ */
24
+ import { existsSync, readFileSync } from 'node:fs'
25
+ import { join } from 'node:path'
26
+
27
+ const SPECIFIER = '#foundation'
28
+
29
+ // The conditions an export target may be keyed by, in the order a site's build reads them.
30
+ const CONDITIONS = { client: ['browser', 'import', 'module', 'default'], ssr: ['node', 'import', 'module', 'default'] }
31
+
32
+ /**
33
+ * The file an `exports` map names for a subpath, relative to the package, or null when it
34
+ * names none. Handles a string map, a subpath map, condition objects, arrays of targets and
35
+ * one `*` per pattern, which is what Node reads.
36
+ *
37
+ * @param {object} pkg - the foundation's package.json
38
+ * @param {string} subpath - '.' or './<sub>'
39
+ * @param {string[]} [conditions]
40
+ * @returns {string|null}
41
+ */
42
+ export function foundationExportTarget(pkg, subpath, conditions = CONDITIONS.client) {
43
+ const { exports } = pkg
44
+ if (exports == null) {
45
+ if (subpath === '.') return pkg.main || './index.js'
46
+ return subpath
47
+ }
48
+ const map = typeof exports === 'string' || Array.isArray(exports) || !Object.keys(exports).some((k) => k.startsWith('.'))
49
+ ? { '.': exports }
50
+ : exports
51
+ if (Object.prototype.hasOwnProperty.call(map, subpath)) return pick(map[subpath], conditions)
52
+ for (const [key, target] of Object.entries(map)) {
53
+ const star = key.indexOf('*')
54
+ if (star < 0) continue
55
+ const before = key.slice(0, star)
56
+ const after = key.slice(star + 1)
57
+ if (subpath.startsWith(before) && subpath.endsWith(after) && subpath.length >= key.length - 1) {
58
+ const match = subpath.slice(before.length, subpath.length - after.length)
59
+ const picked = pick(target, conditions)
60
+ return picked == null ? null : picked.split('*').join(match)
61
+ }
62
+ }
63
+ return null
64
+ }
65
+
66
+ function pick(target, conditions) {
67
+ if (target == null) return null
68
+ if (typeof target === 'string') return target
69
+ if (Array.isArray(target)) {
70
+ for (const t of target) {
71
+ const picked = pick(t, conditions)
72
+ if (picked != null) return picked
73
+ }
74
+ return null
75
+ }
76
+ for (const condition of conditions) {
77
+ if (Object.prototype.hasOwnProperty.call(target, condition)) {
78
+ const picked = pick(target[condition], conditions)
79
+ if (picked != null) return picked
80
+ }
81
+ }
82
+ return null
83
+ }
84
+
85
+ /**
86
+ * The file `#foundation` or `#foundation/<sub>` names in a foundation's folder.
87
+ *
88
+ * @param {string} id - the specifier a site imports
89
+ * @param {string} dir - the foundation's folder, as `detectFoundationType` found it
90
+ * @param {{ ssr?: boolean }} [options]
91
+ * @returns {string|null} an absolute path, or null when `id` is not the foundation's
92
+ * @throws {Error} when the foundation's package.json names nothing for that subpath
93
+ */
94
+ export function resolveFoundationImport(id, dir, { ssr = false } = {}) {
95
+ if (id !== SPECIFIER && !id.startsWith(SPECIFIER + '/')) return null
96
+ const subpath = '.' + id.slice(SPECIFIER.length)
97
+ const pkgPath = join(dir, 'package.json')
98
+ const pkg = existsSync(pkgPath) ? JSON.parse(readFileSync(pkgPath, 'utf8')) : {}
99
+ const target = foundationExportTarget(pkg, subpath, ssr ? CONDITIONS.ssr : CONDITIONS.client)
100
+ if (target == null) {
101
+ throw new Error(
102
+ `[site] The foundation at ${dir} has no "${subpath}" in its package.json exports, so "${id}" names nothing. ` +
103
+ `A foundation made by \`uniweb create\` exports ".", "./styles", "./dist" and "./dist/styles".`,
104
+ )
105
+ }
106
+ return join(dir, target)
107
+ }
108
+
109
+ /**
110
+ * The Vite plugin a site's build and dev server read `#foundation` through, ahead of every
111
+ * other resolver.
112
+ *
113
+ * @param {string} dir - the foundation's folder, as `detectFoundationType` found it
114
+ */
115
+ export function foundationImportsPlugin(dir) {
116
+ return {
117
+ name: 'uniweb:foundation-imports',
118
+ enforce: 'pre',
119
+ resolveId(id, _importer, options) {
120
+ try {
121
+ return resolveFoundationImport(id, dir, { ssr: !!options?.ssr })
122
+ } catch (err) {
123
+ this.error(err.message)
124
+ }
125
+ },
126
+ }
127
+ }
@@ -1,195 +0,0 @@
1
- /**
2
- * Do WE and VITE agree on where the foundation is?
3
- *
4
- * ## The bug this exists for
5
- *
6
- * A site build resolves its foundation **twice, by two different mechanisms**,
7
- * and until 2026-09-01 nothing checked that they agreed:
8
- *
9
- * 1. **We resolve a PATH.** `detectFoundationType('src', siteRoot)` returns
10
- * `{ type: 'local', path: <siteRoot>/../src }`, and the
11
- * `uniweb:ensure-foundation-entry` plugin generates `_entry.generated.js`
12
- * into exactly that directory.
13
- * 2. **Vite resolves a NAME.** `site/config.js` sets
14
- * `alias['#foundation'] = foundationInfo.name` — the bare specifier — so
15
- * Vite runs its own node_modules lookup and reads that package's `main`.
16
- *
17
- * Those name the same directory only because a package manager linked
18
- * `node_modules/<name>` to the foundation. Nothing enforces it, and when it does
19
- * not hold we generate into one directory while Vite reads another.
20
- *
21
- * ## ⛔ The failure is worse when it does NOT fail
22
- *
23
- * If the directory Vite reaches has no `_entry.generated.js`, the build dies with
24
- * vite's `[commonjs--resolver] Failed to resolve entry for package "<name>"` —
25
- * opaque, but loud.
26
- *
27
- * **If it has a STALE one, nothing fails at all.** The site builds against a
28
- * different foundation than the one on disk, and reports success. A developer
29
- * editing `src/` sees their change generated into `src/_entry.generated.js` and
30
- * simply not take effect. *(Measured by the `flows` lane 2026-09-01: their
31
- * harness minted fixtures under a `node_modules` that was itself a symlink to a
32
- * seed tree, so a relative `../../src` link resolved into the seed. Every run
33
- * that mutated its foundation and then built a site had been silently building
34
- * the seed's copy — and presenting as green — for as long as the harness had
35
- * existed. The red they opened a channel about was the harmless half.)*
36
- *
37
- * ⇒ **This check is about the silent case.** An error message can only reach the
38
- * loud one; comparing the two answers reaches both.
39
- *
40
- * ## Why it compares REALPATHS and not link text
41
- *
42
- * `readlink node_modules/<name>` returning `../../src` looks healthy and proves
43
- * nothing: **a relative symlink resolves against the link's target, not its
44
- * location**, so with `node_modules` itself a link, `../../src` lands in a
45
- * different tree. Only the resolved physical path answers the question vite
46
- * actually asks. *(This module's first draft compared link text. It reported
47
- * healthy on the one tree that was broken.)*
48
- *
49
- * ## Why it does its own node_modules walk
50
- *
51
- * `createRequire(...).resolve(name)` cannot be used: in the failure case `main`
52
- * points at the missing entry, so it throws rather than telling us where it
53
- * looked. `require.resolve(name + '/package.json')` cannot either — a foundation
54
- * declares `exports: { ".": "./_entry.generated.js" }`, which gates every other
55
- * subpath, so that lookup fails on a *healthy* package.
56
- *
57
- * So we walk `node_modules` upward for the package directory, which is the part
58
- * of node resolution that locates a package before `exports` or `main` is
59
- * consulted. That is the step whose answer we need.
60
- */
61
-
62
- import { existsSync, readFileSync, realpathSync } from 'node:fs'
63
- import { dirname, join, parse } from 'node:path'
64
-
65
- /**
66
- * The directory a bare specifier's package lives in, by node's own
67
- * node_modules walk — the step that runs before `exports`/`main` are read.
68
- *
69
- * @param {string} name - the bare specifier (a foundation's package name)
70
- * @param {string} fromDir - the directory resolution starts in (the site root)
71
- * @returns {string|null} the package directory, or null if no node_modules
72
- * anywhere up the tree holds it
73
- */
74
- export function findPackageDir(name, fromDir) {
75
- let dir = fromDir
76
- const { root } = parse(fromDir)
77
- // eslint-disable-next-line no-constant-condition
78
- while (true) {
79
- const candidate = join(dir, 'node_modules', name)
80
- if (existsSync(join(candidate, 'package.json'))) return candidate
81
- if (dir === root) return null
82
- const parent = dirname(dir)
83
- if (parent === dir) return null
84
- dir = parent
85
- }
86
- }
87
-
88
- /**
89
- * Does Vite's resolution of this package land on the very file we generated?
90
- *
91
- * ⭐ **This is the question the check exists to ask.** Comparing DIRECTORIES
92
- * asked a different one and got it wrong for the most common layout there is: a
93
- * package rooted at `foundations/<x>/`, its entry generated into
94
- * `foundations/<x>/src/`, and `main` pointing there. That is two directories and
95
- * ONE file. Measured 2026-09-10 against every site of a ten-site project: the
96
- * directory check fired for six — five healthy `src/` layouts, and the single
97
- * genuine case, a pnpm `file:` dependency copied into the store, buried among
98
- * them. The entry comparison leaves exactly that one.
99
- * A warning that fires on healthy projects is the failure this module's own
100
- * header warns against.
101
- *
102
- * ⛔ **True only when the match is PROVEN** — both files exist and realpath to
103
- * one place. Any failure to resolve returns false, so the caller reports the
104
- * directory disagreement rather than silencing it: a copy with no entry, or one
105
- * carrying a stale entry of its own, is still caught.
106
- *
107
- * Follows what Vite reads for a bare specifier: `exports['.']` (a string, or its
108
- * `import`/`default` condition), else `main`, else `index.js`.
109
- */
110
- function resolvesToSameEntry(generatedEntry, packageDir) {
111
- let pkg
112
- try {
113
- pkg = JSON.parse(readFileSync(join(packageDir, 'package.json'), 'utf8'))
114
- } catch {
115
- return false
116
- }
117
- const pick = (v) =>
118
- typeof v === 'string' ? v : v && typeof v === 'object' ? pick(v.import ?? v.default) : null
119
- const exp = pkg.exports
120
- let rel = null
121
- if (typeof exp === 'string') rel = exp
122
- else if (exp && typeof exp === 'object') rel = pick('.' in exp ? exp['.'] : exp)
123
- rel ??= typeof pkg.main === 'string' ? pkg.main : null
124
- rel ??= 'index.js'
125
- try {
126
- return realpathSync(generatedEntry) === realpathSync(join(packageDir, rel))
127
- } catch {
128
- return false
129
- }
130
- }
131
-
132
- /**
133
- * Compare where we generated the foundation entry against where vite will look.
134
- *
135
- * ⭐ **Silence is deliberate when the package is not found at all.** Not every
136
- * supported layout puts the foundation in the site's `node_modules` — a
137
- * `foundations/<name>/` multi-site project may not — and a warning that fires on
138
- * a healthy project is worse than no warning, because the next person learns to
139
- * ignore it. A package we cannot locate is also a case vite will fail on by
140
- * itself, loudly. **We report only a disagreement we can actually prove**, which
141
- * makes a false positive impossible by construction.
142
- *
143
- * @param {Object} args
144
- * @param {string} args.name - the foundation's declared name (the bare specifier)
145
- * @param {string} args.generatedInto - the directory we wrote `_entry.generated.js` to
146
- * @param {string} args.siteRoot - where vite resolves the bare specifier from
147
- * @param {string} [args.generatedEntry] - the entry file we wrote; defaults to
148
- * `_entry.generated.js` inside `generatedInto`
149
- * @returns {{ ok: true } | { ok: false, ours: string, theirs: string, message: string }}
150
- */
151
- export function checkFoundationResolution({ name, generatedInto, siteRoot, generatedEntry }) {
152
- const theirsRaw = findPackageDir(name, siteRoot)
153
- if (!theirsRaw) return { ok: true }
154
-
155
- let ours, theirs
156
- try {
157
- ours = realpathSync(generatedInto)
158
- theirs = realpathSync(theirsRaw)
159
- } catch {
160
- // A path vanished between the walk and the realpath. Not a disagreement we
161
- // can prove, so it is not one we report.
162
- return { ok: true }
163
- }
164
-
165
- if (ours === theirs) return { ok: true }
166
-
167
- // Two directories are not two foundations. When the package Vite reaches
168
- // resolves to the entry file we generated, the build reads what we wrote —
169
- // the `src/` layout, where the entry sits one level below the package root.
170
- if (resolvesToSameEntry(generatedEntry ?? join(generatedInto, '_entry.generated.js'), theirsRaw)) {
171
- return { ok: true }
172
- }
173
-
174
- return {
175
- ok: false,
176
- ours,
177
- theirs,
178
- message: [
179
- `[site] ⛔ Foundation "${name}" resolves to two different directories.`,
180
- ``,
181
- ` we generated its entry into : ${ours}`,
182
- ` vite will import it from : ${theirs}`,
183
- ``,
184
- ` Your site build will use the SECOND one, so edits to the first do not`,
185
- ` take effect — and if that directory carries a stale _entry.generated.js`,
186
- ` the build SUCCEEDS against the wrong foundation.`,
187
- ``,
188
- ` This means node_modules/${name} under ${siteRoot} is not the foundation`,
189
- ` directory. Re-run your package manager's install. If you copied or moved`,
190
- ` this project, check whether node_modules (or a parent of it) is a symlink`,
191
- ` into another tree — a relative link inside one resolves against the link's`,
192
- ` target, so it can point outside this project while looking correct.`,
193
- ].join('\n'),
194
- }
195
- }