@speedkit/cli 4.37.0 → 4.38.0

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 (44) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/commands/find-pops.js +2 -2
  3. package/dist/commands/generate-pop-config.js +9 -2
  4. package/dist/commands/login.js +0 -1
  5. package/dist/helpers/origin-proxy.d.ts +2 -2
  6. package/dist/helpers/origin-proxy.js +24 -11
  7. package/dist/helpers/spec/origin-proxy.spec.js +85 -0
  8. package/dist/services/athena/athena-service-build-context.d.ts +8 -0
  9. package/dist/services/athena/athena-service-factory.d.ts +10 -0
  10. package/dist/services/athena/athena-service-factory.js +18 -2
  11. package/dist/services/athena/baqend-athena-service.d.ts +27 -0
  12. package/dist/services/athena/baqend-athena-service.js +69 -7
  13. package/dist/services/athena/error/baqend-query-error.d.ts +4 -0
  14. package/dist/services/athena/error/baqend-query-error.js +4 -0
  15. package/dist/services/athena/error/unreadable-response.d.ts +18 -0
  16. package/dist/services/athena/error/unreadable-response.js +29 -0
  17. package/dist/services/athena/index.d.ts +2 -0
  18. package/dist/services/athena/index.js +2 -0
  19. package/dist/services/athena/spec/baqend-athena-service.spec.js +84 -8
  20. package/dist/services/cli/cli-environment.d.ts +7 -0
  21. package/dist/services/cli/cli-environment.js +7 -0
  22. package/dist/services/config-api/client.js +3 -3
  23. package/dist/services/config-api/config-api-factory.d.ts +12 -1
  24. package/dist/services/config-api/config-api-factory.js +13 -3
  25. package/dist/services/config-api/ensure-login.d.ts +52 -0
  26. package/dist/services/config-api/ensure-login.js +93 -0
  27. package/dist/services/config-api/entity-manager-provider.d.ts +24 -2
  28. package/dist/services/config-api/entity-manager-provider.js +40 -6
  29. package/dist/services/config-api/error/login-error.d.ts +7 -1
  30. package/dist/services/config-api/error/login-error.js +13 -2
  31. package/dist/services/config-api/spec/ensure-login.spec.d.ts +1 -0
  32. package/dist/services/config-api/spec/ensure-login.spec.js +95 -0
  33. package/dist/services/deploy/deploy-service-build-context.d.ts +7 -0
  34. package/dist/services/deploy/deploy-service-factory.js +6 -1
  35. package/dist/services/deploy/mr/merge-request-deploy-service-factory.js +1 -0
  36. package/dist/services/document-handler-runtime/factory/document-handler-runtime-service-factory.js +4 -2
  37. package/dist/services/onboarding/onboarding-service-factory.d.ts +5 -0
  38. package/dist/services/onboarding/onboarding-service-factory.js +9 -4
  39. package/dist/services/onboarding/spec/virtual-orestes-app/crawler.spec.js +34 -1
  40. package/dist/services/pop-config/pop-config-factory.js +1 -0
  41. package/dist/services/prewarm/auto-pre-warm-factory.js +11 -1
  42. package/dist/services/query-builder/query-builder-factory.js +4 -0
  43. package/oclif.manifest.json +144 -144
  44. package/package.json +1 -1
@@ -2,25 +2,55 @@ import { expect } from "chai";
2
2
  import { describe, it } from "mocha";
3
3
  import { AthenaBucket } from "../athena-query-service.js";
4
4
  import { BaqendAthenaService } from "../baqend-athena-service.js";
5
+ import { LoginError } from "../../config-api/error/login-error.js";
6
+ import { BaqendQueryError } from "../error/baqend-query-error.js";
5
7
  const cli = {
8
+ comment: () => undefined,
6
9
  failAction: () => undefined,
7
10
  startAction: () => undefined,
8
11
  successAction: () => undefined,
9
12
  writeError: () => undefined,
10
13
  };
14
+ /** A provider whose entity manager answers every query with `executeQuery`. */
15
+ function providerRunning(executeQuery) {
16
+ return {
17
+ tryGetEntityManager: async () => ({
18
+ data: { [AthenaBucket.RumPi]: { executeQuery } },
19
+ success: true,
20
+ }),
21
+ };
22
+ }
11
23
  /** An entity manager that records the sql it was asked to run. */
12
24
  function providerCapturing(sent) {
25
+ return providerRunning(async (sql) => {
26
+ sent.push(sql);
27
+ return [];
28
+ });
29
+ }
30
+ /** A provider whose login attempt came back with `error`. */
31
+ function providerWithoutLogin(error) {
13
32
  return {
14
- getEntityManager: async () => ({
15
- [AthenaBucket.RumPi]: {
16
- executeQuery: async (sql) => {
17
- sent.push(sql);
18
- return [];
19
- },
20
- },
21
- }),
33
+ tryGetEntityManager: async () => ({ error, success: false }),
22
34
  };
23
35
  }
36
+ /** What the Baqend SDK throws when it could not read the response body. */
37
+ function unreadableResponse() {
38
+ const error = new Error("An unexpected persistent error occurred.");
39
+ error.name = "PersistentErrorConstructor";
40
+ error.cause = new Error("Response was not valid json: Unexpected end of JSON input");
41
+ return error;
42
+ }
43
+ /** The error `getResult` ends with, for a service built on `provider`. */
44
+ async function errorFrom(provider) {
45
+ const service = new BaqendAthenaService("shop-de", provider, cli);
46
+ try {
47
+ await service.getResult("select url from rum.pi", [], 60, AthenaBucket.RumPi);
48
+ }
49
+ catch (error) {
50
+ return error;
51
+ }
52
+ throw new Error("expected getResult to fail");
53
+ }
24
54
  /** The sql that reached the Baqend API for a query run under `catalog`. */
25
55
  async function sentFor(query, catalog) {
26
56
  const sent = [];
@@ -49,3 +79,49 @@ describe("BaqendAthenaService", () => {
49
79
  expect(await sentFor("select liveliness from live.rum.pi")).to.equal("select liveliness from rum.pi");
50
80
  });
51
81
  });
82
+ describe("BaqendAthenaService errors", () => {
83
+ it("should name the missing login rather than fail inside the query", async () => {
84
+ const error = await errorFrom(providerWithoutLogin("Root login is disabled."));
85
+ expect(error).to.be.instanceOf(LoginError);
86
+ expect(error.message).to.contain("shop-de");
87
+ expect(error.message).to.contain("BAQEND_TOKEN");
88
+ });
89
+ it("should say when a token was there and got refused", async () => {
90
+ // A rejected BAT needs a new token, not a first login, so the two must not
91
+ // read the same.
92
+ const error = await errorFrom(providerWithoutLogin("Illegal token."));
93
+ expect(error).to.be.instanceOf(LoginError);
94
+ expect(error.message).to.contain("Illegal token.");
95
+ });
96
+ it("should pass the server's own message on", async () => {
97
+ const error = await errorFrom(providerRunning(async () => {
98
+ throw new Error("Query on Bucket: /db/rum.Pi is not allowed.");
99
+ }));
100
+ expect(error).to.be.instanceOf(BaqendQueryError);
101
+ expect(error.message).to.contain("not allowed");
102
+ expect(error.message).to.contain("shop-de");
103
+ });
104
+ it("should blame the query when only the query fails", async () => {
105
+ // The SDK reports an unreadable response identically whatever caused it,
106
+ // so the probe is what tells the two cases apart.
107
+ const error = await errorFrom(providerRunning(async (sql) => {
108
+ if (sql === "select 1") {
109
+ return [{ x: 1 }];
110
+ }
111
+ throw unreadableResponse();
112
+ }));
113
+ expect(error).to.be.instanceOf(BaqendQueryError);
114
+ expect(error.message).to.contain("empty response");
115
+ expect(error.suggestions?.join(" ")).to.contain("--days");
116
+ });
117
+ it("should report what the probe answered when that fails too", async () => {
118
+ const error = await errorFrom(providerRunning(async (sql) => {
119
+ if (sql === "select 1") {
120
+ throw new Error("Illegal token.");
121
+ }
122
+ throw unreadableResponse();
123
+ }));
124
+ expect(error).to.be.instanceOf(BaqendQueryError);
125
+ expect(error.message).to.contain("Illegal token.");
126
+ });
127
+ });
@@ -1,6 +1,7 @@
1
1
  import { Config } from "@oclif/core";
2
2
  import { CliSettings } from "./cli-settings.js";
3
3
  import type { CliServiceInterface } from "./cli-service-model.js";
4
+ import { EntityManagerProvider } from "../config-api/entity-manager-provider.js";
4
5
  /**
5
6
  * Where a command runs: the user's settings, oclif's config and the
6
7
  * directories the CLI owns.
@@ -20,6 +21,12 @@ export declare class CliEnvironment {
20
21
  readonly settings: CliSettings;
21
22
  /** Where the extra node modules of a customer's documentHandler live. */
22
23
  readonly nodeModulesPath: string;
24
+ /**
25
+ * The Baqend sessions of this invocation. One provider per run, so a
26
+ * command whose query, deploy and asset calls all talk to the same app logs
27
+ * in once, and a login settled up front is the one every later call uses.
28
+ */
29
+ readonly entityManagerProvider: EntityManagerProvider;
23
30
  private attachedCli?;
24
31
  /**
25
32
  * Loads the settings for one invocation.
@@ -4,6 +4,7 @@ import path, { resolve } from "node:path";
4
4
  import { parseChromeFlags } from "../../helpers/chrome-flags.js";
5
5
  import { defaultSettings } from "./cli-settings.js";
6
6
  import ApplicationError from "../error-handling/error/application-error.js";
7
+ import { EntityManagerProvider } from "../config-api/entity-manager-provider.js";
7
8
  dotenv.config({ quiet: true });
8
9
  const environmentMapping = {
9
10
  chromeExtensionPaths: "CHROME_EXTENSION_PATHS",
@@ -49,6 +50,12 @@ export class CliEnvironment {
49
50
  settings = defaultSettings();
50
51
  /** Where the extra node modules of a customer's documentHandler live. */
51
52
  nodeModulesPath;
53
+ /**
54
+ * The Baqend sessions of this invocation. One provider per run, so a
55
+ * command whose query, deploy and asset calls all talk to the same app logs
56
+ * in once, and a login settled up front is the one every later call uses.
57
+ */
58
+ entityManagerProvider = new EntityManagerProvider();
52
59
  attachedCli;
53
60
  /**
54
61
  * Loads the settings for one invocation.
@@ -5,7 +5,7 @@ import { safe } from "../../helpers/safe.js";
5
5
  import { JsonResponseError } from "./error/json-response-error.js";
6
6
  import { ConnectionError } from "../error-handling/error/connection-error.js";
7
7
  import ApplicationError from "../error-handling/error/application-error.js";
8
- import { LoginError } from "./error/login-error.js";
8
+ import { isLoginFailure, loginError } from "./ensure-login.js";
9
9
  import { OrestesApiError } from "./error/orestes-api-error.js";
10
10
  const REQUEST_TIMEOUT = 10_000;
11
11
  const CONTENT_TYPE = "application/json;charset=UTF-8";
@@ -43,8 +43,8 @@ export class Client {
43
43
  if (result.errorObj instanceof RaceTimeOutError) {
44
44
  throw new ConnectionError(`Got timeout of ${REQUEST_TIMEOUT}ms while trying to connect to app ${this.app}`, ["Check you internet-connection"]);
45
45
  }
46
- if (result.error.includes("Root login is disabled")) {
47
- throw new LoginError(this.app);
46
+ if (isLoginFailure(result.error)) {
47
+ throw loginError(this.app, result.error);
48
48
  }
49
49
  throw new ConnectionError(`Could not connect to app: ${this.app} - ${result.error}`);
50
50
  }
@@ -1,9 +1,20 @@
1
1
  import { ConfigApiService } from "./config-api-service.js";
2
2
  import { ConfigApiContextInterface } from "./index.js";
3
+ import { EntityManagerProvider } from "./entity-manager-provider.js";
3
4
  export declare class ConfigApiServiceFactory {
5
+ private readonly entityManagerProvider;
4
6
  context: ConfigApiContextInterface;
5
7
  service: ConfigApiService;
6
- constructor(context: ConfigApiContextInterface);
8
+ /**
9
+ * @param entityManagerProvider - the caller's sessions, when it has them. A
10
+ * command that already logged into the app for its own reasons should not
11
+ * open a second session for the config API; a fresh one is made when there
12
+ * is nothing to share.
13
+ *
14
+ * It sits here rather than on the context because the context is the plain
15
+ * holder for the command's own inputs, and a session is a dependency.
16
+ */
17
+ constructor(context: ConfigApiContextInterface, entityManagerProvider?: EntityManagerProvider);
7
18
  getService(): ConfigApiService;
8
19
  buildService(): void;
9
20
  createLoginTokenFileIfNotExists(): void;
@@ -6,9 +6,20 @@ import os from "node:os";
6
6
  import path from "node:path";
7
7
  import ApplicationError from "../error-handling/error/application-error.js";
8
8
  export class ConfigApiServiceFactory {
9
+ entityManagerProvider;
9
10
  context;
10
11
  service = undefined;
11
- constructor(context) {
12
+ /**
13
+ * @param entityManagerProvider - the caller's sessions, when it has them. A
14
+ * command that already logged into the app for its own reasons should not
15
+ * open a second session for the config API; a fresh one is made when there
16
+ * is nothing to share.
17
+ *
18
+ * It sits here rather than on the context because the context is the plain
19
+ * holder for the command's own inputs, and a session is a dependency.
20
+ */
21
+ constructor(context, entityManagerProvider = new EntityManagerProvider()) {
22
+ this.entityManagerProvider = entityManagerProvider;
12
23
  this.context = context;
13
24
  }
14
25
  getService() {
@@ -22,8 +33,7 @@ export class ConfigApiServiceFactory {
22
33
  throw new ApplicationError("app is undefined");
23
34
  }
24
35
  this.createLoginTokenFileIfNotExists();
25
- const entityManagerProvider = new EntityManagerProvider();
26
- const client = new Client(this.context.app, entityManagerProvider);
36
+ const client = new Client(this.context.app, this.entityManagerProvider);
27
37
  this.service = new ConfigApiService(this.context.app, client);
28
38
  }
29
39
  createLoginTokenFileIfNotExists() {
@@ -0,0 +1,52 @@
1
+ import { EntityManager } from "baqend";
2
+ import { CliServiceInterface } from "../cli/index.js";
3
+ import { EntityManagerProvider } from "./entity-manager-provider.js";
4
+ import { LoginError } from "./error/login-error.js";
5
+ /**
6
+ * Whether a failed connection attempt failed over the login rather than over
7
+ * reaching the app at all.
8
+ *
9
+ * The Baqend SDK reports both through the same channel, so the caller that has
10
+ * to choose between "log in" and "check your connection" has only the message
11
+ * to go on.
12
+ */
13
+ export declare function isLoginFailure(error: string): boolean;
14
+ /**
15
+ * The error to fail with when a login could not be had, saying why.
16
+ *
17
+ * A rejected or expired token must not read as "you never logged in": the two
18
+ * need different fixes, and the token in the environment or in `~/.baqend` is
19
+ * exactly the one whose refusal the user cannot see otherwise. So anything the
20
+ * login attempt actually reported is kept, and only the "found nothing"
21
+ * placeholder is replaced by the thing it stands for.
22
+ */
23
+ export declare function loginError(app: string, reason?: string): LoginError;
24
+ /**
25
+ * Whether asking for a login here can work at all.
26
+ *
27
+ * The Baqend CLI reads the credentials from stdin, so a pipeline, a `--quiet`
28
+ * run and a CI job have nothing to answer with — there the missing login has
29
+ * to be reported instead of waited for.
30
+ */
31
+ export declare function canPromptForLogin(cli: CliServiceInterface): boolean;
32
+ /**
33
+ * A Baqend login for `app`, established *before* the work that needs one
34
+ * starts.
35
+ *
36
+ * Every command that ends up querying through the Baqend API needs a login,
37
+ * but nothing asks for one until the first request is already on its way.
38
+ * A missing one therefore surfaces as whatever the API answered to an
39
+ * unauthenticated request, halfway through a run and naming neither the app
40
+ * nor the login — which is what made a plain "you are not logged in" read as
41
+ * an Athena failure.
42
+ *
43
+ * The handling mirrors `sk onboarding`: a login that is already there — from
44
+ * `BAQEND_TOKEN`/`BAT` or from `~/.baqend` — is used silently, an interactive
45
+ * terminal is asked for one once, and anything else fails with a message that
46
+ * names the command to run.
47
+ *
48
+ * @param prompt - whether the caller allows the prompt at all. Off where the
49
+ * login is checked under a spinner or for a run without a person, which then
50
+ * fails like a non-interactive terminal does.
51
+ */
52
+ export declare function ensureBaqendLogin(app: string, entityManagerProvider: EntityManagerProvider, cli: CliServiceInterface, prompt?: boolean): Promise<EntityManager>;
@@ -0,0 +1,93 @@
1
+ import { safe } from "../../helpers/safe.js";
2
+ import { LoginError } from "./error/login-error.js";
3
+ /**
4
+ * What the Baqend CLI says when it found no credentials at all.
5
+ *
6
+ * It reports that state through its last resort rather than directly: having
7
+ * found nothing in `BAQEND_TOKEN` (or its `BAT` alias), nothing in
8
+ * `~/.baqend` and no prompt
9
+ * to fall back on, it tries a root login against the app itself and hands on
10
+ * whatever *that* answered. Both messages therefore mean "you have no
11
+ * credentials", and neither says so.
12
+ */
13
+ const NO_CREDENTIALS = /root login is disabled|login information are missing|no tty session/i;
14
+ /**
15
+ * A token that was there and got refused, as opposed to none being there. The
16
+ * two need different fixes — a new token versus a first login — so they are
17
+ * told apart rather than both reported as "not logged in".
18
+ */
19
+ const REFUSED_CREDENTIALS = /illegal token|login with baqend token failed/i;
20
+ /**
21
+ * Whether a failed connection attempt failed over the login rather than over
22
+ * reaching the app at all.
23
+ *
24
+ * The Baqend SDK reports both through the same channel, so the caller that has
25
+ * to choose between "log in" and "check your connection" has only the message
26
+ * to go on.
27
+ */
28
+ export function isLoginFailure(error) {
29
+ return NO_CREDENTIALS.test(error) || REFUSED_CREDENTIALS.test(error);
30
+ }
31
+ /**
32
+ * The error to fail with when a login could not be had, saying why.
33
+ *
34
+ * A rejected or expired token must not read as "you never logged in": the two
35
+ * need different fixes, and the token in the environment or in `~/.baqend` is
36
+ * exactly the one whose refusal the user cannot see otherwise. So anything the
37
+ * login attempt actually reported is kept, and only the "found nothing"
38
+ * placeholder is replaced by the thing it stands for.
39
+ */
40
+ export function loginError(app, reason) {
41
+ if (reason && !NO_CREDENTIALS.test(reason)) {
42
+ return new LoginError(app, reason);
43
+ }
44
+ return new LoginError(app, "no BAQEND_TOKEN in the environment and no valid token in ~/.baqend");
45
+ }
46
+ /**
47
+ * Whether asking for a login here can work at all.
48
+ *
49
+ * The Baqend CLI reads the credentials from stdin, so a pipeline, a `--quiet`
50
+ * run and a CI job have nothing to answer with — there the missing login has
51
+ * to be reported instead of waited for.
52
+ */
53
+ export function canPromptForLogin(cli) {
54
+ return Boolean(!cli.quiet &&
55
+ !process.env.CI &&
56
+ process.stdin.isTTY &&
57
+ process.stdout.isTTY);
58
+ }
59
+ /**
60
+ * A Baqend login for `app`, established *before* the work that needs one
61
+ * starts.
62
+ *
63
+ * Every command that ends up querying through the Baqend API needs a login,
64
+ * but nothing asks for one until the first request is already on its way.
65
+ * A missing one therefore surfaces as whatever the API answered to an
66
+ * unauthenticated request, halfway through a run and naming neither the app
67
+ * nor the login — which is what made a plain "you are not logged in" read as
68
+ * an Athena failure.
69
+ *
70
+ * The handling mirrors `sk onboarding`: a login that is already there — from
71
+ * `BAQEND_TOKEN`/`BAT` or from `~/.baqend` — is used silently, an interactive
72
+ * terminal is asked for one once, and anything else fails with a message that
73
+ * names the command to run.
74
+ *
75
+ * @param prompt - whether the caller allows the prompt at all. Off where the
76
+ * login is checked under a spinner or for a run without a person, which then
77
+ * fails like a non-interactive terminal does.
78
+ */
79
+ export async function ensureBaqendLogin(app, entityManagerProvider, cli, prompt = true) {
80
+ const cached = await entityManagerProvider.tryGetEntityManager(app);
81
+ if (cached.success === true) {
82
+ return cached.data;
83
+ }
84
+ if (!prompt || !canPromptForLogin(cli)) {
85
+ throw loginError(app, cached.error);
86
+ }
87
+ cli.comment(`No Baqend login for app ${app} found — logging in now.`);
88
+ const result = await safe(entityManagerProvider.getEntityManager(app));
89
+ if (result.success === true) {
90
+ return result.data;
91
+ }
92
+ throw loginError(app, result.error);
93
+ }
@@ -1,11 +1,33 @@
1
1
  import { EntityManager } from "baqend";
2
+ import { Safe } from "../../helpers/safe.js";
2
3
  /**
3
4
  * Logs in to an app once and hands out its `EntityManager` from then on.
4
5
  *
5
6
  * A connection provider, not a service factory: services receive it and ask it
6
- * for a connection at run time.
7
+ * for a connection at run time. The environment carries one per invocation, so
8
+ * a run logs in once however many collaborators talk to the app.
7
9
  */
8
10
  export declare class EntityManagerProvider {
9
- EntityManager: EntityManager;
11
+ /**
12
+ * One entity manager per app. Keyed by app because a single provider is
13
+ * handed to collaborators that may talk to more than one of them, and a
14
+ * cache that ignores the name answers the second app with the first one's
15
+ * session.
16
+ */
17
+ private readonly entityManagers;
18
+ /**
19
+ * The entity manager for `app`, logging in when none is cached yet. In an
20
+ * interactive terminal the Baqend CLI asks for the credentials here.
21
+ */
10
22
  getEntityManager(app: string): Promise<EntityManager>;
23
+ /**
24
+ * The entity manager for `app` from the credentials that are already there,
25
+ * or what went wrong reaching for them.
26
+ *
27
+ * `skipInput` suppresses only the interactive prompt — the Baqend CLI still
28
+ * reads `BAQEND_TOKEN`/`BAT` and the `~/.baqend` profile — so this answers
29
+ * "are we logged in?" for every non-interactive way of being logged in,
30
+ * rather than asking the user to be.
31
+ */
32
+ tryGetEntityManager(app: string): Promise<Safe<EntityManager>>;
11
33
  }
@@ -1,17 +1,51 @@
1
1
  import { account } from "baqend/cli";
2
+ import { safe } from "../../helpers/safe.js";
2
3
  /**
3
4
  * Logs in to an app once and hands out its `EntityManager` from then on.
4
5
  *
5
6
  * A connection provider, not a service factory: services receive it and ask it
6
- * for a connection at run time.
7
+ * for a connection at run time. The environment carries one per invocation, so
8
+ * a run logs in once however many collaborators talk to the app.
7
9
  */
8
10
  export class EntityManagerProvider {
9
- EntityManager;
11
+ /**
12
+ * One entity manager per app. Keyed by app because a single provider is
13
+ * handed to collaborators that may talk to more than one of them, and a
14
+ * cache that ignores the name answers the second app with the first one's
15
+ * session.
16
+ */
17
+ entityManagers = new Map();
18
+ /**
19
+ * The entity manager for `app`, logging in when none is cached yet. In an
20
+ * interactive terminal the Baqend CLI asks for the credentials here.
21
+ */
10
22
  async getEntityManager(app) {
11
- if (this.EntityManager) {
12
- return this.EntityManager;
23
+ const cached = this.entityManagers.get(app);
24
+ if (cached) {
25
+ return cached;
13
26
  }
14
- this.EntityManager = await account.login({ app });
15
- return this.EntityManager;
27
+ const entityManager = await account.login({ app });
28
+ this.entityManagers.set(app, entityManager);
29
+ return entityManager;
30
+ }
31
+ /**
32
+ * The entity manager for `app` from the credentials that are already there,
33
+ * or what went wrong reaching for them.
34
+ *
35
+ * `skipInput` suppresses only the interactive prompt — the Baqend CLI still
36
+ * reads `BAQEND_TOKEN`/`BAT` and the `~/.baqend` profile — so this answers
37
+ * "are we logged in?" for every non-interactive way of being logged in,
38
+ * rather than asking the user to be.
39
+ */
40
+ async tryGetEntityManager(app) {
41
+ const cached = this.entityManagers.get(app);
42
+ if (cached) {
43
+ return { data: cached, success: true };
44
+ }
45
+ const result = await safe(account.login({ app, skipInput: true }));
46
+ if (result.success === true) {
47
+ this.entityManagers.set(app, result.data);
48
+ }
49
+ return result;
16
50
  }
17
51
  }
@@ -1,5 +1,11 @@
1
1
  import ApplicationError from "../../error-handling/error/application-error.js";
2
2
  export declare class LoginError extends ApplicationError {
3
3
  readonly code = "LOGIN_ERROR";
4
- constructor(app: string);
4
+ /**
5
+ * @param app - the app the login was for. Named in the message because a
6
+ * command may talk to more than one, and in the suggestion because
7
+ * `sk login` on its own logs into `bbq`, not into the app.
8
+ * @param reason - what the login attempt answered, when there was one.
9
+ */
10
+ constructor(app: string, reason?: string);
5
11
  }
@@ -1,7 +1,18 @@
1
1
  import ApplicationError from "../../error-handling/error/application-error.js";
2
2
  export class LoginError extends ApplicationError {
3
3
  code = "LOGIN_ERROR";
4
- constructor(app) {
5
- super(`Could not login to app ${app}`, ["run sk login"]);
4
+ /**
5
+ * @param app - the app the login was for. Named in the message because a
6
+ * command may talk to more than one, and in the suggestion because
7
+ * `sk login` on its own logs into `bbq`, not into the app.
8
+ * @param reason - what the login attempt answered, when there was one.
9
+ */
10
+ constructor(app, reason) {
11
+ super(reason
12
+ ? `Could not login to app ${app}: ${reason}`
13
+ : `Could not login to app ${app}`, [
14
+ `run: sk login ${app}`,
15
+ "or pass a Baqend app token via BAQEND_TOKEN (BAT is read as well)",
16
+ ]);
6
17
  }
7
18
  }
@@ -0,0 +1,95 @@
1
+ import { expect } from "chai";
2
+ import { describe, it } from "mocha";
3
+ import { ensureBaqendLogin, isLoginFailure, loginError, } from "../ensure-login.js";
4
+ import { LoginError } from "../error/login-error.js";
5
+ /** A cli that cannot ask anything, as a piped or `--quiet` run has. */
6
+ const quietCli = {
7
+ comment: () => undefined,
8
+ quiet: true,
9
+ };
10
+ const session = { token: "a-token" };
11
+ /** A provider with a cached login, and one without. */
12
+ function provider(cached, onLogin = async () => session) {
13
+ return {
14
+ getEntityManager: onLogin,
15
+ tryGetEntityManager: async () => cached
16
+ ? { data: session, success: true }
17
+ : { error: "Root login is disabled.", success: false },
18
+ };
19
+ }
20
+ describe("ensureBaqendLogin", () => {
21
+ it("should use a login that is already there without asking", async () => {
22
+ let asked = false;
23
+ const entityManager = await ensureBaqendLogin("shop-de", provider(true, async () => {
24
+ asked = true;
25
+ return session;
26
+ }), quietCli);
27
+ expect(entityManager).to.equal(session);
28
+ expect(asked, "logged in again despite a cached session").to.equal(false);
29
+ });
30
+ it("should fail with a login error where it cannot ask for one", async () => {
31
+ // The point of the early check: a run that cannot prompt learns here that
32
+ // it has no login, rather than from whatever the API answers later on.
33
+ try {
34
+ await ensureBaqendLogin("shop-de", provider(false), quietCli);
35
+ }
36
+ catch (error) {
37
+ expect(error).to.be.instanceOf(LoginError);
38
+ expect(error.suggestions).to.contain("run: sk login shop-de");
39
+ expect(error.message).to.contain("~/.baqend");
40
+ return;
41
+ }
42
+ throw new Error("expected ensureBaqendLogin to fail");
43
+ });
44
+ it("should not ask where the caller forbids it, even in a terminal", async () => {
45
+ // A bulk deploy checks the login under a spinner: a prompt there is one
46
+ // the user cannot see.
47
+ const terminalCli = {
48
+ comment: () => undefined,
49
+ quiet: false,
50
+ };
51
+ let asked = false;
52
+ try {
53
+ await ensureBaqendLogin("shop-de", provider(false, async () => {
54
+ asked = true;
55
+ return session;
56
+ }), terminalCli, false);
57
+ }
58
+ catch (error) {
59
+ expect(error).to.be.instanceOf(LoginError);
60
+ expect(asked, "asked for a login it was told not to").to.equal(false);
61
+ return;
62
+ }
63
+ throw new Error("expected ensureBaqendLogin to fail");
64
+ });
65
+ });
66
+ describe("loginError", () => {
67
+ it("should spell out where a token was looked for when none was found", () => {
68
+ // What the Baqend CLI reports for "no credentials anywhere" is the answer
69
+ // to its root-login last resort, which names neither.
70
+ const error = loginError("shop-de", "Root login is disabled.");
71
+ expect(error.message).to.contain("BAQEND_TOKEN");
72
+ expect(error.message).to.contain("~/.baqend");
73
+ });
74
+ it("should keep what the login attempt actually reported", () => {
75
+ expect(loginError("shop-de", "Illegal token.").message).to.contain("Illegal token.");
76
+ });
77
+ });
78
+ describe("isLoginFailure", () => {
79
+ it("should recognise every way the SDK reports a login problem", () => {
80
+ // What the app answers when nothing was sent, when a stale token was, and
81
+ // when the CLI ran out of places to look.
82
+ for (const error of [
83
+ "Root login is disabled.",
84
+ "Login information are missing. Login with baqend login",
85
+ "Illegal token.",
86
+ "Login with Baqend token failed.",
87
+ ]) {
88
+ expect(isLoginFailure(error), error).to.equal(true);
89
+ }
90
+ });
91
+ it("should leave an unreachable app to the connection error", () => {
92
+ // Telling someone to log in when the host is down sends them the wrong way.
93
+ expect(isLoginFailure("getaddrinfo ENOTFOUND shop-de.app.baqend.com")).to.equal(false);
94
+ });
95
+ });
@@ -36,6 +36,13 @@ export interface DeployServiceBuildContextValues extends CommandContextValues {
36
36
  readonly skipPostDeployChecks?: boolean;
37
37
  /** Open the diff tool for a file that differs, as a person expects; the default. */
38
38
  readonly opensDiffTool?: boolean;
39
+ /**
40
+ * Whether a missing Baqend login may be asked for before the deploy starts;
41
+ * the default. Off where the deploy is built under a spinner or without a
42
+ * person, as in a bulk run: there a missing login fails the configuration
43
+ * with the command to run instead.
44
+ */
45
+ readonly promptForLogin?: boolean;
39
46
  }
40
47
  declare const DeployServiceBuildContext_base: new (values: DeployServiceBuildContextValues) => Readonly<DeployServiceBuildContextValues>;
41
48
  /** What `sk deploy` deploys: one config of one customer. */
@@ -16,6 +16,7 @@ import { DeviceDetectionChangedCheck } from "./checks/pre-deploy/device-detectio
16
16
  import { RefreshDeploymentJobCheck } from "./checks/post-deploy/refresh-deployment-job-check.js";
17
17
  import { CustomerApprovalCheck } from "./checks/activation/customer-approval-check.js";
18
18
  import { BundleServiceFactory } from "../bundler/index.js";
19
+ import { ensureBaqendLogin } from "../config-api/ensure-login.js";
19
20
  import { InteractiveDeployPolicy, } from "./policy/index.js";
20
21
  export default class DeployServiceFactory {
21
22
  context;
@@ -43,6 +44,10 @@ export default class DeployServiceFactory {
43
44
  const files = await this.getIntegrationFiles();
44
45
  const customer = files.getCustomerConfig().config;
45
46
  const configName = customer.name || this.context.configName;
47
+ // Before anything talks to the app: every handler and check below needs
48
+ // the session, and a login asked for halfway through the diffs either
49
+ // times out unseen or fails as an unreadable API error.
50
+ await ensureBaqendLogin(customer.app, this.context.environment.entityManagerProvider, cliService, this.context.promptForLogin ?? true);
46
51
  const configApi = this.getConfigApi(customer.app);
47
52
  this.files = files;
48
53
  this.configName = configName;
@@ -71,7 +76,7 @@ export default class DeployServiceFactory {
71
76
  }
72
77
  getConfigApi(app) {
73
78
  const configApiContext = new ConfigApiContext(app);
74
- return new ConfigApiServiceFactory(configApiContext).getService();
79
+ return new ConfigApiServiceFactory(configApiContext, this.context.environment.entityManagerProvider).getService();
75
80
  }
76
81
  async getIntegrationFiles() {
77
82
  const integrationApiContext = new IntegrationApiServiceBuildContext({
@@ -45,6 +45,7 @@ export class MergeRequestDeployServiceFactory {
45
45
  installFilesOnly: true,
46
46
  skipPostDeployChecks: this.context.skipPostDeployChecks,
47
47
  opensDiffTool: this.context.interactive ?? false,
48
+ promptForLogin: this.context.interactive ?? false,
48
49
  }), policy);
49
50
  const deployService = await deployFactory.buildService();
50
51
  // A deploy that runs without a person never opens a diff tool, so the