@decocms/apps-wake 7.66.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 (56) hide show
  1. package/package.json +58 -0
  2. package/src/actions/cart/addCoupon.ts +43 -0
  3. package/src/actions/cart/addItem.ts +10 -0
  4. package/src/actions/cart/addItems.ts +50 -0
  5. package/src/actions/cart/addKit.ts +53 -0
  6. package/src/actions/cart/partnerAssociate.ts +48 -0
  7. package/src/actions/cart/partnerDisassociate.ts +43 -0
  8. package/src/actions/cart/removeCoupon.ts +39 -0
  9. package/src/actions/cart/removeKit.ts +56 -0
  10. package/src/actions/cart/updateItemQuantity.ts +69 -0
  11. package/src/actions/newsletter/register.ts +32 -0
  12. package/src/actions/notifyme.ts +28 -0
  13. package/src/actions/review/create.ts +30 -0
  14. package/src/actions/shippingSimulation.ts +60 -0
  15. package/src/actions/submmitForm.ts +25 -0
  16. package/src/actions/wishlist/addProduct.ts +43 -0
  17. package/src/actions/wishlist/removeProduct.ts +45 -0
  18. package/src/client.ts +123 -0
  19. package/src/commerceLoaders.ts +137 -0
  20. package/src/handlers/sitemap.ts +61 -0
  21. package/src/index.ts +58 -0
  22. package/src/loaders/cart.ts +46 -0
  23. package/src/loaders/partners.ts +58 -0
  24. package/src/loaders/productDetailsPage.ts +174 -0
  25. package/src/loaders/productList.ts +262 -0
  26. package/src/loaders/productListingPage.ts +333 -0
  27. package/src/loaders/proxy.ts +79 -0
  28. package/src/loaders/recommendations.ts +84 -0
  29. package/src/loaders/shop.ts +37 -0
  30. package/src/loaders/suggestion.ts +67 -0
  31. package/src/loaders/user.ts +48 -0
  32. package/src/loaders/wishlist.ts +40 -0
  33. package/src/manifest.gen.ts +69 -0
  34. package/src/mod.ts +88 -0
  35. package/src/registry.ts +9 -0
  36. package/src/utils/authError.ts +107 -0
  37. package/src/utils/authenticate.ts +42 -0
  38. package/src/utils/capitalize.ts +9 -0
  39. package/src/utils/cart.ts +33 -0
  40. package/src/utils/client.ts +11 -0
  41. package/src/utils/cookies.ts +82 -0
  42. package/src/utils/getVariations.ts +47 -0
  43. package/src/utils/graphql/queries.ts +1363 -0
  44. package/src/utils/graphql/storefront.graphql.gen.ts +10233 -0
  45. package/src/utils/graphql.ts +88 -0
  46. package/src/utils/graphqlOperationName.ts +67 -0
  47. package/src/utils/httpError.ts +15 -0
  48. package/src/utils/instrumentedFetch.ts +46 -0
  49. package/src/utils/operationRouter.ts +51 -0
  50. package/src/utils/parseHeaders.ts +19 -0
  51. package/src/utils/partner.ts +34 -0
  52. package/src/utils/requestCtx.ts +41 -0
  53. package/src/utils/transform.ts +460 -0
  54. package/src/utils/types.ts +6 -0
  55. package/src/utils/user.ts +9 -0
  56. package/tsconfig.json +7 -0
@@ -0,0 +1,88 @@
1
+ import { type FetchFn, withFetchTimeout } from "@decocms/blocks/sdk/fetchTimeout";
2
+ import type { InstrumentedFetchInit } from "@decocms/blocks/sdk/instrumentedFetch";
3
+ import { extractGraphqlOperationName } from "./graphqlOperationName";
4
+
5
+ /**
6
+ * Tagged-template helper that composes a GraphQL document string.
7
+ * Kept identical to the Deno `gql` so the ported `graphql/queries.ts`
8
+ * (which defines `{ fragments, query }` objects) works verbatim.
9
+ */
10
+ export function gql(strings: TemplateStringsArray, ...values: unknown[]): string {
11
+ return strings.reduce((acc, str, i) => acc + str + (values[i] ?? ""), "");
12
+ }
13
+
14
+ export interface QueryDefinition {
15
+ fragments?: string[];
16
+ query: string;
17
+ }
18
+
19
+ export function buildQuery(def: QueryDefinition): string {
20
+ const fragments = def.fragments?.join("\n") ?? "";
21
+ return fragments ? `${fragments}\n${def.query}` : def.query;
22
+ }
23
+
24
+ export interface GraphQLClient {
25
+ /**
26
+ * Run a GraphQL operation. `extraHeaders` is merged over the client's
27
+ * base headers for the single call — Wake loaders use it to forward the
28
+ * client IP (`X-Forwarded-For`) via `parseHeaders(...)`.
29
+ */
30
+ query<T>(
31
+ query: string | QueryDefinition,
32
+ variables?: Record<string, unknown>,
33
+ extraHeaders?: Record<string, string>,
34
+ ): Promise<T>;
35
+ }
36
+
37
+ export function createGraphqlClient(
38
+ endpoint: string,
39
+ headers: Record<string, string>,
40
+ fetchFn?: FetchFn,
41
+ ): GraphQLClient {
42
+ const _fetch = fetchFn ?? withFetchTimeout();
43
+ return {
44
+ async query<T>(
45
+ queryOrDef: string | QueryDefinition,
46
+ variables?: Record<string, unknown>,
47
+ extraHeaders?: Record<string, string>,
48
+ ): Promise<T> {
49
+ const query = typeof queryOrDef === "string" ? queryOrDef : buildQuery(queryOrDef);
50
+
51
+ // Stamp the GraphQL operation as init.operation so the framework's
52
+ // span name becomes `wake.<OperationName>` instead of the generic
53
+ // `wake.storefront.graphql` from the URL router. The extra field is
54
+ // silently dropped by plain `fetch` and read by any `InstrumentedFetch`
55
+ // configured via `setWakeFetch`.
56
+ const operation = extractGraphqlOperationName(query);
57
+ const init: InstrumentedFetchInit = {
58
+ method: "POST",
59
+ headers: {
60
+ // Per-call `extraHeaders` (e.g. forwarded client IP) come first so
61
+ // they can never override the app's auth token or Content-Type.
62
+ ...extraHeaders,
63
+ "Content-Type": "application/json",
64
+ ...headers,
65
+ },
66
+ body: JSON.stringify({ query, variables }),
67
+ ...(operation ? { operation } : {}),
68
+ };
69
+ const response = await _fetch(endpoint, init);
70
+
71
+ if (!response.ok) {
72
+ throw new Error(`Wake GraphQL error: ${response.status} ${response.statusText}`);
73
+ }
74
+
75
+ const json = (await response.json()) as { data?: T; errors?: Array<{ message: string }> };
76
+
77
+ if (json.errors?.length) {
78
+ throw new Error(`Wake GraphQL errors: ${json.errors.map((e) => e.message).join(", ")}`);
79
+ }
80
+
81
+ if (json.data === undefined) {
82
+ throw new Error("Wake GraphQL response missing data");
83
+ }
84
+
85
+ return json.data;
86
+ },
87
+ };
88
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Extract a semantic operation name from a GraphQL document.
3
+ *
4
+ * Used at the Shopify GraphQL client layer to stamp `init.operation`
5
+ * on the outbound fetch. The framework then suffixes the integration
6
+ * name (`shopify.<operation>`) onto the span and uses the same string
7
+ * as the `fetch.operation` attribute + histogram label.
8
+ *
9
+ * Resolution order:
10
+ *
11
+ * 1. An explicit `operationName` argument (e.g. when the client
12
+ * received one alongside a multi-operation document) wins.
13
+ * 2. If the document has exactly one named operation, that name
14
+ * is used.
15
+ * 3. If the document has zero or many anonymous operations, we
16
+ * return `undefined` so the caller can fall back (typically to
17
+ * the URL-derived `storefront.graphql` / `admin.graphql`).
18
+ *
19
+ * The parser is deliberately a small regex pass, not a full GraphQL
20
+ * tokenizer:
21
+ *
22
+ * - GraphQL operation definitions live at the top level of the
23
+ * document, never nested inside other operations, fragments, or
24
+ * selection sets, so positional context isn't required to find
25
+ * them — only to not match the literal words `query` /
26
+ * `mutation` / `subscription` inside string values.
27
+ * - We strip block strings (`""" … """`), string literals
28
+ * (`"…"`), and `# …` comments before matching, which is enough
29
+ * to make false-positive matches inside comments / docs vanish.
30
+ *
31
+ * If a Shopify operation is ever sufficiently mis-named to break
32
+ * this (unlikely, since the storefront SDK names them deliberately),
33
+ * the caller can always set `init.operation` explicitly.
34
+ */
35
+
36
+ const OPERATION_RE = /\b(?:query|mutation|subscription)\s+([A-Za-z_][A-Za-z0-9_]*)/g;
37
+
38
+ const stripCommentsAndStrings = (doc: string): string =>
39
+ doc
40
+ .replace(/"""[\s\S]*?"""/g, '""')
41
+ .replace(/"(?:\\.|[^"\\])*"/g, '""')
42
+ .replace(/#[^\n]*/g, "");
43
+
44
+ export function extractGraphqlOperationName(
45
+ document: string,
46
+ explicit?: string,
47
+ ): string | undefined {
48
+ if (explicit) return explicit;
49
+ if (!document) return undefined;
50
+
51
+ const stripped = stripCommentsAndStrings(document);
52
+ const names: string[] = [];
53
+
54
+ OPERATION_RE.lastIndex = 0;
55
+ for (
56
+ let match = OPERATION_RE.exec(stripped);
57
+ match !== null;
58
+ match = OPERATION_RE.exec(stripped)
59
+ ) {
60
+ const [, name] = match;
61
+ if (name) names.push(name);
62
+ if (names.length > 1) break;
63
+ }
64
+
65
+ if (names.length === 1) return names[0];
66
+ return undefined;
67
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Minimal HTTP error carrying a status code.
3
+ *
4
+ * The Deno Wake app threw `HttpError` from `deco/utils/http.ts`; in this
5
+ * architecture actions just throw `Error`, so this local class preserves the
6
+ * `.status` field that some callers/handlers inspect.
7
+ */
8
+ export class HttpError extends Error {
9
+ status: number;
10
+ constructor(status: number, message?: string) {
11
+ super(message ?? `HTTP ${status}`);
12
+ this.name = "HttpError";
13
+ this.status = status;
14
+ }
15
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Pre-wired instrumented fetch factory for Wake. Mirrors
3
+ * `apps-shopify/utils/instrumentedFetch.ts`.
4
+ *
5
+ * Bundles `createInstrumentedFetch` (spans, traceparent, URL redaction), the
6
+ * `wakeOperationRouter` URL fallback, and an `onComplete` that records the
7
+ * canonical `http.client.request.duration` histogram with `provider: "wake"`.
8
+ *
9
+ * Sites do:
10
+ * ```ts
11
+ * import { setWakeFetch, createWakeFetch } from "@decocms/apps-wake";
12
+ * setWakeFetch(createWakeFetch());
13
+ * ```
14
+ */
15
+
16
+ import type { FetchFn } from "@decocms/blocks/sdk/fetchTimeout";
17
+ import {
18
+ createInstrumentedFetch,
19
+ type InstrumentedFetch,
20
+ } from "@decocms/blocks/sdk/instrumentedFetch";
21
+ import { recordCommerceMetric } from "@decocms/blocks/sdk/observability";
22
+ import { wakeOperationRouter } from "./operationRouter";
23
+
24
+ export interface CreateWakeFetchOptions {
25
+ baseFetch?: FetchFn;
26
+ disableHistogram?: boolean;
27
+ }
28
+
29
+ export function createWakeFetch(options: CreateWakeFetchOptions = {}): InstrumentedFetch {
30
+ const { baseFetch, disableHistogram = false } = options;
31
+ return createInstrumentedFetch({
32
+ name: "wake",
33
+ baseFetch,
34
+ resolveOperation: wakeOperationRouter,
35
+ onComplete: disableHistogram
36
+ ? undefined
37
+ : ({ operation, status, durationMs, cached }) => {
38
+ recordCommerceMetric(durationMs, {
39
+ provider: "wake",
40
+ operation,
41
+ status_class: `${Math.floor(status / 100)}xx`,
42
+ cached,
43
+ });
44
+ },
45
+ });
46
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * URL-derived operation name router for Wake API calls.
3
+ *
4
+ * Plugged into `@decocms/blocks`'s `createInstrumentedFetch` via the
5
+ * `resolveOperation(url, method)` option. Wake's API surface here is the
6
+ * GraphQL storefront (`/graphql`) plus a couple of checkout REST endpoints.
7
+ * The semantic GraphQL operation name is extracted from the document itself
8
+ * (see `./graphqlOperationName.ts`) and stamped as `init.operation`, which
9
+ * always wins over this router; this router is the fallback.
10
+ */
11
+
12
+ type OperationResolver = string | ((match: RegExpMatchArray, method: string) => string);
13
+
14
+ interface Matcher {
15
+ pattern: RegExp;
16
+ operation: OperationResolver;
17
+ }
18
+
19
+ const m = (pattern: RegExp, operation: OperationResolver): Matcher => ({ pattern, operation });
20
+
21
+ const MATCHERS: ReadonlyArray<Matcher> = [
22
+ m(/^\/graphql/, "storefront.graphql"),
23
+ m(/^\/api\/Login\/Get/, "checkout.login"),
24
+ m(/^\/api\/carrinho/, "checkout.cart"),
25
+ m(/^\/api\//, "checkout.api"),
26
+ m(/^\/Sitemap\.xml/i, "sitemap"),
27
+ ];
28
+
29
+ /**
30
+ * Resolve an operation name for a Wake URL. Returns `undefined` if no matcher
31
+ * fires, which causes the framework to fall back to `wake.fetch`.
32
+ */
33
+ export function wakeOperationRouter(url: string, method: string): string | undefined {
34
+ let pathname: string;
35
+ try {
36
+ pathname = new URL(url).pathname;
37
+ } catch {
38
+ const qs = url.indexOf("?");
39
+ const hash = url.indexOf("#");
40
+ const end = [qs, hash].filter((i) => i >= 0).sort((a, b) => a - b)[0];
41
+ pathname = end === undefined ? url : url.slice(0, end);
42
+ }
43
+
44
+ const upperMethod = method.toUpperCase();
45
+ for (const { pattern, operation } of MATCHERS) {
46
+ const match = pathname.match(pattern);
47
+ if (!match) continue;
48
+ return typeof operation === "function" ? operation(match, upperMethod) : operation;
49
+ }
50
+ return undefined;
51
+ }
@@ -0,0 +1,19 @@
1
+ export const getClientIP = (headers: Headers) => {
2
+ const cfConnectingIp = headers.get("cf-connecting-ip");
3
+ const xForwardedFor = headers.get("x-forwarded-for");
4
+
5
+ if (cfConnectingIp) return cfConnectingIp;
6
+
7
+ return xForwardedFor;
8
+ };
9
+
10
+ /**
11
+ * Build a headers bag that forwards the originating client IP to Wake.
12
+ * Passed per-call into the storefront GraphQL client.
13
+ */
14
+ export const parseHeaders = (headers: Headers): Record<string, string> => {
15
+ const clientIP = getClientIP(headers);
16
+ const out: Record<string, string> = {};
17
+ if (clientIP) out["X-Forwarded-For"] = clientIP;
18
+ return out;
19
+ };
@@ -0,0 +1,34 @@
1
+ import { getCookies, setCookie } from "./cookies";
2
+ import { isSecureRequest } from "./requestCtx";
3
+
4
+ const PARTNER_COOKIE = "partner-token";
5
+
6
+ const TEN_DAYS_MS = 10 * 24 * 3600 * 1_000;
7
+
8
+ export const getPartnerCookie = (headers: Headers): string | undefined => {
9
+ const cookies = getCookies(headers);
10
+
11
+ return cookies[PARTNER_COOKIE];
12
+ };
13
+
14
+ export const setPartnerCookie = (headers: Headers, partnerToken: string) =>
15
+ setCookie(headers, {
16
+ name: PARTNER_COOKIE,
17
+ value: partnerToken,
18
+ path: "/",
19
+ expires: new Date(Date.now() + TEN_DAYS_MS),
20
+ // Server-only token — nothing client-side reads it.
21
+ httpOnly: true,
22
+ // Secure only on HTTPS — a Secure cookie is dropped over http:// (localhost dev).
23
+ secure: isSecureRequest(),
24
+ sameSite: "Lax",
25
+ });
26
+
27
+ export const deletePartnerCookie = (headers: Headers) =>
28
+ setCookie(headers, {
29
+ name: PARTNER_COOKIE,
30
+ value: "",
31
+ path: "/",
32
+ expires: new Date(0),
33
+ maxAge: 0,
34
+ });
@@ -0,0 +1,41 @@
1
+ import { RequestContext } from "@decocms/blocks/sdk/requestContext";
2
+ import { parseHeaders } from "./parseHeaders";
3
+
4
+ /**
5
+ * Request-scoped helpers bridging the Deno `(req, ctx)` convention to this
6
+ * architecture's `RequestContext` singleton. Loaders/actions read the active
7
+ * request's URL/cookies and write Set-Cookie via these.
8
+ */
9
+
10
+ export const currentRequest = (): Request | null => RequestContext.current?.request ?? null;
11
+
12
+ export const currentUrl = (): URL => new URL(currentRequest()?.url ?? "https://localhost");
13
+
14
+ export const currentRequestHeaders = (): Headers => currentRequest()?.headers ?? new Headers();
15
+
16
+ export const currentResponseHeaders = (): Headers =>
17
+ RequestContext.current?.responseHeaders ?? new Headers();
18
+
19
+ /** Client-IP forwarding headers for the storefront GraphQL call. */
20
+ export const forwardedHeaders = (): Record<string, string> => {
21
+ const req = currentRequest();
22
+ return req ? parseHeaders(req.headers) : {};
23
+ };
24
+
25
+ /**
26
+ * Whether the active request is HTTPS — drives the `Secure` cookie flag.
27
+ * A `Secure` cookie is rejected by browsers over plain HTTP (e.g. localhost
28
+ * dev), so cookies must only be marked Secure on real HTTPS requests. Defaults
29
+ * to `true` when the request is unknown (prod-safety).
30
+ */
31
+ export const isSecureRequest = (): boolean => {
32
+ const req = currentRequest();
33
+ if (!req) return true;
34
+ try {
35
+ const proto = req.headers.get("x-forwarded-proto");
36
+ if (proto) return proto.split(",")[0].trim() === "https";
37
+ return new URL(req.url).protocol === "https:";
38
+ } catch {
39
+ return true;
40
+ }
41
+ };