@decocms/blocks 8.1.0-next.0 → 8.1.0-next.1

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 (114) hide show
  1. package/package.json +6 -92
  2. package/src/index.ts +2 -12
  3. package/src/protocol/storage/memory.ts +1 -1
  4. package/src/v8/background.ts +3 -3
  5. package/src/v8/builtins/legacy.ts +1 -1
  6. package/src/v8/cli/index.ts +1 -1
  7. package/src/v8/fetch.ts +8 -27
  8. package/src/v8/remoteLoader.ts +1 -1
  9. package/src/v8/telemetry.ts +1 -1
  10. package/src/cms/applySectionConventions.ts +0 -148
  11. package/src/cms/blockSource.ts +0 -228
  12. package/src/cms/client.ts +0 -85
  13. package/src/cms/deferredTrigger.ts +0 -58
  14. package/src/cms/draftSource.ts +0 -476
  15. package/src/cms/index.ts +0 -180
  16. package/src/cms/loadDecofileDirectory.ts +0 -89
  17. package/src/cms/loader.ts +0 -563
  18. package/src/cms/registry.ts +0 -264
  19. package/src/cms/renderJson.ts +0 -179
  20. package/src/cms/resolve.ts +0 -2583
  21. package/src/cms/schema.ts +0 -1219
  22. package/src/cms/sectionLoaderContext.ts +0 -113
  23. package/src/cms/sectionLoaders.ts +0 -686
  24. package/src/cms/sectionMixins.ts +0 -153
  25. package/src/flags/audience.ts +0 -56
  26. package/src/flags/everyone.ts +0 -29
  27. package/src/flags/flag.ts +0 -15
  28. package/src/flags/multivariate/image.ts +0 -11
  29. package/src/flags/multivariate/message.ts +0 -11
  30. package/src/flags/multivariate/page.ts +0 -16
  31. package/src/flags/multivariate/section.ts +0 -16
  32. package/src/flags/multivariate.ts +0 -1
  33. package/src/flags/types.ts +0 -59
  34. package/src/flags/utils/multivariate.ts +0 -20
  35. package/src/hooks/Image.tsx +0 -314
  36. package/src/hooks/JsonLd.tsx +0 -353
  37. package/src/hooks/LazySection.tsx +0 -121
  38. package/src/hooks/LiveControls.tsx +0 -144
  39. package/src/hooks/Picture.tsx +0 -127
  40. package/src/hooks/RenderSection.tsx +0 -91
  41. package/src/hooks/SectionErrorFallback.tsx +0 -97
  42. package/src/hooks/Stats.tsx +0 -134
  43. package/src/hooks/index.ts +0 -35
  44. package/src/hooks/useLoadMore.ts +0 -100
  45. package/src/matchers/builtins.ts +0 -459
  46. package/src/matchers/countryNames.ts +0 -104
  47. package/src/matchers/override.ts +0 -136
  48. package/src/matchers/posthog.ts +0 -154
  49. package/src/middleware/decoState.ts +0 -55
  50. package/src/middleware/healthMetrics.ts +0 -133
  51. package/src/middleware/hydrationContext.ts +0 -79
  52. package/src/middleware/index.ts +0 -88
  53. package/src/middleware/liveness.ts +0 -21
  54. package/src/middleware/observability.ts +0 -800
  55. package/src/middleware/validateSection.ts +0 -100
  56. package/src/preview/DraftPreviewBadge.tsx +0 -306
  57. package/src/preview/decoMark.ts +0 -11
  58. package/src/preview/index.ts +0 -8
  59. package/src/sdk/abTesting.ts +0 -556
  60. package/src/sdk/analytics.ts +0 -147
  61. package/src/sdk/cacheHeaders.ts +0 -633
  62. package/src/sdk/cacheStorage.ts +0 -287
  63. package/src/sdk/cachedLoader.ts +0 -556
  64. package/src/sdk/clx.ts +0 -5
  65. package/src/sdk/cn.ts +0 -28
  66. package/src/sdk/composite.ts +0 -114
  67. package/src/sdk/cookie.ts +0 -129
  68. package/src/sdk/crypto.ts +0 -199
  69. package/src/sdk/csp.ts +0 -59
  70. package/src/sdk/deepOmit.ts +0 -52
  71. package/src/sdk/detectDevice.ts +0 -45
  72. package/src/sdk/djb2.ts +0 -20
  73. package/src/sdk/encoding.ts +0 -44
  74. package/src/sdk/env.ts +0 -54
  75. package/src/sdk/experiments.ts +0 -314
  76. package/src/sdk/fetchCache.ts +0 -269
  77. package/src/sdk/fetchTimeout.ts +0 -58
  78. package/src/sdk/flags.ts +0 -138
  79. package/src/sdk/http.ts +0 -124
  80. package/src/sdk/index.ts +0 -97
  81. package/src/sdk/inflightTimeout.ts +0 -53
  82. package/src/sdk/instrumentedFetch.ts +0 -362
  83. package/src/sdk/invoke.ts +0 -298
  84. package/src/sdk/logger.ts +0 -304
  85. package/src/sdk/mergeCacheControl.ts +0 -150
  86. package/src/sdk/nonce.ts +0 -46
  87. package/src/sdk/normalizeUrls.ts +0 -91
  88. package/src/sdk/observability.ts +0 -116
  89. package/src/sdk/otel.ts +0 -1118
  90. package/src/sdk/otelAdapters/clickhouseCollector.ts +0 -65
  91. package/src/sdk/otelAdapters.ts +0 -144
  92. package/src/sdk/otelHttpLog.ts +0 -419
  93. package/src/sdk/otelHttpMeter.ts +0 -532
  94. package/src/sdk/otelHttpTracer.ts +0 -543
  95. package/src/sdk/redirects.ts +0 -336
  96. package/src/sdk/requestContext.ts +0 -281
  97. package/src/sdk/requestContextStorage.browser.ts +0 -43
  98. package/src/sdk/requestContextStorage.ts +0 -35
  99. package/src/sdk/responseCache.ts +0 -82
  100. package/src/sdk/retry.ts +0 -45
  101. package/src/sdk/serverTimings.ts +0 -68
  102. package/src/sdk/signal.ts +0 -42
  103. package/src/sdk/sitemap.ts +0 -160
  104. package/src/sdk/urlRedaction.ts +0 -82
  105. package/src/sdk/urlUtils.ts +0 -183
  106. package/src/sdk/useDevice.ts +0 -89
  107. package/src/sdk/useDeviceContext.tsx +0 -108
  108. package/src/sdk/useId.ts +0 -7
  109. package/src/sdk/useScript.ts +0 -210
  110. package/src/sdk/useSuggestions.ts +0 -188
  111. package/src/sdk/wrapCaughtErrors.ts +0 -107
  112. package/src/setup.ts +0 -120
  113. package/src/types/index.ts +0 -53
  114. package/src/types/widgets.ts +0 -14
@@ -1,114 +0,0 @@
1
- /**
2
- * Composite adapters — fan out to multiple backends with try/catch isolation.
3
- *
4
- * Used by `instrumentWorker()` so the same logger/meter can dual-emit to
5
- * (e.g.) console-JSON + OTLP, or AE + OTLP, without any one backend's
6
- * failure taking down the others.
7
- *
8
- * The "always include console-JSON logger" guarantee in the observability
9
- * plan relies on this: even if HyperDX is down, the local console adapter
10
- * still records the line.
11
- */
12
-
13
- import type { MeterAdapter } from "../middleware/observability";
14
- import type { LoggerAdapter, LogLevel } from "./logger";
15
-
16
- type Labels = Record<string, string | number | boolean>;
17
-
18
- // ---------------------------------------------------------------------------
19
- // Logger
20
- // ---------------------------------------------------------------------------
21
-
22
- /**
23
- * Returns a single LoggerAdapter that fans every call out to all
24
- * provided adapters. Falsy entries (e.g. `otelEnabled ? otelAdapter : null`)
25
- * are filtered out so call sites can write:
26
- *
27
- * ```ts
28
- * createCompositeLogger([defaultLoggerAdapter, otelEnabled ? otelLogger : null]);
29
- * ```
30
- *
31
- * Each downstream `.log()` call is isolated in try/catch so a thrown
32
- * error in one backend cannot suppress the others.
33
- */
34
- export function createCompositeLogger(
35
- adapters: Array<LoggerAdapter | null | undefined | false>,
36
- ): LoggerAdapter {
37
- const list = adapters.filter((a): a is LoggerAdapter => Boolean(a));
38
-
39
- if (list.length === 1) return list[0];
40
-
41
- return {
42
- log(level: LogLevel, msg: string, attrs?: Record<string, unknown>) {
43
- for (const adapter of list) {
44
- try {
45
- adapter.log(level, msg, attrs);
46
- } catch (error) {
47
- // Use console.error directly — calling logger here would recurse.
48
- try {
49
- console.error("[composite-logger] adapter failed", String(error));
50
- } catch {
51
- /* swallow */
52
- }
53
- }
54
- }
55
- },
56
- };
57
- }
58
-
59
- // ---------------------------------------------------------------------------
60
- // Meter
61
- // ---------------------------------------------------------------------------
62
-
63
- /**
64
- * Returns a single MeterAdapter that fans counter/gauge/histogram writes
65
- * out to all provided meters. Same semantics as `createCompositeLogger`:
66
- * falsy entries are dropped, each downstream call is try/catch isolated.
67
- */
68
- export function createCompositeMeter(
69
- adapters: Array<MeterAdapter | null | undefined | false>,
70
- ): MeterAdapter {
71
- const list = adapters.filter((a): a is MeterAdapter => Boolean(a));
72
-
73
- if (list.length === 1) return list[0];
74
-
75
- return {
76
- counterInc(name: string, value?: number, labels?: Labels) {
77
- for (const m of list) {
78
- try {
79
- m.counterInc(name, value, labels);
80
- } catch (error) {
81
- warn("counterInc", name, error);
82
- }
83
- }
84
- },
85
- gaugeSet(name: string, value: number, labels?: Labels) {
86
- for (const m of list) {
87
- if (!m.gaugeSet) continue;
88
- try {
89
- m.gaugeSet(name, value, labels);
90
- } catch (error) {
91
- warn("gaugeSet", name, error);
92
- }
93
- }
94
- },
95
- histogramRecord(name: string, value: number, labels?: Labels) {
96
- for (const m of list) {
97
- if (!m.histogramRecord) continue;
98
- try {
99
- m.histogramRecord(name, value, labels);
100
- } catch (error) {
101
- warn("histogramRecord", name, error);
102
- }
103
- }
104
- },
105
- };
106
- }
107
-
108
- function warn(op: string, metric: string, error: unknown) {
109
- try {
110
- console.error(`[composite-meter] ${op}(${metric}) adapter failed`, String(error));
111
- } catch {
112
- /* swallow */
113
- }
114
- }
package/src/sdk/cookie.ts DELETED
@@ -1,129 +0,0 @@
1
- export function getCookie(name: string): string {
2
- return (
3
- globalThis.window?.document?.cookie?.split("; ").reduce((r, v) => {
4
- const parts = v.split("=");
5
- return parts[0] === name ? decodeURIComponent(parts[1]) : r;
6
- }, "") ?? ""
7
- );
8
- }
9
-
10
- export function setCookie(name: string, value: string, days: number) {
11
- const expires = new Date(Date.now() + days * 864e5).toUTCString();
12
- if (globalThis?.window?.document) {
13
- globalThis.window.document.cookie =
14
- name + "=" + encodeURIComponent(value) + "; expires=" + expires + "; path=/";
15
- }
16
- }
17
-
18
- export function deleteCookie(name: string) {
19
- if (globalThis?.window?.document) {
20
- globalThis.window.document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
21
- }
22
- }
23
-
24
- export function getServerSideCookie(req: Request, name: string): string {
25
- const cookie = req.headers
26
- .get("cookie")
27
- ?.split(";")
28
- .find((c) => c.trim().startsWith(name))
29
- ?.split("=")[1];
30
- return cookie ? decodeURIComponent(cookie) : "";
31
- }
32
-
33
- export function decodeCookie(cookieValue: string): any {
34
- try {
35
- return JSON.parse(decodeURIComponent(cookieValue));
36
- } catch {
37
- return null;
38
- }
39
- }
40
-
41
- // ---------------------------------------------------------------------------
42
- // Server-side cookie helpers — Web-platform / Workers-friendly.
43
- //
44
- // These mirror the surface area of Deno's `@std/http/cookie`, which deco
45
- // storefronts depended on heavily before TanStack/Workers migration. Sites
46
- // can now import from "@decocms/start/sdk/cookie" instead of shipping a
47
- // per-site shim or pulling JSR.
48
- // ---------------------------------------------------------------------------
49
-
50
- export interface Cookie {
51
- name: string;
52
- value: string;
53
- expires?: Date | number;
54
- maxAge?: number;
55
- domain?: string;
56
- path?: string;
57
- secure?: boolean;
58
- httpOnly?: boolean;
59
- sameSite?: "Strict" | "Lax" | "None";
60
- }
61
-
62
- /**
63
- * Parse all cookies from a Request's `Cookie` header into a plain object.
64
- * Returns `{}` when no cookies are present. Values are URL-decoded.
65
- *
66
- * Equivalent to `getCookies(req.headers)` from `@std/http/cookie`.
67
- */
68
- export function getCookies(headers: Headers): Record<string, string> {
69
- const cookie = headers.get("cookie");
70
- if (!cookie) return {};
71
- const out: Record<string, string> = {};
72
- for (const pair of cookie.split(/;\s*/)) {
73
- const eq = pair.indexOf("=");
74
- if (eq === -1) continue;
75
- const name = pair.slice(0, eq).trim();
76
- if (!name) continue;
77
- const value = pair.slice(eq + 1).trim();
78
- try {
79
- out[name] = decodeURIComponent(value);
80
- } catch {
81
- out[name] = value;
82
- }
83
- }
84
- return out;
85
- }
86
-
87
- /**
88
- * Serialize a cookie spec and append a `Set-Cookie` header to a Response's
89
- * `Headers`. Equivalent to `setCookie(headers, cookie)` from `@std/http/cookie`.
90
- *
91
- * Note: this uses `headers.append`, not `set`, so multiple cookies stack
92
- * correctly (a single `Set-Cookie` header cannot represent multiple cookies).
93
- */
94
- export function setResponseCookie(headers: Headers, cookie: Cookie): void {
95
- const parts = [`${cookie.name}=${cookie.value}`];
96
- if (cookie.expires !== undefined) {
97
- const date = cookie.expires instanceof Date
98
- ? cookie.expires
99
- : new Date(cookie.expires);
100
- parts.push(`Expires=${date.toUTCString()}`);
101
- }
102
- if (cookie.maxAge !== undefined) parts.push(`Max-Age=${cookie.maxAge}`);
103
- if (cookie.domain) parts.push(`Domain=${cookie.domain}`);
104
- if (cookie.path) parts.push(`Path=${cookie.path}`);
105
- if (cookie.secure) parts.push("Secure");
106
- if (cookie.httpOnly) parts.push("HttpOnly");
107
- if (cookie.sameSite) parts.push(`SameSite=${cookie.sameSite}`);
108
- headers.append("Set-Cookie", parts.join("; "));
109
- }
110
-
111
- /**
112
- * Append a delete instruction (`Max-Age=0` + epoch `Expires`) for a cookie.
113
- * `path` and `domain` should match the original `setResponseCookie` call to
114
- * actually clear the cookie in the browser.
115
- */
116
- export function deleteResponseCookie(
117
- headers: Headers,
118
- name: string,
119
- attributes: { path?: string; domain?: string } = {},
120
- ): void {
121
- setResponseCookie(headers, {
122
- name,
123
- value: "",
124
- expires: new Date(0),
125
- maxAge: 0,
126
- path: attributes.path,
127
- domain: attributes.domain,
128
- });
129
- }
package/src/sdk/crypto.ts DELETED
@@ -1,199 +0,0 @@
1
- /**
2
- * Secret decryption for CMS encrypted values.
3
- *
4
- * CMS blocks store sensitive values (API keys, tokens) encrypted with AES-CBC.
5
- * The encryption key is stored in the DECO_CRYPTO_KEY environment variable
6
- * as a base64-encoded JSON: { key: number[], iv: number[] }
7
- *
8
- * Usage:
9
- * import { decryptSecret, resolveSecret } from "@decocms/start/sdk/crypto";
10
- *
11
- * // Decrypt a hex-encoded encrypted string
12
- * const apiKey = await decryptSecret("888fafd937dd...");
13
- *
14
- * // Or resolve a CMS secret block (handles all formats)
15
- * const apiKey = await resolveSecret(block.apiKey, "RESEND_API_KEY");
16
- */
17
-
18
- import { getRuntimeEnv } from "./otelAdapters";
19
-
20
- const textDecoder = new TextDecoder();
21
- const textEncoder = new TextEncoder();
22
-
23
- // Cache the imported key
24
- let cachedKey: Promise<{ key: CryptoKey; iv: Uint8Array }> | null = null;
25
-
26
- function hexToBytes(hex: string): Uint8Array {
27
- const bytes = new Uint8Array(hex.length / 2);
28
- for (let i = 0; i < hex.length; i += 2) {
29
- bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16);
30
- }
31
- return bytes;
32
- }
33
-
34
- /**
35
- * Get the AES key from DECO_CRYPTO_KEY environment variable.
36
- * Returns null if not set.
37
- */
38
- function getKeyFromEnv(): Promise<{ key: CryptoKey; iv: Uint8Array }> | null {
39
- const envKey = getEnvVar("DECO_CRYPTO_KEY");
40
- if (!envKey) return null;
41
-
42
- return cachedKey ??= (async () => {
43
- const parsed = JSON.parse(atob(envKey));
44
- const keyBytes = new Uint8Array(
45
- Array.isArray(parsed.key) ? parsed.key : Object.values(parsed.key),
46
- );
47
- const iv = new Uint8Array(
48
- Array.isArray(parsed.iv) ? parsed.iv : Object.values(parsed.iv),
49
- );
50
-
51
- const importedKey = await crypto.subtle.importKey(
52
- "raw",
53
- keyBytes.buffer,
54
- "AES-CBC",
55
- false,
56
- ["decrypt"],
57
- );
58
-
59
- return { key: importedKey, iv };
60
- })();
61
- }
62
-
63
- /**
64
- * Check if the crypto key is available.
65
- */
66
- export function hasCryptoKey(): boolean {
67
- return !!getEnvVar("DECO_CRYPTO_KEY");
68
- }
69
-
70
- /**
71
- * Decrypt a hex-encoded AES-CBC encrypted string.
72
- * Requires DECO_CRYPTO_KEY environment variable.
73
- *
74
- * @returns The decrypted string, or null if decryption fails.
75
- */
76
- export async function decryptSecret(encryptedHex: string): Promise<string | null> {
77
- const keyPromise = getKeyFromEnv();
78
- if (!keyPromise) {
79
- return null;
80
- }
81
-
82
- try {
83
- const { key, iv } = await keyPromise;
84
- const encryptedBytes = hexToBytes(encryptedHex);
85
- const decrypted = await crypto.subtle.decrypt(
86
- { name: "AES-CBC", iv } as AesCbcParams,
87
- key,
88
- encryptedBytes as unknown as BufferSource,
89
- );
90
- return textDecoder.decode(new Uint8Array(decrypted));
91
- } catch (e) {
92
- console.warn("[crypto] Failed to decrypt secret:", (e as Error).message);
93
- return null;
94
- }
95
- }
96
-
97
- // In-memory cache for resolved secrets
98
- const secretCache = new Map<string, string | null>();
99
-
100
- /**
101
- * Resolve a CMS secret value from multiple sources.
102
- *
103
- * Resolution order:
104
- * 1. Plain string → use directly
105
- * 2. Object with .get() → call .get() (old Secret loader pattern)
106
- * 3. Object with .encrypted → decrypt using DECO_CRYPTO_KEY
107
- * 4. Environment variable (envVarName) → fallback
108
- *
109
- * @param value - The secret value from CMS block (string | { encrypted } | { get })
110
- * @param envVarName - Optional env var name to use as fallback (e.g. "RESEND_API_KEY")
111
- * @returns The resolved secret string, or null if not available
112
- */
113
- export async function resolveSecret(
114
- value: unknown,
115
- envVarName?: string,
116
- ): Promise<string | null> {
117
- // 1. Plain string
118
- if (typeof value === "string" && value.length > 0) {
119
- return value;
120
- }
121
-
122
- if (value && typeof value === "object") {
123
- const obj = value as Record<string, any>;
124
-
125
- // 2. Secret object with .get()
126
- if (typeof obj.get === "function") {
127
- const result = obj.get();
128
- if (typeof result === "string" && result.length > 0) return result;
129
- }
130
-
131
- // 3. Encrypted secret
132
- if (typeof obj.encrypted === "string" && obj.encrypted.length > 0) {
133
- const cacheKey = obj.encrypted;
134
- if (secretCache.has(cacheKey)) return secretCache.get(cacheKey)!;
135
-
136
- const decrypted = await decryptSecret(obj.encrypted);
137
- // Only cache successful decryptions — null would block env var fallback
138
- if (decrypted) {
139
- secretCache.set(cacheKey, decrypted);
140
- return decrypted;
141
- }
142
- }
143
- }
144
-
145
- // 4. Environment variable fallback
146
- if (envVarName) {
147
- const envValue = getEnvVar(envVarName);
148
- if (envValue) return envValue;
149
- }
150
-
151
- return null;
152
- }
153
-
154
- /**
155
- * Get an environment variable, checking process.env first, then .dev.vars file,
156
- * then the Cloudflare Workers `env` binding stashed in RequestContext.
157
- * Cloudflare Workers dev mode stores env vars in .dev.vars but they're only
158
- * accessible via the `env` binding inside request handlers. During setup.ts
159
- * (module-level init), we need to read the file directly. In production/preview
160
- * there is no .dev.vars and no process.env — the only source is the `env` object
161
- * passed to the fetch handler, which workerEntry.ts stashes via setRuntimeEnv().
162
- */
163
- function getEnvVar(name: string): string | undefined {
164
- // 1. process.env (works in Node, may work in Workers with nodejs_compat)
165
- if (typeof process !== "undefined" && process.env?.[name]) {
166
- return process.env[name];
167
- }
168
-
169
- // 2. Read .dev.vars file (Cloudflare Workers dev mode)
170
- try {
171
- const fs = require("node:fs");
172
- const path = require("node:path");
173
- const devVarsPath = path.resolve(".dev.vars");
174
- if (fs.existsSync(devVarsPath)) {
175
- const content = fs.readFileSync(devVarsPath, "utf-8");
176
- for (const line of content.split("\n")) {
177
- const trimmed = line.trim();
178
- if (trimmed.startsWith("#") || !trimmed.includes("=")) continue;
179
- const eqIdx = trimmed.indexOf("=");
180
- const key = trimmed.slice(0, eqIdx).trim();
181
- const val = trimmed.slice(eqIdx + 1).trim();
182
- if (key === name) return val;
183
- }
184
- }
185
- } catch {
186
- // fs not available (e.g., pure Worker runtime) — ignore
187
- }
188
-
189
- // 3. CF Workers `env` binding, stashed per-request in RequestContext by
190
- // workerEntry.ts's setRuntimeEnv(env). This is the ONLY source in a real
191
- // Workers production/preview deploy (no process.env, no .dev.vars). Returns
192
- // undefined at module-init time (no active request) — that's why apps are
193
- // re-configured on the first request via reconfigureAppsOnce().
194
- const runtimeEnv = getRuntimeEnv();
195
- const v = runtimeEnv?.[name];
196
- if (typeof v === "string" && v) return v;
197
-
198
- return undefined;
199
- }
package/src/sdk/csp.ts DELETED
@@ -1,59 +0,0 @@
1
- /**
2
- * Content Security Policy header utilities.
3
- *
4
- * Sets frame-ancestors to allow the Deco admin to embed the
5
- * storefront in an iframe for live preview.
6
- */
7
-
8
- const DEFAULT_ADMIN_ORIGINS = ["https://admin.deco.cx", "https://deco.cx", "https://localhost:*"];
9
-
10
- export interface CSPOptions {
11
- /** Additional origins allowed to frame the storefront. */
12
- extraOrigins?: string[];
13
- /**
14
- * Deco admin origins. Defaults to admin.deco.cx + localhost.
15
- * Set to empty array to disallow all external framing.
16
- */
17
- adminOrigins?: string[];
18
- }
19
-
20
- /**
21
- * Set Content-Security-Policy frame-ancestors header on a Response.
22
- *
23
- * This is required for the Deco admin live preview iframe to work.
24
- * Also removes X-Frame-Options if present (CSP supersedes it).
25
- *
26
- * @example
27
- * ```ts
28
- * import { setCSPHeaders } from "@decocms/start/sdk/csp";
29
- *
30
- * // In middleware:
31
- * const response = await next();
32
- * setCSPHeaders(response);
33
- * return response;
34
- * ```
35
- */
36
- export function setCSPHeaders(response: Response, options?: CSPOptions): void {
37
- const origins = [
38
- "'self'",
39
- ...(options?.adminOrigins ?? DEFAULT_ADMIN_ORIGINS),
40
- ...(options?.extraOrigins ?? []),
41
- ];
42
-
43
- response.headers.set("Content-Security-Policy", `frame-ancestors ${origins.join(" ")}`);
44
-
45
- response.headers.delete("X-Frame-Options");
46
- }
47
-
48
- /**
49
- * Build the CSP header value string without applying it.
50
- * Useful when constructing headers in route definitions.
51
- */
52
- export function buildCSPHeaderValue(options?: CSPOptions): string {
53
- const origins = [
54
- "'self'",
55
- ...(options?.adminOrigins ?? DEFAULT_ADMIN_ORIGINS),
56
- ...(options?.extraOrigins ?? []),
57
- ];
58
- return `frame-ancestors ${origins.join(" ")}`;
59
- }
@@ -1,52 +0,0 @@
1
- /**
2
- * deepOmit — immutably remove dotted paths from an object tree.
3
- *
4
- * Used by section `renderJson` projections to trim a section's props before it
5
- * is serialized for the mobile app (the ?renderJson page-as-JSON path):
6
- *
7
- * ```ts
8
- * export const renderJson = (props: SectionProps<typeof loader>) =>
9
- * deepOmit(props, "storeConfig", "page.seo", "page.productsMap.*.hasFetchedSimilars");
10
- * ```
11
- *
12
- * Semantics:
13
- * - Top-level key: `deepOmit(o, "seoProps")`.
14
- * - Nested path (dot-separated): `deepOmit(o, "page.seo")`.
15
- * - Wildcard `*`: fans the remaining path over every array element OR record
16
- * value — `"page.productsMap.*.hasFetchedSimilars"` strips `hasFetchedSimilars`
17
- * from every value of `productsMap`.
18
- * - Arrays without an explicit `*`: the path auto-applies to each element and the
19
- * array shape is preserved.
20
- * - Missing key: a no-op — never fabricates an `undefined` branch.
21
- *
22
- * Pure: spreads/copies at each level, never mutates the input.
23
- */
24
- const omitAtPath = (obj: unknown, parts: string[]): unknown => {
25
- if (!obj || typeof obj !== "object" || parts.length === 0) return obj;
26
- const [key, ...rest] = parts;
27
-
28
- // `*` fans the remaining path out over every array element / record value.
29
- if (key === "*") {
30
- if (Array.isArray(obj)) return obj.map((v) => omitAtPath(v, rest));
31
- return Object.fromEntries(
32
- Object.entries(obj as Record<string, unknown>).map(([k, v]) => [k, omitAtPath(v, rest)]),
33
- );
34
- }
35
- // Preserve array shape: apply the same path to each element.
36
- if (Array.isArray(obj)) return obj.map((v) => omitAtPath(v, parts));
37
-
38
- const current = obj as Record<string, unknown>;
39
- if (rest.length === 0) {
40
- const copy = { ...current };
41
- delete copy[key];
42
- return copy;
43
- }
44
- if (!(key in current)) return current; // absent path = no-op, never creates undefined branches
45
- return { ...current, [key]: omitAtPath(current[key], rest) };
46
- };
47
-
48
- export const deepOmit = <T extends object>(obj: T, ...paths: string[]): T => {
49
- let result: unknown = obj;
50
- for (const path of paths) result = omitAtPath(result, path.split("."));
51
- return result as T;
52
- };
@@ -1,45 +0,0 @@
1
- /**
2
- * Pure User-Agent device detection — no React, no RequestContext, no
3
- * side effects. Import from HERE (not `./useDevice`) in any module that can
4
- * end up in a Next.js App Router **route handler** graph.
5
- *
6
- * Why this file exists: `useDevice.ts` re-exports the `"use client"`
7
- * context half (`./useDeviceContext`, which calls `createContext` at module
8
- * scope) for backward compatibility. That re-export is harmless in Server
9
- * Components — Next honors the `"use client"` boundary there — but route
10
- * handlers (App Router route.ts files) have NO client graph: the directive
11
- * is ignored, the module executes against Next's vendored **RSC** React
12
- * (`vendored/rsc/react.js`), and that build has no `createContext`, so the
13
- * whole route module crashes at evaluation time
14
- * ("...createContext is not a function"). `@decocms/nextjs`'s admin route
15
- * handlers reach device detection via `cms/sectionMixins.ts`
16
- * (`detectDevice`) and `sdk/requestContext.ts` (`isMobileUA`) — both now
17
- * import this leaf so their graphs never touch the client context file.
18
- */
19
-
20
- export type Device = "mobile" | "tablet" | "desktop";
21
-
22
- // Android phones include "Mobile" in their UA; Android tablets do not.
23
- // Check TABLET_RE first so `android(?!.*mobile)` captures tablets before
24
- // the MOBILE_RE `android.*mobile` branch matches phones.
25
- export const MOBILE_RE = /mobile|android.*mobile|iphone|ipod|webos|blackberry|opera mini|iemobile/i;
26
- export const TABLET_RE = /ipad|tablet|kindle|silk|playbook|android(?!.*mobile)/i;
27
-
28
- /**
29
- * Simple mobile-or-not check (mobile + tablet = true).
30
- * Use this for cache key splitting or any context where you
31
- * only need a mobile/desktop binary decision.
32
- */
33
- export function isMobileUA(userAgent: string): boolean {
34
- return MOBILE_RE.test(userAgent) || TABLET_RE.test(userAgent);
35
- }
36
-
37
- /**
38
- * Detect device type from a User-Agent string.
39
- * Pure function — no side effects, works anywhere.
40
- */
41
- export function detectDevice(userAgent: string): Device {
42
- if (TABLET_RE.test(userAgent)) return "tablet";
43
- if (MOBILE_RE.test(userAgent)) return "mobile";
44
- return "desktop";
45
- }
package/src/sdk/djb2.ts DELETED
@@ -1,20 +0,0 @@
1
- /**
2
- * DJB2 hash — a fast, non-cryptographic hash function.
3
- *
4
- * Used for ETags, cache keys, and content fingerprinting throughout the framework.
5
- * Produces consistent unsigned 32-bit integers.
6
- */
7
-
8
- /** Compute a DJB2 hash and return the raw unsigned 32-bit integer. */
9
- export function djb2(str: string): number {
10
- let hash = 5381;
11
- for (let i = 0; i < str.length; i++) {
12
- hash = ((hash << 5) + hash + str.charCodeAt(i)) | 0;
13
- }
14
- return hash >>> 0;
15
- }
16
-
17
- /** Compute a DJB2 hash and return a base-36 string. */
18
- export function djb2Hex(str: string): string {
19
- return djb2(str).toString(36);
20
- }
@@ -1,44 +0,0 @@
1
- /**
2
- * Web-platform base64 / base64url helpers.
3
- *
4
- * Replaces the surface area of Deno's `@std/encoding/base64` so deco
5
- * storefronts on TanStack/Workers can drop the per-site shim.
6
- *
7
- * All implementations use the global `btoa` / `atob` (available in Workers,
8
- * browsers, and Node 16+) so there is zero runtime dependency.
9
- */
10
-
11
- function toBytes(data: ArrayBuffer | Uint8Array | string): Uint8Array {
12
- if (typeof data === "string") return new TextEncoder().encode(data);
13
- if (data instanceof ArrayBuffer) return new Uint8Array(data);
14
- return data;
15
- }
16
-
17
- export function encodeBase64(data: ArrayBuffer | Uint8Array | string): string {
18
- const bytes = toBytes(data);
19
- // Build the binary string in chunks to avoid blowing the call stack on
20
- // large inputs (`String.fromCharCode(...bytes)` spreads the entire array).
21
- let bin = "";
22
- const CHUNK = 0x8000;
23
- for (let i = 0; i < bytes.byteLength; i += CHUNK) {
24
- bin += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
25
- }
26
- return btoa(bin);
27
- }
28
-
29
- export function decodeBase64(b64: string): Uint8Array<ArrayBuffer> {
30
- const bin = atob(b64);
31
- const out = new Uint8Array(bin.length);
32
- for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
33
- return out;
34
- }
35
-
36
- export function encodeBase64Url(data: ArrayBuffer | Uint8Array | string): string {
37
- return encodeBase64(data).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
38
- }
39
-
40
- export function decodeBase64Url(b64url: string): Uint8Array {
41
- const padded = b64url.replace(/-/g, "+").replace(/_/g, "/");
42
- const padLen = (4 - (padded.length % 4)) % 4;
43
- return decodeBase64(padded + "=".repeat(padLen));
44
- }