@theholocron/kyber 5.0.0-alpha.344 → 5.0.0-alpha.346
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/README.md +24 -0
- package/dist/plugins.d.mts +221 -0
- package/dist/plugins.mjs +216 -0
- package/dist/testing.mjs +1 -1
- package/package.json +12 -7
package/README.md
CHANGED
|
@@ -20,8 +20,32 @@ Published, so a second CLI can import it. `@theholocron/cli` is its first consum
|
|
|
20
20
|
| `/testing` | A test harness for a CLI: `createCliRunner` runs a built binary in a fresh directory with an environment built from nothing, `runCommand` runs one yargs command module through a real parse, `ensureBuilt` is a Vitest global setup that builds only when `dist` is missing or stale, and `hermeticCreateRequire` resolves modules only from one directory. |
|
|
21
21
|
| `/observability` | The logging and telemetry wiring of a CLI: `createCliLogger({ envPrefix, resolveAxiom? })` returns a memoized root logger (`buildCliLogger`, `getLogger`, `reportError`, `getRunId`, `resolveLogLevel`) whose level comes from `--log` / `--verbose` / `--quiet`, then `<PREFIX>_LOG_LEVEL`, then the config file, and is quiet on a terminal unless asked; `createCliTelemetry({ envPrefix, dsn, posthogKey, posthogHost })` returns Sentry error reporting and PostHog analytics behind `<PREFIX>_TELEMETRY=false`. `@theholocron/observability` is an optional peer. |
|
|
22
22
|
| `/config` | A `<name>.config.{ts,js,mjs,cjs,json}` for a new CLI: `createConfigSystem({ name, derive?, resolve, merge })` returns `defineConfig`, `loadConfig` (walks up to `.git`) and `compose()` (dedupe by `id`, all unmet `requires` in one `ConfigError`, per-key merge). Strategies: `lastWins`, `shallowMerge`, `union`, `mergeByKey`. `@theholocron/datapad` is an optional peer. |
|
|
23
|
+
| `/plugins` | A plugin system for a new CLI: `createPluginSystem({ packagePrefix, providers, communityPrefix?, configFile?, pluginOptions?, preload? })` returns a `PluginLoader` class and `resolvePackage`. `load()` imports each configured provider's package (from the working directory first, importer injectable), calls its `createPlugin(options)` and fills a registry typed by your capability map: `get(key)` is one implementation for a `single` capability and an array for a `many` one. A package may export a capability config (`{ provider, options? }`) whose preset options sit under the project's. A failing provider is recorded in `loadFailures()` and `get` rethrows its error; `load()` never throws for one. Also `assertPluginsResolvable`, `isModuleNotFound`, `resolvePluginPackage`, `defaultImporter` and `LoaderError`. |
|
|
23
24
|
| `/flags` | The options every command of a tool takes: `addGlobalOptions(parser, { describe?, cwd? })` declares `--dry-run`, a repeatable `--token` and `--cwd` once on the root; `tokenContext(values, report)` parses the `--token` values and reports a bad one without a stack trace; `groupMenu(parent, open)` is the hidden default command that makes a bare group (`tool repo`) do something useful; `InferArgs` types a command's handler arguments from its builder. |
|
|
24
25
|
|
|
26
|
+
## Build a plugin system
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
import { createPluginSystem } from "@theholocron/kyber/plugins";
|
|
30
|
+
|
|
31
|
+
type Capabilities = {
|
|
32
|
+
source: { cardinality: "single"; impl: Source };
|
|
33
|
+
notify: { cardinality: "many"; impl: Notifier };
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
const { PluginLoader } = createPluginSystem<Capabilities, Config, { repoRoot: string }>({
|
|
37
|
+
packagePrefix: "@acme/mytool-plugin-",
|
|
38
|
+
providers: (config) => config.providers,
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
const loader = new PluginLoader(config, { repoRoot: process.cwd() });
|
|
42
|
+
await loader.load();
|
|
43
|
+
loader.get("source"); // Source
|
|
44
|
+
loader.get("notify"); // Notifier[]
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
A plugin package exports `createPlugin(options)` returning `{ name, capabilities: { source: () => impl } }`.
|
|
48
|
+
|
|
25
49
|
## Usage
|
|
26
50
|
|
|
27
51
|
```ts
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
/** How many providers a capability resolves to: one (`"single"`) or several active at once (`"many"`). */
|
|
2
|
+
type Cardinality = "single" | "many";
|
|
3
|
+
/**
|
|
4
|
+
* The capabilities of a CLI as a type: each key maps to its cardinality and to the interface a provider implements.
|
|
5
|
+
* It exists only at the type level; it types `loader.get(key)` so a `single` key hands back one implementation and a
|
|
6
|
+
* `many` key an array.
|
|
7
|
+
* Declare it as a `type` alias, not an `interface` (an interface has no index signature).
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* type MyCapabilities = {
|
|
11
|
+
* source: { cardinality: "single"; impl: Source };
|
|
12
|
+
* notifications: { cardinality: "many"; impl: Notifier };
|
|
13
|
+
* };
|
|
14
|
+
*/
|
|
15
|
+
type CapabilityShape = Record<string, {
|
|
16
|
+
cardinality: Cardinality;
|
|
17
|
+
impl: unknown;
|
|
18
|
+
}>;
|
|
19
|
+
/** The capability keys of a {@link CapabilityShape}. */
|
|
20
|
+
type CapabilityKeyOf<Caps extends CapabilityShape> = Extract<keyof Caps, string>;
|
|
21
|
+
/** What `loader.get(key)` returns for `key`: one implementation for a `single` capability, an array for a `many`. */
|
|
22
|
+
type ResolvedCapability<Caps extends CapabilityShape, K extends CapabilityKeyOf<Caps>> = Caps[K]["cardinality"] extends "many" ? Caps[K]["impl"][] : Caps[K]["impl"];
|
|
23
|
+
/** A provider with its plugin package resolved. */
|
|
24
|
+
interface ProviderTuple {
|
|
25
|
+
/** The provider's short name, e.g. `github`. */
|
|
26
|
+
provider: string;
|
|
27
|
+
/** The package that implements it, e.g. `@acme/mycli-plugin-github`. */
|
|
28
|
+
packageName: string;
|
|
29
|
+
/** Options the config gives this provider. */
|
|
30
|
+
options: Record<string, unknown>;
|
|
31
|
+
}
|
|
32
|
+
/** What a capability is configured with: one provider, or a list of them. */
|
|
33
|
+
type ProviderEntry = {
|
|
34
|
+
cardinality: "single";
|
|
35
|
+
tuple: ProviderTuple;
|
|
36
|
+
} | {
|
|
37
|
+
cardinality: "many";
|
|
38
|
+
tuples: ProviderTuple[];
|
|
39
|
+
};
|
|
40
|
+
/** Imports a package by name. Injectable, so tests need no real packages installed. */
|
|
41
|
+
type PluginImporter = (packageName: string) => Promise<unknown>;
|
|
42
|
+
/**
|
|
43
|
+
* What a plugin's `createPlugin(options)` returns: a name, a factory per capability it implements, and whatever else
|
|
44
|
+
* the CLI lets a plugin carry (`Extra`, e.g. probes).
|
|
45
|
+
*/
|
|
46
|
+
type LoadedPlugin<Caps extends CapabilityShape, Extra extends object = Record<never, never>> = {
|
|
47
|
+
/** The plugin's name. */
|
|
48
|
+
name: string;
|
|
49
|
+
/** A factory for each capability the plugin implements; the loader calls the one it needs. */
|
|
50
|
+
capabilities: Partial<{ [K in CapabilityKeyOf<Caps>]: () => unknown; }>;
|
|
51
|
+
} & Extra;
|
|
52
|
+
/** The shape a plugin package must export: `createPlugin(options)`. */
|
|
53
|
+
interface PluginModule<Caps extends CapabilityShape, Extra extends object = Record<never, never>> {
|
|
54
|
+
/** Builds the plugin from the merged options. */
|
|
55
|
+
createPlugin: (options: Record<string, unknown>) => LoadedPlugin<Caps, Extra>;
|
|
56
|
+
}
|
|
57
|
+
/** The default export of a capability config package: a provider and the preset options to start it with. */
|
|
58
|
+
interface CapabilityConfigPackage {
|
|
59
|
+
/** The provider's short name or package. */
|
|
60
|
+
provider: string;
|
|
61
|
+
/** Preset options; the project's own options for the provider win over them. */
|
|
62
|
+
options?: Record<string, unknown>;
|
|
63
|
+
}
|
|
64
|
+
/** A provider that could not be loaded: a missing package, a bad token, an unimplemented capability. */
|
|
65
|
+
interface PluginLoadFailure<Key extends string = string> {
|
|
66
|
+
/** The capability that was being loaded. */
|
|
67
|
+
key: Key;
|
|
68
|
+
/** The provider's short name. */
|
|
69
|
+
provider: string;
|
|
70
|
+
/** The package that failed. */
|
|
71
|
+
packageName: string;
|
|
72
|
+
/** What went wrong. */
|
|
73
|
+
error: Error;
|
|
74
|
+
}
|
|
75
|
+
/** The part of a loader {@link assertPluginsResolvable} reads. Every `PluginLoader` satisfies it. */
|
|
76
|
+
interface PluginLoadReport {
|
|
77
|
+
/** The capability keys that loaded. */
|
|
78
|
+
loadedKeys(): readonly string[];
|
|
79
|
+
/** The providers that failed to load. */
|
|
80
|
+
loadFailures(): readonly PluginLoadFailure[];
|
|
81
|
+
}
|
|
82
|
+
/** What a {@link PluginSystemOptions.preload} step can do to the loader while it runs. */
|
|
83
|
+
interface PreloadApi<Caps extends CapabilityShape> {
|
|
84
|
+
/** Load one provider (import, `createPlugin`, capability factory) and return its implementation. Throws on failure. */
|
|
85
|
+
loadOne(key: CapabilityKeyOf<Caps>, tuple: ProviderTuple): Promise<unknown>;
|
|
86
|
+
/** Record a provider as failed, so `get` and `loadFailures` report it, and carry on. */
|
|
87
|
+
fail(key: CapabilityKeyOf<Caps>, tuple: ProviderTuple, err: unknown): void;
|
|
88
|
+
/** Put the loaded implementations of a capability in the registry. */
|
|
89
|
+
register(key: CapabilityKeyOf<Caps>, impls: unknown): void;
|
|
90
|
+
}
|
|
91
|
+
/** A step that runs before the providers load, and that loads some capabilities itself. */
|
|
92
|
+
interface PreloadStep<Caps extends CapabilityShape, Config, Context, LoadOptions> {
|
|
93
|
+
/** The capabilities the step loads, so the normal loop skips them. */
|
|
94
|
+
keys: readonly CapabilityKeyOf<Caps>[];
|
|
95
|
+
/** Runs once at the start of `load()`. */
|
|
96
|
+
run(api: PreloadApi<Caps>, input: {
|
|
97
|
+
config: Config;
|
|
98
|
+
context: Context;
|
|
99
|
+
options: LoadOptions | undefined;
|
|
100
|
+
}): Promise<void> | void;
|
|
101
|
+
}
|
|
102
|
+
/** What {@link createPluginSystem} needs to build a CLI's plugin loader. */
|
|
103
|
+
interface PluginSystemOptions<Caps extends CapabilityShape, Config, Context extends object, LoadOptions = undefined> {
|
|
104
|
+
/** What a short provider name is prefixed with to get its package, e.g. `@acme/mycli-plugin-`. */
|
|
105
|
+
packagePrefix: string;
|
|
106
|
+
/** The prefix of an unscoped third-party plugin package, e.g. `mycli-plugin-`; such names are used as they are. */
|
|
107
|
+
communityPrefix?: string;
|
|
108
|
+
/** The name of the config file, for the message when a capability is asked for and was never configured. */
|
|
109
|
+
configFile?: string;
|
|
110
|
+
/** Reads the resolved provider entries, by capability, out of the CLI's config. */
|
|
111
|
+
providers: (config: Config) => Partial<{ [K in CapabilityKeyOf<Caps>]: ProviderEntry; }>;
|
|
112
|
+
/**
|
|
113
|
+
* The options handed to `createPlugin` for one provider. Defaults to the context spread first and the provider's own
|
|
114
|
+
* options over it. Return what you want, with the provider's `tuple.options` last so they win.
|
|
115
|
+
*/
|
|
116
|
+
pluginOptions?: (input: {
|
|
117
|
+
config: Config;
|
|
118
|
+
context: Context;
|
|
119
|
+
tuple: ProviderTuple;
|
|
120
|
+
}) => Record<string, unknown>;
|
|
121
|
+
/** A step that loads some capabilities before the rest (for example credentials that other plugins read). */
|
|
122
|
+
preload?: PreloadStep<Caps, Config, Context, LoadOptions>;
|
|
123
|
+
}
|
|
124
|
+
/** The loader a CLI builds with {@link createPluginSystem}. */
|
|
125
|
+
interface PluginLoader<Caps extends CapabilityShape, Extra extends object = Record<never, never>> extends PluginLoadReport {
|
|
126
|
+
/**
|
|
127
|
+
* Imports every configured plugin and builds the capability registry. Never throws for one plugin's failure: it is
|
|
128
|
+
* recorded in {@link PluginLoader.loadFailures} and the load continues, so a command learns a capability is absent
|
|
129
|
+
* from `has()` / `get()`.
|
|
130
|
+
*/
|
|
131
|
+
load(): Promise<void>;
|
|
132
|
+
/** The implementation of a capability: one for a `single` key, an array for a `many` key. Throws when it did not load. */
|
|
133
|
+
get<K extends CapabilityKeyOf<Caps>>(key: K): ResolvedCapability<Caps, K>;
|
|
134
|
+
/** Whether a capability has loaded. */
|
|
135
|
+
has(key: CapabilityKeyOf<Caps>): boolean;
|
|
136
|
+
/** Every capability key that has loaded. */
|
|
137
|
+
loadedKeys(): CapabilityKeyOf<Caps>[];
|
|
138
|
+
/** The providers that failed to load. Empty on a clean load. */
|
|
139
|
+
loadFailures(): readonly PluginLoadFailure<CapabilityKeyOf<Caps>>[];
|
|
140
|
+
/** The plugin object of each provider that was created, by provider name. */
|
|
141
|
+
plugins(): ReadonlyMap<string, LoadedPlugin<Caps, Extra>>;
|
|
142
|
+
}
|
|
143
|
+
/** The class {@link createPluginSystem} returns; extend it or construct it directly. */
|
|
144
|
+
interface PluginLoaderConstructor<Caps extends CapabilityShape, Config, Context extends object, Extra extends object = Record<never, never>, LoadOptions = undefined> {
|
|
145
|
+
/**
|
|
146
|
+
* @param config - The resolved config.
|
|
147
|
+
* @param context - Per-run context every plugin receives in its options.
|
|
148
|
+
* @param importer - Imports a package by name; defaults to resolving from the current directory first.
|
|
149
|
+
* @param options - Passed to the {@link PluginSystemOptions.preload} step.
|
|
150
|
+
*/
|
|
151
|
+
new (config: Config, context: Context, importer?: PluginImporter, options?: LoadOptions): PluginLoader<Caps, Extra>;
|
|
152
|
+
}
|
|
153
|
+
/** What {@link createPluginSystem} returns. */
|
|
154
|
+
interface PluginSystem<Caps extends CapabilityShape, Config, Context extends object, Extra extends object = Record<never, never>, LoadOptions = undefined> {
|
|
155
|
+
/** The loader class, bound to this CLI's prefix, config shape and hooks. */
|
|
156
|
+
PluginLoader: PluginLoaderConstructor<Caps, Config, Context, Extra, LoadOptions>;
|
|
157
|
+
/** Turn a provider's short name into its package name with this CLI's prefixes. */
|
|
158
|
+
resolvePackage: (provider: string) => string;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Build the plugin system of a new CLI: a loader that reads the providers from your config, imports each one's package
|
|
162
|
+
* (resolving from the working directory first), calls its `createPlugin(options)` and keeps the capabilities it
|
|
163
|
+
* implements in a typed registry, `single` or `many` per capability.
|
|
164
|
+
*
|
|
165
|
+
* A package may also export a capability config (`export default { provider, options? }`); the loader follows it to the
|
|
166
|
+
* provider and merges the preset options under the project's own. A provider that fails to load is recorded and
|
|
167
|
+
* skipped, never thrown, so one missing token does not stop a command that does not need it.
|
|
168
|
+
*
|
|
169
|
+
* What is yours stays yours: the capability interfaces (the `Caps` type), the package prefix, how the config lists
|
|
170
|
+
* providers and what a plugin is handed. Nothing about credentials, tokens or `.env` files is built in; a CLI that
|
|
171
|
+
* wants them uses `pluginOptions` and the `preload` step.
|
|
172
|
+
*
|
|
173
|
+
* @example
|
|
174
|
+
* const { PluginLoader } = createPluginSystem<MyCapabilities, MyConfig, MyContext>({
|
|
175
|
+
* packagePrefix: "@acme/mycli-plugin-",
|
|
176
|
+
* providers: (config) => config.providers,
|
|
177
|
+
* });
|
|
178
|
+
* const loader = new PluginLoader(config, { repoRoot });
|
|
179
|
+
* await loader.load();
|
|
180
|
+
* const source = loader.get("source");
|
|
181
|
+
*/
|
|
182
|
+
export declare function createPluginSystem<Caps extends CapabilityShape, Config, Context extends object, Extra extends object = Record<never, never>, LoadOptions = undefined>(options: PluginSystemOptions<Caps, Config, Context, LoadOptions>): PluginSystem<Caps, Config, Context, Extra, LoadOptions>;
|
|
183
|
+
/**
|
|
184
|
+
* Turn "every plugin failed because none is installed here" (a CLI run from a global install, outside the project that
|
|
185
|
+
* has the plugins) into one actionable error, instead of a stack of `Cannot find package` failures.
|
|
186
|
+
*
|
|
187
|
+
* Does nothing in every other case: some capability loaded, a failure that is not a missing package (a bad token, an
|
|
188
|
+
* unimplemented capability) or no plugins configured at all. Call it right after `await loader.load()`.
|
|
189
|
+
*
|
|
190
|
+
* @param loader - A loaded plugin loader.
|
|
191
|
+
* @param command - The command being run, for the message.
|
|
192
|
+
* @param createError - Builds the error to throw from the command and the unresolved package names.
|
|
193
|
+
*/
|
|
194
|
+
export declare function assertPluginsResolvable(loader: PluginLoadReport, command: string, createError: (command: string, packages: readonly string[]) => Error): void;
|
|
195
|
+
/**
|
|
196
|
+
* The importer a plugin loader uses unless it is given another: resolves the package from the current working
|
|
197
|
+
* directory first, so a globally installed CLI finds the plugins of the project it runs in, and falls back to a plain
|
|
198
|
+
* `import()` when that fails.
|
|
199
|
+
*/
|
|
200
|
+
export declare const defaultImporter: PluginImporter;
|
|
201
|
+
/**
|
|
202
|
+
* Whether an error is a raw "package isn't installed here" failure from `import()` or `require.resolve`:
|
|
203
|
+
* `ERR_MODULE_NOT_FOUND` / `MODULE_NOT_FOUND`, or the "Cannot find package/module" message Node prints for it.
|
|
204
|
+
*/
|
|
205
|
+
export declare function isModuleNotFound(err: unknown): boolean;
|
|
206
|
+
/** Raised when a plugin cannot be imported, does not export what a plugin must, or a capability is asked for and absent. */
|
|
207
|
+
export declare class LoaderError extends Error {
|
|
208
|
+
name: string;
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Turn a provider name into the package that implements it: `"github"` becomes `"<prefix>github"`. A scoped name
|
|
212
|
+
* (`@acme/x`), a name that already starts with `communityPrefix` and any name containing `/` are returned as they are,
|
|
213
|
+
* which is how plugins published outside your scope work.
|
|
214
|
+
*
|
|
215
|
+
* @param provider - The short name or the full package name.
|
|
216
|
+
* @param prefix - What a short name is prefixed with, e.g. `@acme/mycli-plugin-`.
|
|
217
|
+
* @param communityPrefix - The prefix an unscoped third-party package uses, e.g. `mycli-plugin-`.
|
|
218
|
+
* @throws `Error` when `provider` is empty.
|
|
219
|
+
*/
|
|
220
|
+
export declare function resolvePluginPackage(provider: string, prefix: string, communityPrefix?: string): string;
|
|
221
|
+
export type { CapabilityConfigPackage, CapabilityKeyOf, CapabilityShape, Cardinality, LoadedPlugin, PluginImporter, PluginLoadFailure, PluginLoadReport, PluginLoader, PluginLoaderConstructor, PluginModule, PluginSystem, PluginSystemOptions, PreloadApi, PreloadStep, ProviderEntry, ProviderTuple, ResolvedCapability };
|
package/dist/plugins.mjs
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { pathToFileURL } from "node:url";
|
|
3
|
+
// src/plugins/loader-error/loader-error.ts
|
|
4
|
+
/** Raised when a plugin cannot be imported, does not export what a plugin must, or a capability is asked for and absent. */
|
|
5
|
+
var LoaderError = class extends Error {
|
|
6
|
+
name = "LoaderError";
|
|
7
|
+
};
|
|
8
|
+
// src/plugins/assert-plugins-resolvable/assert-plugins-resolvable.ts
|
|
9
|
+
/**
|
|
10
|
+
* Turn "every plugin failed because none is installed here" (a CLI run from a global install, outside the project that
|
|
11
|
+
* has the plugins) into one actionable error, instead of a stack of `Cannot find package` failures.
|
|
12
|
+
*
|
|
13
|
+
* Does nothing in every other case: some capability loaded, a failure that is not a missing package (a bad token, an
|
|
14
|
+
* unimplemented capability) or no plugins configured at all. Call it right after `await loader.load()`.
|
|
15
|
+
*
|
|
16
|
+
* @param loader - A loaded plugin loader.
|
|
17
|
+
* @param command - The command being run, for the message.
|
|
18
|
+
* @param createError - Builds the error to throw from the command and the unresolved package names.
|
|
19
|
+
*/
|
|
20
|
+
function assertPluginsResolvable(loader, command, createError) {
|
|
21
|
+
if (loader.loadedKeys().length > 0) return;
|
|
22
|
+
const failures = loader.loadFailures();
|
|
23
|
+
if (failures.length === 0) return;
|
|
24
|
+
const isImportFailure = (err) => err instanceof LoaderError && err.message.startsWith("failed to import");
|
|
25
|
+
if (!failures.every((f) => isImportFailure(f.error))) return;
|
|
26
|
+
throw createError(command, [...new Set(failures.map((f) => f.packageName))]);
|
|
27
|
+
}
|
|
28
|
+
// src/plugins/default-importer/default-importer.ts
|
|
29
|
+
/**
|
|
30
|
+
* The importer a plugin loader uses unless it is given another: resolves the package from the current working
|
|
31
|
+
* directory first, so a globally installed CLI finds the plugins of the project it runs in, and falls back to a plain
|
|
32
|
+
* `import()` when that fails.
|
|
33
|
+
*/
|
|
34
|
+
const defaultImporter = async (packageName) => {
|
|
35
|
+
try {
|
|
36
|
+
const resolved = createRequire(process.cwd() + "/").resolve(packageName);
|
|
37
|
+
return import(pathToFileURL(resolved).href);
|
|
38
|
+
} catch {
|
|
39
|
+
return import(packageName);
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
// src/plugins/resolve-plugin-package/resolve-plugin-package.ts
|
|
43
|
+
/**
|
|
44
|
+
* Turn a provider name into the package that implements it: `"github"` becomes `"<prefix>github"`. A scoped name
|
|
45
|
+
* (`@acme/x`), a name that already starts with `communityPrefix` and any name containing `/` are returned as they are,
|
|
46
|
+
* which is how plugins published outside your scope work.
|
|
47
|
+
*
|
|
48
|
+
* @param provider - The short name or the full package name.
|
|
49
|
+
* @param prefix - What a short name is prefixed with, e.g. `@acme/mycli-plugin-`.
|
|
50
|
+
* @param communityPrefix - The prefix an unscoped third-party package uses, e.g. `mycli-plugin-`.
|
|
51
|
+
* @throws `Error` when `provider` is empty.
|
|
52
|
+
*/
|
|
53
|
+
function resolvePluginPackage(provider, prefix, communityPrefix) {
|
|
54
|
+
if (!provider) throw new Error("provider name is empty");
|
|
55
|
+
if (provider.startsWith("@")) return provider;
|
|
56
|
+
if (communityPrefix && provider.startsWith(communityPrefix)) return provider;
|
|
57
|
+
if (provider.includes("/")) return provider;
|
|
58
|
+
return prefix + provider;
|
|
59
|
+
}
|
|
60
|
+
// src/plugins/create-plugin-system/create-plugin-system.ts
|
|
61
|
+
function messageOf(err) {
|
|
62
|
+
return err instanceof Error ? err.message : String(err);
|
|
63
|
+
}
|
|
64
|
+
function isPluginModule(mod) {
|
|
65
|
+
return typeof mod?.createPlugin === "function";
|
|
66
|
+
}
|
|
67
|
+
function isCapabilityConfigModule(mod) {
|
|
68
|
+
return typeof (mod?.default)?.provider === "string";
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Build the plugin system of a new CLI: a loader that reads the providers from your config, imports each one's package
|
|
72
|
+
* (resolving from the working directory first), calls its `createPlugin(options)` and keeps the capabilities it
|
|
73
|
+
* implements in a typed registry, `single` or `many` per capability.
|
|
74
|
+
*
|
|
75
|
+
* A package may also export a capability config (`export default { provider, options? }`); the loader follows it to the
|
|
76
|
+
* provider and merges the preset options under the project's own. A provider that fails to load is recorded and
|
|
77
|
+
* skipped, never thrown, so one missing token does not stop a command that does not need it.
|
|
78
|
+
*
|
|
79
|
+
* What is yours stays yours: the capability interfaces (the `Caps` type), the package prefix, how the config lists
|
|
80
|
+
* providers and what a plugin is handed. Nothing about credentials, tokens or `.env` files is built in; a CLI that
|
|
81
|
+
* wants them uses `pluginOptions` and the `preload` step.
|
|
82
|
+
*
|
|
83
|
+
* @example
|
|
84
|
+
* const { PluginLoader } = createPluginSystem<MyCapabilities, MyConfig, MyContext>({
|
|
85
|
+
* packagePrefix: "@acme/mycli-plugin-",
|
|
86
|
+
* providers: (config) => config.providers,
|
|
87
|
+
* });
|
|
88
|
+
* const loader = new PluginLoader(config, { repoRoot });
|
|
89
|
+
* await loader.load();
|
|
90
|
+
* const source = loader.get("source");
|
|
91
|
+
*/
|
|
92
|
+
function createPluginSystem(options) {
|
|
93
|
+
const { packagePrefix, communityPrefix, configFile = "the config", providers, pluginOptions, preload } = options;
|
|
94
|
+
const resolvePackage = (provider) => resolvePluginPackage(provider, packagePrefix, communityPrefix);
|
|
95
|
+
class Loader {
|
|
96
|
+
config;
|
|
97
|
+
context;
|
|
98
|
+
importer;
|
|
99
|
+
loadOptions;
|
|
100
|
+
registry = /* @__PURE__ */ new Map();
|
|
101
|
+
failures = [];
|
|
102
|
+
created = /* @__PURE__ */ new Map();
|
|
103
|
+
constructor(config, context, importer = defaultImporter, loadOptions) {
|
|
104
|
+
this.config = config;
|
|
105
|
+
this.context = context;
|
|
106
|
+
this.importer = importer;
|
|
107
|
+
this.loadOptions = loadOptions;
|
|
108
|
+
}
|
|
109
|
+
async load() {
|
|
110
|
+
const skip = new Set(preload?.keys ?? []);
|
|
111
|
+
if (preload) await preload.run({
|
|
112
|
+
loadOne: (key, tuple) => this.loadOne(key, tuple),
|
|
113
|
+
fail: (key, tuple, err) => this.recordFailure(key, tuple, err),
|
|
114
|
+
register: (key, impls) => void this.registry.set(key, impls)
|
|
115
|
+
}, {
|
|
116
|
+
config: this.config,
|
|
117
|
+
context: this.context,
|
|
118
|
+
options: this.loadOptions
|
|
119
|
+
});
|
|
120
|
+
const entries = Object.entries(providers(this.config));
|
|
121
|
+
for (const [key, entry] of entries) {
|
|
122
|
+
if (!entry || skip.has(key)) continue;
|
|
123
|
+
if (entry.cardinality === "single") try {
|
|
124
|
+
this.registry.set(key, await this.loadOne(key, entry.tuple));
|
|
125
|
+
} catch (err) {
|
|
126
|
+
this.recordFailure(key, entry.tuple, err);
|
|
127
|
+
}
|
|
128
|
+
else {
|
|
129
|
+
const impls = [];
|
|
130
|
+
for (const tuple of entry.tuples) try {
|
|
131
|
+
impls.push(await this.loadOne(key, tuple));
|
|
132
|
+
} catch (err) {
|
|
133
|
+
this.recordFailure(key, tuple, err);
|
|
134
|
+
}
|
|
135
|
+
if (impls.length > 0) this.registry.set(key, impls);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
get(key) {
|
|
140
|
+
const impl = this.registry.get(key);
|
|
141
|
+
if (impl === void 0) {
|
|
142
|
+
const failure = this.failures.find((f) => f.key === key);
|
|
143
|
+
if (failure) throw failure.error;
|
|
144
|
+
throw new LoaderError(`capability \`${key}\` is not loaded — is it declared in ${configFile}?`);
|
|
145
|
+
}
|
|
146
|
+
return impl;
|
|
147
|
+
}
|
|
148
|
+
has(key) {
|
|
149
|
+
return this.registry.has(key);
|
|
150
|
+
}
|
|
151
|
+
loadedKeys() {
|
|
152
|
+
return Array.from(this.registry.keys());
|
|
153
|
+
}
|
|
154
|
+
loadFailures() {
|
|
155
|
+
return this.failures;
|
|
156
|
+
}
|
|
157
|
+
plugins() {
|
|
158
|
+
return this.created;
|
|
159
|
+
}
|
|
160
|
+
recordFailure(key, tuple, err) {
|
|
161
|
+
this.failures.push({
|
|
162
|
+
key,
|
|
163
|
+
provider: tuple.provider,
|
|
164
|
+
packageName: tuple.packageName,
|
|
165
|
+
error: err instanceof Error ? err : new Error(String(err))
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
async loadOne(key, tuple) {
|
|
169
|
+
const mod = await this.importer(tuple.packageName).catch((err) => {
|
|
170
|
+
throw new LoaderError(`failed to import \`${tuple.packageName}\` for capability \`${key}\`: ${messageOf(err)}`);
|
|
171
|
+
});
|
|
172
|
+
if (isPluginModule(mod)) {
|
|
173
|
+
const plugin = mod.createPlugin(pluginOptions ? pluginOptions({
|
|
174
|
+
config: this.config,
|
|
175
|
+
context: this.context,
|
|
176
|
+
tuple
|
|
177
|
+
}) : {
|
|
178
|
+
...this.context,
|
|
179
|
+
...tuple.options
|
|
180
|
+
});
|
|
181
|
+
this.created.set(tuple.provider, plugin);
|
|
182
|
+
const factory = plugin.capabilities[key];
|
|
183
|
+
if (typeof factory !== "function") throw new LoaderError(`\`${tuple.packageName}\` does not implement the \`${key}\` capability`);
|
|
184
|
+
return factory();
|
|
185
|
+
}
|
|
186
|
+
if (isCapabilityConfigModule(mod)) {
|
|
187
|
+
const cap = mod.default;
|
|
188
|
+
return this.loadOne(key, {
|
|
189
|
+
provider: cap.provider,
|
|
190
|
+
packageName: resolvePackage(cap.provider),
|
|
191
|
+
options: {
|
|
192
|
+
...cap.options,
|
|
193
|
+
...tuple.options
|
|
194
|
+
}
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
throw new LoaderError(`\`${tuple.packageName}\` does not export \`createPlugin(options)\` or a capability config ({ provider, options? })`);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
return {
|
|
201
|
+
PluginLoader: Loader,
|
|
202
|
+
resolvePackage
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
// src/plugins/is-module-not-found/is-module-not-found.ts
|
|
206
|
+
/**
|
|
207
|
+
* Whether an error is a raw "package isn't installed here" failure from `import()` or `require.resolve`:
|
|
208
|
+
* `ERR_MODULE_NOT_FOUND` / `MODULE_NOT_FOUND`, or the "Cannot find package/module" message Node prints for it.
|
|
209
|
+
*/
|
|
210
|
+
function isModuleNotFound(err) {
|
|
211
|
+
if (!(err instanceof Error)) return false;
|
|
212
|
+
const code = err.code;
|
|
213
|
+
if (code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND") return true;
|
|
214
|
+
return /Cannot find (?:package|module)|MODULE_NOT_FOUND/.test(err.message);
|
|
215
|
+
}
|
|
216
|
+
export { LoaderError, assertPluginsResolvable, createPluginSystem, defaultImporter, isModuleNotFound, resolvePluginPackage };
|
package/dist/testing.mjs
CHANGED
|
@@ -2,8 +2,8 @@ import { execFileSync, spawn } from "node:child_process";
|
|
|
2
2
|
import { existsSync, readdirSync, realpathSync, statSync } from "node:fs";
|
|
3
3
|
import { dirname, join, sep } from "node:path";
|
|
4
4
|
import { tmpdir } from "node:os";
|
|
5
|
-
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
6
5
|
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
7
7
|
import yargs from "yargs";
|
|
8
8
|
// src/testing/cli-runner/cli-runner.ts
|
|
9
9
|
/**
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theholocron/kyber",
|
|
3
|
-
"version": "5.0.0-alpha.
|
|
3
|
+
"version": "5.0.0-alpha.346",
|
|
4
4
|
"description": "The reusable parts of a command-line tool: terminal output, prompts, the interactive menu, the update notifier, safe handling of tokens, a test harness and the global flags.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cli",
|
|
@@ -45,6 +45,11 @@
|
|
|
45
45
|
"import": "./dist/observability.mjs",
|
|
46
46
|
"default": "./dist/observability.mjs"
|
|
47
47
|
},
|
|
48
|
+
"./plugins": {
|
|
49
|
+
"types": "./dist/plugins.d.mts",
|
|
50
|
+
"import": "./dist/plugins.mjs",
|
|
51
|
+
"default": "./dist/plugins.mjs"
|
|
52
|
+
},
|
|
48
53
|
"./prompts": {
|
|
49
54
|
"types": "./dist/prompts.d.mts",
|
|
50
55
|
"import": "./dist/prompts.mjs",
|
|
@@ -90,12 +95,12 @@
|
|
|
90
95
|
"typescript": "^5.9.3",
|
|
91
96
|
"vitest": "^5.0.5",
|
|
92
97
|
"yargs": "^18.1.0",
|
|
93
|
-
"@theholocron/datapad": "5.0.0-alpha.
|
|
94
|
-
"@theholocron/observability": "0.7.0-alpha.1",
|
|
98
|
+
"@theholocron/datapad": "5.0.0-alpha.346",
|
|
95
99
|
"@theholocron/eslint-config": "^8.9.0-alpha.8",
|
|
100
|
+
"@theholocron/observability": "0.7.0-alpha.1",
|
|
96
101
|
"@theholocron/tsconfig": "^8.9.0-alpha.8",
|
|
97
|
-
"@theholocron/
|
|
98
|
-
"@theholocron/
|
|
102
|
+
"@theholocron/vitest-config": "^8.9.0-alpha.8",
|
|
103
|
+
"@theholocron/tsdown-config": "^8.9.0-alpha.8"
|
|
99
104
|
},
|
|
100
105
|
"peerDependencies": {
|
|
101
106
|
"@inquirer/prompts": "^8.0.0",
|
|
@@ -106,8 +111,8 @@
|
|
|
106
111
|
"dotenv": "^17.0.0",
|
|
107
112
|
"ora": "^9.0.0",
|
|
108
113
|
"yargs": "^18.0.0",
|
|
109
|
-
"@theholocron/
|
|
110
|
-
"@theholocron/
|
|
114
|
+
"@theholocron/observability": "^0.7.0-alpha.1",
|
|
115
|
+
"@theholocron/datapad": "^5.0.0-alpha.346"
|
|
111
116
|
},
|
|
112
117
|
"peerDependenciesMeta": {
|
|
113
118
|
"@inquirer/prompts": {
|