@decocms/start 4.0.0 → 4.2.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decocms/start",
3
- "version": "4.0.0",
3
+ "version": "4.2.0",
4
4
  "type": "module",
5
5
  "description": "Deco framework for TanStack Start - CMS bridge, admin protocol, hooks, schema generation",
6
6
  "main": "./src/index.ts",
@@ -6,6 +6,7 @@ import {
6
6
  getLogLevel,
7
7
  type LoggerAdapter,
8
8
  logger,
9
+ serializeError,
9
10
  setLogLevel,
10
11
  } from "./logger";
11
12
 
@@ -133,3 +134,55 @@ describe("configureLogger", () => {
133
134
  logSpy.mockRestore();
134
135
  });
135
136
  });
137
+
138
+ describe("serializeError", () => {
139
+ it("flattens an Error into a JSON-safe shape with stack", () => {
140
+ const err = new Error("boom");
141
+ const out = serializeError(err);
142
+ expect(out).toEqual({ name: "Error", message: "boom", stack: err.stack });
143
+ });
144
+
145
+ it("preserves subclass name (TypeError, RangeError, custom)", () => {
146
+ expect(serializeError(new TypeError("bad type")).name).toBe("TypeError");
147
+ class MyErr extends Error {
148
+ override name = "MyErr";
149
+ }
150
+ expect(serializeError(new MyErr("custom")).name).toBe("MyErr");
151
+ });
152
+
153
+ it("survives JSON.stringify round-trip", () => {
154
+ const err = new Error("round-trip");
155
+ const out = serializeError(err);
156
+ expect(() => JSON.parse(JSON.stringify(out))).not.toThrow();
157
+ expect(JSON.parse(JSON.stringify(out)).message).toBe("round-trip");
158
+ });
159
+
160
+ it("captures plain objects as JSON in message, marking them as NonError", () => {
161
+ const out = serializeError({ code: 500, body: "vtex down" });
162
+ expect(out.name).toBe("NonError");
163
+ expect(out.message).toBe('{"code":500,"body":"vtex down"}');
164
+ expect(out.stack).toBeUndefined();
165
+ });
166
+
167
+ it("falls back to String() when an object has circular refs", () => {
168
+ const circ: Record<string, unknown> = { a: 1 };
169
+ circ.self = circ;
170
+ const out = serializeError(circ);
171
+ expect(out.name).toBe("NonError");
172
+ expect(typeof out.message).toBe("string");
173
+ expect(out.stack).toBeUndefined();
174
+ });
175
+
176
+ it("handles primitives (string, number, null, undefined)", () => {
177
+ expect(serializeError("just a string")).toEqual({
178
+ name: "NonError",
179
+ message: "just a string",
180
+ });
181
+ expect(serializeError(42)).toEqual({ name: "NonError", message: "42" });
182
+ expect(serializeError(null)).toEqual({ name: "NonError", message: "null" });
183
+ expect(serializeError(undefined)).toEqual({
184
+ name: "NonError",
185
+ message: "undefined",
186
+ });
187
+ });
188
+ });
package/src/sdk/logger.ts CHANGED
@@ -127,11 +127,25 @@ function shouldLog(level: LogLevel): boolean {
127
127
  // ---------------------------------------------------------------------------
128
128
 
129
129
  /**
130
- * Mirrors `@deco/deco/o11y` logger:
131
- * - first arg is the message
130
+ * Strict structured logger. Mirrors `@deco/deco/o11y`:
131
+ * - first arg is a human-readable message string
132
132
  * - optional second arg is a flat attributes object
133
133
  *
134
- * Adapters decide the destination (stdout JSON, OTLP, both, …).
134
+ * Adapters decide the destination (stdout JSON, OTLP, both, …). The
135
+ * contract is intentionally narrow so structured output stays predictable
136
+ * across all sinks.
137
+ *
138
+ * @example
139
+ * ```ts
140
+ * logger.info("checkout started", { orderFormId, items });
141
+ * logger.warn("retrying vtex call", { attempt, host });
142
+ *
143
+ * // For Errors, serialize explicitly into the attrs payload:
144
+ * try { ... } catch (err) {
145
+ * const e = serializeError(err);
146
+ * logger.error(e.message, { error: e, stage: "checkout" });
147
+ * }
148
+ * ```
135
149
  */
136
150
  export interface Logger {
137
151
  debug(msg: string, attrs?: Record<string, unknown>): void;
@@ -140,6 +154,47 @@ export interface Logger {
140
154
  error(msg: string, attrs?: Record<string, unknown>): void;
141
155
  }
142
156
 
157
+ /**
158
+ * Normalised, JSON-safe error shape suitable for inclusion in logger
159
+ * attributes. `serializeError` always returns this shape regardless of
160
+ * what was thrown.
161
+ */
162
+ export interface SerializedError {
163
+ name: string;
164
+ message: string;
165
+ stack?: string;
166
+ }
167
+
168
+ /**
169
+ * Convert any thrown value into a flat, structured object that survives
170
+ * `JSON.stringify` and round-trips cleanly to OTel / Cloudflare Logs.
171
+ * Strict logger sites should call this from their catch blocks rather
172
+ * than passing the Error directly.
173
+ *
174
+ * @example
175
+ * ```ts
176
+ * try { ... } catch (err) {
177
+ * const e = serializeError(err);
178
+ * logger.error(e.message, { error: e });
179
+ * }
180
+ * ```
181
+ */
182
+ export function serializeError(err: unknown): SerializedError {
183
+ if (err instanceof Error) {
184
+ return { name: err.name, message: err.message, stack: err.stack };
185
+ }
186
+ if (err && typeof err === "object") {
187
+ let body: string;
188
+ try {
189
+ body = JSON.stringify(err);
190
+ } catch {
191
+ body = String(err);
192
+ }
193
+ return { name: "NonError", message: body };
194
+ }
195
+ return { name: "NonError", message: String(err) };
196
+ }
197
+
143
198
  function emit(level: LogLevel, msg: string, attrs?: Record<string, unknown>): void {
144
199
  if (!shouldLog(level)) return;
145
200
  try {
@@ -5,14 +5,29 @@ import {
5
5
  SamplingDecision,
6
6
  } from "@opentelemetry/sdk-trace-base";
7
7
  import { describe, expect, it } from "vitest";
8
- import { createUrlBasedHeadSampler, decodeSamplingConfig, URLBasedSampler } from "./sampler";
8
+ import {
9
+ createUrlBasedHeadSampler,
10
+ DEFAULT_SAMPLE_RATIO,
11
+ decodeSamplingConfig,
12
+ URLBasedSampler,
13
+ } from "./sampler";
9
14
 
10
- const TRACE_ID = "0000000000000000ffffffffffffffff";
15
+ // Two trace IDs at opposite ends of the TraceIdRatioBased accumulator.
16
+ // `accumulate(traceId)` xors the trace ID in 8-hex-char chunks; threshold at
17
+ // ratio R is `floor(R * 0xffffffff)`. See
18
+ // `@opentelemetry/sdk-trace-base/src/sampler/TraceIdRatioBasedSampler`.
19
+ //
20
+ // LOW: 0x00000000 ^ 0x00000000 ^ 0xffffffff ^ 0xffffffff = 0
21
+ // → 0 < threshold for any ratio > 0 → SAMPLED at any ratio > 0
22
+ // HIGH: 0xffffffff ^ 0x00000000 ^ 0x00000000 ^ 0x00000000 = 0xffffffff
23
+ // → never below threshold for ratio < 1.0 → DROPPED at any ratio < 1
24
+ const LOW_TRACE_ID = "0000000000000000ffffffffffffffff";
25
+ const HIGH_TRACE_ID = "ffffffff000000000000000000000000";
11
26
 
12
- function decide(sampler: URLBasedSampler, path: string) {
27
+ function decide(sampler: URLBasedSampler, path: string, traceId = LOW_TRACE_ID) {
13
28
  return sampler.shouldSample(
14
29
  ROOT_CONTEXT,
15
- TRACE_ID,
30
+ traceId,
16
31
  "span-name",
17
32
  SpanKind.SERVER,
18
33
  { "url.path": path },
@@ -21,7 +36,28 @@ function decide(sampler: URLBasedSampler, path: string) {
21
36
  }
22
37
 
23
38
  describe("URLBasedSampler", () => {
24
- it("falls back to default ratio when no rule matches", () => {
39
+ it("exposes 0.1 as the framework-wide default sample ratio", () => {
40
+ expect(DEFAULT_SAMPLE_RATIO).toBe(0.1);
41
+ });
42
+
43
+ it("defaults to DEFAULT_SAMPLE_RATIO (0.1) when config omits `default`", () => {
44
+ const s = new URLBasedSampler();
45
+ // LOW_TRACE_ID accumulates to 0 — sampled at any ratio > 0, including 0.1.
46
+ expect(decide(s, "/anything").decision).toBe(SamplingDecision.RECORD_AND_SAMPLED);
47
+ // HIGH_TRACE_ID accumulates to ~uint32 max — dropped at 0.1, would be
48
+ // kept only at ratio ~= 1. This is the assertion that catches an
49
+ // accidental revert to the old `?? 1.0` fallback.
50
+ expect(decide(s, "/anything", HIGH_TRACE_ID).decision).toBe(SamplingDecision.NOT_RECORD);
51
+ });
52
+
53
+ it("explicit `default: 1` opts in to AlwaysOn (records every trace)", () => {
54
+ const s = new URLBasedSampler({ default: 1 });
55
+ expect(decide(s, "/anything", HIGH_TRACE_ID).decision).toBe(
56
+ SamplingDecision.RECORD_AND_SAMPLED,
57
+ );
58
+ });
59
+
60
+ it("falls back to provided default ratio when no rule matches", () => {
25
61
  const s = new URLBasedSampler({ default: 1.0 });
26
62
  expect(decide(s, "/anything").decision).toBe(SamplingDecision.RECORD_AND_SAMPLED);
27
63
  });
@@ -40,7 +76,7 @@ describe("URLBasedSampler", () => {
40
76
 
41
77
  it("falls back to default when no path attribute is present", () => {
42
78
  const s = new URLBasedSampler({ default: 1.0 });
43
- const result = s.shouldSample(ROOT_CONTEXT, TRACE_ID, "noop", SpanKind.INTERNAL, {}, []);
79
+ const result = s.shouldSample(ROOT_CONTEXT, LOW_TRACE_ID, "noop", SpanKind.INTERNAL, {}, []);
44
80
  expect(result.decision).toBe(SamplingDecision.RECORD_AND_SAMPLED);
45
81
  });
46
82
 
@@ -50,7 +86,7 @@ describe("URLBasedSampler", () => {
50
86
  rules: [{ pattern: "^/wanted", ratio: 1.0 }],
51
87
  });
52
88
  const ok = (attrs: Record<string, string>) =>
53
- s.shouldSample(ROOT_CONTEXT, TRACE_ID, "n", SpanKind.SERVER, attrs, []);
89
+ s.shouldSample(ROOT_CONTEXT, LOW_TRACE_ID, "n", SpanKind.SERVER, attrs, []);
54
90
 
55
91
  expect(ok({ "url.path": "/wanted/x" }).decision).toBe(SamplingDecision.RECORD_AND_SAMPLED);
56
92
  expect(ok({ "http.target": "/wanted/y" }).decision).toBe(SamplingDecision.RECORD_AND_SAMPLED);
@@ -103,18 +139,20 @@ describe("createUrlBasedHeadSampler", () => {
103
139
  expect(sampler).toBeInstanceOf(ParentBasedSampler);
104
140
  });
105
141
 
106
- it("applies the default-ratio = 1.0 when config is null", () => {
107
- // Smoke test only — sampler internals are validated above.
142
+ it("applies DEFAULT_SAMPLE_RATIO when config is null", () => {
108
143
  const sampler = createUrlBasedHeadSampler(null);
144
+ // High-accumulating trace ID is dropped at 0.1 — proves the ParentBased
145
+ // wrapper inherits the URLBasedSampler default and isn't accidentally
146
+ // forcing AlwaysOn.
109
147
  const result = sampler.shouldSample(
110
148
  ROOT_CONTEXT,
111
- TRACE_ID,
149
+ HIGH_TRACE_ID,
112
150
  "n",
113
151
  SpanKind.SERVER,
114
152
  { "url.path": "/" },
115
153
  [],
116
154
  );
117
- expect(result.decision).toBe(SamplingDecision.RECORD_AND_SAMPLED);
155
+ expect(result.decision).toBe(SamplingDecision.NOT_RECORD);
118
156
  });
119
157
  });
120
158
 
@@ -9,6 +9,13 @@
9
9
  * decision when one exists (i.e. distributed traces are kept consistent end
10
10
  * to end).
11
11
  *
12
+ * **Default ratio.** When no `default` is provided in the config (or the env
13
+ * var is unset entirely), the sampler keeps **10%** of traces. Production
14
+ * storefront traffic at full sampling will burn HyperDX ingest quotas
15
+ * quickly — for an unconfigured site we'd rather drop 90% than overspend by
16
+ * default. Sites that genuinely want every trace recorded must opt-in
17
+ * explicitly with `OTEL_SAMPLING_CONFIG` setting `default: 1`.
18
+ *
12
19
  * @example
13
20
  * ```jsonc
14
21
  * // base64-encode this and set as OTEL_SAMPLING_CONFIG:
@@ -41,12 +48,23 @@ export interface SamplingRule {
41
48
  }
42
49
 
43
50
  export interface SamplingConfig {
44
- /** Default sample ratio applied when no rule matches. Defaults to 1.0 (always sample). */
51
+ /**
52
+ * Default sample ratio applied when no rule matches. Defaults to **0.1**
53
+ * (10% sampled) when omitted. Set to `1` to record every trace
54
+ * (only do this when you need a full debug stream and accept the cost).
55
+ */
45
56
  default?: number;
46
57
  /** Ordered list of rules. First match wins. */
47
58
  rules?: SamplingRule[];
48
59
  }
49
60
 
61
+ /**
62
+ * Default ratio applied by `URLBasedSampler` when neither the config nor a
63
+ * matching rule specifies one. Centralised so tests + docs share a single
64
+ * source of truth.
65
+ */
66
+ export const DEFAULT_SAMPLE_RATIO = 0.1;
67
+
50
68
  interface CompiledRule {
51
69
  re: RegExp;
52
70
  sampler: Sampler;
@@ -61,7 +79,7 @@ export class URLBasedSampler implements Sampler {
61
79
  private readonly rules: CompiledRule[];
62
80
 
63
81
  constructor(config: SamplingConfig = {}) {
64
- this.defaultSampler = ratioToSampler(config.default ?? 1.0);
82
+ this.defaultSampler = ratioToSampler(config.default ?? DEFAULT_SAMPLE_RATIO);
65
83
  this.rules = (config.rules ?? []).map((rule) => ({
66
84
  re: new RegExp(rule.pattern),
67
85
  sampler: ratioToSampler(rule.ratio),
@@ -128,7 +146,7 @@ function extractPath(attrs: Attributes): string | null {
128
146
 
129
147
  /**
130
148
  * Decode a base64-encoded `OTEL_SAMPLING_CONFIG` value into a `SamplingConfig`.
131
- * Returns `null` (caller falls back to default ratio 1.0) on:
149
+ * Returns `null` (caller falls back to `DEFAULT_SAMPLE_RATIO`, currently 0.1) on:
132
150
  * - missing / empty input
133
151
  * - invalid base64
134
152
  * - JSON parse failure
@@ -31,7 +31,7 @@
31
31
  * export default defineConfig({ plugins: [decoVitePlugin(), ...] });
32
32
  * ```
33
33
  */
34
- import { readFileSync, existsSync } from "node:fs";
34
+ import { existsSync, readFileSync } from "node:fs";
35
35
 
36
36
  // Bare-specifier stubs resolved by ID before Vite touches them.
37
37
  /** @type {Record<string, string>} */
@@ -44,6 +44,23 @@ const CLIENT_STUBS = {
44
44
  "tanstack-start-injected-head-scripts:v": "\0stub:tanstack-head-scripts",
45
45
  };
46
46
 
47
+ // SSR-only stubs. Same mechanism as CLIENT_STUBS but applied to the worker
48
+ // SSR build instead of the browser build.
49
+ /** @type {Record<string, string>} */
50
+ const SSR_STUBS = {
51
+ // `@opentelemetry/resources` (transitively pulled in by sdk-logs /
52
+ // sdk-metrics / exporter-* OTel packages — five copies in node_modules due
53
+ // to OTel monorepo peer-dep version pinning) statically imports bare `fs`
54
+ // inside its node-platform machine-id detectors. We never call those
55
+ // detectors — `instrumentWorker` builds the OTel Resource from explicit
56
+ // attributes only — but Vite's CF Workers SSR resolver still walks the
57
+ // re-export barrel and chokes on the bare `fs` specifier (workerd's
58
+ // `nodejs_compat` only exposes the prefixed `node:fs`, not the legacy
59
+ // bare form). Stub it; the static import resolves and the unreachable
60
+ // detector code is never executed.
61
+ fs: "\0stub:bare-fs",
62
+ };
63
+
47
64
  // Minimal stub source for each virtual module.
48
65
  /** @type {Record<string, string>} */
49
66
  const STUB_SOURCE = {
@@ -72,13 +89,18 @@ const STUB_SOURCE = {
72
89
  "export default { AsyncLocalStorage: _ALS, AsyncResource, executionAsyncId, createHook };",
73
90
  ].join("\n"),
74
91
 
75
- "\0stub:tanstack-head-scripts":
76
- "export const injectedHeadScripts = undefined;",
92
+ "\0stub:tanstack-head-scripts": "export const injectedHeadScripts = undefined;",
77
93
 
78
94
  // The admin schema bundle is server-only — the client receives pre-resolved
79
95
  // blocks via the SSR payload. Stubbing it on the client cuts a large module
80
96
  // (typically 0.5-5 MB) out of the browser bundle.
81
97
  "\0stub:meta-gen": "export default {};",
98
+
99
+ // Bare `fs` shim — see SSR_STUBS comment above for the rationale. Surfaces
100
+ // just enough of `import { promises as fs } from 'fs'` to satisfy static
101
+ // module resolution; method calls would throw, but the OTel detector code
102
+ // path is unreachable from `instrumentWorker`.
103
+ "\0stub:bare-fs": "export const promises = {}; export default { promises };",
82
104
  };
83
105
 
84
106
  /** @returns {import("vite").PluginOption} */
@@ -89,6 +111,9 @@ export function decoVitePlugin() {
89
111
  enforce: "pre",
90
112
 
91
113
  resolveId(id, importer, options) {
114
+ // SSR-only stubs — must be checked first since the client guard below
115
+ // returns undefined for everything that hasn't matched yet on SSR.
116
+ if (options?.ssr && SSR_STUBS[id]) return SSR_STUBS[id];
92
117
  // Server builds keep the real modules.
93
118
  if (options?.ssr) return undefined;
94
119
  // Bare-specifier exact-match stubs (react-dom/server, node:stream, etc.).
@@ -98,10 +123,7 @@ export function decoVitePlugin() {
98
123
  // plugin works whether `setup.ts` imports the .json directly (current)
99
124
  // or a future variant routes through a generated .ts wrapper.
100
125
  // Requires `importer` so we don't accidentally stub the entry module.
101
- if (
102
- importer &&
103
- (id.endsWith("meta.gen.json") || id.endsWith("meta.gen.ts"))
104
- ) {
126
+ if (importer && (id.endsWith("meta.gen.json") || id.endsWith("meta.gen.ts"))) {
105
127
  return "\0stub:meta-gen";
106
128
  }
107
129
  return undefined;
@@ -154,7 +176,6 @@ export function decoVitePlugin() {
154
176
  const siteName = process.env.DECO_SITE_NAME;
155
177
  const envName = process.env.DECO_ENV_NAME;
156
178
  if (siteName && envName) {
157
-
158
179
  // Daemon files are .ts and live inside node_modules. Node's
159
180
  // experimental strip-types refuses to transpile node_modules, so
160
181
  // a plain dynamic `import()` blows up under `vite dev`. Use tsx's
@@ -214,18 +235,12 @@ export function decoVitePlugin() {
214
235
  rollupOptions: {
215
236
  output: {
216
237
  manualChunks(id) {
217
- if (
218
- id.includes("node_modules/react-dom") ||
219
- id.includes("node_modules/react/")
220
- ) {
238
+ if (id.includes("node_modules/react-dom") || id.includes("node_modules/react/")) {
221
239
  return "vendor-react";
222
240
  }
223
241
 
224
242
  // TanStack Router — client-side router (always needed)
225
- if (
226
- id.includes("@tanstack/react-router") ||
227
- id.includes("@tanstack/router-core")
228
- ) {
243
+ if (id.includes("@tanstack/react-router") || id.includes("@tanstack/router-core")) {
229
244
  return "vendor-router";
230
245
  }
231
246
 
@@ -275,8 +290,7 @@ export function decoVitePlugin() {
275
290
  configEnvironment(name, env) {
276
291
  if (name === "ssr" || name === "client") {
277
292
  env.optimizeDeps = env.optimizeDeps || {};
278
- env.optimizeDeps.esbuildOptions =
279
- env.optimizeDeps.esbuildOptions || {};
293
+ env.optimizeDeps.esbuildOptions = env.optimizeDeps.esbuildOptions || {};
280
294
  env.optimizeDeps.esbuildOptions.jsx = "automatic";
281
295
  env.optimizeDeps.esbuildOptions.jsxImportSource = "react";
282
296
  }
@@ -0,0 +1,54 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { decoVitePlugin } from "./plugin.js";
3
+
4
+ /**
5
+ * The Vite plugin's `resolveId` / `load` hooks are pure functions over their
6
+ * inputs, so we can exercise them without spinning up a Vite environment.
7
+ */
8
+
9
+ function getPlugin() {
10
+ const result = decoVitePlugin();
11
+ // decoVitePlugin returns a single plugin object today, but the type is
12
+ // `PluginOption` which permits arrays — handle both.
13
+ return Array.isArray(result) ? result[0] : result;
14
+ }
15
+
16
+ describe("decoVitePlugin SSR stubs", () => {
17
+ it("rewrites bare `fs` to a virtual module on SSR", () => {
18
+ const p = getPlugin();
19
+ const id = p.resolveId.call({}, "fs", undefined, { ssr: true });
20
+ expect(id).toBe("\0stub:bare-fs");
21
+ });
22
+
23
+ it("does NOT rewrite bare `fs` on client (browser builds don't import fs)", () => {
24
+ const p = getPlugin();
25
+ const id = p.resolveId.call({}, "fs", undefined, { ssr: false });
26
+ expect(id).toBeUndefined();
27
+ });
28
+
29
+ it("loads an empty surface for the bare-fs virtual module", () => {
30
+ const p = getPlugin();
31
+ const src = p.load.call({}, "\0stub:bare-fs", { ssr: true });
32
+ expect(src).toContain("export const promises = {}");
33
+ expect(src).toContain("export default");
34
+ });
35
+
36
+ it("does not interfere with real SSR modules", () => {
37
+ const p = getPlugin();
38
+ expect(p.resolveId.call({}, "@decocms/start/cms", undefined, { ssr: true })).toBeUndefined();
39
+ });
40
+ });
41
+
42
+ describe("decoVitePlugin client stubs (regression guard)", () => {
43
+ it("still rewrites node:async_hooks on the client build", () => {
44
+ const p = getPlugin();
45
+ const id = p.resolveId.call({}, "node:async_hooks", undefined, { ssr: false });
46
+ expect(id).toBe("\0stub:node-async-hooks");
47
+ });
48
+
49
+ it("does not rewrite client stubs on SSR", () => {
50
+ const p = getPlugin();
51
+ const id = p.resolveId.call({}, "react-dom/server", undefined, { ssr: true });
52
+ expect(id).toBeUndefined();
53
+ });
54
+ });