@counterfact/repl 0.1.1

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/License.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Patrick McElhaney
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,57 @@
1
+ # `@counterfact/repl`
2
+
3
+ Counterfact's interactive Node.js REPL integration. It accepts narrow runtime
4
+ registries and a client route catalog, so applications can embed the terminal
5
+ experience without importing Counterfact's CLI or telemetry policy.
6
+
7
+ ## Starting a REPL
8
+
9
+ ```js
10
+ import { createOpenApiRouteCatalog } from "@counterfact/client";
11
+ import {
12
+ ContextRegistry,
13
+ Registry,
14
+ ScenarioRegistry,
15
+ } from "@counterfact/runtime";
16
+ import { startRepl } from "@counterfact/repl";
17
+
18
+ const contextRegistry = new ContextRegistry();
19
+ const registry = new Registry();
20
+ const scenarioRegistry = new ScenarioRegistry();
21
+ const config = { port: 3000, proxyPaths: new Map(), proxyUrl: "" };
22
+ const routeCatalog = createOpenApiRouteCatalog({ paths: {} });
23
+
24
+ const replServer = startRepl(
25
+ contextRegistry,
26
+ registry,
27
+ config,
28
+ undefined,
29
+ routeCatalog,
30
+ scenarioRegistry,
31
+ undefined,
32
+ undefined,
33
+ (event) => console.log(event),
34
+ );
35
+ ```
36
+
37
+ The optional event reporter receives command names but never command arguments.
38
+ Reporter failures are ignored so observability cannot interrupt an interactive
39
+ session.
40
+
41
+ ## REPL globals
42
+
43
+ The REPL starts with these live values:
44
+
45
+ - `context` and `loadContext(path)` expose runtime state.
46
+ - `client` is an `@counterfact/client` `RawHttpClient` configured for the
47
+ simulator.
48
+ - `route(path)` creates an immutable request builder.
49
+ - `routes` is shared with scenario functions.
50
+ - `store` is present when the simulator has a shared store.
51
+
52
+ For multiple APIs, `context`, `loadContext`, `route`, and `routes` are grouped
53
+ by API name. The `.proxy` command changes live proxy configuration and
54
+ `.scenario` applies named scenario functions.
55
+
56
+ See [`examples/complete-routes.mjs`](./examples/complete-routes.mjs) for a
57
+ complete public-import example.
@@ -0,0 +1 @@
1
+ export { createCompleter, startRepl, type CompleterCallback, type ReplApiBinding, type ReplCommand, type ReplConfig, type ReplEvent, type ReplEventReporter, } from "./repl.js";
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { createCompleter, startRepl, } from "./repl.js";
package/dist/repl.d.ts ADDED
@@ -0,0 +1,55 @@
1
+ import repl from "node:repl";
2
+ import { type RouteCatalog } from "@counterfact/client";
3
+ import type { ContextLookup, RouteListing, ScenarioCatalog } from "@counterfact/runtime";
4
+ declare function printToStdout(line: string): void;
5
+ export type CompleterCallback = (err: Error | null, result: [string[], string]) => void;
6
+ export interface ReplApiBinding {
7
+ contextRegistry: ContextLookup;
8
+ group: string;
9
+ registry: RouteListing;
10
+ routeCatalog?: RouteCatalog;
11
+ scenarioRegistry?: ScenarioCatalog;
12
+ }
13
+ export interface ReplConfig {
14
+ port: number;
15
+ proxyPaths: Map<string, boolean>;
16
+ proxyUrl: string;
17
+ }
18
+ export type ReplCommand = "counterfact" | "proxy" | "scenario";
19
+ export interface ReplEvent {
20
+ command: ReplCommand;
21
+ type: "command-used";
22
+ }
23
+ export type ReplEventReporter = (event: ReplEvent) => void;
24
+ /**
25
+ * Creates a tab-completion function for the REPL.
26
+ *
27
+ * @param registry - The route registry used to complete path arguments for `route()` and `client.*()` calls.
28
+ * @param fallback - Optional fallback completer (e.g. the Node.js built-in completer) invoked when no custom completion matches.
29
+ * @param routeCatalog - Optional catalog used as the source of route completions when available.
30
+ * @param scenarioRegistry - When provided, enables tab completion for `.scenario` commands by enumerating
31
+ * exported function names and file-key prefixes from the loaded scenario modules.
32
+ */
33
+ export declare function createCompleter(registry: RouteListing, fallback?: (line: string, callback: CompleterCallback) => void, routeCatalog?: RouteCatalog, scenarioRegistry?: ScenarioCatalog, groupedScenarioRegistries?: Record<string, ScenarioCatalog | undefined>): (line: string, callback: CompleterCallback) => void;
34
+ /**
35
+ * Launches the interactive Counterfact REPL.
36
+ *
37
+ * The REPL is a standard Node.js REPL augmented with:
38
+ * - `context` / `loadContext(path)` globals wired to the {@link ContextRegistry}.
39
+ * - `client` — a {@link RawHttpClient} pre-configured for `localhost`.
40
+ * - `route(path)` — creates a {@link RouteBuilder} for the given path.
41
+ * - `.counterfact` — help command.
42
+ * - `.proxy` — proxy configuration command.
43
+ * - `.scenario` — runs a named scenario function from the scenarios directory.
44
+ *
45
+ * @param contextRegistry - The live context registry.
46
+ * @param registry - The route registry (used for tab completion).
47
+ * @param config - Server configuration.
48
+ * @param print - Output function; defaults to writing to `stdout`.
49
+ * @param routeCatalog - Optional route catalog for tab completion and request help.
50
+ * @param scenarioRegistry - Optional scenario registry for `.scenario` support.
51
+ * @param reportEvent - Optional observer for REPL command usage.
52
+ * @returns The configured Node.js REPL server instance.
53
+ */
54
+ export declare function startRepl(contextRegistry: ContextLookup, registry: RouteListing, config: ReplConfig, print?: typeof printToStdout, routeCatalog?: RouteCatalog, scenarioRegistry?: ScenarioCatalog, apiBindings?: ReplApiBinding[], store?: object, reportEvent?: ReplEventReporter): repl.REPLServer;
55
+ export {};
package/dist/repl.js ADDED
@@ -0,0 +1,422 @@
1
+ import repl from "node:repl";
2
+ import { RawHttpClient, createRouteFunction, } from "@counterfact/client";
3
+ function printToStdout(line) {
4
+ process.stdout.write(`${line}\n`);
5
+ }
6
+ const ROUTE_BUILDER_METHODS = [
7
+ "body(",
8
+ "headers(",
9
+ "help(",
10
+ "method(",
11
+ "missing(",
12
+ "path(",
13
+ "query(",
14
+ "ready(",
15
+ "send(",
16
+ ];
17
+ function getScenarioCompletions(line, scenarioRegistry, groupedScenarioRegistries) {
18
+ function getPathCompletions(partial, registry) {
19
+ if (registry === undefined) {
20
+ return [[], partial];
21
+ }
22
+ const slashIdx = partial.lastIndexOf("/");
23
+ if (slashIdx === -1) {
24
+ const indexFunctions = registry.getExportedFunctionNames("index");
25
+ const fileKeys = registry.getFileKeys().filter((k) => k !== "index");
26
+ const topLevelPrefixes = [
27
+ ...new Set(fileKeys.map((k) => k.split("/")[0] + "/")),
28
+ ];
29
+ const allOptions = [...indexFunctions, ...topLevelPrefixes];
30
+ const matches = allOptions.filter((c) => c.startsWith(partial));
31
+ return [matches, partial];
32
+ }
33
+ const fileKey = partial.slice(0, slashIdx);
34
+ const funcPartial = partial.slice(slashIdx + 1);
35
+ const functions = registry.getExportedFunctionNames(fileKey);
36
+ const matches = functions
37
+ .filter((e) => e.startsWith(funcPartial))
38
+ .map((e) => `${fileKey}/${e}`);
39
+ return [matches, partial];
40
+ }
41
+ if (groupedScenarioRegistries !== undefined) {
42
+ if (!/^\.scenario(?:\s|$)/u.test(line)) {
43
+ return undefined;
44
+ }
45
+ const hasTrailingWhitespace = /\s$/u.test(line);
46
+ const args = line.trim().split(/\s+/u).slice(1);
47
+ const groupKeys = Object.keys(groupedScenarioRegistries);
48
+ if (args.length === 0) {
49
+ return [groupKeys, ""];
50
+ }
51
+ if (args.length === 1 && !hasTrailingWhitespace) {
52
+ const groupPartial = args[0] ?? "";
53
+ const matches = groupKeys.filter((key) => key.startsWith(groupPartial));
54
+ return [matches, groupPartial];
55
+ }
56
+ const selectedGroup = args[0] ?? "";
57
+ const selectedRegistry = groupedScenarioRegistries[selectedGroup];
58
+ if (selectedRegistry === undefined) {
59
+ const scenarioPartial = hasTrailingWhitespace
60
+ ? ""
61
+ : (args[args.length - 1] ?? "");
62
+ return [[], scenarioPartial];
63
+ }
64
+ if (args.length === 1 && hasTrailingWhitespace) {
65
+ return getPathCompletions("", selectedRegistry);
66
+ }
67
+ if (args.length === 2 && !hasTrailingWhitespace) {
68
+ const scenarioPartial = args[1];
69
+ if (scenarioPartial === undefined) {
70
+ return [[], ""];
71
+ }
72
+ return getPathCompletions(scenarioPartial, selectedRegistry);
73
+ }
74
+ // More than two args (or trailing whitespace after the second arg) means
75
+ // no additional `.scenario` arguments are valid in multi-API mode.
76
+ return [[], args[args.length - 1] ?? ""];
77
+ }
78
+ const applyMatch = line.match(/^\.scenario\s+(?<partial>\S*)$/u);
79
+ if (!applyMatch) {
80
+ return undefined;
81
+ }
82
+ const partial = applyMatch.groups?.["partial"] ?? "";
83
+ return getPathCompletions(partial, scenarioRegistry);
84
+ }
85
+ function getRouteBuilderMethodCompletions(line) {
86
+ const builderMatch = line.match(/route\(.*\)\.(?<partial>[a-zA-Z]*)$/u);
87
+ if (!builderMatch) {
88
+ return undefined;
89
+ }
90
+ const partial = builderMatch.groups?.["partial"] ?? "";
91
+ const matches = ROUTE_BUILDER_METHODS.filter((m) => m.startsWith(partial));
92
+ return [matches, partial];
93
+ }
94
+ function getRoutesForCompletion(registry, routeCatalog) {
95
+ const openApiPaths = routeCatalog?.listPaths() ?? [];
96
+ if (openApiPaths.length > 0) {
97
+ return openApiPaths;
98
+ }
99
+ return registry.routes.map((route) => route.path);
100
+ }
101
+ function getRouteCompletions(line, routes) {
102
+ const routeMatch = line.match(/(?:client\.(?:get|post|put|patch|delete)|route)\("(?<partial>[^"]*)$/u);
103
+ if (!routeMatch) {
104
+ return undefined;
105
+ }
106
+ const partial = routeMatch.groups?.["partial"] ?? "";
107
+ const matches = routes.filter((route) => route.startsWith(partial));
108
+ return [matches, partial];
109
+ }
110
+ /**
111
+ * Creates a tab-completion function for the REPL.
112
+ *
113
+ * @param registry - The route registry used to complete path arguments for `route()` and `client.*()` calls.
114
+ * @param fallback - Optional fallback completer (e.g. the Node.js built-in completer) invoked when no custom completion matches.
115
+ * @param routeCatalog - Optional catalog used as the source of route completions when available.
116
+ * @param scenarioRegistry - When provided, enables tab completion for `.scenario` commands by enumerating
117
+ * exported function names and file-key prefixes from the loaded scenario modules.
118
+ */
119
+ export function createCompleter(registry, fallback, routeCatalog, scenarioRegistry, groupedScenarioRegistries) {
120
+ const routes = getRoutesForCompletion(registry, routeCatalog);
121
+ return (line, callback) => {
122
+ const scenarioCompletions = getScenarioCompletions(line, scenarioRegistry, groupedScenarioRegistries);
123
+ if (scenarioCompletions !== undefined) {
124
+ callback(null, scenarioCompletions);
125
+ return;
126
+ }
127
+ const routeBuilderCompletions = getRouteBuilderMethodCompletions(line);
128
+ if (routeBuilderCompletions !== undefined) {
129
+ callback(null, routeBuilderCompletions);
130
+ return;
131
+ }
132
+ const routeCompletions = getRouteCompletions(line, routes);
133
+ if (routeCompletions === undefined) {
134
+ if (fallback) {
135
+ fallback(line, callback);
136
+ }
137
+ else {
138
+ callback(null, [[], line]);
139
+ }
140
+ return;
141
+ }
142
+ callback(null, routeCompletions);
143
+ };
144
+ }
145
+ /**
146
+ * Launches the interactive Counterfact REPL.
147
+ *
148
+ * The REPL is a standard Node.js REPL augmented with:
149
+ * - `context` / `loadContext(path)` globals wired to the {@link ContextRegistry}.
150
+ * - `client` — a {@link RawHttpClient} pre-configured for `localhost`.
151
+ * - `route(path)` — creates a {@link RouteBuilder} for the given path.
152
+ * - `.counterfact` — help command.
153
+ * - `.proxy` — proxy configuration command.
154
+ * - `.scenario` — runs a named scenario function from the scenarios directory.
155
+ *
156
+ * @param contextRegistry - The live context registry.
157
+ * @param registry - The route registry (used for tab completion).
158
+ * @param config - Server configuration.
159
+ * @param print - Output function; defaults to writing to `stdout`.
160
+ * @param routeCatalog - Optional route catalog for tab completion and request help.
161
+ * @param scenarioRegistry - Optional scenario registry for `.scenario` support.
162
+ * @param reportEvent - Optional observer for REPL command usage.
163
+ * @returns The configured Node.js REPL server instance.
164
+ */
165
+ export function startRepl(contextRegistry, registry, config, print = printToStdout, routeCatalog, scenarioRegistry, apiBindings, store, reportEvent) {
166
+ const bindings = apiBindings === undefined || apiBindings.length === 0
167
+ ? [
168
+ {
169
+ contextRegistry,
170
+ group: "",
171
+ registry,
172
+ routeCatalog,
173
+ scenarioRegistry,
174
+ },
175
+ ]
176
+ : apiBindings;
177
+ const isMultiApi = bindings.length > 1;
178
+ const groupedBindings = bindings.map((binding) => ({
179
+ ...binding,
180
+ key: binding.group.trim(),
181
+ }));
182
+ if (isMultiApi) {
183
+ const invalidBindings = groupedBindings.filter((binding) => binding.key === "");
184
+ if (invalidBindings.length > 0) {
185
+ throw new Error("Each API binding must define a non-empty group when multiple APIs are configured.");
186
+ }
187
+ const seenGroups = new Set();
188
+ const duplicateGroups = new Set();
189
+ for (const binding of groupedBindings) {
190
+ if (seenGroups.has(binding.key)) {
191
+ duplicateGroups.add(binding.key);
192
+ }
193
+ seenGroups.add(binding.key);
194
+ }
195
+ }
196
+ const rootBinding = groupedBindings[0];
197
+ if (rootBinding === undefined) {
198
+ throw new Error("startRepl requires at least one API binding");
199
+ }
200
+ const groupedLoadContext = Object.fromEntries(groupedBindings.map((binding) => [
201
+ binding.key,
202
+ (path) => binding.contextRegistry.find(path),
203
+ ]));
204
+ const groupedRoute = Object.fromEntries(groupedBindings.map((binding) => [
205
+ binding.key,
206
+ createRouteFunction(config.port, "localhost", binding.routeCatalog),
207
+ ]));
208
+ function printProxyStatus() {
209
+ if (config.proxyUrl === "") {
210
+ print("The proxy URL is not set.");
211
+ print('To set it, type ".proxy url <url>');
212
+ return;
213
+ }
214
+ print("Proxy Configuration:");
215
+ print("");
216
+ print(`The proxy URL is ${config.proxyUrl}`);
217
+ print("");
218
+ print("Paths prefixed with [+] will be proxied.");
219
+ print("Paths prefixed with [-] will not be proxied.");
220
+ print("");
221
+ const entries = [...config.proxyPaths.entries()].sort(([path1], [path2]) => path1 < path2 ? -1 : 1);
222
+ for (const [path, state] of entries) {
223
+ print(`${state ? "[+]" : "[-]"} ${path}/`);
224
+ }
225
+ }
226
+ function setProxyUrl(url) {
227
+ if (url === undefined) {
228
+ print("usage: .proxy url <url>");
229
+ return;
230
+ }
231
+ config.proxyUrl = url;
232
+ print(`proxy URL is set to ${url}`);
233
+ }
234
+ function turnProxyOnOrOff(text) {
235
+ const [command, endpoint] = text.split(" ");
236
+ const printEndpoint = endpoint === undefined || endpoint === "" ? "/" : endpoint;
237
+ config.proxyPaths.set((endpoint ?? "").replace(/\/$/u, ""), command === "on");
238
+ if (command === "on") {
239
+ print(`Requests to ${printEndpoint} will be proxied to ${config.proxyUrl || "<proxy URL>"}${printEndpoint}`);
240
+ }
241
+ if (command === "off") {
242
+ print(`Requests to ${printEndpoint} will be handled by local code`);
243
+ }
244
+ }
245
+ const replServer = repl.start({
246
+ prompt: "\x1b[38;2;0;113;181m⬣> \x1b[0m",
247
+ });
248
+ const builtinCompleter = replServer.completer;
249
+ // completer is typed as readonly in @types/node but is writable at runtime
250
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
251
+ replServer.completer = createCompleter(rootBinding.registry, builtinCompleter, rootBinding.routeCatalog, rootBinding.scenarioRegistry, isMultiApi
252
+ ? Object.fromEntries(groupedBindings.map((binding) => [
253
+ binding.key,
254
+ binding.scenarioRegistry,
255
+ ]))
256
+ : undefined);
257
+ function reportCommand(command) {
258
+ try {
259
+ reportEvent?.({ command, type: "command-used" });
260
+ }
261
+ catch {
262
+ // Observability must never change interactive command behavior.
263
+ }
264
+ }
265
+ replServer.defineCommand("counterfact", {
266
+ action() {
267
+ reportCommand("counterfact");
268
+ print("This is a read-eval-print loop (REPL), the same as the one you get when you run node with no arguments.");
269
+ print("Except that it's connected to the running server, which you can access with the following globals:");
270
+ print("");
271
+ print("- loadContext('/some/path'): to access the context object for a given path");
272
+ print("- context: the root context ( same as loadContext('/') )");
273
+ print("- route('/some/path'): create a request builder for the given path");
274
+ print("");
275
+ print("For more information, see https://github.com/counterfact/api-simulator/blob/main/docs/usage.md");
276
+ print("");
277
+ this.clearBufferedCommand();
278
+ this.displayPrompt();
279
+ },
280
+ help: "Get help with Counterfact",
281
+ });
282
+ replServer.defineCommand("proxy", {
283
+ action(text) {
284
+ reportCommand("proxy");
285
+ if (text === "help" || text === "") {
286
+ print(".proxy [on|off] - turn the proxy on/off at the root level");
287
+ print(".proxy [on|off] <path-prefix> - turn the proxy on for a path");
288
+ print(".proxy status - show the proxy status");
289
+ print(".proxy help - show this message");
290
+ }
291
+ else if (text.startsWith("url")) {
292
+ setProxyUrl(text.split(" ")[1]);
293
+ }
294
+ else if (text === "status") {
295
+ printProxyStatus();
296
+ }
297
+ else {
298
+ turnProxyOnOrOff(text);
299
+ }
300
+ this.clearBufferedCommand();
301
+ this.displayPrompt();
302
+ },
303
+ help: 'proxy configuration (".proxy help" for details)',
304
+ });
305
+ replServer.context.loadContext = isMultiApi
306
+ ? groupedLoadContext
307
+ : groupedLoadContext[rootBinding.key];
308
+ replServer.context.context = isMultiApi
309
+ ? Object.fromEntries(groupedBindings.map((binding) => [
310
+ binding.key,
311
+ binding.contextRegistry.find("/"),
312
+ ]))
313
+ : rootBinding.contextRegistry.find("/");
314
+ replServer.context.client = new RawHttpClient("localhost", config.port);
315
+ replServer.context.RawHttpClient = RawHttpClient;
316
+ replServer.context.route = isMultiApi
317
+ ? groupedRoute
318
+ : groupedRoute[rootBinding.key];
319
+ replServer.context.routes = isMultiApi
320
+ ? Object.fromEntries(groupedBindings.map((binding) => [binding.key, {}]))
321
+ : {};
322
+ if (store !== undefined) {
323
+ replServer.context.store = store;
324
+ }
325
+ replServer.defineCommand("scenario", {
326
+ async action(text) {
327
+ reportCommand("scenario");
328
+ const trimmedText = text.trim();
329
+ const parsedArgs = trimmedText.split(/\s+/u).filter(Boolean);
330
+ const usage = isMultiApi
331
+ ? "usage: .scenario <group> <path>"
332
+ : "usage: .scenario <path>";
333
+ const { selectedBinding, scenarioPath } = (() => {
334
+ if (!isMultiApi) {
335
+ if (trimmedText === "") {
336
+ return { scenarioPath: undefined, selectedBinding: undefined };
337
+ }
338
+ return { scenarioPath: trimmedText, selectedBinding: rootBinding };
339
+ }
340
+ if (parsedArgs.length !== 2) {
341
+ return { scenarioPath: undefined, selectedBinding: undefined };
342
+ }
343
+ return {
344
+ scenarioPath: parsedArgs[1],
345
+ selectedBinding: groupedBindings.find((binding) => binding.key === parsedArgs[0]),
346
+ };
347
+ })();
348
+ if (selectedBinding === undefined || scenarioPath === undefined) {
349
+ if (isMultiApi &&
350
+ scenarioPath !== undefined &&
351
+ selectedBinding === undefined) {
352
+ const groupName = parsedArgs[0] ?? "";
353
+ const availableGroups = groupedBindings.map((binding) => binding.key);
354
+ print(`Error: Unknown API group "${groupName}". Available groups: ${availableGroups.join(", ")}`);
355
+ }
356
+ else {
357
+ print(usage);
358
+ }
359
+ this.clearBufferedCommand();
360
+ this.displayPrompt();
361
+ return;
362
+ }
363
+ const parts = scenarioPath.split("/").filter(Boolean);
364
+ if (parts.length === 0) {
365
+ print(usage);
366
+ this.clearBufferedCommand();
367
+ this.displayPrompt();
368
+ return;
369
+ }
370
+ if (parts.some((part) => part === ".." || part === ".")) {
371
+ print("Error: Path must not contain '.' or '..' segments");
372
+ this.clearBufferedCommand();
373
+ this.displayPrompt();
374
+ return;
375
+ }
376
+ const functionName = parts[parts.length - 1] ?? "";
377
+ const fileKey = parts.length === 1 ? "index" : parts.slice(0, -1).join("/");
378
+ const module = selectedBinding.scenarioRegistry?.getModule(fileKey);
379
+ if (module === undefined) {
380
+ print(`Error: Could not find scenario file "${fileKey}"`);
381
+ this.clearBufferedCommand();
382
+ this.displayPrompt();
383
+ return;
384
+ }
385
+ const fn = module[functionName];
386
+ if (typeof fn !== "function") {
387
+ print(`Error: "${functionName}" is not a function exported from "${fileKey}"`);
388
+ this.clearBufferedCommand();
389
+ this.displayPrompt();
390
+ return;
391
+ }
392
+ try {
393
+ const selectedRoutes = isMultiApi
394
+ ? replServer.context["routes"][selectedBinding.key]
395
+ : replServer.context["routes"];
396
+ if (isMultiApi && selectedRoutes === undefined) {
397
+ print(`Error: Could not resolve routes for API group "${selectedBinding.key}"`);
398
+ this.clearBufferedCommand();
399
+ this.displayPrompt();
400
+ return;
401
+ }
402
+ const applyContext = {
403
+ context: selectedBinding.contextRegistry.find("/"),
404
+ loadContext: ((path) => selectedBinding.contextRegistry.find(path)),
405
+ route: groupedRoute[selectedBinding.key],
406
+ routes: selectedRoutes,
407
+ };
408
+ await fn(applyContext);
409
+ print(`Applied ${text.trim()}`);
410
+ }
411
+ catch (error) {
412
+ print(`Error: ${String(error)}`);
413
+ }
414
+ this.clearBufferedCommand();
415
+ this.displayPrompt();
416
+ },
417
+ help: isMultiApi
418
+ ? 'apply a scenario script (".scenario <group> <path>" calls the named export from that group\'s scenarios/)'
419
+ : 'apply a scenario script (".scenario <path>" calls the named export from scenarios/)',
420
+ });
421
+ return replServer;
422
+ }
@@ -0,0 +1,18 @@
1
+ import assert from "node:assert/strict";
2
+
3
+ import { createOpenApiRouteCatalog } from "@counterfact/client";
4
+ import { createCompleter } from "@counterfact/repl";
5
+
6
+ const catalog = createOpenApiRouteCatalog({
7
+ paths: { "/pets/{petId}": { get: {} } },
8
+ });
9
+ const completer = createCompleter({ routes: [] }, undefined, catalog);
10
+
11
+ const completion = await new Promise((resolve, reject) => {
12
+ completer('route("/pe', (error, result) => {
13
+ if (error) reject(error);
14
+ else resolve(result);
15
+ });
16
+ });
17
+
18
+ assert.deepEqual(completion, [["/pets/{petId}"], "/pe"]);
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@counterfact/repl",
3
+ "version": "0.1.1",
4
+ "description": "Inspect and manipulate a running Counterfact simulator from a Node.js REPL.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "examples",
17
+ "README.md",
18
+ "License.md"
19
+ ],
20
+ "sideEffects": false,
21
+ "author": "Patrick McElhaney <pmcelhaney@gmail.com>",
22
+ "license": "MIT",
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/counterfact/api-simulator.git",
26
+ "directory": "packages/repl"
27
+ },
28
+ "bugs": "https://github.com/counterfact/api-simulator/issues",
29
+ "homepage": "https://counterfact.dev",
30
+ "funding": {
31
+ "type": "github",
32
+ "url": "https://github.com/sponsors/pmcelhaney"
33
+ },
34
+ "keywords": [
35
+ "counterfact",
36
+ "openapi",
37
+ "repl",
38
+ "api-mocking",
39
+ "typescript",
40
+ "testing"
41
+ ],
42
+ "engines": {
43
+ "node": ">=22"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public"
47
+ },
48
+ "scripts": {
49
+ "build": "rimraf dist && tsc --build --force",
50
+ "prepack": "yarn build",
51
+ "test": "node --experimental-vm-modules ../../node_modules/jest-cli/bin/jest.js --config ../../jest.config.js packages/repl/test",
52
+ "test:packed-consumer": "node test/package/repl-consumer-smoke.mjs"
53
+ },
54
+ "dependencies": {
55
+ "@counterfact/client": "0.1.0",
56
+ "@counterfact/runtime": "0.1.1"
57
+ }
58
+ }