@decocms/blocks 8.0.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 (220) hide show
  1. package/bin/deco.js +13 -0
  2. package/package.json +32 -82
  3. package/src/index.ts +35 -8
  4. package/src/protocol/assets.ts +124 -0
  5. package/src/protocol/canonical.ts +7 -0
  6. package/src/protocol/ciphertext.ts +6 -0
  7. package/src/protocol/client.ts +170 -0
  8. package/src/protocol/conformance/cases/assets.ts +81 -0
  9. package/src/protocol/conformance/cases/guards.ts +314 -0
  10. package/src/protocol/conformance/cases/reads.ts +168 -0
  11. package/src/protocol/conformance/cases/types.ts +9 -0
  12. package/src/protocol/conformance/cases/wire.ts +138 -0
  13. package/src/protocol/conformance/cases/writes.ts +345 -0
  14. package/src/protocol/conformance/contentHashFixtures.ts +79 -0
  15. package/src/protocol/conformance/context.ts +222 -0
  16. package/src/protocol/conformance/index.ts +140 -0
  17. package/src/protocol/errors.ts +142 -0
  18. package/src/protocol/index.ts +39 -0
  19. package/src/protocol/keys.ts +279 -0
  20. package/src/protocol/params.ts +67 -0
  21. package/src/protocol/secrets.ts +231 -0
  22. package/src/protocol/server/assets.ts +119 -0
  23. package/src/protocol/server/auth.ts +49 -0
  24. package/src/protocol/server/bodyCache.ts +84 -0
  25. package/src/protocol/server/content.ts +175 -0
  26. package/src/protocol/server/core.ts +112 -0
  27. package/src/protocol/server/handler.ts +102 -0
  28. package/src/protocol/server/http.ts +139 -0
  29. package/src/protocol/server/index.ts +11 -0
  30. package/src/protocol/server/methods/apply.ts +341 -0
  31. package/src/protocol/server/methods/read.ts +156 -0
  32. package/src/protocol/server/rpc.ts +136 -0
  33. package/src/protocol/storage/fs/hash.ts +21 -0
  34. package/src/protocol/storage/fs/index.ts +338 -0
  35. package/src/protocol/storage/fs/lock.ts +68 -0
  36. package/src/protocol/storage/fs/transaction.ts +183 -0
  37. package/src/protocol/storage/fs/unsupported.ts +15 -0
  38. package/src/protocol/storage/memory.ts +238 -0
  39. package/src/protocol/storage.ts +182 -0
  40. package/src/protocol/types.ts +172 -0
  41. package/src/v8/analytics.ts +50 -0
  42. package/src/v8/background.ts +107 -0
  43. package/src/v8/builtins/data.ts +23 -0
  44. package/src/v8/builtins/index.ts +26 -0
  45. package/src/v8/builtins/lazy.ts +23 -0
  46. package/src/v8/builtins/legacy.ts +65 -0
  47. package/src/v8/builtins/matchers.ts +31 -0
  48. package/src/v8/builtins/multivariate.ts +25 -0
  49. package/src/v8/builtins/secret.ts +82 -0
  50. package/src/v8/canonical.ts +117 -0
  51. package/src/v8/ciphertext.ts +158 -0
  52. package/src/v8/cli/builtins.ts +20 -0
  53. package/src/v8/cli/check/index.ts +774 -0
  54. package/src/v8/cli/check/messages.ts +168 -0
  55. package/src/v8/cli/content.ts +287 -0
  56. package/src/v8/cli/index.ts +17 -0
  57. package/src/v8/cli/log.ts +18 -0
  58. package/src/v8/cli/main.ts +12 -0
  59. package/src/v8/cli/root.ts +66 -0
  60. package/src/v8/cli/run.ts +236 -0
  61. package/src/v8/cli/schema/builtinSchemas.ts +236 -0
  62. package/src/v8/cli/schema/generate.ts +507 -0
  63. package/src/v8/cli/schema/index.ts +63 -0
  64. package/src/v8/cli/schema/tsProgram.ts +497 -0
  65. package/src/v8/cli/schema/typeToSchema.ts +689 -0
  66. package/src/v8/cli/serve/server.ts +303 -0
  67. package/src/v8/cli/watch.ts +86 -0
  68. package/src/v8/client.ts +147 -0
  69. package/src/v8/cms.ts +237 -0
  70. package/src/v8/content.ts +195 -0
  71. package/src/v8/draft.ts +136 -0
  72. package/src/v8/errors.ts +59 -0
  73. package/src/v8/fetch.ts +133 -0
  74. package/src/v8/identity.ts +65 -0
  75. package/src/v8/index.ts +39 -0
  76. package/src/v8/json.ts +74 -0
  77. package/src/v8/matchRoute.ts +204 -0
  78. package/src/v8/remoteLoader.ts +282 -0
  79. package/src/v8/resolver.ts +278 -0
  80. package/src/v8/secrets.ts +17 -0
  81. package/src/v8/telemetry.ts +533 -0
  82. package/src/v8/types.ts +240 -0
  83. package/src/cms/applySectionConventions.ts +0 -124
  84. package/src/cms/blockSource.test.ts +0 -76
  85. package/src/cms/blockSource.ts +0 -191
  86. package/src/cms/client.browserBundle.test.ts +0 -44
  87. package/src/cms/client.ts +0 -80
  88. package/src/cms/draftSource.test.ts +0 -343
  89. package/src/cms/draftSource.ts +0 -362
  90. package/src/cms/index.ts +0 -151
  91. package/src/cms/layoutCacheRace.test.ts +0 -181
  92. package/src/cms/loadDecofileDirectory.test.ts +0 -109
  93. package/src/cms/loadDecofileDirectory.ts +0 -89
  94. package/src/cms/loader.test.ts +0 -200
  95. package/src/cms/loader.ts +0 -304
  96. package/src/cms/registry.test.ts +0 -110
  97. package/src/cms/registry.ts +0 -242
  98. package/src/cms/resolve.test.ts +0 -980
  99. package/src/cms/resolve.ts +0 -2282
  100. package/src/cms/schema.test.ts +0 -356
  101. package/src/cms/schema.ts +0 -1215
  102. package/src/cms/sectionLoaderContext.test.ts +0 -111
  103. package/src/cms/sectionLoaderContext.ts +0 -113
  104. package/src/cms/sectionLoaders.test.ts +0 -533
  105. package/src/cms/sectionLoaders.ts +0 -636
  106. package/src/cms/sectionMixins.test.ts +0 -167
  107. package/src/cms/sectionMixins.ts +0 -153
  108. package/src/cms/stickyFlags.test.ts +0 -117
  109. package/src/flags/audience.ts +0 -56
  110. package/src/flags/everyone.ts +0 -29
  111. package/src/flags/flag.ts +0 -15
  112. package/src/flags/flags.test.ts +0 -148
  113. package/src/flags/multivariate/image.ts +0 -11
  114. package/src/flags/multivariate/message.ts +0 -11
  115. package/src/flags/multivariate/page.ts +0 -16
  116. package/src/flags/multivariate/section.ts +0 -16
  117. package/src/flags/multivariate.ts +0 -1
  118. package/src/flags/types.ts +0 -59
  119. package/src/flags/utils/multivariate.ts +0 -20
  120. package/src/hooks/Image.test.ts +0 -100
  121. package/src/hooks/Image.tsx +0 -250
  122. package/src/hooks/JsonLd.tsx +0 -353
  123. package/src/hooks/LazySection.tsx +0 -121
  124. package/src/hooks/LiveControls.tsx +0 -122
  125. package/src/hooks/Picture.tsx +0 -127
  126. package/src/hooks/RenderSection.test.tsx +0 -81
  127. package/src/hooks/RenderSection.tsx +0 -91
  128. package/src/hooks/SectionErrorFallback.tsx +0 -97
  129. package/src/hooks/index.ts +0 -30
  130. package/src/matchers/builtins.test.ts +0 -318
  131. package/src/matchers/builtins.ts +0 -459
  132. package/src/matchers/countryNames.ts +0 -104
  133. package/src/matchers/override.test.ts +0 -205
  134. package/src/matchers/override.ts +0 -136
  135. package/src/matchers/posthog.ts +0 -154
  136. package/src/middleware/decoState.ts +0 -55
  137. package/src/middleware/healthMetrics.ts +0 -133
  138. package/src/middleware/hydrationContext.test.ts +0 -61
  139. package/src/middleware/hydrationContext.ts +0 -79
  140. package/src/middleware/index.ts +0 -88
  141. package/src/middleware/liveness.ts +0 -21
  142. package/src/middleware/observability.test.ts +0 -242
  143. package/src/middleware/observability.ts +0 -643
  144. package/src/middleware/validateSection.test.ts +0 -147
  145. package/src/middleware/validateSection.ts +0 -100
  146. package/src/sdk/abTesting.test.ts +0 -326
  147. package/src/sdk/abTesting.ts +0 -499
  148. package/src/sdk/analytics.ts +0 -77
  149. package/src/sdk/cacheHeaders.test.ts +0 -115
  150. package/src/sdk/cacheHeaders.ts +0 -433
  151. package/src/sdk/cachedLoader.test.ts +0 -122
  152. package/src/sdk/cachedLoader.ts +0 -503
  153. package/src/sdk/cachedLoaderModule.test.ts +0 -209
  154. package/src/sdk/clx.ts +0 -5
  155. package/src/sdk/cn.test.ts +0 -34
  156. package/src/sdk/cn.ts +0 -28
  157. package/src/sdk/composite.test.ts +0 -121
  158. package/src/sdk/composite.ts +0 -114
  159. package/src/sdk/cookie.test.ts +0 -108
  160. package/src/sdk/cookie.ts +0 -129
  161. package/src/sdk/crypto.ts +0 -185
  162. package/src/sdk/csp.ts +0 -59
  163. package/src/sdk/detectDevice.ts +0 -45
  164. package/src/sdk/djb2.ts +0 -20
  165. package/src/sdk/encoding.test.ts +0 -71
  166. package/src/sdk/encoding.ts +0 -47
  167. package/src/sdk/env.test.ts +0 -33
  168. package/src/sdk/env.ts +0 -54
  169. package/src/sdk/flags.test.ts +0 -91
  170. package/src/sdk/flags.ts +0 -108
  171. package/src/sdk/http.test.ts +0 -71
  172. package/src/sdk/http.ts +0 -124
  173. package/src/sdk/index.ts +0 -90
  174. package/src/sdk/inflightTimeout.test.ts +0 -35
  175. package/src/sdk/inflightTimeout.ts +0 -53
  176. package/src/sdk/instrumentedFetch.test.ts +0 -559
  177. package/src/sdk/instrumentedFetch.ts +0 -339
  178. package/src/sdk/invoke.test.ts +0 -115
  179. package/src/sdk/invoke.ts +0 -298
  180. package/src/sdk/logger.test.ts +0 -432
  181. package/src/sdk/logger.ts +0 -304
  182. package/src/sdk/mergeCacheControl.ts +0 -150
  183. package/src/sdk/normalizeUrls.ts +0 -91
  184. package/src/sdk/observability.ts +0 -109
  185. package/src/sdk/otel.test.ts +0 -526
  186. package/src/sdk/otel.ts +0 -1012
  187. package/src/sdk/otelAdapters/clickhouseCollector.ts +0 -65
  188. package/src/sdk/otelAdapters.test.ts +0 -89
  189. package/src/sdk/otelAdapters.ts +0 -144
  190. package/src/sdk/otelHttpLog.test.ts +0 -457
  191. package/src/sdk/otelHttpLog.ts +0 -419
  192. package/src/sdk/otelHttpMeter.test.ts +0 -292
  193. package/src/sdk/otelHttpMeter.ts +0 -506
  194. package/src/sdk/otelHttpTracer.test.ts +0 -474
  195. package/src/sdk/otelHttpTracer.ts +0 -543
  196. package/src/sdk/redirects.ts +0 -228
  197. package/src/sdk/requestContext.ts +0 -281
  198. package/src/sdk/requestContextStorage.browser.test.ts +0 -29
  199. package/src/sdk/requestContextStorage.browser.ts +0 -43
  200. package/src/sdk/requestContextStorage.ts +0 -35
  201. package/src/sdk/retry.ts +0 -45
  202. package/src/sdk/serverTimings.ts +0 -68
  203. package/src/sdk/signal.ts +0 -42
  204. package/src/sdk/sitemap.ts +0 -160
  205. package/src/sdk/urlRedaction.test.ts +0 -73
  206. package/src/sdk/urlRedaction.ts +0 -82
  207. package/src/sdk/urlUtils.ts +0 -134
  208. package/src/sdk/useDevice.test.ts +0 -130
  209. package/src/sdk/useDevice.ts +0 -89
  210. package/src/sdk/useDeviceContext.tsx +0 -108
  211. package/src/sdk/useId.ts +0 -7
  212. package/src/sdk/useScript.test.ts +0 -128
  213. package/src/sdk/useScript.ts +0 -210
  214. package/src/sdk/useSuggestions.test.ts +0 -230
  215. package/src/sdk/useSuggestions.ts +0 -188
  216. package/src/sdk/wrapCaughtErrors.ts +0 -107
  217. package/src/setup.ts +0 -120
  218. package/src/types/index.ts +0 -53
  219. package/src/types/widgets.ts +0 -14
  220. package/tsconfig.json +0 -7
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,185 +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
- const textDecoder = new TextDecoder();
19
- const textEncoder = new TextEncoder();
20
-
21
- // Cache the imported key
22
- let cachedKey: Promise<{ key: CryptoKey; iv: Uint8Array }> | null = null;
23
-
24
- function hexToBytes(hex: string): Uint8Array {
25
- const bytes = new Uint8Array(hex.length / 2);
26
- for (let i = 0; i < hex.length; i += 2) {
27
- bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16);
28
- }
29
- return bytes;
30
- }
31
-
32
- /**
33
- * Get the AES key from DECO_CRYPTO_KEY environment variable.
34
- * Returns null if not set.
35
- */
36
- function getKeyFromEnv(): Promise<{ key: CryptoKey; iv: Uint8Array }> | null {
37
- const envKey = getEnvVar("DECO_CRYPTO_KEY");
38
- if (!envKey) return null;
39
-
40
- return cachedKey ??= (async () => {
41
- const parsed = JSON.parse(atob(envKey));
42
- const keyBytes = new Uint8Array(
43
- Array.isArray(parsed.key) ? parsed.key : Object.values(parsed.key),
44
- );
45
- const iv = new Uint8Array(
46
- Array.isArray(parsed.iv) ? parsed.iv : Object.values(parsed.iv),
47
- );
48
-
49
- const importedKey = await crypto.subtle.importKey(
50
- "raw",
51
- keyBytes.buffer,
52
- "AES-CBC",
53
- false,
54
- ["decrypt"],
55
- );
56
-
57
- return { key: importedKey, iv };
58
- })();
59
- }
60
-
61
- /**
62
- * Check if the crypto key is available.
63
- */
64
- export function hasCryptoKey(): boolean {
65
- return !!getEnvVar("DECO_CRYPTO_KEY");
66
- }
67
-
68
- /**
69
- * Decrypt a hex-encoded AES-CBC encrypted string.
70
- * Requires DECO_CRYPTO_KEY environment variable.
71
- *
72
- * @returns The decrypted string, or null if decryption fails.
73
- */
74
- export async function decryptSecret(encryptedHex: string): Promise<string | null> {
75
- const keyPromise = getKeyFromEnv();
76
- if (!keyPromise) {
77
- return null;
78
- }
79
-
80
- try {
81
- const { key, iv } = await keyPromise;
82
- const encryptedBytes = hexToBytes(encryptedHex);
83
- const decrypted = await crypto.subtle.decrypt(
84
- { name: "AES-CBC", iv } as AesCbcParams,
85
- key,
86
- encryptedBytes as unknown as BufferSource,
87
- );
88
- return textDecoder.decode(new Uint8Array(decrypted));
89
- } catch (e) {
90
- console.warn("[crypto] Failed to decrypt secret:", (e as Error).message);
91
- return null;
92
- }
93
- }
94
-
95
- // In-memory cache for resolved secrets
96
- const secretCache = new Map<string, string | null>();
97
-
98
- /**
99
- * Resolve a CMS secret value from multiple sources.
100
- *
101
- * Resolution order:
102
- * 1. Plain string → use directly
103
- * 2. Object with .get() → call .get() (old Secret loader pattern)
104
- * 3. Object with .encrypted → decrypt using DECO_CRYPTO_KEY
105
- * 4. Environment variable (envVarName) → fallback
106
- *
107
- * @param value - The secret value from CMS block (string | { encrypted } | { get })
108
- * @param envVarName - Optional env var name to use as fallback (e.g. "RESEND_API_KEY")
109
- * @returns The resolved secret string, or null if not available
110
- */
111
- export async function resolveSecret(
112
- value: unknown,
113
- envVarName?: string,
114
- ): Promise<string | null> {
115
- // 1. Plain string
116
- if (typeof value === "string" && value.length > 0) {
117
- return value;
118
- }
119
-
120
- if (value && typeof value === "object") {
121
- const obj = value as Record<string, any>;
122
-
123
- // 2. Secret object with .get()
124
- if (typeof obj.get === "function") {
125
- const result = obj.get();
126
- if (typeof result === "string" && result.length > 0) return result;
127
- }
128
-
129
- // 3. Encrypted secret
130
- if (typeof obj.encrypted === "string" && obj.encrypted.length > 0) {
131
- const cacheKey = obj.encrypted;
132
- if (secretCache.has(cacheKey)) return secretCache.get(cacheKey)!;
133
-
134
- const decrypted = await decryptSecret(obj.encrypted);
135
- // Only cache successful decryptions — null would block env var fallback
136
- if (decrypted) {
137
- secretCache.set(cacheKey, decrypted);
138
- return decrypted;
139
- }
140
- }
141
- }
142
-
143
- // 4. Environment variable fallback
144
- if (envVarName) {
145
- const envValue = getEnvVar(envVarName);
146
- if (envValue) return envValue;
147
- }
148
-
149
- return null;
150
- }
151
-
152
- /**
153
- * Get an environment variable, checking process.env first, then .dev.vars file.
154
- * Cloudflare Workers dev mode stores env vars in .dev.vars but they're only
155
- * accessible via the `env` binding inside request handlers. During setup.ts
156
- * (module-level init), we need to read the file directly.
157
- */
158
- function getEnvVar(name: string): string | undefined {
159
- // 1. process.env (works in Node, may work in Workers with nodejs_compat)
160
- if (typeof process !== "undefined" && process.env?.[name]) {
161
- return process.env[name];
162
- }
163
-
164
- // 2. Read .dev.vars file (Cloudflare Workers dev mode)
165
- try {
166
- const fs = require("node:fs");
167
- const path = require("node:path");
168
- const devVarsPath = path.resolve(".dev.vars");
169
- if (fs.existsSync(devVarsPath)) {
170
- const content = fs.readFileSync(devVarsPath, "utf-8");
171
- for (const line of content.split("\n")) {
172
- const trimmed = line.trim();
173
- if (trimmed.startsWith("#") || !trimmed.includes("=")) continue;
174
- const eqIdx = trimmed.indexOf("=");
175
- const key = trimmed.slice(0, eqIdx).trim();
176
- const val = trimmed.slice(eqIdx + 1).trim();
177
- if (key === name) return val;
178
- }
179
- }
180
- } catch {
181
- // fs not available (e.g., pure Worker runtime) — ignore
182
- }
183
-
184
- return undefined;
185
- }
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,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,71 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import {
3
- decodeBase64,
4
- decodeBase64Url,
5
- encodeBase64,
6
- encodeBase64Url,
7
- } from "./encoding";
8
-
9
- describe("encodeBase64 / decodeBase64", () => {
10
- it("round-trips ASCII strings", () => {
11
- const data = "hello, world";
12
- const b64 = encodeBase64(data);
13
- expect(b64).toBe("aGVsbG8sIHdvcmxk");
14
- const decoded = new TextDecoder().decode(decodeBase64(b64));
15
- expect(decoded).toBe(data);
16
- });
17
-
18
- it("round-trips multi-byte UTF-8", () => {
19
- const data = "São Paulo — café ☕";
20
- const b64 = encodeBase64(data);
21
- const decoded = new TextDecoder().decode(decodeBase64(b64));
22
- expect(decoded).toBe(data);
23
- });
24
-
25
- it("accepts Uint8Array input", () => {
26
- const bytes = new Uint8Array([1, 2, 3, 4, 5]);
27
- const b64 = encodeBase64(bytes);
28
- expect(decodeBase64(b64)).toEqual(bytes);
29
- });
30
-
31
- it("accepts ArrayBuffer input", () => {
32
- const buf = new Uint8Array([255, 254, 253]).buffer;
33
- const b64 = encodeBase64(buf);
34
- expect(Array.from(decodeBase64(b64))).toEqual([255, 254, 253]);
35
- });
36
-
37
- it("handles inputs larger than the chunking window", () => {
38
- // 0x8000 + 7 bytes — forces the chunking branch.
39
- const bytes = new Uint8Array(0x8000 + 7);
40
- for (let i = 0; i < bytes.length; i++) bytes[i] = i & 0xff;
41
- const b64 = encodeBase64(bytes);
42
- expect(decodeBase64(b64)).toEqual(bytes);
43
- });
44
- });
45
-
46
- describe("encodeBase64Url / decodeBase64Url", () => {
47
- it("uses URL-safe alphabet and strips padding", () => {
48
- // Inputs that produce '+', '/', and padding under standard base64.
49
- const bytes = new Uint8Array([251, 255, 191, 251, 239, 254]);
50
- const standard = encodeBase64(bytes);
51
- const url = encodeBase64Url(bytes);
52
- // Every '+' becomes '-', '/' becomes '_', trailing '=' is stripped.
53
- expect(url).toBe(
54
- standard.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""),
55
- );
56
- expect(url).not.toContain("+");
57
- expect(url).not.toContain("/");
58
- expect(url).not.toContain("=");
59
- });
60
-
61
- it("round-trips through the URL-safe pair", () => {
62
- const data = new Uint8Array(64);
63
- for (let i = 0; i < data.length; i++) data[i] = (i * 7) & 0xff;
64
- expect(decodeBase64Url(encodeBase64Url(data))).toEqual(data);
65
- });
66
-
67
- it("decodes inputs missing their padding", () => {
68
- // 'a' = 0x61. encodeBase64('a') = 'YQ==', URL form drops to 'YQ'.
69
- expect(new TextDecoder().decode(decodeBase64Url("YQ"))).toBe("a");
70
- });
71
- });
@@ -1,47 +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 {
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)
38
- .replace(/\+/g, "-")
39
- .replace(/\//g, "_")
40
- .replace(/=+$/, "");
41
- }
42
-
43
- export function decodeBase64Url(b64url: string): Uint8Array {
44
- const padded = b64url.replace(/-/g, "+").replace(/_/g, "/");
45
- const padLen = (4 - (padded.length % 4)) % 4;
46
- return decodeBase64(padded + "=".repeat(padLen));
47
- }
@@ -1,33 +0,0 @@
1
- import { afterEach, describe, expect, it, vi } from "vitest";
2
-
3
- // isDevMode() memoises its result in module-level state after the first
4
- // call, so each case below resets modules and re-imports fresh to get an
5
- // unmemoised read for the NODE_ENV value it's stubbing.
6
- describe("isDevMode", () => {
7
- afterEach(() => {
8
- vi.unstubAllEnvs();
9
- });
10
-
11
- it("is false when NODE_ENV is production", async () => {
12
- vi.stubEnv("NODE_ENV", "production");
13
- vi.stubEnv("DECO_PREVIEW", "");
14
- vi.resetModules();
15
- const { isDevMode } = await import("./env");
16
- expect(isDevMode()).toBe(false);
17
- });
18
-
19
- it("is true when NODE_ENV is development", async () => {
20
- vi.stubEnv("NODE_ENV", "development");
21
- vi.resetModules();
22
- const { isDevMode } = await import("./env");
23
- expect(isDevMode()).toBe(true);
24
- });
25
-
26
- it("is true when DECO_PREVIEW=true even if NODE_ENV is production", async () => {
27
- vi.stubEnv("NODE_ENV", "production");
28
- vi.stubEnv("DECO_PREVIEW", "true");
29
- vi.resetModules();
30
- const { isDevMode } = await import("./env");
31
- expect(isDevMode()).toBe(true);
32
- });
33
- });
package/src/sdk/env.ts DELETED
@@ -1,54 +0,0 @@
1
- /**
2
- * Centralized environment detection for @decocms/start.
3
- *
4
- * Works in Cloudflare Workers (wrangler dev), Node, and Vite SSR.
5
- * Evaluates lazily on first call so it picks up env vars set after module load.
6
- */
7
-
8
- let _isDev: boolean | null = null;
9
-
10
- /**
11
- * Reads `process.env.NODE_ENV` defensively.
12
- *
13
- * Wrapped in try/catch so the bare `process` reference can't throw in runtimes
14
- * without a `process` global (workerd without `nodejs_compat`). Bundlers that
15
- * statically define `process.env.NODE_ENV` (Vite/esbuild in Workers builds —
16
- * the same role the old `import.meta.env.DEV` signal served) replace this
17
- * expression with a string constant at build time, so no runtime `process`
18
- * global is needed in that path at all.
19
- */
20
- function readNodeEnv(): string | undefined {
21
- try {
22
- return process.env.NODE_ENV;
23
- } catch {
24
- return undefined;
25
- }
26
- }
27
-
28
- /**
29
- * Returns `true` when running in a development environment.
30
- *
31
- * Detection order:
32
- * 1. `readNodeEnv() === "development"` — bundler-define-friendly read of
33
- * `process.env.NODE_ENV` (see `readNodeEnv` above). This replaces the
34
- * previous `import.meta.env.DEV` signal: `import.meta` is ESM-only syntax
35
- * and is a hard syntax error when CJS consumers (ts-jest) compile this
36
- * raw-TS package, and `env.ts` is reachable via the `@decocms/blocks/sdk`
37
- * barrel, so any such consumer importing the barrel would fail to compile.
38
- * 2. `NODE_ENV=development` read off `globalThis.process.env` — standard
39
- * Node/Vite convention, for runtimes where `process` is a real global.
40
- * 3. `DECO_PREVIEW=true` — explicit preview-mode override.
41
- *
42
- * The result is memoised after the first evaluation.
43
- */
44
- export function isDevMode(): boolean {
45
- if (_isDev !== null) return _isDev;
46
-
47
- const env = typeof globalThis.process !== "undefined" ? globalThis.process.env : undefined;
48
-
49
- const nodeEnvDev = readNodeEnv() === "development";
50
-
51
- _isDev = nodeEnvDev || env?.NODE_ENV === "development" || env?.DECO_PREVIEW === "true";
52
-
53
- return _isDev;
54
- }