@speedkit/cli 4.43.0 → 4.44.0-beta.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 (29) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/services/bundler/bundle-service-factory.d.ts +3 -0
  3. package/dist/services/bundler/bundle-service-factory.js +5 -1
  4. package/dist/services/bundler/bundle-service.d.ts +10 -1
  5. package/dist/services/bundler/bundle-service.js +16 -1
  6. package/dist/services/bundler/error/packjockel-error.d.ts +3 -0
  7. package/dist/services/bundler/error/packjockel-error.js +3 -0
  8. package/dist/services/bundler/index.d.ts +1 -0
  9. package/dist/services/bundler/index.js +1 -0
  10. package/dist/services/bundler/packjockel-service.d.ts +72 -0
  11. package/dist/services/bundler/packjockel-service.js +156 -0
  12. package/dist/services/bundler/spec/packjockel-service.spec.d.ts +1 -0
  13. package/dist/services/bundler/spec/packjockel-service.spec.js +143 -0
  14. package/dist/services/deploy/checks/activation/customer-approval-check.js +1 -1
  15. package/dist/services/deploy/checks/pre-deploy/device-detection-changed-check.js +2 -3
  16. package/dist/services/deploy/checks/pre-deploy/split-change-check.js +2 -3
  17. package/dist/services/document-handler-runtime/document-handler-server.d.ts +17 -0
  18. package/dist/services/document-handler-runtime/document-handler-server.js +81 -19
  19. package/dist/services/integration-api/integration-api-model.d.ts +2 -1
  20. package/dist/services/integration-api/spec/speed-kit-config-file.spec.js +68 -8
  21. package/dist/services/integration-api/struct/customer-config.d.ts +32 -1
  22. package/dist/services/integration-api/struct/customer-config.js +33 -3
  23. package/dist/services/integration-api/struct/speed-kit-config-file.d.ts +9 -4
  24. package/dist/services/integration-api/struct/speed-kit-config-file.js +27 -10
  25. package/dist/services/onboarding/config-renderer/speed-kit-install-context.js +20 -8
  26. package/dist/services/onboarding/templates/install-speed-kit-js-template.js +5 -0
  27. package/dist/services/query-builder/query-builder-factory.js +3 -3
  28. package/oclif.manifest.json +1 -1
  29. package/package.json +2 -1
package/CHANGELOG.md CHANGED
@@ -1,3 +1,17 @@
1
+ # [4.44.0-beta.2](https://gitlab.orestes.info/baqend/speed-kit-cli/compare/v4.44.0-beta.1...v4.44.0-beta.2) (2026-10-09)
2
+
3
+
4
+ ### Features
5
+
6
+ * **bundler:** follow packjockel 3.0.0 and run it through binaryPath() ([200ae27](https://gitlab.orestes.info/baqend/speed-kit-cli/commit/200ae276087eee79d4791652ff712eb0cd0237fb))
7
+
8
+ # [4.44.0-beta.1](https://gitlab.orestes.info/baqend/speed-kit-cli/compare/v4.43.0...v4.44.0-beta.1) (2026-10-09)
9
+
10
+
11
+ ### Features
12
+
13
+ * bundle with packjockel for customers with the configPlugins feature ([0a4108b](https://gitlab.orestes.info/baqend/speed-kit-cli/commit/0a4108bd3d3c3df6827a2ddf7db94e758e4a6702))
14
+
1
15
  # [4.43.0](https://gitlab.orestes.info/baqend/speed-kit-cli/compare/v4.42.0...v4.43.0) (2026-10-09)
2
16
 
3
17
 
@@ -1,6 +1,9 @@
1
1
  import { BundleService } from "./bundle-service.js";
2
2
  export declare class BundleServiceFactory {
3
3
  private customerFolder?;
4
+ /**
5
+ * @param customerFolder the directory bundled code resolves its own imports from
6
+ */
4
7
  constructor(customerFolder?: string);
5
8
  buildService(): BundleService;
6
9
  }
@@ -1,10 +1,14 @@
1
1
  import { BundleService } from "./bundle-service.js";
2
+ import { PackjockelService } from "./packjockel-service.js";
2
3
  export class BundleServiceFactory {
3
4
  customerFolder;
5
+ /**
6
+ * @param customerFolder the directory bundled code resolves its own imports from
7
+ */
4
8
  constructor(customerFolder) {
5
9
  this.customerFolder = customerFolder;
6
10
  }
7
11
  buildService() {
8
- return new BundleService(this.customerFolder);
12
+ return new BundleService(this.customerFolder, new PackjockelService());
9
13
  }
10
14
  }
@@ -1,4 +1,5 @@
1
1
  import { PluginBuild, LogLevel } from "esbuild";
2
+ import type { PackjockelService } from "./packjockel-service.js";
2
3
  export type BundleEntryPoints = Record<string, string>;
3
4
  export type BundleBasePaths = Record<string, string>;
4
5
  /**
@@ -8,10 +9,18 @@ export type BundleBasePaths = Record<string, string>;
8
9
  export type BundleResolveFallback = (specifier: string) => Promise<string | null>;
9
10
  export declare class BundleService {
10
11
  private moduleDiscoveryDir;
12
+ private readonly packjockelService?;
11
13
  /**
12
14
  * @param moduleDiscoveryDir the directory bundled code resolves its own imports from
15
+ * @param packjockelService bundles instead of esbuild for customers with the `configPlugins` feature
13
16
  */
14
- constructor(moduleDiscoveryDir: string);
17
+ constructor(moduleDiscoveryDir: string, packjockelService?: PackjockelService);
18
+ /**
19
+ * The packjockel bundler for customers with the `configPlugins` feature.
20
+ *
21
+ * @throws ApplicationError when the service was built without one
22
+ */
23
+ get packjockel(): PackjockelService;
15
24
  bundle({ entryPoints, basePaths, define, target, minify, logLevel, alias, platform, resolveFallback, packages, }: {
16
25
  entryPoints: BundleEntryPoints;
17
26
  basePaths?: BundleBasePaths;
@@ -4,16 +4,31 @@ import { URL } from "node:url";
4
4
  import { BundleResolveError } from "./error/bundle-resolve-error.js";
5
5
  import { BundleFetchError } from "./error/bundle-fetch-error.js";
6
6
  import { resolve } from "node:path";
7
+ import ApplicationError from "../error-handling/error/application-error.js";
7
8
  const FALLBACK_NAMESPACE = "bundle-resolve-fallback";
8
9
  const RELATIVE_SPECIFIER = /^\.{1,2}\//;
9
10
  const importCache = {};
10
11
  export class BundleService {
11
12
  moduleDiscoveryDir;
13
+ packjockelService;
12
14
  /**
13
15
  * @param moduleDiscoveryDir the directory bundled code resolves its own imports from
16
+ * @param packjockelService bundles instead of esbuild for customers with the `configPlugins` feature
14
17
  */
15
- constructor(moduleDiscoveryDir) {
18
+ constructor(moduleDiscoveryDir, packjockelService) {
16
19
  this.moduleDiscoveryDir = moduleDiscoveryDir;
20
+ this.packjockelService = packjockelService;
21
+ }
22
+ /**
23
+ * The packjockel bundler for customers with the `configPlugins` feature.
24
+ *
25
+ * @throws ApplicationError when the service was built without one
26
+ */
27
+ get packjockel() {
28
+ if (!this.packjockelService) {
29
+ throw new ApplicationError("This bundler has no packjockel");
30
+ }
31
+ return this.packjockelService;
17
32
  }
18
33
  async bundle({ entryPoints, basePaths, define, target = "es5", minify = true, logLevel = "silent", alias = {}, platform, resolveFallback, packages = "bundle", }) {
19
34
  const plugins = [];
@@ -0,0 +1,3 @@
1
+ import ApplicationError from "../../error-handling/error/application-error.js";
2
+ export declare class PackjockelError extends ApplicationError {
3
+ }
@@ -0,0 +1,3 @@
1
+ import ApplicationError from "../../error-handling/error/application-error.js";
2
+ export class PackjockelError extends ApplicationError {
3
+ }
@@ -1,2 +1,3 @@
1
1
  export * from "./bundle-service-factory.js";
2
2
  export * from "./bundle-service.js";
3
+ export * from "./packjockel-service.js";
@@ -1,2 +1,3 @@
1
1
  export * from "./bundle-service-factory.js";
2
2
  export * from "./bundle-service.js";
3
+ export * from "./packjockel-service.js";
@@ -0,0 +1,72 @@
1
+ /**
2
+ * The tags of the Speed Kit assets that packjockel bundles, each a version such as `1.8.0` or a channel
3
+ * such as `@release`. packjockel takes `latest` for a tag that is not set. The names are the client
4
+ * config keys of packjockel.
5
+ */
6
+ export interface AssetVersions {
7
+ /** Speed Kit: snippet, service worker and dynamic fetcher */
8
+ speedKitVersion?: string;
9
+ rumPluginVersion?: string;
10
+ /** predictive preloading */
11
+ ppVersion?: string;
12
+ configPluginsVersion?: string;
13
+ documentHandlerVersion?: string;
14
+ }
15
+ export interface PackjockelBundleRequest {
16
+ /** The entry points by file name, in output order. */
17
+ entryPoints: Record<string, string>;
18
+ versions?: AssetVersions;
19
+ define?: Record<string, string>;
20
+ platform?: "browser" | "node";
21
+ target?: "es5" | "es6";
22
+ minify?: boolean;
23
+ }
24
+ export interface PackjockelDocumentHandlerRequest {
25
+ /** The document handler library; without it packjockel bundles the published one of `documentHandlerVersion`. */
26
+ documentHandler?: string;
27
+ documentHandlerConfig: string;
28
+ speedKitConfig: string;
29
+ appName: string;
30
+ dynamicFetcher?: string;
31
+ dynamicFetcherConfig?: string;
32
+ customStyle?: string;
33
+ versions?: AssetVersions;
34
+ }
35
+ /**
36
+ * Bundles with the packjockel binary in embedded mode, so no packjockel server is needed.
37
+ *
38
+ * Every input goes to the binary as a file, because a document handler is too large for one
39
+ * command line argument.
40
+ */
41
+ export declare class PackjockelService {
42
+ private readonly resolveBinary;
43
+ /**
44
+ * @param resolveBinary returns the packjockel binary; it runs only when a bundle is needed, so
45
+ * a platform without a packjockel package fails only for the `configPlugins` feature
46
+ */
47
+ constructor(resolveBinary?: () => string);
48
+ /**
49
+ * Bundles the entry points in their order into one script. packjockel puts a script before them
50
+ * which exposes the `SpeedKit` global.
51
+ *
52
+ * @returns the bundled code
53
+ */
54
+ bundle(request: PackjockelBundleRequest): Promise<string>;
55
+ /**
56
+ * Bundles a document handler with its config, the embedded Speed Kit config and the default `post`.
57
+ *
58
+ * @returns the code of one CommonJS module, which exports `post`
59
+ */
60
+ bundleDocumentHandler(request: PackjockelDocumentHandlerRequest): Promise<string>;
61
+ /**
62
+ * Runs packjockel in a scratch directory, which is removed afterwards.
63
+ *
64
+ * @param buildArgs writes the inputs into the directory and returns the arguments that read them
65
+ */
66
+ private run;
67
+ /**
68
+ * Runs the binary without stdin: packjockel reads a piped stdin as the document handler, and only
69
+ * without input it bundles the published one.
70
+ */
71
+ private execute;
72
+ }
@@ -0,0 +1,156 @@
1
+ import { spawn } from "node:child_process";
2
+ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { binaryPath } from "@speedkit/packjockel";
6
+ import { PackjockelError } from "./error/packjockel-error.js";
7
+ const VERSION_FLAGS = {
8
+ speedKitVersion: "--speed-kit-version",
9
+ rumPluginVersion: "--rum-plugin-version",
10
+ ppVersion: "--pp-version",
11
+ configPluginsVersion: "--config-plugins-version",
12
+ documentHandlerVersion: "--document-handler-version",
13
+ };
14
+ /**
15
+ * Bundles with the packjockel binary in embedded mode, so no packjockel server is needed.
16
+ *
17
+ * Every input goes to the binary as a file, because a document handler is too large for one
18
+ * command line argument.
19
+ */
20
+ export class PackjockelService {
21
+ resolveBinary;
22
+ /**
23
+ * @param resolveBinary returns the packjockel binary; it runs only when a bundle is needed, so
24
+ * a platform without a packjockel package fails only for the `configPlugins` feature
25
+ */
26
+ constructor(resolveBinary = binaryPath) {
27
+ this.resolveBinary = resolveBinary;
28
+ }
29
+ /**
30
+ * Bundles the entry points in their order into one script. packjockel puts a script before them
31
+ * which exposes the `SpeedKit` global.
32
+ *
33
+ * @returns the bundled code
34
+ */
35
+ async bundle(request) {
36
+ return this.run(async (directory) => {
37
+ const args = [
38
+ "bundle",
39
+ "--bundle",
40
+ `--platform=${request.platform ?? "browser"}`,
41
+ `--target=${request.target ?? "es5"}`,
42
+ ];
43
+ if (request.minify) {
44
+ args.push("--minify");
45
+ }
46
+ args.push(...keyValueFlags("--define", request.define));
47
+ for (const [name, code] of Object.entries(request.entryPoints)) {
48
+ args.push(await writeInput(directory, name, code));
49
+ }
50
+ return args;
51
+ }, request.versions);
52
+ }
53
+ /**
54
+ * Bundles a document handler with its config, the embedded Speed Kit config and the default `post`.
55
+ *
56
+ * @returns the code of one CommonJS module, which exports `post`
57
+ */
58
+ async bundleDocumentHandler(request) {
59
+ return this.run(async (directory) => {
60
+ const args = ["bundle", "document-handler"];
61
+ if (request.documentHandler !== undefined) {
62
+ args.push(await writeInput(directory, "DocumentHandler.js", request.documentHandler));
63
+ }
64
+ args.push(`--document-handler-config=${await writeInput(directory, "documentHandlerConfig.js", request.documentHandlerConfig)}`, `--speed-kit-config=${await writeInput(directory, "speedKitConfig.js", request.speedKitConfig)}`, `--app-name=${request.appName}`);
65
+ const optional = {
66
+ "dynamic-fetcher": ["dynamicFetcher.js", request.dynamicFetcher],
67
+ "dynamic-fetcher-config": [
68
+ "dynamicFetcherConfig.js",
69
+ request.dynamicFetcherConfig,
70
+ ],
71
+ "custom-style": ["customStyle.css", request.customStyle],
72
+ };
73
+ for (const [flag, [name, value]] of Object.entries(optional)) {
74
+ if (value) {
75
+ args.push(`--${flag}=${await writeInput(directory, name, value)}`);
76
+ }
77
+ }
78
+ return args;
79
+ }, request.versions);
80
+ }
81
+ /**
82
+ * Runs packjockel in a scratch directory, which is removed afterwards.
83
+ *
84
+ * @param buildArgs writes the inputs into the directory and returns the arguments that read them
85
+ */
86
+ async run(buildArgs, versions = {}) {
87
+ const directory = await mkdtemp(join(tmpdir(), "sk-packjockel-"));
88
+ try {
89
+ const output = join(directory, "out.js");
90
+ const args = [
91
+ ...(await buildArgs(directory)),
92
+ ...versionFlags(versions),
93
+ "--embedded",
94
+ `--output=${output}`,
95
+ ];
96
+ await this.execute(args);
97
+ return await readFile(output, "utf8");
98
+ }
99
+ finally {
100
+ await rm(directory, { recursive: true, force: true });
101
+ }
102
+ }
103
+ /**
104
+ * Runs the binary without stdin: packjockel reads a piped stdin as the document handler, and only
105
+ * without input it bundles the published one.
106
+ */
107
+ execute(args) {
108
+ let binary;
109
+ try {
110
+ binary = this.resolveBinary();
111
+ }
112
+ catch (error) {
113
+ return Promise.reject(new PackjockelError(error.message));
114
+ }
115
+ return new Promise((resolve, reject) => {
116
+ const child = spawn(binary, args, {
117
+ stdio: ["ignore", "ignore", "pipe"],
118
+ });
119
+ let stderr = "";
120
+ child.stderr.on("data", (chunk) => (stderr += chunk));
121
+ child.on("error", (error) => reject(new PackjockelError(`packjockel failed: ${error.message}`)));
122
+ child.on("close", (code) => {
123
+ if (code === 0) {
124
+ resolve();
125
+ }
126
+ else {
127
+ reject(new PackjockelError(`packjockel failed: ${withoutLogLines(stderr) || `exit code ${code}`}`));
128
+ }
129
+ });
130
+ });
131
+ }
132
+ }
133
+ /** Writes one input into the scratch directory and returns the `file://` value that reads it. */
134
+ async function writeInput(directory, name, content) {
135
+ const path = join(directory, name);
136
+ await writeFile(path, content);
137
+ return `file://${path}`;
138
+ }
139
+ /** The flags of the tags that are set. */
140
+ function versionFlags(versions) {
141
+ return Object.entries(VERSION_FLAGS)
142
+ .filter(([key]) => versions[key])
143
+ .map(([key, flag]) => `${flag}=${versions[key]}`);
144
+ }
145
+ function keyValueFlags(flag, values = {}) {
146
+ return Object.entries(values).map(([key, value]) => `${flag}=${key}=${value}`);
147
+ }
148
+ /** packjockel and its cache log to stderr as well; the error is in the remaining lines. */
149
+ function withoutLogLines(stderr = "") {
150
+ return stderr
151
+ .split("\n")
152
+ .filter((line) => line.trim() &&
153
+ !line.startsWith("time=") &&
154
+ !/^\d{4}\/\d{2}\/\d{2} /.test(line))
155
+ .join("\n");
156
+ }
@@ -0,0 +1,143 @@
1
+ import { expect } from "chai";
2
+ import { afterEach, beforeEach, describe, it } from "mocha";
3
+ import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
4
+ import { existsSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { PackjockelService } from "../packjockel-service.js";
8
+ import { PackjockelError } from "../error/packjockel-error.js";
9
+ /**
10
+ * A packjockel stand-in: it records its arguments, the content of every `file://` input and a
11
+ * piped stdin, and writes a fixed bundle to `--output`.
12
+ */
13
+ const FAKE_PACKJOCKEL = `#!/bin/sh
14
+ if [ -p /dev/stdin ] || [ -f /dev/stdin ]; then
15
+ echo "piped" > "$RECORD_DIR/stdin"
16
+ fi
17
+ out=""
18
+ for arg in "$@"; do
19
+ echo "$arg" >> "$RECORD_DIR/args"
20
+ case "$arg" in
21
+ --output=*) out="\${arg#--output=}" ;;
22
+ esac
23
+ path=$(echo "$arg" | sed -n 's|.*file://||p')
24
+ if [ -n "$path" ]; then
25
+ echo "$(basename "$path"): $(cat "$path")" >> "$RECORD_DIR/inputs"
26
+ fi
27
+ done
28
+ if [ -n "$FAIL" ]; then
29
+ echo "time=\\"2026\\" level=info msg=starting" >&2
30
+ echo "invalid bundle: could not resolve x" >&2
31
+ exit 1
32
+ fi
33
+ echo "bundled" > "$out"
34
+ `;
35
+ describe("PackjockelService", () => {
36
+ let directory;
37
+ let service;
38
+ beforeEach(async () => {
39
+ directory = await mkdtemp(join(tmpdir(), "packjockel-spec-"));
40
+ const binary = join(directory, "packjockel");
41
+ await writeFile(binary, FAKE_PACKJOCKEL);
42
+ await chmod(binary, 0o755);
43
+ process.env.RECORD_DIR = directory;
44
+ service = new PackjockelService(() => binary);
45
+ });
46
+ afterEach(async () => {
47
+ delete process.env.RECORD_DIR;
48
+ delete process.env.FAIL;
49
+ await rm(directory, { recursive: true, force: true });
50
+ });
51
+ async function recorded() {
52
+ const args = (await readFile(join(directory, "args"), "utf8"))
53
+ .trim()
54
+ .split("\n");
55
+ const inputs = (await readFile(join(directory, "inputs"), "utf8"))
56
+ .trim()
57
+ .split("\n");
58
+ return { args, inputs };
59
+ }
60
+ it("should bundle the entry points in their order", async () => {
61
+ const bundle = await service.bundle({
62
+ entryPoints: { "rum.js": "rum()", "config.js": "SpeedKit.config = {}" },
63
+ versions: { configPluginsVersion: "@release", rumPluginVersion: "" },
64
+ define: { APP: '"shop"' },
65
+ platform: "browser",
66
+ });
67
+ const { args, inputs } = await recorded();
68
+ expect(bundle.trim()).to.equal("bundled");
69
+ expect(args.slice(0, 5)).to.deep.equal([
70
+ "bundle",
71
+ "--bundle",
72
+ "--platform=browser",
73
+ "--target=es5",
74
+ '--define=APP="shop"',
75
+ ]);
76
+ expect(args).to.include("--config-plugins-version=@release");
77
+ expect(args.filter((arg) => arg.endsWith("-version=")), "a tag that is not set is left to packjockel").to.deep.equal([]);
78
+ expect(args).to.include("--embedded");
79
+ expect(inputs).to.deep.equal([
80
+ "rum.js: rum()",
81
+ "config.js: SpeedKit.config = {}",
82
+ ]);
83
+ });
84
+ it("should bundle a document handler with every input it got", async () => {
85
+ await service.bundleDocumentHandler({
86
+ documentHandler: "var DocumentHandler = 1",
87
+ documentHandlerConfig: "export default new DocumentHandler()",
88
+ speedKitConfig: "SpeedKit.config = {}",
89
+ appName: "shop",
90
+ dynamicFetcherConfig: "window.dynamicBlockConfig = {}",
91
+ });
92
+ const { args, inputs } = await recorded();
93
+ expect(args.slice(0, 2)).to.deep.equal(["bundle", "document-handler"]);
94
+ expect(args).to.include("--app-name=shop");
95
+ expect(args.some((arg) => arg.startsWith("--dynamic-fetcher="))).to.equal(false);
96
+ expect(inputs).to.deep.equal([
97
+ "DocumentHandler.js: var DocumentHandler = 1",
98
+ "documentHandlerConfig.js: export default new DocumentHandler()",
99
+ "speedKitConfig.js: SpeedKit.config = {}",
100
+ "dynamicFetcherConfig.js: window.dynamicBlockConfig = {}",
101
+ ]);
102
+ });
103
+ it("should leave the document handler to packjockel without one", async () => {
104
+ await service.bundleDocumentHandler({
105
+ documentHandlerConfig: "export default new DomDocumentHandler()",
106
+ speedKitConfig: "SpeedKit.config = {}",
107
+ appName: "shop",
108
+ versions: {
109
+ documentHandlerVersion: "1.8.0",
110
+ speedKitVersion: "2.22.4",
111
+ rumPluginVersion: "@release",
112
+ },
113
+ });
114
+ const { args, inputs } = await recorded();
115
+ expect(args.slice(0, 2)).to.deep.equal(["bundle", "document-handler"]);
116
+ expect(args[2], "no handler argument").to.match(/^--document-handler-config=/);
117
+ expect(args).to.include("--document-handler-version=1.8.0");
118
+ expect(args).to.include("--speed-kit-version=2.22.4");
119
+ expect(args).to.include("--rum-plugin-version=@release");
120
+ expect(existsSync(join(directory, "stdin")), "packjockel reads a piped stdin as the handler").to.equal(false);
121
+ expect(inputs).to.deep.equal([
122
+ "documentHandlerConfig.js: export default new DomDocumentHandler()",
123
+ "speedKitConfig.js: SpeedKit.config = {}",
124
+ ]);
125
+ });
126
+ it("should report the error of packjockel without its log lines", async () => {
127
+ process.env.FAIL = "1";
128
+ const failure = await service
129
+ .bundle({ entryPoints: { "config.js": "x" } })
130
+ .catch((error) => error);
131
+ expect(failure).to.be.instanceOf(PackjockelError);
132
+ expect(failure.message).to.equal("packjockel failed: invalid bundle: could not resolve x");
133
+ });
134
+ it("should report a platform without a packjockel package", async () => {
135
+ const failure = await new PackjockelService(() => {
136
+ throw new Error("packjockel: @speedkit/packjockel-aix-ppc64 is not installed.");
137
+ })
138
+ .bundle({ entryPoints: { "config.js": "x" } })
139
+ .catch((error) => error);
140
+ expect(failure).to.be.instanceOf(PackjockelError);
141
+ expect(failure.message).to.contain("is not installed");
142
+ });
143
+ });
@@ -50,7 +50,7 @@ export class CustomerApprovalCheck {
50
50
  const configFile = await VirtualSpeedKitConfigFile.createRemote(speedKitConfig, this.bundler);
51
51
  const splits = [];
52
52
  for (const origin of this.customer.origins) {
53
- const result = await safe(configFile.evaluate(this.customer.app, origin));
53
+ const result = await safe(configFile.evaluate(this.customer, origin));
54
54
  if (result.success === false) {
55
55
  // An unreadable config is not proof that the split is 0, so keep the
56
56
  // approval question rather than skipping it.
@@ -61,11 +61,10 @@ export class DeviceDetectionChangedCheck {
61
61
  }
62
62
  async checkForChangedDeviceDetection(speedKitConfigFile, activeSpeedKitConfig) {
63
63
  const remoteConfigFile = await VirtualSpeedKitConfigFile.createRemote(activeSpeedKitConfig, this.bundler);
64
- const app = this.customerConfig.app;
65
64
  const origin = this.customerConfig.origins[0];
66
65
  const changes = [];
67
- const localSpeedKit = await speedKitConfigFile.evaluate(app, origin);
68
- const remoteSpeedKit = await remoteConfigFile.evaluate(app, origin);
66
+ const localSpeedKit = await speedKitConfigFile.evaluate(this.customerConfig, origin);
67
+ const remoteSpeedKit = await remoteConfigFile.evaluate(this.customerConfig, origin);
69
68
  if ((localSpeedKit.detectDevice && !remoteSpeedKit.detectDevice) ||
70
69
  (!localSpeedKit.detectDevice && remoteSpeedKit.detectDevice)) {
71
70
  changes.push("detectDevice");
@@ -63,11 +63,10 @@ export class SplitChangeCheck {
63
63
  }
64
64
  async checkSplitsForEachOrigin(speedKitConfigFile, activeSpeedKitConfig) {
65
65
  const remoteConfigFile = await VirtualSpeedKitConfigFile.createRemote(activeSpeedKitConfig, this.bundler);
66
- const app = this.customerConfig.app;
67
66
  const changes = [];
68
67
  for (const origin of this.customerConfig.origins) {
69
- const localSpeedKit = await speedKitConfigFile.evaluate(app, origin);
70
- const remoteSpeedKit = await remoteConfigFile.evaluate(app, origin);
68
+ const localSpeedKit = await speedKitConfigFile.evaluate(this.customerConfig, origin);
69
+ const remoteSpeedKit = await remoteConfigFile.evaluate(this.customerConfig, origin);
71
70
  // check for split change
72
71
  if (localSpeedKit.split !== remoteSpeedKit.split) {
73
72
  changes.push({
@@ -13,6 +13,11 @@ export declare class DocumentHandlerServer {
13
13
  private entityManager?;
14
14
  private documentHandlerCode;
15
15
  private documentHandlerConfigCode;
16
+ /**
17
+ * The packjockel bundle for a customer with the `configPlugins` feature: the handler, its config
18
+ * and the Speed Kit config in one CommonJS module, which exports `post`.
19
+ */
20
+ private documentHandlerBundle?;
16
21
  private database;
17
22
  /** Sources of app modules already looked up; `null` marks a lookup that came back empty. */
18
23
  private readonly appModules;
@@ -22,11 +27,23 @@ export declare class DocumentHandlerServer {
22
27
  */
23
28
  constructor(customerConfig: CustomerConfig, files: FileListInterface, bundler: BundleService, cli: CliServiceInterface, workSpace: string, verboseLevel?: boolean, entityManager?: EntityManager);
24
29
  transform(contentType: string, html: string, variation: string, url: string, headers: Record<string, string>): Promise<DocumentHandlerResponse>;
30
+ /** Runs the handler in the context, and returns the config, which calls its `post`. */
31
+ private createScript;
32
+ /** Loads the packjockel bundle like a CommonJS module, and calls the `post` it exports. */
33
+ private createBundleScript;
34
+ private getDocumentHandlerConfigPath;
25
35
  private getTransformFunctionWrapper;
26
36
  buildDocumentHandler(): Promise<void>;
37
+ /**
38
+ * Bundles the handler, its config and the Speed Kit config into one module, the way the server
39
+ * deploys a customer with the `configPlugins` feature.
40
+ */
41
+ private bundleWithPackjockel;
27
42
  private deactivateReleaseAndDeploymentDetection;
28
43
  private getDocumentHandler;
29
44
  private getDynamicFetcher;
45
+ /** The customer's own dynamic fetcher, or else the source of the latest one. */
46
+ private getDynamicFetcherSource;
30
47
  private getDynamicFetcherConfig;
31
48
  private getStyles;
32
49
  private getDocumentHandlerConfig;
@@ -2,6 +2,7 @@ import { LATEST_DYNAMIC_FETCHER_URL, LOCAL_DOCUMENT_HANDLER, LOCAL_DOCUMENT_HAND
2
2
  import RequiredFileNotFoundError from "./error/required-file-not-found-error.js";
3
3
  import DatabaseMock from "./templates/database-mock.js";
4
4
  import * as vm from "node:vm";
5
+ import { usesConfigPlugins, } from "../integration-api/index.js";
5
6
  import { INTEGRATION_FILES } from "../../models/files.js";
6
7
  // documentHandlerDependencies
7
8
  import fetch from "node-fetch";
@@ -25,6 +26,11 @@ export class DocumentHandlerServer {
25
26
  entityManager;
26
27
  documentHandlerCode;
27
28
  documentHandlerConfigCode;
29
+ /**
30
+ * The packjockel bundle for a customer with the `configPlugins` feature: the handler, its config
31
+ * and the Speed Kit config in one CommonJS module, which exports `post`.
32
+ */
33
+ documentHandlerBundle;
28
34
  database;
29
35
  /** Sources of app modules already looked up; `null` marks a lookup that came back empty. */
30
36
  appModules = new Map();
@@ -42,7 +48,11 @@ export class DocumentHandlerServer {
42
48
  this.entityManager = entityManager;
43
49
  }
44
50
  async transform(contentType, html, variation, url, headers) {
45
- if (!this.documentHandlerCode || !this.documentHandlerConfigCode) {
51
+ const configPlugins = usesConfigPlugins(this.customerConfig);
52
+ const built = configPlugins
53
+ ? this.documentHandlerBundle
54
+ : this.documentHandlerCode && this.documentHandlerConfigCode;
55
+ if (!built) {
46
56
  await this.buildDocumentHandler();
47
57
  }
48
58
  const skInternalRequest = new Request(url, html, variation, headers, {
@@ -57,26 +67,21 @@ export class DocumentHandlerServer {
57
67
  skInternalError: {},
58
68
  Abort: DocumentHandlerAbort,
59
69
  APP: this.customerConfig.app,
60
- DYNAMIC_FETCHER: await this.getDynamicFetcher(),
61
- DYNAMIC_FETCHER_CONFIG: await this.getDynamicFetcherConfig(),
62
- CUSTOM_STYLES: this.getStyles(),
70
+ // packjockel defines these in the bundle itself.
71
+ ...(configPlugins
72
+ ? {}
73
+ : {
74
+ DYNAMIC_FETCHER: await this.getDynamicFetcher(),
75
+ DYNAMIC_FETCHER_CONFIG: await this.getDynamicFetcherConfig(),
76
+ CUSTOM_STYLES: this.getStyles(),
77
+ }),
63
78
  ...this.getContextVars(),
64
79
  ...this.createNodeVmContext(),
65
80
  skErrorContext: {},
66
81
  };
67
- const customDocumentHandlerFile = this.files.getByName(INTEGRATION_FILES.CUSTOM.DOCUMENT_HANDLER);
68
- if (customDocumentHandlerFile.path) {
69
- vm.runInNewContext(this.documentHandlerCode, vmContext, {
70
- filename: customDocumentHandlerFile.path,
71
- displayErrors: true,
72
- });
73
- }
74
- else {
75
- vm.runInNewContext(this.documentHandlerCode, vmContext);
76
- }
77
- const script = new vm.Script(this.documentHandlerConfigCode + this.getTransformFunctionWrapper(), {
78
- filename: this.files.getByName("config_documentHandler").path,
79
- });
82
+ const script = configPlugins
83
+ ? this.createBundleScript()
84
+ : this.createScript(vmContext);
80
85
  const vmResponse = await safe(new Promise((resolve, reject) => {
81
86
  vmContext.skInternalResponse.resolve = resolve;
82
87
  // @ts-expect-error reject is unknown
@@ -92,17 +97,67 @@ export class DocumentHandlerServer {
92
97
  }
93
98
  throw new DocumentHandlerTransformError(vmResponse.errorObj);
94
99
  }
100
+ /** Runs the handler in the context, and returns the config, which calls its `post`. */
101
+ createScript(vmContext) {
102
+ const customDocumentHandlerFile = this.files.getByName(INTEGRATION_FILES.CUSTOM.DOCUMENT_HANDLER);
103
+ if (customDocumentHandlerFile.path) {
104
+ vm.runInNewContext(this.documentHandlerCode, vmContext, {
105
+ filename: customDocumentHandlerFile.path,
106
+ displayErrors: true,
107
+ });
108
+ }
109
+ else {
110
+ vm.runInNewContext(this.documentHandlerCode, vmContext);
111
+ }
112
+ return new vm.Script(this.documentHandlerConfigCode + this.getTransformFunctionWrapper(), { filename: this.getDocumentHandlerConfigPath() });
113
+ }
114
+ /** Loads the packjockel bundle like a CommonJS module, and calls the `post` it exports. */
115
+ createBundleScript() {
116
+ return new vm.Script(`(function (module, exports) {\n${this.documentHandlerBundle}\n})(module, module.exports);\n\n` +
117
+ `module.exports.post(db, skInternalRequest, skInternalResponse).catch((error)=>reject(error));`, { filename: this.getDocumentHandlerConfigPath() });
118
+ }
119
+ getDocumentHandlerConfigPath() {
120
+ return this.files.getByName("config_documentHandler")
121
+ .path;
122
+ }
95
123
  getTransformFunctionWrapper() {
96
124
  return `\n\npost(db, skInternalRequest, skInternalResponse).catch((error)=>reject(error));`;
97
125
  }
98
126
  async buildDocumentHandler() {
99
127
  this.cli.startAction("DOCUMENTHANDLER:BUILD", "rebuild documentHandler");
128
+ if (usesConfigPlugins(this.customerConfig)) {
129
+ this.documentHandlerBundle = await this.bundleWithPackjockel();
130
+ this.cli.successAction("DOCUMENTHANDLER:BUILD");
131
+ return;
132
+ }
100
133
  this.documentHandlerCode = await this.bundleDocumentHandlerCode("custom_documentHandler.js", await this.getDocumentHandler());
101
134
  this.documentHandlerConfigCode = await this.bundleDocumentHandlerCode("config_documentHandler.js", this.deactivateReleaseAndDeploymentDetection());
102
135
  this.cli.successAction("DOCUMENTHANDLER:BUILD");
103
136
  }
137
+ /**
138
+ * Bundles the handler, its config and the Speed Kit config into one module, the way the server
139
+ * deploys a customer with the `configPlugins` feature.
140
+ */
141
+ async bundleWithPackjockel() {
142
+ const customDocumentHandler = this.files.getByName(INTEGRATION_FILES.CUSTOM.DOCUMENT_HANDLER);
143
+ return this.bundler.packjockel.bundleDocumentHandler({
144
+ // Without a custom one, packjockel bundles the published handler of documentHandlerVersion.
145
+ documentHandler: customDocumentHandler?.path
146
+ ? await this.getDocumentHandler()
147
+ : undefined,
148
+ documentHandlerConfig: this.deactivateReleaseAndDeploymentDetection(),
149
+ speedKitConfig: this.files
150
+ .getByName(INTEGRATION_FILES.CONFIG.SPEED_KIT)
151
+ .getContent(),
152
+ appName: this.customerConfig.app,
153
+ dynamicFetcher: await this.getDynamicFetcherSource(),
154
+ dynamicFetcherConfig: await this.getDynamicFetcherConfig(),
155
+ customStyle: this.getStyles(),
156
+ versions: this.customerConfig,
157
+ });
158
+ }
104
159
  deactivateReleaseAndDeploymentDetection() {
105
- return this.getDocumentHandlerConfig().replace("const documentHandler =", (selected) => {
160
+ return this.getDocumentHandlerConfig().replace(/const documentHandler =|export default new /, (selected) => {
106
161
  return (`config["executeDeploymentDetection"] = false;config["executeReleaseDetection"] = false;\n` +
107
162
  selected);
108
163
  });
@@ -113,10 +168,17 @@ export class DocumentHandlerServer {
113
168
  .getContent();
114
169
  }
115
170
  async getDynamicFetcher() {
171
+ if (!this.files.hasFile(LOCAL_DYNAMIC_FETCHER)) {
172
+ return await this.bundleDynamicFetcher({ "dynamic-fetcher": "https://www.baqend.com/speed-kit/latest/" }, await this.getDynamicFetcherSource());
173
+ }
174
+ return this.getDynamicFetcherSource();
175
+ }
176
+ /** The customer's own dynamic fetcher, or else the source of the latest one. */
177
+ async getDynamicFetcherSource() {
116
178
  // todo use fetchRemoteFile from integration api
117
179
  if (!this.files.hasFile(LOCAL_DYNAMIC_FETCHER)) {
118
180
  const response = await fetch(LATEST_DYNAMIC_FETCHER_URL);
119
- return await this.bundleDynamicFetcher({ "dynamic-fetcher": "https://www.baqend.com/speed-kit/latest/" }, await response.text());
181
+ return await response.text();
120
182
  }
121
183
  return this.files
122
184
  .getByName(INTEGRATION_FILES.CUSTOM.DYNAMIC_FETCHER)
@@ -13,6 +13,7 @@ export * from "./virtual/external-recipe.js";
13
13
  export * from "./virtual/static-recipe.js";
14
14
  export * from "./external/external-file-reader.js";
15
15
  import type { SpeedKitConfig } from "./struct/speed-kit-config.js";
16
+ import type { SpeedKitConfigCustomer } from "./struct/speed-kit-config-file.js";
16
17
  import { CustomerConfig } from "./struct/customer-config.js";
17
18
  import { RoFile } from "./struct/ro-file.js";
18
19
  import { VirtualFile } from "./struct/virtual-file.js";
@@ -89,7 +90,7 @@ export interface InstallResourceInterface extends ConfigFileInterface, FileInter
89
90
  readonly remoteKey: string;
90
91
  }
91
92
  export interface SpeedKitConfigInterface extends InstallResourceInterface {
92
- evaluate(app: string, origin: string): Promise<SpeedKitConfig>;
93
+ evaluate(customer: SpeedKitConfigCustomer, origin: string): Promise<SpeedKitConfig>;
93
94
  }
94
95
  export interface CustomerConfigInterface extends ConfigFileInterface {
95
96
  config: CustomerConfig;
@@ -2,8 +2,21 @@ import { expect } from "chai";
2
2
  import { describe, it } from "mocha";
3
3
  import { SpeedKitConfigFile, VirtualSpeedKitConfigFile } from "../index.js";
4
4
  import { INTEGRATION_FILES } from "../../../models/files.js";
5
- import { BundleServiceFactory } from "../../bundler/index.js";
5
+ import { BundleService, BundleServiceFactory, } from "../../bundler/index.js";
6
6
  const bundler = new BundleServiceFactory("./").buildService();
7
+ const SHOP_DE = { app: "shop-de" };
8
+ /** Answers every bundle request with one bundle and keeps the requests. */
9
+ class FakePackjockel {
10
+ bundled;
11
+ requests = [];
12
+ constructor(bundled) {
13
+ this.bundled = bundled;
14
+ }
15
+ async bundle(request) {
16
+ this.requests.push(request);
17
+ return this.bundled;
18
+ }
19
+ }
7
20
  function configFile(source) {
8
21
  return new SpeedKitConfigFile({
9
22
  name: INTEGRATION_FILES.CONFIG.SPEED_KIT,
@@ -13,7 +26,7 @@ function configFile(source) {
13
26
  }, bundler);
14
27
  }
15
28
  function evaluate(source) {
16
- return configFile(source).evaluate("shop-de", "https://www.shop.de");
29
+ return configFile(source).evaluate(SHOP_DE, "https://www.shop.de");
17
30
  }
18
31
  /** What the config assigned, for the tests about the browser mock itself. */
19
32
  async function evaluateRaw(source) {
@@ -89,19 +102,19 @@ describe("SpeedKitConfigFile", () => {
89
102
  // builder and the pre-deploy checks both go through here.
90
103
  const file = configFile(`window.speedKit = { host: window.location.host };`);
91
104
  const [first, second] = await Promise.all([
92
- file.evaluate("shop-de", "https://www.shop.de"),
93
- file.evaluate("shop-de", "https://www.shop.de"),
105
+ file.evaluate(SHOP_DE, "https://www.shop.de"),
106
+ file.evaluate(SHOP_DE, "https://www.shop.de"),
94
107
  ]);
95
- const otherOrigin = await file.evaluate("shop-de", "https://m.shop.de");
108
+ const otherOrigin = await file.evaluate(SHOP_DE, "https://m.shop.de");
96
109
  expect(first).to.equal(second);
97
110
  expect(otherOrigin).to.not.equal(first);
98
111
  expect(otherOrigin.raw.host).to.equal("m.shop.de");
99
112
  });
100
113
  it("should forget what it read when the file changes", async () => {
101
114
  const file = configFile(`window.speedKit = { split: 0.1 };`);
102
- const before = await file.evaluate("shop-de", "https://www.shop.de");
115
+ const before = await file.evaluate(SHOP_DE, "https://www.shop.de");
103
116
  file.setContent(`window.speedKit = { split: 0.5 };`);
104
- const after = await file.evaluate("shop-de", "https://www.shop.de");
117
+ const after = await file.evaluate(SHOP_DE, "https://www.shop.de");
105
118
  expect(before.split).to.equal(0.1);
106
119
  expect(after.split).to.equal(0.5);
107
120
  });
@@ -109,8 +122,55 @@ describe("SpeedKitConfigFile", () => {
109
122
  const source = `window.speedKit = { split: 0.5, appName: APP };`;
110
123
  const remote = await VirtualSpeedKitConfigFile.createRemote(source, bundler);
111
124
  const local = await evaluate(source);
112
- const deployed = await remote.evaluate("shop-de", "https://www.shop.de");
125
+ const deployed = await remote.evaluate(SHOP_DE, "https://www.shop.de");
113
126
  expect(deployed).to.deep.equal(local);
114
127
  expect(remote.getContent()).to.equal(source);
115
128
  });
129
+ describe("with the configPlugins feature", () => {
130
+ const SOURCE = "window.speedKit = { split: 0.1 };";
131
+ const EMBEDDED = {
132
+ app: "shop-de",
133
+ features: { configPlugins: true },
134
+ configPluginsVersion: "@release",
135
+ };
136
+ function embeddedFile(bundled) {
137
+ const packjockel = new FakePackjockel(bundled);
138
+ const file = new SpeedKitConfigFile({
139
+ name: INTEGRATION_FILES.CONFIG.SPEED_KIT,
140
+ path: "config_SpeedKit.js",
141
+ content: SOURCE,
142
+ remoteKey: "config",
143
+ }, new BundleService("./", packjockel));
144
+ return { file, packjockel };
145
+ }
146
+ it("should bundle with packjockel and the tags of the customer", async () => {
147
+ const { file, packjockel } = embeddedFile(`SpeedKit.config = {};`);
148
+ await file.evaluate(EMBEDDED, "https://www.shop.de");
149
+ expect(packjockel.requests).to.have.length(1);
150
+ expect(packjockel.requests[0]).to.deep.equal({
151
+ entryPoints: { "config.js": SOURCE },
152
+ versions: EMBEDDED,
153
+ define: { APP: '"shop-de"' },
154
+ platform: "browser",
155
+ });
156
+ });
157
+ it("should read SpeedKit.config and the plugins pushed without a guard", async () => {
158
+ const { file } = embeddedFile(`SpeedKit.configPlugins.push({ name: "StripQueryParamPlugin" });
159
+ SpeedKit.config = { split: 0.3, appName: "shop-de" };`);
160
+ const config = await file.evaluate(EMBEDDED, "https://www.shop.de");
161
+ expect(config.split).to.equal(0.3);
162
+ expect(config.raw.appName).to.equal("shop-de");
163
+ });
164
+ it("should still read a config that assigns window.speedKit", async () => {
165
+ const { file } = embeddedFile(`window.speedKit = { split: 0.7 };`);
166
+ const config = await file.evaluate(EMBEDDED, "https://www.shop.de");
167
+ expect(config.split).to.equal(0.7);
168
+ });
169
+ it("should not reuse a reading of the other bundler", async () => {
170
+ const { file, packjockel } = embeddedFile(`SpeedKit.config = {};`);
171
+ await file.evaluate(EMBEDDED, "https://www.shop.de");
172
+ await file.evaluate({ app: "shop-de" }, "https://www.shop.de");
173
+ expect(packjockel.requests).to.have.length(1);
174
+ });
175
+ });
116
176
  });
@@ -1,3 +1,16 @@
1
+ import type { AssetVersions } from "../../bundler/index.js";
2
+ /**
3
+ * The installation features of a config. `null` leaves a feature at its default.
4
+ */
5
+ export interface CustomerFeatures {
6
+ /**
7
+ * packjockel bundles the config with the config plugins of its target and
8
+ * embeds it into the document handler and the install script. The config
9
+ * writes `SpeedKit.config`.
10
+ */
11
+ configPlugins?: boolean | null;
12
+ [feature: string]: unknown;
13
+ }
1
14
  export interface CustomerConfigs {
2
15
  production: CustomerConfig;
3
16
  [configName: string]: CustomerConfig;
@@ -21,6 +34,24 @@ export declare class CustomerConfig {
21
34
  * installation whose split is greater than 0 for any origin.
22
35
  */
23
36
  readonly needsCustomerApproval?: boolean;
24
- constructor(app: string, origins: string[], domain: string, swPath: string, scope: string, appDomain?: string, installPath?: string, installParameters?: string, name?: string, forceInstall?: boolean, chromeFlags?: string[], dependencies?: Record<string, string>, needsCustomerApproval?: boolean);
37
+ readonly features?: CustomerFeatures;
38
+ /**
39
+ * The tag of Speed Kit (snippet, service worker, dynamic fetcher) for the `configPlugins` feature: a
40
+ * version such as `2.22.4`, or a channel such as `@release`; `latest` when not set. This and the other
41
+ * tags are named like the client config keys of packjockel.
42
+ */
43
+ readonly speedKitVersion?: string;
44
+ /** The tag of RUM for the `configPlugins` feature, see {@link speedKitVersion}. */
45
+ readonly rumPluginVersion?: string;
46
+ /** The tag of predictive preloading for the `configPlugins` feature, see {@link speedKitVersion}. */
47
+ readonly ppVersion?: string;
48
+ /** The tag of the speed-kit-config plugins for the `configPlugins` feature, see {@link speedKitVersion}. */
49
+ readonly configPluginsVersion?: string;
50
+ /**
51
+ * The tag of the published document handler for the `configPlugins` feature, see {@link speedKitVersion}.
52
+ * A `custom_documentHandler.js` replaces it.
53
+ */
54
+ readonly documentHandlerVersion?: string;
55
+ constructor(app: string, origins: string[], domain: string, swPath: string, scope: string, appDomain?: string, installPath?: string, installParameters?: string, name?: string, forceInstall?: boolean, chromeFlags?: string[], dependencies?: Record<string, string>, needsCustomerApproval?: boolean, features?: CustomerFeatures, versions?: AssetVersions);
25
56
  static createFrom(configFile: Partial<CustomerConfig>, configName?: string): CustomerConfig;
26
57
  }
@@ -18,7 +18,25 @@ export class CustomerConfig {
18
18
  * installation whose split is greater than 0 for any origin.
19
19
  */
20
20
  needsCustomerApproval;
21
- constructor(app, origins, domain, swPath, scope, appDomain, installPath, installParameters, name, forceInstall, chromeFlags, dependencies, needsCustomerApproval) {
21
+ features;
22
+ /**
23
+ * The tag of Speed Kit (snippet, service worker, dynamic fetcher) for the `configPlugins` feature: a
24
+ * version such as `2.22.4`, or a channel such as `@release`; `latest` when not set. This and the other
25
+ * tags are named like the client config keys of packjockel.
26
+ */
27
+ speedKitVersion;
28
+ /** The tag of RUM for the `configPlugins` feature, see {@link speedKitVersion}. */
29
+ rumPluginVersion;
30
+ /** The tag of predictive preloading for the `configPlugins` feature, see {@link speedKitVersion}. */
31
+ ppVersion;
32
+ /** The tag of the speed-kit-config plugins for the `configPlugins` feature, see {@link speedKitVersion}. */
33
+ configPluginsVersion;
34
+ /**
35
+ * The tag of the published document handler for the `configPlugins` feature, see {@link speedKitVersion}.
36
+ * A `custom_documentHandler.js` replaces it.
37
+ */
38
+ documentHandlerVersion;
39
+ constructor(app, origins, domain, swPath, scope, appDomain, installPath, installParameters, name, forceInstall, chromeFlags, dependencies, needsCustomerApproval, features, versions = {}) {
22
40
  this.app = app;
23
41
  this.origins = origins;
24
42
  this.domain = domain;
@@ -32,11 +50,23 @@ export class CustomerConfig {
32
50
  this.chromeFlags = chromeFlags;
33
51
  this.dependencies = dependencies;
34
52
  this.needsCustomerApproval = needsCustomerApproval;
53
+ this.features = features;
54
+ this.speedKitVersion = versions.speedKitVersion;
55
+ this.rumPluginVersion = versions.rumPluginVersion;
56
+ this.ppVersion = versions.ppVersion;
57
+ this.configPluginsVersion = versions.configPluginsVersion;
58
+ this.documentHandlerVersion = versions.documentHandlerVersion;
35
59
  }
36
60
  static createFrom(configFile, configName) {
37
- const { app, origins, domain, swPath, scope, appDomain, installPath, installParams, name, forceInstall, chromeFlags, dependencies, needsCustomerApproval, } = configFile;
61
+ const { app, origins, domain, swPath, scope, appDomain, installPath, installParams, name, forceInstall, chromeFlags, dependencies, needsCustomerApproval, features, speedKitVersion, rumPluginVersion, ppVersion, configPluginsVersion, documentHandlerVersion, } = configFile;
38
62
  return new CustomerConfig(new RequiredParameter("app", app).isString().getValue(), new RequiredParameter("origins", origins).isArray().getValue(), domain, new RequiredParameter("swPath", swPath).isString().getValue(), new RequiredParameter("scope", scope).isString().getValue(), appDomain || `${app}.app.baqend.com`, installPath ||
39
- `https://${app}.app.baqend.com/v1/speedkit/install.js?d=${name || configName}`, installParams || 'async="" crossorigin="anonymous"', name, forceInstall || false, chromeFlags, dependencies || {}, needsCustomerApproval || false);
63
+ `https://${app}.app.baqend.com/v1/speedkit/install.js?d=${name || configName}`, installParams || 'async="" crossorigin="anonymous"', name, forceInstall || false, chromeFlags, dependencies || {}, needsCustomerApproval || false, features || {}, {
64
+ speedKitVersion,
65
+ rumPluginVersion,
66
+ ppVersion,
67
+ configPluginsVersion,
68
+ documentHandlerVersion,
69
+ });
40
70
  }
41
71
  }
42
72
  class RequiredParameter {
@@ -1,7 +1,10 @@
1
- import type { BundleService } from "../../bundler/index.js";
1
+ import type { AssetVersions, BundleService } from "../../bundler/index.js";
2
2
  import type { SpeedKitConfigInterface, VirtualFileInterface, VirtualFileRecipe } from "../integration-api-model.js";
3
3
  import { InstallResourceFile } from "./install-resource-file.js";
4
4
  import { SpeedKitConfig } from "./speed-kit-config.js";
5
+ import type { CustomerConfig } from "./customer-config.js";
6
+ /** What of the customer config decides how a Speed Kit config is bundled and read. */
7
+ export type SpeedKitConfigCustomer = Pick<CustomerConfig, "app" | "features"> & AssetVersions;
5
8
  /** The name the config deployed to the app is read back under. */
6
9
  export declare const REMOTE_SPEED_KIT_CONFIG = "config_SpeedKit@remote";
7
10
  /** The file a {@link SpeedKitConfigFile} stands for. */
@@ -23,7 +26,7 @@ export interface SpeedKitConfigFileInit {
23
26
  export declare class SpeedKitConfigFile extends InstallResourceFile implements SpeedKitConfigInterface {
24
27
  private readonly bundler;
25
28
  /**
26
- * One evaluation per app and origin. A config branches on
29
+ * One evaluation per app, origin and bundler. A config branches on
27
30
  * `window.location`, so the same file read for two origins is two different
28
31
  * configs — and bundling one is expensive enough not to repeat per caller.
29
32
  */
@@ -34,8 +37,8 @@ export declare class SpeedKitConfigFile extends InstallResourceFile implements S
34
37
  */
35
38
  constructor(file: SpeedKitConfigFileInit, bundler: BundleService);
36
39
  setContent(content: string): void;
37
- /** The config this file describes for one app and origin. */
38
- evaluate(app: string, origin: string): Promise<SpeedKitConfig>;
40
+ /** The config this file describes for one customer and origin. */
41
+ evaluate(customer: SpeedKitConfigCustomer, origin: string): Promise<SpeedKitConfig>;
39
42
  }
40
43
  /**
41
44
  * A SpeedKit config that has no file on disk behind it — the one deployed to
@@ -60,3 +63,5 @@ export declare class VirtualSpeedKitConfigFile extends SpeedKitConfigFile implem
60
63
  delete(): Promise<void>;
61
64
  onChange(): void;
62
65
  }
66
+ /** The customer has the `configPlugins` feature: packjockel bundles its config. */
67
+ export declare function usesConfigPlugins(customer: SpeedKitConfigCustomer): boolean;
@@ -3,7 +3,7 @@ import { EvaluateSkConfigError } from "../error/evaluate-sk-config-error.js";
3
3
  import ApplicationError from "../../error-handling/error/application-error.js";
4
4
  import { StaticRecipe } from "../virtual/static-recipe.js";
5
5
  import { InstallResourceFile } from "./install-resource-file.js";
6
- import { SpeedKitConfig } from "./speed-kit-config.js";
6
+ import { SpeedKitConfig, } from "./speed-kit-config.js";
7
7
  /** The name the config deployed to the app is read back under. */
8
8
  export const REMOTE_SPEED_KIT_CONFIG = "config_SpeedKit@remote";
9
9
  /**
@@ -17,7 +17,7 @@ export const REMOTE_SPEED_KIT_CONFIG = "config_SpeedKit@remote";
17
17
  export class SpeedKitConfigFile extends InstallResourceFile {
18
18
  bundler;
19
19
  /**
20
- * One evaluation per app and origin. A config branches on
20
+ * One evaluation per app, origin and bundler. A config branches on
21
21
  * `window.location`, so the same file read for two origins is two different
22
22
  * configs — and bundling one is expensive enough not to repeat per caller.
23
23
  */
@@ -34,14 +34,15 @@ export class SpeedKitConfigFile extends InstallResourceFile {
34
34
  super.setContent(content);
35
35
  this.evaluations.clear();
36
36
  }
37
- /** The config this file describes for one app and origin. */
38
- evaluate(app, origin) {
39
- const key = `${app}|${origin}`;
37
+ /** The config this file describes for one customer and origin. */
38
+ evaluate(customer, origin) {
39
+ const { app } = customer;
40
+ const key = `${app}|${origin}|${usesConfigPlugins(customer) ? "packjockel" : "esbuild"}`;
40
41
  const cached = this.evaluations.get(key);
41
42
  if (cached) {
42
43
  return cached;
43
44
  }
44
- const evaluation = bundle(this.bundler, this.getContent(), app)
45
+ const evaluation = bundle(this.bundler, this.getContent(), customer)
45
46
  .then((code) => evaluateSpeedKitConfig(app, origin, code, this.path))
46
47
  .catch((error) => {
47
48
  // A failure is not an answer: forget it, so the next caller — or the
@@ -95,7 +96,8 @@ export class VirtualSpeedKitConfigFile extends SpeedKitConfigFile {
95
96
  }
96
97
  /**
97
98
  * Run a bundled config against a browser mock and hand back what it assigned to
98
- * `window.speedKit`, together with the config plugins it registered.
99
+ * `SpeedKit.config`, or else to `window.speedKit`, together with the config
100
+ * plugins it registered.
99
101
  *
100
102
  * @param app the app the config is evaluated for, exposed to it as `APP`
101
103
  * @param origin the origin the config is evaluated for, its `window.location`
@@ -113,7 +115,7 @@ function evaluateSpeedKitConfig(app, origin, code, filename) {
113
115
  if (browserContext.vmError !== null) {
114
116
  throw new EvaluateSkConfigError(`[${filename}] ${browserContext.vmError?.message}`);
115
117
  }
116
- return SpeedKitConfig.createFrom(browserContext.window.speedKit, registeredPlugins(browserContext));
118
+ return SpeedKitConfig.createFrom(browserContext.window.SpeedKit.config ?? browserContext.window.speedKit, registeredPlugins(browserContext));
117
119
  }
118
120
  /**
119
121
  * The plugins a config registered, read the way `ConfigController.getPlugins`
@@ -136,7 +138,9 @@ function buildBrowserMock(origin, app) {
136
138
  },
137
139
  customVariation: [],
138
140
  },
139
- SpeedKit: {},
141
+ // An embedded config pushes its plugins without creating the list, the
142
+ // way packjockel hands it over.
143
+ SpeedKit: { configPlugins: [] },
140
144
  serviceWorkerUrl: "",
141
145
  screen: { width: 0, height: 0 },
142
146
  devicePixelRatio: 1,
@@ -214,10 +218,23 @@ function safeFileContentWrapper(fileContent) {
214
218
  }
215
219
  `;
216
220
  }
217
- async function bundle(bundler, content, app) {
221
+ /** The customer has the `configPlugins` feature: packjockel bundles its config. */
222
+ export function usesConfigPlugins(customer) {
223
+ return customer.features?.configPlugins === true;
224
+ }
225
+ async function bundle(bundler, content, customer) {
218
226
  if (!content) {
219
227
  throw new ApplicationError("Content is empty");
220
228
  }
229
+ const app = customer.app;
230
+ if (usesConfigPlugins(customer)) {
231
+ return bundler.packjockel.bundle({
232
+ entryPoints: { "config.js": content },
233
+ versions: customer,
234
+ define: { APP: JSON.stringify(app) },
235
+ platform: "browser",
236
+ });
237
+ }
221
238
  return bundler.bundle({
222
239
  basePaths: {
223
240
  "speed-kit-config": "https://www.baqend.com/speed-kit-config/latest/",
@@ -1,3 +1,4 @@
1
+ import { usesConfigPlugins, } from "../../integration-api/index.js";
1
2
  import { INTEGRATION_FILES } from "../../../models/files.js";
2
3
  const IMPORT_PATHS = {
3
4
  rum: "https://www.baqend.com/rum/latest/",
@@ -19,8 +20,10 @@ export class SpeedKitInstallContext {
19
20
  this.skTemplate = skTemplate;
20
21
  }
21
22
  async getSpeedKitInstallJs() {
23
+ const configPlugins = usesConfigPlugins(this.customerConfig);
22
24
  const configJs = this.skTemplate.render({
23
25
  config: this.getConfigSpeedKit(),
26
+ configPlugins,
24
27
  forceInstall: this.customerConfig.forceInstall,
25
28
  installPath: this.customerConfig.installPath,
26
29
  installParams: this.customerConfig.installParams,
@@ -29,15 +32,24 @@ export class SpeedKitInstallContext {
29
32
  .getByName(INTEGRATION_FILES.CUSTOM.DYNAMIC_FETCHER)
30
33
  .getContent(),
31
34
  });
35
+ const entryPoints = {
36
+ "rum.js": this.prepareConfigLoadHandler(),
37
+ "config.js": configJs,
38
+ "loader.js": this.files
39
+ .getByName(INTEGRATION_FILES.CUSTOM.LOADER)
40
+ .getContent(),
41
+ };
42
+ if (configPlugins) {
43
+ return this.bundler.packjockel.bundle({
44
+ entryPoints,
45
+ versions: this.customerConfig,
46
+ define: { APP: JSON.stringify(this.customerConfig.app) },
47
+ platform: "browser",
48
+ });
49
+ }
32
50
  return this.bundler.bundle({
33
51
  basePaths: IMPORT_PATHS,
34
- entryPoints: {
35
- "rum.js": this.prepareConfigLoadHandler(),
36
- "config.js": configJs,
37
- "loader.js": this.files
38
- .getByName(INTEGRATION_FILES.CUSTOM.LOADER)
39
- .getContent(),
40
- },
52
+ entryPoints,
41
53
  logLevel: "error",
42
54
  minify: false,
43
55
  platform: "browser",
@@ -72,7 +84,7 @@ export class SpeedKitInstallContext {
72
84
  return config.replace(value, "100");
73
85
  });
74
86
  }
75
- return configString.replace(/window\.speedKit[^{]*=[^{]*{/, (configOpenTag) => {
87
+ return configString.replace(/(?:window\.speedKit|SpeedKit\.config)[^{]*=[^{]*{/, (configOpenTag) => {
76
88
  return configOpenTag + `\n delayRacedOrigin: 100,\n`;
77
89
  });
78
90
  }
@@ -5,6 +5,11 @@ export class InstallSpeedKitJsTemplate extends AbstractTemplate {
5
5
  // Config
6
6
  {{{config}}}
7
7
 
8
+ {{#if configPlugins}}
9
+ // The config writes SpeedKit.config, which packjockel exposes; the overrides below change it.
10
+ var speedKit = SpeedKit.config;
11
+ {{/if}}
12
+
8
13
  // Reset potential split test parameters
9
14
  speedKit.split = 1.0;
10
15
  speedKit.splitTestId = 'debug';
@@ -22,7 +22,7 @@ export class QueryBuilderFactory {
22
22
  const customerConfig = files.getCustomerConfig().config;
23
23
  const app = customerConfig.app;
24
24
  const origins = customerConfig.origins ?? [];
25
- const speedKitConfig = await this.getSpeedKitConfig(app, origins[0], files.getSpeedKitConfig());
25
+ const speedKitConfig = await this.getSpeedKitConfig(customerConfig, origins[0], files.getSpeedKitConfig());
26
26
  const serviceContext = {
27
27
  app,
28
28
  bySet: this.context.bySet,
@@ -72,8 +72,8 @@ export class QueryBuilderFactory {
72
72
  const integrationApi = new IntegrationApiFactory(integrationApiContext).buildService();
73
73
  return await integrationApi.run();
74
74
  }
75
- async getSpeedKitConfig(app, origin, speedKitConfigFile) {
76
- const result = await safe(speedKitConfigFile.evaluate(app, origin));
75
+ async getSpeedKitConfig(customer, origin, speedKitConfigFile) {
76
+ const result = await safe(speedKitConfigFile.evaluate(customer, origin));
77
77
  if (result.success !== true) {
78
78
  throw new ParseConfigSpeedKitError(result.error);
79
79
  }
@@ -1788,5 +1788,5 @@
1788
1788
  ]
1789
1789
  }
1790
1790
  },
1791
- "version": "4.43.0"
1791
+ "version": "4.44.0-beta.2"
1792
1792
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@speedkit/cli",
3
3
  "description": "Speed Kit CLI",
4
- "version": "4.43.0",
4
+ "version": "4.44.0-beta.2",
5
5
  "author": {
6
6
  "name": "Baqend.com",
7
7
  "email": "info@baqend.com"
@@ -110,6 +110,7 @@
110
110
  "@oclif/plugin-help": "^6.2.45",
111
111
  "@oclif/plugin-not-found": "^3.2.81",
112
112
  "@oclif/plugin-warn-if-update-available": "^3.1.61",
113
+ "@speedkit/packjockel": "3.0.0",
113
114
  "@speedkit/rules": "^1.3.0-0",
114
115
  "baqend": "^4.2.5",
115
116
  "chalk": "^5.6.2",