@speedkit/cli 4.51.0-run-control.1 → 4.51.0-run-control.2

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.
Files changed (93) hide show
  1. package/README.md +81 -29
  2. package/dist/build-info.json +3 -3
  3. package/dist/commands/diff.d.ts +1 -0
  4. package/dist/commands/login.d.ts +3 -0
  5. package/dist/commands/login.js +14 -3
  6. package/dist/commands/onboarding/browser/emulate.d.ts +12 -0
  7. package/dist/commands/onboarding/browser/emulate.js +3 -0
  8. package/dist/commands/onboarding/browser/navigate.d.ts +8 -0
  9. package/dist/commands/onboarding/browser/navigate.js +2 -1
  10. package/dist/commands/onboarding/cache/prewarm.js +1 -1
  11. package/dist/commands/onboarding/debug/arm.d.ts +6 -0
  12. package/dist/commands/onboarding/debug/arm.js +2 -1
  13. package/dist/commands/onboarding/files/rebuild.d.ts +6 -6
  14. package/dist/commands/onboarding/logs.js +3 -2
  15. package/dist/commands/onboarding/status.js +2 -2
  16. package/dist/commands/onboarding/stop.d.ts +13 -0
  17. package/dist/commands/onboarding/stop.js +17 -0
  18. package/dist/commands/onboarding.d.ts +1 -1
  19. package/dist/commands/onboarding.js +1 -1
  20. package/dist/services/diff/diff-service-build-context.d.ts +4 -0
  21. package/dist/services/diff/diff-service-build-context.js +5 -0
  22. package/dist/services/diff/diff-service-factory.js +17 -5
  23. package/dist/services/diff/run-runtime-config.d.ts +33 -0
  24. package/dist/services/diff/run-runtime-config.js +74 -0
  25. package/dist/services/diff/spec/run-runtime-config.spec.d.ts +1 -0
  26. package/dist/services/diff/spec/run-runtime-config.spec.js +87 -0
  27. package/dist/services/onboarding/browse/browse-service.d.ts +13 -1
  28. package/dist/services/onboarding/browse/browse-service.js +40 -7
  29. package/dist/services/onboarding/browser/answer-dialogs.d.ts +12 -0
  30. package/dist/services/onboarding/browser/answer-dialogs.js +25 -0
  31. package/dist/services/onboarding/browser/emulate-device.d.ts +12 -1
  32. package/dist/services/onboarding/browser/emulate-device.js +33 -6
  33. package/dist/services/onboarding/browser/launch-browser.d.ts +2 -1
  34. package/dist/services/onboarding/browser/launch-browser.js +3 -1
  35. package/dist/services/onboarding/control/browser-session.d.ts +26 -12
  36. package/dist/services/onboarding/control/browser-session.js +118 -91
  37. package/dist/services/onboarding/control/control-protocol.d.ts +39 -1
  38. package/dist/services/onboarding/control/control-protocol.js +0 -11
  39. package/dist/services/onboarding/control/control-server.d.ts +8 -0
  40. package/dist/services/onboarding/control/control-server.js +22 -2
  41. package/dist/services/onboarding/control/debug-session.d.ts +30 -1
  42. package/dist/services/onboarding/control/debug-session.js +106 -10
  43. package/dist/services/onboarding/control/navigate-wait.d.ts +33 -0
  44. package/dist/services/onboarding/control/navigate-wait.js +56 -0
  45. package/dist/services/onboarding/control/service-worker-tracker.js +1 -0
  46. package/dist/services/onboarding/control/watch.js +9 -1
  47. package/dist/services/onboarding/fetch-event-handler.js +9 -0
  48. package/dist/services/onboarding/inject/inject-service.js +1 -1
  49. package/dist/services/onboarding/onboarding-model.js +2 -1
  50. package/dist/services/onboarding/onboarding-service-build-context.js +1 -1
  51. package/dist/services/onboarding/onboarding-service-factory.js +20 -7
  52. package/dist/services/onboarding/onboarding-service.js +1 -1
  53. package/dist/services/onboarding/spec/browser/answer-dialogs.spec.d.ts +1 -0
  54. package/dist/services/onboarding/spec/browser/answer-dialogs.spec.js +66 -0
  55. package/dist/services/onboarding/spec/control/browser-session.spec.js +127 -2
  56. package/dist/services/onboarding/spec/control/control-server.spec.js +33 -0
  57. package/dist/services/onboarding/spec/control/debug-session.spec.js +58 -0
  58. package/dist/services/onboarding/spec/control/navigate-wait.spec.d.ts +1 -0
  59. package/dist/services/onboarding/spec/control/navigate-wait.spec.js +47 -0
  60. package/dist/services/onboarding/spec/control/watch.spec.js +15 -0
  61. package/dist/services/onboarding/spec/fetch-event-handler.spec.js +17 -0
  62. package/dist/services/onboarding/spec/onboarding-model.spec.js +2 -3
  63. package/dist/services/onboarding/spec/onboarding-service-factory.spec.js +24 -1
  64. package/dist/services/onboarding/spec/virtual-orestes-app/virtual-orestes-app.spec.d.ts +1 -0
  65. package/dist/services/onboarding/spec/virtual-orestes-app/virtual-orestes-app.spec.js +65 -0
  66. package/dist/services/onboarding/virtual-orestes-app/index.d.ts +4 -0
  67. package/dist/services/onboarding/virtual-orestes-app/index.js +31 -0
  68. package/dist/services/origin-request/runtime-config-source.d.ts +6 -0
  69. package/dist/services/origin-request/runtime-config-source.js +6 -0
  70. package/dist/services/run-control/browser/run-browser-contexts.d.ts +16 -0
  71. package/dist/services/run-control/browser/run-browser-contexts.js +14 -1
  72. package/dist/services/run-control/browser/run-browser-service.d.ts +5 -1
  73. package/dist/services/run-control/browser/run-browser-service.js +16 -9
  74. package/dist/services/run-control/debug/run-debug-contexts.d.ts +5 -0
  75. package/dist/services/run-control/debug/run-debug-contexts.js +3 -0
  76. package/dist/services/run-control/debug/run-debug-service.d.ts +1 -0
  77. package/dist/services/run-control/debug/run-debug-service.js +3 -0
  78. package/dist/services/run-control/files/run-files-contexts.d.ts +5 -5
  79. package/dist/services/run-control/inject/run-inject-contexts.js +7 -1
  80. package/dist/services/run-control/inject/run-inject-service.d.ts +2 -2
  81. package/dist/services/run-control/inject/run-inject-service.js +32 -8
  82. package/dist/services/run-control/probe/run-probe-service.js +1 -0
  83. package/dist/services/run-control/session/run-session-service.d.ts +8 -1
  84. package/dist/services/run-control/session/run-session-service.js +58 -2
  85. package/dist/services/run-control/spec/cache/run-cache-service.spec.js +1 -1
  86. package/dist/services/run-control/spec/inject/run-inject-service.spec.js +27 -0
  87. package/dist/services/run-control/spec/session/run-session-service.spec.js +49 -0
  88. package/dist/services/run-log/request-log.d.ts +3 -1
  89. package/dist/services/run-registry/run-registry.d.ts +7 -2
  90. package/dist/services/run-registry/run-registry.js +26 -5
  91. package/dist/services/run-registry/spec/run-registry.spec.js +17 -0
  92. package/oclif.manifest.json +281 -181
  93. package/package.json +1 -1
@@ -383,13 +383,138 @@ describe("BrowserSession", () => {
383
383
  });
384
384
  expect(data.method).to.equal("Network.getCookies");
385
385
  });
386
- it("should emulate a device on the page, and keep it across a new session", async () => {
386
+ /**
387
+ * A browser whose auto-attach reports `workers`: each a service worker
388
+ * target that answers, or one that never does, as a stopped worker can.
389
+ */
390
+ const withWorkers = (workers) => {
391
+ const sent = [];
392
+ const sessions = new Map(workers.map((worker) => {
393
+ let userAgent = "the host's UA";
394
+ return [
395
+ worker.targetId,
396
+ {
397
+ detached: false,
398
+ send: (method, params = {}) => {
399
+ sent.push({ targetId: worker.targetId, method });
400
+ if (!worker.answers) {
401
+ return new Promise(() => undefined);
402
+ }
403
+ userAgent = params.userAgent ?? userAgent;
404
+ return Promise.resolve(method === "Runtime.evaluate"
405
+ ? { result: { value: userAgent } }
406
+ : {});
407
+ },
408
+ detach: async () => undefined,
409
+ },
410
+ ];
411
+ }));
412
+ let onAttached = () => undefined;
413
+ const root = {
414
+ on: (_, handler) => {
415
+ onAttached = handler;
416
+ },
417
+ connection: () => ({ session: (id) => sessions.get(id) }),
418
+ send: async (method) => {
419
+ if (method === "Target.setAutoAttach") {
420
+ for (const worker of workers) {
421
+ onAttached({
422
+ sessionId: worker.targetId,
423
+ waitingForDebugger: false,
424
+ targetInfo: { ...worker, type: "service_worker" },
425
+ });
426
+ }
427
+ }
428
+ return {};
429
+ },
430
+ detach: async () => undefined,
431
+ };
387
432
  const browser = {
388
433
  version: async () => "Chrome/146.0.7680.165",
434
+ target: () => ({ createCDPSession: async () => root }),
389
435
  targets: () => [],
436
+ };
437
+ return { browser, sent };
438
+ };
439
+ it("should report only the worker in charge, and never wait on a stale one", async () => {
440
+ const stale = Array.from({ length: 12 }, (_, index) => ({
441
+ targetId: `stale-${index}`,
442
+ url: `${BASE}/old-sw-${index}.js`,
443
+ answers: false,
444
+ }));
445
+ const { browser, sent } = withWorkers([
446
+ ...stale,
447
+ { targetId: "live", url: `${BASE}/sw.js`, answers: true },
448
+ ]);
449
+ const serviceWorkers = new ServiceWorkerTracker();
450
+ serviceWorkers.recordRegistrations([
451
+ { registrationId: "1", scopeURL: `${BASE}/`, isDeleted: false },
452
+ ]);
453
+ serviceWorkers.recordVersions([
454
+ {
455
+ versionId: "7",
456
+ registrationId: "1",
457
+ scriptURL: `${BASE}/sw.js`,
458
+ status: "activated",
459
+ runningStatus: "running",
460
+ targetId: "live",
461
+ },
462
+ ]);
463
+ const cdp = {
464
+ detached: false,
390
465
  on: () => undefined,
391
- off: () => undefined,
466
+ send: async () => ({}),
467
+ };
468
+ const page = {
469
+ isClosed: () => false,
470
+ url: () => `${BASE}/`,
471
+ goto: async () => undefined,
472
+ target: () => ({ createCDPSession: async () => cdp }),
392
473
  };
474
+ const session = new BrowserSession(200);
475
+ session.attach(browser, page, {
476
+ origin: BASE,
477
+ origins: [BASE],
478
+ reinstall: async () => undefined,
479
+ serviceWorkers,
480
+ });
481
+ const started = Date.now();
482
+ const data = await session.emulate({ device: "tablet" });
483
+ // Twelve stale workers at 200ms each, one after the other, would be 2.4s.
484
+ expect(Date.now() - started).to.be.below(1000);
485
+ expect(data.serviceWorkers).to.deep.equal([
486
+ {
487
+ url: `${BASE}/sw.js`,
488
+ userAgent: data.emulation?.userAgent,
489
+ emulated: true,
490
+ active: true,
491
+ },
492
+ ]);
493
+ expect(sent.filter((call) => call.method === "Runtime.evaluate")).to.deep.equal([{ targetId: "live", method: "Runtime.evaluate" }]);
494
+ // The client hints reach every worker, the stale ones included.
495
+ expect(sent.filter((call) => call.method === "Network.setUserAgentOverride")).to.have.lengthOf(13);
496
+ });
497
+ it("should emulate an iPad with Safari's user agent: tablet metrics, no client hints", async () => {
498
+ const safari = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15";
499
+ const { session, calls } = attached(`${BASE}/`, [BASE], withWorkers([]).browser);
500
+ const data = await session.emulate({
501
+ device: "tablet",
502
+ userAgent: safari,
503
+ touch: false,
504
+ reload: false,
505
+ });
506
+ expect(data.emulation).to.include({
507
+ width: 834,
508
+ userAgent: safari,
509
+ touch: false,
510
+ });
511
+ expect(paramsOf(calls, "Emulation.setUserAgentOverride")).to.deep.equal({
512
+ userAgent: safari,
513
+ });
514
+ expect(paramsOf(calls, "Emulation.setTouchEmulationEnabled")).to.deep.equal({ enabled: false });
515
+ });
516
+ it("should emulate a device on the page, and keep it across a new session", async () => {
517
+ const browser = withWorkers([]).browser;
393
518
  const { session, calls, detachCdp } = attached(`${BASE}/`, [BASE, SIBLING], browser);
394
519
  const data = await session.emulate({ device: "mobile", reload: false });
395
520
  const metrics = () => calls.filter((call) => call.method === "Emulation.setDeviceMetricsOverride");
@@ -336,3 +336,36 @@ describe("ControlServer — two callers at once", () => {
336
336
  expect(overlapped, "reads were serialised against each other").to.equal(true);
337
337
  });
338
338
  });
339
+ describe("ControlServer — config.runtime", () => {
340
+ const ask1 = async (runtimeConfig) => {
341
+ const runDirectory = mkdtempSync(join(tmpdir(), "sk-control-runtime-"));
342
+ const controller = new AbortController();
343
+ const server = new ControlServer(runDirectory, "example.com-production-r", {
344
+ cache: new Cache(memoryCli(), join(runDirectory, "dh-cache")),
345
+ cli: memoryCli(),
346
+ files: fileList(),
347
+ runtimeConfig,
348
+ });
349
+ await server.listen(controller.signal);
350
+ try {
351
+ const [, response] = await ask(server.socketPath, [
352
+ hello(),
353
+ JSON.stringify({ id: "1", op: "config.runtime" }),
354
+ ]);
355
+ return response;
356
+ }
357
+ finally {
358
+ controller.abort();
359
+ await server.close();
360
+ rmSync(runDirectory, { recursive: true, force: true });
361
+ }
362
+ };
363
+ it("should answer null for a run that loaded no runtime config", async () => {
364
+ expect(success(await ask1(() => undefined))).to.deep.equal({
365
+ config: null,
366
+ });
367
+ });
368
+ it("should refuse on a run that loads no runtime config at all", async () => {
369
+ expect(failure(await ask1()).code).to.equal(CONTROL_ERRORS.handlerFailed);
370
+ });
371
+ });
@@ -138,6 +138,20 @@ function pausedPayload() {
138
138
  };
139
139
  }
140
140
  describe("DebugSession", () => {
141
+ describe("status", () => {
142
+ it("answers within one CDP budget when the page does not answer", async () => {
143
+ // Each read times out after its budget on a stuck page. In sequence they
144
+ // outlasted the client's 5 s, which saw only CONTROL_TIMEOUT.
145
+ const { session, transport } = build();
146
+ const slow = () => new Promise((_, reject) => setTimeout(() => reject(new Error("CDP_TIMEOUT")), 150));
147
+ transport.send = slow;
148
+ transport.threadState = slow;
149
+ const started = Date.now();
150
+ const status = await session.status();
151
+ expect(Date.now() - started).to.be.below(290);
152
+ expect(status.paused).to.equal(null);
153
+ });
154
+ });
141
155
  describe("arming", () => {
142
156
  it("should hold the debugger open and install the hooks", async () => {
143
157
  // Holding Debugger.enable is the whole trick: an injected `debugger;` is
@@ -247,6 +261,34 @@ describe("DebugSession", () => {
247
261
  expect(transport.added[0]).to.contain('setItem("sk-devtools-bp4", "on")');
248
262
  });
249
263
  });
264
+ describe("arm --compared", () => {
265
+ it("wraps the comparison marks even when the extension is loaded", async () => {
266
+ const { session, transport } = build(true);
267
+ await session.arm([1, 3], "none", true);
268
+ expect(transport.added[0]).to.contain("performance.mark = function");
269
+ expect(transport.added[0]).to.contain('"skChangeDetectionStart":1');
270
+ expect(transport.added[0]).to.contain('"sk-prerender-change-detection-start":3');
271
+ expect(transport.added[0]).to.contain('removeItem("sk-devtools-bp1")');
272
+ expect(transport.added[0]).to.not.contain('setItem("sk-devtools-bp1"');
273
+ });
274
+ it("copies the sides from BP1's calling frame", async () => {
275
+ const { session, transport } = build();
276
+ transport.lastBp = "BP1";
277
+ transport.evalValue = { pass: "regular", legacy: false, rules: 2 };
278
+ await session.arm([1], "none", true);
279
+ const waiting = session.awaitPause(2000);
280
+ const payload = pausedPayload();
281
+ payload.callFrames.push({
282
+ ...payload.callFrames[0],
283
+ callFrameId: "frame-2",
284
+ });
285
+ transport.emit("Debugger.paused", payload);
286
+ const result = await waiting;
287
+ const capture = transport.sent.find(({ params }) => params?.expression?.includes("__skCD = "));
288
+ expect(capture?.params).to.include({ callFrameId: "frame-2" });
289
+ expect(result.pause?.compared).to.deep.equal(transport.evalValue);
290
+ });
291
+ });
250
292
  describe("what the panel is told", () => {
251
293
  it("reports the armed set so the panel's switches can mirror it", async () => {
252
294
  // The panel's switches are backed by extension storage rather than read
@@ -283,6 +325,22 @@ describe("DebugSession", () => {
283
325
  expect(result.navigationType).to.equal("reload");
284
326
  expect(result.diagnosis).to.contain("was a reload");
285
327
  });
328
+ it("should always answer with paused and pause, paused or not", async () => {
329
+ // An answer without them was read as a pause. JSON drops what is
330
+ // undefined, so the contract is checked after a round trip.
331
+ const { session, transport } = build();
332
+ await session.arm([3]);
333
+ const quiet = JSON.parse(JSON.stringify(await session.awaitPause(10)));
334
+ expect(quiet).to.include({ paused: false, pause: null, fired: false });
335
+ // `paused` is set at once, the pause itself once its frame is read.
336
+ const send = transport.send.bind(transport);
337
+ transport.send = (method, params) => method === "Debugger.evaluateOnCallFrame"
338
+ ? new Promise(() => undefined)
339
+ : send(method, params);
340
+ transport.emit("Debugger.paused", pausedPayload());
341
+ const result = JSON.parse(JSON.stringify(await session.awaitPause(10)));
342
+ expect(result).to.include({ paused: true, pause: null, fired: false });
343
+ });
286
344
  it("should refuse to wait when nothing is armed", async () => {
287
345
  const { session } = build();
288
346
  expect(await rejection(session.awaitPause(10))).to.be.instanceOf(NotArmedError);
@@ -0,0 +1,47 @@
1
+ import { expect } from "chai";
2
+ import { describe, it } from "mocha";
3
+ import { AFTER_LOAD_GRACE_MS, decideWait, } from "../../control/navigate-wait.js";
4
+ function probe(patch = {}) {
5
+ return {
6
+ marks: {},
7
+ ssr: false,
8
+ readyState: "interactive",
9
+ responseSource: "AssetAPI",
10
+ responseCause: "Hit",
11
+ ...patch,
12
+ };
13
+ }
14
+ describe("decideWait", () => {
15
+ it("returns the mark's time once it lands", () => {
16
+ expect(decideWait("bp2", probe({ marks: { "baqend-blocking-script-end": 812 } }))).to.deep.equal({
17
+ point: "bp2",
18
+ mark: "baqend-blocking-script-end",
19
+ reached: true,
20
+ atMs: 812,
21
+ });
22
+ });
23
+ it("returns at once for an SSR mark on a page without SSR", () => {
24
+ const decided = decideWait("bp3", probe());
25
+ expect(decided.reached).to.equal(false);
26
+ expect(decided.reason).to.contain("no SSR on this page");
27
+ });
28
+ it("names the skipped comparison when BP4 landed without BP3", () => {
29
+ const decided = decideWait("bp3", probe({ ssr: true, marks: { "sk-prerender-observe-end": 1500 } }));
30
+ expect(decided.reason).to.contain("skipped the SSR comparison");
31
+ });
32
+ it("waits for a merge mark until the load event is some time past", () => {
33
+ expect(decideWait("bp1", probe({ readyState: "complete" }), 100)).to.equal(undefined);
34
+ });
35
+ it("names why Speed Kit did not merge once the page has loaded", () => {
36
+ const decided = decideWait("bp1", probe({
37
+ readyState: "complete",
38
+ responseSource: "Network",
39
+ responseCause: "Blacklist",
40
+ }), AFTER_LOAD_GRACE_MS);
41
+ expect(decided.reached).to.equal(false);
42
+ expect(decided.reason).to.contain("responseCause Blacklist");
43
+ });
44
+ it("keeps waiting for BP4 on an SSR page after the load event", () => {
45
+ expect(decideWait("bp4", probe({ ssr: true, readyState: "complete" }), 10_000)).to.equal(undefined);
46
+ });
47
+ });
@@ -59,6 +59,21 @@ describe("runWatch", () => {
59
59
  expect(result.totalSamples).to.equal(5);
60
60
  expect(result.mode).to.equal("transitions");
61
61
  });
62
+ it("should say when it raised a too-short interval", async () => {
63
+ const transport = new FakeTransport();
64
+ const preloads = new PreloadRegistry(transport);
65
+ transport.page = slot([sample(1)]);
66
+ const raised = await runWatch(preloads, async () => undefined, {
67
+ ...options,
68
+ intervalMs: 10,
69
+ });
70
+ const kept = await runWatch(preloads, async () => undefined, options);
71
+ expect(raised.intervalMs).to.equal(20);
72
+ expect(raised.notes).to.deep.equal([
73
+ "interval 10ms raised to 20ms, the shortest the sampler takes",
74
+ ]);
75
+ expect(kept.notes).to.deep.equal([]);
76
+ });
62
77
  it("should hand back every tick when asked", async () => {
63
78
  const transport = new FakeTransport();
64
79
  const preloads = new PreloadRegistry(transport);
@@ -178,6 +178,23 @@ describe("FetchEventHandler request records", () => {
178
178
  expect(requestLog.records[0]).to.include({ outcome: "error" });
179
179
  expect(requestLog.records[0].error).to.contain("handler blew up");
180
180
  });
181
+ it("records a request the page dropped as cancelled, not as an error", async () => {
182
+ // A navigation away while a handler works leaves Chrome's interception id
183
+ // stale. As an error it headed the problems list and read as a proxy fault.
184
+ const stale = {
185
+ patterns: [{ urlPattern: ".*", requestStage: "Request" }],
186
+ handle: async () => {
187
+ throw new Error("Protocol error (Fetch.continueRequest): Invalid InterceptionId.");
188
+ },
189
+ };
190
+ const errors = [];
191
+ cli.writeError = (text) => void errors.push(text);
192
+ const { requestLog, session } = await intercept([stale]);
193
+ cli.writeError = () => undefined;
194
+ expect(requestLog.records[0].outcome).to.equal("cancelled");
195
+ expect(errors).to.deep.equal([]);
196
+ expect(session.sent.map(({ method }) => method)).to.not.include("Fetch.failRequest");
197
+ });
181
198
  it("distinguishes the response stage from the request stage", async () => {
182
199
  const { requestLog } = await intercept([], pausedEvent({ responseHeaders: [{ name: "x", value: "y" }] }));
183
200
  expect(requestLog.records[0].stage).to.equal("Response");
@@ -30,8 +30,8 @@ describe("BrowserContext.getPuppeteerLaunchOptions remote debugging port", () =>
30
30
  it("uses the provided debug port when debugging is enabled", () => {
31
31
  expect(remoteDebuggingArg(true, false, 9223)).to.equal("--remote-debugging-port=9223");
32
32
  });
33
- it("uses the provided debug port in headless mode", () => {
34
- expect(remoteDebuggingArg(false, true, 9224)).to.equal("--remote-debugging-port=9224");
33
+ it("opens no port in headless mode without -p", () => {
34
+ expect(remoteDebuggingArg(false, true, 9224)).to.equal(undefined);
35
35
  });
36
36
  it("omits the remote debugging port when debugging and headless are both off", () => {
37
37
  expect(remoteDebuggingArg(false, false, 9223)).to.equal(undefined);
@@ -281,7 +281,6 @@ describe("BrowserContext launch options", () => {
281
281
  };
282
282
  for (const [debuggingPort, headless] of [
283
283
  [true, false],
284
- [false, true],
285
284
  [true, true],
286
285
  ]) {
287
286
  const { args } = new BrowserContext("example.com", "Google Chrome for Testing 154.0.8037.57", [], withExtensions, undefined, debuggingPort, headless, 9333).getPuppeteerLaunchOptions();
@@ -11,6 +11,7 @@ import { MissingCustomerPathError } from "../error/missing-customer-path-error.j
11
11
  import { BrowserContext } from "../onboarding-model.js";
12
12
  import { OnboardingServiceBuildContext, } from "../onboarding-service-build-context.js";
13
13
  import { OnboardingServiceFactory } from "../onboarding-service-factory.js";
14
+ import { RunRegistry } from "../../run-registry/index.js";
14
15
  const cli = new Proxy({}, {
15
16
  get: (_target, property) => property === "nonInteractive" ? true : () => undefined,
16
17
  });
@@ -83,6 +84,24 @@ describe("OnboardingServiceFactory", () => {
83
84
  customerChromeFlags: undefined,
84
85
  });
85
86
  });
87
+ it("serves run control on a recorded browse run", async () => {
88
+ const cacheDirectory = mkdtempSync(join(tmpdir(), "sk-browse-run-"));
89
+ const run = new RunRegistry(cacheDirectory).start({
90
+ domain: "www.example.com",
91
+ configName: "production",
92
+ cliVersion: "1.2.3",
93
+ flags: {
94
+ local: true,
95
+ headless: true,
96
+ useTestConfig: false,
97
+ ignoreContentSecurityPolicy: false,
98
+ },
99
+ });
100
+ const service = await new RecordingFactory(buildContext({ browse: true, domain: "www.example.com" }), run).getService();
101
+ const { controlServer } = service;
102
+ expect(controlServer?.socketPath).to.equal(join(run.dir, "control.sock"));
103
+ rmSync(cacheDirectory, { recursive: true, force: true });
104
+ });
86
105
  it("fails in browse mode without a domain and without a CUSTOMERPATH", async () => {
87
106
  const factory = new RecordingFactory(buildContext({ browse: true }));
88
107
  const error = await factory.getService().catch((error_) => error_);
@@ -188,7 +207,11 @@ describe("OnboardingServiceFactory", () => {
188
207
  });
189
208
  }
190
209
  it("keeps the extensions and a TCP debug port next to the pipe", () => {
191
- const options = launchOptions({ browse: true, headless: true });
210
+ const options = launchOptions({
211
+ browse: true,
212
+ headless: true,
213
+ debuggingPort: true,
214
+ });
192
215
  expect(options).to.include({ pipe: true, headless: true });
193
216
  expect(options["enableExtensions"]).to.deep.equal([
194
217
  "/tmp/sk-test-devtools",
@@ -0,0 +1,65 @@
1
+ import { expect } from "chai";
2
+ import { describe, it } from "mocha";
3
+ import { mkdtempSync, rmSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { memoryCli } from "../../../cli/spec/memory-cli.js";
7
+ import { MemorySink } from "../../../cli/sink.js";
8
+ import { Cache } from "../../request-cache/cache.js";
9
+ import { assetRequestUrl } from "../../request-cache/asset-key.js";
10
+ import { VirtualOrestesApp } from "../../virtual-orestes-app/index.js";
11
+ const APP_DOMAIN = "shop.app.baqend.com";
12
+ const PAGE = "https://shop.example.com/cart";
13
+ /** A local app whose origin fetcher names `variations` and must not be asked to fetch. */
14
+ function app(sink, variations = []) {
15
+ const directory = mkdtempSync(join(tmpdir(), "sk-orestes-"));
16
+ let fetched = false;
17
+ const originFetcher = {
18
+ namedVariations: () => variations,
19
+ fetch: async () => {
20
+ fetched = true;
21
+ return undefined;
22
+ },
23
+ };
24
+ const orestes = new VirtualOrestesApp({ appDomain: APP_DOMAIN }, originFetcher, {}, new Cache(memoryCli(), join(directory, "dh-cache")), memoryCli(sink), {});
25
+ return {
26
+ orestes,
27
+ fetched: () => fetched,
28
+ remove: () => rmSync(directory, { recursive: true, force: true }),
29
+ };
30
+ }
31
+ const request = (variation) => ({
32
+ request: { url: assetRequestUrl(APP_DOMAIN, PAGE, variation) },
33
+ });
34
+ describe("VirtualOrestesApp — the break variation", () => {
35
+ it("should answer a break page as Orestes does, so the worker serves it from origin", async () => {
36
+ const sink = new MemorySink();
37
+ const { orestes, fetched, remove } = app(sink);
38
+ try {
39
+ const response = (await orestes.fetchAssetResponse(request("break")));
40
+ await orestes.fetchAssetResponse(request("break"));
41
+ expect(response.responseCode).to.equal(400);
42
+ expect(response.responseHeaders).to.deep.include({
43
+ name: "server-timing",
44
+ value: "errorcode;desc=322",
45
+ });
46
+ expect(fetched()).to.equal(false);
47
+ const reported = sink.lines.filter((line) => line.includes("break"));
48
+ expect(reported).to.have.length(1);
49
+ expect(reported[0]).to.contain("served from origin");
50
+ }
51
+ finally {
52
+ remove();
53
+ }
54
+ });
55
+ it("should build a break page like any other when the runtime config defines break", async () => {
56
+ const { orestes, fetched, remove } = app(new MemorySink(), ["break"]);
57
+ try {
58
+ await orestes.fetchAssetResponse(request("break"));
59
+ expect(fetched()).to.equal(true);
60
+ }
61
+ finally {
62
+ remove();
63
+ }
64
+ });
65
+ });
@@ -17,6 +17,8 @@ export declare class VirtualOrestesApp {
17
17
  private removeContentSecurityPolicy;
18
18
  private localCacheErrors;
19
19
  private prerendererHintShown;
20
+ /** The pages already reported as `break` pages, so each is reported once. */
21
+ private readonly breakPages;
20
22
  constructor(customerConfig: CustomerConfig, originFetcher: OriginFetcher, documentHandler: DocumentHandlerServer, cache: Cache, cli: CliServiceInterface, developmentToolsMessages: DevtoolsExtensionApi, removeContentSecurityPolicy?: boolean);
21
23
  fetchAssetResponse(event: Protocol.Fetch.RequestPausedEvent): Promise<Partial<Protocol.Fetch.FulfillRequestRequest> | AbortResponse>;
22
24
  /** The variations the runtime config names: see {@link OriginFetcher.namedVariations}. */
@@ -94,6 +96,8 @@ export declare class VirtualOrestesApp {
94
96
  * `ServerDocumentHandlerAbort`. Answering 500 instead makes the service worker treat
95
97
  * the page as an infrastructure failure and disconnect Speed Kit.
96
98
  */
99
+ /** What Orestes answers for an undefined variation: the service worker serves from origin. */
100
+ private returnBreakResponse;
97
101
  private returnAbortResponse;
98
102
  private reportAbort;
99
103
  private warnPrerendererUnreachable;
@@ -21,6 +21,13 @@ const SECURITY_HEADERS = [
21
21
  "strict-transport-security",
22
22
  "x-frame-options",
23
23
  ];
24
+ /**
25
+ * The reserved variation a `customVariation` returns to serve a page from origin. Orestes
26
+ * defines no such variation, so it answers a Bad Request and the service worker falls back.
27
+ */
28
+ const BREAK_VARIATION = "break";
29
+ /** Orestes' `ServerVariationNotDefined`, the error code a `break` request gets. */
30
+ const VARIATION_NOT_DEFINED_CODE = "322";
24
31
  export class VirtualOrestesApp {
25
32
  customerConfig;
26
33
  originFetcher;
@@ -36,6 +43,8 @@ export class VirtualOrestesApp {
36
43
  localCacheErrors = new Map();
37
44
  // The hint to start the pre-renderer is shown once; every later page gets one line.
38
45
  prerendererHintShown = false;
46
+ /** The pages already reported as `break` pages, so each is reported once. */
47
+ breakPages = new Set();
39
48
  constructor(customerConfig, originFetcher, documentHandler, cache, cli, developmentToolsMessages, removeContentSecurityPolicy = false) {
40
49
  this.customerConfig = customerConfig;
41
50
  this.originFetcher = originFetcher;
@@ -149,6 +158,10 @@ export class VirtualOrestesApp {
149
158
  const variation = UrlObject.searchParams.has("bqvariation")
150
159
  ? UrlObject.searchParams.get("bqvariation").trim()
151
160
  : "default";
161
+ if (variation === BREAK_VARIATION &&
162
+ !this.originFetcher.namedVariations().includes(BREAK_VARIATION)) {
163
+ return this.returnBreakResponse(originUrl);
164
+ }
152
165
  const fetchResult = await this.originFetcher.fetch(originUrl, variation);
153
166
  const response = fetchResult?.response;
154
167
  // URL we actually fetched (origin + variation query params); used for the redirect check below
@@ -280,6 +293,24 @@ export class VirtualOrestesApp {
280
293
  * `ServerDocumentHandlerAbort`. Answering 500 instead makes the service worker treat
281
294
  * the page as an infrastructure failure and disconnect Speed Kit.
282
295
  */
296
+ /** What Orestes answers for an undefined variation: the service worker serves from origin. */
297
+ returnBreakResponse(originUrl) {
298
+ if (!this.breakPages.has(originUrl)) {
299
+ this.breakPages.add(originUrl);
300
+ this.cli.comment(`${originUrl} has the variation break: served from origin, not accelerated`, false, {
301
+ scope: "cache",
302
+ data: { url: originUrl, variation: BREAK_VARIATION },
303
+ });
304
+ }
305
+ const message = `Variation ${BREAK_VARIATION} not found.`;
306
+ return new BaqendResponse(message, null, [
307
+ { name: "x-error", value: message },
308
+ {
309
+ name: "server-timing",
310
+ value: originErrorServerTiming(VARIATION_NOT_DEFINED_CODE),
311
+ },
312
+ ], ORIGIN_ERROR_STATUS_CODE);
313
+ }
283
314
  returnAbortResponse(customResponse, customHeaders) {
284
315
  const message = customResponse.error;
285
316
  this.reportAbort(message, customResponse.errorObj);
@@ -15,6 +15,12 @@ export interface OriginRequestConfig {
15
15
  /** `speedKit.originMap`: per origin, a rewrite target and extra headers. */
16
16
  readonly originMap: OriginMap;
17
17
  }
18
+ /**
19
+ * What a session without the runtime config loses. Everything the runtime config alone carries
20
+ * is gone, including any override of a device variation; those still resolve from their
21
+ * built-in defaults only.
22
+ */
23
+ export declare const NO_RUNTIME_CONFIG_WARNING = "without the runtime config, origin fetches carry no basic auth, no custom variation and no configured override of default, mobile or tablet \u2014 those fall back to the built-in defaults.";
18
24
  /** What loading the runtime config reports through. */
19
25
  export type RuntimeConfigLog = Pick<CliServiceInterface, "writeError" | "writeSuccess" | "startAction" | "successAction" | "failAction">;
20
26
  export interface RuntimeConfigSourceDeps {
@@ -1,5 +1,11 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import { safe } from "../../helpers/safe.js";
3
+ /**
4
+ * What a session without the runtime config loses. Everything the runtime config alone carries
5
+ * is gone, including any override of a device variation; those still resolve from their
6
+ * built-in defaults only.
7
+ */
8
+ export const NO_RUNTIME_CONFIG_WARNING = "without the runtime config, origin fetches carry no basic auth, no custom variation and no configured override of default, mobile or tablet — those fall back to the built-in defaults.";
3
9
  /**
4
10
  * The runtime config a request to origin is built from: the app's deployed one, so a request
5
11
  * follows production, or a local file the command names.