uniweb 1.30.1 → 1.31.0

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.30.1",
3
+ "version": "1.31.0",
4
4
  "description": "Create structured Vite + React sites with content/code separation",
5
5
  "type": "module",
6
6
  "bin": {
@@ -43,13 +43,13 @@
43
43
  "tar": "^7.5.21",
44
44
  "@uniweb/core": "~1.6.9",
45
45
  "@uniweb/semantic-parser": "~1.13.2",
46
- "@uniweb/schemas": "~1.6.11",
46
+ "@uniweb/schemas": "~1.7.0",
47
47
  "@uniweb/content-writer": "~1.3.1"
48
48
  },
49
49
  "peerDependencies": {
50
- "@uniweb/content-reader": "~1.5.9",
50
+ "@uniweb/build": "~1.20.0",
51
51
  "@uniweb/semantic-parser": "~1.13.2",
52
- "@uniweb/build": "~1.19.1"
52
+ "@uniweb/content-reader": "~1.5.9"
53
53
  },
54
54
  "peerDependenciesMeta": {
55
55
  "@uniweb/build": {
@@ -136,7 +136,7 @@ data: {
136
136
 
137
137
  `single`/`whole` are refused over a schema whose root is a list (`@std/nav`, `@std/form`). A `whole` key its source cannot answer whole is `null`. An optional `schemas.config.js` routes a scope to a folder: `export default { '@acme': '../shared/acme-schemas' }` — a routed scope wins, has no package fallback, and `@/`/`@uniweb` are never routable. Worked examples: `development/schemas-in-practice.md`.
138
138
 
139
- **Any foundation can use any registered data schema, by its full name** — `data: { members: '@acme/member' }`, `schema: '@acme/member'` in `queries.yml`. A scope is a namespace that keeps names from colliding, not a limit on who uses a type. So a type another foundation registers is named, never copied: a copy of its file is a second definition of the same type, which `doctor` points out (`type-defined-twice`). A register names such a type and sends no definition of it. A local build still needs the file: `schemas.config.js` routes that type, `'@acme/member': '../hub/src/schemas/member.yml'`, or its scope's folder. A site's records of it sit in `records/acme/member/`; in `records/member/` they'd be the foundation's own `@/member`.
139
+ **Any foundation can use a data schema another defines, by its full name** — `data: { members: '@acme/member' }`, `schema: '@acme/member'` in `queries.yml`. No backend is involved, and in a workspace nothing to configure: a local build, `uniweb dev` included, reads the type from the foundation whose name gives the `@acme` scope and whose own `schemas/` defines it. Two packages of the workspace defining it stop the build, naming both. A type outside the workspace comes from `schemas.config.js` (`'@acme/member': '../elsewhere/member.yml'`, or the scope's folder), which wins over the workspace, or an installed `@acme/schemas` package. A scope is a namespace that keeps names from colliding, not a limit on who uses a type. So a type another foundation defines is named, never copied: a copy of its file is a second definition of the same type, which `doctor` points out where the two foundations' names give one scope (`type-defined-twice`). Registering, which only a site with a backend does, names such a type and sends no definition of it. A site can hold another site's records of a type too: `paths: { 'records/acme/member': '../../hub/site/records/acme/member' }` in its `site.yml` reads them as its own, a push adds them by reference rather than as copies once their own site has pushed them, and a pull leaves those files alone. A site's records of it sit in `records/acme/member/`; in `records/member/` they'd be the foundation's own `@/member`.
140
140
 
141
141
  ```jsx
142
142
  function Article({ content, block }) { // data: { article: { schema: '@std/article', single: true } }
@@ -73,7 +73,7 @@ Things you won't discover from exports:
73
73
  - **A reader can open a picture larger.** `components={{ image: EnlargeableImage }}` does it for an image in a page's body, and `Mermaid` does it on its own (`enlarge={false}` turns it off). `<Enlargeable>` goes around a picture a section draws itself. It's offered only when opening shows the picture noticeably larger, and the prerendered page doesn't change.
74
74
  - **Kit brings no words.** What a reader or a screen reader meets comes from your foundation, so `Media` takes `playLabel`, `Asset` `downloadLabel`, `Disclaimer` `closeLabel` (it has a button at its foot only with one), `Prose` `footnoteBackLabel` and `DataPlaceholder` `label`. Without one it uses what the author wrote, a role or a symbol: a play button with no caption or alt is named `▶`. `<Link>`'s own tooltip is only a social service's name, an address or a number, so a link holding only an icon needs a `title` or `aria-label` from you. Words your own section draws are content: *A section's own words*, below.
75
75
  - **A word wider than its box breaks**, so a long heading can't pan a phone's page (`overflow-wrap: break-word`, in kit's base). What must stay whole in a narrow box says `whitespace-nowrap`: a big numeral, a figure, a number with its unit. Without it, `10 min` in a tight box comes out as `10 mi / n`.
76
- - **Headings balance their lines and a paragraph's last line keeps company**, inside prose and out (`text-wrap: balance` on `h1`–`h6`, `pretty` on `p`, in kit's base, at no weight). A `text-wrap` or `text-*` class of your own wins; don't write the default again.
76
+ - **Headings balance their lines and a paragraph's last line keeps company**, inside prose and out (`text-wrap-style: balance` on `h1`–`h6`, `pretty` on `p`, in kit's base, at no weight). It sets only the style, so text in a `whitespace-nowrap` box stays on one line. A `text-wrap` or `text-*` class of your own wins; don't write the default again.
77
77
  - **Kit hooks are SSR-safe.** "document is not defined" → use the hook, don't add guards.
78
78
  - **`cn()` drops an earlier `leading-*` when a `text-<size>` follows**, since Tailwind's size classes set line height too: `cn('leading-[1.1] text-4xl')` → `text-4xl`. Put the size first, or fold the leading into it (`text-[clamp(2rem,5vw,4rem)]/[1.1]`).
79
79
  - **"3 of 12 pages didn't render"** means the build stopped, exit 1, because a section threw while rendering a page, and `dist/` isn't complete. It names the error, the section type and the pages. A section that only fails here reads something only a browser has; `uniweb dev` won't show that one.
@@ -1432,15 +1432,24 @@ export function writeHeldTypes(siteDir, backend, folderDoc) {
1432
1432
  * The backend keeps them, in no folder, until they are deleted (`utils/retired-records.js`). A
1433
1433
  * retired record placed again (a move undone) is dropped from the list.
1434
1434
  *
1435
+ * ⭐ ONLY THIS COPY'S OWN RECORDS. A record of another site's directory, mounted here
1436
+ * (`site.yml::paths`), is placed by reference to the entity its owner's push made. This copy never
1437
+ * sent it, and a pull leaves its file to the owner, so the `records` map, which every push and pull
1438
+ * writes for the records they carry, never holds it. Leaving the folder, it is the owner's to
1439
+ * retire. ⛔ Until 2026-11-08 it was retired here too, and one uuid the caller may not administer
1440
+ * refuses the whole delete before anything is deleted [backend, 2026-11-08].
1441
+ *
1435
1442
  * ⚠️ Nothing is known before a copy first banks its types, so a copy banked before 2026-11-04
1436
1443
  * retires nothing on its first push after that.
1437
1444
  *
1438
1445
  * @returns {string[]} the uuids this push retired
1439
1446
  */
1440
1447
  export function retireUnplaced(siteDir, backend, { before, after }) {
1441
- const prior = readBackendState(siteDir, backend).retired || {}
1448
+ const state = readBackendState(siteDir, backend)
1449
+ const prior = state.retired || {}
1450
+ const own = new Set(Object.values(state.records || {}))
1442
1451
  const now = Object.fromEntries(Object.entries(prior).filter(([uuid]) => !(uuid in after)))
1443
- const retired = Object.keys(before).filter((uuid) => !(uuid in after))
1452
+ const retired = Object.keys(before).filter((uuid) => !(uuid in after) && own.has(uuid))
1444
1453
  for (const uuid of retired) now[uuid] = before[uuid]
1445
1454
  setBackendMap(siteDir, backend, 'retired', now)
1446
1455
  return retired
@@ -1685,7 +1685,9 @@ export function checkGeneratedDataDir({ sitePath, siteName, siteYml, issues, sho
1685
1685
  /**
1686
1686
  * ⭐ WHAT DOCTOR CHECKS IS WHERE YOU STAND, by the rule `dev` and `status` read the folder you stand in
1687
1687
  * (`pick-site.js::siteAround`): in a site, that site and what it is built from, its foundation and its
1688
- * extensions; in a foundation with no site around it, that foundation; elsewhere, the whole workspace.
1688
+ * extensions; in a foundation, the site beside it when that site is built from it, else that foundation;
1689
+ * elsewhere, the whole workspace. ⛔ Until 2026-11-08 the site beside a foundation was checked whatever
1690
+ * it was built from, so in `shop/src` beside a site on another foundation, nothing checked `shop/src`.
1689
1691
  * ⛔ Until 2026-11-08 only the sites were narrowed: run in one site, doctor reported on every foundation
1690
1692
  * in the workspace before the site's own checks, which were hard to find among them.
1691
1693
  *
@@ -1693,20 +1695,24 @@ export function checkGeneratedDataDir({ sitePath, siteName, siteYml, issues, sho
1693
1695
  * null for the whole workspace
1694
1696
  */
1695
1697
  export function doctorFocus({ workspaceDir, projectDir, allSites, foundations, extensions }) {
1696
- const here = siteAround(allSites.map((s) => relative(workspaceDir, s.path)), workspaceDir, projectDir)
1697
- if (here) {
1698
- const site = allSites.find((s) => relative(workspaceDir, s.path) === here)
1699
- const used = siteBuiltFrom(site.path)
1700
- const isUsed = (f) => used.has(realOf(f.path))
1701
- return { site, sites: [site], foundations: foundations.filter(isUsed), extensions: extensions.filter(isUsed) }
1702
- }
1703
1698
  const inside = (dir) => {
1704
1699
  const rel = relative(dir, projectDir)
1705
1700
  return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel))
1706
1701
  }
1707
1702
  const foundation = foundations.find((f) => inside(f.path))
1708
1703
  const extension = extensions.find((e) => inside(e.path))
1709
- if (!foundation && !extension) return null
1704
+ const standingIn = foundation || extension
1705
+ const here = siteAround(allSites.map((s) => relative(workspaceDir, s.path)), workspaceDir, projectDir)
1706
+ if (here) {
1707
+ const site = allSites.find((s) => relative(workspaceDir, s.path) === here)
1708
+ const used = siteBuiltFrom(site.path)
1709
+ // In a foundation the site beside it isn't built from, you mean the foundation.
1710
+ if (!standingIn || used.has(realOf(standingIn.path))) {
1711
+ const isUsed = (f) => used.has(realOf(f.path))
1712
+ return { site, sites: [site], foundations: foundations.filter(isUsed), extensions: extensions.filter(isUsed) }
1713
+ }
1714
+ }
1715
+ if (!standingIn) return null
1710
1716
  return {
1711
1717
  foundation: foundation || extension,
1712
1718
  sites: [],
@@ -1747,8 +1753,8 @@ export async function checkTypesDefinedTwice({ workspaceDir, checkedDirs, issues
1747
1753
  info(`[${id}] ${t.ref} is defined in ${t.files.length} places${t.differ ? ', and they differ' : ''}`)
1748
1754
  for (const f of t.files) log(` ${relative(workspaceDir, f)}`)
1749
1755
  log(
1750
- ` A registered data schema is usable by any foundation by its full name, so keep one definition and name ` +
1751
- `it in full in the others (${colors.green}${t.ref}${colors.reset}); schemas.config.js gives a local build its file.`
1756
+ ` Any foundation can use a data schema by its full name, so keep one definition and name it in full in the ` +
1757
+ `others (${colors.green}${t.ref}${colors.reset}): in this workspace their build finds its file, with nothing to configure.`
1752
1758
  )
1753
1759
  }
1754
1760
  }
@@ -2183,7 +2189,8 @@ async function runDoctor(args = []) {
2183
2189
  })
2184
2190
  }
2185
2191
 
2186
- // One name in a scope is one type: each defined by two packages here, among those checked.
2192
+ // A data schema two packages here each keep a file for, among those checked: one full name is one
2193
+ // type, so the second file is a copy.
2187
2194
  await checkTypesDefinedTwice({
2188
2195
  workspaceDir,
2189
2196
  checkedDirs: focus ? [...checkedFoundations, ...checkedExtensions].map((f) => f.path) : null,
@@ -2455,8 +2462,8 @@ async function runDoctor(args = []) {
2455
2462
  }
2456
2463
  }
2457
2464
 
2458
- // Check extensions
2459
- for (const ext of extensions) {
2465
+ // Check extensions: those `doctorFocus` chose, as with the foundations above.
2466
+ for (const ext of checkedExtensions) {
2460
2467
  log('')
2461
2468
  info(`Checking extension: ${ext.name}`)
2462
2469
 
@@ -1350,6 +1350,11 @@ export async function pull(args = [], deps = {}) {
1350
1350
  removed.push(resolve(projDir, report.recordsFile))
1351
1351
  }
1352
1352
  records += report.placed.length + report.updated.length
1353
+ // ⭐ Another site's records, mounted (`site.yml::paths`): read where they are, and left as the
1354
+ // owner's files hold them, since a pull of this site writes nothing there.
1355
+ if (report.leftToOwner?.length) {
1356
+ note(` ${report.leftToOwner.length} record(s) are mounted from another site (site.yml paths:) and left as its files hold them`)
1357
+ }
1353
1358
  // ⭐ A FILE RECORD'S BYTES (`@uniweb/file`, 2026-09-28): fetched to where `folder.yml` now
1354
1359
  // places each one, as media are fetched. A file that did not arrive is a record not taken —
1355
1360
  // reported, and the pull fails below as it does for any, so the next one fetches it again.
@@ -1379,7 +1384,7 @@ export async function pull(args = [], deps = {}) {
1379
1384
  if (report.skipped.length) {
1380
1385
  recordsNotPlaced = describeUnplacedRecords({
1381
1386
  docs: folderLane.docs,
1382
- taken: report.placed.length + report.updated.length + report.unchanged.length,
1387
+ taken: report.placed.length + report.updated.length + report.unchanged.length + (report.leftToOwner?.length || 0),
1383
1388
  skipped: report.skipped
1384
1389
  })
1385
1390
  error(recordsNotPlaced.headline)
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "generatedAt": "2026-11-09T01:10:38.607Z",
3
+ "generatedAt": "2026-11-09T18:42:57.806Z",
4
4
  "packages": {
5
5
  "@uniweb/api": {
6
- "version": "1.6.9"
6
+ "version": "1.6.10"
7
7
  },
8
8
  "@uniweb/build": {
9
- "version": "1.19.1"
9
+ "version": "1.20.0"
10
10
  },
11
11
  "@uniweb/content-reader": {
12
12
  "version": "1.5.9"
@@ -24,7 +24,7 @@
24
24
  "version": "1.0.8"
25
25
  },
26
26
  "@uniweb/kit": {
27
- "version": "1.7.16"
27
+ "version": "1.7.18"
28
28
  },
29
29
  "@uniweb/loom": {
30
30
  "version": "1.1.3"
@@ -42,7 +42,7 @@
42
42
  "version": "1.0.1"
43
43
  },
44
44
  "@uniweb/schemas": {
45
- "version": "1.6.11"
45
+ "version": "1.7.0"
46
46
  },
47
47
  "@uniweb/scholar": {
48
48
  "version": "1.1.0"
@@ -60,7 +60,7 @@
60
60
  "version": "1.3.2"
61
61
  },
62
62
  "@uniweb/unipress": {
63
- "version": "1.1.36"
63
+ "version": "1.1.37"
64
64
  }
65
65
  },
66
66
  "templates": {
@@ -434,8 +434,18 @@ export async function updateRootScripts(rootDir, sites, pm = 'pnpm') {
434
434
  const newScripts = computeRootScripts(runs ? [runs, ...unique.filter((s) => s !== runs)] : unique, pm)
435
435
  const previewIsCli = /^(pnpm --filter \S+ (run )?preview|npm -w \S+ run preview)$/.test(scripts.preview ?? '')
436
436
  if (scripts.preview && !runs && !previewIsCli) delete newScripts.preview
437
- // Nor is a script the workspace already has for a site added again under another name.
438
- const held = new Set(Object.values(scripts))
437
+ // A per-site script under a name the CLI gives the site it runs (its package's, its project's), or
438
+ // one for a site that is gone, is the CLI's own, and regenerated below. One under another name is
439
+ // the person's, for a command the CLI writes too.
440
+ const cliNamed = (key, value) => {
441
+ const m = /^(dev|preview):(.+)$/.exec(key)
442
+ const target = m && cliScriptTarget(value)
443
+ if (!target) return false
444
+ const s = unique.find((o) => isSite(o, target))
445
+ return !s || m[2] === target || m[2] === s.name || m[2] === siteScriptName(s)
446
+ }
447
+ // Nor is a script the workspace already has under a name of the person's added again under another.
448
+ const held = new Set(Object.entries(scripts).filter(([k, v]) => !cliNamed(k, v)).map(([, v]) => v))
439
449
  for (const [key, command] of Object.entries(newScripts)) {
440
450
  if (!(key in scripts) && held.has(command)) delete newScripts[key]
441
451
  }
@@ -450,16 +460,15 @@ export async function updateRootScripts(rootDir, sites, pm = 'pnpm') {
450
460
  }
451
461
  }
452
462
 
453
- // ⭐ The per-site scripts this CLI writes are regenerated from the sites there are
454
- // now, and one it wrote for a site that is gone — renamed, moved, removed — goes.
455
- // A script whose command is not one the CLI writes is the user's, and stays. Known by its
456
- // command, since a project's site goes by the project's name (`siteScriptName`).
457
- // ⛔ Until 2026-10-13 they were only ever added: after `rename site blog journal`,
458
- // `dev:blog` still ran `uniweb dev blog`, a site that no longer existed.
463
+ // ⭐ The per-site scripts this CLI writes are regenerated from the sites there are now: one of
464
+ // its own the regenerated set doesn't hold goes — its site renamed, moved or removed, or the site's
465
+ // scripts named or run another way now (by its project's name; under npm, by its folder). A script
466
+ // under the person's own name for a command, or whose command the CLI doesn't write, stays.
467
+ // ⛔ Until 2026-10-13 they were only ever added: after `rename site blog journal`, `dev:blog`
468
+ // still ran `uniweb dev blog`. ⛔ In 1.30.0 and 1.30.1 only a gone site's went, so a
469
+ // renamed project kept its old pair beside the new one.
459
470
  for (const [key, value] of Object.entries(scripts)) {
460
- if (key in newScripts || !/^(dev|preview):./.test(key)) continue
461
- const target = cliScriptTarget(value)
462
- if (target && !unique.some((s) => isSite(s, target))) delete scripts[key]
471
+ if (!(key in newScripts) && cliNamed(key, value)) delete scripts[key]
463
472
  }
464
473
 
465
474
  pkg.scripts = { ...scripts, ...newScripts }
@@ -25,15 +25,24 @@
25
25
  // and every other key, `onlyBuiltDependencies` and `allowBuilds` among them.
26
26
  //
27
27
  // Node built-ins, js-yaml and Handlebars only: the CLI's startup path reaches this
28
- // module (`utils/workspace.js`), before any project is installed.
28
+ // module (`utils/workspace.js`), before any project is installed. ⭐ The reading half is
29
+ // `./workspace-patterns.js`, mirrored byte for byte in `@uniweb/build`, which reads the same
30
+ // rule; this module keeps the writing and re-exports the reading.
29
31
 
30
- import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
32
+ import { readFileSync } from 'node:fs'
31
33
  import { dirname, join } from 'node:path'
32
34
  import { fileURLToPath } from 'node:url'
33
35
  import yaml from 'js-yaml'
34
36
  import Handlebars from 'handlebars'
37
+ import { WORKSPACE_FILE, strings } from './workspace-patterns.js'
35
38
 
36
- export const WORKSPACE_FILE = 'pnpm-workspace.yaml'
39
+ export {
40
+ WORKSPACE_FILE,
41
+ readWorkspacePatterns,
42
+ workspacePackages,
43
+ resolveWorkspacePackages,
44
+ patternsCover,
45
+ } from './workspace-patterns.js'
37
46
 
38
47
  const TEMPLATE = join(
39
48
  dirname(fileURLToPath(import.meta.url)),
@@ -44,88 +53,6 @@ const TEMPLATE = join(
44
53
  `${WORKSPACE_FILE}.hbs`
45
54
  )
46
55
 
47
- // ─── Reading ────────────────────────────────────────────────────────────────
48
-
49
- /**
50
- * The package patterns a workspace declares, and the file they are read from:
51
- * pnpm-workspace.yaml when the workspace has one, else package.json's `workspaces`.
52
- *
53
- * @param {string} rootDir
54
- * @returns {{ source: string|null, patterns: string[] }}
55
- */
56
- export function readWorkspacePatterns(rootDir) {
57
- const ymlPath = join(rootDir, WORKSPACE_FILE)
58
- if (existsSync(ymlPath)) {
59
- const doc = yaml.load(readFileSync(ymlPath, 'utf8'))
60
- return { source: WORKSPACE_FILE, patterns: strings(doc?.packages) }
61
- }
62
- try {
63
- const pkg = JSON.parse(readFileSync(join(rootDir, 'package.json'), 'utf8'))
64
- if (Array.isArray(pkg.workspaces)) return { source: 'package.json', patterns: strings(pkg.workspaces) }
65
- } catch {
66
- // No package.json, or not JSON — a workspace with no packages declared.
67
- }
68
- return { source: null, patterns: [] }
69
- }
70
-
71
- /**
72
- * The workspace's packages: the folders its patterns name.
73
- *
74
- * @param {string} rootDir
75
- * @returns {string[]} see {@link resolveWorkspacePackages}
76
- */
77
- export function workspacePackages(rootDir) {
78
- return resolveWorkspacePackages(rootDir, readWorkspacePatterns(rootDir).patterns)
79
- }
80
-
81
- /**
82
- * The folders `patterns` name under `rootDir`, as workspace-relative paths in `/`
83
- * form, each once, in the order of the first pattern that names it — alphabetical
84
- * within a pattern. A folder a wildcard finds counts only when it holds a
85
- * package.json; one a pattern names by its own path counts if it exists.
86
- *
87
- * @param {string} rootDir
88
- * @param {string[]} patterns
89
- * @returns {string[]}
90
- */
91
- export function resolveWorkspacePackages(rootDir, patterns) {
92
- const { include, exclude } = parsePatterns(patterns)
93
- const seen = new Set()
94
- const out = []
95
- for (const pattern of include) {
96
- const byWildcard = pattern.some((segment) => segment === '**' || hasMagic(segment))
97
- for (const rel of expand(rootDir, pattern, [], 0, [])) {
98
- // The root is the workspace itself, never one of its packages.
99
- if (!rel || seen.has(rel)) continue
100
- if (byWildcard && !existsSync(join(rootDir, rel, 'package.json'))) continue
101
- if (exclude.some((ex) => matches(ex, rel.split('/')))) continue
102
- seen.add(rel)
103
- out.push(rel)
104
- }
105
- }
106
- return out
107
- }
108
-
109
- /**
110
- * Do `patterns` cover the folder at `relPath` — would it be one of the workspace's
111
- * packages? Answered from the patterns alone, so it holds for a folder about to be
112
- * created.
113
- *
114
- * @param {string[]} patterns
115
- * @param {string} relPath - workspace-relative
116
- * @returns {boolean}
117
- */
118
- export function patternsCover(patterns, relPath) {
119
- const path = normalizePath(relPath)
120
- if (!path) return false
121
- const segments = path.split('/')
122
- const { include, exclude } = parsePatterns(patterns)
123
- return (
124
- include.some((p) => matches(p, segments)) &&
125
- !exclude.some((p) => matches(p, segments))
126
- )
127
- }
128
-
129
56
  // ─── Writing ────────────────────────────────────────────────────────────────
130
57
 
131
58
  /**
@@ -178,159 +105,6 @@ export function editWorkspaceFilePackages(text, edit) {
178
105
  return out
179
106
  }
180
107
 
181
- // ─── Patterns ───────────────────────────────────────────────────────────────
182
-
183
- // `@(…)`, `+(…)`, `!(…)`, `*(…)`, `?(…)` — extended globs, which this does not read.
184
- const EXTGLOB = /[@+!*?]\(/
185
- const warned = new Set()
186
-
187
- /** Positive and negative patterns as folder-name lists, `{a,b}` expanded. */
188
- function parsePatterns(patterns) {
189
- const include = []
190
- const exclude = []
191
- for (const raw of strings(patterns)) {
192
- let pattern = raw.trim()
193
- const negated = pattern.startsWith('!')
194
- if (negated) pattern = pattern.slice(1)
195
- if (EXTGLOB.test(pattern)) {
196
- if (!warned.has(raw)) {
197
- warned.add(raw)
198
- process.stderr.write(
199
- `⚠ uniweb does not read the workspace pattern "${raw}" (extended glob syntax) — ` +
200
- `list the folders it stands for instead.\n`
201
- )
202
- }
203
- continue
204
- }
205
- for (const one of expandBraces(pattern)) {
206
- const path = normalizePath(one)
207
- if (path) (negated ? exclude : include).push(path.split('/'))
208
- }
209
- }
210
- return { include, exclude }
211
- }
212
-
213
- /** `a/{b,c}/d` → `a/b/d`, `a/c/d`; nested lists expand innermost first. */
214
- function expandBraces(pattern) {
215
- const m = /\{([^{}]*)\}/.exec(pattern)
216
- if (!m) return [pattern]
217
- const options = m[1].split(',')
218
- // `{x}` lists nothing to choose between: a literal brace, as in pnpm.
219
- if (options.length < 2) return [pattern]
220
- const head = pattern.slice(0, m.index)
221
- const tail = pattern.slice(m.index + m[0].length)
222
- return options.flatMap((o) => expandBraces(head + o + tail))
223
- }
224
-
225
- /** `./a//b/` → `a/b`; `\` becomes `/`; `.` and `` are the root. */
226
- function normalizePath(path) {
227
- let s = String(path).replace(/\\/g, '/').replace(/\/{2,}/g, '/')
228
- while (s.startsWith('./')) s = s.slice(2)
229
- s = s.replace(/^\/+/, '').replace(/\/+$/, '')
230
- return s === '.' ? '' : s
231
- }
232
-
233
- const hasMagic = (segment) => /[*?[]/.test(segment)
234
-
235
- /** Can a wildcard step into this folder? Never `node_modules`, never a dot-folder. */
236
- const wildcardMayEnter = (name) => !name.startsWith('.') && name !== 'node_modules'
237
-
238
- const regexCache = new Map()
239
-
240
- /** One folder-name pattern as a regex: `*`, `?` and `[...]`, everything else literal. */
241
- function segmentRegex(segment) {
242
- let re = regexCache.get(segment)
243
- if (re) return re
244
- let src = ''
245
- for (let i = 0; i < segment.length; i++) {
246
- const c = segment[i]
247
- if (c === '*') src += '[^/]*'
248
- else if (c === '?') src += '[^/]'
249
- else if (c === '[' && segment.indexOf(']', i + 2) > i) {
250
- const end = segment.indexOf(']', i + 2)
251
- let body = segment.slice(i + 1, end).replace(/\\/g, '\\\\')
252
- if (body.startsWith('!')) body = `^${body.slice(1)}`
253
- src += `[${body}]`
254
- i = end
255
- } else src += c.replace(/[.+^$(){}|\\[\]]/g, '\\$&')
256
- }
257
- re = new RegExp(`^${src}$`)
258
- regexCache.set(segment, re)
259
- return re
260
- }
261
-
262
- function segmentMatches(segment, name) {
263
- if (!hasMagic(segment)) return segment === name
264
- // A wildcard does not match a dot-folder unless the pattern spells the dot.
265
- if (name.startsWith('.') && !segment.startsWith('.')) return false
266
- if (name === 'node_modules') return false
267
- return segmentRegex(segment).test(name)
268
- }
269
-
270
- /** Does the folder-name list `path` match the pattern `pattern`? `**` is any depth. */
271
- function matches(pattern, path, i = 0, j = 0) {
272
- if (i === pattern.length) return j === path.length
273
- if (pattern[i] === '**') {
274
- for (let k = j; k <= path.length; k++) {
275
- if (k > j && !wildcardMayEnter(path[k - 1])) break
276
- if (matches(pattern, path, i + 1, k)) return true
277
- }
278
- return false
279
- }
280
- if (j === path.length || !segmentMatches(pattern[i], path[j])) return false
281
- return matches(pattern, path, i + 1, j + 1)
282
- }
283
-
284
- /** The folders under `rootDir` that `pattern` names, found on disk. */
285
- function expand(rootDir, pattern, base, i, out) {
286
- if (i === pattern.length) {
287
- out.push(base.join('/'))
288
- return out
289
- }
290
- const segment = pattern[i]
291
- const here = join(rootDir, ...base)
292
- if (segment === '**') {
293
- expand(rootDir, pattern, base, i + 1, out)
294
- // Real folders only: a symlink back up the tree would never end.
295
- for (const name of subfolders(here, { followLinks: false })) {
296
- if (wildcardMayEnter(name)) expand(rootDir, pattern, [...base, name], i, out)
297
- }
298
- return out
299
- }
300
- if (!hasMagic(segment)) {
301
- if (segment === '.') return expand(rootDir, pattern, base, i + 1, out)
302
- if (isFolder(join(here, segment))) expand(rootDir, pattern, [...base, segment], i + 1, out)
303
- return out
304
- }
305
- for (const name of subfolders(here)) {
306
- if (segmentMatches(segment, name)) expand(rootDir, pattern, [...base, name], i + 1, out)
307
- }
308
- return out
309
- }
310
-
311
- function subfolders(dir, { followLinks = true } = {}) {
312
- let entries
313
- try {
314
- entries = readdirSync(dir, { withFileTypes: true })
315
- } catch {
316
- return []
317
- }
318
- return entries
319
- .filter(
320
- (e) => e.isDirectory() || (followLinks && e.isSymbolicLink() && isFolder(join(dir, e.name)))
321
- )
322
- .map((e) => e.name)
323
- .sort()
324
- }
325
-
326
- function isFolder(path) {
327
- try {
328
- return statSync(path).isDirectory()
329
- } catch {
330
- return false
331
- }
332
- }
333
-
334
108
  // ─── The `packages:` list, as text ──────────────────────────────────────────
335
109
 
336
110
  /**
@@ -422,10 +196,6 @@ function formatEntry(value, quote) {
422
196
 
423
197
  // ─── Helpers ────────────────────────────────────────────────────────────────
424
198
 
425
- function strings(list) {
426
- return Array.isArray(list) ? list.filter((v) => typeof v === 'string') : []
427
- }
428
-
429
199
  function sameValue(a, b) {
430
200
  return JSON.stringify(a) === JSON.stringify(b)
431
201
  }
@@ -0,0 +1,272 @@
1
+ // THE WORKSPACE'S PACKAGES, READ AS PNPM READS THEM: the reading half of the CLI's
2
+ // `utils/workspace-packages.js`, in a module of its own, so that `@uniweb/build` holds the same rule
3
+ // without either package importing the other.
4
+ //
5
+ // ⛔ THIS FILE IS MIRRORED, BYTE FOR BYTE: `framework/cli/src/utils/workspace-patterns.js` and
6
+ // `framework/build/src/workspace-patterns.js`. The CLI's startup path reads it before any project,
7
+ // and so any `@uniweb/build`, is installed; the build reads it to find a data schema another package
8
+ // of the workspace defines (`foundation/shared-types.js`). Edit one and copy it over the other:
9
+ // `_contracts/workspace-patterns-mirror.test.js` fails until they match.
10
+ //
11
+ // A workspace lists its packages as folder patterns: `packages:` in pnpm-workspace.yaml, or
12
+ // `workspaces` in package.json for npm and yarn. Patterns are read as pnpm reads them: `*`, `?` and
13
+ // `[...]` within one folder name, `**` for any depth, `{a,b}` for alternatives, and a leading `!` to
14
+ // exclude what the other patterns match. A folder a wildcard finds counts when it holds a
15
+ // package.json, as pnpm counts it — so `**` never sweeps in a `pages/` or `dist/` folder — and a
16
+ // wildcard never enters `node_modules` or a dot-folder. A folder listed by its own path counts if it
17
+ // exists: listing it says it is one, and a command that reads content only (`validate`) works on a
18
+ // folder with no manifest yet. Any other syntax is refused by name, never read as a path.
19
+ //
20
+ // Node built-ins and js-yaml only.
21
+
22
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
23
+ import { join } from 'node:path'
24
+ import yaml from 'js-yaml'
25
+
26
+ export const WORKSPACE_FILE = 'pnpm-workspace.yaml'
27
+
28
+ // Read as the build reads YAML (`build/src/utils/yaml-schema.js`): js-yaml's types without the
29
+ // implicit timestamp, so a folder named like a date, `packages: [2025-06-01]`, stays its name instead
30
+ // of becoming a Date that the list then drops. Restated here, since this file imports only js-yaml.
31
+ const YAML_OPTIONS = Object.freeze({ schema: yaml.CORE_SCHEMA.extend({ implicit: [yaml.types.merge] }) })
32
+
33
+ // ─── Reading ────────────────────────────────────────────────────────────────
34
+
35
+ /**
36
+ * The package patterns a workspace declares, and the file they are read from:
37
+ * pnpm-workspace.yaml when the workspace has one, else package.json's `workspaces`.
38
+ *
39
+ * @param {string} rootDir
40
+ * @returns {{ source: string|null, patterns: string[] }}
41
+ */
42
+ export function readWorkspacePatterns(rootDir) {
43
+ const ymlPath = join(rootDir, WORKSPACE_FILE)
44
+ if (existsSync(ymlPath)) {
45
+ const doc = yaml.load(readFileSync(ymlPath, 'utf8'), YAML_OPTIONS)
46
+ return { source: WORKSPACE_FILE, patterns: strings(doc?.packages) }
47
+ }
48
+ try {
49
+ const pkg = JSON.parse(readFileSync(join(rootDir, 'package.json'), 'utf8'))
50
+ if (Array.isArray(pkg.workspaces)) return { source: 'package.json', patterns: strings(pkg.workspaces) }
51
+ } catch {
52
+ // No package.json, or not JSON — a workspace with no packages declared.
53
+ }
54
+ return { source: null, patterns: [] }
55
+ }
56
+
57
+ /**
58
+ * The workspace's packages: the folders its patterns name.
59
+ *
60
+ * @param {string} rootDir
61
+ * @returns {string[]} see {@link resolveWorkspacePackages}
62
+ */
63
+ export function workspacePackages(rootDir) {
64
+ return resolveWorkspacePackages(rootDir, readWorkspacePatterns(rootDir).patterns)
65
+ }
66
+
67
+ /**
68
+ * The folders `patterns` name under `rootDir`, as workspace-relative paths in `/`
69
+ * form, each once, in the order of the first pattern that names it — alphabetical
70
+ * within a pattern. A folder a wildcard finds counts only when it holds a
71
+ * package.json; one a pattern names by its own path counts if it exists.
72
+ *
73
+ * @param {string} rootDir
74
+ * @param {string[]} patterns
75
+ * @returns {string[]}
76
+ */
77
+ export function resolveWorkspacePackages(rootDir, patterns) {
78
+ const { include, exclude } = parsePatterns(patterns)
79
+ const seen = new Set()
80
+ const out = []
81
+ for (const pattern of include) {
82
+ const byWildcard = pattern.some((segment) => segment === '**' || hasMagic(segment))
83
+ for (const rel of expand(rootDir, pattern, [], 0, [])) {
84
+ // The root is the workspace itself, never one of its packages.
85
+ if (!rel || seen.has(rel)) continue
86
+ if (byWildcard && !existsSync(join(rootDir, rel, 'package.json'))) continue
87
+ if (exclude.some((ex) => matches(ex, rel.split('/')))) continue
88
+ seen.add(rel)
89
+ out.push(rel)
90
+ }
91
+ }
92
+ return out
93
+ }
94
+
95
+ /**
96
+ * Do `patterns` cover the folder at `relPath` — would it be one of the workspace's
97
+ * packages? Answered from the patterns alone, so it holds for a folder about to be
98
+ * created.
99
+ *
100
+ * @param {string[]} patterns
101
+ * @param {string} relPath - workspace-relative
102
+ * @returns {boolean}
103
+ */
104
+ export function patternsCover(patterns, relPath) {
105
+ const path = normalizePath(relPath)
106
+ if (!path) return false
107
+ const segments = path.split('/')
108
+ const { include, exclude } = parsePatterns(patterns)
109
+ return (
110
+ include.some((p) => matches(p, segments)) &&
111
+ !exclude.some((p) => matches(p, segments))
112
+ )
113
+ }
114
+
115
+ // ─── Patterns ───────────────────────────────────────────────────────────────
116
+
117
+ // `@(…)`, `+(…)`, `!(…)`, `*(…)`, `?(…)` — extended globs, which this does not read.
118
+ const EXTGLOB = /[@+!*?]\(/
119
+ const warned = new Set()
120
+
121
+ /** Positive and negative patterns as folder-name lists, `{a,b}` expanded. */
122
+ function parsePatterns(patterns) {
123
+ const include = []
124
+ const exclude = []
125
+ for (const raw of strings(patterns)) {
126
+ let pattern = raw.trim()
127
+ const negated = pattern.startsWith('!')
128
+ if (negated) pattern = pattern.slice(1)
129
+ if (EXTGLOB.test(pattern)) {
130
+ if (!warned.has(raw)) {
131
+ warned.add(raw)
132
+ process.stderr.write(
133
+ `⚠ uniweb does not read the workspace pattern "${raw}" (extended glob syntax) — ` +
134
+ `list the folders it stands for instead.\n`
135
+ )
136
+ }
137
+ continue
138
+ }
139
+ for (const one of expandBraces(pattern)) {
140
+ const path = normalizePath(one)
141
+ if (path) (negated ? exclude : include).push(path.split('/'))
142
+ }
143
+ }
144
+ return { include, exclude }
145
+ }
146
+
147
+ /** `a/{b,c}/d` → `a/b/d`, `a/c/d`; nested lists expand innermost first. */
148
+ function expandBraces(pattern) {
149
+ const m = /\{([^{}]*)\}/.exec(pattern)
150
+ if (!m) return [pattern]
151
+ const options = m[1].split(',')
152
+ // `{x}` lists nothing to choose between: a literal brace, as in pnpm.
153
+ if (options.length < 2) return [pattern]
154
+ const head = pattern.slice(0, m.index)
155
+ const tail = pattern.slice(m.index + m[0].length)
156
+ return options.flatMap((o) => expandBraces(head + o + tail))
157
+ }
158
+
159
+ /** `./a//b/` → `a/b`; `\` becomes `/`; `.` and `` are the root. */
160
+ function normalizePath(path) {
161
+ let s = String(path).replace(/\\/g, '/').replace(/\/{2,}/g, '/')
162
+ while (s.startsWith('./')) s = s.slice(2)
163
+ s = s.replace(/^\/+/, '').replace(/\/+$/, '')
164
+ return s === '.' ? '' : s
165
+ }
166
+
167
+ const hasMagic = (segment) => /[*?[]/.test(segment)
168
+
169
+ /** Can a wildcard step into this folder? Never `node_modules`, never a dot-folder. */
170
+ const wildcardMayEnter = (name) => !name.startsWith('.') && name !== 'node_modules'
171
+
172
+ const regexCache = new Map()
173
+
174
+ /** One folder-name pattern as a regex: `*`, `?` and `[...]`, everything else literal. */
175
+ function segmentRegex(segment) {
176
+ let re = regexCache.get(segment)
177
+ if (re) return re
178
+ let src = ''
179
+ for (let i = 0; i < segment.length; i++) {
180
+ const c = segment[i]
181
+ if (c === '*') src += '[^/]*'
182
+ else if (c === '?') src += '[^/]'
183
+ else if (c === '[' && segment.indexOf(']', i + 2) > i) {
184
+ const end = segment.indexOf(']', i + 2)
185
+ let body = segment.slice(i + 1, end).replace(/\\/g, '\\\\')
186
+ if (body.startsWith('!')) body = `^${body.slice(1)}`
187
+ src += `[${body}]`
188
+ i = end
189
+ } else src += c.replace(/[.+^$(){}|\\[\]]/g, '\\$&')
190
+ }
191
+ re = new RegExp(`^${src}$`)
192
+ regexCache.set(segment, re)
193
+ return re
194
+ }
195
+
196
+ function segmentMatches(segment, name) {
197
+ if (!hasMagic(segment)) return segment === name
198
+ // A wildcard does not match a dot-folder unless the pattern spells the dot.
199
+ if (name.startsWith('.') && !segment.startsWith('.')) return false
200
+ if (name === 'node_modules') return false
201
+ return segmentRegex(segment).test(name)
202
+ }
203
+
204
+ /** Does the folder-name list `path` match the pattern `pattern`? `**` is any depth. */
205
+ function matches(pattern, path, i = 0, j = 0) {
206
+ if (i === pattern.length) return j === path.length
207
+ if (pattern[i] === '**') {
208
+ for (let k = j; k <= path.length; k++) {
209
+ if (k > j && !wildcardMayEnter(path[k - 1])) break
210
+ if (matches(pattern, path, i + 1, k)) return true
211
+ }
212
+ return false
213
+ }
214
+ if (j === path.length || !segmentMatches(pattern[i], path[j])) return false
215
+ return matches(pattern, path, i + 1, j + 1)
216
+ }
217
+
218
+ /** The folders under `rootDir` that `pattern` names, found on disk. */
219
+ function expand(rootDir, pattern, base, i, out) {
220
+ if (i === pattern.length) {
221
+ out.push(base.join('/'))
222
+ return out
223
+ }
224
+ const segment = pattern[i]
225
+ const here = join(rootDir, ...base)
226
+ if (segment === '**') {
227
+ expand(rootDir, pattern, base, i + 1, out)
228
+ // Real folders only: a symlink back up the tree would never end.
229
+ for (const name of subfolders(here, { followLinks: false })) {
230
+ if (wildcardMayEnter(name)) expand(rootDir, pattern, [...base, name], i, out)
231
+ }
232
+ return out
233
+ }
234
+ if (!hasMagic(segment)) {
235
+ if (segment === '.') return expand(rootDir, pattern, base, i + 1, out)
236
+ if (isFolder(join(here, segment))) expand(rootDir, pattern, [...base, segment], i + 1, out)
237
+ return out
238
+ }
239
+ for (const name of subfolders(here)) {
240
+ if (segmentMatches(segment, name)) expand(rootDir, pattern, [...base, name], i + 1, out)
241
+ }
242
+ return out
243
+ }
244
+
245
+ function subfolders(dir, { followLinks = true } = {}) {
246
+ let entries
247
+ try {
248
+ entries = readdirSync(dir, { withFileTypes: true })
249
+ } catch {
250
+ return []
251
+ }
252
+ return entries
253
+ .filter(
254
+ (e) => e.isDirectory() || (followLinks && e.isSymbolicLink() && isFolder(join(dir, e.name)))
255
+ )
256
+ .map((e) => e.name)
257
+ .sort()
258
+ }
259
+
260
+ function isFolder(path) {
261
+ try {
262
+ return statSync(path).isDirectory()
263
+ } catch {
264
+ return false
265
+ }
266
+ }
267
+
268
+ // ─── Helpers ────────────────────────────────────────────────────────────────
269
+
270
+ export function strings(list) {
271
+ return Array.isArray(list) ? list.filter((v) => typeof v === 'string') : []
272
+ }
@@ -12,17 +12,14 @@ import { workspacePackages } from './workspace-packages.js'
12
12
  * The names of one scope two packages of the workspace define.
13
13
  *
14
14
  * @param {string} workspaceDir
15
- * @param {{ dir: string, kind: 'foundation'|'schemas', scope: string }} [self] - a package whose scope
16
- * was just settled, which its own files may not say yet (`register`)
17
15
  * @returns {Promise<{ ref: string, files: string[], differ: boolean }[]>}
18
16
  */
19
- export async function workspaceTypesDefinedTwice(workspaceDir, self = null) {
17
+ export async function workspaceTypesDefinedTwice(workspaceDir) {
20
18
  const packages = []
21
19
  for (const rel of workspacePackages(workspaceDir)) {
22
20
  const dir = join(workspaceDir, rel)
23
21
  const kind = classifyPackage(dir) === 'foundation' ? 'foundation' : isSchemasPackage(dir) ? 'schemas' : null
24
22
  if (kind) packages.push({ dir, kind })
25
23
  }
26
- if (self) packages.unshift(self)
27
24
  return typesDefinedTwice(packages)
28
25
  }