-
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathrepl.test.ts
More file actions
686 lines (523 loc) · 19.7 KB
/
repl.test.ts
File metadata and controls
686 lines (523 loc) · 19.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
import type { REPLServer } from "node:repl";
import { jest } from "@jest/globals";
import { createCompleter, startRepl } from "../../src/repl/repl.js";
import type { CompleterCallback } from "../../src/repl/repl.js";
import type { Config } from "../../src/server/config.js";
import { ContextRegistry } from "../../src/server/context-registry.js";
import { Registry } from "../../src/server/registry.js";
import { ScenarioRegistry } from "../../src/server/scenario-registry.js";
const CONFIG: Config = {
basePath: "",
generate: {
routes: true,
types: true,
},
openApiPath: "",
port: 9999,
proxyPaths: new Map([]),
proxyUrl: "https://example.com/test",
routePrefix: "",
startAdminApi: false,
startRepl: false,
startServer: true,
watch: {
routes: true,
types: true,
},
};
class MockRepl {
public isBufferCleared = false;
public isPromptDisplayed = false;
public commandLog: string[] = [];
public clearBufferedCommand() {
this.commandLog.push("clearBufferedCommand");
}
public displayPrompt() {
this.commandLog.push("displayPrompt");
}
}
class ReplHarness {
public server: REPLServer;
private readonly mock = new MockRepl();
public output: string[] = [];
public constructor(
contextRegistry: ContextRegistry,
registry: Registry,
config: Config,
scenarioRegistry?: ScenarioRegistry,
) {
this.server = startRepl(
contextRegistry,
registry,
config,
(line) => this.output.push(line),
undefined,
scenarioRegistry,
);
}
public call(name: string, options: string) {
this.server.commands[name]?.action.call(this.mock, options);
}
public async callAsync(name: string, options: string): Promise<void> {
await this.server.commands[name]?.action.call(this.mock, options);
}
public isReset() {
return (
this.mock.commandLog[0] === "clearBufferedCommand" &&
this.mock.commandLog[1] === "displayPrompt"
);
}
}
function createHarness(scenarioRegistry?: ScenarioRegistry) {
const contextRegistry = new ContextRegistry();
const registry = new Registry();
const config = { ...CONFIG };
config.proxyPaths = new Map();
const harness = new ReplHarness(
contextRegistry,
registry,
config,
scenarioRegistry,
);
return { config, contextRegistry, harness, registry };
}
describe("REPL", () => {
it("turns on the proxy globally", () => {
const { config, harness } = createHarness();
harness.call("proxy", "on");
expect(config.proxyPaths.get("")).toBe(true);
expect(harness.isReset()).toBe(true);
});
it("turns off the proxy globally", () => {
const { config, harness } = createHarness();
harness.call("proxy", "off");
expect(config.proxyPaths.get("")).toBe(false);
expect(harness.isReset()).toBe(true);
});
it("turns on the proxy for the root", () => {
const { config, harness } = createHarness();
harness.call("proxy", "on /");
expect(config.proxyPaths.get("")).toBe(true);
expect(harness.isReset()).toBe(true);
});
it("turns off the proxy for the root", () => {
const { config, harness } = createHarness();
harness.call("proxy", "off /");
expect(config.proxyPaths.get("")).toBe(false);
expect(harness.isReset()).toBe(true);
});
it("turns on the proxy for an endpoint", () => {
const { config, harness } = createHarness();
harness.call("proxy", "on /foo/bar");
expect(config.proxyPaths.get("/foo/bar")).toBe(true);
expect(harness.isReset()).toBe(true);
});
it("turns off the proxy for an endpoint", () => {
const { config, harness } = createHarness();
harness.call("proxy", "off /foo/bar");
expect(config.proxyPaths.get("/foo/bar")).toBe(false);
expect(harness.isReset()).toBe(true);
});
it("shows the proxy status", () => {
const { config, harness } = createHarness();
config.proxyPaths.set("/foo", true);
config.proxyPaths.set("/foo/bar", false);
harness.call("proxy", "status");
expect(harness.output).toEqual([
"Proxy Configuration:",
"",
"The proxy URL is https://example.com/test",
"",
"Paths prefixed with [+] will be proxied.",
"Paths prefixed with [-] will not be proxied.",
"",
"[+] /foo/",
"[-] /foo/bar/",
]);
expect(harness.isReset()).toBe(true);
});
it("shows the proxy status when no URL is set", () => {
const { config, harness } = createHarness();
config.proxyUrl = "";
config.proxyPaths.set("/foo", true);
config.proxyPaths.set("/foo/bar", false);
harness.call("proxy", "status");
expect(harness.output).toEqual([
"The proxy URL is not set.",
'To set it, type ".proxy url <url>',
]);
expect(harness.isReset()).toBe(true);
});
it("displays an explanatory message after turning the proxy on for an endpoint", () => {
const { harness } = createHarness();
harness.call("proxy", "on /foo/bar");
expect(harness.output).toEqual([
"Requests to /foo/bar will be proxied to https://example.com/test/foo/bar",
]);
});
it("displays an explanatory message after turning the proxy off for an endpoint", () => {
const { harness } = createHarness();
harness.call("proxy", "off /foo/bar");
expect(harness.output).toEqual([
"Requests to /foo/bar will be handled by local code",
]);
});
it.each(["", "help"])("displays a proxy help message (%s)", () => {
const { harness } = createHarness();
harness.call("proxy", "help");
expect(harness.output).toEqual([
".proxy [on|off] - turn the proxy on/off at the root level",
".proxy [on|off] <path-prefix> - turn the proxy on for a path",
".proxy status - show the proxy status",
".proxy help - show this message",
]);
});
it("sets the proxy url", () => {
const { config, harness } = createHarness();
harness.call("proxy", "url https://example.com/new-url");
expect(config.proxyUrl).toBe("https://example.com/new-url");
expect(harness.output).toEqual([
"proxy URL is set to https://example.com/new-url",
]);
expect(harness.isReset()).toBe(true);
});
it("displays a message if 'proxy url' is entered without a URL", () => {
const { harness } = createHarness();
harness.call("proxy", "url");
expect(harness.output).toEqual(["usage: .proxy url <url>"]);
expect(harness.isReset()).toBe(true);
});
it("displays help information for the counterfact command", () => {
const { harness } = createHarness();
harness.call("counterfact", "");
expect(harness.output).toEqual([
"This is a read-eval-print loop (REPL), the same as the one you get when you run node with no arguments.",
"Except that it's connected to the running server, which you can access with the following globals:",
"",
"- loadContext('/some/path'): to access the context object for a given path",
"- context: the root context ( same as loadContext('/') )",
"- route('/some/path'): create a request builder for the given path",
"",
"For more information, see https://counterfact.dev/docs/usage.html",
"",
]);
expect(harness.isReset()).toBe(true);
});
describe(".scenario command", () => {
it("calls the named export from scenarios/index for a single-segment path", async () => {
const scenarioRegistry = new ScenarioRegistry();
scenarioRegistry.add("index", {
foo(ctx: { context: Record<string, unknown> }) {
ctx.context["applied"] = "foo";
},
});
const { harness, contextRegistry } = createHarness(scenarioRegistry);
await harness.callAsync("scenario", "foo");
expect(harness.output).toContain("Applied foo");
expect(contextRegistry.find("/")).toMatchObject({ applied: "foo" });
expect(harness.isReset()).toBe(true);
});
it("calls the named export from scenarios/<name> for a two-segment path", async () => {
const scenarioRegistry = new ScenarioRegistry();
scenarioRegistry.add("myscript", {
bar(ctx: { context: Record<string, unknown> }) {
ctx.context["applied"] = "bar";
},
});
const { harness, contextRegistry } = createHarness(scenarioRegistry);
await harness.callAsync("scenario", "myscript/bar");
expect(harness.output).toContain("Applied myscript/bar");
expect(contextRegistry.find("/")).toMatchObject({ applied: "bar" });
});
it("calls the named export from scenarios/<dir>/<name> for a three-segment path", async () => {
const scenarioRegistry = new ScenarioRegistry();
scenarioRegistry.add("foo/bar", {
baz(ctx: { context: Record<string, unknown> }) {
ctx.context["applied"] = "baz";
},
});
const { harness, contextRegistry } = createHarness(scenarioRegistry);
await harness.callAsync("scenario", "foo/bar/baz");
expect(harness.output).toContain("Applied foo/bar/baz");
expect(contextRegistry.find("/")).toMatchObject({ applied: "baz" });
});
it("passes routes and route to the function", async () => {
const scenarioRegistry = new ScenarioRegistry();
scenarioRegistry.add("index", {
setup(ctx: { routes: Record<string, unknown> }) {
ctx.routes["myRoute"] = { path: "/pets" };
},
});
const { harness } = createHarness(scenarioRegistry);
await harness.callAsync("scenario", "setup");
expect(harness.output).toContain("Applied setup");
expect(
(harness.server.context["routes"] as Record<string, unknown>)[
"myRoute"
],
).toMatchObject({ path: "/pets" });
});
it("shows an error when the scenario file is not in the registry", async () => {
const scenarioRegistry = new ScenarioRegistry();
const { harness } = createHarness(scenarioRegistry);
await harness.callAsync("scenario", "nonexistent");
expect(harness.output[0]).toMatch(/Error: Could not find/u);
expect(harness.isReset()).toBe(true);
});
it("shows an error when the named export is not a function", async () => {
const scenarioRegistry = new ScenarioRegistry();
scenarioRegistry.add("index", {
notAFunction: "I am a string",
});
const { harness } = createHarness(scenarioRegistry);
await harness.callAsync("scenario", "notAFunction");
expect(harness.output[0]).toMatch(
/Error: "notAFunction" is not a function/u,
);
expect(harness.isReset()).toBe(true);
});
it("shows a usage message when called with no argument", async () => {
const { harness } = createHarness();
await harness.callAsync("scenario", "");
expect(harness.output).toContain("usage: .scenario <path>");
expect(harness.isReset()).toBe(true);
});
it("rejects path traversal using '..' segments", async () => {
const { harness } = createHarness();
await harness.callAsync("scenario", "../secret/foo");
expect(harness.output[0]).toMatch(/Error: Path must not contain/u);
expect(harness.isReset()).toBe(true);
});
});
describe("route autocomplete", () => {
function callCompleter(
completer: ReturnType<typeof createCompleter>,
line: string,
): Promise<[string[], string]> {
return new Promise((resolve, reject) => {
completer(line, (err, result) => {
if (err) reject(err);
else resolve(result);
});
});
}
it('returns matching routes when typing client.get("', async () => {
const registry = new Registry();
registry.add("/pets", { GET() {} });
registry.add("/pets/{petId}", { GET() {} });
registry.add("/users", { GET() {} });
const completer = createCompleter(registry);
const [completions, prefix] = await callCompleter(
completer,
'client.get("/p',
);
expect(prefix).toBe("/p");
expect(completions).toEqual(["/pets", "/pets/{petId}"]);
});
it("returns all routes when no partial is provided", async () => {
const registry = new Registry();
registry.add("/pets", { GET() {} });
registry.add("/users", { GET() {} });
const completer = createCompleter(registry);
const [completions, prefix] = await callCompleter(
completer,
'client.post("',
);
expect(prefix).toBe("");
expect(completions).toEqual(["/pets", "/users"]);
});
it("returns empty completions for non-matching input when no fallback is set", async () => {
const registry = new Registry();
registry.add("/pets", { GET() {} });
const completer = createCompleter(registry);
const [completions, prefix] = await callCompleter(
completer,
"someOtherExpression",
);
expect(completions).toEqual([]);
expect(prefix).toBe("someOtherExpression");
});
it("calls fallback completer for non-matching input", async () => {
const registry = new Registry();
registry.add("/pets", { GET() {} });
const fallback = jest.fn((_line: string, callback: CompleterCallback) => {
callback(null, [["context", "client"], "c"]);
});
const completer = createCompleter(registry, fallback);
const [completions, prefix] = await callCompleter(completer, "c");
expect(fallback).toHaveBeenCalledWith("c", expect.any(Function));
expect(completions).toEqual(["context", "client"]);
expect(prefix).toBe("c");
});
it.each(["get", "post", "put", "patch", "delete"])(
"works for client.%s(...)",
async (method) => {
const registry = new Registry();
registry.add("/pets", {
GET() {},
POST() {},
PUT() {},
PATCH() {},
DELETE() {},
});
const completer = createCompleter(registry);
const [completions] = await callCompleter(
completer,
`client.${method}("/pets`,
);
expect(completions).toEqual(["/pets"]);
},
);
it('returns matching routes when typing route("', async () => {
const registry = new Registry();
registry.add("/pets", { GET() {} });
registry.add("/pets/{petId}", { GET() {} });
registry.add("/users", { GET() {} });
const completer = createCompleter(registry);
const [completions, prefix] = await callCompleter(completer, 'route("/p');
expect(prefix).toBe("/p");
expect(completions).toEqual(["/pets", "/pets/{petId}"]);
});
it('returns all routes when typing route(" with no partial', async () => {
const registry = new Registry();
registry.add("/pets", { GET() {} });
registry.add("/users", { GET() {} });
const completer = createCompleter(registry);
const [completions, prefix] = await callCompleter(completer, 'route("');
expect(prefix).toBe("");
expect(completions).toEqual(["/pets", "/users"]);
});
it('suggests all RouteBuilder methods after route("/path").', async () => {
const registry = new Registry();
const completer = createCompleter(registry);
const [completions, prefix] = await callCompleter(
completer,
'route("/pets").',
);
expect(prefix).toBe("");
expect(completions).toEqual([
"body(",
"headers(",
"help(",
"method(",
"missing(",
"path(",
"query(",
"ready(",
"send(",
]);
});
it('filters RouteBuilder methods based on typed prefix after route("/path").', async () => {
const registry = new Registry();
const completer = createCompleter(registry);
const [completions, prefix] = await callCompleter(
completer,
'route("/pets").me',
);
expect(prefix).toBe("me");
expect(completions).toEqual(["method("]);
});
it('suggests RouteBuilder methods after a chained call like route("/path").method("get").', async () => {
const registry = new Registry();
const completer = createCompleter(registry);
const [completions, prefix] = await callCompleter(
completer,
'route("/pets").method("get").',
);
expect(prefix).toBe("");
expect(completions).toEqual([
"body(",
"headers(",
"help(",
"method(",
"missing(",
"path(",
"query(",
"ready(",
"send(",
]);
});
});
describe(".scenario tab completion", () => {
function callCompleter(
completer: ReturnType<typeof createCompleter>,
line: string,
): Promise<[string[], string]> {
return new Promise((resolve, reject) => {
completer(line, (err, result) => {
if (err) reject(err);
else resolve(result);
});
});
}
it("returns function names from the index key when no slash in partial", async () => {
const scenarioRegistry = new ScenarioRegistry();
scenarioRegistry.add("index", {
soldPets() {},
resetAll() {},
notAScenario: 42,
});
const registry = new Registry();
const completer = createCompleter(registry, undefined, scenarioRegistry);
// Partial "sold" — should match soldPets only, not the non-function export
const [completions, prefix] = await callCompleter(
completer,
".scenario sold",
);
expect(prefix).toBe("sold");
expect(completions).toEqual(["soldPets"]);
expect(completions).not.toContain("resetAll");
// Partial "reset" — should match resetAll only
const [completions2] = await callCompleter(completer, ".scenario reset");
expect(completions2).toEqual(["resetAll"]);
// Non-function exports should not be suggested
const [completions3] = await callCompleter(completer, ".scenario not");
expect(completions3).toEqual([]);
});
it("returns all function names and file prefixes when partial is empty", async () => {
const scenarioRegistry = new ScenarioRegistry();
scenarioRegistry.add("index", { foo() {}, bar() {} });
scenarioRegistry.add("myscript", { baz() {} });
const registry = new Registry();
const completer = createCompleter(registry, undefined, scenarioRegistry);
const [completions, prefix] = await callCompleter(
completer,
".scenario ",
);
expect(prefix).toBe("");
expect(completions).toContain("foo");
expect(completions).toContain("bar");
expect(completions).toContain("myscript/");
});
it("returns exports from the named file key when partial contains a slash", async () => {
const scenarioRegistry = new ScenarioRegistry();
scenarioRegistry.add("myscript", { soldPets() {}, resetAll() {} });
const registry = new Registry();
const completer = createCompleter(registry, undefined, scenarioRegistry);
const [completions, prefix] = await callCompleter(
completer,
".scenario myscript/sol",
);
expect(prefix).toBe("myscript/sol");
expect(completions).toEqual(["myscript/soldPets"]);
});
it("returns all exports from the named file key when only the slash is typed", async () => {
const scenarioRegistry = new ScenarioRegistry();
scenarioRegistry.add("pets", { sold() {}, reset() {} });
const registry = new Registry();
const completer = createCompleter(registry, undefined, scenarioRegistry);
const [completions, prefix] = await callCompleter(
completer,
".scenario pets/",
);
expect(prefix).toBe("pets/");
expect(completions).toEqual(["pets/sold", "pets/reset"]);
});
it("returns empty completions when scenarioRegistry is not provided", async () => {
const registry = new Registry();
const completer = createCompleter(registry);
const [completions] = await callCompleter(completer, ".scenario sold");
expect(completions).toEqual([]);
});
});
});