@contentbit/studio 2.0.0-next.0 → 2.0.0-next.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/README.md CHANGED
@@ -3,7 +3,8 @@
3
3
  The local read-only dashboard of [contentbit](https://contentbit.dev), the SEO
4
4
  content check for agents.
5
5
 
6
- Studio is launched by the `contentbit` CLI:
6
+ Studio is launched by the `contentbit` CLI, which starts only the Studio of
7
+ its own version. Install the same version as `contentbit`:
7
8
 
8
9
  ```bash
9
10
  pnpm add -D @contentbit/studio
@@ -13,7 +14,7 @@ contentbit studio
13
14
  `contentbit.config.ts` supplies the content glob, registry, and build folder.
14
15
  Explicit globs and flags still override it for one invocation.
15
16
 
16
- New projects created with `contentbit init` get a shorter script:
17
+ `contentbit init --blocks` adds a shorter script:
17
18
 
18
19
  ```bash
19
20
  pnpm studio
@@ -1 +1 @@
1
- {"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../../src/server/api.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAA;AAIhE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAE/C,wBAAsB,sBAAsB,CAC1C,OAAO,EAAE,aAAa,EACtB,GAAG,EAAE,eAAe,EACpB,GAAG,EAAE,cAAc,GAClB,OAAO,CAAC,OAAO,CAAC,CAyDlB"}
1
+ {"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../../src/server/api.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAA;AAKhE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAE/C,wBAAsB,sBAAsB,CAC1C,OAAO,EAAE,aAAa,EACtB,GAAG,EAAE,eAAe,EACpB,GAAG,EAAE,cAAc,GAClB,OAAO,CAAC,OAAO,CAAC,CA0DlB"}
@@ -1809,16 +1809,10 @@ import { spawn } from "node:child_process";
1809
1809
  import { existsSync as existsSync4 } from "node:fs";
1810
1810
  import { createRequire } from "node:module";
1811
1811
  import { createServer as createNetServer } from "node:net";
1812
- import { dirname, isAbsolute as isAbsolute3, join as join5, resolve as resolvePath } from "node:path";
1812
+ import { dirname as dirname2, isAbsolute as isAbsolute3, join as join5, resolve as resolvePath } from "node:path";
1813
1813
  import { fileURLToPath } from "node:url";
1814
1814
  import { createServer } from "vite";
1815
1815
 
1816
- // src/server/scan.ts
1817
- import {
1818
- createSeoBrief as createSeoBrief2,
1819
- readContentPageFacts as readContentPageFacts2
1820
- } from "@contentbit/core";
1821
-
1822
1816
  // ../built-site/dist/findings.js
1823
1817
  var DEFAULT_SEVERITY_BY_CODE = {
1824
1818
  CB_PAGE_TITLE_MISSING: "error",
@@ -1842,7 +1836,7 @@ var DEFAULT_SEVERITY_BY_CODE = {
1842
1836
  CB_LINK_PAGE_MISSING: "error",
1843
1837
  CB_LINK_ANCHOR_MISSING: "error",
1844
1838
  CB_LINK_FILE_MISSING: "error",
1845
- CB_LINK_NOINDEX_TARGET: "warning",
1839
+ CB_LINK_NOINDEX_TARGET: "info",
1846
1840
  CB_SITE_HREFLANG_NOT_RECIPROCAL: "warning",
1847
1841
  CB_SITE_HREFLANG_X_DEFAULT_MISSING: "warning",
1848
1842
  CB_SITE_SITEMAP_URL_NOT_BUILT: "error",
@@ -1929,9 +1923,6 @@ var LAYOUT_LANDMARKS = /* @__PURE__ */ new Set([
1929
1923
  "aside",
1930
1924
  "footer"
1931
1925
  ]);
1932
- function linkPlacement({ landmark }) {
1933
- return landmark !== void 0 && LAYOUT_LANDMARKS.has(landmark) ? "layout" : "content";
1934
- }
1935
1926
 
1936
1927
  // ../built-site/dist/origin.js
1937
1928
  function httpOrigin(value) {
@@ -2195,7 +2186,7 @@ function checkImages(index) {
2195
2186
  }
2196
2187
 
2197
2188
  // ../built-site/dist/checks/link-contract.js
2198
- var LAYOUT_LINKS = "Links in the header, nav, aside or footer do not count.";
2189
+ var LAYOUT_LINKS = "Links in the header, nav, aside or footer, or outside the page content, do not count.";
2199
2190
  function checkLinkContracts(index) {
2200
2191
  const { sources, seo } = index;
2201
2192
  if (!sources || !seo)
@@ -2204,7 +2195,7 @@ function checkLinkContracts(index) {
2204
2195
  const linksOut = /* @__PURE__ */ new Map();
2205
2196
  const linksIn = /* @__PURE__ */ new Map();
2206
2197
  forEachLinkBetweenPages(index, (from, link, to) => {
2207
- if (linkPlacement(link) === "layout")
2198
+ if (link.placement === "layout")
2208
2199
  return;
2209
2200
  linksOut.set(from, (linksOut.get(from) ?? /* @__PURE__ */ new Set()).add(to));
2210
2201
  linksIn.set(to, (linksIn.get(to) ?? /* @__PURE__ */ new Set()).add(from));
@@ -2472,7 +2463,7 @@ function compare(a, b) {
2472
2463
  }
2473
2464
 
2474
2465
  // ../built-site/dist/context.js
2475
- import { relative, resolve } from "node:path";
2466
+ import { basename, relative, resolve } from "node:path";
2476
2467
  import { closest, createSeoBrief } from "@contentbit/core";
2477
2468
 
2478
2469
  // ../built-site/dist/finding-origins.js
@@ -2642,7 +2633,7 @@ function pageContext(input, page) {
2642
2633
  from: from.path,
2643
2634
  text: link.text,
2644
2635
  ...anchor !== void 0 && { anchor },
2645
- placement: linkPlacement(link)
2636
+ placement: link.placement
2646
2637
  });
2647
2638
  });
2648
2639
  return {
@@ -2670,7 +2661,7 @@ function pageContext(input, page) {
2670
2661
  linksOut: facts.links.map((link) => ({
2671
2662
  href: link.href,
2672
2663
  text: link.text,
2673
- placement: linkPlacement(link),
2664
+ placement: link.placement,
2674
2665
  target: linkOutTarget(index.resolveLink(link.href, page))
2675
2666
  })),
2676
2667
  findings: input.findings.filter((finding) => findingPages(finding).includes(page.path)).map((finding) => onPage(finding, page.path)),
@@ -2690,7 +2681,7 @@ function siteContext(input) {
2690
2681
  return counts;
2691
2682
  };
2692
2683
  forEachLinkBetweenPages(index, (_from, link, to) => {
2693
- linksInto(to)[linkPlacement(link)]++;
2684
+ linksInto(to)[link.placement]++;
2694
2685
  });
2695
2686
  const pages = input.site.pages.map((page) => {
2696
2687
  const document = input.sources.pages.get(page.path);
@@ -4972,9 +4963,9 @@ var HEADING_LEVELS = /* @__PURE__ */ new Map([
4972
4963
  ["h5", 5],
4973
4964
  ["h6", 6]
4974
4965
  ]);
4975
- var LANDMARK_TAGS = /* @__PURE__ */ new Set(["header", "nav", "main", "aside", "footer"]);
4976
4966
  var SECTIONING_TAGS = /* @__PURE__ */ new Set(["article", "aside", "main", "nav", "section"]);
4977
4967
  var SECTIONING_ROLES = /* @__PURE__ */ new Set(["article", "complementary", "main", "navigation", "region"]);
4968
+ var SECTIONING_ROOTS = /* @__PURE__ */ new Set(["blockquote", "details", "dialog", "fieldset", "figure", "td"]);
4978
4969
  var LANDMARK_ROLES = /* @__PURE__ */ new Map([
4979
4970
  ["banner", "header"],
4980
4971
  ["navigation", "nav"],
@@ -5046,8 +5037,16 @@ function readRenderedPageFacts(html) {
5046
5037
  const main = emptyRegion();
5047
5038
  let hasMain = false;
5048
5039
  let h1OutsideMain = false;
5049
- const regions = (frame) => frame?.main ? [page, main] : [page];
5040
+ const h1Articles = /* @__PURE__ */ new Set();
5041
+ const regions = (frame) => [
5042
+ page,
5043
+ ...frame?.main ? [main] : [],
5044
+ ...frame?.article && !frame.articleFooter ? [frame.article] : []
5045
+ ];
5046
+ const pendingLinks = [];
5050
5047
  let permalink;
5048
+ const layoutAsides = [];
5049
+ let asides = 0;
5051
5050
  const capture = (finish, { visibleOnly = false, imageAlts = false } = {}) => captures.push({ depth: stack.length - 1, parts: [], visibleOnly, imageAlts, finish });
5052
5051
  let wordBreak = false;
5053
5052
  let closed = false;
@@ -5055,7 +5054,8 @@ function readRenderedPageFacts(html) {
5055
5054
  for (const open of captures)
5056
5055
  if (open.parts.at(-1) !== " ")
5057
5056
  open.parts.push(" ");
5058
- for (const region of [page, main]) {
5057
+ const article = stack.at(-1)?.article;
5058
+ for (const region of article ? [page, main, article] : [page, main]) {
5059
5059
  const { parts } = region.open;
5060
5060
  if (parts.at(-1) !== " ")
5061
5061
  parts.push(" ");
@@ -5066,24 +5066,33 @@ function readRenderedPageFacts(html) {
5066
5066
  parts.push(" ");
5067
5067
  parts.push(text);
5068
5068
  };
5069
- const parser = new Parser({
5069
+ const parser = new Parser(deferAsides(layoutAsides, {
5070
5070
  onopentag(name, attribs) {
5071
5071
  const parent = stack.at(-1);
5072
5072
  const role = attribs.role?.trim().toLowerCase().split(WHITESPACE)[0];
5073
- const own = landmarkOf(name, role, parent?.sectioning ?? false);
5073
+ const own = landmarkOf(name, role, parent, name === "aside" && layoutAsides[asides++]);
5074
5074
  const landmark = own ?? parent?.landmark;
5075
5075
  const visible = (parent?.visible ?? true) && !HIDDEN_TEXT_TAGS.has(name);
5076
5076
  const level = HEADING_LEVELS.get(name);
5077
+ const sectioning = SECTIONING_TAGS.has(name) || role !== void 0 && SECTIONING_ROLES.has(role);
5077
5078
  const frame = {
5078
5079
  name,
5079
5080
  landmark,
5080
- sectioning: (parent?.sectioning ?? false) || SECTIONING_TAGS.has(name) || role !== void 0 && SECTIONING_ROLES.has(role),
5081
+ sectioning: sectioning || (parent?.sectioning ?? false),
5082
+ scope: own === "main" ? "main" : sectioning || SECTIONING_ROOTS.has(name) ? "other" : parent?.scope ?? "page",
5081
5083
  visible,
5082
5084
  svg: name === "svg" || (parent?.svg ?? false),
5083
- content: visible && name !== "pre" && (parent?.content ?? true) && !(landmark && LAYOUT_LANDMARKS.has(landmark)) && !(name === "a" && attribs.href !== void 0 && attribs.href === permalink),
5085
+ content: visible && name !== "pre" && (parent?.content ?? true) && !isLayout(landmark) && !(name === "a" && attribs.href !== void 0 && attribs.href === permalink),
5084
5086
  main: own === "main" || (parent?.main ?? false),
5087
+ article: parent?.article,
5088
+ articleFooter: (parent?.articleFooter ?? false) || name === "footer" && own === void 0 && parent?.scope === "article",
5085
5089
  heading: level !== void 0 || (parent?.heading ?? false)
5086
5090
  };
5091
+ const isArticle = role ? role === "article" : name === "article";
5092
+ if (isArticle && frame.main && frame.content && !frame.article) {
5093
+ frame.article = emptyRegion();
5094
+ frame.scope = "article";
5095
+ }
5087
5096
  if (own === "main" && frame.content)
5088
5097
  hasMain = true;
5089
5098
  if (name !== "a" && !INLINE_TAGS.has(name))
@@ -5103,8 +5112,12 @@ function readRenderedPageFacts(html) {
5103
5112
  openSection(region, heading);
5104
5113
  permalink = attribs.id === void 0 ? void 0 : `#${attribs.id}`;
5105
5114
  }
5106
- if (level === 1 && frame.content && !frame.main)
5107
- h1OutsideMain = true;
5115
+ if (level === 1 && frame.content) {
5116
+ if (frame.main)
5117
+ h1Articles.add(frame.article);
5118
+ else
5119
+ h1OutsideMain = true;
5120
+ }
5108
5121
  capture((text) => {
5109
5122
  heading.text = collapseWhitespace(text);
5110
5123
  heading.words = countWords(heading.text);
@@ -5138,9 +5151,12 @@ function readRenderedPageFacts(html) {
5138
5151
  href: attribs.href,
5139
5152
  ...attribs.rel !== void 0 && { rel: attribs.rel },
5140
5153
  ...elementContext(frame, attribs.class),
5154
+ placement: "layout",
5141
5155
  text: ""
5142
5156
  };
5143
5157
  facts.links.push(link);
5158
+ if (!isLayout(frame.landmark))
5159
+ pendingLinks.push({ link, within: regions(frame) });
5144
5160
  const label = attribs["aria-label"];
5145
5161
  capture((text) => link.text = collapseWhitespace(text) || collapseWhitespace(label ?? ""), { visibleOnly: true, imageAlts: true });
5146
5162
  }
@@ -5197,10 +5213,16 @@ function readRenderedPageFacts(html) {
5197
5213
  open.finish(open.parts.join(""));
5198
5214
  }
5199
5215
  }
5200
- }, { decodeEntities: true });
5216
+ }), { decodeEntities: true });
5201
5217
  parser.write(html);
5202
5218
  parser.end();
5203
- for (const { heading, parts } of (hasMain && !h1OutsideMain ? main : page).sections) {
5219
+ const [h1Article] = h1Articles;
5220
+ const content = !hasMain || h1OutsideMain ? page : h1Articles.size === 1 && h1Article ? h1Article : main;
5221
+ for (const { link, within } of pendingLinks) {
5222
+ if (within.includes(content))
5223
+ link.placement = "content";
5224
+ }
5225
+ for (const { heading, parts } of content.sections) {
5204
5226
  const body = collapseWhitespace(parts.join(""));
5205
5227
  if (!heading) {
5206
5228
  facts.intro = body;
@@ -5215,12 +5237,94 @@ function readRenderedPageFacts(html) {
5215
5237
  facts.ids = [...ids];
5216
5238
  return facts;
5217
5239
  }
5218
- function landmarkOf(name, role, inSectioning) {
5219
- const scoped = inSectioning && (name === "header" || name === "footer");
5220
- if (LANDMARK_TAGS.has(name) && !scoped)
5221
- return name;
5240
+ function landmarkOf(name, role, parent, layoutAside) {
5241
+ switch (name) {
5242
+ case "main":
5243
+ case "nav":
5244
+ return name;
5245
+ case "header":
5246
+ if (!parent?.sectioning)
5247
+ return name;
5248
+ break;
5249
+ case "footer":
5250
+ if (parent === void 0 || parent.scope === "page" || parent.scope === "main")
5251
+ return name;
5252
+ break;
5253
+ case "aside":
5254
+ if (layoutAside)
5255
+ return name;
5256
+ break;
5257
+ }
5222
5258
  return role === void 0 ? void 0 : LANDMARK_ROLES.get(role);
5223
5259
  }
5260
+ function deferAsides(layout, reader) {
5261
+ const held = [];
5262
+ const open = [];
5263
+ const stack = [];
5264
+ const breakText = () => {
5265
+ for (const aside of open) {
5266
+ aside.text.push(" ");
5267
+ aside.linkText.push(" ");
5268
+ }
5269
+ };
5270
+ return {
5271
+ onopentag(name, attribs, implied) {
5272
+ if (name === "aside") {
5273
+ open.push({ index: layout.length, depth: stack.length, text: [], linkText: [] });
5274
+ layout.push(true);
5275
+ }
5276
+ if (open.length === 0) {
5277
+ reader.onopentag(name, attribs, implied);
5278
+ return;
5279
+ }
5280
+ held.push(() => reader.onopentag(name, attribs, implied));
5281
+ if (!INLINE_TAGS.has(name))
5282
+ breakText();
5283
+ const parent = stack.at(-1);
5284
+ stack.push({
5285
+ visible: (parent?.visible ?? true) && !HIDDEN_TEXT_TAGS.has(name),
5286
+ link: (parent?.link ?? false) || name === "a" && attribs.href !== void 0
5287
+ });
5288
+ },
5289
+ ontext(text) {
5290
+ if (open.length === 0) {
5291
+ reader.ontext(text);
5292
+ return;
5293
+ }
5294
+ held.push(() => reader.ontext(text));
5295
+ const frame = stack.at(-1);
5296
+ if (frame?.visible === false)
5297
+ return;
5298
+ for (const aside of open) {
5299
+ aside.text.push(text);
5300
+ if (frame?.link)
5301
+ aside.linkText.push(text);
5302
+ }
5303
+ },
5304
+ onclosetag(name, implied) {
5305
+ if (open.length === 0) {
5306
+ reader.onclosetag(name, implied);
5307
+ return;
5308
+ }
5309
+ held.push(() => reader.onclosetag(name, implied));
5310
+ stack.pop();
5311
+ if (!INLINE_TAGS.has(name))
5312
+ breakText();
5313
+ const aside = open.at(-1);
5314
+ if (aside?.depth !== stack.length)
5315
+ return;
5316
+ open.pop();
5317
+ const words = countWords(aside.text.join(""));
5318
+ layout[aside.index] = countWords(aside.linkText.join("")) * 2 >= words;
5319
+ if (open.length === 0)
5320
+ for (const event of held.splice(0))
5321
+ event();
5322
+ }
5323
+ };
5324
+ }
5325
+ function isLayout(landmark) {
5326
+ return landmark !== void 0 && LAYOUT_LANDMARKS.has(landmark);
5327
+ }
5224
5328
  function elementContext(frame, classes) {
5225
5329
  const classNames = classes?.split(WHITESPACE).filter(Boolean) ?? [];
5226
5330
  return {
@@ -5611,11 +5715,11 @@ function compileEntry(entry, index) {
5611
5715
  function list(value) {
5612
5716
  return value === void 0 ? [] : [value].flat();
5613
5717
  }
5614
- function globMatcher(globs, normalize = (value) => value) {
5718
+ function globMatcher(globs, normalize2 = (value) => value) {
5615
5719
  if (globs.length === 0)
5616
5720
  return void 0;
5617
- const isMatch = (0, import_picomatch.default)(globs.map(normalize), { dot: true, windows: false });
5618
- return (values) => values.some((value) => isMatch(normalize(value)));
5721
+ const isMatch = (0, import_picomatch.default)(globs.map(normalize2), { dot: true, windows: false });
5722
+ return (values) => values.some((value) => isMatch(normalize2(value)));
5619
5723
  }
5620
5724
  function withoutTrailingSlash(value) {
5621
5725
  return value.length > 1 && value.endsWith("/") ? value.slice(0, -1) : value;
@@ -5627,7 +5731,7 @@ import { createBlockRegistry, scanContentProject } from "@contentbit/core";
5627
5731
  import { createHash } from "node:crypto";
5628
5732
  import { existsSync } from "node:fs";
5629
5733
  import { readFile as readFile2 } from "node:fs/promises";
5630
- import { isAbsolute, join as join2 } from "node:path";
5734
+ import { basename as basename2, dirname, extname, isAbsolute, join as join2 } from "node:path";
5631
5735
  import { pathToFileURL } from "node:url";
5632
5736
  import { glob } from "tinyglobby";
5633
5737
  var ProjectLoadError = class extends Error {
@@ -5667,18 +5771,47 @@ async function loadRegistry(registryPath, options = {}) {
5667
5771
  mod = await importFresh(resolvedPath);
5668
5772
  } catch (err) {
5669
5773
  if (err instanceof Error && "code" in err && err.code === "ERR_UNKNOWN_FILE_EXTENSION") {
5670
- throw new Error(`Importing a TypeScript registry needs Node 22.18+ (native type stripping): ${resolvedPath}`, { cause: err });
5774
+ const extension = extname(resolvedPath);
5775
+ throw new ProjectLoadError(2, /^\.[cm]?ts$/.test(extension) ? `Importing a TypeScript registry needs Node 22.18+ (native type stripping): ${resolvedPath}` : `Node cannot import a ${extension} registry module: ${resolvedPath}. Use a .ts, .mts, .js or .mjs file.`);
5671
5776
  }
5672
5777
  throw err;
5673
5778
  }
5674
5779
  if (!Array.isArray(mod.default)) {
5675
- throw new Error(`--registry module must default-export an array of block definitions: ${resolvedPath}`);
5780
+ throw new ProjectLoadError(2, `Registry module must default-export an array of block definitions: ${resolvedPath}`);
5676
5781
  }
5677
5782
  registry.use(mod.default);
5678
5783
  return registry;
5679
5784
  }
5680
5785
  async function importFresh(path) {
5681
- return import((await versionedUrl(path)).href);
5786
+ const { href } = await versionedUrl(path);
5787
+ try {
5788
+ return await import(href);
5789
+ } catch (err) {
5790
+ if (err instanceof SyntaxError && await isEsmInCommonJsPackage(path)) {
5791
+ const extension = extname(path);
5792
+ throw new ProjectLoadError(2, `${path} uses import or export, but its package.json sets "type": "commonjs", so Node reads it as CommonJS. Rename it to ${basename2(path, extension)}.m${extension.slice(1)}.`);
5793
+ }
5794
+ throw err;
5795
+ }
5796
+ }
5797
+ async function isEsmInCommonJsPackage(path) {
5798
+ if (!/\.[jt]s$/.test(path))
5799
+ return false;
5800
+ const source = await readFile2(path, "utf8").catch(() => "");
5801
+ if (!/^\s*(?:import|export)\s/m.test(source))
5802
+ return false;
5803
+ for (let dir = dirname(path); ; dir = dirname(dir)) {
5804
+ const manifest = await readFile2(join2(dir, "package.json"), "utf8").catch(() => void 0);
5805
+ if (manifest !== void 0) {
5806
+ try {
5807
+ return JSON.parse(manifest).type === "commonjs";
5808
+ } catch {
5809
+ return false;
5810
+ }
5811
+ }
5812
+ if (dirname(dir) === dir)
5813
+ return false;
5814
+ }
5682
5815
  }
5683
5816
  async function versionedUrl(path) {
5684
5817
  const url = pathToFileURL(path);
@@ -5697,6 +5830,7 @@ async function loadContentFiles(files, input) {
5697
5830
  const linkOptions = input.linkOptions ?? {};
5698
5831
  const scan = scanContentProject(sources, registry, {
5699
5832
  linkOptions,
5833
+ root: input.cwd ?? process.cwd(),
5700
5834
  ...input.scan
5701
5835
  });
5702
5836
  return { files, registry, sources, linkOptions, scan };
@@ -5876,15 +6010,15 @@ async function readBuild(cmd, path, root) {
5876
6010
  } catch (error) {
5877
6011
  const code = error.code;
5878
6012
  if (code === "ENOENT") {
5879
- throw new ProjectLoadError(2, `${cmd}: the build folder ${displayPath(path)} does not exist. ${buildAdvice(root)}`);
6013
+ throw new ProjectLoadError(2, `${cmd}: the build folder ${displayPath(path, root)} does not exist. ${buildAdvice(root)}`);
5880
6014
  }
5881
6015
  if (code === "ENOTDIR") {
5882
- throw new ProjectLoadError(2, `${cmd}: ${displayPath(path)} is not a folder.`);
6016
+ throw new ProjectLoadError(2, `${cmd}: ${displayPath(path, root)} is not a folder.`);
5883
6017
  }
5884
6018
  throw error;
5885
6019
  }
5886
6020
  if (site.pages.length === 0) {
5887
- throw new ProjectLoadError(2, `${cmd}: the build folder ${displayPath(path)} holds no HTML page. ${buildAdvice(root)}`);
6021
+ throw new ProjectLoadError(2, `${cmd}: the build folder ${displayPath(path, root)} holds no HTML page. ${buildAdvice(root)}`);
5888
6022
  }
5889
6023
  return site;
5890
6024
  }
@@ -5895,8 +6029,15 @@ function buildAdvice(root) {
5895
6029
  return server;
5896
6030
  return `Build the site with ${buildCommand(root)} first, or set site.build in contentbit.config.ts to the folder its build writes.`;
5897
6031
  }
5898
- function displayPath(file) {
5899
- return relativeInside(process.cwd(), file) ?? file;
6032
+ function displayPath(file, root) {
6033
+ if (relative2(root, file) === "")
6034
+ return ".";
6035
+ return relativeInside(root, file) ?? file;
6036
+ }
6037
+ function pathsFromRoot(root, build) {
6038
+ const folders = build === void 0 ? [root] : [root, build];
6039
+ const isPath = (text) => folders.some((folder) => text === folder || text.startsWith(`${folder}${sep}`));
6040
+ return (_key, value) => typeof value === "string" && isPath(value) ? relative2(root, value).split(sep).join("/") || "." : value;
5900
6041
  }
5901
6042
  function relativeInside(folder, file) {
5902
6043
  const path = relative2(folder, file);
@@ -5977,7 +6118,11 @@ function resolveOrigin(flag, configured, site) {
5977
6118
  }
5978
6119
 
5979
6120
  // src/server/scan.ts
5980
- import { basename } from "node:path";
6121
+ import {
6122
+ createSeoBrief as createSeoBrief2,
6123
+ readContentPageFacts as readContentPageFacts2
6124
+ } from "@contentbit/core";
6125
+ import { basename as basename3, normalize } from "node:path";
5981
6126
 
5982
6127
  // src/server/preview.ts
5983
6128
  import { ContentBlocks } from "@contentbit/react";
@@ -6278,7 +6423,7 @@ function fileSummary(file, cwd, frontmatter, stats, findings, options, seoPage)
6278
6423
  };
6279
6424
  }
6280
6425
  function titleFor(file, frontmatter, stats) {
6281
- return stringValue(frontmatter.title) ?? stats.outline[0]?.text ?? basename(file);
6426
+ return stringValue(frontmatter.title) ?? stats.outline[0]?.text ?? basename3(file);
6282
6427
  }
6283
6428
  function summarize(findings) {
6284
6429
  const count = (severity) => findings.filter((finding) => finding.severity === severity).length;
@@ -6291,9 +6436,8 @@ function statusFor(findings) {
6291
6436
  return "healthy";
6292
6437
  }
6293
6438
  function findAllowedFile(context, cwd, requestedPath) {
6294
- return context.files.find(
6295
- (file) => file === requestedPath || relativePath(cwd, file) === requestedPath
6296
- ) ?? null;
6439
+ const requested = normalize(requestedPath);
6440
+ return context.files.find((file) => file === requested || relativePath(cwd, file) === requested) ?? null;
6297
6441
  }
6298
6442
  function stringValue(value) {
6299
6443
  return typeof value === "string" && value.trim().length > 0 ? value : void 0;
@@ -6307,58 +6451,59 @@ async function handleStudioApiRequest(options, req, res) {
6307
6451
  if (!req.url) return false;
6308
6452
  const url = new URL(req.url, "http://contentbit.local");
6309
6453
  if (!url.pathname.startsWith("/api/")) return false;
6454
+ const root = options.cwd ?? process.cwd();
6310
6455
  try {
6311
6456
  if (req.method !== "GET") {
6312
- sendJson(res, 405, { error: "Studio API is read-only." });
6457
+ sendJson(res, root, 405, { error: "Studio API is read-only." });
6313
6458
  return true;
6314
6459
  }
6315
6460
  if (url.pathname === "/api/project") {
6316
- sendJson(res, 200, await scanProject(options));
6461
+ sendJson(res, root, 200, await scanProject(options));
6317
6462
  return true;
6318
6463
  }
6319
6464
  if (url.pathname === "/api/site") {
6320
- sendJson(res, 200, await scanSite(options));
6465
+ sendJson(res, root, 200, await scanSite(options));
6321
6466
  return true;
6322
6467
  }
6323
6468
  if (url.pathname === "/api/page") {
6324
6469
  const path = url.searchParams.get("path");
6325
6470
  if (!path) {
6326
- sendJson(res, 400, { error: "Missing ?path=" });
6471
+ sendJson(res, root, 400, { error: "Missing ?path=" });
6327
6472
  return true;
6328
6473
  }
6329
6474
  const page = await scanPage(options, path);
6330
6475
  if (!page) {
6331
- sendJson(res, 404, { error: `The build has no page ${path}.` });
6476
+ sendJson(res, root, 404, { error: `The build has no page ${path}.` });
6332
6477
  return true;
6333
6478
  }
6334
- sendJson(res, 200, page);
6479
+ sendJson(res, root, 200, page);
6335
6480
  return true;
6336
6481
  }
6337
6482
  if (url.pathname === "/api/document") {
6338
6483
  const path = url.searchParams.get("path");
6339
6484
  if (!path) {
6340
- sendJson(res, 400, { error: "Missing ?path=" });
6485
+ sendJson(res, root, 400, { error: "Missing ?path=" });
6341
6486
  return true;
6342
6487
  }
6343
6488
  const document = await scanDocument(options, path);
6344
6489
  if (!document) {
6345
- sendJson(res, 404, { error: "Document is not in the configured content set." });
6490
+ sendJson(res, root, 404, { error: "Document is not in the configured content set." });
6346
6491
  return true;
6347
6492
  }
6348
- sendJson(res, 200, document);
6493
+ sendJson(res, root, 200, document);
6349
6494
  return true;
6350
6495
  }
6351
- sendJson(res, 404, { error: "Unknown Studio API route." });
6496
+ sendJson(res, root, 404, { error: "Unknown Studio API route." });
6352
6497
  return true;
6353
6498
  } catch (err) {
6354
- sendJson(res, 500, { error: err instanceof Error ? err.message : String(err) });
6499
+ sendJson(res, root, 500, { error: err instanceof Error ? err.message : String(err) });
6355
6500
  return true;
6356
6501
  }
6357
6502
  }
6358
- function sendJson(res, status, body) {
6503
+ function sendJson(res, root, status, body) {
6359
6504
  res.statusCode = status;
6360
6505
  res.setHeader("content-type", "application/json; charset=utf-8");
6361
- res.end(JSON.stringify(body, null, 2));
6506
+ res.end(JSON.stringify(body, pathsFromRoot(root), 2));
6362
6507
  }
6363
6508
 
6364
6509
  // src/server/index.ts
@@ -6367,7 +6512,7 @@ async function startStudio(options) {
6367
6512
  const host = options.host ?? "127.0.0.1";
6368
6513
  const port = options.port === 0 ? await freePort(host) : options.port ?? 4377;
6369
6514
  const cwd = options.cwd ?? process.cwd();
6370
- const fontRoot = dirname(
6515
+ const fontRoot = dirname2(
6371
6516
  createRequire(join5(root, "package.json")).resolve("@fontsource-variable/inter/package.json")
6372
6517
  );
6373
6518
  const fsAllow = [root, fontRoot];
@@ -6437,7 +6582,7 @@ function componentCandidates(options) {
6437
6582
  const dirs = /* @__PURE__ */ new Set();
6438
6583
  if (options.registryPath) {
6439
6584
  const registryPath = isAbsolute3(options.registryPath) ? options.registryPath : resolvePath(options.cwd, options.registryPath);
6440
- dirs.add(dirname(registryPath));
6585
+ dirs.add(dirname2(registryPath));
6441
6586
  }
6442
6587
  dirs.add(join5(options.cwd, "blocks"));
6443
6588
  const rendererCandidates = [
@@ -6488,10 +6633,10 @@ async function freePort(host) {
6488
6633
  return port;
6489
6634
  }
6490
6635
  function findPackageRoot() {
6491
- let dir = dirname(fileURLToPath(import.meta.url));
6636
+ let dir = dirname2(fileURLToPath(import.meta.url));
6492
6637
  for (; ; ) {
6493
6638
  if (existsSync4(join5(dir, "package.json"))) return dir;
6494
- const next = dirname(dir);
6639
+ const next = dirname2(dir);
6495
6640
  if (next === dir) throw new Error("Could not locate @contentbit/studio package root.");
6496
6641
  dir = next;
6497
6642
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contentbit/studio",
3
- "version": "2.0.0-next.0",
3
+ "version": "2.0.0-next.2",
4
4
  "description": "Local read-only dashboard for contentbit: a site's built pages, page context, template findings, and Markdown.",
5
5
  "keywords": [
6
6
  "contentbit",
@@ -57,9 +57,9 @@
57
57
  "tinyglobby": "^0.2.10",
58
58
  "tw-animate-css": "^1.4.0",
59
59
  "vite": "^8",
60
- "@contentbit/blocks": "2.0.0-next.0",
61
- "@contentbit/core": "2.0.0-next.0",
62
- "@contentbit/react": "2.0.0-next.0"
60
+ "@contentbit/blocks": "2.0.0-next.2",
61
+ "@contentbit/core": "2.0.0-next.2",
62
+ "@contentbit/react": "2.0.0-next.2"
63
63
  },
64
64
  "devDependencies": {
65
65
  "@testing-library/dom": "^10.4.2",
package/src/server/api.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { IncomingMessage, ServerResponse } from 'node:http'
2
+ import { pathsFromRoot } from '@contentbit/project'
2
3
 
3
4
  import { scanDocument, scanProject } from './scan.js'
4
5
  import { scanPage, scanSite } from './site.js'
@@ -12,63 +13,65 @@ export async function handleStudioApiRequest(
12
13
  if (!req.url) return false
13
14
  const url = new URL(req.url, 'http://contentbit.local')
14
15
  if (!url.pathname.startsWith('/api/')) return false
16
+ const root = options.cwd ?? process.cwd()
15
17
 
16
18
  try {
17
19
  if (req.method !== 'GET') {
18
- sendJson(res, 405, { error: 'Studio API is read-only.' })
20
+ sendJson(res, root, 405, { error: 'Studio API is read-only.' })
19
21
  return true
20
22
  }
21
23
 
22
24
  if (url.pathname === '/api/project') {
23
- sendJson(res, 200, await scanProject(options))
25
+ sendJson(res, root, 200, await scanProject(options))
24
26
  return true
25
27
  }
26
28
 
27
29
  if (url.pathname === '/api/site') {
28
- sendJson(res, 200, await scanSite(options))
30
+ sendJson(res, root, 200, await scanSite(options))
29
31
  return true
30
32
  }
31
33
 
32
34
  if (url.pathname === '/api/page') {
33
35
  const path = url.searchParams.get('path')
34
36
  if (!path) {
35
- sendJson(res, 400, { error: 'Missing ?path=' })
37
+ sendJson(res, root, 400, { error: 'Missing ?path=' })
36
38
  return true
37
39
  }
38
40
  const page = await scanPage(options, path)
39
41
  if (!page) {
40
- sendJson(res, 404, { error: `The build has no page ${path}.` })
42
+ sendJson(res, root, 404, { error: `The build has no page ${path}.` })
41
43
  return true
42
44
  }
43
- sendJson(res, 200, page)
45
+ sendJson(res, root, 200, page)
44
46
  return true
45
47
  }
46
48
 
47
49
  if (url.pathname === '/api/document') {
48
50
  const path = url.searchParams.get('path')
49
51
  if (!path) {
50
- sendJson(res, 400, { error: 'Missing ?path=' })
52
+ sendJson(res, root, 400, { error: 'Missing ?path=' })
51
53
  return true
52
54
  }
53
55
  const document = await scanDocument(options, path)
54
56
  if (!document) {
55
- sendJson(res, 404, { error: 'Document is not in the configured content set.' })
57
+ sendJson(res, root, 404, { error: 'Document is not in the configured content set.' })
56
58
  return true
57
59
  }
58
- sendJson(res, 200, document)
60
+ sendJson(res, root, 200, document)
59
61
  return true
60
62
  }
61
63
 
62
- sendJson(res, 404, { error: 'Unknown Studio API route.' })
64
+ sendJson(res, root, 404, { error: 'Unknown Studio API route.' })
63
65
  return true
64
66
  } catch (err) {
65
- sendJson(res, 500, { error: err instanceof Error ? err.message : String(err) })
67
+ sendJson(res, root, 500, { error: err instanceof Error ? err.message : String(err) })
66
68
  return true
67
69
  }
68
70
  }
69
71
 
70
- function sendJson(res: ServerResponse, status: number, body: unknown): void {
72
+ /** The UI shows and copies the paths a response holds, so each is from the project root. */
73
+ function sendJson(res: ServerResponse, root: string, status: number, body: unknown): void {
71
74
  res.statusCode = status
72
75
  res.setHeader('content-type', 'application/json; charset=utf-8')
73
- res.end(JSON.stringify(body, null, 2))
76
+ res.end(JSON.stringify(body, pathsFromRoot(root), 2))
74
77
  }
@@ -1,11 +1,11 @@
1
- import { mkdir, mkdtemp, symlink, writeFile } from 'node:fs/promises'
2
- import { tmpdir } from 'node:os'
1
+ import { mkdir, symlink, writeFile } from 'node:fs/promises'
3
2
  import { dirname, join } from 'node:path'
4
3
  import { fileURLToPath, pathToFileURL } from 'node:url'
5
4
  import { afterEach, expect, test } from 'vitest'
6
5
 
7
6
  import { scanDocument, scanProject } from './scan'
8
7
  import { startStudio, type StudioServer } from './index'
8
+ import { tempDir } from '../../../../test/temp-dir.js'
9
9
 
10
10
  const root = fileURLToPath(new URL('../../../..', import.meta.url))
11
11
  const runningServers: StudioServer[] = []
@@ -523,7 +523,7 @@ export function Callout() { return createElement('aside', { 'data-project-styled
523
523
  })
524
524
 
525
525
  async function fixture(files: Record<string, string>): Promise<string> {
526
- const dir = await mkdtemp(join(tmpdir(), 'cb-studio-'))
526
+ const dir = await tempDir('cb-studio-')
527
527
  for (const [path, content] of Object.entries(files)) {
528
528
  const fullPath = join(dir, path)
529
529
  await mkdir(dirname(fullPath), { recursive: true })
@@ -6,7 +6,7 @@ import {
6
6
  type SeoPage,
7
7
  } from '@contentbit/core'
8
8
  import { relativeInside } from '@contentbit/project'
9
- import { basename } from 'node:path'
9
+ import { basename, normalize } from 'node:path'
10
10
 
11
11
  import { renderStudioPreview } from './preview.js'
12
12
  import { loadSiteOrJoinInFlight, pagesByFile } from './site.js'
@@ -248,10 +248,10 @@ function statusFor(findings: StudioFileSummary['findings']): StudioStatus {
248
248
  }
249
249
 
250
250
  function findAllowedFile(context: ScanContext, cwd: string, requestedPath: string): string | null {
251
+ const requested = normalize(requestedPath)
251
252
  return (
252
- context.files.find(
253
- (file) => file === requestedPath || relativePath(cwd, file) === requestedPath,
254
- ) ?? null
253
+ context.files.find((file) => file === requested || relativePath(cwd, file) === requested) ??
254
+ null
255
255
  )
256
256
  }
257
257
 
@@ -1,13 +1,13 @@
1
- import { mkdir, mkdtemp, realpath, writeFile } from 'node:fs/promises'
1
+ import { mkdir, realpath, writeFile } from 'node:fs/promises'
2
2
  import { connect } from 'node:net'
3
- import { tmpdir } from 'node:os'
4
3
  import { dirname, join } from 'node:path'
5
4
  import { afterEach, assert, expect, test } from 'vitest'
6
5
 
7
6
  import { startStudio, type StudioServer } from './index'
8
7
  import { scanDocument, scanProject } from './scan'
9
- import { scanPage, scanSite } from './site'
10
- import type { StudioOptions } from './types'
8
+ import { scanPage, scanSite, type StudioPage, type StudioSite } from './site'
9
+ import type { StudioDocument, StudioOptions, StudioProject } from './types'
10
+ import { tempDir } from '../../../../test/temp-dir.js'
11
11
 
12
12
  const runningServers: StudioServer[] = []
13
13
 
@@ -298,7 +298,7 @@ test('startStudio serves the site and page context endpoints from the build fold
298
298
  expect(await site.json()).toMatchObject({
299
299
  kind: 'built',
300
300
  context: {
301
- build: join(dir, 'web'),
301
+ build: 'web',
302
302
  origin: { url: 'https://www.bakery.example', source: 'flag' },
303
303
  pages: { length: 5 },
304
304
  },
@@ -310,6 +310,35 @@ test('startStudio serves the site and page context endpoints from the build fold
310
310
  expect(noPath.status).toBe(400)
311
311
  })
312
312
 
313
+ test('every path in a Studio API response is from the project root, and a document opens by it', async () => {
314
+ const dir = await fixture(bakery)
315
+ const server = await startStudio({ ...options(dir), port: 0, open: false })
316
+ runningServers.push(server)
317
+ const get = async (path: string) => {
318
+ const response = await fetch(new URL(path, server.url))
319
+ expect(response.status, path).toBe(200)
320
+ return response.text()
321
+ }
322
+ const query = (route: string, path: string) => `${route}?path=${encodeURIComponent(path)}`
323
+
324
+ const project = await get('/api/project')
325
+ const site = await get('/api/site')
326
+ const built = JSON.parse(site) as Extract<StudioSite, { kind: 'built' }>
327
+ const pages = await Promise.all(
328
+ built.context.pages.map(({ path }) => get(query('/api/page', path))),
329
+ )
330
+ const files = (JSON.parse(project) as StudioProject).files.map(({ path }) => path)
331
+ const documents = await Promise.all(files.map((file) => get(query('/api/document', file))))
332
+ const sourdough = JSON.parse(await get(query('/api/page', '/blog/sourdough/'))) as StudioPage
333
+ const rye = JSON.parse(await get(query('/api/document', 'content/blog/rye.md'))) as StudioDocument
334
+
335
+ expect(sourdough.context.source?.file).toBe('content/blog/sourdough.md')
336
+ await get(query('/api/document', sourdough.context.source?.file ?? ''))
337
+ expect(rye.seoBrief?.target.path).toBe('content/blog/rye.md')
338
+ expect(rye.seoBrief?.relatedPages.map(({ path }) => path)).toEqual(['content/blog/spelt.md'])
339
+ for (const body of [project, site, ...pages, ...documents]) expect(body).not.toContain(dir)
340
+ })
341
+
313
342
  test('a request whose URL Studio cannot parse gets an error, and Studio keeps serving', async () => {
314
343
  const dir = await fixture(bakery)
315
344
  const server = await startStudio({ ...options(dir), port: 0, open: false })
@@ -345,7 +374,7 @@ function withoutMarkdown(files: Record<string, string>): Record<string, string>
345
374
  }
346
375
 
347
376
  async function fixture(files: Record<string, string>): Promise<string> {
348
- const dir = await realpath(await mkdtemp(join(tmpdir(), 'cb-studio-site-')))
377
+ const dir = await realpath(await tempDir('cb-studio-site-'))
349
378
  for (const [path, content] of Object.entries(files)) {
350
379
  const fullPath = join(dir, path)
351
380
  await mkdir(dirname(fullPath), { recursive: true })