@kaynooo/cli-page 0.0.1 → 0.0.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.
Files changed (3) hide show
  1. package/README.md +3 -0
  2. package/dist/cli.js +70 -14
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -15,8 +15,11 @@ bun install -g @kaynooo/cli-page
15
15
 
16
16
  Targets are HTML files or URLs already served: `page` never starts or builds an app. The widths are 1440 and 400 unless `-w 1280,768,375` says otherwise. PNGs go next to a file, into `-o <dir>`, or under `~/.cache/kaynooo-page` for a URL.
17
17
 
18
+ A page behind a login takes `--cookie name=value`, `-H "Authorization: Bearer <token>"` (sent to the target's origin only, never to the third-party scripts and fonts it loads) or `--storage-state <file>`, a Playwright storage state with cookies and localStorage. Both commands take them; a malformed value is refused without being echoed.
19
+
18
20
  What `check` reports:
19
21
 
22
+ - `redirect`: the page landed on another URL, a login page say, so every other line is about that page. `diff` says so on stderr instead.
20
23
  - `overflow`: the page scrolls sideways; the up to three elements where it starts, with their right edge.
21
24
  - `console`: console errors and uncaught exceptions. `request`: requests that failed or answered 4xx/5xx. Both once per target, at the first width they show at.
22
25
  - `font`: text drawn in another font than its `font-family` asks for, naming the font Chromium drew it with (CDP `CSS.getPlatformFontsForNode`): a named family that is not available, or a generic one such as `system-ui` resolving to a monospace font.
package/dist/cli.js CHANGED
@@ -352,6 +352,9 @@ function marked(mark, text, stream, detail, env = process6.env) {
352
352
  }
353
353
  return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
354
354
  }
355
+ function warn(text, detail) {
356
+ console.error(marked("warn", text, process6.stderr, detail));
357
+ }
355
358
  function problem(text, detail) {
356
359
  console.error(marked("problem", text, process6.stderr, detail));
357
360
  }
@@ -1507,8 +1510,35 @@ function targetOf(given, out) {
1507
1510
  const name = basename(path).replace(HTML_EXT, "");
1508
1511
  return { label: given, url: pathToFileURL(path).href, stem: join7(out === undefined ? dirname4(path) : resolve4(out), name) };
1509
1512
  }
1510
- async function open(browser, url, width, prepare) {
1511
- const context = await browser.newContext({ viewport: { width, height: 900 }, deviceScaleFactor: 1, hasTouch: width < PHONE_WIDTH, isMobile: false });
1513
+ function sessionOf(values) {
1514
+ const cookies = (values.cookie ?? []).map((cookie) => {
1515
+ const at = cookie.indexOf("=");
1516
+ if (at < 1)
1517
+ badUsage("--cookie takes name=value");
1518
+ return { name: cookie.slice(0, at), value: cookie.slice(at + 1) };
1519
+ });
1520
+ const headers = {};
1521
+ for (const header of values.header ?? []) {
1522
+ if (!HEADER_LINE.test(header))
1523
+ badUsage('-H takes "Name: value"');
1524
+ const at = header.indexOf(":");
1525
+ headers[header.slice(0, at).trim().toLowerCase()] = header.slice(at + 1).trim();
1526
+ }
1527
+ const storageState = values["storage-state"];
1528
+ if (storageState !== undefined && !existsSync3(storageState))
1529
+ fail(`--storage-state ${storageState} does not exist`);
1530
+ return { cookies, headers, ...storageState === undefined ? {} : { storageState } };
1531
+ }
1532
+ async function open(browser, url, width, session, prepare) {
1533
+ const context = await browser.newContext({ viewport: { width, height: 900 }, deviceScaleFactor: 1, hasTouch: width < PHONE_WIDTH, isMobile: false, ...session.storageState === undefined ? {} : { storageState: session.storageState } });
1534
+ if (HTTP_URL.test(url)) {
1535
+ if (session.cookies.length > 0)
1536
+ await context.addCookies(session.cookies.map((cookie) => ({ ...cookie, url })));
1537
+ if (Object.keys(session.headers).length > 0) {
1538
+ const { origin } = new URL(url);
1539
+ await context.route((requested) => requested.origin === origin, async (route) => route.continue({ headers: { ...route.request().headers(), ...session.headers } }));
1540
+ }
1541
+ }
1512
1542
  const page = await context.newPage();
1513
1543
  await prepare?.(page);
1514
1544
  await page.goto(url, { waitUntil: "load", timeout: 30000 });
@@ -1516,7 +1546,15 @@ async function open(browser, url, width, prepare) {
1516
1546
  await page.waitForLoadState("networkidle", { timeout: 5000 });
1517
1547
  } catch {}
1518
1548
  await inPage(page, "measure", "fontsReady");
1519
- return { context, page };
1549
+ return { context, page, landed: page.url() };
1550
+ }
1551
+ function redirectedTo(asked, landed) {
1552
+ const bare = (url) => {
1553
+ const parsed = new URL(url);
1554
+ parsed.hash = "";
1555
+ return parsed.href;
1556
+ };
1557
+ return bare(asked) === bare(landed) ? undefined : landed;
1520
1558
  }
1521
1559
  async function shoot(page, path) {
1522
1560
  const options = { ...path === undefined ? {} : { path }, fullPage: true, animations: "disabled", caret: "hide" };
@@ -1526,15 +1564,21 @@ async function shoot(page, path) {
1526
1564
  return page.screenshot(options);
1527
1565
  }
1528
1566
  }
1529
- var HTTP_URL, HTML_EXT, UNSAFE, EDGE_DASHES, PHONE_WIDTH = 600, SYSTEM_CHROMES;
1567
+ var HTTP_URL, HEADER_LINE, HTML_EXT, UNSAFE, EDGE_DASHES, PHONE_WIDTH = 600, SYSTEM_CHROMES, SESSION_OPTIONS;
1530
1568
  var init_browser = __esm(() => {
1531
1569
  init_src();
1532
1570
  init_inpage();
1533
1571
  HTTP_URL = /^https?:\/\//;
1572
+ HEADER_LINE = /^[\w!#$%&'*+.^`|~-]+:/;
1534
1573
  HTML_EXT = /\.html?$/;
1535
1574
  UNSAFE = /[^\w.-]+/g;
1536
1575
  EDGE_DASHES = /^-+|-+$/g;
1537
1576
  SYSTEM_CHROMES = ["/usr/bin/chromium", "/usr/bin/chromium-browser", "/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/usr/bin/brave", "/usr/bin/brave-browser"];
1577
+ SESSION_OPTIONS = {
1578
+ cookie: { type: "string", multiple: true, description: "name=value, a cookie for a URL target's site, repeatable" },
1579
+ header: { type: "string", short: "H", multiple: true, description: `"Name: value", a header sent with every request to a URL target's origin and nowhere else, repeatable` },
1580
+ "storage-state": { type: "string", description: "a Playwright storage state file (cookies and localStorage) every page starts from" }
1581
+ };
1538
1582
  });
1539
1583
 
1540
1584
  // src/fonts.ts
@@ -1670,7 +1714,7 @@ async function check(args) {
1670
1714
  const { values, positionals } = parse(args, USAGE, OPTIONS, {
1671
1715
  positionals: ["<file|url>..."],
1672
1716
  exits: EXITS,
1673
- examples: [["page check mockup.html", "mockup-1440.png and mockup-400.png beside it, then the defects"], "page check http://localhost:5173/settings -w 1280,768,375 -o shots", "page check index.html --skip font,padding --json"]
1717
+ examples: [["page check mockup.html", "mockup-1440.png and mockup-400.png beside it, then the defects"], ["page check http://localhost:5173/settings --cookie session=<value>", "a page behind a login"], "page check http://localhost:5173/settings -w 1280,768,375 -o shots", "page check index.html --skip font,padding --json"]
1674
1718
  });
1675
1719
  const widths = widthsOf(values.widths);
1676
1720
  const skipped = new Set(values.skip?.split(",").map((kind) => kind.trim()) ?? []);
@@ -1678,6 +1722,7 @@ async function check(args) {
1678
1722
  if (unknown !== undefined)
1679
1723
  badUsage(`--skip takes ${KINDS.join(", ")}, not ${unknown}`);
1680
1724
  const targets = positionals.map((given) => targetOf(given, values.out));
1725
+ const session = sessionOf(values);
1681
1726
  const shots = [];
1682
1727
  const findings = [];
1683
1728
  const failed = [];
@@ -1690,7 +1735,7 @@ async function check(args) {
1690
1735
  const heard = [];
1691
1736
  let loaded;
1692
1737
  try {
1693
- loaded = await open(browser, target.url, width, async (page) => {
1738
+ loaded = await open(browser, target.url, width, session, async (page) => {
1694
1739
  listen(page, heard);
1695
1740
  await beforeLoad(page, "measure", "watchShifts");
1696
1741
  });
@@ -1701,7 +1746,10 @@ async function check(args) {
1701
1746
  `)) : message });
1702
1747
  break;
1703
1748
  }
1704
- const { context, page } = loaded;
1749
+ const { context, page, landed } = loaded;
1750
+ const redirect = redirectedTo(target.url, landed);
1751
+ if (redirect !== undefined)
1752
+ heard.unshift({ kind: "redirect", message: `landed on ${shortUrl(redirect)}` });
1705
1753
  const file = `${target.stem}-${width}.png`;
1706
1754
  mkdirSync2(dirname5(file), { recursive: true });
1707
1755
  await shoot(page, file);
@@ -1742,20 +1790,22 @@ var init_check = __esm(() => {
1742
1790
  init_fonts();
1743
1791
  init_inpage();
1744
1792
  init_report2();
1745
- KINDS = ["overflow", "console", "request", "font", "tap-target", "padding", "image", "layout-shift"];
1746
- ONCE = new Set(["console", "request", "font"]);
1793
+ KINDS = ["redirect", "overflow", "console", "request", "font", "tap-target", "padding", "image", "layout-shift"];
1794
+ ONCE = new Set(["redirect", "console", "request", "font"]);
1747
1795
  EXITS = [[0, "nothing found"], [1, "a defect was found"], [2, "a usage error, or a target that would not load"]];
1748
1796
  USAGE = `page check <file|url>...
1749
1797
 
1750
1798
  Opens each HTML file or URL in a local Chromium at every width, writes a full-page PNG per width (next to a file as <name>-<width>.png, into --out, or the cache folder for a URL) and prints its path, then one line per defect: <target> <width>px <kind> <selector>: <measure>.
1751
- Kinds: overflow (the page scrolls sideways; the elements where it starts), console (errors and uncaught exceptions), request (failed, or answered 4xx/5xx), font (text drawn in another font than its stack asks for, naming the one drawn), tap-target (under 44px below ${PHONE_WIDTH}px wide, under 24px otherwise; a link inside a sentence is exempt), padding (text touching the border or background edge of its box), image (did not load), layout-shift (a score above 0.1).
1752
- It never starts or builds an app: give it a file or a URL already served. Chromium comes from PAGE_CHROMIUM, ~/.cache/ms-playwright or /usr/bin, never downloaded.
1799
+ Kinds: redirect (the page landed elsewhere, a login page say, so what follows is about that page), overflow (the page scrolls sideways; the elements where it starts), console (errors and uncaught exceptions), request (failed, or answered 4xx/5xx), font (text drawn in another font than its stack asks for, naming the one drawn), tap-target (under 44px below ${PHONE_WIDTH}px wide, under 24px otherwise; a link inside a sentence is exempt), padding (text touching the border or background edge of its box), image (did not load), layout-shift (a score above 0.1).
1800
+ It never starts or builds an app: give it a file or a URL already served. A page behind a login takes --cookie, -H or --storage-state; a header goes to the target's origin alone.
1801
+ Chromium comes from PAGE_CHROMIUM, ~/.cache/ms-playwright or /usr/bin, never downloaded.
1753
1802
 
1754
1803
  Exits 0 when nothing is found, 1 when something is, 2 on a usage error or when a target would not load.`;
1755
1804
  OPTIONS = {
1756
1805
  widths: { type: "string", short: "w", description: "viewport widths, comma separated (1440,400)" },
1757
1806
  out: { type: "string", short: "o", description: "folder the PNGs go to instead of next to each file" },
1758
1807
  skip: { type: "string", description: `kinds left out, comma separated: ${KINDS.join(", ")}` },
1808
+ ...SESSION_OPTIONS,
1759
1809
  json: jsonOption("{shots: [{target, width, path}], findings: [{target, width, kind, selector, message}], failed: [{target, error}]}")
1760
1810
  };
1761
1811
  });
@@ -1768,8 +1818,11 @@ __export(exports_diff, {
1768
1818
  import { mkdirSync as mkdirSync3 } from "fs";
1769
1819
  import { dirname as dirname6 } from "path";
1770
1820
  import process20 from "process";
1771
- async function capture(browser, url, width) {
1772
- const { context, page } = await open(browser, url, width);
1821
+ async function capture(browser, target, width, session) {
1822
+ const { context, page, landed } = await open(browser, target.url, width, session);
1823
+ const redirect = redirectedTo(target.url, landed);
1824
+ if (redirect !== undefined)
1825
+ warn(`${target.label} landed on ${redirect} at ${width}px`, "the shot is of that page");
1773
1826
  try {
1774
1827
  return await shoot(page);
1775
1828
  } finally {
@@ -1790,6 +1843,7 @@ async function diff(args) {
1790
1843
  const threshold = wholeNumber(values.threshold, "threshold", THRESHOLD, 0);
1791
1844
  const mockup = targetOf(mockupGiven, values.out);
1792
1845
  const built = targetOf(builtGiven, values.out);
1846
+ const session = sessionOf(values);
1793
1847
  const results = [];
1794
1848
  const findings = [];
1795
1849
  const path = role("path", process20.stdout);
@@ -1797,7 +1851,7 @@ async function diff(args) {
1797
1851
  try {
1798
1852
  const blank = await browser.newPage();
1799
1853
  for (const width of widths) {
1800
- const [left, right] = await Promise.all([capture(browser, mockup.url, width), capture(browser, built.url, width)]);
1854
+ const [left, right] = await Promise.all([capture(browser, mockup, width, session), capture(browser, built, width, session)]);
1801
1855
  const compared = await inPage(blank, "compare", "compareImages", { mockup: left.toString("base64"), built: right.toString("base64"), threshold: Math.min(threshold, 255) });
1802
1856
  const side = `${built.stem}-side-${width}.png`;
1803
1857
  const overlay = `${built.stem}-diff-${width}.png`;
@@ -1834,6 +1888,7 @@ var init_diff = __esm(() => {
1834
1888
  USAGE2 = `page diff <mockup> <built>
1835
1889
 
1836
1890
  Shoots the mockup and the built page (HTML files or URLs) full-page at every width, then writes two PNGs per width next to the built file, into --out, or the cache folder for a URL: <name>-side-<width>.png, the mockup left and the built page right, and <name>-diff-<width>.png, the built page faded with every differing pixel in red. The differing regions are boxed and numbered on both, then printed one line each: <built> <width>px region <n>: <width>\xD7<height>px at <x>,<y>.
1891
+ A page behind a login takes --cookie, -H or --storage-state, as page check does; a page landing elsewhere is warned about on stderr.
1837
1892
  A pixel differs when a colour channel moves by more than --threshold (${THRESHOLD} of 255); a lone differing pixel in an 8px cell is taken for antialiasing and left out.
1838
1893
 
1839
1894
  Exits 0 when both look the same at every width, 1 when a region differs or a page would not load, 2 on a usage error.`;
@@ -1841,6 +1896,7 @@ Exits 0 when both look the same at every width, 1 when a region differs or a pag
1841
1896
  widths: { type: "string", short: "w", description: "viewport widths, comma separated (1440,400)" },
1842
1897
  out: { type: "string", short: "o", description: "folder the PNGs go to instead of next to the built file" },
1843
1898
  threshold: { type: "string", description: `largest per-channel difference still counted as the same pixel, 0 to 255 (${THRESHOLD})` },
1899
+ ...SESSION_OPTIONS,
1844
1900
  json: jsonOption("[{width, side, overlay, mockupHeight, builtHeight, differing, regions: [{x, y, width, height}]}]")
1845
1901
  };
1846
1902
  });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-page",
3
3
  "type": "module",
4
- "version": "0.0.1",
4
+ "version": "0.0.2",
5
5
  "description": "page: shoots HTML files or URLs at several widths in a local Chromium and reports their layout defects one line each, or diffs a built page against its mockup.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",