mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-23 13:23:04 +00:00
fix(plugin-sdk): make require('trek-plugin-sdk') actually resolve everywhere
A freshly scaffolded plugin could not load anywhere: the npm package is
ESM-only (no require condition in its exports map), so the scaffold's
require('trek-plugin-sdk') threw ERR_PACKAGE_PATH_NOT_EXPORTED under
`trek-plugin dev` - and the runtime injection the wiki promised for the
plugin child never existed, so a packed plugin (node_modules stripped)
crashed with MODULE_NOT_FOUND after a real install.
- plugin child: inject a frozen {definePlugin, PLUGIN_API_VERSION} shim
for require('trek-plugin-sdk'); subpaths fail with a pointed error
- trek-plugin dev: inject the exact same shim, so a fresh scaffold runs
with zero npm install and dev parity with production holds
- npm package: ship a real CommonJS build (dist/cjs + require export
conditions) so the installed package also requires cleanly on Node 18+
- create: scaffold a package.json (type commonjs, SDK as devDependency,
npx scripts); print resolvable `npx trek-plugin-sdk ...` hints
- wiki: package.json in the scaffold tree + publishing checklist, and
document the zero-install dev flow
This commit is contained in:
@@ -15,7 +15,7 @@ import net from 'node:net';
|
||||
import dns from 'node:dns';
|
||||
import dgram from 'node:dgram';
|
||||
import { createRequire } from 'node:module';
|
||||
import { createPluginContext, type ChildTransport, type PluginContext, type PluginDefinition } from './plugin-sdk';
|
||||
import { createPluginContext, definePlugin, PLUGIN_API_VERSION, type ChildTransport, type PluginContext, type PluginDefinition } from './plugin-sdk';
|
||||
import { isBlockedIp, makeHostAllow, classifyConnect, dgramSendTarget, dgramConnectTarget } from './egress-policy';
|
||||
import type { Envelope, RpcError } from '../protocol/envelope';
|
||||
|
||||
@@ -47,12 +47,37 @@ const transport: ChildTransport = {
|
||||
let def: PluginDefinition | null = null;
|
||||
let ctx: PluginContext | null = null;
|
||||
|
||||
/**
|
||||
* Make `require('trek-plugin-sdk')` resolve inside the child WITHOUT the plugin
|
||||
* vendoring the package: the shim below is served from memory for every require
|
||||
* of that name, anywhere in the plugin's module graph. This is what lets `pack`
|
||||
* strip node_modules and still keep the scaffold's
|
||||
* `const { definePlugin } = require('trek-plugin-sdk')` working in production.
|
||||
* Subpaths (`trek-plugin-sdk/testing`) are build/test-time tools and fail with a
|
||||
* pointed message instead of a confusing MODULE_NOT_FOUND.
|
||||
*/
|
||||
function installSdkInjection(requirePlugin: NodeJS.Require): void {
|
||||
const nodeModule = requirePlugin('node:module') as {
|
||||
_load: (request: string, parent: unknown, isMain: boolean) => unknown;
|
||||
};
|
||||
const realLoad = nodeModule._load;
|
||||
const shim = Object.freeze({ definePlugin, PLUGIN_API_VERSION });
|
||||
nodeModule._load = function (request: string, parent: unknown, isMain: boolean): unknown {
|
||||
if (request === 'trek-plugin-sdk') return shim;
|
||||
if (request.startsWith('trek-plugin-sdk/')) {
|
||||
throw new Error(`${request} is a build/test-time module — only 'trek-plugin-sdk' itself is injected inside TREK`);
|
||||
}
|
||||
return realLoad.call(this, request, parent, isMain);
|
||||
};
|
||||
}
|
||||
|
||||
async function boot(config: Record<string, unknown>): Promise<void> {
|
||||
try {
|
||||
// createRequire works whether this bootstrap runs as CJS (prod dist) or ESM
|
||||
// (tsx in tests), so `require` being undefined in ESM never bites us.
|
||||
const entry = path.join(pluginDir, 'server', 'index.js');
|
||||
const requirePlugin = createRequire(entry);
|
||||
installSdkInjection(requirePlugin);
|
||||
const mod = requirePlugin(entry);
|
||||
def = mod && mod.default ? (mod.default as PluginDefinition) : (mod as PluginDefinition);
|
||||
ctx = createPluginContext(pluginId, config, transport);
|
||||
|
||||
@@ -8,6 +8,9 @@
|
||||
* child holds no db handle, no secrets, no network by default.
|
||||
*/
|
||||
|
||||
/** Mirrors the published package's constant — bumped on any breaking API change. */
|
||||
export const PLUGIN_API_VERSION = 1 as const;
|
||||
|
||||
export interface PluginContext {
|
||||
readonly id: string;
|
||||
readonly config: Readonly<Record<string, unknown>>;
|
||||
|
||||
@@ -92,6 +92,33 @@ describe('PluginSupervisor — isolated runtime', () => {
|
||||
expect(events.some((e) => e.topic === '__log')).toBe(true);
|
||||
});
|
||||
|
||||
it('injects require(trek-plugin-sdk) — a scaffold-style plugin loads with no node_modules', async () => {
|
||||
const events: Array<{ topic: string; data: unknown }> = [];
|
||||
sup = makeSupervisor(events);
|
||||
|
||||
writePlugin(
|
||||
'scaffolded',
|
||||
`const { definePlugin, PLUGIN_API_VERSION } = require('trek-plugin-sdk');
|
||||
let testingError = '';
|
||||
try { require('trek-plugin-sdk/testing'); } catch (e) { testingError = e.message; }
|
||||
module.exports = definePlugin({
|
||||
async onLoad() {
|
||||
process.send({ k: 'evt', topic: 'diag', data: { api: PLUGIN_API_VERSION, fn: typeof definePlugin, testingError } });
|
||||
},
|
||||
routes: [{ method: 'GET', path: '/hello', auth: true, async handler() { return { status: 200 }; } }],
|
||||
});`,
|
||||
);
|
||||
|
||||
await sup.activate('scaffolded', new Set(['db:own']), {});
|
||||
expect(sup.isActive('scaffolded')).toBe(true);
|
||||
|
||||
const diag = events.find((e) => e.topic === 'diag')?.data as { api: number; fn: string; testingError: string };
|
||||
expect(diag).toBeTruthy();
|
||||
expect(diag.api).toBe(1); // the injected shim, not a vendored copy
|
||||
expect(diag.fn).toBe('function');
|
||||
expect(diag.testingError).toMatch(/build\/test-time/); // subpaths fail with a pointed message
|
||||
});
|
||||
|
||||
it('a plugin that throws in onLoad fails activation and is marked error — the host survives', async () => {
|
||||
const events: Array<{ topic: string; data: unknown }> = [];
|
||||
sup = makeSupervisor(events);
|
||||
|
||||
Reference in New Issue
Block a user