@speedkit/cli 2.62.1 → 2.64.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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,22 @@
1
+ # [2.64.0](https://gitlab.orestes.info/baqend/speed-kit-cli/compare/v2.63.0...v2.64.0) (2024-11-01)
2
+
3
+
4
+ ### Features
5
+
6
+ * **deploy:** add preDeployCheck for customVariation and customDevice ([eda9271](https://gitlab.orestes.info/baqend/speed-kit-cli/commit/eda92715c21963a97b907795fecaa06e579d5629))
7
+
8
+ # [2.63.0](https://gitlab.orestes.info/baqend/speed-kit-cli/compare/v2.62.1...v2.63.0) (2024-11-01)
9
+
10
+
11
+ ### Bug Fixes
12
+
13
+ * create dashboardEndpoint also without aws-credentials ([38ccbf9](https://gitlab.orestes.info/baqend/speed-kit-cli/commit/38ccbf9d83b9d9fc3d37cbcbe3196e1509ffdaff))
14
+
15
+
16
+ ### Features
17
+
18
+ * **onboarding:** make documentHandler errors more verbose ([cfb7e44](https://gitlab.orestes.info/baqend/speed-kit-cli/commit/cfb7e448491ae7469addfd2370167a303f381851))
19
+
1
20
  ## [2.62.1](https://gitlab.orestes.info/baqend/speed-kit-cli/compare/v2.62.0...v2.62.1) (2024-11-01)
2
21
 
3
22
 
package/README.md CHANGED
@@ -21,7 +21,7 @@ $ npm install -g @speedkit/cli
21
21
  $ sk COMMAND
22
22
  running command...
23
23
  $ sk (--version)
24
- @speedkit/cli/2.62.1 linux-x64 node-v20.18.0
24
+ @speedkit/cli/2.64.0 linux-x64 node-v20.18.0
25
25
  $ sk --help [COMMAND]
26
26
  USAGE
27
27
  $ sk COMMAND
@@ -13,10 +13,14 @@ async function safeAsync(promise) {
13
13
  return { data, success: true };
14
14
  }
15
15
  catch (error) {
16
- if (error instanceof Error) {
16
+ if (error instanceof Error || isError(error)) {
17
17
  return { success: false, error: error.message, errorObj: error };
18
18
  }
19
- return { success: false, error: "Something went wrong", errorObj: error };
19
+ return {
20
+ success: false,
21
+ error: "Something went wrong: " + error?.message,
22
+ errorObj: error,
23
+ };
20
24
  }
21
25
  }
22
26
  function safeSync(function_) {
@@ -25,9 +29,18 @@ function safeSync(function_) {
25
29
  return { data, success: true };
26
30
  }
27
31
  catch (error) {
28
- if (error instanceof Error) {
32
+ if (error instanceof Error || isError(error)) {
29
33
  return { success: false, error: error.message, errorObj: error };
30
34
  }
31
35
  return { success: false, error: "Something went wrong", errorObj: error };
32
36
  }
33
37
  }
38
+ function isError(error) {
39
+ if (!("message" in error)) {
40
+ return false;
41
+ }
42
+ if (!("stack" in error)) {
43
+ return false;
44
+ }
45
+ return true;
46
+ }
@@ -0,0 +1,18 @@
1
+ import { FileListInterface, CustomerConfig } from "../../../integration-api";
2
+ import { CliServiceInterface } from "../../../cli";
3
+ import { ConfigApiService } from "../../../config-api";
4
+ export declare class DeviceDetectionChangedCheck {
5
+ private cli;
6
+ private fileList;
7
+ private configApi;
8
+ private customerConfig;
9
+ private configName;
10
+ private isProduction;
11
+ constructor(cli: CliServiceInterface, fileList: FileListInterface, configApi: ConfigApiService, customerConfig: CustomerConfig, configName: string, isProduction: boolean);
12
+ check(): Promise<void>;
13
+ private checkForChangedDeviceDetection;
14
+ private evaluateLocalAndRemoteSpeedKit;
15
+ private getActiveInstallResource;
16
+ private buildBrowserMock;
17
+ safeFileContentWrapper(fileContent: string): string;
18
+ }
@@ -0,0 +1,189 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DeviceDetectionChangedCheck = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const cli_1 = require("../../../cli");
6
+ const files_1 = require("../../../../models/files");
7
+ const vm = tslib_1.__importStar(require("node:vm"));
8
+ const safe_1 = require("../../../../helpers/safe");
9
+ const evaluate_sk_config_error_1 = require("../../error/evaluate-sk-config-error");
10
+ class DeviceDetectionChangedCheck {
11
+ cli;
12
+ fileList;
13
+ configApi;
14
+ customerConfig;
15
+ configName;
16
+ isProduction;
17
+ constructor(cli, fileList, configApi, customerConfig, configName, isProduction) {
18
+ this.cli = cli;
19
+ this.fileList = fileList;
20
+ this.configApi = configApi;
21
+ this.customerConfig = customerConfig;
22
+ this.configName = configName;
23
+ this.isProduction = isProduction;
24
+ }
25
+ async check() {
26
+ if (
27
+ // do not check for environments other than production
28
+ !this.isProduction ||
29
+ // do not check if speedKitConfigFile is not to be deployed
30
+ !this.fileList.hasFile(files_1.INTEGRATION_FILES.CONFIG.SPEED_KIT) ||
31
+ this.fileList
32
+ .getByName(files_1.INTEGRATION_FILES.CONFIG.SPEED_KIT)
33
+ .shouldSkipFile()) {
34
+ return;
35
+ }
36
+ const activeInstallResource = await this.getActiveInstallResource();
37
+ // do not check if there is no active install resource to be updated
38
+ if (!activeInstallResource) {
39
+ return;
40
+ }
41
+ this.cli.startAction("Checking for customDeviceDetection");
42
+ const speedKitConfigFile = this.fileList.getByName(files_1.INTEGRATION_FILES.CONFIG.SPEED_KIT);
43
+ const activeSpeedKitConfig = activeInstallResource[speedKitConfigFile.remoteKey];
44
+ const changesResponse = (0, safe_1.safe)(() => {
45
+ return this.checkForChangedDeviceDetection(speedKitConfigFile, activeSpeedKitConfig);
46
+ });
47
+ if (changesResponse.success === false) {
48
+ this.cli.endAction(cli_1.CliActionStatus.FAILED);
49
+ this.cli.writeError(`Unable to evaluate changes: ${changesResponse.error}`);
50
+ return;
51
+ }
52
+ const changes = changesResponse.data.map((value) => {
53
+ return "config_SpeedKit." + value;
54
+ });
55
+ this.cli.endAction(cli_1.CliActionStatus.COMPLETED);
56
+ if (changes.length === 0) {
57
+ return;
58
+ }
59
+ // this.cli.table(changes, { origin: {}, type: {}, old: {}, new: {} });
60
+ const result = await this.cli.confirm(`Detected change in ${changes.join(" | ")}. ${this.cli.style.red("Was this checked by QA?")}`, false);
61
+ if (!result) {
62
+ this.cli.exit(0);
63
+ }
64
+ }
65
+ checkForChangedDeviceDetection(speedKitConfigFile, activeSpeedKitConfig) {
66
+ const changes = [];
67
+ const { localSpeedKit, remoteSpeedKit } = this.evaluateLocalAndRemoteSpeedKit(this.customerConfig.origins[0], speedKitConfigFile, activeSpeedKitConfig);
68
+ if ((localSpeedKit.detectDevice && !remoteSpeedKit.detectDevice) ||
69
+ (!localSpeedKit.detectDevice && remoteSpeedKit.detectDevice)) {
70
+ changes.push("detectDevice");
71
+ }
72
+ if (localSpeedKit.detectDevice &&
73
+ remoteSpeedKit.detectDevice &&
74
+ localSpeedKit.detectDevice.toString() !==
75
+ remoteSpeedKit.detectDevice.toString()) {
76
+ changes.push("detectDevice");
77
+ }
78
+ if ((localSpeedKit.customVariation && !remoteSpeedKit.customVariation) ||
79
+ (!localSpeedKit.customVariation && remoteSpeedKit.customVariation)) {
80
+ changes.push("customVariation");
81
+ }
82
+ if (localSpeedKit.customVariation && remoteSpeedKit.customVariation) {
83
+ const localFunctionsAsString = localSpeedKit.customVariation
84
+ .map((rule) => {
85
+ return rule.variationFunction.toString();
86
+ })
87
+ .join("|");
88
+ const remoteFunctionsAsString = remoteSpeedKit.customVariation
89
+ .map((rule) => {
90
+ return rule.variationFunction.toString();
91
+ })
92
+ .join("|");
93
+ if (localFunctionsAsString !== remoteFunctionsAsString) {
94
+ changes.push("customVariation");
95
+ }
96
+ }
97
+ return changes;
98
+ }
99
+ evaluateLocalAndRemoteSpeedKit(origin, speedKitConfigFile, activeSpeedKitConfig) {
100
+ const localBrowserContext = this.buildBrowserMock(origin, this.customerConfig.app);
101
+ vm.runInNewContext(this.safeFileContentWrapper(speedKitConfigFile.getContent()), localBrowserContext, {
102
+ filename: speedKitConfigFile.path,
103
+ displayErrors: false,
104
+ breakOnSigint: true,
105
+ });
106
+ const remoteBrowserContext = this.buildBrowserMock(origin, this.customerConfig.app);
107
+ vm.runInNewContext(this.safeFileContentWrapper(activeSpeedKitConfig), remoteBrowserContext, {
108
+ displayErrors: false,
109
+ breakOnSigint: true,
110
+ });
111
+ if (localBrowserContext.vmError !== null) {
112
+ throw new evaluate_sk_config_error_1.EvaluateSkConfigError(`[config_Speedkit.js] ${localBrowserContext.vmError?.message}`);
113
+ }
114
+ if (remoteBrowserContext.vmError !== null) {
115
+ throw new evaluate_sk_config_error_1.EvaluateSkConfigError(`[remote_config] ${JSON.stringify(remoteBrowserContext.vmError?.message)}`);
116
+ }
117
+ const localSpeedKit = localBrowserContext.window.speedKit;
118
+ const remoteSpeedKit = remoteBrowserContext.window.speedKit;
119
+ return { localSpeedKit, remoteSpeedKit };
120
+ }
121
+ async getActiveInstallResource() {
122
+ const activeInstallResourceResponse = await (0, safe_1.safe)(this.configApi.getActiveInstall(this.configName));
123
+ if (activeInstallResourceResponse.success !== true) {
124
+ this.cli.endAction(cli_1.CliActionStatus.FAILED);
125
+ this.cli.writeError("Could not load active install resource");
126
+ this.cli.exit(1);
127
+ return;
128
+ }
129
+ return activeInstallResourceResponse.data;
130
+ }
131
+ buildBrowserMock(origin, app) {
132
+ const originUrl = new URL(origin);
133
+ const window = {
134
+ location: originUrl,
135
+ APP: app,
136
+ speedKit: {
137
+ split: undefined,
138
+ splitTestId: undefined,
139
+ },
140
+ serviceWorkerUrl: "",
141
+ screen: { width: 0, height: 0 },
142
+ devicePixelRatio: 1,
143
+ navigator: {
144
+ userAgent: "",
145
+ connection: {},
146
+ cookieEnabled: false,
147
+ languages: [],
148
+ online: true,
149
+ },
150
+ top: {},
151
+ };
152
+ window.top = window;
153
+ const document = {
154
+ cookie: "",
155
+ querySelector: () => { },
156
+ querySelectorAll: () => { },
157
+ createElement: () => { },
158
+ addEventListener: () => { },
159
+ head: {},
160
+ body: {},
161
+ };
162
+ document.head = document;
163
+ document.body = document;
164
+ return {
165
+ vmError: null,
166
+ ...window,
167
+ window,
168
+ document,
169
+ navigator: { userAgent: "" },
170
+ localStorage: {
171
+ getItem: () => { },
172
+ setItem: () => { },
173
+ },
174
+ JSON: JSON,
175
+ decodeURIComponent: decodeURIComponent,
176
+ URL: URL,
177
+ };
178
+ }
179
+ safeFileContentWrapper(fileContent) {
180
+ return `
181
+ try{
182
+ ${fileContent}
183
+ } catch (error){
184
+ vmError = error
185
+ }
186
+ `;
187
+ }
188
+ }
189
+ exports.DeviceDetectionChangedCheck = DeviceDetectionChangedCheck;
@@ -17,6 +17,7 @@ const integration_api_1 = require("../integration-api");
17
17
  const split_change_check_1 = require("./checks/pre-deploy/split-change-check");
18
18
  const config_api_1 = require("../config-api");
19
19
  const deprecated_deployment_detection_check_1 = require("./checks/post-deploy/deprecated-deployment-detection-check");
20
+ const device_detection_changed_check_1 = require("./checks/pre-deploy/device-detection-changed-check");
20
21
  class DeployServiceFactory {
21
22
  context;
22
23
  cliConfig;
@@ -50,6 +51,7 @@ class DeployServiceFactory {
50
51
  new server_config_handler_1.default(configApi, diffService, cliService),
51
52
  ], cliService, [
52
53
  new split_change_check_1.SplitChangeCheck(cliService, files, configApi, customer, configName, this.context.isProduction),
54
+ new device_detection_changed_check_1.DeviceDetectionChangedCheck(cliService, files, configApi, customer, configName, this.context.isProduction),
53
55
  ], this.getPostDeployChecks(files, cliService, configApi, customer.app), this.context.dryRun);
54
56
  }
55
57
  getConfigApi(app) {
@@ -10,3 +10,20 @@ export type Change = {
10
10
  old: string;
11
11
  new: string;
12
12
  };
13
+ export type speedKitVariationRule = {
14
+ contentType?: string[];
15
+ host?: string[];
16
+ pathname?: Array<string | RegExp>;
17
+ url?: Array<string | RegExp>;
18
+ };
19
+ export type speedKitVariationRules = {
20
+ rules?: speedKitVariationRule;
21
+ variationFunction: (request: Request, device: string, cookies: Map<string, string>) => string;
22
+ };
23
+ export type speedKit = {
24
+ split: number;
25
+ splitTestId: string;
26
+ userAgentDetection?: boolean;
27
+ detectDevice?: (doc: Document) => string | null;
28
+ customVariation?: speedKitVariationRules[];
29
+ };
@@ -6,7 +6,6 @@ const document_handler_runtime_context_1 = require("./context/document-handler-r
6
6
  const required_file_not_found_error_1 = tslib_1.__importDefault(require("./error/required-file-not-found-error"));
7
7
  const database_mock_1 = tslib_1.__importDefault(require("./templates/database-mock"));
8
8
  const vm = tslib_1.__importStar(require("node:vm"));
9
- const vm_error_1 = require("../onboarding/error/vm-error");
10
9
  const node_path_1 = tslib_1.__importDefault(require("node:path"));
11
10
  const files_1 = require("../../models/files");
12
11
  // documentHandlerDependencies
@@ -15,6 +14,7 @@ const request_1 = require("./server/request");
15
14
  const document_handler_response_1 = require("./server/document-handler-response");
16
15
  const safe_1 = require("../../helpers/safe");
17
16
  const vm_empty_response_error_1 = require("../onboarding/error/vm-empty-response-error");
17
+ const document_handler_transform_error_1 = require("../onboarding/error/document-handler-transform-error");
18
18
  class DocumentHandlerServer {
19
19
  customerConfig;
20
20
  files;
@@ -50,6 +50,7 @@ class DocumentHandlerServer {
50
50
  CUSTOM_STYLES: this.getStyles(),
51
51
  ...this.getContextVars(),
52
52
  ...this.createNodeVmContext(),
53
+ skErrorContext: {},
53
54
  };
54
55
  const customDocumentHandlerFile = this.files.getByName(files_1.INTEGRATION_FILES.CUSTOM.DOCUMENT_HANDLER);
55
56
  if (customDocumentHandlerFile.path) {
@@ -77,10 +78,10 @@ class DocumentHandlerServer {
77
78
  }
78
79
  return vmResponse.data;
79
80
  }
80
- throw new vm_error_1.VmError(vmResponse.error + JSON.stringify(vmResponse.errorObj));
81
+ throw new document_handler_transform_error_1.DocumentHandlerTransformError(vmResponse.errorObj);
81
82
  }
82
83
  getTransformFunctionWrapper() {
83
- return `\n\npost(db, skInternalRequest, skInternalResponse).catch((err)=>{reject(err);});`;
84
+ return `\n\npost(db, skInternalRequest, skInternalResponse).catch((error)=>reject(error));`;
84
85
  }
85
86
  async buildDocumentHandler() {
86
87
  this.documentHandlerCode = await this.getDocumentHandler();
@@ -1,10 +1,12 @@
1
1
  import { DiffService } from "../../diff";
2
2
  import { DocumentHandlerServer } from "../../document-handler-runtime/document-handler-server";
3
3
  import { Crawler } from "../virtual-orestes-app/crawler";
4
+ import { CliService } from "../../cli";
4
5
  export declare class DiffAgainstCurrentPage {
5
6
  private diffService;
6
7
  private documentHandlerRuntime;
7
8
  private crawler;
8
- constructor(diffService: DiffService, documentHandlerRuntime: DocumentHandlerServer, crawler: Crawler);
9
+ private cli;
10
+ constructor(diffService: DiffService, documentHandlerRuntime: DocumentHandlerServer, crawler: Crawler, cli: CliService);
9
11
  postDiff(currentHtml: string, currentUrl: string, variant?: string, transform?: boolean): Promise<boolean>;
10
12
  }
@@ -1,21 +1,29 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DiffAgainstCurrentPage = void 0;
4
+ const cli_1 = require("../../cli");
4
5
  class DiffAgainstCurrentPage {
5
6
  diffService;
6
7
  documentHandlerRuntime;
7
8
  crawler;
8
- constructor(diffService, documentHandlerRuntime, crawler) {
9
+ cli;
10
+ constructor(diffService, documentHandlerRuntime, crawler, cli) {
9
11
  this.diffService = diffService;
10
12
  this.documentHandlerRuntime = documentHandlerRuntime;
11
13
  this.crawler = crawler;
14
+ this.cli = cli;
12
15
  }
13
16
  async postDiff(currentHtml, currentUrl, variant = "DEFAULT", transform = false) {
17
+ this.cli.writeWarning(`received diff for url: ${currentUrl}`);
18
+ this.cli.startAction(`fetch remote`);
14
19
  const originResponse = await this.crawler.fetchRemote(currentUrl, variant.toUpperCase());
15
20
  let originHtml = await originResponse?.text();
16
21
  if (!originHtml) {
22
+ this.cli.endAction(cli_1.CliActionStatus.FAILED);
17
23
  throw new Error("Could not fetch remote page");
18
24
  }
25
+ this.cli.endAction(cli_1.CliActionStatus.COMPLETED);
26
+ this.cli.startAction(`transform documents`);
19
27
  if (transform) {
20
28
  // todo check if the currentHTML is already transformed
21
29
  const currentDocumentHandlerResponse = await this.documentHandlerRuntime.transform(currentHtml, variant, currentUrl, {});
@@ -23,6 +31,7 @@ class DiffAgainstCurrentPage {
23
31
  const originDocumentHandlerResponse = await this.documentHandlerRuntime.transform(originHtml, variant, currentUrl, {});
24
32
  originHtml = originDocumentHandlerResponse.body;
25
33
  }
34
+ this.cli.endAction(cli_1.CliActionStatus.COMPLETED);
26
35
  const remoteFilePath = await this.diffService.writeContentToTemporalFile(`remote-${variant}`, originHtml);
27
36
  const localFilePath = await this.diffService.writeContentToTemporalFile("current", currentHtml);
28
37
  return await this.diffService.executeDiff(localFilePath, remoteFilePath);
@@ -0,0 +1,3 @@
1
+ export declare class DocumentHandlerTransformError extends Error {
2
+ constructor(error: Error);
3
+ }
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DocumentHandlerTransformError = void 0;
4
+ class DocumentHandlerTransformError extends Error {
5
+ constructor(error) {
6
+ super(error.message);
7
+ this.stack = error.stack;
8
+ this.cause = error.cause;
9
+ }
10
+ }
11
+ exports.DocumentHandlerTransformError = DocumentHandlerTransformError;
@@ -124,14 +124,12 @@ class OnboardingServiceFactory {
124
124
  new speed_kit_install_js_1.SpeedKitInstallJs(customerConfig, files.getByName(files_1.INTEGRATION_FILES.BUILD.INSTALL)),
125
125
  new customer_service_worker_js_1.CustomerServiceWorkerJs(customerConfig),
126
126
  new speed_kit_service_worker_js_1.SpeedKitServiceWorkerJs(customerConfig, files.getByName(files_1.INTEGRATION_FILES.CUSTOM.SW)),
127
+ new dashboard_request_1.DashboardRequest(new dashboard_1.Dashboard(customerConfig, parameterQueryBuilder, athenaClient, requestDiffService, new diff_against_current_page_1.DiffAgainstCurrentPage(DiffService, documentHandler, crawler, cli), cache)),
127
128
  ];
128
129
  if (this.context.local) {
129
130
  const orestesApp = new virtual_orestes_app_1.VirtualOrestesApp(customerConfig, crawler, documentHandler, cache, cli);
130
131
  handlers.push(new speed_kit_asset_request_1.SpeedKitAssetRequest(customerConfig, orestesApp), new speed_kit_rum_pi_request_1.SpeedKitRumPiRequest(customerConfig, cache, cli));
131
132
  }
132
- if (athenaClient) {
133
- handlers.push(new dashboard_request_1.DashboardRequest(new dashboard_1.Dashboard(customerConfig, parameterQueryBuilder, athenaClient, requestDiffService, new diff_against_current_page_1.DiffAgainstCurrentPage(DiffService, documentHandler, crawler), cache)));
134
- }
135
133
  return new fetch_event_handler_1.FetchEventHandler(handlers, customerConfig, cli, configApi);
136
134
  }
137
135
  async getSpeedKitServerConfig(configApi, cli) {
@@ -79,12 +79,10 @@ class VirtualOrestesApp {
79
79
  return baqendResponse;
80
80
  }
81
81
  returnErrorResponse(customResponse, customHeaders) {
82
- let message = `could not transform html - ${customResponse.error}`;
83
- if (customResponse.errorObj) {
84
- message = customResponse.errorObj.message;
85
- }
86
- this.cli.writeError(message);
87
- this.cli.writeError(JSON.stringify(customResponse.errorObj));
82
+ const message = `Could not transform html: - ${customResponse.error}`;
83
+ this.cli.writeError(`[VirtualOrestes]: ${message}`);
84
+ this.cli.comment(customResponse.errorObj.stack);
85
+ this.cli.writeWarning("Suggestion: check files: config_documentHandler.es6 | custom_documentHandler.js");
88
86
  customHeaders.push({ name: "x-error", value: message });
89
87
  return new baqend_response_1.BaqendResponse(message, null, customHeaders, 500);
90
88
  }
@@ -712,5 +712,5 @@
712
712
  ]
713
713
  }
714
714
  },
715
- "version": "2.62.1"
715
+ "version": "2.64.0"
716
716
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@speedkit/cli",
3
3
  "description": "Speed Kit CLI",
4
- "version": "2.62.1",
4
+ "version": "2.64.0",
5
5
  "author": {
6
6
  "name": "Baqend.com",
7
7
  "email": "info@baqend.com"