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

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 (97) 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 +6 -1
  35. package/dist/services/onboarding/browser/resume-restarted-workers.d.ts +14 -0
  36. package/dist/services/onboarding/browser/resume-restarted-workers.js +26 -0
  37. package/dist/services/onboarding/control/browser-session.d.ts +26 -12
  38. package/dist/services/onboarding/control/browser-session.js +118 -91
  39. package/dist/services/onboarding/control/control-protocol.d.ts +39 -1
  40. package/dist/services/onboarding/control/control-protocol.js +0 -11
  41. package/dist/services/onboarding/control/control-server.d.ts +8 -0
  42. package/dist/services/onboarding/control/control-server.js +22 -2
  43. package/dist/services/onboarding/control/debug-session.d.ts +30 -1
  44. package/dist/services/onboarding/control/debug-session.js +106 -10
  45. package/dist/services/onboarding/control/navigate-wait.d.ts +33 -0
  46. package/dist/services/onboarding/control/navigate-wait.js +56 -0
  47. package/dist/services/onboarding/control/service-worker-tracker.js +1 -0
  48. package/dist/services/onboarding/control/watch.js +9 -1
  49. package/dist/services/onboarding/fetch-event-handler.js +9 -0
  50. package/dist/services/onboarding/inject/inject-service.js +1 -1
  51. package/dist/services/onboarding/onboarding-model.js +2 -1
  52. package/dist/services/onboarding/onboarding-service-build-context.js +1 -1
  53. package/dist/services/onboarding/onboarding-service-factory.js +20 -7
  54. package/dist/services/onboarding/onboarding-service.js +1 -1
  55. package/dist/services/onboarding/spec/browser/answer-dialogs.spec.d.ts +1 -0
  56. package/dist/services/onboarding/spec/browser/answer-dialogs.spec.js +66 -0
  57. package/dist/services/onboarding/spec/browser/resume-restarted-workers.spec.d.ts +1 -0
  58. package/dist/services/onboarding/spec/browser/resume-restarted-workers.spec.js +45 -0
  59. package/dist/services/onboarding/spec/control/browser-session.spec.js +127 -2
  60. package/dist/services/onboarding/spec/control/control-server.spec.js +33 -0
  61. package/dist/services/onboarding/spec/control/debug-session.spec.js +58 -0
  62. package/dist/services/onboarding/spec/control/navigate-wait.spec.d.ts +1 -0
  63. package/dist/services/onboarding/spec/control/navigate-wait.spec.js +47 -0
  64. package/dist/services/onboarding/spec/control/watch.spec.js +15 -0
  65. package/dist/services/onboarding/spec/fetch-event-handler.spec.js +17 -0
  66. package/dist/services/onboarding/spec/onboarding-model.spec.js +2 -3
  67. package/dist/services/onboarding/spec/onboarding-service-factory.spec.js +24 -1
  68. package/dist/services/onboarding/spec/virtual-orestes-app/virtual-orestes-app.spec.d.ts +1 -0
  69. package/dist/services/onboarding/spec/virtual-orestes-app/virtual-orestes-app.spec.js +65 -0
  70. package/dist/services/onboarding/virtual-orestes-app/index.d.ts +4 -0
  71. package/dist/services/onboarding/virtual-orestes-app/index.js +31 -0
  72. package/dist/services/origin-request/runtime-config-source.d.ts +6 -0
  73. package/dist/services/origin-request/runtime-config-source.js +6 -0
  74. package/dist/services/run-control/browser/run-browser-contexts.d.ts +16 -0
  75. package/dist/services/run-control/browser/run-browser-contexts.js +14 -1
  76. package/dist/services/run-control/browser/run-browser-service.d.ts +5 -1
  77. package/dist/services/run-control/browser/run-browser-service.js +16 -9
  78. package/dist/services/run-control/debug/run-debug-contexts.d.ts +5 -0
  79. package/dist/services/run-control/debug/run-debug-contexts.js +3 -0
  80. package/dist/services/run-control/debug/run-debug-service.d.ts +1 -0
  81. package/dist/services/run-control/debug/run-debug-service.js +3 -0
  82. package/dist/services/run-control/files/run-files-contexts.d.ts +5 -5
  83. package/dist/services/run-control/inject/run-inject-contexts.js +7 -1
  84. package/dist/services/run-control/inject/run-inject-service.d.ts +2 -2
  85. package/dist/services/run-control/inject/run-inject-service.js +32 -8
  86. package/dist/services/run-control/probe/run-probe-service.js +1 -0
  87. package/dist/services/run-control/session/run-session-service.d.ts +8 -1
  88. package/dist/services/run-control/session/run-session-service.js +58 -2
  89. package/dist/services/run-control/spec/cache/run-cache-service.spec.js +1 -1
  90. package/dist/services/run-control/spec/inject/run-inject-service.spec.js +27 -0
  91. package/dist/services/run-control/spec/session/run-session-service.spec.js +49 -0
  92. package/dist/services/run-log/request-log.d.ts +3 -1
  93. package/dist/services/run-registry/run-registry.d.ts +7 -2
  94. package/dist/services/run-registry/run-registry.js +26 -5
  95. package/dist/services/run-registry/spec/run-registry.spec.js +17 -0
  96. package/oclif.manifest.json +281 -181
  97. package/package.json +1 -1
@@ -0,0 +1,13 @@
1
+ import { RunControlCommand } from "../../base/run-control-command.js";
2
+ import { RunSessionBuildContext } from "../../services/run-control/index.js";
3
+ export default class Stop extends RunControlCommand<InstanceType<typeof RunSessionBuildContext>> {
4
+ static description: string;
5
+ static buildContext: typeof RunSessionBuildContext;
6
+ static args: {};
7
+ static flags: {
8
+ run: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
9
+ json: import("@oclif/core/interfaces").BooleanFlag<boolean>;
10
+ };
11
+ static examples: string[];
12
+ run(): Promise<void>;
13
+ }
@@ -0,0 +1,17 @@
1
+ import { RunControlCommand } from "../../base/run-control-command.js";
2
+ import { RunSessionBuildContext, RunSessionServiceFactory, } from "../../services/run-control/index.js";
3
+ export default class Stop extends RunControlCommand {
4
+ static description = "End the live onboarding run, or the one --run names, as Ctrl+C does";
5
+ static buildContext = RunSessionBuildContext;
6
+ static args = RunSessionBuildContext.args;
7
+ static flags = RunSessionBuildContext.flags;
8
+ static examples = [
9
+ `$ sk onboarding stop`,
10
+ `$ sk onboarding stop --run worktree/my-task/customers/decathlon.de --json`,
11
+ ];
12
+ async run() {
13
+ await new RunSessionServiceFactory(this.context)
14
+ .buildService()
15
+ .stop(this.context.run);
16
+ }
17
+ }
@@ -14,7 +14,7 @@ import { RunRegistry } from "../services/run-registry/index.js";
14
14
  * @returns whether to go ahead.
15
15
  */
16
16
  export declare function confirmConflicts(cli: CliServiceInterface, registry: RunRegistry, intent: {
17
- customerPath: string;
17
+ customerPath?: string;
18
18
  debugPort?: number;
19
19
  }): Promise<boolean>;
20
20
  export default class Onboarding extends SkCommand<OnboardingServiceBuildContext> {
@@ -62,7 +62,7 @@ export default class Onboarding extends SkCommand {
62
62
  static examples = [
63
63
  `$ sk onboarding <customerPath> -c <configName> -d <domain>`,
64
64
  `$ sk onboarding customers/decathlon.de -c production -d www.decathlon.de`,
65
- `$ sk onboarding --browse -d www.decathlon.de --headless --debugPort 9290`,
65
+ `$ sk onboarding --browse -d www.decathlon.de --headless`,
66
66
  `$ sk onboarding customers/decathlon.de --browse -p`,
67
67
  `$ sk onboarding customers/decathlon.de -p --device tablet`,
68
68
  `$ sk onboarding customers/decathlon.de --inject`,
@@ -22,6 +22,7 @@ declare const flags: {
22
22
  browserFetch: Interfaces.BooleanFlag<boolean>;
23
23
  host: Interfaces.OptionFlag<string, Interfaces.CustomOptions>;
24
24
  variationsFile: Interfaces.OptionFlag<string, Interfaces.CustomOptions>;
25
+ run: Interfaces.OptionFlag<string, Interfaces.CustomOptions>;
25
26
  hideDiff: Interfaces.BooleanFlag<boolean>;
26
27
  configName: Interfaces.OptionFlag<string, Interfaces.CustomOptions>;
27
28
  };
@@ -75,6 +76,8 @@ export interface DiffOptions {
75
76
  readonly ignore: readonly string[];
76
77
  readonly host?: string;
77
78
  readonly variationsFile?: string;
79
+ /** `--run`: the live run whose runtime config the requests follow. */
80
+ readonly run?: string;
78
81
  /** Fetch through a headless Chrome instead of a direct request. */
79
82
  readonly browserFetch: boolean;
80
83
  }
@@ -104,6 +107,7 @@ export declare class DiffServiceBuildContext extends DiffServiceBuildContext_bas
104
107
  browserFetch: Interfaces.BooleanFlag<boolean>;
105
108
  host: Interfaces.OptionFlag<string, Interfaces.CustomOptions>;
106
109
  variationsFile: Interfaces.OptionFlag<string, Interfaces.CustomOptions>;
110
+ run: Interfaces.OptionFlag<string, Interfaces.CustomOptions>;
107
111
  hideDiff: Interfaces.BooleanFlag<boolean>;
108
112
  configName: Interfaces.OptionFlag<string, Interfaces.CustomOptions>;
109
113
  };
@@ -77,6 +77,10 @@ const flags = {
77
77
  variationsFile: Flags.string({
78
78
  description: "Resolve the requests against a runtime config in a local file instead of the app's deployed one",
79
79
  }),
80
+ run: Flags.string({
81
+ exclusive: ["variationsFile"],
82
+ description: "Take the runtime config from this live sk onboarding run: its id, its customer name, or its path. Without it, the one live run of the customer is used",
83
+ }),
80
84
  hideDiff: Flags.boolean({
81
85
  char: "h",
82
86
  hidden: true,
@@ -334,6 +338,7 @@ export class DiffServiceBuildContext extends Context() {
334
338
  ignore: parsedFlags.ignore ?? [],
335
339
  host: parsedFlags.host,
336
340
  variationsFile: parsedFlags.variationsFile,
341
+ run: parsedFlags.run,
337
342
  browserFetch: parsedFlags.browserFetch,
338
343
  });
339
344
  }
@@ -13,6 +13,8 @@ import { stderrLog } from "./diff-log.js";
13
13
  import { variationPair, } from "./diff-service-build-context.js";
14
14
  import { DiffService } from "./diff-service.js";
15
15
  import { configAtRef } from "./config-at-ref.js";
16
+ import { RunRegistry } from "../run-registry/index.js";
17
+ import { DEFAULTS_ONLY, diffRuntimeConfig, liveRunFor, } from "./run-runtime-config.js";
16
18
  import { PageSource } from "./page-source.js";
17
19
  /**
18
20
  * The variations a person can choose from: the device variations and the
@@ -65,10 +67,20 @@ export class DiffServiceFactory {
65
67
  }
66
68
  applyOriginProxy(customer.chromeFlags, ownsStdout ? undefined : environment.cli);
67
69
  }
68
- const config = await this.loadRuntimeConfig(log, customer?.app);
69
- if (!config) {
70
- throw new ApplicationError("no runtime config to build the requests from");
71
- }
70
+ const config = await diffRuntimeConfig({
71
+ log,
72
+ // A named file wins; else the live run the customer has, so the diff sees what it sees.
73
+ run: this.context.variationsFile
74
+ ? undefined
75
+ : liveRunFor({
76
+ registry: new RunRegistry(environment.cacheDir),
77
+ selector: this.context.run,
78
+ customerPath: this.context.customerPath,
79
+ }),
80
+ runNamed: Boolean(this.context.run),
81
+ file: this.context.variationsFile,
82
+ load: () => this.loadRuntimeConfig(log, customer?.app),
83
+ });
72
84
  const options = await this.withChosenVariations(chosenParameters, config.variations);
73
85
  const fetcher = new OriginFetcher({
74
86
  cli: log,
@@ -173,7 +185,7 @@ export class DiffServiceFactory {
173
185
  async loadRuntimeConfig(log, app) {
174
186
  if (!app && !this.context.variationsFile) {
175
187
  log.writeWarning("no customer: the requests carry Speed Kit's device defaults only, no variations of an app");
176
- return { variations: {}, authentications: [], originMap: {} };
188
+ return DEFAULTS_ONLY;
177
189
  }
178
190
  return new RuntimeConfigSource({
179
191
  cli: log,
@@ -0,0 +1,33 @@
1
+ import { OriginRequestConfig } from "../origin-request/index.js";
2
+ import { LiveRun } from "../run-control/live-run.js";
3
+ import { RunRegistry } from "../run-registry/index.js";
4
+ import { DiffLog } from "./diff-log.js";
5
+ /** What a request carries without a runtime config: the device defaults only. */
6
+ export declare const DEFAULTS_ONLY: OriginRequestConfig;
7
+ /**
8
+ * The live run whose runtime config `sk diff` follows: the one `--run` names,
9
+ * else the one live run of the customer. Several live runs pick none.
10
+ */
11
+ export declare function liveRunFor(input: {
12
+ registry: RunRegistry;
13
+ selector?: string;
14
+ customerPath?: string;
15
+ }): LiveRun | undefined;
16
+ export interface DiffRuntimeConfigDeps {
17
+ readonly log: DiffLog;
18
+ /** The live run to follow; absent without one. */
19
+ readonly run?: Pick<LiveRun, "id" | "request">;
20
+ /** Whether `--run` named the run, so a failure to ask it is not hidden. */
21
+ readonly runNamed?: boolean;
22
+ /** `--variationsFile`: the file `load` reads instead of the app's config. */
23
+ readonly file?: string;
24
+ /** The app's or the file's runtime config, as `RuntimeConfigSource` loads it. */
25
+ readonly load: () => Promise<OriginRequestConfig | undefined>;
26
+ }
27
+ /**
28
+ * The runtime config `sk diff` builds its requests from: the live run's, so
29
+ * the diff sees what the run sees, else the one `load` reads.
30
+ *
31
+ * @throws {ApplicationError} Without a config: the run loaded none, or `load` read none.
32
+ */
33
+ export declare function diffRuntimeConfig(deps: DiffRuntimeConfigDeps): Promise<OriginRequestConfig>;
@@ -0,0 +1,74 @@
1
+ import { resolve } from "node:path";
2
+ import ApplicationError from "../error-handling/error/application-error.js";
3
+ import { ControlError } from "../run-control/control-client.js";
4
+ import { LiveRun } from "../run-control/live-run.js";
5
+ /** What a request carries without a runtime config: the device defaults only. */
6
+ export const DEFAULTS_ONLY = {
7
+ variations: {},
8
+ authentications: [],
9
+ originMap: {},
10
+ };
11
+ /**
12
+ * The live run whose runtime config `sk diff` follows: the one `--run` names,
13
+ * else the one live run of the customer. Several live runs pick none.
14
+ */
15
+ export function liveRunFor(input) {
16
+ const { registry, selector, customerPath } = input;
17
+ if (selector)
18
+ return LiveRun.resolve(registry, selector);
19
+ if (!customerPath)
20
+ return undefined;
21
+ const wanted = resolve(customerPath);
22
+ const runs = registry
23
+ .liveRuns()
24
+ .filter((run) => (run.meta.customerDir ?? resolve(run.meta.customerPath)) === wanted);
25
+ return runs.length === 1 ? new LiveRun(runs[0]) : undefined;
26
+ }
27
+ /**
28
+ * The runtime config `sk diff` builds its requests from: the live run's, so
29
+ * the diff sees what the run sees, else the one `load` reads.
30
+ *
31
+ * @throws {ApplicationError} Without a config: the run loaded none, or `load` read none.
32
+ */
33
+ export async function diffRuntimeConfig(deps) {
34
+ const { log, run, runNamed, file, load } = deps;
35
+ if (run) {
36
+ try {
37
+ const { config } = await run.request({
38
+ op: "config.runtime",
39
+ });
40
+ if (config) {
41
+ log.comment(`runtime config from the live run ${run.id}`);
42
+ return config;
43
+ }
44
+ // The device defaults would hide that the run lacks the variations and the basic auth.
45
+ throw noRuntimeConfig(`the live run ${run.id} loaded no runtime config`, [
46
+ 'Run "sk login", then restart the run so it loads the runtime config.',
47
+ ]);
48
+ }
49
+ catch (error) {
50
+ // A run of an older build does not know the op; the login still works.
51
+ if (runNamed || !(error instanceof ControlError))
52
+ throw error;
53
+ log.comment(`the live run ${run.id} did not share its runtime config (${error.message}); loading the app's`);
54
+ }
55
+ }
56
+ const config = await load();
57
+ if (!config && file) {
58
+ throw new ApplicationError(`no runtime config to build the requests from: ${file} could not be read`);
59
+ }
60
+ if (!config) {
61
+ throw noRuntimeConfig("no login", [
62
+ 'Run "sk login".',
63
+ "Or pass --run <run> to take it from a live sk onboarding run.",
64
+ ]);
65
+ }
66
+ return config;
67
+ }
68
+ /** The refusal without a runtime config; `--variationsFile` always fixes it. */
69
+ function noRuntimeConfig(cause, fixes) {
70
+ return new ApplicationError(`no runtime config to build the requests from: ${cause}`, [
71
+ ...fixes,
72
+ "Or pass --variationsFile <file> to use a config you already have.",
73
+ ]);
74
+ }
@@ -0,0 +1,87 @@
1
+ import { expect } from "chai";
2
+ import { describe, it } from "mocha";
3
+ import ApplicationError from "../../error-handling/error/application-error.js";
4
+ import { memoryCli } from "../../cli/spec/memory-cli.js";
5
+ import { ControlError } from "../../run-control/control-client.js";
6
+ import { diffRuntimeConfig } from "../run-runtime-config.js";
7
+ const LOGIN_CONFIG = {
8
+ variations: { app: { headers: { "x-app": "1" } } },
9
+ authentications: [],
10
+ originMap: {},
11
+ };
12
+ /** A live run that answers `config.runtime` with `config`, or fails with `error`. */
13
+ function liveRun(config, error) {
14
+ return {
15
+ id: "shop-production-1",
16
+ request: async () => {
17
+ if (error)
18
+ throw error;
19
+ return { config };
20
+ },
21
+ };
22
+ }
23
+ describe("diffRuntimeConfig", () => {
24
+ it("should take the config the live run loaded, without the login", async () => {
25
+ const runConfig = { ...LOGIN_CONFIG, originMap: { a: {} } };
26
+ let loaded = false;
27
+ const config = await diffRuntimeConfig({
28
+ log: memoryCli(),
29
+ run: liveRun(runConfig),
30
+ load: async () => {
31
+ loaded = true;
32
+ return LOGIN_CONFIG;
33
+ },
34
+ });
35
+ expect(config).to.deep.equal(runConfig);
36
+ expect(loaded).to.equal(false);
37
+ });
38
+ it("should refuse when the run loaded no config, even with a login, and name the cause and fixes", async () => {
39
+ const error = await diffRuntimeConfig({
40
+ log: memoryCli(),
41
+ run: liveRun(null),
42
+ load: async () => LOGIN_CONFIG,
43
+ }).catch((caught) => caught);
44
+ expect(error).to.be.instanceOf(ApplicationError);
45
+ expect(error.message).to.contain("the live run shop-production-1 loaded no runtime config");
46
+ const suggestions = error.suggestions.join(" ");
47
+ expect(suggestions).to.contain("sk login");
48
+ expect(suggestions).to.contain("--variationsFile");
49
+ });
50
+ it("should refuse without a run and without a login, and name the alternatives", async () => {
51
+ const error = await diffRuntimeConfig({
52
+ log: memoryCli(),
53
+ load: async () => undefined,
54
+ }).catch((caught) => caught);
55
+ expect(error).to.be.instanceOf(ApplicationError);
56
+ expect(error.message).to.contain("no login");
57
+ const suggestions = error.suggestions.join(" ");
58
+ expect(suggestions).to.contain("sk login");
59
+ expect(suggestions).to.contain("--run");
60
+ expect(suggestions).to.contain("--variationsFile");
61
+ });
62
+ it("should refuse when --variationsFile cannot be read, and name the file", async () => {
63
+ const error = await diffRuntimeConfig({
64
+ log: memoryCli(),
65
+ file: "runtime.json",
66
+ load: async () => undefined,
67
+ }).catch((caught) => caught);
68
+ expect(error.message).to.contain("runtime.json could not be read");
69
+ });
70
+ it("should load the app's config when a found run of an older build cannot answer", async () => {
71
+ const config = await diffRuntimeConfig({
72
+ log: memoryCli(),
73
+ run: liveRun(null, new ControlError("UNKNOWN_OP", "no such op")),
74
+ load: async () => LOGIN_CONFIG,
75
+ });
76
+ expect(config).to.equal(LOGIN_CONFIG);
77
+ });
78
+ it("should not hide the failure of a run --run named", async () => {
79
+ const error = await diffRuntimeConfig({
80
+ log: memoryCli(),
81
+ run: liveRun(null, new ControlError("UNKNOWN_OP", "no such op")),
82
+ runNamed: true,
83
+ load: async () => LOGIN_CONFIG,
84
+ }).catch((caught) => caught);
85
+ expect(error).to.be.instanceOf(ControlError);
86
+ });
87
+ });
@@ -1,18 +1,30 @@
1
1
  import { CliServiceInterface } from "../../cli/index.js";
2
2
  import { BrowserContext } from "../onboarding-model.js";
3
+ import { BrowserSession, ControlServer } from "../control/index.js";
3
4
  /**
4
5
  * `sk onboarding --browse`: the onboarding Chrome on the live site, as a visitor gets it.
5
6
  *
6
7
  * It launches the same Chrome as onboarding, with the same flags, profile and extensions. It
7
8
  * installs no request interception, serves no local files and injects no Speed Kit, so a site that
8
9
  * runs Speed Kit in production runs its own deployed build.
10
+ *
11
+ * A recorded run serves the control socket, so `sk onboarding browser …` and
12
+ * `debug …` reach it with `--run`, as they reach an onboarding run.
9
13
  */
10
14
  export declare class BrowseService {
11
15
  private readonly browserContext;
12
16
  private readonly cli;
13
- constructor(browserContext: BrowserContext, cli: CliServiceInterface);
17
+ /** Absent when the run was not recorded. */
18
+ private readonly controlServer?;
19
+ private readonly browserSession?;
20
+ constructor(browserContext: BrowserContext, cli: CliServiceInterface,
21
+ /** Absent when the run was not recorded. */
22
+ controlServer?: ControlServer, browserSession?: BrowserSession);
23
+ private readonly serviceWorkers;
14
24
  /** Opens the site, then blocks until the caller aborts `externalSignal` or Chrome disconnects. */
15
25
  run(externalSignal: AbortSignal): Promise<void>;
26
+ /** Feeds `sk onboarding browser state`, which reads what CDP streamed. */
27
+ private trackServiceWorkers;
16
28
  private readyLine;
17
29
  private findPage;
18
30
  }
@@ -1,21 +1,32 @@
1
1
  import { safe } from "../../../helpers/safe.js";
2
2
  import { launchBrowser, resetBrowserState } from "../browser/launch-browser.js";
3
- import { BROWSER_EVENTS } from "../onboarding-model.js";
3
+ import { BROWSER_EVENTS, CDP_SESSION, } from "../onboarding-model.js";
4
4
  import { waitForAbort } from "../onboarding-service.js";
5
+ import { ServiceWorkerTracker, } from "../control/index.js";
5
6
  /**
6
7
  * `sk onboarding --browse`: the onboarding Chrome on the live site, as a visitor gets it.
7
8
  *
8
9
  * It launches the same Chrome as onboarding, with the same flags, profile and extensions. It
9
10
  * installs no request interception, serves no local files and injects no Speed Kit, so a site that
10
11
  * runs Speed Kit in production runs its own deployed build.
12
+ *
13
+ * A recorded run serves the control socket, so `sk onboarding browser …` and
14
+ * `debug …` reach it with `--run`, as they reach an onboarding run.
11
15
  */
12
16
  export class BrowseService {
13
17
  browserContext;
14
18
  cli;
15
- constructor(browserContext, cli) {
19
+ controlServer;
20
+ browserSession;
21
+ constructor(browserContext, cli,
22
+ /** Absent when the run was not recorded. */
23
+ controlServer, browserSession) {
16
24
  this.browserContext = browserContext;
17
25
  this.cli = cli;
26
+ this.controlServer = controlServer;
27
+ this.browserSession = browserSession;
18
28
  }
29
+ serviceWorkers = new ServiceWorkerTracker();
19
30
  /** Opens the site, then blocks until the caller aborts `externalSignal` or Chrome disconnects. */
20
31
  async run(externalSignal) {
21
32
  this.cli.startAction("ONBOARDING:BROWSE:BROWSER", `prepare browser ${this.cli.style.bold(this.browserContext.browserVersionString)}`);
@@ -24,20 +35,36 @@ export class BrowseService {
24
35
  externalSignal,
25
36
  disconnected.signal,
26
37
  ]);
27
- const browser = await launchBrowser(this.browserContext);
38
+ if (this.controlServer) {
39
+ const listening = await safe(this.controlServer.listen(shutdownSignal));
40
+ if (listening.success !== true) {
41
+ this.cli.writeWarning(`control socket unavailable, external tools cannot reach this run: ${listening.error}`);
42
+ }
43
+ }
44
+ const browser = await launchBrowser(this.browserContext, this.cli);
28
45
  browser.on(BROWSER_EVENTS.DISCONNECTED, () => {
29
46
  this.cli.writeError("Browser disconnected, shutting down");
30
47
  disconnected.abort();
31
48
  });
32
49
  const page = await this.findPage(browser);
33
50
  const url = this.browserContext.domain;
51
+ const origin = new URL(url).origin;
34
52
  const reset = await safe(page
35
53
  .target()
36
54
  .createCDPSession()
37
- .then((session) => resetBrowserState(session, new URL(url).origin)));
55
+ .then((session) => {
56
+ this.trackServiceWorkers(session);
57
+ return resetBrowserState(session, origin);
58
+ }));
38
59
  if (reset.success !== true) {
39
60
  this.cli.writeWarning(`Could not reset the browser state: ${reset.error}`);
40
61
  }
62
+ this.browserSession?.attach(browser, page, {
63
+ origin,
64
+ origins: [origin],
65
+ reinstall: () => Promise.reject(new Error("browse mode installs no Speed Kit to reinstall")),
66
+ serviceWorkers: this.serviceWorkers,
67
+ });
41
68
  this.cli.successAction("ONBOARDING:BROWSE:BROWSER");
42
69
  const navigation = await safe(page.goto(url));
43
70
  if (navigation.success !== true) {
@@ -45,13 +72,19 @@ export class BrowseService {
45
72
  }
46
73
  this.cli.writeSuccess(this.readyLine(url));
47
74
  await waitForAbort(shutdownSignal);
75
+ this.browserSession?.detach();
48
76
  await safe(browser.close());
49
77
  }
78
+ /** Feeds `sk onboarding browser state`, which reads what CDP streamed. */
79
+ trackServiceWorkers(session) {
80
+ session.on(CDP_SESSION.EVENTS.SERVICE_WORKER.REGISTRATION_UPDATED, ({ registrations, }) => this.serviceWorkers.recordRegistrations(registrations));
81
+ session.on(CDP_SESSION.EVENTS.SERVICE_WORKER.VERSION_UPDATED, ({ versions }) => this.serviceWorkers.recordVersions(versions));
82
+ }
50
83
  readyLine(url) {
51
- const { debuggingPort, headless, debugPort } = this.browserContext;
52
- const cdp = debuggingPort || headless
84
+ const { debuggingPort, debugPort } = this.browserContext;
85
+ const cdp = debuggingPort
53
86
  ? `CDP on http://127.0.0.1:${debugPort}`
54
- : "no CDP port, pass -p or --headless to expose one";
87
+ : "no CDP port, pass -p to expose one";
55
88
  return `Browsing ${url} live, without interception or Speed Kit injection; ${cdp}. Press Ctrl+C to stop.`;
56
89
  }
57
90
  async findPage(browser) {
@@ -0,0 +1,12 @@
1
+ import { Browser } from "puppeteer";
2
+ import { CliServiceInterface } from "../../cli/index.js";
3
+ /**
4
+ * Answers every JavaScript dialog of every page of `browser`, and logs it.
5
+ *
6
+ * An open alert, confirm, prompt or beforeunload dialog blocks the page's main thread. Every CDP
7
+ * call then times out, a navigation never commits, and a headless run has nobody to close it: the
8
+ * run looked alive and every tool answered CDP_TIMEOUT until a restart. A confirm and a prompt are
9
+ * cancelled, which changes nothing on the site; an alert and a beforeunload are accepted, so the
10
+ * page goes on and a navigation leaves it.
11
+ */
12
+ export declare function answerDialogs(browser: Pick<Browser, "on" | "targets">, cli: Pick<CliServiceInterface, "writeWarning">): void;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Answers every JavaScript dialog of every page of `browser`, and logs it.
3
+ *
4
+ * An open alert, confirm, prompt or beforeunload dialog blocks the page's main thread. Every CDP
5
+ * call then times out, a navigation never commits, and a headless run has nobody to close it: the
6
+ * run looked alive and every tool answered CDP_TIMEOUT until a restart. A confirm and a prompt are
7
+ * cancelled, which changes nothing on the site; an alert and a beforeunload are accepted, so the
8
+ * page goes on and a navigation leaves it.
9
+ */
10
+ export function answerDialogs(browser, cli) {
11
+ const watch = async (target) => {
12
+ const page = await target.page().catch(() => null);
13
+ page?.on("dialog", (dialog) => void answer(dialog, page, cli));
14
+ };
15
+ browser.on("targetcreated", watch);
16
+ for (const target of browser.targets())
17
+ void watch(target);
18
+ }
19
+ async function answer(dialog, page, cli) {
20
+ const type = dialog.type();
21
+ const accept = type === "alert" || type === "beforeunload";
22
+ cli.writeWarning(`the page opened a dialog (${type}: "${dialog.message().slice(0, 200)}"); ${accept ? "accepted" : "cancelled"} it, as a blocked page answers no tool`, false, { scope: "browser", data: { page: page.url(), dialog: type } });
23
+ // A dialog that a navigation already closed cannot be answered any more.
24
+ await (accept ? dialog.accept() : dialog.dismiss()).catch(() => undefined);
25
+ }
@@ -1,4 +1,4 @@
1
- import { Browser } from "puppeteer";
1
+ import { Browser, CDPSession, Protocol } from "puppeteer";
2
2
  import { BrowserContext } from "../onboarding-model.js";
3
3
  /**
4
4
  * Emulates the device of `--device` on every page and Service Worker of `browser`: the ones open
@@ -11,3 +11,14 @@ import { BrowserContext } from "../onboarding-model.js";
11
11
  * The overrides live as long as this session, which lives as long as the browser connection.
12
12
  */
13
13
  export declare function emulateDevice(browser: Browser, browserContext: BrowserContext): Promise<void>;
14
+ /**
15
+ * Calls `handle` on every target of `browser` that `filter` admits: the ones open now, and every
16
+ * one opened later. A new target waits until `handle` is done, so its first request already
17
+ * carries what `handle` set.
18
+ *
19
+ * The wait is bounded and always ends: a handle that hangs on a stopped worker must never leave a
20
+ * page or worker paused at its first line.
21
+ *
22
+ * Detach the returned session to stop; its targets' sessions, and what was set in them, go with it.
23
+ */
24
+ export declare function onEveryTarget(browser: Browser, handle: (session: CDPSession, targetInfo: Protocol.Target.TargetInfo) => Promise<void>, filter?: Protocol.Target.TargetFilter): Promise<CDPSession>;
@@ -10,19 +10,49 @@ import { safe } from "../../../helpers/safe.js";
10
10
  * The overrides live as long as this session, which lives as long as the browser connection.
11
11
  */
12
12
  export async function emulateDevice(browser, browserContext) {
13
+ await onEveryTarget(browser, (session, targetInfo) => emulateTarget(session, targetInfo, browserContext));
14
+ }
15
+ /** How long {@link onEveryTarget} holds a new target before it lets it run. */
16
+ const HOLD_MS = 4000;
17
+ /**
18
+ * Calls `handle` on every target of `browser` that `filter` admits: the ones open now, and every
19
+ * one opened later. A new target waits until `handle` is done, so its first request already
20
+ * carries what `handle` set.
21
+ *
22
+ * The wait is bounded and always ends: a handle that hangs on a stopped worker must never leave a
23
+ * page or worker paused at its first line.
24
+ *
25
+ * Detach the returned session to stop; its targets' sessions, and what was set in them, go with it.
26
+ */
27
+ export async function onEveryTarget(browser, handle, filter) {
13
28
  const session = await browser.target().createCDPSession();
14
29
  session.on("Target.attachedToTarget", (event) => {
15
30
  const target = session.connection()?.session(event.sessionId);
16
- if (target)
17
- void emulateTarget(target, event, browserContext);
31
+ if (!target)
32
+ return;
33
+ void (async () => {
34
+ let timer;
35
+ await safe(Promise.race([
36
+ handle(target, event.targetInfo),
37
+ new Promise((resolve) => {
38
+ timer = setTimeout(resolve, HOLD_MS);
39
+ timer.unref();
40
+ }),
41
+ ]).finally(() => clearTimeout(timer)));
42
+ if (event.waitingForDebugger) {
43
+ await safe(target.send("Runtime.runIfWaitingForDebugger"));
44
+ }
45
+ })();
18
46
  });
19
47
  await session.send("Target.setAutoAttach", {
20
48
  autoAttach: true,
21
49
  waitForDebuggerOnStart: true,
22
50
  flatten: true,
51
+ ...(filter ? { filter } : {}),
23
52
  });
53
+ return session;
24
54
  }
25
- async function emulateTarget(session, { targetInfo, waitingForDebugger }, browserContext) {
55
+ async function emulateTarget(session, targetInfo, browserContext) {
26
56
  // Not the DevTools window that `devtools: true` docks next to a headed page.
27
57
  const isPage = targetInfo.type === "page" && !targetInfo.url.startsWith("devtools:");
28
58
  const { userAgent, metadata } = browserContext.emulation;
@@ -44,7 +74,4 @@ async function emulateTarget(session, { targetInfo, waitingForDebugger }, browse
44
74
  configuration: "mobile",
45
75
  }));
46
76
  }
47
- if (waitingForDebugger) {
48
- await safe(session.send("Runtime.runIfWaitingForDebugger"));
49
- }
50
77
  }
@@ -1,7 +1,8 @@
1
1
  import { Browser, CDPSession } from "puppeteer";
2
2
  import { BrowserContext } from "../onboarding-model.js";
3
+ import { CliServiceInterface } from "../../cli/index.js";
3
4
  /** Launches the onboarding Chrome. Onboarding and browse mode share it, so their hardening cannot drift. */
4
- export declare function launchBrowser(browserContext: BrowserContext): Promise<Browser>;
5
+ export declare function launchBrowser(browserContext: BrowserContext, cli: Pick<CliServiceInterface, "writeWarning">): Promise<Browser>;
5
6
  /**
6
7
  * Starts from a clean state for `origin`: no service worker, no cookies, no stored data, no
7
8
  * emulation left over from an earlier session on the same profile.
@@ -1,11 +1,16 @@
1
1
  import puppeteerExtra from "puppeteer-extra";
2
2
  import { emulateDevice } from "./emulate-device.js";
3
+ import { answerDialogs } from "./answer-dialogs.js";
4
+ import { resumeRestartedWorkers } from "./resume-restarted-workers.js";
3
5
  /** Launches the onboarding Chrome. Onboarding and browse mode share it, so their hardening cannot drift. */
4
- export async function launchBrowser(browserContext) {
6
+ export async function launchBrowser(browserContext, cli) {
5
7
  const browser = await puppeteerExtra.default.launch(browserContext.getPuppeteerLaunchOptions());
8
+ // First, so that it covers the sessions the emulation opens.
9
+ await resumeRestartedWorkers(browser);
6
10
  if (browserContext.emulation) {
7
11
  await emulateDevice(browser, browserContext);
8
12
  }
13
+ answerDialogs(browser, cli);
9
14
  return browser;
10
15
  }
11
16
  /**
@@ -0,0 +1,14 @@
1
+ import { Browser } from "puppeteer";
2
+ /**
3
+ * Lets a target run again when Chrome restarts it, on every CDP session the run opens on `browser`.
4
+ *
5
+ * Chrome stops a service worker and starts it again under the same target. While a session is
6
+ * attached, Chrome holds the restarted worker at its first line and tells only the attached
7
+ * sessions, with `Inspector.targetReloadedAfterCrash`. The run keeps sessions on its workers for
8
+ * the device emulation, so nobody resumed it. An activating worker then stayed `starting`, every
9
+ * navigation in its scope waited for it, and every tool answered CDP_TIMEOUT until an outside
10
+ * client attached and resumed the worker.
11
+ *
12
+ * `Runtime.runIfWaitingForDebugger` does nothing on a target that does not wait.
13
+ */
14
+ export declare function resumeRestartedWorkers(browser: Pick<Browser, "target">): Promise<void>;