@reqvire-org/ads-guard 0.5.4 → 0.5.6

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
@@ -140,3 +140,12 @@ application passes data, never plain markup or an HTML string. Plain markup in
140
140
  application source is `design-usage/local-markup`, and injecting an HTML string
141
141
  is `design-usage/design-prop`. Adapt Markdown, HTML (parsed and sanitised) or
142
142
  rich text to the tree the design system's content pattern takes.
143
+
144
+ ## External components
145
+
146
+ When the design system declares external components (`external({ from, renders })` in `externals/*.ads.ts`), the
147
+ guard renders each once on the server with the application's own React and checks that it renders one element of
148
+ the declared kind, puts the class it is given on it, and brings no `style` of its own. A library that does not
149
+ (an image component that styles its element) is reported as `external-mismatch`. An application without
150
+ `react-dom/server` reports each external as one to verify by hand. Nothing is configured.
151
+
@@ -449,9 +449,9 @@ function readGuardConfig2(root) {
449
449
  }
450
450
 
451
451
  // src/guard/run.mts
452
- import { existsSync as existsSync3, readFileSync as readFileSync4 } from "node:fs";
453
- import { createRequire } from "node:module";
454
- import path5 from "node:path";
452
+ import { existsSync as existsSync3, readFileSync as readFileSync5 } from "node:fs";
453
+ import { createRequire as createRequire2 } from "node:module";
454
+ import path6 from "node:path";
455
455
 
456
456
  // src/guard/files.mts
457
457
  import { readdirSync, statSync as statSync2 } from "node:fs";
@@ -492,27 +492,100 @@ function guardScope(root, include, exclude, designSystemFolder) {
492
492
  return { files: [...files].sort(), excluded: [...excluded].map(([name, count]) => ({ path: name, files: count })), tests, designSystem };
493
493
  }
494
494
 
495
+ // src/guard/externals.mts
496
+ import { readdirSync as readdirSync2, readFileSync as readFileSync4, statSync as statSync3 } from "node:fs";
497
+ import { createRequire } from "node:module";
498
+ import path5 from "node:path";
499
+ import { pathToFileURL } from "node:url";
500
+ var MARK = /export \{ ([\w$]+)(?: as ([\w$]+))? \} from "([^"]+)";\n\/\* ads-external (\{[^*]*\}) \*\//g;
501
+ var PROBE = "ads-external-probe";
502
+ function declared(folder) {
503
+ const found = [];
504
+ const visit = (directory, depth) => {
505
+ if (depth > 6)
506
+ return;
507
+ for (const entry of readdirSync2(directory)) {
508
+ if (entry === "node_modules" || entry.startsWith("."))
509
+ continue;
510
+ const file = path5.join(directory, entry);
511
+ if (statSync3(file).isDirectory())
512
+ visit(file, depth + 1);
513
+ else if (/\.ads\.[cm]?[jt]s$/.test(entry)) {
514
+ for (const match of readFileSync4(file, "utf8").matchAll(MARK)) {
515
+ const mark = JSON.parse(match[4] ?? "{}");
516
+ if (mark.name !== undefined && mark.renders !== undefined)
517
+ found.push({ name: mark.name, exportName: match[1] ?? "default", from: match[3] ?? "", renders: mark.renders });
518
+ }
519
+ }
520
+ }
521
+ };
522
+ visit(folder, 0);
523
+ return found;
524
+ }
525
+ async function verifyExternals(root, entry) {
526
+ const externals = declared(path5.dirname(entry));
527
+ if (externals.length === 0)
528
+ return [];
529
+ const require2 = createRequire(path5.join(root, "package.json"));
530
+ let react;
531
+ let server;
532
+ try {
533
+ react = require2("react");
534
+ server = require2("react-dom/server");
535
+ } catch {
536
+ return externals.map((external) => ({ ...external, problem: "the application has no react and react-dom/server to render it with: verify it by hand" }));
537
+ }
538
+ const checks = [];
539
+ for (const external of externals) {
540
+ let problem = null;
541
+ try {
542
+ const module = await import(pathToFileURL(require2.resolve(external.from)).href);
543
+ const exported = external.exportName === "default" ? module["default"]?.["default"] ?? module["default"] : module[external.exportName];
544
+ if (exported === undefined)
545
+ problem = `${external.from} exports no ${external.exportName}`;
546
+ else {
547
+ const markup = server.renderToStaticMarkup(react.createElement(exported, { className: PROBE, href: "/", children: "probe" })).replace(/^(?:<link[^>]*\brel="(?:preload|modulepreload|preconnect|dns-prefetch)"[^>]*\/?>)+/, "");
548
+ const root = /^<([a-z][\w-]*)([^>]*)>/.exec(markup);
549
+ const closes = root === null ? false : markup.endsWith(`</${root[1]}>`) || markup.endsWith("/>");
550
+ if (root === null || !closes)
551
+ problem = `it renders ${markup.slice(0, 80)}, not one element`;
552
+ else if (root[1] !== external.renders)
553
+ problem = `it renders <${root[1]}>, not the declared <${external.renders}>`;
554
+ else if (!new RegExp(`class="[^"]*\\b${PROBE}\\b`).test(root[2] ?? ""))
555
+ problem = "it does not put the class it is given on its element";
556
+ else if (/\sstyle="/.test(root[2] ?? ""))
557
+ problem = "it brings a style of its own: it carries design (use its data function instead)";
558
+ }
559
+ } catch (error) {
560
+ problem = `it could not be rendered: ${error instanceof Error ? error.message.split(`
561
+ `)[0] : String(error)}`;
562
+ }
563
+ checks.push({ name: external.name, from: external.from, renders: external.renders, problem });
564
+ }
565
+ return checks;
566
+ }
567
+
495
568
  // src/guard/run.mts
496
569
  var ENTRY_NAMES = ["index.ts", "index.tsx", "index.mts", "index.js", "index.mjs"];
497
570
  function entryFile(root, config) {
498
571
  if (config.entry !== undefined) {
499
- const configured = path5.resolve(root, config.entry);
572
+ const configured = path6.resolve(root, config.entry);
500
573
  return ok(configured);
501
574
  }
502
575
  const specifier = config.designSystem;
503
576
  if (specifier.startsWith(".")) {
504
- const target = path5.resolve(root, specifier);
505
- const found = [target, ...ENTRY_NAMES.map((name) => path5.join(target, name))].find((candidate) => existsSync3(candidate) && /\.[cm]?[jt]sx?$/.test(candidate));
577
+ const target = path6.resolve(root, specifier);
578
+ const found = [target, ...ENTRY_NAMES.map((name) => path6.join(target, name))].find((candidate) => existsSync3(candidate) && /\.[cm]?[jt]sx?$/.test(candidate));
506
579
  return found === undefined ? err(`"designSystem" is ${specifier}, and no entry file is at ${target}.`) : ok(found);
507
580
  }
508
581
  try {
509
- return ok(createRequire(path5.join(root, "package.json")).resolve(specifier));
582
+ return ok(createRequire2(path6.join(root, "package.json")).resolve(specifier));
510
583
  } catch {
511
584
  return err(`"designSystem" is ${specifier}, which does not resolve as a package from ${root}. If it is an alias of the bundler or of TypeScript, add "entry" with the path of the design system's public entry file.`);
512
585
  }
513
586
  }
514
587
  async function runGuard2(root) {
515
- const absolute = path5.resolve(root);
588
+ const absolute = path6.resolve(root);
516
589
  const config = readGuardConfig2(absolute);
517
590
  if (config.kind === "err")
518
591
  return config;
@@ -520,19 +593,21 @@ async function runGuard2(root) {
520
593
  if (located.kind === "err")
521
594
  return err([located.error]);
522
595
  const entry = await designSystemEntry2(config.value.designSystem, located.value);
523
- const folder = path5.dirname(located.value);
524
- const scope = guardScope(absolute, config.value.include, config.value.exclude, folder.startsWith(absolute + path5.sep) ? folder : null);
525
- const sources = scope.files.map((file) => ({ file, text: readFileSync4(path5.join(absolute, file), "utf8") }));
596
+ const folder = path6.dirname(located.value);
597
+ const scope = guardScope(absolute, config.value.include, config.value.exclude, folder.startsWith(absolute + path6.sep) ? folder : null);
598
+ const sources = scope.files.map((file) => ({ file, text: readFileSync5(path6.join(absolute, file), "utf8") }));
526
599
  const findings = await checkDesignUsage2(sources, entry, { components: config.value.allow, metadata: true });
527
- const inside = located.value.startsWith(absolute + path5.sep);
600
+ const inside = located.value.startsWith(absolute + path6.sep);
601
+ const externals = await verifyExternals(absolute, located.value);
528
602
  return ok({
529
- ok: findings.length === 0,
603
+ ok: findings.length === 0 && externals.every((item) => item.problem === null),
530
604
  designSystem: config.value.designSystem,
531
- entry: inside ? path5.relative(absolute, located.value).split(path5.sep).join("/") : located.value,
605
+ entry: inside ? path6.relative(absolute, located.value).split(path6.sep).join("/") : located.value,
532
606
  patterns: entry.patterns.size,
533
607
  checked: scope.files.length,
534
608
  scope: { excluded: scope.excluded, tests: scope.tests, designSystem: scope.designSystem },
535
- findings
609
+ findings,
610
+ externals
536
611
  });
537
612
  }
538
613
  function guardText2(report) {
@@ -548,8 +623,12 @@ function guardText2(report) {
548
623
  if (report.scope.designSystem > 0)
549
624
  left.push(`${report.scope.designSystem} file${report.scope.designSystem === 1 ? "" : "s"} of the design system`);
550
625
  const summary = `Checked ${report.checked} file${report.checked === 1 ? "" : "s"} against ${report.designSystem} (${report.patterns} pattern${report.patterns === 1 ? "" : "s"})${left.length ? `; not checked: ${left.join("; ")}` : ""}.`;
551
- const verdict = report.ok ? "The source uses the design system only." : `${report.findings.length} finding${report.findings.length === 1 ? "" : "s"}.`;
552
- return [...lines, summary, verdict].join(`
626
+ const externals = report.externals.map((item) => item.problem === null ? `external ${item.name} (${item.from}) renders <${item.renders}> as declared` : `external ${item.name} (${item.from}) external-mismatch
627
+ ${item.problem}
628
+ Declare what it renders, or use a component that renders one element with the given class and no style of its own.`);
629
+ const failing = report.findings.length + report.externals.filter((item) => item.problem !== null).length;
630
+ const verdict = report.ok ? "The source uses the design system only." : `${failing} finding${failing === 1 ? "" : "s"}.`;
631
+ return [...lines, ...externals, summary, verdict].join(`
553
632
  `);
554
633
  }
555
634
 
package/dist/cli.mjs CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  GUARD_CONFIG_FILE2,
5
5
  runGuard2,
6
6
  guardText2
7
- } from "./chunk-9tgeqb4z.mjs";
7
+ } from "./chunk-63g3wrkz.mjs";
8
8
 
9
9
  // src/guard/cli.mts
10
10
  var HELP = `ads-guard [directory] [--json]
package/dist/index.mjs CHANGED
@@ -6,7 +6,7 @@ import {
6
6
  readGuardConfig2,
7
7
  runGuard2,
8
8
  guardText2
9
- } from "./chunk-9tgeqb4z.mjs";
9
+ } from "./chunk-63g3wrkz.mjs";
10
10
  export {
11
11
  GUARD_CONFIG_FILE2 as GUARD_CONFIG_FILE,
12
12
  checkDesignUsage2 as checkDesignUsage,
@@ -0,0 +1,10 @@
1
+ /** One external's verification. */
2
+ export interface ExternalCheck {
3
+ readonly name: string;
4
+ readonly from: string;
5
+ readonly renders: string;
6
+ /** `null`: it renders as declared. */
7
+ readonly problem: string | null;
8
+ }
9
+ /** Verifies each external the design system declares; empty when it declares none or the application has no React. */
10
+ export declare function verifyExternals(root: string, entry: string): Promise<readonly ExternalCheck[]>;
@@ -1,6 +1,7 @@
1
1
  import { type DesignUsageFinding } from "../design-usage.mts";
2
2
  import { type Result } from "../result.mts";
3
3
  import { type GuardScope } from "./files.mts";
4
+ import { type ExternalCheck } from "./externals.mts";
4
5
  /** A finished run. */
5
6
  export interface GuardReport {
6
7
  /** True when no file has a finding. */
@@ -13,6 +14,8 @@ export interface GuardReport {
13
14
  readonly checked: number;
14
15
  readonly scope: Omit<GuardScope, "files">;
15
16
  readonly findings: readonly DesignUsageFinding[];
17
+ /** The design system's declared externals, each rendered once with the application's React (./externals.mts). */
18
+ readonly externals: readonly ExternalCheck[];
16
19
  }
17
20
  /** Runs the guard for the application in `root`. An error is a problem with the configuration, not with the source. */
18
21
  export declare function runGuard(root: string): Promise<Result<GuardReport, readonly string[]>>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reqvire-org/ads-guard",
3
- "version": "0.5.4",
3
+ "version": "0.5.6",
4
4
  "description": "Confirms that an application's source does no design of its own and uses its ADS design system only.",
5
5
  "repository": {
6
6
  "type": "git",