@blankgrimoire/testing 0.0.0-stage → 1.0.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 BlankGrimoire contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,74 @@
1
- # Temporary Holding Version
1
+ # @blankgrimoire/testing
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Node testing utilities for BlankGrimoire theme adapters:
4
+
5
+ - `NativeBridge` — emulates the `__native` bridge with an HTTP allowlist.
6
+ - `MockServer` — loopback HTTP server bound to `127.0.0.1` for synthetic pages.
7
+ - `VMHarness` — loads the real `dist/runtime.js` IIFE in a `node:vm` context
8
+ and runs an adapter end-to-end.
9
+
10
+ ## NativeBridge
11
+
12
+ The allowlist accepts bare hosts (`example.org`) and full URLs
13
+ (`https://www.example.org/path`). Every redirect target is revalidated before
14
+ the next request; leaving the allowlist throws. Only `http:` and `https:` are
15
+ supported.
16
+
17
+ ```ts
18
+ import { NativeBridge } from '@blankgrimoire/testing';
19
+
20
+ const bridge = new NativeBridge(['example.org']);
21
+ const response = await bridge.request({ url: 'https://example.org/search' });
22
+ ```
23
+
24
+ `parseHTML` uses jsdom and returns the runtime `DocumentLike` interface.
25
+
26
+ ## VMHarness
27
+
28
+ ```ts
29
+ import { readFileSync } from 'node:fs';
30
+ import { VMHarness } from '@blankgrimoire/testing';
31
+
32
+ const runtimeIIFE = readFileSync(
33
+ 'node_modules/@blankgrimoire/runtime/dist/runtime.js',
34
+ 'utf8',
35
+ );
36
+
37
+ const harness = new VMHarness(['example.org'], runtimeIIFE, adapterModule);
38
+ const result = await harness.testTheme(html, 'https://example.org/', {
39
+ mangaKey: 'lorem-ipsum',
40
+ });
41
+ ```
42
+
43
+ The harness scores the detection signature, then calls the runtime through its
44
+ JSON dispatcher. When the theme is not detected it returns only detection data.
45
+ Adapters may be passed directly or as a module-shaped `{ default: adapter }`.
46
+
47
+ ## MockServer
48
+
49
+ ```ts
50
+ import { MockServer } from '@blankgrimoire/testing';
51
+
52
+ const server = new MockServer();
53
+ server.register('/page', async () => ({
54
+ status: 200,
55
+ headers: { 'content-type': 'text/html' },
56
+ body: '<html><body>Lorem ipsum</body></html>',
57
+ }));
58
+ await server.start();
59
+ // server.port -> 127.0.0.1:<port>
60
+ await server.stop();
61
+ ```
62
+
63
+ ## Development
64
+
65
+ ```bash
66
+ pnpm build
67
+ pnpm typecheck
68
+ pnpm test
69
+ ```
70
+
71
+ The test script builds `@blankgrimoire/runtime` first so the harness always
72
+ loads the real IIFE artifact.
73
+
74
+ License: MIT — © BlankGrimoire contributors.
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Resolve the hostname from either a full URL or a bare host.
3
+ * Returns `null` for malformed input.
4
+ */
5
+ export declare function hostFromInput(input: string): string | null;
6
+ /**
7
+ * Host allowlist. A host is allowed when it matches an entry exactly or is a
8
+ * subdomain of it (e.g. `example.org` allows `www.example.org`).
9
+ * Matching is case-insensitive. Full URLs are accepted as input.
10
+ */
11
+ export declare function isAllowed(input: string, allowedHosts: string[]): boolean;
@@ -0,0 +1,36 @@
1
+ // SPDX-License-Identifier: MIT
2
+ /**
3
+ * Resolve the hostname from either a full URL or a bare host.
4
+ * Returns `null` for malformed input.
5
+ */
6
+ export function hostFromInput(input) {
7
+ const value = input.trim();
8
+ if (value === '') {
9
+ return null;
10
+ }
11
+ try {
12
+ const url = value.includes('://') ? new URL(value) : new URL(`http://${value}`);
13
+ return url.hostname.toLowerCase();
14
+ }
15
+ catch {
16
+ return null;
17
+ }
18
+ }
19
+ /**
20
+ * Host allowlist. A host is allowed when it matches an entry exactly or is a
21
+ * subdomain of it (e.g. `example.org` allows `www.example.org`).
22
+ * Matching is case-insensitive. Full URLs are accepted as input.
23
+ */
24
+ export function isAllowed(input, allowedHosts) {
25
+ const host = hostFromInput(input);
26
+ if (host === null) {
27
+ return false;
28
+ }
29
+ return allowedHosts.some((allowed) => {
30
+ const entry = hostFromInput(allowed);
31
+ if (entry === null) {
32
+ return false;
33
+ }
34
+ return host === entry || host.endsWith(`.${entry}`);
35
+ });
36
+ }
@@ -0,0 +1,4 @@
1
+ export { NativeBridge, type NativeRequestOptions, type NativeResponse, type NativeParseResult, } from './nativeBridge.js';
2
+ export { MockServer } from './mockServer.js';
3
+ export { isAllowed, hostFromInput } from './allowlist.js';
4
+ export { VMHarness, type ThemeTestOptions, type ThemeTestResult, } from './vmHarness.js';
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ // SPDX-License-Identifier: MIT
2
+ export { NativeBridge, } from './nativeBridge.js';
3
+ export { MockServer } from './mockServer.js';
4
+ export { isAllowed, hostFromInput } from './allowlist.js';
5
+ export { VMHarness, } from './vmHarness.js';
@@ -0,0 +1,24 @@
1
+ import http from 'http';
2
+ type RouteHandler = (req: http.IncomingMessage) => Promise<{
3
+ status: number;
4
+ headers: Record<string, string>;
5
+ body: string;
6
+ }>;
7
+ /**
8
+ * HTTP mock server bound to 127.0.0.1 (loopback). Tests use it to simulate
9
+ * site responses without any real network access.
10
+ */
11
+ export declare class MockServer {
12
+ private server;
13
+ private portValue;
14
+ private handlers;
15
+ private started;
16
+ constructor();
17
+ /** Register a handler for a path. The method is not filtered here. */
18
+ register(path: string, handler: RouteHandler): void;
19
+ start(): Promise<void>;
20
+ stop(): Promise<void>;
21
+ get port(): number;
22
+ get isStarted(): boolean;
23
+ }
24
+ export {};
@@ -0,0 +1,60 @@
1
+ // SPDX-License-Identifier: MIT
2
+ import http from 'http';
3
+ /**
4
+ * HTTP mock server bound to 127.0.0.1 (loopback). Tests use it to simulate
5
+ * site responses without any real network access.
6
+ */
7
+ export class MockServer {
8
+ constructor() {
9
+ this.portValue = 0;
10
+ this.handlers = new Map();
11
+ this.started = false;
12
+ this.server = http.createServer((req, res) => {
13
+ const path = req.url ?? '/';
14
+ const handler = this.handlers.get(path);
15
+ if (!handler) {
16
+ res.writeHead(404, { 'Content-Type': 'text/plain' });
17
+ res.end('not found');
18
+ return;
19
+ }
20
+ const result = handler(req);
21
+ Promise.resolve(result).then((response) => {
22
+ res.writeHead(response.status, response.headers);
23
+ res.end(response.body);
24
+ });
25
+ });
26
+ }
27
+ /** Register a handler for a path. The method is not filtered here. */
28
+ register(path, handler) {
29
+ this.handlers.set(path, handler);
30
+ }
31
+ async start() {
32
+ await new Promise((resolve, reject) => {
33
+ this.server.listen(0, '127.0.0.1', () => {
34
+ this.portValue = this.server.address().port;
35
+ this.started = true;
36
+ resolve();
37
+ });
38
+ this.server.on('error', reject);
39
+ });
40
+ }
41
+ async stop() {
42
+ await new Promise((resolve, reject) => {
43
+ this.server.close((error) => {
44
+ if (error) {
45
+ reject(error);
46
+ }
47
+ else {
48
+ resolve();
49
+ }
50
+ });
51
+ });
52
+ this.started = false;
53
+ }
54
+ get port() {
55
+ return this.portValue;
56
+ }
57
+ get isStarted() {
58
+ return this.started;
59
+ }
60
+ }
@@ -0,0 +1,26 @@
1
+ import type { HttpRequest } from '@blankgrimoire/types';
2
+ import type { DocumentLike } from '@blankgrimoire/runtime';
3
+ export type NativeRequestOptions = HttpRequest;
4
+ export type NativeResponse = {
5
+ status: number;
6
+ url: string;
7
+ headers: Record<string, string>;
8
+ body: string;
9
+ };
10
+ export type NativeParseResult = DocumentLike;
11
+ /**
12
+ * Emulates the `__native` bridge exposed by the runtime to adapters.
13
+ * Every network operation is subject to the host allowlist, including each
14
+ * redirect target.
15
+ */
16
+ export declare class NativeBridge {
17
+ private readonly allowedHosts;
18
+ private timers;
19
+ private timerIdCounter;
20
+ constructor(allowedHosts: string[]);
21
+ request(options: NativeRequestOptions): Promise<NativeResponse>;
22
+ parseHTML(html: string): NativeParseResult;
23
+ log(...args: unknown[]): void;
24
+ setTimeout(cb: () => void, ms: number): number;
25
+ clearTimeout(id: number): void;
26
+ }
@@ -0,0 +1,92 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // @ts-ignore - jsdom has no bundled type declarations
3
+ import { JSDOM } from 'jsdom';
4
+ import { isAllowed } from './allowlist.js';
5
+ const MAX_REDIRECTS = 5;
6
+ /**
7
+ * Emulates the `__native` bridge exposed by the runtime to adapters.
8
+ * Every network operation is subject to the host allowlist, including each
9
+ * redirect target.
10
+ */
11
+ export class NativeBridge {
12
+ constructor(allowedHosts) {
13
+ this.allowedHosts = allowedHosts;
14
+ this.timers = new Map();
15
+ this.timerIdCounter = 0;
16
+ }
17
+ async request(options) {
18
+ let current = options.url;
19
+ let method = options.method ?? 'GET';
20
+ let body = options.body;
21
+ for (let redirects = 0; redirects <= MAX_REDIRECTS; redirects += 1) {
22
+ if (!isAllowed(current, this.allowedHosts)) {
23
+ throw new Error(`Host not allowed by allowlist: ${current}`);
24
+ }
25
+ let parsed;
26
+ try {
27
+ parsed = new URL(current);
28
+ }
29
+ catch {
30
+ throw new Error(`Invalid request URL: ${current}`);
31
+ }
32
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
33
+ throw new Error(`Unsupported protocol: ${parsed.protocol}`);
34
+ }
35
+ const fetchOptions = {
36
+ method,
37
+ redirect: 'manual',
38
+ };
39
+ if (options.headers) {
40
+ fetchOptions.headers = options.headers;
41
+ }
42
+ if (body !== undefined) {
43
+ fetchOptions.body = body;
44
+ }
45
+ const response = await fetch(current, fetchOptions);
46
+ const location = response.headers.get('location');
47
+ if (response.status >= 300 && response.status < 400 && location) {
48
+ current = new URL(location, current).toString();
49
+ if (response.status === 303 || ((response.status === 301 || response.status === 302) && method === 'POST')) {
50
+ method = 'GET';
51
+ body = undefined;
52
+ }
53
+ continue;
54
+ }
55
+ const text = await response.text();
56
+ return {
57
+ status: response.status,
58
+ url: response.url || current,
59
+ headers: Object.fromEntries(response.headers.entries()),
60
+ body: text,
61
+ };
62
+ }
63
+ throw new Error(`Too many redirects: ${options.url}`);
64
+ }
65
+ parseHTML(html) {
66
+ const dom = new JSDOM(html);
67
+ return dom.window.document;
68
+ }
69
+ log(...args) {
70
+ console.log(...args);
71
+ }
72
+ setTimeout(cb, ms) {
73
+ const id = ++this.timerIdCounter;
74
+ const nativeId = setTimeout(() => {
75
+ const entry = this.timers.get(id);
76
+ if (entry) {
77
+ this.timers.delete(id);
78
+ entry.cb();
79
+ }
80
+ }, ms);
81
+ nativeId.unref?.();
82
+ this.timers.set(id, { nativeId, cb });
83
+ return id;
84
+ }
85
+ clearTimeout(id) {
86
+ const entry = this.timers.get(id);
87
+ if (entry !== undefined) {
88
+ clearTimeout(entry.nativeId);
89
+ this.timers.delete(id);
90
+ }
91
+ }
92
+ }
@@ -0,0 +1,34 @@
1
+ import { type Chapter, type MangaDetails, type MangaSummary, type Page, type PagedResult, type SearchQuery, type ThemeAdapter, type ThemeSelectors, type ThemeSignature } from '@blankgrimoire/types';
2
+ import { NativeBridge } from './nativeBridge.js';
3
+ export interface ThemeTestOptions {
4
+ mangaKey?: string;
5
+ chapterKey?: string;
6
+ searchQuery?: SearchQuery;
7
+ }
8
+ export interface ThemeTestResult {
9
+ detected: boolean;
10
+ score: number;
11
+ detectionSignature: ThemeSignature;
12
+ selectors: ThemeSelectors;
13
+ search?: PagedResult<MangaSummary>;
14
+ details?: MangaDetails;
15
+ chapters?: Chapter[];
16
+ pages?: Page[];
17
+ }
18
+ /**
19
+ * Loads the real `dist/runtime.js` IIFE into an isolated `node:vm` context,
20
+ * together with an adapter and a native bridge, and exercises the same
21
+ * declarative engine used on iOS.
22
+ */
23
+ export declare class VMHarness {
24
+ private readonly bridge;
25
+ private readonly runtime;
26
+ private readonly adapter;
27
+ constructor(allowedHosts: string[], runtimeIIFE: string, adapterModule: {
28
+ default: ThemeAdapter;
29
+ } | ThemeAdapter);
30
+ private score;
31
+ testTheme(html: string, url?: string, options?: ThemeTestOptions): Promise<ThemeTestResult>;
32
+ /** Exposes the bridge for tests that simulate network responses. */
33
+ getNativeBridge(): NativeBridge;
34
+ }
@@ -0,0 +1,128 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // @ts-ignore - jsdom has no bundled type declarations
3
+ import { JSDOM } from 'jsdom';
4
+ import * as nodeVm from 'node:vm';
5
+ import { API_VERSION, } from '@blankgrimoire/types';
6
+ import { NativeBridge } from './nativeBridge.js';
7
+ /**
8
+ * Loads the real `dist/runtime.js` IIFE into an isolated `node:vm` context,
9
+ * together with an adapter and a native bridge, and exercises the same
10
+ * declarative engine used on iOS.
11
+ */
12
+ export class VMHarness {
13
+ constructor(allowedHosts, runtimeIIFE, adapterModule) {
14
+ this.bridge = new NativeBridge(allowedHosts);
15
+ this.adapter = 'default' in adapterModule ? adapterModule.default : adapterModule;
16
+ const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>');
17
+ const window = dom.window;
18
+ const document = dom.window.document;
19
+ const native = {
20
+ request: (request) => this.bridge.request(request),
21
+ parseHTML: (html) => this.bridge.parseHTML(html),
22
+ log: (...args) => this.bridge.log(...args),
23
+ error: (...args) => this.bridge.log(...args),
24
+ warn: (...args) => this.bridge.log(...args),
25
+ setTimeout: (callback, ms) => this.bridge.setTimeout(callback, ms),
26
+ clearTimeout: (id) => this.bridge.clearTimeout(id),
27
+ };
28
+ const sandbox = {
29
+ window,
30
+ document,
31
+ __native: native,
32
+ console,
33
+ URL,
34
+ atob: (value) => Buffer.from(value, 'base64').toString('binary'),
35
+ btoa: (value) => Buffer.from(value, 'binary').toString('base64'),
36
+ setTimeout: (callback, ms) => this.bridge.setTimeout(callback, ms),
37
+ clearTimeout: (id) => this.bridge.clearTimeout(id),
38
+ };
39
+ const context = nodeVm.createContext(sandbox);
40
+ nodeVm.runInContext(runtimeIIFE, context, { filename: 'runtime.js' });
41
+ const runtime = sandbox.BlankGrimoireRuntime;
42
+ if (!runtime || runtime.__apiVersion !== API_VERSION) {
43
+ throw new Error(`runtimeIIFE did not expose a BlankGrimoireRuntime global for API version ${API_VERSION}`);
44
+ }
45
+ if (typeof runtime.dispatch !== 'function') {
46
+ throw new Error('runtimeIIFE did not expose a BlankGrimoireRuntime global with dispatch');
47
+ }
48
+ this.runtime = runtime;
49
+ }
50
+ score(signature, document, url) {
51
+ let total = 0;
52
+ if (signature.metaGenerator) {
53
+ const meta = document.querySelector('meta[name="generator"]');
54
+ const content = meta?.getAttribute('content') ?? '';
55
+ if (new RegExp(signature.metaGenerator).test(content)) {
56
+ total += 3;
57
+ }
58
+ }
59
+ for (const selector of signature.selectors ?? []) {
60
+ if (document.querySelector(selector)) {
61
+ total += 2;
62
+ }
63
+ }
64
+ for (const pattern of signature.scriptSrc ?? []) {
65
+ const regex = new RegExp(pattern);
66
+ const scripts = Array.from(document.querySelectorAll('script'));
67
+ if (scripts.some((script) => {
68
+ const src = script.getAttribute('src') ?? '';
69
+ return regex.test(src);
70
+ })) {
71
+ total += 1;
72
+ }
73
+ }
74
+ return (async () => {
75
+ for (const probePath of signature.probePaths ?? []) {
76
+ try {
77
+ const response = await this.bridge.request({
78
+ url: new URL(probePath, url).toString(),
79
+ method: 'GET',
80
+ });
81
+ if (response.status >= 200 && response.status < 300) {
82
+ total += 3;
83
+ }
84
+ }
85
+ catch {
86
+ // A failed probe simply contributes no score.
87
+ }
88
+ }
89
+ return total;
90
+ })();
91
+ }
92
+ async testTheme(html, url = 'https://example.org/', options = {}) {
93
+ const dom = new JSDOM(html, { url });
94
+ const document = dom.window.document;
95
+ const window = dom.window;
96
+ const detectionSignature = this.adapter.detectionSignature;
97
+ const score = await this.score(detectionSignature, document, url);
98
+ const base = {
99
+ detected: score >= detectionSignature.minScore,
100
+ score,
101
+ detectionSignature,
102
+ selectors: this.adapter.selectors,
103
+ };
104
+ if (!base.detected) {
105
+ return base;
106
+ }
107
+ const runtime = {
108
+ adapter: this.adapter,
109
+ context: { baseURL: url, siteName: 'Example Site', overrides: {} },
110
+ document,
111
+ window,
112
+ parseHTML: (value) => this.bridge.parseHTML(value),
113
+ };
114
+ const mangaKey = options.mangaKey ?? 'lorem-ipsum';
115
+ const searchQuery = options.searchQuery ?? { page: 1 };
116
+ const call = async (method, args) => JSON.parse(await this.runtime.dispatch(runtime, method, JSON.stringify(args)));
117
+ base.search = await call('search', searchQuery);
118
+ base.details = await call('details', { key: mangaKey });
119
+ base.chapters = await call('chapters', { key: mangaKey });
120
+ const chapterKey = options.chapterKey ?? base.chapters[0]?.key ?? 'chapter-1';
121
+ base.pages = await call('pages', { mangaKey, chapterKey });
122
+ return base;
123
+ }
124
+ /** Exposes the bridge for tests that simulate network responses. */
125
+ getNativeBridge() {
126
+ return this.bridge;
127
+ }
128
+ }
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@blankgrimoire/testing",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.1",
4
+ "description": "Node testing harness and mock server for BlankGrimoire theme adapters.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "publishConfig": {
19
+ "access": "public",
20
+ "provenance": true
21
+ },
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "https://github.com/BlankGrimoire/BlankGrimoire-sdk",
25
+ "directory": "packages/testing"
26
+ },
27
+ "dependencies": {
28
+ "jsdom": "^24.0.0",
29
+ "@blankgrimoire/types": "1.0.1",
30
+ "@blankgrimoire/runtime": "1.0.1"
31
+ },
32
+ "scripts": {
33
+ "build": "tsc -p tsconfig.json",
34
+ "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.test.json",
35
+ "pretest": "pnpm --filter @blankgrimoire/runtime... build",
36
+ "test": "vitest run --passWithNoTests"
37
+ }
6
38
  }