@speedkit/cli 4.38.1 → 4.40.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 (33) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +10 -1
  3. package/dist/commands/airports_iata.json +9202 -1
  4. package/dist/commands/generate-customer-config.d.ts +2 -0
  5. package/dist/commands/generate-customer-config.js +7 -1
  6. package/dist/services/customer-config/customer-config-service-build-context.d.ts +8 -0
  7. package/dist/services/customer-config/customer-config-service-build-context.js +8 -0
  8. package/dist/services/customer-config/customer-config-service-factory.js +3 -1
  9. package/dist/services/customer-config/customer-config-service.d.ts +10 -7
  10. package/dist/services/customer-config/customer-config-service.js +138 -308
  11. package/dist/services/customer-config/index.d.ts +2 -0
  12. package/dist/services/customer-config/index.js +2 -0
  13. package/dist/services/customer-config/spec/wizard-answers.spec.d.ts +1 -0
  14. package/dist/services/customer-config/spec/wizard-answers.spec.js +207 -0
  15. package/dist/services/customer-config/wizard-answers.d.ts +48 -0
  16. package/dist/services/customer-config/wizard-answers.js +67 -0
  17. package/dist/services/customer-config/wizard-questions.d.ts +86 -0
  18. package/dist/services/customer-config/wizard-questions.js +400 -0
  19. package/dist/services/document-handler-runtime/document-handler-abort.d.ts +44 -0
  20. package/dist/services/document-handler-runtime/document-handler-abort.js +48 -0
  21. package/dist/services/document-handler-runtime/document-handler-console.d.ts +45 -0
  22. package/dist/services/document-handler-runtime/document-handler-console.js +81 -0
  23. package/dist/services/document-handler-runtime/document-handler-server.js +3 -23
  24. package/dist/services/document-handler-runtime/spec/document-handler-abort.spec.js +57 -1
  25. package/dist/services/document-handler-runtime/spec/document-handler-console.spec.d.ts +1 -0
  26. package/dist/services/document-handler-runtime/spec/document-handler-console.spec.js +97 -0
  27. package/dist/services/onboarding/error/document-handler-transform-error.d.ts +2 -0
  28. package/dist/services/onboarding/error/document-handler-transform-error.js +3 -0
  29. package/dist/services/onboarding/virtual-orestes-app/index.d.ts +3 -0
  30. package/dist/services/onboarding/virtual-orestes-app/index.js +27 -2
  31. package/dist/templates/speedKit.Revalidated.js +5 -1
  32. package/oclif.manifest.json +98 -83
  33. package/package.json +1 -1
@@ -0,0 +1,400 @@
1
+ import { ShopSystem, } from "./customer-config-service-model.js";
2
+ export const DEFAULT_RULES = {
3
+ appFlag: "the value of the -a flag",
4
+ detectedShopSystem: "the shop system that the site analysis detected; no default when it detected none",
5
+ japaneseHost: "true for a production host that ends in .jp, else false",
6
+ preCheckedFeatures: "every feature choice whose own default resolves to true",
7
+ };
8
+ const notShopify = {
9
+ key: "shopSystem",
10
+ notEquals: ShopSystem.SHOPIFY,
11
+ };
12
+ const fullConfig = { mode: "customer-config" };
13
+ export const WIZARD_QUESTIONS = [
14
+ {
15
+ key: "appName",
16
+ type: "string",
17
+ prompt: "[App] Enter desired Speed Kit app name:",
18
+ description: "The Speed Kit app name, in kebab-case. It also names the output directory.",
19
+ default: { rule: "appFlag" },
20
+ phase: "settings",
21
+ },
22
+ {
23
+ key: "productionHost",
24
+ type: "string",
25
+ prompt: "[Production] Enter production host (without https://):",
26
+ description: "The production host, without https://. The site analysis runs against it.",
27
+ suggestion: "www.<app>.de",
28
+ phase: "settings",
29
+ },
30
+ {
31
+ key: "analyzeSite",
32
+ type: "boolean",
33
+ prompt: "[Analysis] Analyze production site to auto-detect settings?",
34
+ description: "Whether the wizard fetches the production home to detect the shop system, the install.js and the feature defaults.",
35
+ default: true,
36
+ phase: "settings",
37
+ },
38
+ {
39
+ key: "shopSystem",
40
+ type: "select",
41
+ prompt: "[Shop System] Which shop system is in use?",
42
+ description: "The shop platform behind the storefront. It selects platform plugins, for example ShopifyPlugin.",
43
+ choices: [
44
+ ...Object.values(ShopSystem).filter((value) => value !== ShopSystem.OTHER),
45
+ ShopSystem.OTHER,
46
+ ].map((value) => ({ value })),
47
+ default: { rule: "detectedShopSystem" },
48
+ skipPromptWhenDefaulted: true,
49
+ phase: "settings",
50
+ },
51
+ {
52
+ key: "productionInstallJsPresent",
53
+ type: "boolean",
54
+ prompt: "[Production] Is the install.js already present?",
55
+ description: "Whether the production pages already load the Speed Kit install.js. If not, local testing force-installs it.",
56
+ default: { fromAnalysis: "hasInstallJs", fallback: false },
57
+ phase: "settings",
58
+ },
59
+ {
60
+ key: "staging",
61
+ type: "object",
62
+ prompt: "[Staging] Should a staging config also be added?",
63
+ description: 'A staging host to scaffold a second config for: { "host": "<host>", "installJsPresent": <bool> }, or null for none.',
64
+ default: null,
65
+ when: notShopify,
66
+ phase: "settings",
67
+ },
68
+ {
69
+ key: "needsCustomerApproval",
70
+ type: "boolean",
71
+ prompt: "[Approval] Must the customer approve a change before it may be activated?",
72
+ description: "Whether the customer signs off every change before sk deploy may activate a split above 0.",
73
+ default: { rule: "japaneseHost" },
74
+ engineerDecision: true,
75
+ phase: "settings",
76
+ },
77
+ {
78
+ key: "features",
79
+ type: "multiSelect",
80
+ prompt: "[Features] Select features to enable:",
81
+ description: "The features to scaffold. Each choice names the fact that decides it.",
82
+ default: { rule: "preCheckedFeatures" },
83
+ when: fullConfig,
84
+ phase: "settings",
85
+ choices: [
86
+ {
87
+ value: "removeLazyLoading",
88
+ label: "Lazy-Loading Removal / Preloading",
89
+ description: "Above-the-fold images arrive lazy-loaded in the server HTML (loading=lazy, data-src).",
90
+ default: { fromAnalysis: "removeLazyLoading", fallback: true },
91
+ },
92
+ {
93
+ value: "hasSoftNavigations",
94
+ label: "Soft Navigation Tracking",
95
+ description: "Any navigation changes the URL without a new document request: between page types, a PLP filter or sort, a PDP variant, or a checkout step.",
96
+ default: { fromAnalysis: "hasSoftNavigations", fallback: false },
97
+ },
98
+ {
99
+ value: "includeServiceWorker",
100
+ label: "Include existing Service Worker",
101
+ description: "The site registers its own service worker, and Speed Kit has to include it.",
102
+ default: { fromAnalysis: "includeServiceWorker", fallback: false },
103
+ },
104
+ {
105
+ value: "useGATracking",
106
+ label: "GA DataLayer Tracking",
107
+ description: "The site pushes its e-commerce events to a GA dataLayer, and Speed Kit reads them from there.",
108
+ default: { fromAnalysis: "useGATracking", fallback: true },
109
+ when: notShopify,
110
+ },
111
+ {
112
+ value: "withGoogleOptimize",
113
+ label: "Google Optimize Support",
114
+ description: "The site runs Google Optimize experiments.",
115
+ default: { fromAnalysis: "withGoogleOptimize", fallback: false },
116
+ },
117
+ {
118
+ value: "activateCfRocketLoaderPlugin",
119
+ label: "Cloudflare Rocket Loader Plugin",
120
+ description: "Cloudflare Rocket Loader defers the site's scripts.",
121
+ default: {
122
+ fromAnalysis: "activateCfRocketLoaderPlugin",
123
+ fallback: false,
124
+ },
125
+ },
126
+ {
127
+ value: "handleUsercentrics",
128
+ label: "Usercentrics Handling",
129
+ description: "The site loads the Usercentrics CMP (uc-block.bundle.js), which must run as a safe script.",
130
+ default: { fromAnalysis: "handleUsercentrics", fallback: false },
131
+ },
132
+ {
133
+ value: "useDisabledSitesApproach",
134
+ label: "Disabled Sites approach",
135
+ description: "The URLs do not tell the page types apart, so a whitelist of enabled pages is impractical.",
136
+ },
137
+ {
138
+ value: "activateImageOptimisation",
139
+ label: "Image Optimisation",
140
+ description: "Speed Kit should optimise images: no image CDN serves WebP already, and the app is no PoV.",
141
+ },
142
+ {
143
+ value: "addSSR",
144
+ label: "Server-Side Rendering (SSR)",
145
+ description: "Above-the-fold content is missing from the server HTML and renders client-side. Also enables device detection.",
146
+ },
147
+ {
148
+ value: "addDeviceDetection",
149
+ label: "Device Detection",
150
+ description: "The origin serves different HTML to mobile and desktop for the same URL.",
151
+ },
152
+ {
153
+ value: "isPOV",
154
+ label: "Enhanced PoV Tracking",
155
+ description: "The handover marks the engagement as a Proof of Value.",
156
+ },
157
+ {
158
+ value: "useScrapingBee",
159
+ label: "ScrapingBee",
160
+ description: "The origin answers by visitor geo-location, so the renderer must fetch through ScrapingBee.",
161
+ },
162
+ {
163
+ value: "addDowntimeDetection",
164
+ label: "Downtime Detection",
165
+ description: "The app needs the downtime detection script.",
166
+ },
167
+ ],
168
+ },
169
+ {
170
+ key: "serviceWorkerPath",
171
+ type: "string",
172
+ prompt: "[Service Worker] Enter path of Service Worker to be included:",
173
+ description: "The path of the site's own service worker script.",
174
+ default: "/sw.js",
175
+ when: { key: "features", includes: "includeServiceWorker" },
176
+ phase: "settings",
177
+ },
178
+ {
179
+ key: "ssrInnerShadowDomSupport",
180
+ type: "boolean",
181
+ prompt: "[SSR] Activate handling for customer-utilized Shadow DOMs?",
182
+ description: "The site renders content inside its own shadow roots, which the SSR snapshot must keep.",
183
+ default: false,
184
+ when: { key: "features", includes: "addSSR" },
185
+ phase: "settings",
186
+ },
187
+ {
188
+ key: "convertSoftToHardNavigations",
189
+ type: "boolean",
190
+ prompt: "[Soft Navigations] Convert soft navigations between home, PLP and PDP to hard navigations?",
191
+ description: "A soft navigation between home, PLP and PDP, or between PLP categories, becomes a hard one so cached documents serve it. Every other soft navigation stays soft.",
192
+ default: false,
193
+ when: { key: "features", includes: "hasSoftNavigations" },
194
+ phase: "settings",
195
+ },
196
+ {
197
+ key: "graduatePrePoc",
198
+ type: "boolean",
199
+ prompt: "Rename the pre-PoC files and continue?",
200
+ description: "Asked when the output directory holds a pre-PoC config: park its files as *_pre-poc next to the new config.",
201
+ engineerDecision: true,
202
+ phase: "output",
203
+ },
204
+ {
205
+ key: "existingDirectory",
206
+ type: "select",
207
+ prompt: "Output directory is not empty. How to proceed?",
208
+ description: "Asked when the output directory is not empty.",
209
+ choices: [
210
+ { value: "new-name", description: "Scaffold into a new directory." },
211
+ {
212
+ value: "overwrite-file-wise",
213
+ description: "Keep the directory, and answer per existing file.",
214
+ },
215
+ { value: "empty", description: "Delete the directory's content first." },
216
+ ],
217
+ engineerDecision: true,
218
+ phase: "output",
219
+ },
220
+ {
221
+ key: "newDirectoryName",
222
+ type: "string",
223
+ prompt: "Please enter new output directory name:",
224
+ description: 'The new directory name, when existingDirectory is "new-name".',
225
+ suggestion: "<app>-2",
226
+ phase: "output",
227
+ },
228
+ {
229
+ key: "overwriteExistingFiles",
230
+ type: "boolean",
231
+ prompt: "File already exists. Overwrite?",
232
+ description: 'Answers every "file already exists" question, when existingDirectory is "overwrite-file-wise".',
233
+ engineerDecision: true,
234
+ phase: "output",
235
+ },
236
+ ];
237
+ export function wizardQuestion(key) {
238
+ return WIZARD_QUESTIONS.find((question) => question.key === key);
239
+ }
240
+ /** Whether a condition holds for the answers so far and the wizard mode. */
241
+ export function conditionHolds(condition, answers, mode) {
242
+ if (!condition)
243
+ return true;
244
+ if ("allOf" in condition) {
245
+ return condition.allOf.every((c) => conditionHolds(c, answers, mode));
246
+ }
247
+ if ("mode" in condition)
248
+ return condition.mode === mode;
249
+ const value = answers[condition.key];
250
+ if ("equals" in condition && value !== condition.equals)
251
+ return false;
252
+ if ("notEquals" in condition && value === condition.notEquals)
253
+ return false;
254
+ if (condition.includes !== undefined &&
255
+ !(Array.isArray(value) && value.includes(condition.includes))) {
256
+ return false;
257
+ }
258
+ return true;
259
+ }
260
+ const DETECTED_SHOP_SYSTEMS = {
261
+ shopify: ShopSystem.SHOPIFY,
262
+ shopware: ShopSystem.SHOPWARE,
263
+ salesforce: ShopSystem.SALESFORCE,
264
+ oxid: ShopSystem.OXID,
265
+ plentymarkets: ShopSystem.PLENTYMARKETS,
266
+ magento: ShopSystem.MAGENTO,
267
+ woocommerce: ShopSystem.WOOCOMMERCE,
268
+ bigcommerce: ShopSystem.BIGCOMMERCE,
269
+ prestashop: ShopSystem.PRESTASHOP,
270
+ jtl: ShopSystem.JTL,
271
+ commercetools: ShopSystem.COMMERCETOOLS,
272
+ spryker: ShopSystem.SPRYKER,
273
+ shoptet: ShopSystem.SHOPTET,
274
+ ecforce: ShopSystem.ECFORCE,
275
+ futureshop: ShopSystem.FUTURESHOP,
276
+ };
277
+ /** The choices of a question that apply to the answers so far. */
278
+ export function applicableChoices(question, context) {
279
+ return (question.choices ?? []).filter((choice) => conditionHolds(choice.when, context.answers, context.mode));
280
+ }
281
+ /** Resolves a default to a value; `undefined` means the question has none here. */
282
+ export function resolveDefault(question, value, context) {
283
+ if (value === undefined || value === null || typeof value !== "object") {
284
+ return value;
285
+ }
286
+ if ("fromAnalysis" in value) {
287
+ return context.analysis
288
+ ? Boolean(context.analysis[value.fromAnalysis]) || value.fallback
289
+ : value.fallback;
290
+ }
291
+ switch (value.rule) {
292
+ case "appFlag":
293
+ return context.appName || undefined;
294
+ case "detectedShopSystem":
295
+ return context.analysis?.shopSystem
296
+ ? DETECTED_SHOP_SYSTEMS[context.analysis.shopSystem]
297
+ : undefined;
298
+ case "japaneseHost":
299
+ return /\.jp$/i.test((context.answers.productionHost ?? "").trim().replace(/\/.*$/, ""));
300
+ case "preCheckedFeatures":
301
+ return applicableChoices(question, context)
302
+ .filter((choice) => resolveDefault(question, choice.default, context) === true)
303
+ .map((choice) => choice.value);
304
+ }
305
+ }
306
+ /** Checks one answer against its question; returns the problem, or undefined. */
307
+ export function validateAnswer(question, value, context) {
308
+ const allowed = applicableChoices(question, context).map((c) => c.value);
309
+ switch (question.type) {
310
+ case "string":
311
+ if (typeof value !== "string" || value === "") {
312
+ return `"${question.key}" must be a non-empty string.`;
313
+ }
314
+ if (question.key === "appName" &&
315
+ !/^[\da-z]+(?:-[\da-z]+)*$/.test(value)) {
316
+ return `The app name "${value}" is no valid kebab-case.`;
317
+ }
318
+ return undefined;
319
+ case "boolean":
320
+ return typeof value === "boolean"
321
+ ? undefined
322
+ : `"${question.key}" must be true or false.`;
323
+ case "select":
324
+ return allowed.includes(value)
325
+ ? undefined
326
+ : `Unknown ${question.key} "${String(value)}". Use one of: ${allowed.join(", ")}.`;
327
+ case "multiSelect": {
328
+ if (!Array.isArray(value))
329
+ return `"${question.key}" must be a list.`;
330
+ const unknown = value.filter((v) => !allowed.includes(v));
331
+ return unknown.length === 0
332
+ ? undefined
333
+ : `Unknown ${question.key} here: ${unknown.join(", ")}. Use any of: ${allowed.join(", ")}.`;
334
+ }
335
+ case "object":
336
+ if (value === null)
337
+ return undefined;
338
+ if (typeof value !== "object" ||
339
+ typeof value.host !== "string") {
340
+ return `"${question.key}" must be null or an object with a "host".`;
341
+ }
342
+ return undefined;
343
+ }
344
+ }
345
+ /** The template variables that the answers decide. */
346
+ export function settingsFromAnswers(answers, mode) {
347
+ const shop = answers.shopSystem;
348
+ const settings = {
349
+ appName: answers.appName,
350
+ production: {
351
+ host: answers.productionHost,
352
+ forceInstall: !answers.productionInstallJsPresent,
353
+ },
354
+ staging: answers.staging
355
+ ? {
356
+ host: answers.staging.host,
357
+ forceInstall: !answers.staging.installJsPresent,
358
+ }
359
+ : undefined,
360
+ needsCustomerApproval: answers.needsCustomerApproval,
361
+ shopSystemName: shop === ShopSystem.OTHER ? undefined : shop,
362
+ isShopify: shop === ShopSystem.SHOPIFY || undefined,
363
+ isShopware: shop === ShopSystem.SHOPWARE || undefined,
364
+ isSalesforce: shop === ShopSystem.SALESFORCE || undefined,
365
+ isOxid: shop === ShopSystem.OXID || undefined,
366
+ isPlentymarkets: shop === ShopSystem.PLENTYMARKETS || undefined,
367
+ };
368
+ if (mode === "pre-poc")
369
+ return settings;
370
+ const features = answers.features ?? [];
371
+ const featureChoices = wizardQuestion("features").choices;
372
+ for (const choice of featureChoices) {
373
+ if (choice.value !== "includeServiceWorker") {
374
+ settings[choice.value] = features.includes(choice.value);
375
+ }
376
+ }
377
+ // SSR always implies device detection
378
+ settings.addDeviceDetection = settings.addSSR || settings.addDeviceDetection;
379
+ settings.includeServiceWorker = features.includes("includeServiceWorker")
380
+ ? answers.serviceWorkerPath
381
+ : undefined;
382
+ settings.addSSRInnerShadowDomSupport = settings.addSSR
383
+ ? answers.ssrInnerShadowDomSupport
384
+ : undefined;
385
+ settings.convertSoftToHardNavigations = settings.hasSoftNavigations
386
+ ? answers.convertSoftToHardNavigations
387
+ : undefined;
388
+ return settings;
389
+ }
390
+ /** The table as `--print-questions` prints it. */
391
+ export function describeWizardQuestions(cliVersion) {
392
+ return {
393
+ cliVersion,
394
+ usage: "Answer the settings questions whose `when` holds, then run sk generate-customer-config -a <app> --answers <file>. " +
395
+ "A key you leave out takes its default; a question without a default must be answered. " +
396
+ "Ask the engineer before you answer a question marked engineerDecision.",
397
+ defaultRules: DEFAULT_RULES,
398
+ questions: WIZARD_QUESTIONS,
399
+ };
400
+ }
@@ -56,3 +56,47 @@ export declare const ABORT_SERVER_TIMING = "errorcode;desc=303";
56
56
  * @param error - Error to classify.
57
57
  */
58
58
  export declare function isDocumentHandlerAbort(error?: Error): boolean;
59
+ /**
60
+ * Port the Document Handler posts SSR requests to when neither `NATS_URL` nor
61
+ * `preRender.lambdaUrl` is set (`requestViaLocal` in the document-handler's
62
+ * `SsrService.ts`). Locally that is the puppeteer-lambda pre-renderer.
63
+ */
64
+ export declare const LOCAL_PRERENDERER_PORT = 3001;
65
+ /**
66
+ * Whether an error is a refused connection to the local pre-renderer — the `TypeError:
67
+ * fetch failed` that `fetch` throws when nothing listens on {@link LOCAL_PRERENDERER_PORT}.
68
+ * The refused connection sits in the error's `cause`. The error comes from the `vm`
69
+ * context, so it is matched by shape, not by class.
70
+ *
71
+ * @param error - Any value; only an error with that cause matches.
72
+ */
73
+ export declare function isRefusedByLocalPrerenderer(error: unknown): boolean;
74
+ /**
75
+ * Whether an abort means SSR could not reach the local pre-renderer at all.
76
+ *
77
+ * The Document Handler wraps a failed SSR fetch as `Abort(error.toString(), { url,
78
+ * variation, error })`, so the fetch error is the abort's `data.error`.
79
+ *
80
+ * @param error - Error the Document Handler run failed with.
81
+ */
82
+ export declare function isLocalPrerendererUnreachable(error?: Error): boolean;
83
+ /** The payload of the abort the Document Handler throws when the pre-renderer answers non-200. */
84
+ export interface PrerenderFailure {
85
+ url: string;
86
+ variation: string;
87
+ /** Status the pre-renderer answered with. */
88
+ status: number;
89
+ /** The pre-renderer's `x-render-error`, e.g. a selector it waited for in vain. */
90
+ detailMessage: string | null;
91
+ }
92
+ /**
93
+ * The pre-renderer's failure, when an abort means it ran but could not render the page.
94
+ *
95
+ * `handleSSRResponse` in the document-handler's `SsrService.ts` throws
96
+ * `Abort(detailMessage, { url, variation, status, detailMessage })` for a non-200
97
+ * answer, and the SSR step re-throws it unchanged. Matched by shape, like every
98
+ * error from the `vm`.
99
+ *
100
+ * @param error - Error the Document Handler run failed with, or a value it logged.
101
+ */
102
+ export declare function prerenderFailure(error: unknown): PrerenderFailure | undefined;
@@ -64,3 +64,51 @@ export function isDocumentHandlerAbort(error) {
64
64
  }
65
65
  return (error.name === "Abort" || error.isAbort === true);
66
66
  }
67
+ /**
68
+ * Port the Document Handler posts SSR requests to when neither `NATS_URL` nor
69
+ * `preRender.lambdaUrl` is set (`requestViaLocal` in the document-handler's
70
+ * `SsrService.ts`). Locally that is the puppeteer-lambda pre-renderer.
71
+ */
72
+ export const LOCAL_PRERENDERER_PORT = 3001;
73
+ /**
74
+ * Whether an error is a refused connection to the local pre-renderer — the `TypeError:
75
+ * fetch failed` that `fetch` throws when nothing listens on {@link LOCAL_PRERENDERER_PORT}.
76
+ * The refused connection sits in the error's `cause`. The error comes from the `vm`
77
+ * context, so it is matched by shape, not by class.
78
+ *
79
+ * @param error - Any value; only an error with that cause matches.
80
+ */
81
+ export function isRefusedByLocalPrerenderer(error) {
82
+ const cause = error?.cause;
83
+ return (cause?.code === "ECONNREFUSED" && cause?.port === LOCAL_PRERENDERER_PORT);
84
+ }
85
+ /**
86
+ * Whether an abort means SSR could not reach the local pre-renderer at all.
87
+ *
88
+ * The Document Handler wraps a failed SSR fetch as `Abort(error.toString(), { url,
89
+ * variation, error })`, so the fetch error is the abort's `data.error`.
90
+ *
91
+ * @param error - Error the Document Handler run failed with.
92
+ */
93
+ export function isLocalPrerendererUnreachable(error) {
94
+ return isRefusedByLocalPrerenderer(error?.data?.error);
95
+ }
96
+ /**
97
+ * The pre-renderer's failure, when an abort means it ran but could not render the page.
98
+ *
99
+ * `handleSSRResponse` in the document-handler's `SsrService.ts` throws
100
+ * `Abort(detailMessage, { url, variation, status, detailMessage })` for a non-200
101
+ * answer, and the SSR step re-throws it unchanged. Matched by shape, like every
102
+ * error from the `vm`.
103
+ *
104
+ * @param error - Error the Document Handler run failed with, or a value it logged.
105
+ */
106
+ export function prerenderFailure(error) {
107
+ const data = error?.data;
108
+ if (typeof data?.url !== "string" ||
109
+ typeof data.status !== "number" ||
110
+ !("detailMessage" in data)) {
111
+ return undefined;
112
+ }
113
+ return data;
114
+ }
@@ -0,0 +1,45 @@
1
+ import { CliServiceInterface } from "../cli/index.js";
2
+ /**
3
+ * The `console` the customer's Document Handler sees inside the `vm`.
4
+ *
5
+ * Output goes through the CLI, prefixed with where it came from. `warn` and `error`
6
+ * are always shown; everything else only with `--verboseLevel`. Without a console of
7
+ * its own, a `vm` context falls back to V8's, which writes only to an attached
8
+ * inspector — so a Document Handler warning used to vanish unless `-v` was set.
9
+ *
10
+ * The Document Handler's own SSR warnings are dropped when the abort that follows
11
+ * reports the same failure in one line: a refused connection to the local
12
+ * pre-renderer, or a pre-renderer that could not render the page. The warning would
13
+ * add a full stack trace on every page.
14
+ */
15
+ export declare class DocumentHandlerConsole {
16
+ private readonly cli;
17
+ private readonly prefix;
18
+ private readonly verbose;
19
+ /**
20
+ * @param cli - Where the output goes.
21
+ * @param prefix - Marks the source of each line, e.g. `documentHandler`.
22
+ * @param verbose - Whether `log`, `info`, `debug` and the rest are shown.
23
+ */
24
+ constructor(cli: CliServiceInterface, prefix: string, verbose?: boolean);
25
+ error: (...logArguments: unknown[]) => void;
26
+ warn: (...logArguments: unknown[]) => void;
27
+ log: (...logArguments: unknown[]) => void;
28
+ info: (...logArguments: unknown[]) => void;
29
+ debug: (...logArguments: unknown[]) => void;
30
+ trace: (...logArguments: unknown[]) => void;
31
+ dir: (...logArguments: unknown[]) => void;
32
+ table: (...logArguments: unknown[]) => void;
33
+ time: (...logArguments: unknown[]) => void;
34
+ timeEnd: (...logArguments: unknown[]) => void;
35
+ timeLog: (...logArguments: unknown[]) => void;
36
+ count: (...logArguments: unknown[]) => void;
37
+ countReset: (...logArguments: unknown[]) => void;
38
+ group: (...logArguments: unknown[]) => void;
39
+ groupCollapsed: (...logArguments: unknown[]) => void;
40
+ groupEnd: (...logArguments: unknown[]) => void;
41
+ assert: (...logArguments: unknown[]) => void;
42
+ private native;
43
+ private isKnownNoise;
44
+ private format;
45
+ }
@@ -0,0 +1,81 @@
1
+ import { format } from "node:util";
2
+ import { isRefusedByLocalPrerenderer, prerenderFailure, } from "./document-handler-abort.js";
3
+ /**
4
+ * The `console` the customer's Document Handler sees inside the `vm`.
5
+ *
6
+ * Output goes through the CLI, prefixed with where it came from. `warn` and `error`
7
+ * are always shown; everything else only with `--verboseLevel`. Without a console of
8
+ * its own, a `vm` context falls back to V8's, which writes only to an attached
9
+ * inspector — so a Document Handler warning used to vanish unless `-v` was set.
10
+ *
11
+ * The Document Handler's own SSR warnings are dropped when the abort that follows
12
+ * reports the same failure in one line: a refused connection to the local
13
+ * pre-renderer, or a pre-renderer that could not render the page. The warning would
14
+ * add a full stack trace on every page.
15
+ */
16
+ export class DocumentHandlerConsole {
17
+ cli;
18
+ prefix;
19
+ verbose;
20
+ /**
21
+ * @param cli - Where the output goes.
22
+ * @param prefix - Marks the source of each line, e.g. `documentHandler`.
23
+ * @param verbose - Whether `log`, `info`, `debug` and the rest are shown.
24
+ */
25
+ constructor(cli, prefix, verbose = false) {
26
+ this.cli = cli;
27
+ this.prefix = prefix;
28
+ this.verbose = verbose;
29
+ }
30
+ error = (...logArguments) => {
31
+ if (!this.isKnownNoise(logArguments)) {
32
+ this.cli.writeError(this.format(logArguments));
33
+ }
34
+ };
35
+ warn = (...logArguments) => {
36
+ if (!this.isKnownNoise(logArguments)) {
37
+ this.cli.writeWarning(this.format(logArguments));
38
+ }
39
+ };
40
+ log = (...logArguments) => {
41
+ if (this.verbose) {
42
+ this.cli.write(this.format(logArguments));
43
+ }
44
+ };
45
+ info = this.log;
46
+ debug = (...logArguments) => {
47
+ if (this.verbose) {
48
+ this.cli.comment(this.format(logArguments));
49
+ }
50
+ };
51
+ trace = this.debug;
52
+ dir = this.debug;
53
+ table = this.log;
54
+ // Counters, timers and groups only make sense on the real console; they are
55
+ // accepted so a Document Handler calling them does not throw, and only take
56
+ // effect with `--verboseLevel`.
57
+ time = this.native("time");
58
+ timeEnd = this.native("timeEnd");
59
+ timeLog = this.native("timeLog");
60
+ count = this.native("count");
61
+ countReset = this.native("countReset");
62
+ group = this.native("group");
63
+ groupCollapsed = this.native("groupCollapsed");
64
+ groupEnd = this.native("groupEnd");
65
+ assert = this.native("assert");
66
+ native(method) {
67
+ return (...logArguments) => {
68
+ if (this.verbose) {
69
+ // eslint-disable-next-line no-console -- timers and groups keep their state on the real console
70
+ console[method](...logArguments);
71
+ }
72
+ };
73
+ }
74
+ isKnownNoise(logArguments) {
75
+ return logArguments.some((argument) => isRefusedByLocalPrerenderer(argument) ||
76
+ prerenderFailure(argument) !== undefined);
77
+ }
78
+ format(logArguments) {
79
+ return `[${this.prefix}]: ${format(...logArguments)}`;
80
+ }
81
+ }
@@ -8,6 +8,7 @@ import fetch from "node-fetch";
8
8
  import { Request } from "./server/request.js";
9
9
  import { DocumentHandlerResponse } from "./server/document-handler-response.js";
10
10
  import { DocumentHandlerAbort } from "./document-handler-abort.js";
11
+ import { DocumentHandlerConsole } from "./document-handler-console.js";
11
12
  import { safe } from "../../helpers/safe.js";
12
13
  import { VmEmptyResponseError } from "../onboarding/error/vm-empty-response-error.js";
13
14
  import { DocumentHandlerTransformError } from "../onboarding/error/document-handler-transform-error.js";
@@ -144,26 +145,7 @@ export class DocumentHandlerServer {
144
145
  return contextVariables;
145
146
  }
146
147
  async createDataBaseMock() {
147
- const vmConsole = {
148
- log: (...logArguments) => {
149
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions
150
- this.verboseLevel
151
- ? this.cli.write(`[documentHandler.dbLog]: ${JSON.stringify(logArguments)}`)
152
- : "";
153
- },
154
- info: (...logArguments) => {
155
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions
156
- this.verboseLevel
157
- ? this.cli.writeWarning(`[documentHandler.dbLog]: ${JSON.stringify(logArguments)}`)
158
- : "";
159
- },
160
- error: (...logArguments) => {
161
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions
162
- this.verboseLevel
163
- ? this.cli.writeError(`[documentHandler.dbLog]: ${JSON.stringify(logArguments)}`)
164
- : "";
165
- },
166
- };
148
+ const vmConsole = new DocumentHandlerConsole(this.cli, "documentHandler.dbLog", this.verboseLevel);
167
149
  if (!this.database) {
168
150
  const dataBaseMock = new DatabaseMock();
169
151
  const databaseCode = dataBaseMock.render(dataBaseMock.create(this.customerConfig.origins[0], this.customerConfig.app));
@@ -193,10 +175,8 @@ export class DocumentHandlerServer {
193
175
  TextEncoder,
194
176
  TextDecoder,
195
177
  module: { exports: {} },
178
+ console: new DocumentHandlerConsole(this.cli, "documentHandler", this.verboseLevel),
196
179
  };
197
- if (this.verboseLevel) {
198
- context["console"] = console;
199
- }
200
180
  return context;
201
181
  }
202
182
  /**