Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 28 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,11 @@ A working VTEX storefront needs three things: a `deco-vtex` config block, an `in

```ts
import { createSiteSetup } from "@decocms/start/setup";
import { createInstrumentedFetch } from "@decocms/start/sdk/instrumentedFetch";
import { initVtexFromBlocks, setVtexFetch } from "@decocms/apps/vtex/client";
import {
createVtexFetch,
initVtexFromBlocks,
setVtexFetch,
} from "@decocms/apps/vtex";
import { createVtexCommerceLoaders } from "@decocms/apps/vtex/commerceLoaders";

createSiteSetup({
Expand All @@ -69,9 +72,28 @@ createSiteSetup({
getCommerceLoaders: () => createVtexCommerceLoaders(),
});

setVtexFetch(createInstrumentedFetch("vtex"));
// Plumbs spans, traceparent injection, URL redaction, and the
// `commerce_request_duration_ms` histogram into every outbound
// VTEX call. Operation names are derived from the URL via
// `vtexOperationRouter` (overridable per call via `init.operation`).
setVtexFetch(createVtexFetch());
```

For Shopify storefronts the equivalent factory is `createShopifyFetch()`:

```ts
import { createShopifyFetch, setShopifyFetch } from "@decocms/apps/shopify";

setShopifyFetch(createShopifyFetch());
```

Shopify's GraphQL operation name (`query Foo { ... }` → `Foo`) is
extracted from the document body and stamped automatically — spans
become `shopify.Foo` instead of the generic `shopify.storefront.graphql`.

> **Heads up:** the factories require `@decocms/start@>=5.3.0-rc.0`
> for the per-call `init.operation` API used to label spans.

#### 3. Hooks in components

```tsx
Expand Down Expand Up @@ -134,7 +156,9 @@ await sendEmail({
| Subpath | Purpose |
|---------|---------|
| `@decocms/apps/vtex` | Barrel index |
| `@decocms/apps/vtex/client` | `vtexFetch`, `vtexFetchWithCookies`, `intelligentSearch`, `setVtexFetch`, `initVtexFromBlocks`, `configureVtex` |
| `@decocms/apps/vtex/client` | `vtexFetch`, `vtexFetchWithCookies`, `intelligentSearch`, `setVtexFetch`, `getVtexFetch`, `initVtexFromBlocks`, `configureVtex` |
| `@decocms/apps/vtex` (barrel) | All of `client`, plus `createVtexFetch`, `vtexOperationRouter` for observability wiring |
| `@decocms/apps/shopify` (barrel) | `createShopifyFetch`, `setShopifyFetch`, `shopifyOperationRouter`, `extractGraphqlOperationName` for observability wiring |
| `@decocms/apps/vtex/commerceLoaders` | `createVtexCommerceLoaders` |
| `@decocms/apps/vtex/loaders/*` | Cart, user, wishlist, search, catalog, sessions, orders, autocomplete |
| `@decocms/apps/vtex/actions/*` | Cart mutations, auth, profile, address, wishlist, newsletter |
Expand Down
3 changes: 0 additions & 3 deletions knip.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,5 @@
],
"ignoreBinaries": [
"semantic-release"
],
"ignoreDependencies": [
"@decocms/start"
]
}
58 changes: 46 additions & 12 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -109,14 +109,14 @@
"access": "public"
},
"peerDependencies": {
"@decocms/start": ">=0.19.0",
"@decocms/start": ">=5.3.0-rc.0",
"@tanstack/react-query": ">=5",
"react": ">=18",
"react-dom": ">=18"
},
"devDependencies": {
"@biomejs/biome": "^2.4.7",
"@decocms/start": "^2.5.0",
"@decocms/start": "5.3.0-rc.0",
"@semantic-release/exec": "^7.1.0",
"@tanstack/react-query": "^5.90.21",
"@types/react": "^19.0.0",
Expand Down
6 changes: 6 additions & 0 deletions shopify/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,10 @@ export { default as userLoader } from "./loaders/user";
export { getCartCookie, setCartCookie } from "./utils/cart";
// Cookie utils
export { getCookies, setCookie } from "./utils/cookies";
export { extractGraphqlOperationName } from "./utils/graphqlOperationName";
export {
type CreateShopifyFetchOptions,
createShopifyFetch,
} from "./utils/instrumentedFetch";
export { shopifyOperationRouter } from "./utils/operationRouter";
export { getUserCookie, setUserCookie } from "./utils/user";
80 changes: 80 additions & 0 deletions shopify/utils/__tests__/graphqlOperationName.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { describe, expect, it } from "vitest";
import { extractGraphqlOperationName } from "../graphqlOperationName";

describe("extractGraphqlOperationName", () => {
it("returns the explicit name when provided, regardless of body content", () => {
expect(extractGraphqlOperationName("query Whatever { x }", "ForcedName")).toBe("ForcedName");
expect(extractGraphqlOperationName("", "Override")).toBe("Override");
});

it("extracts a single named query", () => {
expect(
extractGraphqlOperationName("query ProductBySlug($slug: String!) { product { id } }"),
).toBe("ProductBySlug");
});

it("extracts a single named mutation", () => {
expect(
extractGraphqlOperationName("mutation CartLinesAdd($cartId: ID!) { cartLinesAdd { } }"),
).toBe("CartLinesAdd");
});

it("extracts a single named subscription", () => {
expect(extractGraphqlOperationName("subscription OrderEvents { orderUpdated { id } }")).toBe(
"OrderEvents",
);
});

it("returns undefined for anonymous operations", () => {
expect(extractGraphqlOperationName("{ product { id } }")).toBeUndefined();
expect(extractGraphqlOperationName("query { product { id } }")).toBeUndefined();
});

it("returns undefined when document has more than one named operation (caller must disambiguate)", () => {
const multi = `
query OpA { a }
query OpB { b }
`;
expect(extractGraphqlOperationName(multi)).toBeUndefined();
});

it("ignores the words query/mutation/subscription inside string literals", () => {
const docWithStringy = `query RealName { thing(arg: "this query mutation subscription is a string") }`;
expect(extractGraphqlOperationName(docWithStringy)).toBe("RealName");
});

it("ignores the words inside block strings (triple-quoted)", () => {
const doc = `
"""
This block string mentions query Inner and mutation Inner2.
"""
query OuterReal { x }
`;
expect(extractGraphqlOperationName(doc)).toBe("OuterReal");
});

it("ignores the words inside # comments", () => {
const doc = `
# query CommentedOut { x }
query Active { y }
`;
expect(extractGraphqlOperationName(doc)).toBe("Active");
});

it("returns undefined on an empty / nullish body", () => {
expect(extractGraphqlOperationName("")).toBeUndefined();
expect(extractGraphqlOperationName(" \n\t ")).toBeUndefined();
});

it("handles a real-world Shopify storefront query shape", () => {
const doc = `
query ProductDetails($handle: String!, $country: CountryCode!) @inContext(country: $country) {
product(handle: $handle) {
id
title
}
}
`;
expect(extractGraphqlOperationName(doc)).toBe("ProductDetails");
});
});
83 changes: 83 additions & 0 deletions shopify/utils/__tests__/instrumentedFetch.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/**
* Smoke tests for the pre-wired Shopify fetch factory. Same wiring
* assertions as `vtex/utils/__tests__/instrumentedFetch.test.ts`.
*/

import { configureMeter, type MeterAdapter } from "@decocms/start/sdk/observability";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createShopifyFetch } from "../instrumentedFetch";

type Labels = Record<string, string | number | boolean>;

function captureHistogram(): {
calls: { name: string; value: number; attrs: Labels }[];
meter: MeterAdapter;
} {
const calls: { name: string; value: number; attrs: Labels }[] = [];
const meter: MeterAdapter = {
counterInc: vi.fn(),
gaugeSet: vi.fn(),
histogramRecord: (name, value, attrs) => {
calls.push({ name, value, attrs: attrs ?? {} });
},
};
return { calls, meter };
}

describe("createShopifyFetch", () => {
afterEach(() => {
vi.restoreAllMocks();
configureMeter({
counterInc: () => {},
gaugeSet: () => {},
histogramRecord: () => {},
});
});

it("emits commerce_request_duration_ms with provider=shopify on success", async () => {
const { calls, meter } = captureHistogram();
configureMeter(meter);

const baseFetch = vi.fn(async () => new Response("{}", { status: 200 }));
const fetchFn = createShopifyFetch({ baseFetch: baseFetch as typeof fetch });

await fetchFn("https://store.myshopify.com/api/2025-04/graphql.json", { method: "POST" });

expect(calls).toHaveLength(1);
expect(calls[0].attrs).toMatchObject({
provider: "shopify",
operation: "storefront.graphql",
status_code: "200",
});
});

it("honors init.operation (used by the GraphQL client to stamp <OperationName>)", async () => {
const { calls, meter } = captureHistogram();
configureMeter(meter);

const baseFetch = vi.fn(async () => new Response("{}", { status: 200 }));
const fetchFn = createShopifyFetch({ baseFetch: baseFetch as typeof fetch });

await fetchFn("https://store.myshopify.com/api/2025-04/graphql.json", {
method: "POST",
operation: "ProductBySlug",
});

expect(calls[0].attrs.operation).toBe("ProductBySlug");
});

it("skips histogram emission when disableHistogram is true", async () => {
const { calls, meter } = captureHistogram();
configureMeter(meter);

const baseFetch = vi.fn(async () => new Response("{}", { status: 200 }));
const fetchFn = createShopifyFetch({
baseFetch: baseFetch as typeof fetch,
disableHistogram: true,
});

await fetchFn("https://store.myshopify.com/api/2025-04/graphql.json", { method: "POST" });

expect(calls).toHaveLength(0);
});
});
Loading