@jskit-ai/jskit-catalog 0.2.150 → 0.2.152

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": "@jskit-ai/jskit-catalog",
3
- "version": "0.2.150",
3
+ "version": "0.2.152",
4
4
  "description": "Published metadata catalog for JSKIT package metadata.",
5
5
  "type": "module",
6
6
  "files": [
@@ -9,6 +9,7 @@ import { checkManifestCapabilities, formatManifestCapabilitiesReport } from "./m
9
9
  import { checkMaterial3, formatMaterial3Report } from "./material3.mjs";
10
10
  import { checkPackageNix, formatPackageNixReport } from "./package-nix.mjs";
11
11
  import { checkProject } from "./project-packages.mjs";
12
+ import { checkServerPaths, formatServerPathsReport } from "./server-paths.mjs";
12
13
  import { checkServerSetup, formatServerSetupReport } from "./server-setup.mjs";
13
14
  import { checkTestRuns, formatTestRunsReport } from "./testing/runs.mjs";
14
15
  import { checkTestSources, formatTestSourcesReport } from "./testing/sources.mjs";
@@ -42,6 +43,7 @@ export async function runProjectCheck({ projectRoot, additionalManifests }) {
42
43
  const nixPackage = await checkPackageNix({ projectRoot });
43
44
  const agents = await checkAgentsBlock({ projectRoot });
44
45
  const server = await checkServerSetup({ projectRoot });
46
+ const pages = await checkServerPaths({ projectRoot });
45
47
  const capacitor = await checkCapacitor({
46
48
  projectRoot,
47
49
  catalog,
@@ -62,8 +64,9 @@ export async function runProjectCheck({ projectRoot, additionalManifests }) {
62
64
  formatPackageNixReport(nixPackage),
63
65
  formatAgentsBlockReport(agents),
64
66
  formatServerSetupReport(server),
67
+ formatServerPathsReport(pages),
65
68
  formatCapacitorReport(capacitor)
66
69
  ].filter(Boolean);
67
- const ok = [result, ui, tests, sources, data, capabilities, nixPackage, agents, server, capacitor].every(({ ok: passed }) => passed);
70
+ const ok = [result, ui, tests, sources, data, capabilities, nixPackage, agents, server, pages, capacitor].every(({ ok: passed }) => passed);
68
71
  return { ok, report: reports.join("\n") };
69
72
  }
@@ -0,0 +1,162 @@
1
+ import { readdir, readFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ // The server-paths part of plain `jskit check`: the client network rules the linter applies to modules and Vue
5
+ // components, applied to the files it cannot read, the app's HTML pages (index.html and any other) and the Markdown
6
+ // sources its pages render. Each finding names the place:
7
+ // - client/server-path-binding: an address attribute (src, href, action, poster, data, formaction, srcset) or a
8
+ // Markdown link or image naming a server path (`/api...`), which inside an app reaches the app, not the server;
9
+ // - client/no-raw-network: an inline script reaching fetch, EventSource, WebSocket, XMLHttpRequest or sendBeacon;
10
+ // - client/no-service-worker: an inline script registering a service worker, which replaces push-web's;
11
+ // - client/no-native-plugin-import: an inline script importing a device plugin.
12
+ // An exception is the linter's: `<!-- readable-check: allow <rule> - <reason> -->` on the line before.
13
+
14
+ const GUIDE = "https://mobily-enterprises.github.io/jskit-ai/guide/framework/client-features";
15
+ const SKIPPED_DIRECTORIES = new Set(["node_modules", ".git", ".jskit", ".vite", "dist", "build", "coverage", "android", "ios",
16
+ "test", "tests", "test-results", "playwright-report"]);
17
+ const PAGE_FILE = /\.(?:html|md)$/u;
18
+ const SERVER_PATH = String.raw`/api(?:[/?#"'\s)]|$)`;
19
+
20
+ const RULES = Object.freeze([
21
+ {
22
+ rule: "server-path-binding",
23
+ pattern: new RegExp(String.raw`\b(?:src|href|action|poster|data|formaction|srcset)\s*=\s*["']?${SERVER_PATH}`, "giu"),
24
+ markdown: new RegExp(String.raw`\]\(\s*<?${SERVER_PATH}`, "gu"),
25
+ message: "names a server path the browser loads as it is: inside an app it reaches the app, not the server. Give " +
26
+ "the page its address from code, through serverUrl(), or signedUrl() / frameUrl() when the server checks who asks.",
27
+ section: "server-addresses-in-templates"
28
+ },
29
+ {
30
+ rule: "no-raw-network",
31
+ pattern: /(?<![\w$.])(?:(?:globalThis|window|self)\.)?(?:fetch\s*\(|new\s+(?:EventSource|WebSocket|XMLHttpRequest)\b)|\bnavigator\.sendBeacon\b/gu,
32
+ script: true,
33
+ message: "reaches the server with the browser's own network object, signed in on the web only: inside an app the " +
34
+ "page is on another site, with no cookie and no token. Move the script into a module that uses http-web.",
35
+ section: "network-calls"
36
+ },
37
+ {
38
+ rule: "no-service-worker",
39
+ pattern: /\bserviceWorker\s*\.\s*register\s*\(/gu,
40
+ script: true,
41
+ message: "registers a service worker, replacing the one push-web registers to show notifications; inside an app " +
42
+ "none runs. Add what the worker must do to push-web's worker.",
43
+ section: "service-workers"
44
+ },
45
+ {
46
+ rule: "no-native-plugin-import",
47
+ pattern: /["'](?:@capacitor\/|@capgo\/|@capawesome\/|@capacitor-mlkit\/|capacitor-widget-bridge)[^"']*["']/gu,
48
+ script: true,
49
+ message: "imports a device plugin directly. Resolve the JSKIT interface that wraps it instead, which works on the web too.",
50
+ section: "device-plugins"
51
+ }
52
+ ]);
53
+
54
+ // The HTML pages and Markdown sources under one tree, outside dependencies, builds, native projects and tests.
55
+ async function pageFiles(root, directory = root, files = []) {
56
+ let entries;
57
+ try {
58
+ entries = await readdir(directory, { withFileTypes: true });
59
+ } catch (error) {
60
+ if (error?.code === "ENOENT") return files;
61
+ throw error;
62
+ }
63
+ for (const entry of entries) {
64
+ const next = path.join(directory, entry.name);
65
+ if (entry.isDirectory()) {
66
+ if (!SKIPPED_DIRECTORIES.has(entry.name) && !entry.name.startsWith(".")) await pageFiles(root, next, files);
67
+ } else if (entry.isFile() && PAGE_FILE.test(entry.name) && !/^(?:README|CHANGELOG|AGENTS|CLAUDE|LICENSE)\b/iu.test(entry.name)) {
68
+ files.push(next);
69
+ }
70
+ }
71
+ return files;
72
+ }
73
+
74
+ // Where an app's pages come from: index.html at its root, and its src and public trees and each local package's src.
75
+ async function sourceFiles(root) {
76
+ const files = [];
77
+ try {
78
+ await readFile(path.join(root, "index.html"));
79
+ files.push(path.join(root, "index.html"));
80
+ } catch (error) {
81
+ if (error?.code !== "ENOENT") throw error;
82
+ }
83
+ const trees = [path.join(root, "src"), path.join(root, "public")];
84
+ for (const entry of await readdir(path.join(root, "packages"), { withFileTypes: true }).catch(() => [])) {
85
+ if (entry.isDirectory()) trees.push(path.join(root, "packages", entry.name, "src"));
86
+ }
87
+ for (const tree of trees) await pageFiles(tree, tree, files);
88
+ return files;
89
+ }
90
+
91
+ // The ranges of a page's inline scripts' code: what a <script> element holds, or a Markdown file's ```js blocks never
92
+ // (a code sample is no script).
93
+ function scriptRanges(text) {
94
+ const ranges = [];
95
+ for (const match of text.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/giu)) {
96
+ const start = match.index + match[0].indexOf(">") + 1;
97
+ ranges.push([start, start + match[1].length]);
98
+ }
99
+ return ranges;
100
+ }
101
+
102
+ // A Markdown file's fenced code blocks, whose text is a sample, never a page's address.
103
+ function fencedRanges(text) {
104
+ return [...text.matchAll(/^(```|~~~)[^\n]*\n[\s\S]*?^\1[ \t]*$/gmu)].map((match) => [match.index, match.index + match[0].length]);
105
+ }
106
+
107
+ const inside = (ranges, offset) => ranges.some(([start, end]) => offset >= start && offset < end);
108
+
109
+ function pageFindings(file, text) {
110
+ const markdown = file.endsWith(".md");
111
+ const scripts = scriptRanges(text);
112
+ const samples = markdown ? fencedRanges(text) : [];
113
+ const lineStarts = [0];
114
+ for (const match of text.matchAll(/\n/gu)) lineStarts.push(match.index + 1);
115
+ const lineOf = (offset) => {
116
+ let line = 0;
117
+ while (line + 1 < lineStarts.length && lineStarts[line + 1] <= offset) line += 1;
118
+ return line + 1;
119
+ };
120
+ const lines = text.split("\n");
121
+ const findings = [];
122
+ for (const { rule, pattern, markdown: markdownPattern, script, message, section } of RULES) {
123
+ const patterns = markdown && markdownPattern ? [pattern, markdownPattern] : [pattern];
124
+ for (const current of patterns) {
125
+ for (const match of text.matchAll(current)) {
126
+ if (inside(samples, match.index) || (script && !inside(scripts, match.index))) continue;
127
+ const line = lineOf(match.index);
128
+ if ((lines[line - 2] || "").includes(`readable-check: allow ${rule} - `)) continue;
129
+ findings.push({ line, rule: `client/${rule}`, message: `${match[0].trim()} ${message}`, guide: `${GUIDE}#${section}` });
130
+ }
131
+ }
132
+ }
133
+ return findings;
134
+ }
135
+
136
+ /**
137
+ * Checks the app's HTML pages and Markdown sources for what the client network rules refuse in code.
138
+ * @param {{ projectRoot: string }} options
139
+ * @returns {Promise<{ ok: boolean, findings: { file: string, line: number, rule: string, message: string, guide: string }[], pages: number }>}
140
+ */
141
+ async function checkServerPaths({ projectRoot }) {
142
+ const root = path.resolve(projectRoot);
143
+ const files = (await sourceFiles(root)).sort();
144
+ const findings = [];
145
+ for (const file of files) {
146
+ const relative = path.relative(root, file).split(path.sep).join("/");
147
+ for (const finding of pageFindings(file, await readFile(file, "utf8"))) findings.push({ file: relative, ...finding });
148
+ }
149
+ findings.sort((left, right) => left.file.localeCompare(right.file) || left.line - right.line);
150
+ return { ok: findings.length < 1, findings, pages: files.length };
151
+ }
152
+
153
+ function formatServerPathsReport(result) {
154
+ const lines = result.findings.flatMap(({ file, line, rule, message, guide }) => [`${file}:${line} ${rule} ${message}`, ` ${guide}`]);
155
+ lines.push(result.ok
156
+ ? `JSKIT pages name no server path and reach no server outside http-web in ${result.pages} HTML and Markdown file(s).`
157
+ : `JSKIT pages: ${result.findings.length} error(s). An HTML page or Markdown source reaches the server around ` +
158
+ "http-web, which inside an app reaches the app instead.");
159
+ return lines.join("\n");
160
+ }
161
+
162
+ export { checkServerPaths, formatServerPathsReport };