Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/25175-create-plugin-scaffold-test.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@objectstack/cli': patch
---

fix(cli): `os create plugin` ships a starter test, so a new project's `npm test` passes

Clause-②: no
Metadata-protocol: none

A project made by `os create plugin NAME` declared `"test": "vitest"` and contained no test file, so its first `npm test` exited 1 with `No test files found, exiting with code 1`. The template now writes `src/index.test.ts`, which runs the checks the kernel runs on a plugin when it loads one: a `name`, an `init` function, and the protocol's `PluginSchema`. It boots no kernel; its header links the `@objectstack/verify` harness for tests that need one. The `test` script is now `vitest run`, one pass that exits.

The starter test lives in `src/`, which `tsc` compiles, so the template also writes `tsconfig.build.json`: it extends `tsconfig.json` and excludes `src/**/*.test.ts`, and `build` and `dev` now run `tsc -p tsconfig.build.json`. `typecheck` still reads `tsconfig.json`, so a type error in a test still fails it, while `dist/` holds no compiled test and `npm test` after `npm run build` runs each test once.

**An existing project made by an earlier `os create plugin`** still has no test file. Add a `*.test.ts` file, for example a copy of the `src/index.test.ts` that a new `os create plugin NAME` writes. If you put it under `src/`, also copy `tsconfig.build.json` and point the `build` and `dev` scripts at it (`tsc -p tsconfig.build.json`), or `tsc` compiles the test into `dist/` and vitest runs it twice.
4 changes: 3 additions & 1 deletion content/docs/plugins/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -98,10 +98,12 @@ os create plugin my-feature
# plugin-my-feature/
# ├── package.json
# ├── tsconfig.json
# ├── tsconfig.build.json
# ├── README.md
# ├── pnpm-workspace.yaml
# └── src/
# └── index.ts
# ├── index.ts
# └── index.test.ts

cd plugin-my-feature
pnpm install
Expand Down
2 changes: 2 additions & 0 deletions content/docs/protocol/kernel/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -398,9 +398,11 @@ os create plugin slack-integration
plugin-slack-integration/
package.json # name, version, dependencies (@objectstack/spec, zod)
tsconfig.json # self-contained, extends nothing outside the project
tsconfig.build.json # what `pnpm build` compiles: tsconfig.json minus the tests
pnpm-workspace.yaml # the pnpm build approvals a fresh install needs
src/
index.ts # default-export Plugin object (name, version, init, destroy)
index.test.ts # starter test: the checks the kernel runs when it loads a plugin
README.md
```

Expand Down
2 changes: 2 additions & 0 deletions content/docs/protocol/kernel/plugin-spec.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -893,7 +893,9 @@ os create plugin crm

✓ Created package.json
✓ Created tsconfig.json
✓ Created tsconfig.build.json
✓ Created src/index.ts
✓ Created src/index.test.ts
✓ Created README.md
✓ Created pnpm-workspace.yaml

Expand Down
59 changes: 56 additions & 3 deletions packages/cli/src/commands/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -392,10 +392,15 @@ export const templates: Record<string, CreateTemplate> = {
// Not a build-script allowlist (that is pnpm-workspace.yaml) — the
// minimum pnpm that reads that file at all.
...(standalone ? { engines: { pnpm: SCAFFOLD_PNPM_RANGE } } : {}),
// `build` and `dev` compile through `tsconfig.build.json`, which
// leaves the starter test out of `dist`; `typecheck` reads
// `tsconfig.json`, which keeps it in. See `tsconfig.build.json` below.
// `test` is `vitest run`, one pass that exits, as `os init` emits:
// bare `vitest` watches in a terminal and never returns.
scripts: {
build: 'tsc',
dev: 'tsc --watch',
test: 'vitest',
build: 'tsc -p tsconfig.build.json',
dev: 'tsc -p tsconfig.build.json --watch',
test: 'vitest run',
typecheck: 'tsc --noEmit',
},
keywords: ['objectstack', 'plugin', name],
Expand Down Expand Up @@ -432,6 +437,20 @@ export const templates: Record<string, CreateTemplate> = {
},
include: ['src/**/*'],
},
// The config `build` and `dev` compile with (#25175). `tsconfig.json`
// includes all of `src/`, the starter test with it, so `typecheck`
// still catches a type error in a test. Built through that same config,
// `tsc` also emitted `dist/index.test.js`, and vitest, whose default
// exclude is only `node_modules` and `.git`, then collected the
// compiled copy beside the source: `npm run build && npm test` ran the
// suite twice, and the package shipped its tests. Excluding the tests
// HERE, never in `tsconfig.json`, keeps both halves. ⛔ `exclude` in an
// extending config replaces the base list rather than adding to it, so
// `dist` and `node_modules` are restated.
'tsconfig.build.json': () => ({
extends: './tsconfig.json',
exclude: ['dist', 'node_modules', 'src/**/*.test.ts'],
}),
'src/index.ts': (name: string) => `import type { Plugin } from '@objectstack/spec/contracts';

/**
Expand All @@ -453,6 +472,40 @@ export const ${sanitizeIdentifier(name)}Plugin: Plugin = {
};

export default ${sanitizeIdentifier(name)}Plugin;
`,
// The starter test the `test` script runs (#25175). Without a test
// file, `vitest run` exits 1 with "No test files found", so a fresh
// project failed its own `npm test` — the defect `os init -t plugin`
// had, closed there by `package.test.ts`. This one runs the checks the
// kernel runs on a plugin at `use()`, before any of its code: the
// loader's `name` and `init` presence checks, then the protocol's
// `PluginSchema` (`assertPluginContract` in `@objectstack/core`),
// through `@objectstack/spec`, which the manifest already declares. It
// deliberately boots no kernel: that needs `@objectstack/verify`
// declared, and the comment points the author at the documented
// harness for that step instead. `test/scaffold-test-script-passes.test.ts`
// runs it in a sandbox, after a build as well as before one.
'src/index.test.ts': (name: string) => `import { describe, expect, it } from 'vitest';
import { PluginSchema } from '@objectstack/spec/kernel';
import plugin from './index';

// The kernel checks a plugin when it is handed one, before it runs any of its
// code: a plugin with no name or no init is refused outright, and every other
// key is judged against the protocol's PluginSchema. This file runs the same
// checks, so a plugin the kernel would refuse fails here first.
//
// To test what the plugin does once it runs, such as the services its init
// registers, boot it in a real stack with @objectstack/verify:
// https://objectstack.ai/docs/protocol/kernel/plugin-spec#a-runtime-plugin
describe('the ${name} plugin', () => {
it('passes the checks the kernel runs when it loads a plugin', () => {
expect(plugin.name).toBeTruthy();
expect(typeof plugin.init).toBe('function');

const contract = PluginSchema.safeParse(plugin);
expect(contract.error?.issues ?? []).toEqual([]);
});
});
`,
'README.md': (name: string) => {
const packageName = pluginPackageName(placement, name);
Expand Down
143 changes: 140 additions & 3 deletions packages/cli/test/scaffold-test-script-passes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,34 @@
*
* Derived from `TEMPLATES`: every template whose rendered `package.json`
* declares a `test` script. A template that grows one later is swept the day
* it lands. `os create plugin` emits a `test` script too and is not swept
* here yet; its starter test ships with the docs listings its file tree is
* pinned against (`create-plugin-docs-parity.test.ts`).
* it lands.
*
* The type layer of the emitted test is `scaffold-emission-typechecks.test.ts`'s
* axis (it compiles every `srcFiles` entry under the shipped `tsconfig.json`),
* so it is not restated here.
*
* ## `os create`
*
* `os create plugin` had the same defect (its script was bare `vitest`) and
* ships `src/index.test.ts`. Its roster is derived from `create`'s
* `templates`, in the default (standalone) placement: the `--in-repo`
* placement's `tsconfig.json` extends this monorepo's root config, so it has no
* meaning in a sandbox outside it. Two more cases than `os init` gets, because
* `create`'s `build` is plain `tsc` and its starter test lives in `src/`, the
* directory `tsc` compiles:
*
* - after the emitted `build` script, `test` still runs exactly the shipped
* test files, and `dist/` holds no compiled test. Built through
* `tsconfig.json`, `tsc` emitted `dist/index.test.js` and vitest collected
* it beside the source: the suite ran twice and the package shipped its
* tests. `tsconfig.build.json` is what keeps them out;
* - the emitted `typecheck` script still type-checks the starter test: a type
* error planted in it fails the script. Moving the test out of `src/`, or
* excluding it in `tsconfig.json`, would have kept `dist/` clean by hiding
* the test from the type checker.
*
* `create`'s whole emission lands nowhere `scaffold-emission-typechecks`
* compiles, so that second case is this file's to hold.
*/

import { afterAll, describe, expect, it } from 'vitest';
Expand All @@ -65,6 +86,7 @@ import {
SCAFFOLD_TSCONFIG_INCLUDE_WITH_ROOT_CONFIG,
writeTemplateSrcFiles,
} from '../src/commands/init.js';
import { DEFAULT_PLACEMENT, templates as createTemplates } from '../src/commands/create.js';
import { childEnv } from './helpers/serve-process.js';

const HERE = path.dirname(fileURLToPath(import.meta.url));
Expand Down Expand Up @@ -149,6 +171,17 @@ function resolveBin(root: string, manifest: Manifest, bin: string): string {
throw new Error(`no declared dependency of the emitted project provides the \`${bin}\` bin`);
}

/** Spawn any other emitted script in the project; its exit code and output. */
function runScript(root: string, manifest: Manifest, script: string): { code: number | null; output: string } {
const [bin, ...args] = manifest.scripts![script].trim().split(/\s+/);
const res = spawnSync(process.execPath, [resolveBin(root, manifest, bin), ...args], {
cwd: root,
encoding: 'utf-8',
env: childEnv({ NO_COLOR: '1', CI: '1' }),
});
return { code: res.status, output: `${res.stdout ?? ''}${res.stderr ?? ''}` };
}

/** Spawn the emitted `test` script, plus a JSON reporter, in the project. */
function runTestScript(root: string, manifest: Manifest) {
const [bin, ...args] = manifest.scripts!.test.trim().split(/\s+/);
Expand Down Expand Up @@ -231,3 +264,107 @@ describe('[#25175] an `os init` template with a `test` script passes it out of t
expect(json?.numPassedTests ?? 0).toBe(0);
}, 120_000);
});

/** The `os create` templates whose emitted manifest declares a `test` script. */
const CREATE_ROSTER = Object.keys(createTemplates).filter((key) => {
const render = createTemplates[key].filesFor(DEFAULT_PLACEMENT)['package.json'];
return typeof (render(PROJECT_NAME) as Manifest).scripts?.test === 'string';
});

/** Materialise one `os create` template the way `Create.run()` writes it. */
function emitCreate(templateKey: string): { root: string; manifest: Manifest; testFiles: string[] } {
const root = fs.mkdtempSync(path.join(TMP_ROOT, `create-${templateKey}-`));
for (const [rel, render] of Object.entries(createTemplates[templateKey].filesFor(DEFAULT_PLACEMENT))) {
const content = render(PROJECT_NAME);
fs.mkdirSync(path.dirname(path.join(root, rel)), { recursive: true });
fs.writeFileSync(
path.join(root, rel),
typeof content === 'string' ? content : JSON.stringify(content, null, 2) + '\n',
);
}
const manifest = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')) as Manifest;
linkDeclaredDependencies(root, manifest);
const testFiles = Object.keys(createTemplates[templateKey].filesFor(DEFAULT_PLACEMENT)).filter((rel) =>
/\.test\.[cm]?[jt]sx?$/.test(rel),
);
return { root, manifest, testFiles };
}

/** Every file under `dir`, relative to it. */
function listFiles(dir: string): string[] {
if (!fs.existsSync(dir)) return [];
return fs.readdirSync(dir, { recursive: true, withFileTypes: true })
.filter((entry) => entry.isFile())
.map((entry) => path.relative(dir, path.join(entry.parentPath, entry.name)))
.sort();
}

describe('[#25175] an `os create` template with a `test` script passes it out of the box', () => {
it('the roster is populated, and still holds the template the defect was measured on', () => {
expect(CREATE_ROSTER.length).toBeGreaterThan(0);
expect(CREATE_ROSTER).toContain('plugin');
});

it.each(CREATE_ROSTER)(
'`os create %s`: the emitted `test` script runs the shipped tests and exits 0',
(templateKey) => {
const { root, manifest, testFiles } = emitCreate(templateKey);
expect(testFiles.length, `\`os create ${templateKey}\` declares a test script and emits no test file`).toBeGreaterThan(0);

const { code, output, json } = runTestScript(root, manifest);

expect(code, `\`${manifest.scripts!.test}\` in a fresh \`os create ${templateKey}\` project:\n${output}`).toBe(0);
expect(json, `the run wrote no JSON report:\n${output}`).not.toBeNull();
expect(json!.numFailedTests).toBe(0);
expect(json!.numPassedTests).toBeGreaterThan(0);
expect(json!.testResults.map((r) => path.relative(root, r.name)).sort()).toEqual([...testFiles].sort());
},
120_000,
);

it.each(CREATE_ROSTER)(
'`os create %s`: after the emitted `build`, `dist/` holds no test and `test` runs the shipped tests once',
(templateKey) => {
const { root, manifest, testFiles } = emitCreate(templateKey);

const build = runScript(root, manifest, 'build');
expect(build.code, `\`${manifest.scripts!.build}\`:\n${build.output}`).toBe(0);
const dist = listFiles(path.join(root, 'dist'));
// Calibration: a build that wrote nothing would pass the next line vacuously.
expect(dist).toContain('index.js');
expect(dist.filter((rel) => /\.test\./.test(rel)), 'the build compiled the starter test into dist/').toEqual([]);

const { code, output, json } = runTestScript(root, manifest);
expect(code, output).toBe(0);
expect(json!.testResults.map((r) => path.relative(root, r.name)).sort()).toEqual([...testFiles].sort());
},
120_000,
);

it.each(CREATE_ROSTER)(
'`os create %s`: the emitted `typecheck` script type-checks the starter test',
(templateKey) => {
const { root, manifest, testFiles } = emitCreate(templateKey);

const clean = runScript(root, manifest, 'typecheck');
expect(clean.code, `\`${manifest.scripts!.typecheck}\` on the fresh scaffold:\n${clean.output}`).toBe(0);

const planted = path.join(root, testFiles[0]);
fs.appendFileSync(planted, '\nexport const planted: number = \'not a number\';\n');
const red = runScript(root, manifest, 'typecheck');
expect(red.code, 'a type error in the starter test passed `typecheck`: the test is outside the checked program').not.toBe(0);
expect(red.output).toContain(path.basename(testFiles[0]));
},
120_000,
);

it('CONTROL: the same project without its shipped tests fails the `test` script (the defect)', () => {
const { root, manifest, testFiles } = emitCreate(CREATE_ROSTER[0]);
for (const rel of testFiles) fs.rmSync(path.join(root, rel));

const { code, json } = runTestScript(root, manifest);

expect(code, 'an empty suite must fail; a harness that reads 0 here measures nothing').not.toBe(0);
expect(json?.numPassedTests ?? 0).toBe(0);
}, 120_000);
});
Loading