Files
Ekklesia/packages/module-pack/tests/support/fixture-module.ts
T
ekklesiaandClaude Opus 5.5 98e59d4ba0
CI / verify (pull_request) Successful in 1m5s
CI / infrastructure-smoke (pull_request) Successful in 35s
CI / migration-smoke (pull_request) Successful in 1m52s
CI / package-release (pull_request) Successful in 35s
CI / image-build (pull_request) Successful in 31s
CI / deploy-smoke (same-origin) (pull_request) Successful in 45s
CI / deploy-smoke (split) (pull_request) Successful in 1m30s
CI / package-publication (pull_request) Successful in 44s
chore(release): prepare 0.2.0
Every platform workspace package and every public @ekklesia/* package
declares 0.2.0, and the deploy README's image build example names it.
templates/module keeps its own version.

0.2.0, not 0.1.3: before 1.0 a minor version is the breaking one
(docs/development/releases.md, ADR 0054), and since 0.1.2 main has
broken modules, module authors, and operators:
- #64 (ADR 0048): one generic image; installed modules live outside it;
- #66, #72 (ADR 0049, 0050): modules install as Module Package v1, and
  move to the Module Database ABI;
- #71: the manifest v8 cutover; v7 manifests are refused;
- #79 (ADR 0053): the curated SDK drops defineModuleSchema and the
  legacy ModuleDatabase type;
plus #67 (AGPL), #74, #77 (licensing, native targets), and the public
package train (#80, #81). It is also the first package train to publish:
0.1.2 never will be.

Because 0.2.0 is outside ^0.1.0, the same change moves to ^0.2.0:
- the standalone fixture's @ekklesia ranges and its exact module-pack pin;
- the compatibility ranges of the modules built for this release: the
  template, the standalone fixture, and the native proof module;
- the test fixtures that model a module of the current release, or the
  current platform's versions;
- the module-development guide's examples, and the release guide, which
  now names what a minor bump moves.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-08 17:26:13 -05:00

321 lines
12 KiB
TypeScript

import {
cp,
lstat,
mkdir,
mkdtemp,
readFile,
realpath,
rm,
symlink,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
/**
* Generated module fixtures for the packager's tests: a built module directory in a temporary
* location, whose `node_modules` links to the real Module SDK and Drizzle this package depends on.
* Everything a development module directory holds is there, including what must never ship
* (`src/`, `tests/`, declarations, source maps, `workspace:` ranges), so a test can prove the
* packager leaves it out.
*/
const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
export interface FakePackage {
readonly name: string;
readonly version?: string;
readonly packageJson?: Record<string, unknown>;
/** Files relative to the fake package's root. */
readonly files?: Record<string, string | Uint8Array>;
}
export interface FixtureModuleOptions {
readonly databaseAbi?: 1;
readonly id?: string;
readonly license?: unknown;
readonly licenseText?: string | Uint8Array;
readonly version?: string;
readonly serverSource?: string;
readonly withModuleDatabase?: boolean;
readonly withSchema?: boolean;
/** The module's `engines` field; omitted from `package.json` when `null`. */
readonly engines?: Record<string, unknown> | null;
/** How the module's `@ekklesia/*` dependencies are installed: linked to this workspace's packages
* (the default), or copied as real directories into a flat `node_modules`, as a registry install
* lays them out. */
readonly ekklesiaInstall?: "workspace" | "registry";
readonly fakePackages?: readonly FakePackage[];
readonly manifest?: (manifest: Record<string, unknown>) => Record<string, unknown>;
}
const temporaryDirectories: string[] = [];
export async function cleanupFixtures(): Promise<void> {
await Promise.all(
temporaryDirectories
.splice(0)
.map((directory) => rm(directory, { force: true, recursive: true })),
);
}
export async function scratchDirectory(prefix = "ekklesia-pack-"): Promise<string> {
const directory = await realpath(await mkdtemp(path.join(tmpdir(), prefix)));
temporaryDirectories.push(directory);
return directory;
}
async function write(file: string, contents: string | Uint8Array): Promise<void> {
await mkdir(path.dirname(file), { recursive: true });
await writeFile(file, contents);
}
const defaultServer = (
id: string,
version: string,
databaseAbi?: 1,
) => `import { defineModuleRuntime } from "@ekklesia/module-sdk";
export default defineModuleRuntime({ ${databaseAbi === 1 ? "database: { abi: 1 }, " : ""}id: ${JSON.stringify(id)}, version: ${JSON.stringify(version)}, register() {} });
`;
const schemaSource = (id: string, databaseAbi?: 1) => `import { createModuleTable${
databaseAbi === 1 ? ", moduleDrizzleSchemaMetadata" : ""
} } from "@ekklesia/module-database/drizzle";
import { text, uuid } from "drizzle-orm/pg-core";
export const records = createModuleTable(${JSON.stringify(id)})("records", {
id: uuid("id").primaryKey(),
value: text("value").notNull(),
});
export default ${
databaseAbi === 1
? `moduleDrizzleSchemaMetadata(${JSON.stringify(id)}, { records })`
: `{ moduleId: ${JSON.stringify(id)}, tables: { records } }`
};
`;
export async function fixtureModule(options: FixtureModuleOptions = {}): Promise<string> {
const id = options.id ?? "example";
const version = options.version ?? "0.1.0";
const root = await scratchDirectory("ekklesia-pack-fixture-");
const moduleDirectory = path.join(root, id);
const tableName = `${id.replaceAll("-", "_")}_records`;
const usesModuleDatabase =
options.withModuleDatabase || options.withSchema || options.databaseAbi === 1;
const engines = options.engines === undefined ? { node: ">=24.11.0 <25" } : options.engines;
const baseManifest: Record<string, unknown> = {
manifestVersion: 8,
id,
name: `${id} module`,
version,
compatibility: { platform: "^0.2.0", moduleSdk: "^0.2.0" },
...(options.databaseAbi === 1 ? { database: { abi: 1 } } : {}),
capabilities: [],
permissions: [],
entrypoints: {
server: "./dist/server/index.js",
...(options.withSchema ? { schema: "./dist/schema/index.js" } : {}),
migrations: "./drizzle",
},
};
const manifest = options.manifest ? options.manifest(baseManifest) : baseManifest;
await write(
path.join(moduleDirectory, "ekklesia.module.json"),
`${JSON.stringify(manifest, null, 2)}\n`,
);
await write(
path.join(moduleDirectory, "package.json"),
`${JSON.stringify(
{
name: `@test/module-${id}`,
version,
license: Object.hasOwn(options, "license") ? options.license : "MIT",
private: true,
type: "module",
...(engines === null ? {} : { engines }),
scripts: { build: "tsc" },
dependencies: {
"@ekklesia/module-sdk": "workspace:*",
...(usesModuleDatabase ? { "@ekklesia/module-database": "workspace:*" } : {}),
"drizzle-orm": "0.45.2",
},
devDependencies: { typescript: "7.0.2" },
exports: { ".": "./dist/server/index.js" },
ekklesia: { layer: "module" },
},
null,
2,
)}\n`,
);
await write(
path.join(moduleDirectory, "LICENSE"),
options.licenseText ?? "MIT License\n\nCopyright (c) 2026 Example Module\n",
);
await write(
path.join(moduleDirectory, "dist/server/index.js"),
options.serverSource ?? defaultServer(id, version, options.databaseAbi),
);
await write(path.join(moduleDirectory, "dist/server/index.js.map"), '{"version":3}\n');
await write(path.join(moduleDirectory, "dist/server/index.d.ts"), "export {};\n");
if (options.withSchema) {
await write(
path.join(moduleDirectory, "dist/schema/index.js"),
schemaSource(id, options.databaseAbi),
);
}
await write(path.join(moduleDirectory, "src/server/index.ts"), "export {};\n");
await write(path.join(moduleDirectory, "tests/server.test.ts"), "export {};\n");
await write(path.join(moduleDirectory, "README.md"), "# Development notes\n");
await write(
path.join(moduleDirectory, "drizzle/0000_initial.sql"),
`CREATE TABLE "${tableName}" ("id" uuid PRIMARY KEY NOT NULL, "value" text NOT NULL);\n`,
);
await write(
path.join(moduleDirectory, "drizzle/meta/_journal.json"),
JSON.stringify({
version: "7",
dialect: "postgresql",
entries: [
{ idx: 0, version: "7", when: 1_700_000_000_000, tag: "0000_initial", breakpoints: true },
],
}),
);
await write(
path.join(moduleDirectory, "drizzle/meta/_ekklesia.json"),
JSON.stringify({
version: 1,
moduleId: id,
entries: [{ tag: "0000_initial", destructive: { mode: "none" } }],
}),
);
await write(
path.join(moduleDirectory, "drizzle/meta/0000_snapshot.json"),
JSON.stringify({
version: "7",
dialect: "postgresql",
id: "10000000-0000-4000-8000-000000000001",
prevId: "00000000-0000-0000-0000-000000000000",
}),
);
// The module's dependencies: the real packages this package depends on, either linked as a
// workspace links them, or copied as a registry install would place them.
const modules = path.join(moduleDirectory, "node_modules");
await mkdir(path.join(modules, "@ekklesia"), { recursive: true });
const ekklesiaPackages = [
"module-sdk",
...(usesModuleDatabase ? ["module-database"] : []),
] as const;
if (options.ekklesiaInstall === "registry") {
await installLikeARegistry(modules, [...ekklesiaPackages, "contracts"]);
} else {
for (const name of ekklesiaPackages) {
await symlink(
await realpath(path.join(packageRoot, "node_modules", "@ekklesia", name)),
path.join(modules, "@ekklesia", name),
);
}
}
await symlink(
await realpath(path.join(packageRoot, "node_modules", "drizzle-orm")),
path.join(modules, "drizzle-orm"),
);
for (const fake of options.fakePackages ?? []) {
const fakeRoot = path.join(modules, ...fake.name.split("/"));
await write(
path.join(fakeRoot, "package.json"),
JSON.stringify({
name: fake.name,
version: fake.version ?? "1.0.0",
type: "module",
main: "index.js",
license: "MIT",
...fake.packageJson,
}),
);
for (const [relative, contents] of Object.entries(fake.files ?? {})) {
await write(path.join(fakeRoot, relative), contents);
}
}
return moduleDirectory;
}
/**
* Copies each `@ekklesia/*` package's published files (`package.json`, `dist`, `LICENSE`) into a flat
* `node_modules` as real directories, and links the third-party packages they depend on beside them:
* the layout a registry install produces, with nothing pointing back into the workspace's sources.
*/
async function installLikeARegistry(modules: string, names: readonly string[]): Promise<void> {
for (const name of names) {
const source = await realpath(path.join(packageRoot, "..", name));
const target = path.join(modules, "@ekklesia", name);
await mkdir(target, { recursive: true });
for (const entry of ["package.json", "dist", "LICENSE"]) {
await cp(path.join(source, entry), path.join(target, entry), {
force: false,
recursive: true,
}).catch((error: NodeJS.ErrnoException) => {
if (error.code !== "ENOENT") throw error;
});
}
const manifest = JSON.parse(
await readFile(path.join(source, "package.json"), "utf8"),
) as Record<string, Record<string, string> | undefined>;
for (const dependency of Object.keys(manifest.dependencies ?? {})) {
const link = path.join(modules, ...dependency.split("/"));
if (dependency.startsWith("@ekklesia/") || (await exists(link))) continue;
await mkdir(path.dirname(link), { recursive: true });
await symlink(await realpath(path.join(source, "node_modules", dependency)), link);
}
}
}
async function exists(file: string): Promise<boolean> {
try {
await lstat(file);
return true;
} catch {
return false;
}
}
export const SOURCE_REVISION = "86ae907f59458508e3277666cdd214f5bd7c1078";
const nativeFixtureSource = path.join(packageRoot, "tests", "fixtures", "native-module");
/**
* The checked-in native proof module (`tests/fixtures/native-module`), copied to a fresh, unrelated
* temporary directory with `node_modules` linking the real sharp and Module SDK this package's
* workspace installed, as a module's own install would provide them.
*/
export async function nativeFixtureModule(): Promise<string> {
// Inside this package, beside its own node_modules, as a module checkout sits beside its own: a
// bundle's module keys are paths relative to the module, so a copy in the system temporary
// directory would bundle paths that climb out of it and into this checkout.
const fixtures = path.join(packageRoot, ".fixtures");
await mkdir(fixtures, { recursive: true });
const root = await realpath(await mkdtemp(path.join(fixtures, "native-")));
temporaryDirectories.push(root);
const moduleDirectory = path.join(root, "native-proof");
await cp(nativeFixtureSource, moduleDirectory, { recursive: true });
const modules = path.join(moduleDirectory, "node_modules");
await mkdir(path.join(modules, "@ekklesia"), { recursive: true });
await symlink(
await realpath(path.join(packageRoot, "node_modules", "sharp")),
path.join(modules, "sharp"),
);
await symlink(
await realpath(path.join(packageRoot, "node_modules", "@ekklesia", "module-sdk")),
path.join(modules, "@ekklesia", "module-sdk"),
);
return moduleDirectory;
}
/** The workspace's real installed package, for tests that build fake native packages from it. */
export async function installedPackageFile(...segments: string[]): Promise<string> {
return realpath(path.join(packageRoot, "node_modules", ...segments));
}