tosijs-ui 1.17.0-beta.1 → 1.17.0-beta.2

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/CHANGELOG.md CHANGED
@@ -1,6 +1,35 @@
1
1
  # Changelog
2
2
 
3
- ## 1.17.0-beta.1
3
+ ## 1.17.0-beta.2
4
+
5
+ > Prerelease, published under the `beta` dist-tag: install with `tosijs-ui@beta`. `latest` stays
6
+ > on 1.16.41. Fixes from Learn 3D's first run of beta.1.
7
+
8
+ - **Accessibility mode: headings in a blockquote or list shift with the rest of the page
9
+ (#3576).** A sidebar's `> ####` under `###` sections stayed an `<h4>` under the new `<h2>`s, so
10
+ the build reported a skipped level and DAISY Ace failed the ePub on heading order. A heading
11
+ inside a blockquote still never becomes the page's title.
12
+ - **DAISY Ace is found on `PATH` (#3577).** The docs said `bun add -d @daisy/ace`, which brings
13
+ Electron and Puppeteer into the project, and their advisories then failed the build's own
14
+ dependency audit. Install it globally (`npm install -g @daisy/ace`) instead; the build looks in
15
+ the project first, then on `PATH`.
16
+ - **The axe audit is about twice as fast, and audits the page a reader gets (#3585).** Pages are
17
+ audited four at a time (this site: 80s to 43s). Each is audited once it stops adding elements,
18
+ rather than after a fixed 300ms, which on a busy machine caught pages half-built. And the
19
+ audit no longer starts the doc browser's background test runner, which runs on localhost and
20
+ never on a deployed site. `TOSIJS_A11Y_AUDIT=off` skips the audit and the Ace check for one
21
+ build while the mode stays on; the ePub then claims no conformance.
22
+ - **Section stubs are not written where they cannot be read, or mid-edit (#3584).** A page whose
23
+ `parent` names a missing doc gets a stub section doc in `sectionsDir`. When `sectionsDir` is
24
+ outside every `docPaths` entry, the build now warns and writes nothing, since the stub would
25
+ never be read back. Stubs are created only on the first build in a process, so a parent that
26
+ disappears for a second during a rename no longer leaves files behind. Each stub written is
27
+ named in the build output.
28
+ - **`preview.host` is optional, and the preview docs no longer say `host` is required (#3586).**
29
+ The type has allowed a config with only `preview.tunnel` since 1.10.0, but the doc comment and
30
+ the reference table still said so. `as any` casts written for it can go.
31
+
32
+ ### 1.17.0-beta.1 (prerelease detail)
4
33
 
5
34
  > Prerelease, published under the `beta` dist-tag: install with `tosijs-ui@beta`. `latest` stays
6
35
  > on 1.16.41. It carries the accessibility half of 1.17.0; the SEO work and #245/#246 follow.
@@ -87,8 +87,24 @@ function withFigures(tokens) {
87
87
  }
88
88
  return out;
89
89
  }
90
+ // Every heading, including those in blockquotes and lists: a sidebar's `> ####` shifts with the
91
+ // page's own headings, or it lands a level too deep (#3576).
92
+ function allHeadings(tokens, out = []) {
93
+ for (const t of tokens) {
94
+ if (t.type === 'heading')
95
+ out.push(t);
96
+ else if (t.type === 'blockquote')
97
+ allHeadings(t.tokens ?? [], out);
98
+ else if (t.type === 'list')
99
+ for (const item of t.items ?? [])
100
+ allHeadings(item.tokens ?? [], out);
101
+ }
102
+ return out;
103
+ }
90
104
  function withOneTitle(tokens, title) {
105
+ // Only a top-level heading can be the page's title.
91
106
  const headings = tokens.filter((t) => t.type === 'heading');
107
+ const nested = allHeadings(tokens);
92
108
  /*
93
109
  A page with no `#` takes its title from its first heading, whatever its level, so that
94
110
  heading IS the title: promote it rather than print the same words twice.
@@ -99,13 +115,13 @@ function withOneTitle(tokens, title) {
99
115
  ? lead
100
116
  : undefined);
101
117
  // The shift comes from the sub-headings as written; a demoted `#` is not one of them.
102
- const below = headings
118
+ const below = nested
103
119
  .filter((h) => h !== first && h.depth > 1)
104
120
  .map((h) => h.depth);
105
121
  const shift = below.length ? Math.min(...below) - 2 : 0;
106
122
  if (first)
107
123
  first.depth = 1;
108
- for (const h of headings) {
124
+ for (const h of nested) {
109
125
  if (h === first)
110
126
  continue;
111
127
  if (h.depth === 1)
@@ -64,40 +64,76 @@ catch (error) {
64
64
  server.stop(true);
65
65
  notRun(`Chromium could not be launched (bunx playwright install chromium): ${error.message.split('\n')[0]}`);
66
66
  }
67
- const violations = [];
67
+ /*
68
+ Pages are audited a few at a time, each in its own tab: one at a time took Learn 3D's 126 pages
69
+ to ~73s (#3585). Results are kept in page order, so the report reads the same either way.
70
+ */
71
+ const CONCURRENCY = 4;
72
+ const perPage = [];
68
73
  try {
69
74
  const context = await browser.newContext();
70
- const page = await context.newPage();
71
- for (const pagePath of pages) {
72
- await page.goto(`http://localhost:${server.port}${prefix}${pagePath}`, {
73
- waitUntil: 'load',
74
- });
75
- // Audit the page a reader uses: hydrated when the bundle loads, static if it does not.
76
- if (await page.$('tosi-doc-system'))
77
- await page
78
- .waitForFunction(() => customElements.get('tosi-doc-system'), null, {
79
- timeout: 10_000,
80
- })
81
- .catch(() => undefined);
82
- await page.waitForTimeout(300);
83
- await page.addScriptTag({ path: axePath });
84
- const found = await page.evaluate(async (tags) => {
85
- const result = await window.axe.run(document, {
86
- runOnly: { type: 'tag', values: tags },
75
+ /*
76
+ The page a reader gets: served from localhost, the doc browser would start its background test
77
+ runner, whose hidden frames and badges no deployed site has.
78
+ */
79
+ await context.addInitScript(() => localStorage.setItem('tosijs-ui-tests-enabled', 'false'));
80
+ let next = 0;
81
+ const worker = async () => {
82
+ const page = await context.newPage();
83
+ while (next < pages.length) {
84
+ const index = next++;
85
+ const pagePath = pages[index];
86
+ await page.goto(`http://localhost:${server.port}${prefix}${pagePath}`, {
87
+ waitUntil: 'networkidle',
87
88
  });
88
- return result.violations.map((v) => ({
89
- rule: v.id,
90
- impact: v.impact,
91
- help: v.help,
92
- targets: v.nodes.map((n) => n.target.join(' ')),
89
+ // Audit the page a reader uses: hydrated when the bundle loads, static if it does not.
90
+ if (await page.$('tosi-doc-system'))
91
+ await page
92
+ .waitForFunction(() => customElements.get('tosi-doc-system'), null, {
93
+ timeout: 10_000,
94
+ })
95
+ .catch(() => undefined);
96
+ /*
97
+ Then until no element has been added or removed for half a second (at most five): live examples render
98
+ after hydration, and a fixed pause audited a busy machine's pages half-built, so the
99
+ findings changed from run to run.
100
+ */
101
+ await page.evaluate(() => new Promise((resolve) => {
102
+ let timer = setTimeout(done, 500);
103
+ const deadline = setTimeout(done, 5000);
104
+ const observer = new MutationObserver(() => {
105
+ clearTimeout(timer);
106
+ timer = setTimeout(done, 500);
107
+ });
108
+ function done() {
109
+ observer.disconnect();
110
+ clearTimeout(timer);
111
+ clearTimeout(deadline);
112
+ resolve();
113
+ }
114
+ // Elements arriving, not attributes: an animation changes a style forever.
115
+ observer.observe(document, { subtree: true, childList: true });
93
116
  }));
94
- }, AXE_TAGS);
95
- for (const v of found)
96
- violations.push({ page: pagePath, ...v });
97
- }
117
+ await page.addScriptTag({ path: axePath });
118
+ const found = await page.evaluate(async (tags) => {
119
+ const result = await window.axe.run(document, {
120
+ runOnly: { type: 'tag', values: tags },
121
+ });
122
+ return result.violations.map((v) => ({
123
+ rule: v.id,
124
+ impact: v.impact,
125
+ help: v.help,
126
+ targets: v.nodes.map((n) => n.target.join(' ')),
127
+ }));
128
+ }, AXE_TAGS);
129
+ perPage[index] = found.map((v) => ({ page: pagePath, ...v }));
130
+ }
131
+ };
132
+ await Promise.all(Array.from({ length: Math.min(CONCURRENCY, pages.length) }, worker));
98
133
  }
99
134
  finally {
100
135
  await browser.close();
101
136
  server.stop(true);
102
137
  }
138
+ const violations = perPage.flat();
103
139
  console.log(JSON.stringify({ violations }));
@@ -26,11 +26,17 @@ export type AceResult = {
26
26
  ran: false;
27
27
  reason: string;
28
28
  };
29
+ /** Why Ace did not run, when it is not installed anywhere. */
30
+ export declare const ACE_NOT_INSTALLED = "DAISY Ace is not installed (npm install -g @daisy/ace, which keeps it out of your lockfile)";
29
31
  /**
30
- * Check a built `.epub` with DAISY Ace (`@daisy/ace`), resolved from the project's own
31
- * `node_modules/.bin`. It is the adopter's: never a dependency of tosijs-ui.
32
+ * Where `ace` is: the project's own `node_modules/.bin` first, then `PATH`. A global install is
33
+ * the one the docs recommend: Ace brings Electron and Puppeteer, whose advisories would otherwise
34
+ * fail the project's own dependency audit (#3577). It is the adopter's, never a dependency of
35
+ * tosijs-ui.
32
36
  */
33
- export declare function runAce(epubFile: string, projectDir?: string): Promise<AceResult>;
37
+ export declare function findAce(projectDir?: string, searchPath?: string): string | null;
38
+ /** Check a built `.epub` with DAISY Ace (`@daisy/ace`). */
39
+ export declare function runAce(epubFile: string, projectDir?: string, searchPath?: string): Promise<AceResult>;
34
40
  /** Pass or fail, and the failing checks' titles, from an Ace `report.json`. */
35
41
  export declare function aceVerdict(report: any): {
36
42
  passed: boolean;
@@ -64,17 +64,25 @@ export function accessibilityMetadata(facts, opts = {}) {
64
64
  .map((line) => `\n ${line}`)
65
65
  .join('');
66
66
  }
67
+ /** Why Ace did not run, when it is not installed anywhere. */
68
+ export const ACE_NOT_INSTALLED = 'DAISY Ace is not installed (npm install -g @daisy/ace, which keeps it out of your lockfile)';
67
69
  /**
68
- * Check a built `.epub` with DAISY Ace (`@daisy/ace`), resolved from the project's own
69
- * `node_modules/.bin`. It is the adopter's: never a dependency of tosijs-ui.
70
+ * Where `ace` is: the project's own `node_modules/.bin` first, then `PATH`. A global install is
71
+ * the one the docs recommend: Ace brings Electron and Puppeteer, whose advisories would otherwise
72
+ * fail the project's own dependency audit (#3577). It is the adopter's, never a dependency of
73
+ * tosijs-ui.
70
74
  */
71
- export async function runAce(epubFile, projectDir = process.cwd()) {
72
- const bin = path.join(projectDir, 'node_modules', '.bin', 'ace');
73
- if (!existsSync(bin))
74
- return {
75
- ran: false,
76
- reason: 'DAISY Ace is not installed in this project (bun add -d @daisy/ace)',
77
- };
75
+ export function findAce(projectDir = process.cwd(), searchPath = process.env.PATH ?? '') {
76
+ const local = path.join(projectDir, 'node_modules', '.bin', 'ace');
77
+ if (existsSync(local))
78
+ return local;
79
+ return Bun.which('ace', { PATH: searchPath }) ?? null;
80
+ }
81
+ /** Check a built `.epub` with DAISY Ace (`@daisy/ace`). */
82
+ export async function runAce(epubFile, projectDir = process.cwd(), searchPath = process.env.PATH ?? '') {
83
+ const bin = findAce(projectDir, searchPath);
84
+ if (!bin)
85
+ return { ran: false, reason: ACE_NOT_INSTALLED };
78
86
  const out = mkdtempSync(path.join(tmpdir(), 'tosijs-ace-'));
79
87
  try {
80
88
  const child = spawn([bin, '--silent', '--force', '--outdir', out, epubFile], {
@@ -395,6 +395,8 @@ whether or not the dependency audit ran — it was gated on `!opts.skipAudit`, w
395
395
  let announcedClobber = false;
396
396
  /** The axe audit runs once per process: it is a release check, not an edit-loop one (#3521). */
397
397
  let auditedAccessibility = false;
398
+ /** Section stubs are created on the first build in a process only (#3584). */
399
+ let sectionStubsDone = false;
398
400
  export async function buildSite(config, opts = {}) {
399
401
  // Look at the machine before adding load to it. Runs on every build, including each
400
402
  // watch rebuild, because the danger is not present at launch and then absent — it
@@ -701,7 +703,11 @@ export async function buildSite(config, opts = {}) {
701
703
  docsJsonPath: DOCS_JSON,
702
704
  sectionsDir: config.sectionsDir ?? 'src/docs',
703
705
  reExtract: extract,
706
+ docPaths,
707
+ // Stubs on the first build in a process only, never a watch rebuild (#3584).
708
+ createStubs: !sectionStubsDone,
704
709
  });
710
+ sectionStubsDone = true;
705
711
  // Fail fast on any live example that can't build — a real syntax/import error,
706
712
  // or illustrative code mistakenly tagged executable (`js`/`ts`/…) instead of
707
713
  // display-only `typescript`. Runs on the whole corpus, so it catches breakage
@@ -1616,13 +1622,20 @@ export async function buildSite(config, opts = {}) {
1616
1622
  // (otherwise a dev rebuild would silently drop it). Cheap (~0.4s).
1617
1623
  /*
1618
1624
  The accessibility mode's release checks (the axe audit, Ace on the ePub, #3521/#3522):
1619
- the first full build in a process, and never under a dev server.
1625
+ the first full build in a process, never under a dev server, and not when
1626
+ TOSIJS_A11Y_AUDIT=off asks a build to skip them while the mode stays on (#3585).
1620
1627
  */
1621
1628
  const lockHolder = currentHolder('.');
1629
+ const a11yChecksOff = process.env.TOSIJS_A11Y_AUDIT?.toLowerCase() === 'off';
1622
1630
  const accessibilityRelease = !!config.accessibility &&
1623
1631
  !opts.skipAudit &&
1632
+ !a11yChecksOff &&
1624
1633
  !auditedAccessibility &&
1625
1634
  !(lockHolder?.pid === process.pid && lockHolder.role === 'dev-server');
1635
+ if (config.accessibility && a11yChecksOff && !auditedAccessibility) {
1636
+ auditedAccessibility = true;
1637
+ console.log('♿ TOSIJS_A11Y_AUDIT=off: no axe audit and no Ace check on this build, so the ePub claims no conformance');
1638
+ }
1626
1639
  if (config.epub) {
1627
1640
  const epubOpts = typeof config.epub === 'object' ? config.epub : {};
1628
1641
  /*
@@ -5,5 +5,19 @@ export interface EnsureSectionsOptions {
5
5
  sectionsDir: string;
6
6
  /** re-run doc extraction so docsJsonPath reflects on-disk changes */
7
7
  reExtract: () => void;
8
+ /**
9
+ * The site's `docPaths`. A stub outside all of them would never be read back, so none is
10
+ * written there (#3584).
11
+ */
12
+ docPaths?: string[];
13
+ /**
14
+ * Whether this build may create stubs. A watch rebuild may not: a parent that is missing for
15
+ * a second, mid-rename, is not a missing parent (#3584). Default true.
16
+ */
17
+ createStubs?: boolean;
18
+ /** where warnings and the list of created files go (default console.warn) */
19
+ log?: (message: string) => void;
8
20
  }
21
+ /** True when `dir` is one of `docPaths`, or inside one. */
22
+ export declare function insideDocPaths(dir: string, docPaths: string[]): boolean;
9
23
  export declare function ensureSections(opts: EnsureSectionsOptions): void;
@@ -16,27 +16,49 @@ import * as path from 'path';
16
16
  import { buildSlugMap, pathForSlug, slugify, resolveParent, } from '../routing.js';
17
17
  import { pinnedSort } from '../nav-tree.js';
18
18
  const TOC_RE = /<!-- toc -->[\s\S]*?<!-- \/toc -->/;
19
+ /** True when `dir` is one of `docPaths`, or inside one. */
20
+ export function insideDocPaths(dir, docPaths) {
21
+ const target = path.resolve(dir);
22
+ return docPaths.some((p) => {
23
+ const root = path.resolve(p);
24
+ return target === root || target.startsWith(root + path.sep);
25
+ });
26
+ }
19
27
  function readDocs(p) {
20
28
  return JSON.parse(readFileSync(p, 'utf8'));
21
29
  }
22
30
  export function ensureSections(opts) {
23
31
  const { docsJsonPath, sectionsDir, reExtract } = opts;
32
+ const log = opts.log ?? ((message) => console.warn(message));
24
33
  let docs = readDocs(docsJsonPath);
25
34
  let slugMap = buildSlugMap(docs);
26
35
  // 1. Auto-create a stub .md for any referenced-but-missing parent.
27
- let created = false;
28
- for (const ref of new Set(docs.map((d) => d.parent).filter(Boolean))) {
29
- if (resolveParent(ref, docs, slugMap))
30
- continue; // already exists
31
- const file = path.join(sectionsDir, slugify(ref) + '.md');
32
- if (existsSync(file))
33
- continue;
34
- mkdirSync(sectionsDir, { recursive: true });
35
- // Heading first so the doc title is clean; empty TOC block filled below.
36
- writeFileSync(file, `# ${ref}\n\n<!-- toc -->\n<!-- /toc -->\n`, 'utf8');
37
- created = true;
36
+ const missing = [
37
+ ...new Set(docs.map((d) => d.parent).filter(Boolean)),
38
+ ].filter((ref) => !resolveParent(ref, docs, slugMap) &&
39
+ !existsSync(path.join(sectionsDir, slugify(ref) + '.md')));
40
+ const readable = !opts.docPaths || insideDocPaths(sectionsDir, opts.docPaths);
41
+ const created = [];
42
+ if (missing.length && opts.createStubs === false) {
43
+ // Said, not written: the next full build creates them if they are still missing.
44
+ }
45
+ else if (missing.length && !readable) {
46
+ log(`⚠️ ${missing.length} page(s) name a parent that does not exist (${missing
47
+ .map((ref) => `"${ref}"`)
48
+ .join(', ')}). No section doc was created for ${missing.length === 1 ? 'it' : 'them'}: sectionsDir "${sectionsDir}" is outside every docPath, so the build would never read ` +
49
+ `it back. Set sectionsDir to a folder inside docPaths, or fix the parent names.`);
50
+ }
51
+ else {
52
+ for (const ref of missing) {
53
+ const file = path.join(sectionsDir, slugify(ref) + '.md');
54
+ mkdirSync(sectionsDir, { recursive: true });
55
+ // Heading first so the doc title is clean; empty TOC block filled below.
56
+ writeFileSync(file, `# ${ref}\n\n<!-- toc -->\n<!-- /toc -->\n`, 'utf8');
57
+ created.push(file);
58
+ }
38
59
  }
39
- if (created) {
60
+ if (created.length) {
61
+ log(`📄 created ${created.length} section doc(s) for parents that had none: ${created.join(', ')}`);
40
62
  reExtract();
41
63
  docs = readDocs(docsJsonPath);
42
64
  slugMap = buildSlugMap(docs);
@@ -503,7 +503,8 @@ export interface SiteConfig {
503
503
  * control, so a phone, a client, or a reviewer can see it without your dev server
504
504
  * (or your laptop) being up.
505
505
  *
506
- * Only `host` is required; everything else has a sensible default:
506
+ * Every field is optional; keep `host` out of the config and supply it from `PREVIEW_HOST`
507
+ * (below). Committed, it looks like this:
507
508
  *
508
509
  * ```ts
509
510
  * preview: { host: 'root@203.0.113.10' }