@contentful/experiences-sdk-core 0.13.0 → 0.13.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.
@@ -1,229 +0,0 @@
1
- import { resolveAttribution } from "./attribution.js";
2
- import { createDebugLogger } from "./debug-logger.js";
3
- import { applyTokenResolver, resolveDesignProperties } from "./design-properties.js";
4
- function getResolver(entry) {
5
- if (typeof entry !== "object" || entry === null) return void 0;
6
- const candidate = entry.resolveData;
7
- return typeof candidate === "function" ? candidate : void 0;
8
- }
9
- const DEFAULT_EXPERIENCE = {
10
- debug: false,
11
- metadata: {}
12
- };
13
- function lookupEntry(config, registration) {
14
- return registration.kind === "experienceTemplate" ? config.experienceTemplates?.[registration.id] : config.components[registration.id];
15
- }
16
- function extractIdFromUrn(urn) {
17
- const segments = urn.split("/").filter((s) => s.length > 0);
18
- return segments[segments.length - 1] ?? urn;
19
- }
20
- function readNodeRef(node) {
21
- const isExperienceTemplate = "experienceTemplate" in node;
22
- const ref = isExperienceTemplate ? node.experienceTemplate : "component" in node ? node.component : void 0;
23
- const urn = ref?.sys?.urn;
24
- if (typeof urn !== "string" || urn.length === 0) return null;
25
- return { kind: isExperienceTemplate ? "experienceTemplate" : "component", urn };
26
- }
27
- function ensureArray(value, field, log, diagnostics) {
28
- if (Array.isArray(value)) return value;
29
- const message = `Experience payload's "${field}" is not an array (got ${value === null ? "null" : typeof value}); treating it as empty instead of throwing. This usually means a malformed or partial payload \u2014 check what produced it.`;
30
- if (typeof console !== "undefined") {
31
- console.warn(`[@contentful/experiences] ${message}`);
32
- }
33
- log.log(message);
34
- diagnostics.push(new Error(message));
35
- return [];
36
- }
37
- function countPayloadNodes(node) {
38
- const slots = node.slots;
39
- let total = 1;
40
- if (slots && typeof slots === "object") {
41
- for (const children of Object.values(slots)) {
42
- if (!Array.isArray(children)) continue;
43
- for (const child of children) total += countPayloadNodes(child);
44
- }
45
- }
46
- return total;
47
- }
48
- function warnUnrenderableNode(node, log, diagnostics) {
49
- const id = node.id;
50
- const label = typeof id === "string" ? ` "${id}"` : "";
51
- const keys = Object.keys(node);
52
- const descendants = countPayloadNodes(node) - 1;
53
- const message = `Skipping unidentifiable node${label}: expected a \`component\` or \`experienceTemplate\` ResourceLink carrying a urn, got keys [${keys.join(", ")}]. Dropping it and ${descendants} descendant node(s). A payload node kind this SDK does not know is usually a version skew \u2014 upgrading @contentful/experiences-sdk-core may be all that is needed.`;
54
- if (typeof console !== "undefined") {
55
- console.warn(`[@contentful/experiences] ${message}`);
56
- }
57
- log.log(message);
58
- diagnostics.push(new Error(message));
59
- }
60
- function buildNodes(nodes, config, nodeRefs, log, diagnostics) {
61
- const built = [];
62
- for (const node of nodes) {
63
- const one = buildNode(node, config, nodeRefs, log, diagnostics);
64
- if (one !== null) built.push(one);
65
- }
66
- return built;
67
- }
68
- function buildNode(node, config, nodeRefs, log, diagnostics) {
69
- const ref = readNodeRef(node);
70
- if (ref === null) {
71
- warnUnrenderableNode(node, log, diagnostics);
72
- return null;
73
- }
74
- const registration = {
75
- kind: ref.kind,
76
- id: extractIdFromUrn(ref.urn)
77
- };
78
- const nodeId = typeof node.id === "string" ? node.id : void 0;
79
- const slots = {};
80
- if (node.slots) {
81
- for (const [slotName, children] of Object.entries(node.slots)) {
82
- if (!Array.isArray(children)) {
83
- const message = `Slot "${slotName}" on ${registration.kind} "${registration.id}"${nodeId ? ` (node "${nodeId}")` : ""} is not an array of nodes (got ${children === null ? "null" : typeof children}); treating it as empty instead of failing the whole experience. A hand-built payload with the wrong slot shape is the usual cause.`;
84
- if (typeof console !== "undefined") {
85
- console.warn(`[@contentful/experiences] ${message}`);
86
- }
87
- log.log(message);
88
- diagnostics.push(new Error(message));
89
- slots[slotName] = [];
90
- continue;
91
- }
92
- slots[slotName] = buildNodes(children, config, nodeRefs, log, diagnostics);
93
- }
94
- }
95
- const built = {
96
- registration,
97
- props: {
98
- content: { ...node.contentProperties ?? {} },
99
- // Resolved design values are written by the pre-resolution pass below.
100
- design: {},
101
- designRaw: { ...node.designProperties ?? {} }
102
- },
103
- slots
104
- };
105
- if (node.id) built.nodeId = node.id;
106
- if (getResolver(lookupEntry(config, registration))) {
107
- nodeRefs.push(built);
108
- }
109
- return built;
110
- }
111
- function preResolveDesignProperties(design, resolveToken) {
112
- return applyTokenResolver(resolveDesignProperties(design), resolveToken);
113
- }
114
- function warnUnresolvedTokens(label, unresolved, log, diagnostics) {
115
- if (!unresolved.length) return;
116
- const message = `resolveToken returned undefined for token id(s) on "${label}": ${unresolved.join(", ")}. Resolved design (getDesignValues()) will carry the raw, unresolved DesignToken for those keys.`;
117
- if (typeof console !== "undefined") {
118
- console.warn(`[@contentful/experiences] ${message}`);
119
- }
120
- log.log(`unresolved token id(s) on "${label}": ${unresolved.join(", ")}`);
121
- for (const tokenId of unresolved) {
122
- diagnostics.push(
123
- new Error(
124
- `Design token "${tokenId}" on ${label} has no \`resolveToken\` mapping; the raw token reaches the component unresolved.`
125
- )
126
- );
127
- }
128
- }
129
- function preResolveNodeTree(node, resolveToken, log, diagnostics) {
130
- const { props, unresolved } = preResolveDesignProperties(node.props.designRaw, resolveToken);
131
- node.props.design = props;
132
- warnUnresolvedTokens(
133
- `${node.registration.kind}:${node.registration.id}`,
134
- unresolved,
135
- log,
136
- diagnostics
137
- );
138
- for (const children of Object.values(node.slots)) {
139
- for (const child of children) {
140
- preResolveNodeTree(child, resolveToken, log, diagnostics);
141
- }
142
- }
143
- }
144
- async function resolveExperience(payload, config, options = {}) {
145
- const log = createDebugLogger(options.debug, "core");
146
- log.lazy("resolveExperience called with payload", () => payload);
147
- const diagnostics = [];
148
- const isPlainPayload = payload !== null && typeof payload === "object";
149
- if (!isPlainPayload) {
150
- const message = `Experience payload is ${payload === null ? "null" : typeof payload}, not an object; treating it as an empty experience (no nodes) instead of throwing. This usually means the fetch or transform pipeline handed resolveExperience a missing or malformed payload \u2014 check what produced it.`;
151
- if (typeof console !== "undefined") {
152
- console.warn(`[@contentful/experiences] ${message}`);
153
- }
154
- log.log(message);
155
- diagnostics.push(new Error(message));
156
- }
157
- const payloadNodes = isPlainPayload ? ensureArray(payload.nodes, "nodes", log, diagnostics) : [];
158
- const nodeRefs = [];
159
- const nodes = buildNodes(payloadNodes, config, nodeRefs, log, diagnostics);
160
- log.log(`built ${nodes.length} top-level node(s); ${nodeRefs.length} declare resolveData`);
161
- const experience = {
162
- debug: options.debug ?? DEFAULT_EXPERIENCE.debug,
163
- metadata: {
164
- ...DEFAULT_EXPERIENCE.metadata,
165
- ...options.metadata ?? {}
166
- }
167
- };
168
- const tasks = [];
169
- for (const node of nodeRefs) {
170
- const resolver = getResolver(lookupEntry(config, node.registration));
171
- if (!resolver) continue;
172
- const ctx = {
173
- content: node.props.content,
174
- design: node.props.designRaw,
175
- experience
176
- };
177
- tasks.push(
178
- // Deferred via `.then(() => resolver(ctx))` rather than
179
- // `Promise.resolve(resolver(ctx))`: the latter calls `resolver(ctx)`
180
- // eagerly as an argument, so a resolver that throws *synchronously*
181
- // escapes immediately instead of becoming a rejection. The `onFailure`
182
- // handler below never rethrows, so one broken resolver can't fail the
183
- // `Promise.all` for every other node.
184
- Promise.resolve().then(() => resolver(ctx)).then(
185
- (resolved) => {
186
- node.props.resolved = resolved;
187
- },
188
- (err) => {
189
- const label = `${node.registration.kind}:${node.registration.id}`;
190
- const reason = err instanceof Error ? err.message : String(err);
191
- const message = `resolveData for ${label}${node.nodeId ? ` (node "${node.nodeId}")` : ""} threw or rejected: ${reason}. Rendering the node without resolved data instead of failing the whole experience.`;
192
- if (typeof console !== "undefined") {
193
- console.warn(`[@contentful/experiences] ${message}`);
194
- }
195
- log.log(message);
196
- diagnostics.push(new Error(message, { cause: err instanceof Error ? err : void 0 }));
197
- }
198
- )
199
- );
200
- }
201
- if (tasks.length > 0) {
202
- await log.time(`${tasks.length} resolveData hook(s)`, () => Promise.all(tasks));
203
- }
204
- for (const node of nodes) {
205
- preResolveNodeTree(node, config.resolveToken, log, diagnostics);
206
- }
207
- log.log("resolved design properties");
208
- const plan = {
209
- nodes,
210
- diagnostics,
211
- metadata: experience.metadata,
212
- debug: experience.debug
213
- };
214
- const sourceMap = options.sourceMap ?? (isPlainPayload ? payload.extensions?.sourceMap : void 0);
215
- if (sourceMap) {
216
- plan.sourceMap = sourceMap;
217
- const attribution = resolveAttribution(sourceMap, nodes, log);
218
- if (attribution) plan.attribution = attribution;
219
- }
220
- const profileId = isPlainPayload && payload.extensions?.personalization?.profile?.id;
221
- if (profileId) {
222
- plan.personalization = { profileId };
223
- }
224
- return plan;
225
- }
226
- export {
227
- resolveExperience
228
- };
229
- //# sourceMappingURL=resolve-experience.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/resolve-experience.ts"],"sourcesContent":["/*\n * Turns an XDA Experience payload into a runtime-neutral PortableRenderPlan.\n * Walks nodes recursively, splits content + design props, runs any registered\n * `resolveData` hooks in parallel, and resolves design values for the renderer.\n */\n\nimport { resolveAttribution } from './attribution.js';\nimport { createDebugLogger, type DebugLogger } from './debug-logger.js';\nimport type {\n DesignPropValue,\n ExperienceContext,\n ExperienceSourceMap,\n ExperienceNode,\n ExperiencePayload,\n PortableRegistration,\n PortableRenderNode,\n PortableRenderPlan,\n ResolveContext,\n ResolveToken,\n} from './types.js';\nimport { applyTokenResolver, resolveDesignProperties } from './design-properties.js';\n\n/**\n * Structural type the resolver walker depends on. Matches the React /\n * Svelte adapter `Config` shape but doesn't require importing them —\n * render-core stays decoupled from any framework.\n *\n * Registry values are typed as `unknown` because each adapter accepts\n * either a bare framework component (function / Svelte class / etc.) OR\n * a config-object shape with `{ component, defaults?, resolveData? }`.\n * The resolver only cares about `resolveData`; it duck-types each entry\n * at runtime and ignores anything without it.\n */\nexport interface ResolverConfig {\n components: Record<string, unknown>;\n experienceTemplates?: Record<string, unknown>;\n /**\n * Resolves `DesignToken` design properties to runtime values. Mirrors the\n * adapter `Config.resolveToken`, so server and client agree without the\n * caller re-supplying it. Used during server-side pre-resolution.\n */\n resolveToken?: ResolveToken;\n}\n\nfunction getResolver(\n entry: unknown\n):\n | ((ctx: ResolveContext) => Record<string, unknown> | Promise<Record<string, unknown>>)\n | undefined {\n if (typeof entry !== 'object' || entry === null) return undefined;\n const candidate = (entry as { resolveData?: unknown }).resolveData;\n return typeof candidate === 'function'\n ? (candidate as (\n ctx: ResolveContext\n ) => Record<string, unknown> | Promise<Record<string, unknown>>)\n : undefined;\n}\n\nexport interface ResolveExperienceOptions {\n /**\n * Arbitrary per-render metadata exposed to every resolver as\n * `ctx.experience.metadata`. Defaults to `{}`.\n */\n metadata?: Record<string, unknown>;\n /**\n * Observability switch. When on, `resolveExperience` logs the resolution\n * steps and per-node `resolveData` fan-out timings. Threads through to the\n * resolver context as `ctx.experience.debug`. Defaults to `false`.\n */\n debug?: boolean;\n /**\n * Source map carried onto the plan. An explicit map wins over\n * `payload.extensions.sourceMap`. Omit to use the payload's map, if it\n * carries one.\n */\n sourceMap?: ExperienceSourceMap;\n}\n\nconst DEFAULT_EXPERIENCE: ExperienceContext = {\n debug: false,\n metadata: {},\n};\n\n/**\n * Registry lookup for a built node. A node's `kind` decides which half of the\n * customer Config owns its implementation — components and Experience\n * Templates are otherwise interchangeable at every other step.\n */\nfunction lookupEntry(config: ResolverConfig, registration: PortableRegistration): unknown {\n return registration.kind === 'experienceTemplate'\n ? config.experienceTemplates?.[registration.id]\n : config.components[registration.id];\n}\n\n/**\n * Extract the id (component or experienceTemplate) from its\n * `ResourceLink` URN. Real URN shapes:\n * crn:contentful:::experience:spaces/$self/environments/$self/components/<id>\n * crn:contentful:::experience:spaces/$self/environments/$self/experienceTemplates/<id>\n *\n * The id is the final path segment. We split on `/` and take the last\n * non-empty piece so this also tolerates trailing slashes or alternative\n * prefix shapes.\n */\nfunction extractIdFromUrn(urn: string): string {\n const segments = urn.split('/').filter((s) => s.length > 0);\n return segments[segments.length - 1] ?? urn;\n}\n\n/**\n * Read the ResourceLink a node points at. Which key is present is the only\n * difference between the two node variants: `experienceTemplate` means the\n * implementation lives in the customer's `experienceTemplates` registry,\n * `component` in `components`. Both carry ids in the same URN shape, the same\n * props shape, and the same slots — so everything downstream is kind-agnostic.\n *\n * `ExperienceNode` is a closed union, so a typed caller cannot produce anything\n * else. Payloads, however, are untrusted JSON at runtime, and the realistic way\n * a third shape arrives is a node kind *newer than this SDK*. Returns `null`\n * for anything unidentifiable rather than letting the ref access throw — see\n * `buildNode`.\n */\nfunction readNodeRef(\n node: ExperienceNode\n): { kind: PortableRegistration['kind']; urn: string } | null {\n const isExperienceTemplate = 'experienceTemplate' in node;\n const ref = isExperienceTemplate\n ? node.experienceTemplate\n : 'component' in node\n ? node.component\n : undefined;\n // Cast because the runtime value may violate the declared type: a node can\n // carry `component: {}`, which satisfies `'component' in node` but has no urn.\n const urn = (ref as { sys?: { urn?: unknown } } | undefined)?.sys?.urn;\n if (typeof urn !== 'string' || urn.length === 0) return null;\n return { kind: isExperienceTemplate ? 'experienceTemplate' : 'component', urn };\n}\n\n/**\n * Guards a top-level payload field that must be an array. A malformed or\n * partial payload (bad JSON, a hand-authored payload with the wrong shape)\n * should degrade to an empty experience rather than throwing and failing the\n * whole render — same \"dropping beats throwing\" rationale as\n * `warnUnrenderableNode` below, just one level up the tree.\n */\nfunction ensureArray<T>(\n value: unknown,\n field: string,\n log: DebugLogger,\n diagnostics: Error[]\n): T[] {\n if (Array.isArray(value)) return value as T[];\n const message =\n `Experience payload's \"${field}\" is not an array (got ${value === null ? 'null' : typeof value}); ` +\n `treating it as empty instead of throwing. This usually means a malformed or partial payload — ` +\n `check what produced it.`;\n if (typeof console !== 'undefined') {\n console.warn(`[@contentful/experiences] ${message}`);\n }\n log.log(message);\n diagnostics.push(new Error(message));\n return [];\n}\n\n/** Total node count in a payload subtree, the node itself included. */\nfunction countPayloadNodes(node: ExperienceNode): number {\n const slots = (node as { slots?: Record<string, unknown> }).slots;\n let total = 1;\n if (slots && typeof slots === 'object') {\n for (const children of Object.values(slots)) {\n if (!Array.isArray(children)) continue;\n for (const child of children) total += countPayloadNodes(child as ExperienceNode);\n }\n }\n return total;\n}\n\n/**\n * The one case where a node is dropped. AIS-413 was the opposite failure —\n * a node kind the SDK recognized and could have rendered, skipped behind a\n * vague warning, taking its whole subtree with it — so the bar here is that\n * nothing vanishes without a diagnostic naming what was lost.\n *\n * Dropping beats throwing: a `resolveExperience` rejection fails the entire\n * experience, so one unrecognized node in a sidebar would take down every page\n * containing it, for a payload the customer does not control and cannot fix.\n */\nfunction warnUnrenderableNode(node: ExperienceNode, log: DebugLogger, diagnostics: Error[]): void {\n const id = (node as { id?: unknown }).id;\n const label = typeof id === 'string' ? ` \"${id}\"` : '';\n const keys = Object.keys(node);\n const descendants = countPayloadNodes(node) - 1;\n const message =\n `Skipping unidentifiable node${label}: expected a \\`component\\` or \\`experienceTemplate\\` ` +\n `ResourceLink carrying a urn, got keys [${keys.join(', ')}]. Dropping it and ${descendants} ` +\n `descendant node(s). A payload node kind this SDK does not know is usually a version skew — ` +\n `upgrading @contentful/experiences-sdk-core may be all that is needed.`;\n if (typeof console !== 'undefined') {\n console.warn(`[@contentful/experiences] ${message}`);\n }\n log.log(message);\n diagnostics.push(new Error(message));\n}\n\n/**\n * Walk a sibling list into IR nodes, dropping any node `buildNode` cannot\n * identify. Used for both the top-level list and every slot.\n */\nfunction buildNodes(\n nodes: ExperienceNode[],\n config: ResolverConfig,\n nodeRefs: PortableRenderNode[],\n log: DebugLogger,\n diagnostics: Error[]\n): PortableRenderNode[] {\n const built: PortableRenderNode[] = [];\n for (const node of nodes) {\n const one = buildNode(node, config, nodeRefs, log, diagnostics);\n if (one !== null) built.push(one);\n }\n return built;\n}\n\n/**\n * Recursively turn a payload node into an IR node. The collected `nodeRefs`\n * array is for the resolver pass — every built node with a registered\n * resolver gets a reference appended so we can run them in parallel without\n * walking the tree twice.\n *\n * Returns `null` only for a node whose ResourceLink cannot be read, which\n * `warnUnrenderableNode` has already reported. Callers go through `buildNodes`.\n */\nfunction buildNode(\n node: ExperienceNode,\n config: ResolverConfig,\n nodeRefs: PortableRenderNode[],\n log: DebugLogger,\n diagnostics: Error[]\n): PortableRenderNode | null {\n const ref = readNodeRef(node);\n if (ref === null) {\n warnUnrenderableNode(node, log, diagnostics);\n return null;\n }\n const registration: PortableRegistration = {\n kind: ref.kind,\n id: extractIdFromUrn(ref.urn),\n };\n const nodeId = typeof node.id === 'string' ? node.id : undefined;\n\n const slots: Record<string, PortableRenderNode[]> = {};\n if (node.slots) {\n for (const [slotName, children] of Object.entries(node.slots)) {\n if (!Array.isArray(children)) {\n const message =\n `Slot \"${slotName}\" on ${registration.kind} \"${registration.id}\"` +\n `${nodeId ? ` (node \"${nodeId}\")` : ''} is not an array of nodes (got ` +\n `${children === null ? 'null' : typeof children}); treating it as empty instead of ` +\n `failing the whole experience. A hand-built payload with the wrong slot shape is the ` +\n `usual cause.`;\n if (typeof console !== 'undefined') {\n console.warn(`[@contentful/experiences] ${message}`);\n }\n log.log(message);\n diagnostics.push(new Error(message));\n slots[slotName] = [];\n continue;\n }\n slots[slotName] = buildNodes(children, config, nodeRefs, log, diagnostics);\n }\n }\n\n const built: PortableRenderNode = {\n registration,\n props: {\n content: { ...(node.contentProperties ?? {}) },\n // Resolved design values are written by the pre-resolution pass below.\n design: {},\n designRaw: { ...(node.designProperties ?? {}) } as Record<string, DesignPropValue>,\n },\n slots,\n };\n if (node.id) built.nodeId = node.id;\n if (getResolver(lookupEntry(config, registration))) {\n nodeRefs.push(built);\n }\n return built;\n}\n\n// Resolve a node's raw design values and tokens.\nfunction preResolveDesignProperties(\n design: Record<string, DesignPropValue>,\n resolveToken: ResolveToken | undefined\n): { props: Record<string, unknown>; unresolved: string[] } {\n return applyTokenResolver(resolveDesignProperties(design), resolveToken);\n}\n\n// Warn when resolveToken left tokens unresolved, so pass-through keys are diagnosable.\nfunction warnUnresolvedTokens(\n label: string,\n unresolved: string[],\n log: DebugLogger,\n diagnostics: Error[]\n): void {\n if (!unresolved.length) return;\n const message = `resolveToken returned undefined for token id(s) on \"${label}\": ${unresolved.join(', ')}. Resolved design (getDesignValues()) will carry the raw, unresolved DesignToken for those keys.`;\n if (typeof console !== 'undefined') {\n console.warn(`[@contentful/experiences] ${message}`);\n }\n log.log(`unresolved token id(s) on \"${label}\": ${unresolved.join(', ')}`);\n for (const tokenId of unresolved) {\n diagnostics.push(\n new Error(\n `Design token \"${tokenId}\" on ${label} has no \\`resolveToken\\` mapping; the raw token reaches the component unresolved.`\n )\n );\n }\n}\n\n// Depth-first token resolution for a node and its slot children.\nfunction preResolveNodeTree(\n node: PortableRenderNode,\n resolveToken: ResolveToken | undefined,\n log: DebugLogger,\n diagnostics: Error[]\n): void {\n const { props, unresolved } = preResolveDesignProperties(node.props.designRaw, resolveToken);\n node.props.design = props;\n warnUnresolvedTokens(\n `${node.registration.kind}:${node.registration.id}`,\n unresolved,\n log,\n diagnostics\n );\n for (const children of Object.values(node.slots)) {\n for (const child of children) {\n preResolveNodeTree(child, resolveToken, log, diagnostics);\n }\n }\n}\n\n/**\n * Turns an Experience payload (XDA response shape) into a PortableRenderPlan\n * ready to hand to a renderer. Walks the tree, classifies props, captures\n * slots, and runs any component-declared `resolveData` hooks (sync or async)\n * in parallel.\n *\n * Implementation note: the function is always async — even when no component\n * declares a resolver, the cost is one microtask. Customers get a single\n * uniform call site.\n */\nexport async function resolveExperience(\n payload: ExperiencePayload,\n config: ResolverConfig,\n options: ResolveExperienceOptions = {}\n): Promise<PortableRenderPlan> {\n const log = createDebugLogger(options.debug, 'core');\n log.lazy('resolveExperience called with payload', () => payload);\n\n const diagnostics: Error[] = [];\n\n // A payload that isn't an object at all (missing fetch result, a raw\n // `null`/`undefined` handed in by a broken transform step) can't be\n // guarded field-by-field via `ensureArray` below — that only guards once\n // we're already inside a `payload.nodes` access. Guard the whole payload\n // first so we degrade to an empty experience instead of throwing a raw\n // TypeError, and report exactly one diagnostic rather than double-counting\n // once we also run `nodes` through `ensureArray`.\n const isPlainPayload = payload !== null && typeof payload === 'object';\n if (!isPlainPayload) {\n const message =\n `Experience payload is ${payload === null ? 'null' : typeof payload}, not an object; ` +\n `treating it as an empty experience (no nodes) instead of throwing. This ` +\n `usually means the fetch or transform pipeline handed resolveExperience a missing or ` +\n `malformed payload — check what produced it.`;\n if (typeof console !== 'undefined') {\n console.warn(`[@contentful/experiences] ${message}`);\n }\n log.log(message);\n diagnostics.push(new Error(message));\n }\n const payloadNodes = isPlainPayload\n ? ensureArray<ExperienceNode>(payload.nodes, 'nodes', log, diagnostics)\n : [];\n // Pass 1: walk the payload into the IR. Collect refs to nodes that need\n // resolveData so pass 2 can run them in parallel without re-walking.\n const nodeRefs: PortableRenderNode[] = [];\n const nodes: PortableRenderNode[] = buildNodes(payloadNodes, config, nodeRefs, log, diagnostics);\n log.log(`built ${nodes.length} top-level node(s); ${nodeRefs.length} declare resolveData`);\n\n // Pass 2: run every node's resolveData hook in parallel.\n const experience: ExperienceContext = {\n debug: options.debug ?? DEFAULT_EXPERIENCE.debug,\n metadata: {\n ...DEFAULT_EXPERIENCE.metadata,\n ...(options.metadata ?? {}),\n },\n };\n\n const tasks: Array<Promise<void>> = [];\n\n for (const node of nodeRefs) {\n const resolver = getResolver(lookupEntry(config, node.registration));\n if (!resolver) continue;\n const ctx: ResolveContext = {\n content: node.props.content,\n design: node.props.designRaw,\n experience,\n };\n tasks.push(\n // Deferred via `.then(() => resolver(ctx))` rather than\n // `Promise.resolve(resolver(ctx))`: the latter calls `resolver(ctx)`\n // eagerly as an argument, so a resolver that throws *synchronously*\n // escapes immediately instead of becoming a rejection. The `onFailure`\n // handler below never rethrows, so one broken resolver can't fail the\n // `Promise.all` for every other node.\n Promise.resolve()\n .then(() => resolver(ctx))\n .then(\n (resolved) => {\n node.props.resolved = resolved;\n },\n (err: unknown) => {\n const label = `${node.registration.kind}:${node.registration.id}`;\n const reason = err instanceof Error ? err.message : String(err);\n const message =\n `resolveData for ${label}${node.nodeId ? ` (node \"${node.nodeId}\")` : ''} threw or ` +\n `rejected: ${reason}. Rendering the node without resolved data instead of failing ` +\n `the whole experience.`;\n if (typeof console !== 'undefined') {\n console.warn(`[@contentful/experiences] ${message}`);\n }\n log.log(message);\n diagnostics.push(new Error(message, { cause: err instanceof Error ? err : undefined }));\n }\n )\n );\n }\n\n // Time the fan-out as a whole rather than per-resolver — one aggregate line\n // keeps the timing signal without a line per node (which gets noisy fast).\n if (tasks.length > 0) {\n await log.time(`${tasks.length} resolveData hook(s)`, () => Promise.all(tasks));\n }\n\n for (const node of nodes) {\n preResolveNodeTree(node, config.resolveToken, log, diagnostics);\n }\n log.log('resolved design properties');\n\n // Reuse `experience.metadata` rather than re-merging, so resolvers and the\n // renderer read the same object.\n const plan: PortableRenderPlan = {\n nodes,\n diagnostics,\n metadata: experience.metadata,\n debug: experience.debug,\n };\n const sourceMap =\n options.sourceMap ?? (isPlainPayload ? payload.extensions?.sourceMap : undefined);\n if (sourceMap) {\n plan.sourceMap = sourceMap;\n const attribution = resolveAttribution(sourceMap, nodes, log);\n if (attribution) plan.attribution = attribution;\n }\n const profileId = isPlainPayload && payload.extensions?.personalization?.profile?.id;\n if (profileId) {\n plan.personalization = { profileId };\n }\n return plan;\n}\n"],"mappings":"AAMA,SAAS,0BAA0B;AACnC,SAAS,yBAA2C;AAapD,SAAS,oBAAoB,+BAA+B;AAwB5D,SAAS,YACP,OAGY;AACZ,MAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;AACxD,QAAM,YAAa,MAAoC;AACvD,SAAO,OAAO,cAAc,aACvB,YAGD;AACN;AAsBA,MAAM,qBAAwC;AAAA,EAC5C,OAAO;AAAA,EACP,UAAU,CAAC;AACb;AAOA,SAAS,YAAY,QAAwB,cAA6C;AACxF,SAAO,aAAa,SAAS,uBACzB,OAAO,sBAAsB,aAAa,EAAE,IAC5C,OAAO,WAAW,aAAa,EAAE;AACvC;AAYA,SAAS,iBAAiB,KAAqB;AAC7C,QAAM,WAAW,IAAI,MAAM,GAAG,EAAE,OAAO,CAAC,MAAM,EAAE,SAAS,CAAC;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AW;AAAA,QACxB;AAAA,QACA,CAAC,QAAiB;AAChB,gBAAM,QAAQ,GAAG,KAAK,aAAa,IAAI,IAAI,KAAK,aAAa,EAAE;AAC/D,gBAAM,SAAS,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC9D,gBAAM,UACJ,mBAAmB,KAAK,GAAG,KAAK,SAAS,WAAW,KAAK,MAAM,OAAO,EAAE,uBAC3D,MAAM;AAErB,cAAI,OAAO,YAAY,aAAa;AAClC,oBAAQ,KAAK,6BAA6B,OAAO,EAAE;AAAA,UACrD;AACA,cAAI,IAAI,OAAO;AACf,sBAAY,KAAK,IAAI,MAAM,SAAS,EAAE,OAAO,eAAe,QAAQ,MAAM,OAAU,CAAC,CAAC;AAAA,QACxF;AAAA,MACF;AAAA,IACJ;AAAA,EACF;AAIA,MAAI,MAAM,SAAS,GAAG;AACpB,UAAM,IAAI,KAAK,GAAG,MAAM,MAAM,wBAAwB,MAAM,QAAQ,IAAI,KAAK,CAAC;AAAA,EAChF;AAEA,aAAW,QAAQ,OAAO;AACxB,uBAAmB,MAAM,OAAO,cAAc,KAAK,WAAW;AAAA,EAChE;AACA,MAAI,IAAI,4BAA4B;AAIpC,QAAM,OAA2B;AAAA,IAC/B;AAAA,IACA;AAAA,IACA,UAAU,WAAW;AAAA,IACrB,OAAO,WAAW;AAAA,EACpB;AACA,QAAM,YACJ,QAAQ,cAAc,iBAAiB,QAAQ,YAAY,YAAY;AACzE,MAAI,WAAW;AACb,SAAK,YAAY;AACjB,UAAM,cAAc,mBAAmB,WAAW,OAAO,GAAG;AAC5D,QAAI,YAAa,MAAK,cAAc;AAAA,EACtC;AACA,QAAM,YAAY,kBAAkB,QAAQ,YAAY,iBAAiB,SAAS;AAClF,MAAI,WAAW;AACb,SAAK,kBAAkB,EAAE,UAAU;AAAA,EACrC;AACA,SAAO;AACT;","names":[]}
@@ -1,34 +0,0 @@
1
- /**
2
- * Lists the occurrence keys of the scopes an element roots, space-separated.
3
- * Put it on the outermost element a node renders. The keys are opaque: they
4
- * resolve through `plan.attribution.scopes`, so no attribution lives in the DOM.
5
- */
6
- declare const TRACKING_SCOPES_ATTRIBUTE = "data-ctfl-scopes";
7
- /**
8
- * Opts an element into click tracking when it is not otherwise interactive.
9
- * Links, buttons, form controls, `[role="button"]`, `[role="link"]`, and
10
- * elements with an `onclick` handler count already. Set it to `"true"`.
11
- */
12
- declare const TRACKING_CLICKABLE_ATTRIBUTE = "data-ctfl-clickable";
13
- interface TrackingAttributes {
14
- [TRACKING_SCOPES_ATTRIBUTE]?: string;
15
- }
16
- /**
17
- * Attributes to spread onto a tracked node's outermost element, built from the
18
- * `attribution` a component context accessor returns. Returns `{}` when the
19
- * node roots no scope: nothing is rendered for it, so a node in the middle of a
20
- * scope, or one without attribution, is left alone.
21
- *
22
- * @example
23
- * ```tsx
24
- * const contentful = useContentfulComponent();
25
- * <section {...getTrackingAttributes(contentful?.attribution)}>…</section>
26
- * ```
27
- */
28
- declare function getTrackingAttributes(attribution: {
29
- roots: ReadonlyArray<{
30
- key: string;
31
- }>;
32
- } | undefined): TrackingAttributes;
33
-
34
- export { TRACKING_CLICKABLE_ATTRIBUTE, TRACKING_SCOPES_ATTRIBUTE, type TrackingAttributes, getTrackingAttributes };
@@ -1,12 +0,0 @@
1
- const TRACKING_SCOPES_ATTRIBUTE = "data-ctfl-scopes";
2
- const TRACKING_CLICKABLE_ATTRIBUTE = "data-ctfl-clickable";
3
- function getTrackingAttributes(attribution) {
4
- const keys = attribution?.roots.map((scope) => scope.key) ?? [];
5
- return keys.length > 0 ? { [TRACKING_SCOPES_ATTRIBUTE]: keys.join(" ") } : {};
6
- }
7
- export {
8
- TRACKING_CLICKABLE_ATTRIBUTE,
9
- TRACKING_SCOPES_ATTRIBUTE,
10
- getTrackingAttributes
11
- };
12
- //# sourceMappingURL=tracking-attributes.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/tracking-attributes.ts"],"sourcesContent":["/**\n * Lists the occurrence keys of the scopes an element roots, space-separated.\n * Put it on the outermost element a node renders. The keys are opaque: they\n * resolve through `plan.attribution.scopes`, so no attribution lives in the DOM.\n */\nexport const TRACKING_SCOPES_ATTRIBUTE = 'data-ctfl-scopes';\n\n/**\n * Opts an element into click tracking when it is not otherwise interactive.\n * Links, buttons, form controls, `[role=\"button\"]`, `[role=\"link\"]`, and\n * elements with an `onclick` handler count already. Set it to `\"true\"`.\n */\nexport const TRACKING_CLICKABLE_ATTRIBUTE = 'data-ctfl-clickable';\n\nexport interface TrackingAttributes {\n [TRACKING_SCOPES_ATTRIBUTE]?: string;\n}\n\n/**\n * Attributes to spread onto a tracked node's outermost element, built from the\n * `attribution` a component context accessor returns. Returns `{}` when the\n * node roots no scope: nothing is rendered for it, so a node in the middle of a\n * scope, or one without attribution, is left alone.\n *\n * @example\n * ```tsx\n * const contentful = useContentfulComponent();\n * <section {...getTrackingAttributes(contentful?.attribution)}>…</section>\n * ```\n */\nexport function getTrackingAttributes(\n attribution: { roots: ReadonlyArray<{ key: string }> } | undefined\n): TrackingAttributes {\n const keys = attribution?.roots.map((scope) => scope.key) ?? [];\n return keys.length > 0 ? { [TRACKING_SCOPES_ATTRIBUTE]: keys.join(' ') } : {};\n}\n"],"mappings":"AAKO,MAAM,4BAA4B;AAOlC,MAAM,+BAA+B;AAkBrC,SAAS,sBACd,aACoB;AACpB,QAAM,OAAO,aAAa,MAAM,IAAI,CAAC,UAAU,MAAM,GAAG,KAAK,CAAC;AAC9D,SAAO,KAAK,SAAS,IAAI,EAAE,CAAC,yBAAyB,GAAG,KAAK,KAAK,GAAG,EAAE,IAAI,CAAC;AAC9E;","names":[]}
package/dist/types.js DELETED
@@ -1 +0,0 @@
1
- //# sourceMappingURL=types.js.map
package/dist/types.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}