fix(sdk) rework the sdk helpers and DX/UX

This commit is contained in:
jubnl
2026-07-13 18:41:22 +02:00
parent c3fb35f4ca
commit 6c8fcb29de
30 changed files with 3808 additions and 528 deletions
+205
View File
@@ -0,0 +1,205 @@
/**
* The test this whole rework rests on.
*
* The SDK's checks are a PORT of the TREK-Plugins registry's gates (scripts/validate-entry.mjs
* and scripts/check-readme.mjs). A port drifts. And when it drifts in the lenient direction the
* result is not a missing feature — it is a FALSE GREEN: an author runs `validate`, sees a pass,
* cuts an immutable GitHub release, and the registry rejects it. That is the exact failure this
* rework exists to make impossible, so it needs a test, not a comment.
*
* Two halves:
*
* 1. The README gate's constants are read out of the registry's own source and compared. If
* someone bumps MIN_PROSE_CHARS to 500 over there, this goes red here.
* 2. The registry's REAL validate-entry.mjs is executed (SKIP_NETWORK=1) against an entry the
* SDK built, and must agree that it is valid.
*
* The registry lives in a separate repo, so these skip when it is not checked out — a plugin-sdk
* CI run without it still passes. Point TREK_PLUGINS_REPO at it to run them anywhere.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { scaffold } from '../src/cli/create.js';
import { packPluginDir } from '../src/cli/pack.js';
import { buildEntry } from '../src/cli/entry.js';
import { validatePluginDir } from '../src/cli/validate.js';
import { REQUIRED_SECTIONS, MIN_PROSE_CHARS, PLACEHOLDER_PATTERNS } from '../src/cli/checks/readme.js';
import { makePublishable } from './helpers.js';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const REGISTRY =
process.env.TREK_PLUGINS_REPO ?? path.resolve(HERE, '..', '..', '..', 'TREK-Plugins');
const haveRegistry = fs.existsSync(path.join(REGISTRY, 'scripts', 'validate-entry.mjs'));
const describeIfRegistry = haveRegistry ? describe : describe.skip;
describeIfRegistry('parity with the TREK-Plugins registry gates', () => {
let tmp: string;
let dir: string;
beforeEach(() => {
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'parity-'));
scaffold('parity-plug', 'widget', tmp);
dir = path.join(tmp, 'parity-plug');
});
afterEach(() => { fs.rmSync(tmp, { recursive: true, force: true }); });
// ── 1. the README gate's constants ────────────────────────────────────────────
const readmeGateSource = (): string =>
fs.readFileSync(path.join(REGISTRY, 'scripts', 'check-readme.mjs'), 'utf8');
it('requires exactly the sections the registry requires', () => {
const src = readmeGateSource();
const match = src.match(/const REQUIRED_HEADINGS = \[([^\]]+)\]/);
expect(match, 'could not find REQUIRED_HEADINGS in check-readme.mjs').toBeTruthy();
const theirs = [...match![1].matchAll(/'([^']+)'/g)].map((m) => m[1]);
expect(REQUIRED_SECTIONS).toEqual(theirs);
});
it('uses the same prose floor as the registry', () => {
const match = readmeGateSource().match(/const MIN_PROSE_CHARS = (\d+)/);
expect(match, 'could not find MIN_PROSE_CHARS in check-readme.mjs').toBeTruthy();
expect(MIN_PROSE_CHARS).toBe(Number(match![1]));
});
it('detects the same template placeholders as the registry', () => {
const src = readmeGateSource();
const block = src.match(/const PLACEHOLDER_PATTERNS = \[([\s\S]*?)\n\]/);
expect(block, 'could not find PLACEHOLDER_PATTERNS in check-readme.mjs').toBeTruthy();
// Compare the regex SOURCES, not the objects — same patterns, whatever the formatting.
const theirs = [...block![1].matchAll(/\/((?:[^/\\\n]|\\.)+)\/[a-z]*/g)].map((m) => m[1]).sort();
const ours = PLACEHOLDER_PATTERNS.map((r) => r.source).sort();
expect(ours).toEqual(theirs);
});
// ── 2. the registry's real validator, run against an entry we built ───────────
/**
* Build a publishable plugin, pack it, and hand the resulting entry to the registry's OWN
* validate-entry.mjs. This is the end of the chain: if the registry's script says yes with
* SKIP_NETWORK=1, then everything the SDK can promise offline, it has promised correctly.
*/
function runRegistryValidator(entry: unknown, id: string): { code: number; output: string } {
const entryDir = fs.mkdtempSync(path.join(os.tmpdir(), 'entry-'));
const entryPath = path.join(entryDir, `${id}.json`);
fs.writeFileSync(entryPath, JSON.stringify(entry, null, 2));
try {
const output = execFileSync('node', [path.join(REGISTRY, 'scripts', 'validate-entry.mjs'), entryPath], {
encoding: 'utf8',
env: { ...process.env, SKIP_NETWORK: '1' },
stdio: ['ignore', 'pipe', 'pipe'],
});
return { code: 0, output };
} catch (e) {
const err = e as { status?: number; stdout?: string; stderr?: string };
return { code: err.status ?? 1, output: (err.stdout ?? '') + (err.stderr ?? '') };
} finally {
fs.rmSync(entryDir, { recursive: true, force: true });
}
}
function entryFor(pluginDir: string) {
const zip = path.join(pluginDir, 'plugin.zip');
packPluginDir(pluginDir, zip);
return buildEntry({
dir: pluginDir,
repo: 'someone/trek-plugin-parity-plug',
tag: 'v1.0.0',
zipPath: zip,
// No git tag exists in a temp dir, so pin the commit by hand — the network checks that
// would verify it are exactly the ones SKIP_NETWORK=1 turns off.
commit: 'a'.repeat(40),
now: '2026-01-01T00:00:00Z',
});
}
it('an entry the SDK builds passes the registry validator', () => {
makePublishable(dir);
expect(validatePluginDir(dir).ok).toBe(true);
const { code, output } = runRegistryValidator(entryFor(dir), 'parity-plug');
expect(output).not.toMatch(/FAIL|schema:/);
expect(code).toBe(0);
});
/**
* The buildEntry bug, pinned.
*
* buildEntry never emitted requiredAddons or pluginDependencies, but validate-entry.mjs
* parity-checks both against the manifest. So any plugin that actually declared an addon
* dependency produced an entry the registry rejected — and the author found out after the
* release was cut and its bytes pinned. This test is the reason that cannot happen again.
*/
it('an entry for a plugin with requiredAddons still passes the registry validator', () => {
const manifestPath = path.join(dir, 'trek-plugin.json');
const m = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
m.requiredAddons = ['budget', 'packing'];
m.pluginDependencies = [{ id: 'some-other-plugin', version: '>=1.0.0 <2.0.0' }];
fs.writeFileSync(manifestPath, JSON.stringify(m, null, 2));
makePublishable(dir);
const entry = entryFor(dir);
// The entry must MIRROR the manifest, or the registry's parity check rejects it.
expect(entry.versions[0].requiredAddons).toEqual(['budget', 'packing']);
expect(entry.versions[0].pluginDependencies).toEqual([{ id: 'some-other-plugin', version: '>=1.0.0 <2.0.0' }]);
const { code, output } = runRegistryValidator(entry, 'parity-plug');
expect(output).not.toMatch(/FAIL|requiredAddons|pluginDependencies/);
expect(code).toBe(0);
});
/**
* `tags` and `homepage` are copied verbatim out of the manifest into the entry, and the
* registry's JSON schema validates both — but nothing local used to. A tag with a capital
* letter (the obvious thing to write) produced an entry CI rejected, after the release was cut.
*
* Both halves are asserted: WE reject it, and the registry rejects it too. Either one alone
* would be a weaker claim than it looks.
*/
it.each([
{ field: 'tags', value: ['Flight Tracking'], match: /tag/i },
{ field: 'homepage', value: 'not-a-url', match: /homepage/i },
])('rejects a bad $field, exactly as the registry schema does', ({ field, value, match }) => {
const manifestPath = path.join(dir, 'trek-plugin.json');
const m = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
m[field] = value;
fs.writeFileSync(manifestPath, JSON.stringify(m, null, 2));
makePublishable(dir);
const ours = validatePluginDir(dir);
expect(ours.ok).toBe(false);
expect(ours.errors.some((e) => match.test(e))).toBe(true);
const { code, output } = runRegistryValidator(entryFor(dir), 'parity-plug');
expect(code).toBe(1);
expect(output).toMatch(/schema:/);
});
/**
* The registry's schema caps `description` at 200 chars and requires at least 5. Nothing local
* used to look at either, so an over-long description sailed through pack + release and failed
* CI once the artifact was immutable. Assert that we now catch it BEFORE the registry does.
*/
it('rejects an over-long description that the registry schema would also reject', () => {
const manifestPath = path.join(dir, 'trek-plugin.json');
const m = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
m.description = 'x'.repeat(201);
fs.writeFileSync(manifestPath, JSON.stringify(m, null, 2));
makePublishable(dir);
// We say no…
const ours = validatePluginDir(dir);
expect(ours.ok).toBe(false);
expect(ours.errors.some((e) => /description/.test(e))).toBe(true);
// …and so does the registry, for the same reason. That agreement is the point.
const { code, output } = runRegistryValidator(entryFor(dir), 'parity-plug');
expect(code).toBe(1);
expect(output).toMatch(/description/);
});
});
+260
View File
@@ -0,0 +1,260 @@
/**
* Per-check unit tests.
*
* Every check is a pure function of a CheckContext, so these need no temp dir and no disk — the
* context is just data, and `exists` is a closure the test supplies. That is the property the
* whole checks/ module was shaped around, and it is what makes the boundary cases (399 vs 400
* chars of prose) cheap enough to actually write down.
*/
import { describe, it, expect } from 'vitest';
import { runOffline } from '../src/cli/checks/index.js';
import { blocking, type CheckContext, type CheckReport } from '../src/cli/checks/types.js';
import { proseLength, missingSections, placeholders, images, undocumentedPermissions } from '../src/cli/checks/readme.js';
/** A manifest that passes everything, so each test can break exactly one thing. */
const GOOD_MANIFEST = {
id: 'flight-tracker',
name: 'Flight Tracker',
version: '1.0.0',
apiVersion: 1,
author: 'Jane Doe',
description: 'Shows your next flight on the trip dashboard.',
type: 'widget',
trek: '>=3.4.0 <4.0.0',
icon: 'Plane',
nativeModules: false,
permissions: ['db:own'],
requiredAddons: [],
pluginDependencies: [],
};
/** A README that passes every registry gate. Long enough to clear the 400-char prose floor. */
const GOOD_README = `# Flight Tracker
![screenshot](./docs/screenshot.png)
## What it does
This plugin shows your next flight on the trip dashboard, so you never have to dig through your
inbox for a boarding pass again. It reads the trip you are looking at, finds the next reservation
of type flight, and renders it as a widget with the gate, the terminal and a countdown. There is
nothing to configure and nothing to sign up for, and it works offline once the trip has synced.
## Screenshots
The image above shows the widget on a trip dashboard.
## Permissions
| Permission | Why |
|---|---|
| \`db:own\` | Stores the cached flight lookup so the widget renders instantly. |
## Setup
Install it and enable it. There is nothing to configure.
`;
function ctx(over: Partial<CheckContext> = {}): CheckContext {
const files = new Set<string>(['server/index.js', 'docs/screenshot.png']);
return {
dir: '/plugins/flight-tracker',
manifest: { ...GOOD_MANIFEST },
readme: GOOD_README,
exists: (rel) => files.has(rel.replace(/^\.?\//, '')),
...over,
};
}
const failed = (r: CheckReport, id: string) => r.errors.some((e) => e.id === id);
const warned = (r: CheckReport, id: string) => r.warnings.some((w) => w.id === id);
describe('the baseline is actually clean', () => {
it('a well-formed plugin passes every offline check', () => {
const r = runOffline(ctx());
expect(r.errors).toEqual([]);
expect(r.ok).toBe(true);
});
});
describe('manifest checks', () => {
it('rejects a description longer than the registry allows', () => {
const r = runOffline(ctx({ manifest: { ...GOOD_MANIFEST, description: 'x'.repeat(201) } }));
expect(failed(r, 'manifest.entry-fields')).toBe(true);
});
it('rejects a missing description — the entry would carry an empty one and fail the schema', () => {
const m = { ...GOOD_MANIFEST };
delete (m as Record<string, unknown>).description;
expect(failed(runOffline(ctx({ manifest: m })), 'manifest.entry-fields')).toBe(true);
});
it('accepts a description at exactly the 200-char cap', () => {
const r = runOffline(ctx({ manifest: { ...GOOD_MANIFEST, description: 'x'.repeat(200) } }));
expect(failed(r, 'manifest.entry-fields')).toBe(false);
});
it('rejects an icon lucide does not have — the registry does', () => {
const r = runOffline(ctx({ manifest: { ...GOOD_MANIFEST, icon: 'Aeroplane' } }));
expect(failed(r, 'manifest.icon')).toBe(true);
});
it('allows no icon at all (TREK falls back to Blocks) but says so', () => {
const m = { ...GOOD_MANIFEST };
delete (m as Record<string, unknown>).icon;
const r = runOffline(ctx({ manifest: m }));
expect(failed(r, 'manifest.icon')).toBe(false);
expect(r.outcomes.find((o) => o.id === 'manifest.icon')?.detail).toMatch(/Blocks/);
});
it('rejects a homoglyph name that mixes Latin with Cyrillic', () => {
// "Flight Trаcker" — the 'а' is Cyrillic U+0430.
const r = runOffline(ctx({ manifest: { ...GOOD_MANIFEST, name: 'Flight Trаcker' } }));
expect(failed(r, 'manifest.entry-fields')).toBe(true);
});
it('warns — but does not fail — on an unbounded trek range', () => {
const r = runOffline(ctx({ manifest: { ...GOOD_MANIFEST, trek: '*' } }));
expect(warned(r, 'manifest.trek-range')).toBe(true);
expect(failed(r, 'manifest.trek-range')).toBe(false);
});
});
/**
* The egress trap.
*
* TREK builds the child's network allow-list and the iframe CSP from the `http:outbound:<host>`
* PERMISSIONS. It never reads the manifest's `egress[]` array — that is a declaration for the
* consent screen. So a host in egress[] with no matching permission is silently unreachable at
* runtime: the plugin installs, activates, consents, and every request to it is blocked. Nothing
* anywhere caught this before.
*/
describe('the egress trap', () => {
const outbound = (permissions: string[], egress: string[]) =>
runOffline(ctx({ manifest: { ...GOOD_MANIFEST, permissions, egress } }));
it('fails a host declared in egress[] with only the bare http:outbound permission', () => {
const r = outbound(['db:own', 'http:outbound'], ['api.example.com']);
expect(failed(r, 'code.egress-reachable')).toBe(true);
const e = r.errors.find((x) => x.id === 'code.egress-reachable');
// The fix has to name the exact permission string, or the author is left guessing.
expect(e?.fix).toContain('"http:outbound:api.example.com"');
});
it('passes when every egress host has its matching per-host permission', () => {
const r = outbound(['db:own', 'http:outbound:api.example.com'], ['api.example.com']);
expect(failed(r, 'code.egress-reachable')).toBe(false);
});
it('warns when a host is reachable but not declared in egress[] (the consent screen understates it)', () => {
const r = outbound(['db:own', 'http:outbound:api.example.com'], []);
expect(warned(r, 'code.egress-declared')).toBe(true);
});
});
describe('README checks', () => {
it('fails a README that is one char short of the prose floor, and passes one that is exactly at it', () => {
// Build prose of an exact length, with all four sections present so only the floor is in play.
const withProse = (n: number) =>
GOOD_README.replace(
/This plugin shows[\s\S]*?has synced\./,
'x'.repeat(n),
);
const proseOf = (md: string) => proseLength(md);
const short = withProse(1);
const long = withProse(2000);
expect(proseOf(short)).toBeLessThan(400);
expect(proseOf(long)).toBeGreaterThanOrEqual(400);
expect(failed(runOffline(ctx({ readme: short })), 'docs.readme-prose')).toBe(true);
expect(failed(runOffline(ctx({ readme: long })), 'docs.readme-prose')).toBe(false);
});
it('fails a README missing a required section', () => {
const r = runOffline(ctx({ readme: GOOD_README.replace('## Setup', '## Configuration') }));
expect(failed(r, 'docs.readme-sections')).toBe(true);
});
it('fails a README with a permission it never explains', () => {
const r = runOffline(ctx({ manifest: { ...GOOD_MANIFEST, permissions: ['db:own', 'weather:read'] } }));
expect(failed(r, 'docs.permissions-explained')).toBe(true);
expect(r.errors.find((e) => e.id === 'docs.permissions-explained')?.detail).toContain('weather:read');
});
it('fails template placeholders left in the README', () => {
const r = runOffline(ctx({ readme: GOOD_README.replace('This plugin shows', 'Describe what it does.') }));
expect(failed(r, 'docs.readme-placeholders')).toBe(true);
});
/**
* The old check regexed for an image LINK and passed if it found one — so the scaffold's
* `![screenshot](./docs/screenshot.png)`, pointing at a file that was never created, satisfied
* it. Resolve the path instead.
*/
it('fails a screenshot link whose file does not exist', () => {
const r = runOffline(ctx({ exists: (rel) => rel === 'server/index.js' }));
expect(failed(r, 'docs.screenshot')).toBe(true);
expect(r.errors.find((e) => e.id === 'docs.screenshot')?.next).toBe('trek-plugin shot');
});
it('fails a README with no image at all', () => {
const r = runOffline(ctx({ readme: GOOD_README.replace('![screenshot](./docs/screenshot.png)', '') }));
expect(failed(r, 'docs.screenshot')).toBe(true);
});
});
/**
* `pack` must not be blocked by a gate that only matters at publish time — packing is how you
* install a plugin into a local TREK to try it, and an unwritten README does not stop it running.
*/
describe('what blocks what', () => {
it('an undocumented plugin blocks publish but not the artifact', () => {
const undocumented = ctx({ readme: '# Nothing here\n', exists: (rel) => rel === 'server/index.js' });
const full = runOffline(undocumented);
expect(full.ok).toBe(false);
expect(blocking(full, 'artifact').ok).toBe(true);
});
it('a broken manifest blocks the artifact too — that plugin could never load', () => {
const broken = runOffline(ctx({ manifest: { ...GOOD_MANIFEST, trek: 'not-a-range' } }));
expect(blocking(broken, 'artifact').ok).toBe(false);
});
it('a missing server entry blocks the artifact', () => {
const r = runOffline(ctx({ exists: (rel) => rel === 'docs/screenshot.png' }));
expect(blocking(r, 'artifact').ok).toBe(false);
expect(failed(r, 'code.server-entry')).toBe(true);
});
});
describe('README helpers mirror the registry exactly', () => {
it('strips headings, tables, links, images and code fences before measuring prose', () => {
const md = '# Title\n\n![x](y.png)\n\n| a | b |\n|---|---|\n\n```js\nconst x = 1;\n```\n\n[link](u)\n';
expect(proseLength(md)).toBeLessThan(20); // nothing above is prose
});
it('finds required sections case-insensitively and as substrings', () => {
expect(missingSections('## What it does\n## Screenshots\n## Permissions\n## Setup')).toEqual([]);
expect(missingSections('### WHAT IT DOES and more\n## Screenshots\n## Permissions\n## Setup')).toEqual([]);
expect(missingSections('## What it does')).toEqual(['Screenshots', 'Permissions', 'Setup']);
});
it('ignores data: URIs when looking for a screenshot, like the registry does', () => {
expect(images('![a](data:image/png;base64,xxx)')).toEqual([]);
expect(images('<img src="shot.png">')).toEqual(['shot.png']);
});
it('matches a permission anywhere in the README, case-insensitively', () => {
expect(undocumentedPermissions('we use `DB:OWN` for caching', ['db:own'])).toEqual([]);
expect(undocumentedPermissions('nothing here', ['db:own'])).toEqual(['db:own']);
});
it('spots each template placeholder the registry spots', () => {
expect(placeholders('Describe what your plugin does.')).toHaveLength(1);
expect(placeholders('see your-name/trek-plugin-x')).toHaveLength(1);
expect(placeholders('{{ TODO }}')).toHaveLength(1);
expect(placeholders('a real README')).toEqual([]);
});
});
+48
View File
@@ -0,0 +1,48 @@
import fs from 'node:fs';
import path from 'node:path';
/**
* Take a scaffolded plugin and do to it what a real author does before publishing: write the
* README and commit a screenshot.
*
* This is exactly the set of things the registry demands and the scaffold deliberately leaves
* undone, so it doubles as executable documentation of the gap between "it runs" and "it ships".
* A test that needs a PUBLISHABLE plugin calls this; a test that needs a FRESH one does not, and
* the difference between them is the contract.
*
* Every permission in the manifest gets a line, because the registry requires each one to be
* explained by name, and the prose has to clear 400 real characters (headings, tables, links and
* code fences are stripped before it is measured, so a big table will not carry you).
*/
export function makePublishable(dir: string): void {
const manifest = JSON.parse(fs.readFileSync(path.join(dir, 'trek-plugin.json'), 'utf8')) as {
name?: string;
permissions?: unknown;
};
const permissions: string[] = Array.isArray(manifest.permissions) ? manifest.permissions.map(String) : [];
fs.mkdirSync(path.join(dir, 'docs'), { recursive: true });
// A 1×1 PNG. The gate is "the file the README links actually exists", not "it is beautiful".
fs.writeFileSync(
path.join(dir, 'docs', 'screenshot.png'),
Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64'),
);
fs.writeFileSync(
path.join(dir, 'README.md'),
`# ${manifest.name ?? 'Plugin'}\n\n` +
'![screenshot](./docs/screenshot.png)\n\n' +
'## What it does\n\n' +
'This plugin adds a genuinely useful capability to TREK, and this paragraph exists to clear the four hundred\n' +
'character floor the registry puts on real prose. It explains, in ordinary sentences, what a traveller gets\n' +
'out of installing it and why they might want to. The registry strips headings, tables, links and code fences\n' +
'before it measures, so padding the file out with a permissions table will not help; it has to be words.\n\n' +
'## Screenshots\n\n' +
'The image above shows the plugin running inside a trip.\n\n' +
'## Permissions\n\n' +
'| Permission | Why |\n|---|---|\n' +
permissions.map((p) => `| \`${p}\` | Needed so the plugin can do its job. |`).join('\n') +
'\n\n## Setup\n\nInstall it from the plugin store and enable it. There is nothing else to configure.\n\n' +
'## License\n\nMIT.\n',
);
}
+108
View File
@@ -22,6 +22,7 @@ vi.mock('node:child_process', () => ({
const { publishPlugin } = await import('../src/cli/publish.js');
const { scaffold } = await import('../src/cli/create.js');
const { makePublishable } = await import('./helpers.js');
describe('publish — a released artifact is immutable', () => {
let tmp: string;
@@ -33,6 +34,9 @@ describe('publish — a released artifact is immutable', () => {
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'publish-'));
scaffold('immutable-plug', 'integration', tmp);
dir = path.join(tmp, 'immutable-plug');
// publish now gates on the registry's checks BEFORE it packs or releases, so a bare scaffold
// never reaches the `gh` calls these tests are about. Document the plugin first.
makePublishable(dir);
});
afterEach(() => { fs.rmSync(tmp, { recursive: true, force: true }); });
@@ -71,3 +75,107 @@ describe('publish — a released artifact is immutable', () => {
expect(fs.existsSync(path.join(dir, 'plugin.zip'))).toBe(true);
});
});
/**
* The reorder, and why it is the most important thing in this file.
*
* publish used to run: pack → tag + GitHub release → preflight → submit. So the checks that
* catch an unwritten README or a missing screenshot ran AFTER the release was cut — and a release
* is immutable in the only sense that matters, because the registry pins its sha256. An author
* who failed preflight had already burned their v1.0.0 tag, and the only way out was to throw it
* away and cut a v1.0.1 whose sole change was the README.
*
* So: when a local gate fails, NOTHING may happen. No zip, no tag, no push, no release.
*/
describe('publish — the local gates run before anything is cut', () => {
let tmp: string;
let dir: string;
beforeEach(() => {
calls.length = 0;
releaseExistsOnRemote = false;
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'publish-gate-'));
scaffold('gated-plug', 'integration', tmp);
dir = path.join(tmp, 'gated-plug');
// Deliberately NOT made publishable: this is a fresh scaffold, exactly what a first-time
// author has when they reach for `publish` too early.
});
afterEach(() => { fs.rmSync(tmp, { recursive: true, force: true }); });
const run = () => publishPlugin({
dir, repo: 'someone/trek-plugin-gated-plug', tag: 'v1.0.0',
now: '2026-01-01T00:00:00Z', skipPreflight: true, log: () => {},
});
it('refuses an undocumented plugin and names what is wrong', async () => {
await expect(run()).rejects.toThrow(/would be rejected by the registry/i);
await expect(run()).rejects.toThrow(/prose|screenshot/i);
});
it('packs nothing, tags nothing, pushes nothing, releases nothing', async () => {
await run().catch(() => {});
expect(fs.existsSync(path.join(dir, 'plugin.zip'))).toBe(false);
expect(calls.some((c) => c.bin === 'git' && c.args.includes('tag'))).toBe(false);
expect(calls.some((c) => c.bin === 'git' && c.args.includes('push'))).toBe(false);
expect(calls.some((c) => c.bin === 'gh')).toBe(false);
});
it('goes through once the plugin is documented', async () => {
makePublishable(dir);
await run().catch(() => {}); // submit is not stubbed; we only care that it got past the gate
expect(calls.some((c) => c.bin === 'gh' && c.args[1] === 'create')).toBe(true);
});
});
/**
* The signing half of the same trap.
*
* TREK pins the author key on first install. A plugin that shipped SIGNED and then publishes
* UNSIGNED is refused on every instance that already has it (SIGNATURE_MISSING) — the update is
* not merely rejected, it strands every existing user on the version they have.
*
* `preflight` has always caught this. But preflight is step 4, and the immutable GitHub release is
* cut at step 3 — so the author learned it with their tag already burned, for a fact that was
* knowable before a single byte was packed. The check belongs in step 1, and this pins it there.
*/
describe('publish — a signed plugin cannot quietly go unsigned', () => {
let tmp: string;
let dir: string;
beforeEach(() => {
calls.length = 0;
releaseExistsOnRemote = false;
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'publish-sign-'));
scaffold('signed-plug', 'integration', tmp);
dir = path.join(tmp, 'signed-plug');
makePublishable(dir);
});
afterEach(() => { fs.rmSync(tmp, { recursive: true, force: true }); });
/** Pretend the registry already lists this plugin as signed, without hitting the network. */
const publishedSigned = {
hasKey: true,
keyPath: '/nonexistent/signing.key',
publishedSigned: true,
publishedKey: 'a-published-key',
};
const run = (signKeyPath?: string) => publishPlugin({
dir, repo: 'someone/trek-plugin-signed-plug', tag: 'v2.0.0',
now: '2026-01-01T00:00:00Z', skipPreflight: true, signKeyPath,
signing: publishedSigned, log: () => {},
});
it('refuses, and names what it would have broken', async () => {
await expect(run(undefined)).rejects.toThrow(/published SIGNED/i);
await expect(run(undefined)).rejects.toThrow(/strand every existing user/i);
});
it('cuts no release — the whole point of checking at step 1', async () => {
await run(undefined).catch(() => {});
expect(fs.existsSync(path.join(dir, 'plugin.zip'))).toBe(false);
expect(calls.some((c) => c.bin === 'git' && c.args.includes('tag'))).toBe(false);
expect(calls.some((c) => c.bin === 'gh')).toBe(false);
});
});
+56 -11
View File
@@ -12,6 +12,7 @@ import { makeZip, listZipNames } from '../src/zip.js';
import { packPluginDir } from '../src/cli/pack.js';
import { buildEntry } from '../src/cli/entry.js';
import { generateKeypair, signArtifact, publicKeyBase64, verifyArtifact, loadPrivateKey } from '../src/cli/sign.js';
import { makePublishable } from './helpers.js';
/** A central-directory zip reader mirroring the TREK server's, to prove round-trip. */
function readZip(buf: Buffer): Record<string, Buffer> {
@@ -397,42 +398,78 @@ describe('scaffold + validate CLIs', () => {
beforeEach(() => { tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'sdk-')); });
afterEach(() => { fs.rmSync(tmp, { recursive: true, force: true }); });
it('scaffolds a widget plugin that then validates (with README warnings)', () => {
/**
* A scaffold is HONESTLY INCOMPLETE: it builds and runs, but it is not publishable until it is
* documented. These two facts are the contract, and they are deliberately different:
*
* pack/dev work immediately — you can install it into a local TREK and try it.
* validate fails until the README is written and a screenshot exists.
*
* It used to be the other way round: a fresh scaffold passed `validate` (which only checked a
* fifth of the registry's rules and demoted the README to a warning), and the author learned
* the truth from CI — after cutting an immutable release. A green that means nothing is worse
* than a red that tells you what to do.
*/
it('scaffolds a widget that builds immediately but is not yet publishable', () => {
scaffold('my-widget', 'widget', tmp);
const dir = path.join(tmp, 'my-widget');
expect(fs.existsSync(path.join(dir, 'trek-plugin.json'))).toBe(true);
expect(fs.existsSync(path.join(dir, 'server', 'index.js'))).toBe(true);
expect(fs.existsSync(path.join(dir, 'client', 'index.html'))).toBe(true);
// It packs — the dev loop is not blocked by the docs gates.
expect(() => packPluginDir(dir, path.join(tmp, 'w.zip'))).not.toThrow();
// But it does not publish, and it says exactly why. Both of these used to be WARNINGS, which
// is how a scaffold could sail through `validate` and then be rejected by the registry.
const r = validatePluginDir(dir);
expect(r.ok).toBe(true); // manifest + files valid
expect(r.warnings.some((w) => /placeholder|screenshot/.test(w))).toBe(true); // README is the unfilled template
expect(r.ok).toBe(false);
expect(r.errors.some((e) => /placeholder/.test(e))).toBe(true);
// The scaffold's README references ./docs/screenshot.png and never creates it. The old check
// regexed for an image LINK and passed; this one resolves the path.
expect(r.errors.some((e) => /screenshot/.test(e))).toBe(true);
expect(fs.existsSync(path.join(dir, 'docs', 'screenshot.png'))).toBe(false);
});
// TREK resolves `icon` against lucide at render time and falls back to Blocks on a
// name it can't find, so a typo is invisible in the UI — validate has to surface it.
it('warns on an icon lucide does not know, without failing validation', () => {
it('a documented scaffold passes validate clean — the scaffold is not born unfixable', () => {
scaffold('done-plug', 'widget', tmp);
const dir = path.join(tmp, 'done-plug');
makePublishable(dir);
const r = validatePluginDir(dir);
expect(r.errors).toEqual([]);
expect(r.ok).toBe(true);
});
/**
* The registry REJECTS an icon lucide does not have (validate-entry.mjs: "is not a lucide icon
* name"), so warning about it locally was a false green: the author saw a pass, cut the release,
* and CI failed them once the artifact was immutable. Local severity now matches the registry's.
*/
it('rejects an icon lucide does not know — the registry does, so we must too', () => {
scaffold('icon-plug', 'widget', tmp);
const dir = path.join(tmp, 'icon-plug');
makePublishable(dir);
const file = path.join(dir, 'trek-plugin.json');
const m = JSON.parse(fs.readFileSync(file, 'utf8'));
fs.writeFileSync(file, JSON.stringify({ ...m, icon: 'Stethscope' }, null, 2));
const r = validatePluginDir(dir);
expect(r.ok).toBe(true); // a bad icon is never a hard error
expect(r.warnings.some((w) => /icon: "Stethscope" is not a known lucide icon name/.test(w))).toBe(true);
expect(r.ok).toBe(false);
expect(r.errors.some((e) => /Stethscope.*not a lucide icon/.test(e))).toBe(true);
});
it('accepts any real lucide icon name, not just a curated few', () => {
scaffold('icon-plug', 'widget', tmp);
const dir = path.join(tmp, 'icon-plug');
makePublishable(dir);
const file = path.join(dir, 'trek-plugin.json');
const m = JSON.parse(fs.readFileSync(file, 'utf8'));
fs.writeFileSync(file, JSON.stringify({ ...m, icon: 'Stethoscope' }, null, 2));
const r = validatePluginDir(dir);
expect(r.ok).toBe(true);
expect(r.warnings.some((w) => /lucide icon name/.test(w))).toBe(false);
expect(r.errors.some((e) => /lucide icon/.test(e))).toBe(false);
});
it('scaffolds a client that opts into the design kit via the marker (source stays one line)', () => {
@@ -449,6 +486,7 @@ describe('scaffold + validate CLIs', () => {
const m = JSON.parse(fs.readFileSync(path.join(dir, 'trek-plugin.json'), 'utf8'));
expect(m.type).toBe('trip-page');
expect(fs.existsSync(path.join(dir, 'client', 'index.html'))).toBe(true); // non-integration → gets a UI
makePublishable(dir);
expect(validatePluginDir(dir).ok).toBe(true);
});
@@ -485,9 +523,16 @@ describe('scaffold + validate CLIs', () => {
it('tolerates a UTF-8 BOM in trek-plugin.json (Windows editors add one)', () => {
scaffold('bom-plug', 'integration', tmp);
const mp = path.join(tmp, 'bom-plug', 'trek-plugin.json');
const dir = path.join(tmp, 'bom-plug');
makePublishable(dir);
const mp = path.join(dir, 'trek-plugin.json');
fs.writeFileSync(mp, '\uFEFF' + fs.readFileSync(mp, 'utf8'));
expect(validatePluginDir(path.join(tmp, 'bom-plug')).ok).toBe(true);
// A bare JSON.parse chokes on the BOM and reports "Unexpected token" against an invisible
// character \u2014 the manifest must still parse, and the plugin must still be publishable.
const r = validatePluginDir(dir);
expect(r.errors.some((e) => /not valid JSON/.test(e))).toBe(false);
expect(r.ok).toBe(true);
});
it('validatePluginDir flags a missing manifest', () => {
+48
View File
@@ -0,0 +1,48 @@
/**
* `shot` up to the point where it would need a browser.
*
* The screenshot path itself needs Playwright and a Chromium, which this suite has no business
* downloading — but everything that decides WHETHER to take a screenshot, and what to tell the
* author when it cannot, is ordinary logic and is where the useful behaviour lives.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { scaffold } from '../src/cli/create.js';
import { runShot, ShotError } from '../src/cli/shot.js';
describe('shot', () => {
let tmp: string;
beforeEach(() => { tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'shot-')); });
afterEach(() => { fs.rmSync(tmp, { recursive: true, force: true }); });
it('refuses a directory that is not a plugin', async () => {
await expect(runShot(tmp)).rejects.toThrow(/no trek-plugin.json/);
});
/**
* An integration plugin has no UI, so there is nothing to render — but it still NEEDS a
* screenshot, because the registry requires one and the store card shows it. Erroring out with
* "no UI" would be true and useless; say what to photograph instead.
*/
it('tells an integration author what to screenshot instead of failing blankly', async () => {
scaffold('int-plug', 'integration', tmp);
const err = await runShot(path.join(tmp, 'int-plug')).catch((e: unknown) => e);
expect(err).toBeInstanceOf(ShotError);
const message = (err as Error).message;
expect(message).toMatch(/no UI/i);
// The useful half: what to do about it.
expect(message).toMatch(/docs\/screenshot\.png/);
expect(message).toMatch(/notification|badge|settings/i);
});
it('does not boot a browser just to discover the plugin has no UI', async () => {
// The integration check must come BEFORE loadChromium, or an author with no Playwright gets
// "install Playwright" for a plugin Playwright could never have helped with.
scaffold('int-plug', 'integration', tmp);
const err = await runShot(path.join(tmp, 'int-plug')).catch((e: unknown) => e);
expect((err as Error).message).not.toMatch(/playwright/i);
});
});
+52
View File
@@ -0,0 +1,52 @@
/**
* Signing: the guard, and what it refuses to let you do.
*
* The PROMPT is interactive and not worth mocking a TTY for. The guard is the part that matters,
* because of what it prevents: a plugin that shipped signed and then publishes unsigned is refused
* by TREK on every instance that already has it (registry.service.ts, SIGNATURE_MISSING) — and
* before this, `preflight` caught that at step 4, AFTER the immutable GitHub release was cut. The
* author's tag was burned for a problem that was knowable before a single byte was packed.
*/
import { describe, it, expect } from 'vitest';
import { assertSigningAllowed, type SigningState } from '../src/cli/signing.js';
const state = (over: Partial<SigningState> = {}): SigningState => ({
hasKey: false,
keyPath: '/home/someone/.trek-plugin/signing.key',
publishedSigned: false,
...over,
});
describe('assertSigningAllowed', () => {
it('allows an unsigned publish of a plugin that was never published signed', () => {
expect(() => assertSigningAllowed(state(), undefined)).not.toThrow();
});
it('allows an unsigned publish even when a key happens to exist — signing stays a choice', () => {
// Having a key on the machine is not consent to sign. An author may keep one for another plugin.
expect(() => assertSigningAllowed(state({ hasKey: true }), undefined)).not.toThrow();
});
it('allows a signed publish of a plugin that was published signed', () => {
const s = state({ hasKey: true, publishedSigned: true, publishedKey: 'abc' });
expect(() => assertSigningAllowed(s, s.keyPath)).not.toThrow();
});
it('REFUSES an unsigned publish of a plugin that was published signed', () => {
const s = state({ hasKey: true, publishedSigned: true, publishedKey: 'abc' });
expect(() => assertSigningAllowed(s, undefined)).toThrow(/published SIGNED/i);
// The fix has to be actionable, and it has to name the key it found.
expect(() => assertSigningAllowed(s, undefined)).toThrow(/--sign/);
expect(() => assertSigningAllowed(s, undefined)).toThrow(new RegExp(s.keyPath));
});
it('explains the lost-key case rather than telling you to pass a flag you cannot honour', () => {
// Telling an author with no key to "re-run with --sign" is advice they cannot take. The key is
// gone; the only route left is a registry maintainer override, and saying so is the whole value.
const s = state({ hasKey: false, publishedSigned: true, publishedKey: 'abc' });
const run = () => assertSigningAllowed(s, undefined);
expect(run).toThrow(/LOST it/i);
expect(run).toThrow(/allow-key-change/);
expect(run).not.toThrow(/Re-run with --sign/);
});
});