@scayle/storefront-cms-contentstack 0.2.0-alpha.0 → 1.0.0-alpha.2
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/README.md +3 -12
- package/dist/index.d.mts +20 -14
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +15 -15
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -77,20 +77,11 @@ The package never reads `process.env` itself — the boilerplate is the sole pla
|
|
|
77
77
|
variables, and passes plain values into the constructor.
|
|
78
78
|
|
|
79
79
|
The boilerplate registers `createCMSService(storefront)` as the `cms` slot on the `ServiceRegistry`
|
|
80
|
-
(`src/server/registries.ts`), alongside every other domain. A controller resolves it from there
|
|
81
|
-
`
|
|
82
|
-
then calls `fetchPageData`/`fetchListingPageData` directly with the raw request:
|
|
80
|
+
(`src/server/registries.ts`), alongside every other domain. A controller resolves it from there and
|
|
81
|
+
calls `fetchPageData`/`fetchListingPageData` with `this.request` (the inbound `IncomingRequest`):
|
|
83
82
|
|
|
84
83
|
```ts
|
|
85
|
-
const
|
|
86
|
-
this.services.cms,
|
|
87
|
-
this.ctx.req,
|
|
88
|
-
)
|
|
89
|
-
const pageData = await this.services.cms.fetchPageData(
|
|
90
|
-
slug,
|
|
91
|
-
locale,
|
|
92
|
-
this.ctx.req,
|
|
93
|
-
)
|
|
84
|
+
const pageData = await this.services.cms.fetchPageData(slug, this.request)
|
|
94
85
|
```
|
|
95
86
|
|
|
96
87
|
See `@scayle/storefront`'s CMS module for the `CMSProviderService` contract this package implements.
|
package/dist/index.d.mts
CHANGED
|
@@ -1,11 +1,17 @@
|
|
|
1
|
-
import { CMSCspConfig, CMSEditorData, CMSPagePayload, CMSProviderService
|
|
2
|
-
import { StorefrontContext } from "@scayle/storefront/types";
|
|
1
|
+
import { CMSCspConfig, CMSEditorData, CMSPagePayload, CMSProviderService } from "@scayle/storefront/cms";
|
|
2
|
+
import { IncomingRequest, StorefrontContext } from "@scayle/storefront/types";
|
|
3
3
|
declare module "@scayle/storefront/cms" {
|
|
4
4
|
interface CMSEditorData {
|
|
5
|
-
|
|
5
|
+
/** Public stack API key for the Live Preview Utils SDK's `stackDetails.apiKey`. */
|
|
6
|
+
apiKey?: string;
|
|
6
7
|
environment?: string;
|
|
7
8
|
branch?: string;
|
|
8
|
-
|
|
9
|
+
/**
|
|
10
|
+
* Regional Contentstack application host (`eu-app.contentstack.com` and
|
|
11
|
+
* friends) for the Visual Builder "open in Contentstack" deep-link.
|
|
12
|
+
* Resolved server-side so the client does not repeat region lookup.
|
|
13
|
+
*/
|
|
14
|
+
appHost?: string;
|
|
9
15
|
}
|
|
10
16
|
}
|
|
11
17
|
/**
|
|
@@ -59,13 +65,15 @@ declare class ContentstackCMSService implements CMSProviderService {
|
|
|
59
65
|
constructor(config: ContentstackCMSServiceConfig, context: StorefrontContext);
|
|
60
66
|
/**
|
|
61
67
|
* Builds editor data for the current request.
|
|
62
|
-
* Contentstack's Live Preview SDK runs client-side and needs
|
|
63
|
-
*
|
|
68
|
+
* Contentstack's Live Preview SDK runs client-side and needs the public
|
|
69
|
+
* stack API key, environment, branch, and the regional application host to
|
|
70
|
+
* connect. These fields ship in server-rendered HTML, so no credential
|
|
71
|
+
* (delivery token, preview token) may ever appear here.
|
|
64
72
|
*
|
|
65
73
|
* @param request Incoming request, used to detect editor mode
|
|
66
74
|
* @returns Editor data fields for Inertia page props, or undefined outside an editor session
|
|
67
75
|
*/
|
|
68
|
-
getCMSEditorData(request:
|
|
76
|
+
getCMSEditorData(request: IncomingRequest): CMSEditorData | undefined;
|
|
69
77
|
private getDeliveryStack;
|
|
70
78
|
private createPreviewStack;
|
|
71
79
|
/**
|
|
@@ -76,7 +84,7 @@ declare class ContentstackCMSService implements CMSProviderService {
|
|
|
76
84
|
* @param request Incoming HTTP request
|
|
77
85
|
* @returns True when the request is from Contentstack's live preview
|
|
78
86
|
*/
|
|
79
|
-
isEditorMode(request:
|
|
87
|
+
isEditorMode(request: IncomingRequest): boolean;
|
|
80
88
|
/**
|
|
81
89
|
* Content-type UID and URL slug queried by `fetchPageData`.
|
|
82
90
|
* Override to look up a different content type or URL shape.
|
|
@@ -120,11 +128,10 @@ declare class ContentstackCMSService implements CMSProviderService {
|
|
|
120
128
|
* Preview requests bypass the cache entirely.
|
|
121
129
|
*
|
|
122
130
|
* @param slug CMS slug
|
|
123
|
-
* @param
|
|
124
|
-
* @param request Incoming request, used to detect editor mode and read editor-specific query params
|
|
131
|
+
* @param request Inbound request, used to detect editor mode and read editor-specific query params
|
|
125
132
|
* @returns Contentstack page data or undefined
|
|
126
133
|
*/
|
|
127
|
-
fetchPageData(slug: string,
|
|
134
|
+
fetchPageData(slug: string, request: IncomingRequest): Promise<CMSPagePayload | undefined>;
|
|
128
135
|
/**
|
|
129
136
|
* Content-type UID and URL slug queried by `fetchListingPageData`.
|
|
130
137
|
* Override to look up a different content type or URL shape.
|
|
@@ -155,11 +162,10 @@ declare class ContentstackCMSService implements CMSProviderService {
|
|
|
155
162
|
* missing PLP content is expected, not an error condition.
|
|
156
163
|
*
|
|
157
164
|
* @param categoryId SCAYLE category ID
|
|
158
|
-
* @param
|
|
159
|
-
* @param request Incoming request, used to detect editor mode and read editor-specific query params
|
|
165
|
+
* @param request Inbound request, used to detect editor mode and read editor-specific query params
|
|
160
166
|
* @returns Contentstack listing page data or undefined
|
|
161
167
|
*/
|
|
162
|
-
fetchListingPageData(categoryId: number,
|
|
168
|
+
fetchListingPageData(categoryId: number, request: IncomingRequest): Promise<CMSPagePayload | undefined>;
|
|
163
169
|
}
|
|
164
170
|
/**
|
|
165
171
|
* CSP configuration for the Contentstack provider.
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/ContentstackCMSService.ts","../src/csp.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/ContentstackCMSService.ts","../src/csp.ts"],"mappings":";;;YAoCmB;;IAEf;IACA;IACA;;;;;;IAMA;;;;;;;;UAqCa;;EAEf;;EAEA;;EAEA;;;;;;;EAOA;;EAEA;;EAEA;;EAEA;;;;;;;;;;;;;;;;;;cAmBW,kCAAkC;iBAC9B;WAEN,WAAW;mBAEH;mBAKA;mBAEA;EAEjB,YACE,QAAQ,8BACR,SAAS;;;;;;;;;;;EAsCX,iBAAiB,SAAS,kBAAkB;UAapC;UAsBA;;;;;;;;;EAsCR,aAAa,SAAS;;;;;;;;YAWZ,eAAe;IACvB;IACA;;;;;;;;;;;;;;UAiBY;;;;;;;;;;;;;;UAqCA;;;;;;;;;EAwEd,cACE,cACA,SAAS,kBACR,QAAQ;;;;;;;;YA8BD,kBAAkB;IAC1B;IACA;;;;;;;;;;;;;;UAoBY;;;;;;;;;;EAqDd,qBACE,oBACA,SAAS,kBACR,QAAQ;;;;;;;;cC5dA,WAAW"}
|
package/dist/index.mjs
CHANGED
|
@@ -2,14 +2,12 @@ import contentstack, { QueryOperation } from "@contentstack/delivery-sdk";
|
|
|
2
2
|
import { getContentstackEndpoints, getRegionForString } from "@timbenniks/contentstack-endpoints";
|
|
3
3
|
import { CMSContentNotFoundError, extractErrorStatus, wrapClientInit } from "@scayle/storefront/cms";
|
|
4
4
|
import { createLogger } from "@scayle/storefront/shared";
|
|
5
|
-
const
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
}
|
|
12
|
-
};
|
|
5
|
+
const isContentstackPreviewRequest = (request) => Boolean(request.query.live_preview);
|
|
6
|
+
const cspConfig = { directives: {
|
|
7
|
+
"frame-ancestors": "'self' https://*.contentstack.com",
|
|
8
|
+
"script-src": "'self' 'unsafe-inline' https://*.contentstack.com",
|
|
9
|
+
"connect-src": "'self' https://*.contentstack.io https://*.contentstack.com"
|
|
10
|
+
} };
|
|
13
11
|
const log = createLogger("cms");
|
|
14
12
|
const CACHE_TTL_SECONDS = 300;
|
|
15
13
|
function resolveRegion(region) {
|
|
@@ -40,10 +38,10 @@ var ContentstackCMSService = class ContentstackCMSService {
|
|
|
40
38
|
getCMSEditorData(request) {
|
|
41
39
|
if (!this.isEditorMode(request)) return;
|
|
42
40
|
return {
|
|
43
|
-
|
|
41
|
+
apiKey: this.config.apiKey,
|
|
44
42
|
environment: this.config.environment,
|
|
45
43
|
branch: this.config.branch,
|
|
46
|
-
|
|
44
|
+
appHost: getEndpoints(this.config.region).application
|
|
47
45
|
};
|
|
48
46
|
}
|
|
49
47
|
getDeliveryStack() {
|
|
@@ -77,7 +75,7 @@ var ContentstackCMSService = class ContentstackCMSService {
|
|
|
77
75
|
}), "Contentstack preview stack initialization failed. Check that CONTENTSTACK_CMS_STACK_API_KEY is a valid API key, CONTENTSTACK_CMS_DELIVERY_TOKEN is a valid delivery token, CONTENTSTACK_CMS_PREVIEW_ACCESS_TOKEN is a valid preview token, and CONTENTSTACK_CMS_ENVIRONMENT is a valid environment name");
|
|
78
76
|
}
|
|
79
77
|
isEditorMode(request) {
|
|
80
|
-
return
|
|
78
|
+
return isContentstackPreviewRequest(request);
|
|
81
79
|
}
|
|
82
80
|
buildPageQuery(slug) {
|
|
83
81
|
return {
|
|
@@ -95,10 +93,10 @@ var ContentstackCMSService = class ContentstackCMSService {
|
|
|
95
93
|
async fetchRawPageData(slug, locale, useDraftContent, request) {
|
|
96
94
|
const stack = useDraftContent ? this.createPreviewStack() : this.getDeliveryStack();
|
|
97
95
|
const { contentTypeUid, url } = this.buildPageQuery(slug);
|
|
98
|
-
const livePreview = useDraftContent && request.query
|
|
96
|
+
const livePreview = useDraftContent && request.query.live_preview;
|
|
99
97
|
if (livePreview) stack.livePreviewQuery({
|
|
100
98
|
live_preview: livePreview,
|
|
101
|
-
content_type_uid: request.query
|
|
99
|
+
content_type_uid: request.query.content_type_uid ?? contentTypeUid
|
|
102
100
|
});
|
|
103
101
|
try {
|
|
104
102
|
const entry = await this.findEntry(stack, contentTypeUid, url, locale);
|
|
@@ -127,7 +125,8 @@ var ContentstackCMSService = class ContentstackCMSService {
|
|
|
127
125
|
throw new Error(`Contentstack API request failed (slug: "${slug}", locale: "${locale}", content-type: "${contentTypeUid}"): ${cause.message}`, { cause });
|
|
128
126
|
}
|
|
129
127
|
}
|
|
130
|
-
async fetchPageData(slug,
|
|
128
|
+
async fetchPageData(slug, request) {
|
|
129
|
+
const locale = this.context.country.locale;
|
|
131
130
|
const useDraftContent = this.isEditorMode(request) && this.draftContentEnabled;
|
|
132
131
|
if (useDraftContent) {
|
|
133
132
|
log.debug({
|
|
@@ -172,7 +171,8 @@ var ContentstackCMSService = class ContentstackCMSService {
|
|
|
172
171
|
throw new Error(`Contentstack API request failed (category: ${categoryId}, url: "${url}", locale: "${locale}", content-type: "${contentTypeUid}"): ${cause.message}`, { cause });
|
|
173
172
|
}
|
|
174
173
|
}
|
|
175
|
-
async fetchListingPageData(categoryId,
|
|
174
|
+
async fetchListingPageData(categoryId, request) {
|
|
175
|
+
const locale = this.context.country.locale;
|
|
176
176
|
const useDraftContent = this.isEditorMode(request) && this.draftContentEnabled;
|
|
177
177
|
const fetchListing = async () => {
|
|
178
178
|
try {
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/csp.ts","../src/ContentstackCMSService.ts"],"sourcesContent":["import type { CMSCspConfig } from '@scayle/storefront/cms'\n\n/**\n * CSP configuration for the Contentstack provider.\n * Allows the Contentstack Visual Builder to embed the storefront in an\n * iframe and the Live Preview SDK to communicate with the Contentstack API.\n * Uses wildcard subdomains for region-agnostic support (EU, US, Azure, GCP).\n */\nexport const cspConfig: CMSCspConfig = {\n isPreviewRequest: (req) => Boolean(req.query('live_preview')),\n directives: {\n 'frame-ancestors': \"'self' https://*.contentstack.com\",\n 'script-src': \"'self' 'unsafe-inline' https://*.contentstack.com\",\n 'connect-src':\n \"'self' https://*.contentstack.io https://*.contentstack.com\",\n },\n}\n","import contentstack, { QueryOperation } from '@contentstack/delivery-sdk'\nimport type { Stack } from '@contentstack/delivery-sdk'\nimport {\n getContentstackEndpoints,\n getRegionForString,\n} from '@timbenniks/contentstack-endpoints'\nimport {\n CMSContentNotFoundError,\n extractErrorStatus,\n wrapClientInit,\n} from '@scayle/storefront/cms'\nimport type {\n CMSCspConfig,\n CMSEditorData,\n CMSPagePayload,\n CMSProviderService,\n CMSRequestLike,\n} from '@scayle/storefront/cms'\nimport { createLogger } from '@scayle/storefront/shared'\nimport type { StorefrontContext } from '@scayle/storefront/types'\nimport { cspConfig } from './csp'\n\nconst log = createLogger('cms')\n\n/** Cache TTL for published CMS content: 5 minutes. */\nconst CACHE_TTL_SECONDS = 5 * 60\n\ndeclare module '@scayle/storefront/cms' {\n /**\n * Fields added by `ContentstackCMSService.getCMSEditorData()` for the\n * client-side Live Preview SDK. A tenant project can layer further fields\n * onto `CMSEditorData` with its own `declare module` block; TypeScript\n * merges augmentations from every file in the program.\n */\n export interface CMSEditorData {\n accessToken?: string\n environment?: string\n branch?: string\n region?: string\n }\n}\n\n/**\n * Resolves a configured region string to a Contentstack region identifier.\n *\n * `getContentstackEndpoints` returns an empty object rather than throwing for an\n * unknown region, which would leave `host` undefined and let the Delivery SDK\n * silently fall back to its North America default. Resolving up front turns a\n * misconfigured region into a startup error instead of wrong-region content.\n *\n * @param region Configured region value\n * @returns Canonical region identifier\n * @throws Error when the region is not a recognized Contentstack region\n */\nfunction resolveRegion(region: string): string {\n const resolved = getRegionForString(region)\n\n if (!resolved) {\n throw new Error(\n `Contentstack CMS initialization failed: invalid region \"${region}\". Set CONTENTSTACK_CMS_REGION to one of: na, eu, au, azure-na, azure-eu, gcp-na, gcp-eu. The aliases \"us\", \"aws-na\", \"aws-eu\", and \"aws-au\" are also accepted. See https://www.contentstack.com/docs/developers/contentstack-regions/api-endpoints`,\n )\n }\n\n return resolved\n}\n\nfunction getEndpoints(region: string) {\n return getContentstackEndpoints(resolveRegion(region), true)\n}\n\n/**\n * Configuration accepted by {@link ContentstackCMSService}'s constructor.\n * The boilerplate reads these from environment variables and passes plain\n * values in, so this package never touches `process.env` directly.\n */\nexport interface ContentstackCMSServiceConfig {\n /** Stack API key (Stack > Settings > Tokens). Used as `apiKey` in the Delivery SDK. */\n apiKey: string\n /** Content Delivery Token for the target environment. */\n deliveryToken: string\n /** Environment name (e.g. `production`, `staging`). */\n environment: string\n /**\n * Stack region: `na`, `eu`, `au`, `azure-na`, `azure-eu`, `gcp-na`, or\n * `gcp-eu`. The aliases `us`, `aws-na`, `aws-eu`, and `aws-au` are also\n * accepted. Defaults to `na` when unset or empty. An unrecognized value\n * throws at initialization.\n */\n region?: string\n /** Optional content branch name. */\n branch?: string\n /** Preview Token, read lazily on first preview request. */\n previewAccessToken?: string\n /** Whether to fetch draft content when the request is in editor mode. */\n draftContentEnabled: boolean\n}\n\n/**\n * Contentstack CMS provider service.\n * Uses a static singleton for delivery (read-only, safe across requests)\n * and creates a fresh Stack instance per preview request because\n * `livePreviewQuery()` mutates the internal config.\n *\n * Unlike Storyblok and Contentful, this class needs no tenant subclass\n * today — `isPageComponent`/`isProductlistingpageComponent` check a fixed\n * `seo` field shape rather than delegating to generated guards. The\n * boilerplate still keeps a thin `service.ts` wrapper per tenant fork\n * (constructed from env vars via `createCMSService()`), since that file is\n * what `pnpm cms:sync` and future tenant customization would touch, even\n * though it currently has no override to add.\n *\n * @see https://www.contentstack.com/docs/developers/sdks/content-delivery-sdk/typescript/get-started-with-typescript-delivery-sdk\n */\nexport class ContentstackCMSService implements CMSProviderService {\n private static deliveryStack: Stack | undefined\n\n readonly cspConfig: CMSCspConfig = cspConfig\n\n private readonly config: Required<\n Omit<ContentstackCMSServiceConfig, 'branch' | 'previewAccessToken'>\n > &\n Pick<ContentstackCMSServiceConfig, 'branch' | 'previewAccessToken'>\n\n private readonly draftContentEnabled: boolean\n\n private readonly context: StorefrontContext\n\n constructor(\n config: ContentstackCMSServiceConfig,\n context: StorefrontContext,\n ) {\n if (!config.apiKey) {\n throw new Error(\n 'Contentstack CMS initialization failed: missing or empty API key. Check that CONTENTSTACK_CMS_STACK_API_KEY is set.',\n )\n }\n\n if (!config.deliveryToken) {\n throw new Error(\n 'Contentstack CMS initialization failed: missing or empty delivery token. Check that CONTENTSTACK_CMS_DELIVERY_TOKEN is set.',\n )\n }\n\n if (!config.environment) {\n throw new Error(\n 'Contentstack CMS initialization failed: missing or empty environment. Check that CONTENTSTACK_CMS_ENVIRONMENT is set.',\n )\n }\n\n // `||` not `??`: a blanked `CONTENTSTACK_CMS_REGION=` arrives as an empty\n // string, which is \"not set\" rather than a typo. This matches the `region ||\n // 'na'` in the setup CLI and `${CONTENTSTACK_CMS_REGION:-na}` in sync-cms.sh.\n this.config = { ...config, region: resolveRegion(config.region || 'na') }\n this.draftContentEnabled = config.draftContentEnabled\n this.context = context\n }\n\n /**\n * Builds editor data for the current request.\n * Contentstack's Live Preview SDK runs client-side and needs its own\n * access token, environment, branch, and region to connect.\n *\n * @param request Incoming request, used to detect editor mode\n * @returns Editor data fields for Inertia page props, or undefined outside an editor session\n */\n getCMSEditorData(request: CMSRequestLike): CMSEditorData | undefined {\n if (!this.isEditorMode(request)) {\n return undefined\n }\n\n return {\n accessToken: this.config.deliveryToken,\n environment: this.config.environment,\n branch: this.config.branch,\n region: this.config.region,\n }\n }\n\n private getDeliveryStack(): Stack {\n if (ContentstackCMSService.deliveryStack) {\n return ContentstackCMSService.deliveryStack\n }\n\n const { apiKey, deliveryToken, environment, region } = this.config\n const endpoints = getEndpoints(region)\n\n ContentstackCMSService.deliveryStack = wrapClientInit(\n () =>\n contentstack.stack({\n apiKey,\n deliveryToken,\n environment,\n region,\n host: endpoints.contentDelivery,\n }),\n 'Contentstack delivery stack initialization failed. Check that CONTENTSTACK_CMS_STACK_API_KEY is a valid API key, CONTENTSTACK_CMS_DELIVERY_TOKEN is a valid delivery token, and CONTENTSTACK_CMS_ENVIRONMENT is a valid environment name',\n )\n return ContentstackCMSService.deliveryStack\n }\n\n private createPreviewStack(): Stack {\n const { apiKey, deliveryToken, environment, region, previewAccessToken } =\n this.config\n\n if (!previewAccessToken) {\n throw new Error(\n 'Contentstack CMS initialization failed: missing or empty preview token. Check that CONTENTSTACK_CMS_PREVIEW_ACCESS_TOKEN is set.',\n )\n }\n\n const endpoints = getEndpoints(region)\n\n return wrapClientInit(\n () =>\n contentstack.stack({\n apiKey,\n deliveryToken,\n environment,\n region,\n host: endpoints.contentDelivery,\n live_preview: {\n enable: true,\n preview_token: previewAccessToken,\n host: endpoints.preview,\n },\n }),\n 'Contentstack preview stack initialization failed. Check that CONTENTSTACK_CMS_STACK_API_KEY is a valid API key, CONTENTSTACK_CMS_DELIVERY_TOKEN is a valid delivery token, CONTENTSTACK_CMS_PREVIEW_ACCESS_TOKEN is a valid preview token, and CONTENTSTACK_CMS_ENVIRONMENT is a valid environment name',\n )\n }\n\n /**\n * Checks whether the current request originates from the Contentstack\n * Live Preview / Visual Builder. Detects editor mode via the\n * `live_preview` query parameter.\n *\n * @param request Incoming HTTP request\n * @returns True when the request is from Contentstack's live preview\n */\n isEditorMode(request: CMSRequestLike): boolean {\n return Boolean(request.query('live_preview'))\n }\n\n /**\n * Content-type UID and URL slug queried by `fetchPageData`.\n * Override to look up a different content type or URL shape.\n *\n * @param slug Page slug to look up\n * @returns Content-type UID and the `url` field value to match\n */\n protected buildPageQuery(slug: string): {\n contentTypeUid: string\n url: string\n } {\n return { contentTypeUid: 'page-component', url: `/${slug}` }\n }\n\n /**\n * Runs a Contentstack entry query for the given content type and URL,\n * returning the first matching entry. Shared by `fetchPageData` and\n * `fetchListingPageData`; override `buildPageQuery`/`buildListingQuery`\n * to change what gets queried, not this method.\n *\n * @param stack Delivery or preview stack\n * @param contentTypeUid Content-type UID to query\n * @param url URL field value to match\n * @param locale Storefront locale code\n * @returns First matching entry, or undefined when none match\n */\n private async findEntry(\n stack: Stack,\n contentTypeUid: string,\n url: string,\n locale: string,\n ): Promise<unknown | undefined> {\n const result = await stack\n .contentType(contentTypeUid)\n .entry()\n .locale(locale.toLowerCase())\n .includeFallback()\n .query()\n .where('url', QueryOperation.EQUALS, url)\n .addParams({\n include_all: 'true',\n include_all_depth: '5',\n include_dimension: 'true',\n })\n .limit(1)\n .find()\n\n return result.entries?.at(0)\n }\n\n /**\n * Retrieves CMS page content from Contentstack by slug.\n * Uses the delivery singleton for normal requests and a fresh preview\n * instance for live preview requests. Tags entries with editable-field\n * metadata when the request is an active live preview session.\n *\n * @param slug Page slug to look up\n * @param locale Storefront locale code\n * @param useDraftContent Whether to fetch draft content instead of published content\n * @param request Incoming request, used to read editor-specific query params\n * @returns Contentstack page data\n * @throws {CMSContentNotFoundError} When no entry matches the slug\n */\n private async fetchRawPageData(\n slug: string,\n locale: string,\n useDraftContent: boolean,\n request: CMSRequestLike,\n ): Promise<CMSPagePayload | undefined> {\n const stack = useDraftContent\n ? this.createPreviewStack()\n : this.getDeliveryStack()\n const { contentTypeUid, url } = this.buildPageQuery(slug)\n const livePreview = useDraftContent && request.query('live_preview')\n\n if (livePreview) {\n stack.livePreviewQuery({\n live_preview: livePreview,\n content_type_uid: request.query('content_type_uid') ?? contentTypeUid,\n })\n }\n\n try {\n const entry = await this.findEntry(stack, contentTypeUid, url, locale)\n\n if (!entry) {\n throw new CMSContentNotFoundError('Contentstack content not found', {\n details: { slug, locale, contentTypeUid, url },\n })\n }\n\n if (livePreview) {\n try {\n contentstack.Utils.addEditableTags(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry as any,\n contentTypeUid,\n true,\n locale.toLowerCase(),\n )\n } catch {\n // Editable tags only add inline edit markers for the Visual\n // Builder; a tagging failure must not fail the page request itself.\n }\n }\n\n return { entry }\n } catch (error) {\n if (error instanceof CMSContentNotFoundError) {\n throw error\n }\n\n if (extractErrorStatus(error) === 404) {\n throw new CMSContentNotFoundError('Contentstack content not found', {\n cause: error,\n details: { slug, locale, contentTypeUid, url },\n })\n }\n\n const cause = error instanceof Error ? error : new Error(String(error))\n throw new Error(\n `Contentstack API request failed (slug: \"${slug}\", locale: \"${locale}\", content-type: \"${contentTypeUid}\"): ${cause.message}`,\n { cause },\n )\n }\n }\n\n /**\n * Retrieves CMS page data with application-level caching.\n * Preview requests bypass the cache entirely.\n *\n * @param slug CMS slug\n * @param locale Storefront locale code\n * @param request Incoming request, used to detect editor mode and read editor-specific query params\n * @returns Contentstack page data or undefined\n */\n async fetchPageData(\n slug: string,\n locale: string,\n request: CMSRequestLike,\n ): Promise<CMSPagePayload | undefined> {\n const useDraftContent =\n this.isEditorMode(request) && this.draftContentEnabled\n\n if (useDraftContent) {\n log.debug({\n message: 'Bypassing CMS cache in preview mode',\n slug,\n locale,\n })\n return await this.fetchRawPageData(slug, locale, useDraftContent, request)\n }\n\n return await this.context.cache.getOrSet(\n `cms:contentstack:page:${slug}:${locale}`,\n // Cast required: StorageValue excludes undefined, but the fetch can return undefined for missing content\n () =>\n this.fetchRawPageData(slug, locale, useDraftContent, request) as never,\n CACHE_TTL_SECONDS,\n )\n }\n\n /**\n * Content-type UID and URL slug queried by `fetchListingPageData`.\n * Override to look up a different content type or URL shape.\n *\n * @param categoryId SCAYLE category ID\n * @returns Content-type UID and the `url` field value to match\n */\n protected buildListingQuery(categoryId: number): {\n contentTypeUid: string\n url: string\n } {\n return {\n contentTypeUid: 'productlistingpage-component',\n url: `/c/c-${categoryId}`,\n }\n }\n\n /**\n * Retrieves CMS content for a product listing page.\n * Throws {@link CMSContentNotFoundError} when no entry matches the\n * category; {@link fetchListingPageData} converts that into `undefined`\n * for the caller.\n *\n * @param categoryId SCAYLE category ID\n * @param locale Storefront locale code\n * @param useDraftContent Whether to fetch draft content instead of published content\n * @returns Contentstack listing page data\n * @throws {CMSContentNotFoundError} When no entry matches the category\n */\n private async fetchRawListingPageData(\n categoryId: number,\n locale: string,\n useDraftContent: boolean,\n ): Promise<CMSPagePayload | undefined> {\n const stack = useDraftContent\n ? this.createPreviewStack()\n : this.getDeliveryStack()\n const { contentTypeUid, url } = this.buildListingQuery(categoryId)\n\n try {\n const entry = await this.findEntry(stack, contentTypeUid, url, locale)\n\n if (!entry) {\n throw new CMSContentNotFoundError(\n 'Contentstack listing content not found',\n { details: { categoryId, slug: url, locale, contentTypeUid } },\n )\n }\n\n return { entry }\n } catch (error) {\n if (error instanceof CMSContentNotFoundError) {\n throw error\n }\n\n if (extractErrorStatus(error) === 404) {\n throw new CMSContentNotFoundError(\n 'Contentstack listing content not found',\n {\n cause: error,\n details: { categoryId, slug: url, locale, contentTypeUid },\n },\n )\n }\n\n const cause = error instanceof Error ? error : new Error(String(error))\n throw new Error(\n `Contentstack API request failed (category: ${categoryId}, url: \"${url}\", locale: \"${locale}\", content-type: \"${contentTypeUid}\"): ${cause.message}`,\n { cause },\n )\n }\n }\n\n /**\n * Retrieves CMS content for a product listing page, with caching.\n * Converts a missing entry into `undefined` rather than throwing, since\n * missing PLP content is expected, not an error condition.\n *\n * @param categoryId SCAYLE category ID\n * @param locale Storefront locale code\n * @param request Incoming request, used to detect editor mode and read editor-specific query params\n * @returns Contentstack listing page data or undefined\n */\n async fetchListingPageData(\n categoryId: number,\n locale: string,\n request: CMSRequestLike,\n ): Promise<CMSPagePayload | undefined> {\n const useDraftContent =\n this.isEditorMode(request) && this.draftContentEnabled\n const fetchListing = async () => {\n try {\n return await this.fetchRawListingPageData(\n categoryId,\n locale,\n useDraftContent,\n )\n } catch (error) {\n if (error instanceof CMSContentNotFoundError) {\n return undefined\n }\n\n log.error({\n message: 'Failed to fetch CMS listing page data',\n err: error instanceof Error ? error : new Error(String(error)),\n categoryId,\n locale,\n })\n\n throw error\n }\n }\n\n if (useDraftContent) {\n log.debug({\n message: 'Bypassing CMS PLP cache in preview mode',\n categoryId,\n locale,\n })\n return await fetchListing()\n }\n\n return await this.context.cache.getOrSet(\n `cms:contentstack:plp:${categoryId}:${locale}`,\n // Cast required: StorageValue excludes undefined, but the fetch can return undefined for missing content\n () => fetchListing() as never,\n CACHE_TTL_SECONDS,\n )\n }\n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AAA,EAAA,MAAA,CAAA;EACzD;CAGF;CAGE,MAAI,qBACQ,YAAA,QAAA,SAAwB;EACrB,MAAA,kBAAA,KAAA,aAAA,OAAA,KAAA,KAAA;EAAM,MAAA,eAAA,YAAA;GAAQ,IAAA;IAAgB,OAAA,MAAA,KAAA,wBAAA,YAAA,QAAA,eAAA;GAAI,SAC9C,OAAA;IAGH,IAAI,iBACE,yBAAA;IACF,IAAA,MAAA;KAOF,SAGA;KAGF,KAAO,iBAAQ,QAAA,QAAA,IAAA,MAAA,OAAA,KAAA,CAAA;KACjB;KACE;IAIA,CAAA;IAEI,MAAA;GACA;EAAW;EAAM,IAAA,iBAAA;GAAQ,IAAA,MAAA;IAAgB,SAAA;IAAI;IAC9C;GAGH,CAAA;GACA,OAAM,MAAI,aACR;EAGJ;EACF,OAAA,MAAA,KAAA,QAAA,MAAA,SAAA,wBAAA,WAAA,GAAA,gBAAA,aAAA,GAAA,iBAAA"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/csp.ts","../src/ContentstackCMSService.ts"],"sourcesContent":["import type { CMSCspConfig } from '@scayle/storefront/cms'\nimport type { IncomingRequest } from '@scayle/storefront/types'\n\n/**\n * Checks whether the request is a Contentstack Live Preview session.\n *\n * Contentstack injects `live_preview` into the iframe URL; both editor-mode\n * detection and preview CSP use this same predicate.\n *\n * @param request Inbound request\n * @returns True when `live_preview` is present on the query string\n */\nexport const isContentstackPreviewRequest = (\n request: IncomingRequest,\n): boolean => Boolean(request.query.live_preview)\n\n/**\n * CSP configuration for the Contentstack provider.\n * Allows the Contentstack Visual Builder to embed the storefront in an\n * iframe and the Live Preview SDK to communicate with the Contentstack API.\n * Uses wildcard subdomains for region-agnostic support (EU, US, Azure, GCP).\n */\nexport const cspConfig: CMSCspConfig = {\n directives: {\n 'frame-ancestors': \"'self' https://*.contentstack.com\",\n 'script-src': \"'self' 'unsafe-inline' https://*.contentstack.com\",\n 'connect-src':\n \"'self' https://*.contentstack.io https://*.contentstack.com\",\n },\n}\n","import contentstack, { QueryOperation } from '@contentstack/delivery-sdk'\nimport type { Stack } from '@contentstack/delivery-sdk'\nimport {\n getContentstackEndpoints,\n getRegionForString,\n} from '@timbenniks/contentstack-endpoints'\nimport {\n CMSContentNotFoundError,\n extractErrorStatus,\n wrapClientInit,\n} from '@scayle/storefront/cms'\nimport type {\n CMSCspConfig,\n CMSEditorData,\n CMSPagePayload,\n CMSProviderService,\n} from '@scayle/storefront/cms'\nimport { createLogger } from '@scayle/storefront/shared'\nimport type {\n IncomingRequest,\n StorefrontContext,\n} from '@scayle/storefront/types'\nimport { cspConfig, isContentstackPreviewRequest } from './csp'\n\nconst log = createLogger('cms')\n\n/** Cache TTL for published CMS content: 5 minutes. */\nconst CACHE_TTL_SECONDS = 5 * 60\n\ndeclare module '@scayle/storefront/cms' {\n /**\n * Fields added by `ContentstackCMSService.getCMSEditorData()` for the\n * client-side Live Preview SDK. A tenant project can layer further fields\n * onto `CMSEditorData` with its own `declare module` block; TypeScript\n * merges augmentations from every file in the program.\n */\n export interface CMSEditorData {\n /** Public stack API key for the Live Preview Utils SDK's `stackDetails.apiKey`. */\n apiKey?: string\n environment?: string\n branch?: string\n /**\n * Regional Contentstack application host (`eu-app.contentstack.com` and\n * friends) for the Visual Builder \"open in Contentstack\" deep-link.\n * Resolved server-side so the client does not repeat region lookup.\n */\n appHost?: string\n }\n}\n\n/**\n * Resolves a configured region string to a Contentstack region identifier.\n *\n * `getContentstackEndpoints` returns an empty object rather than throwing for an\n * unknown region, which would leave `host` undefined and let the Delivery SDK\n * silently fall back to its North America default. Resolving up front turns a\n * misconfigured region into a startup error instead of wrong-region content.\n *\n * @param region Configured region value\n * @returns Canonical region identifier\n * @throws Error when the region is not a recognized Contentstack region\n */\nfunction resolveRegion(region: string): string {\n const resolved = getRegionForString(region)\n\n if (!resolved) {\n throw new Error(\n `Contentstack CMS initialization failed: invalid region \"${region}\". Set CONTENTSTACK_CMS_REGION to one of: na, eu, au, azure-na, azure-eu, gcp-na, gcp-eu. The aliases \"us\", \"aws-na\", \"aws-eu\", and \"aws-au\" are also accepted. See https://www.contentstack.com/docs/developers/contentstack-regions/api-endpoints`,\n )\n }\n\n return resolved\n}\n\nfunction getEndpoints(region: string) {\n return getContentstackEndpoints(resolveRegion(region), true)\n}\n\n/**\n * Configuration accepted by {@link ContentstackCMSService}'s constructor.\n * The boilerplate reads these from environment variables and passes plain\n * values in, so this package never touches `process.env` directly.\n */\nexport interface ContentstackCMSServiceConfig {\n /** Stack API key (Stack > Settings > Tokens). Used as `apiKey` in the Delivery SDK. */\n apiKey: string\n /** Content Delivery Token for the target environment. */\n deliveryToken: string\n /** Environment name (e.g. `production`, `staging`). */\n environment: string\n /**\n * Stack region: `na`, `eu`, `au`, `azure-na`, `azure-eu`, `gcp-na`, or\n * `gcp-eu`. The aliases `us`, `aws-na`, `aws-eu`, and `aws-au` are also\n * accepted. Defaults to `na` when unset or empty. An unrecognized value\n * throws at initialization.\n */\n region?: string\n /** Optional content branch name. */\n branch?: string\n /** Preview Token, read lazily on first preview request. */\n previewAccessToken?: string\n /** Whether to fetch draft content when the request is in editor mode. */\n draftContentEnabled: boolean\n}\n\n/**\n * Contentstack CMS provider service.\n * Uses a static singleton for delivery (read-only, safe across requests)\n * and creates a fresh Stack instance per preview request because\n * `livePreviewQuery()` mutates the internal config.\n *\n * Unlike Storyblok and Contentful, this class needs no tenant subclass\n * today — `isPageComponent`/`isProductlistingpageComponent` check a fixed\n * `seo` field shape rather than delegating to generated guards. The\n * boilerplate still keeps a thin `service.ts` wrapper per tenant fork\n * (constructed from env vars via `createCMSService()`), since that file is\n * what `pnpm cms:sync` and future tenant customization would touch, even\n * though it currently has no override to add.\n *\n * @see https://www.contentstack.com/docs/developers/sdks/content-delivery-sdk/typescript/get-started-with-typescript-delivery-sdk\n */\nexport class ContentstackCMSService implements CMSProviderService {\n private static deliveryStack: Stack | undefined\n\n readonly cspConfig: CMSCspConfig = cspConfig\n\n private readonly config: Required<\n Omit<ContentstackCMSServiceConfig, 'branch' | 'previewAccessToken'>\n > &\n Pick<ContentstackCMSServiceConfig, 'branch' | 'previewAccessToken'>\n\n private readonly draftContentEnabled: boolean\n\n private readonly context: StorefrontContext\n\n constructor(\n config: ContentstackCMSServiceConfig,\n context: StorefrontContext,\n ) {\n if (!config.apiKey) {\n throw new Error(\n 'Contentstack CMS initialization failed: missing or empty API key. Check that CONTENTSTACK_CMS_STACK_API_KEY is set.',\n )\n }\n\n if (!config.deliveryToken) {\n throw new Error(\n 'Contentstack CMS initialization failed: missing or empty delivery token. Check that CONTENTSTACK_CMS_DELIVERY_TOKEN is set.',\n )\n }\n\n if (!config.environment) {\n throw new Error(\n 'Contentstack CMS initialization failed: missing or empty environment. Check that CONTENTSTACK_CMS_ENVIRONMENT is set.',\n )\n }\n\n // `||` not `??`: a blanked `CONTENTSTACK_CMS_REGION=` arrives as an empty\n // string, which is \"not set\" rather than a typo. This matches the `region ||\n // 'na'` in the setup CLI and `${CONTENTSTACK_CMS_REGION:-na}` in sync-cms.sh.\n this.config = { ...config, region: resolveRegion(config.region || 'na') }\n this.draftContentEnabled = config.draftContentEnabled\n this.context = context\n }\n\n /**\n * Builds editor data for the current request.\n * Contentstack's Live Preview SDK runs client-side and needs the public\n * stack API key, environment, branch, and the regional application host to\n * connect. These fields ship in server-rendered HTML, so no credential\n * (delivery token, preview token) may ever appear here.\n *\n * @param request Incoming request, used to detect editor mode\n * @returns Editor data fields for Inertia page props, or undefined outside an editor session\n */\n getCMSEditorData(request: IncomingRequest): CMSEditorData | undefined {\n if (!this.isEditorMode(request)) {\n return undefined\n }\n\n return {\n apiKey: this.config.apiKey,\n environment: this.config.environment,\n branch: this.config.branch,\n appHost: getEndpoints(this.config.region).application,\n }\n }\n\n private getDeliveryStack(): Stack {\n if (ContentstackCMSService.deliveryStack) {\n return ContentstackCMSService.deliveryStack\n }\n\n const { apiKey, deliveryToken, environment, region } = this.config\n const endpoints = getEndpoints(region)\n\n ContentstackCMSService.deliveryStack = wrapClientInit(\n () =>\n contentstack.stack({\n apiKey,\n deliveryToken,\n environment,\n region,\n host: endpoints.contentDelivery,\n }),\n 'Contentstack delivery stack initialization failed. Check that CONTENTSTACK_CMS_STACK_API_KEY is a valid API key, CONTENTSTACK_CMS_DELIVERY_TOKEN is a valid delivery token, and CONTENTSTACK_CMS_ENVIRONMENT is a valid environment name',\n )\n return ContentstackCMSService.deliveryStack\n }\n\n private createPreviewStack(): Stack {\n const { apiKey, deliveryToken, environment, region, previewAccessToken } =\n this.config\n\n if (!previewAccessToken) {\n throw new Error(\n 'Contentstack CMS initialization failed: missing or empty preview token. Check that CONTENTSTACK_CMS_PREVIEW_ACCESS_TOKEN is set.',\n )\n }\n\n const endpoints = getEndpoints(region)\n\n return wrapClientInit(\n () =>\n contentstack.stack({\n apiKey,\n deliveryToken,\n environment,\n region,\n host: endpoints.contentDelivery,\n live_preview: {\n enable: true,\n preview_token: previewAccessToken,\n host: endpoints.preview,\n },\n }),\n 'Contentstack preview stack initialization failed. Check that CONTENTSTACK_CMS_STACK_API_KEY is a valid API key, CONTENTSTACK_CMS_DELIVERY_TOKEN is a valid delivery token, CONTENTSTACK_CMS_PREVIEW_ACCESS_TOKEN is a valid preview token, and CONTENTSTACK_CMS_ENVIRONMENT is a valid environment name',\n )\n }\n\n /**\n * Checks whether the current request originates from the Contentstack\n * Live Preview / Visual Builder. Detects editor mode via the\n * `live_preview` query parameter.\n *\n * @param request Incoming HTTP request\n * @returns True when the request is from Contentstack's live preview\n */\n isEditorMode(request: IncomingRequest): boolean {\n return isContentstackPreviewRequest(request)\n }\n\n /**\n * Content-type UID and URL slug queried by `fetchPageData`.\n * Override to look up a different content type or URL shape.\n *\n * @param slug Page slug to look up\n * @returns Content-type UID and the `url` field value to match\n */\n protected buildPageQuery(slug: string): {\n contentTypeUid: string\n url: string\n } {\n return { contentTypeUid: 'page-component', url: `/${slug}` }\n }\n\n /**\n * Runs a Contentstack entry query for the given content type and URL,\n * returning the first matching entry. Shared by `fetchPageData` and\n * `fetchListingPageData`; override `buildPageQuery`/`buildListingQuery`\n * to change what gets queried, not this method.\n *\n * @param stack Delivery or preview stack\n * @param contentTypeUid Content-type UID to query\n * @param url URL field value to match\n * @param locale Storefront locale code\n * @returns First matching entry, or undefined when none match\n */\n private async findEntry(\n stack: Stack,\n contentTypeUid: string,\n url: string,\n locale: string,\n ): Promise<unknown | undefined> {\n const result = await stack\n .contentType(contentTypeUid)\n .entry()\n .locale(locale.toLowerCase())\n .includeFallback()\n .query()\n .where('url', QueryOperation.EQUALS, url)\n .addParams({\n include_all: 'true',\n include_all_depth: '5',\n include_dimension: 'true',\n })\n .limit(1)\n .find()\n\n return result.entries?.at(0)\n }\n\n /**\n * Retrieves CMS page content from Contentstack by slug.\n * Uses the delivery singleton for normal requests and a fresh preview\n * instance for live preview requests. Tags entries with editable-field\n * metadata when the request is an active live preview session.\n *\n * @param slug Page slug to look up\n * @param locale Storefront locale code\n * @param useDraftContent Whether to fetch draft content instead of published content\n * @param request Incoming request, used to read editor-specific query params\n * @returns Contentstack page data\n * @throws {CMSContentNotFoundError} When no entry matches the slug\n */\n private async fetchRawPageData(\n slug: string,\n locale: string,\n useDraftContent: boolean,\n request: IncomingRequest,\n ): Promise<CMSPagePayload | undefined> {\n const stack = useDraftContent\n ? this.createPreviewStack()\n : this.getDeliveryStack()\n const { contentTypeUid, url } = this.buildPageQuery(slug)\n const livePreview = useDraftContent && request.query.live_preview\n\n if (livePreview) {\n stack.livePreviewQuery({\n live_preview: livePreview,\n content_type_uid: request.query.content_type_uid ?? contentTypeUid,\n })\n }\n\n try {\n const entry = await this.findEntry(stack, contentTypeUid, url, locale)\n\n if (!entry) {\n throw new CMSContentNotFoundError('Contentstack content not found', {\n details: { slug, locale, contentTypeUid, url },\n })\n }\n\n if (livePreview) {\n try {\n contentstack.Utils.addEditableTags(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry as any,\n contentTypeUid,\n true,\n locale.toLowerCase(),\n )\n } catch {\n // Editable tags only add inline edit markers for the Visual\n // Builder; a tagging failure must not fail the page request itself.\n }\n }\n\n return { entry }\n } catch (error) {\n if (error instanceof CMSContentNotFoundError) {\n throw error\n }\n\n if (extractErrorStatus(error) === 404) {\n throw new CMSContentNotFoundError('Contentstack content not found', {\n cause: error,\n details: { slug, locale, contentTypeUid, url },\n })\n }\n\n const cause = error instanceof Error ? error : new Error(String(error))\n throw new Error(\n `Contentstack API request failed (slug: \"${slug}\", locale: \"${locale}\", content-type: \"${contentTypeUid}\"): ${cause.message}`,\n { cause },\n )\n }\n }\n\n /**\n * Retrieves CMS page data with application-level caching.\n * Preview requests bypass the cache entirely.\n *\n * @param slug CMS slug\n * @param request Inbound request, used to detect editor mode and read editor-specific query params\n * @returns Contentstack page data or undefined\n */\n async fetchPageData(\n slug: string,\n request: IncomingRequest,\n ): Promise<CMSPagePayload | undefined> {\n const locale = this.context.country.locale\n const useDraftContent =\n this.isEditorMode(request) && this.draftContentEnabled\n\n if (useDraftContent) {\n log.debug({\n message: 'Bypassing CMS cache in preview mode',\n slug,\n locale,\n })\n return await this.fetchRawPageData(slug, locale, useDraftContent, request)\n }\n\n return await this.context.cache.getOrSet(\n `cms:contentstack:page:${slug}:${locale}`,\n // Cast required: StorageValue excludes undefined, but the fetch can return undefined for missing content\n () =>\n this.fetchRawPageData(slug, locale, useDraftContent, request) as never,\n CACHE_TTL_SECONDS,\n )\n }\n\n /**\n * Content-type UID and URL slug queried by `fetchListingPageData`.\n * Override to look up a different content type or URL shape.\n *\n * @param categoryId SCAYLE category ID\n * @returns Content-type UID and the `url` field value to match\n */\n protected buildListingQuery(categoryId: number): {\n contentTypeUid: string\n url: string\n } {\n return {\n contentTypeUid: 'productlistingpage-component',\n url: `/c/c-${categoryId}`,\n }\n }\n\n /**\n * Retrieves CMS content for a product listing page.\n * Throws {@link CMSContentNotFoundError} when no entry matches the\n * category; {@link fetchListingPageData} converts that into `undefined`\n * for the caller.\n *\n * @param categoryId SCAYLE category ID\n * @param locale Storefront locale code\n * @param useDraftContent Whether to fetch draft content instead of published content\n * @returns Contentstack listing page data\n * @throws {CMSContentNotFoundError} When no entry matches the category\n */\n private async fetchRawListingPageData(\n categoryId: number,\n locale: string,\n useDraftContent: boolean,\n ): Promise<CMSPagePayload | undefined> {\n const stack = useDraftContent\n ? this.createPreviewStack()\n : this.getDeliveryStack()\n const { contentTypeUid, url } = this.buildListingQuery(categoryId)\n\n try {\n const entry = await this.findEntry(stack, contentTypeUid, url, locale)\n\n if (!entry) {\n throw new CMSContentNotFoundError(\n 'Contentstack listing content not found',\n { details: { categoryId, slug: url, locale, contentTypeUid } },\n )\n }\n\n return { entry }\n } catch (error) {\n if (error instanceof CMSContentNotFoundError) {\n throw error\n }\n\n if (extractErrorStatus(error) === 404) {\n throw new CMSContentNotFoundError(\n 'Contentstack listing content not found',\n {\n cause: error,\n details: { categoryId, slug: url, locale, contentTypeUid },\n },\n )\n }\n\n const cause = error instanceof Error ? error : new Error(String(error))\n throw new Error(\n `Contentstack API request failed (category: ${categoryId}, url: \"${url}\", locale: \"${locale}\", content-type: \"${contentTypeUid}\"): ${cause.message}`,\n { cause },\n )\n }\n }\n\n /**\n * Retrieves CMS content for a product listing page, with caching.\n * Converts a missing entry into `undefined` rather than throwing, since\n * missing PLP content is expected, not an error condition.\n *\n * @param categoryId SCAYLE category ID\n * @param request Inbound request, used to detect editor mode and read editor-specific query params\n * @returns Contentstack listing page data or undefined\n */\n async fetchListingPageData(\n categoryId: number,\n request: IncomingRequest,\n ): Promise<CMSPagePayload | undefined> {\n const locale = this.context.country.locale\n const useDraftContent =\n this.isEditorMode(request) && this.draftContentEnabled\n const fetchListing = async () => {\n try {\n return await this.fetchRawListingPageData(\n categoryId,\n locale,\n useDraftContent,\n )\n } catch (error) {\n if (error instanceof CMSContentNotFoundError) {\n return undefined\n }\n\n log.error({\n message: 'Failed to fetch CMS listing page data',\n err: error instanceof Error ? error : new Error(String(error)),\n categoryId,\n locale,\n })\n\n throw error\n }\n }\n\n if (useDraftContent) {\n log.debug({\n message: 'Bypassing CMS PLP cache in preview mode',\n categoryId,\n locale,\n })\n return await fetchListing()\n }\n\n return await this.context.cache.getOrSet(\n `cms:contentstack:plp:${categoryId}:${locale}`,\n // Cast required: StorageValue excludes undefined, but the fetch can return undefined for missing content\n () => fetchListing() as never,\n CACHE_TTL_SECONDS,\n )\n }\n}\n"],"mappings":";;;;;;;;;;AAYA,MAAa,MAAA,aAAA,KAAA;;;;;CAUb,OAAa;AAET;AACA,SAAA,aAAc,QAAA;CACd,OAAA,yBACE,cAAA,MAAA,GAAA,IAAA;AACJ;ACJF,IAAA,yBAAyB,MAAK,uBAAA;;CAG9B,YAAM;;;;;;;;;;;;;EAmCN,KAAA,UAAS;CACP;CAQA,iBAAO,SAAA;EACT,IAAA,CAAA,KAAA,aAAA,OAAA,GAAA;EAEA,OAAS;GACP,QAAO,KAAA,OAAA;GACT,aAAA,KAAA,OAAA;;;;;;;;;;;;;;;;;CA6CA;CACE,qBAAe;EAEN,MAAA,EAAA,QAA0B,eAAA,aAAA,QAAA,uBAAA,KAAA;EAElB,IAAA,CAAA,oBAAA,MAAA,IAAA,MAAA,kIAAA;EAKA,MAAA,YAAA,aAAA,MAAA;EAEA,OAAA,qBAAA,aAAA,MAAA;GAEjB;GAIE;GAMA;GAMA;GASA,MAAK,UAAS;GAAE,cAAG;IAAQ,QAAQ;IAAqC,eAAA;IACxE,MAAK,UAAA;GACL;EACF,CAAA,GAAA,ySAAA;;;;;;;;;EAYA;CACE;CAKE,MAAA,UAAa,OAAO,gBAAA,KAAA,QAAA;EACpB,QAAA,MAAa,MAAK,YAAO,cAAA,CAAA,CAAA,MAAA,CAAA,CAAA,OAAA,OAAA,YAAA,CAAA,CAAA,CAAA,gBAAA,CAAA,CAAA,MAAA,CAAA,CAAA,MAAA,OAAA,eAAA,QAAA,GAAA,CAAA,CAAA,UAAA;GACzB,aAAa;GACb,mBAAS;GACX,mBAAA;EACF,CAAA,CAAA,CAAA,MAAA,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;;;CAqBE,MAAA,qBAAc,YACL,SAAA;EAET,MAAM,SAAE,KAAA,QAAgB,QAAQ;EAChC,MAAM,kBAAc,KAAA,aAAmB,OAAQ,KAAM,KAAA;EAErD,MAAI,eACF,YAAM;GACJ,IAAA;IACA,OAAA,MAAA,KAAkB,wBAAc,YAAoB,QAAA,eAAA;GACrD,SAAA,OAAA;IAGH,IAAI,iBAAA,yBAAA;IACF,IAAA,MAAM;KAEN,SAAK;KAEU,KAAA,iBAAA,QAAA,QAAA,IAAA,MAAA,OAAA,KAAA,CAAA;KAAM;KAAQ;IAAgB,CAAA;IAAI,MAC9C;GAGH;EAEI;EAOF,IAAA,iBAGA;GAGF,IAAA,MAAS;IACX,SAAS;IACP;IAIA;GAEI,CAAA;GACA,OAAA,MAAS,aAAA;EAAE;EAAM,OAAA,MAAA,KAAA,QAAA,MAAA,SAAA,wBAAA,WAAA,GAAA,gBAAA,aAAA,GAAA,iBAAA;CAAQ;AAAgB;AAC3C,SAAC,wBAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@scayle/storefront-cms-contentstack",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.0-alpha.2",
|
|
4
4
|
"description": "Contentstack CMS provider integration for the SCAYLE Storefront Application V3",
|
|
5
5
|
"author": "SCAYLE Commerce Engine",
|
|
6
6
|
"license": "MIT",
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"peerDependencies": {
|
|
25
25
|
"@contentstack/delivery-sdk": "^5.4.0",
|
|
26
26
|
"@timbenniks/contentstack-endpoints": "^3.0.2",
|
|
27
|
-
"@scayle/storefront": "1.0.0-alpha.
|
|
27
|
+
"@scayle/storefront": "1.0.0-alpha.4"
|
|
28
28
|
},
|
|
29
29
|
"devDependencies": {
|
|
30
30
|
"@arethetypeswrong/cli": "0.18.5",
|
|
@@ -38,8 +38,8 @@
|
|
|
38
38
|
"typescript": "6.0.3",
|
|
39
39
|
"obuild": "0.4.38",
|
|
40
40
|
"vitest": "4.1.10",
|
|
41
|
-
"@scayle/eslint-config-storefront": "4.8.3-alpha.
|
|
42
|
-
"@scayle/storefront": "1.0.0-alpha.
|
|
41
|
+
"@scayle/eslint-config-storefront": "4.8.3-alpha.1",
|
|
42
|
+
"@scayle/storefront": "1.0.0-alpha.4",
|
|
43
43
|
"@scayle/vitest-config-storefront": "1.0.0"
|
|
44
44
|
},
|
|
45
45
|
"scripts": {
|