@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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,13 @@
1
+ ## 0.13.1 (2026-10-22)
2
+
3
+ ### 🚀 Features
4
+
5
+ - ⚠️ **web:** add interceptors and diagnostic streams [NT-4155] ([#251](https://github.com/contentful/experiences/pull/251))
6
+
7
+ ### ⚠️ Breaking Changes
8
+
9
+ - **web:** add interceptors and diagnostic streams [NT-4155] ([#251](https://github.com/contentful/experiences/pull/251))
10
+
1
11
  ## 0.13.0 (2026-10-22)
2
12
 
3
13
  ### 🚀 Features
package/dist/index.cjs ADDED
@@ -0,0 +1,542 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/attribution.ts
2
+ var SUPPORTED_VERSION = 1;
3
+ var DEFINING_LAYER_KIND = {
4
+ Experience: "ExperienceTemplate",
5
+ ExperienceFragment: "Component"
6
+ };
7
+ function asRecord(value) {
8
+ return typeof value === "object" && value !== null ? value : void 0;
9
+ }
10
+ function asIndex(value) {
11
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
12
+ }
13
+ function asString(value) {
14
+ return typeof value === "string" && value.length > 0 ? value : void 0;
15
+ }
16
+ function rowAt(rows, ref) {
17
+ const index = asIndex(ref);
18
+ return index === void 0 ? void 0 : asRecord(rows[index]);
19
+ }
20
+ function isPath(value) {
21
+ return Array.isArray(value) && value.every((s) => typeof s === "string" || Number.isInteger(s));
22
+ }
23
+ function parseLayer(value) {
24
+ const record = asRecord(value);
25
+ if (record === void 0) return void 0;
26
+ return { record, kind: asString(record.kind), id: asString(record.id) };
27
+ }
28
+ function scopeKind(layer) {
29
+ if (layer.kind === "Experience") return "Experience";
30
+ if (layer.kind === "ExperienceFragment") return "ExperienceFragment";
31
+ return void 0;
32
+ }
33
+ function createContext(sourceMap, log) {
34
+ const map = asRecord(sourceMap);
35
+ if (_optionalChain([map, 'optionalAccess', _ => _.version]) !== SUPPORTED_VERSION) {
36
+ log.log(`ignoring source map: unsupported version ${String(_optionalChain([map, 'optionalAccess', _2 => _2.version]))}`);
37
+ return void 0;
38
+ }
39
+ const nodes = asRecord(map.nodes);
40
+ if (!Array.isArray(map.layers) || !Array.isArray(map.variants) || nodes === void 0) {
41
+ log.log("ignoring source map: missing layers, variants or nodes");
42
+ return void 0;
43
+ }
44
+ return {
45
+ nodes,
46
+ layers: map.layers.map(parseLayer),
47
+ variants: map.variants,
48
+ entries: Array.isArray(map.entries) ? map.entries : [],
49
+ dataAssemblies: Array.isArray(map.dataAssemblies) ? map.dataAssemblies : [],
50
+ log,
51
+ scopes: {},
52
+ scopeEntries: /* @__PURE__ */ new Map(),
53
+ bindingEntries: /* @__PURE__ */ new Map()
54
+ };
55
+ }
56
+ function reportableScopes(ctx, chain) {
57
+ const outerFirst = [...chain].reverse();
58
+ const scopes = [];
59
+ for (const [position, row] of outerFirst.entries()) {
60
+ const layer = ctx.layers[row];
61
+ const kind = layer === void 0 ? void 0 : scopeKind(layer);
62
+ if (_optionalChain([layer, 'optionalAccess', _3 => _3.id]) === void 0 || kind === void 0) continue;
63
+ if (scopes.some((scope) => scope.row === row)) continue;
64
+ const innerRow = outerFirst[position + 1];
65
+ const innerLayer = innerRow === void 0 ? void 0 : ctx.layers[innerRow];
66
+ const definesThisScope = _optionalChain([innerLayer, 'optionalAccess', _4 => _4.kind]) === DEFINING_LAYER_KIND[kind];
67
+ scopes.push({
68
+ row,
69
+ layer,
70
+ entityId: layer.id,
71
+ kind,
72
+ entityKindId: definesThisScope ? _optionalChain([innerLayer, 'optionalAccess', _5 => _5.id]) : void 0
73
+ });
74
+ }
75
+ return scopes;
76
+ }
77
+ function occurrenceKey(row, listPath, runStart) {
78
+ return `s${row}@${listPath}#${runStart}`;
79
+ }
80
+ function readVariant(ctx, scope) {
81
+ const refs = scope.layer.record.variants;
82
+ if (!Array.isArray(refs) || refs.length === 0) return { variantId: "default" };
83
+ if (refs.length > 1) {
84
+ ctx.log.log(`layer "${scope.entityId}" lists ${refs.length} variants; using the first`);
85
+ }
86
+ const variant = rowAt(ctx.variants, refs[0]);
87
+ const optimizationId = asString(_optionalChain([variant, 'optionalAccess', _6 => _6.optimizationId]));
88
+ const variantId = _nullishCoalesce(asString(_optionalChain([variant, 'optionalAccess', _7 => _7.variantId])), () => ( "default"));
89
+ const variantIndex = _optionalChain([variant, 'optionalAccess', _8 => _8.variantIndex]);
90
+ const fields = { variantId };
91
+ if (optimizationId !== void 0) fields.optimizationId = optimizationId;
92
+ if (typeof variantIndex === "number") fields.variantIndex = variantIndex;
93
+ return fields;
94
+ }
95
+ function buildScope(ctx, scope, key, parentExperience) {
96
+ const attribution = {
97
+ key,
98
+ entityId: scope.entityId,
99
+ entityKind: scope.kind,
100
+ ...readVariant(ctx, scope)
101
+ };
102
+ if (scope.entityKindId !== void 0) {
103
+ attribution.entityKindId = scope.entityKindId;
104
+ }
105
+ if (scope.kind === "ExperienceFragment" && parentExperience !== void 0) {
106
+ attribution.parentExperienceId = parentExperience.entityId;
107
+ if (parentExperience.variantId !== void 0) {
108
+ attribution.parentVariantId = parentExperience.variantId;
109
+ }
110
+ }
111
+ return attribution;
112
+ }
113
+ function entriesBoundAt(ctx, assemblyRow, path) {
114
+ const cacheKey = `${assemblyRow}|${JSON.stringify(path)}`;
115
+ const cached = ctx.bindingEntries.get(cacheKey);
116
+ if (cached !== void 0) return cached;
117
+ const found = /* @__PURE__ */ new Set();
118
+ const visited = /* @__PURE__ */ new Set();
119
+ const followAssembly = (row, path2) => {
120
+ const visitKey = `${row}|${JSON.stringify(path2)}`;
121
+ const assembly = asRecord(ctx.dataAssemblies[row]);
122
+ if (assembly === void 0 || visited.has(visitKey)) return;
123
+ visited.add(visitKey);
124
+ walk(assembly.return, path2);
125
+ };
126
+ const walkLeaf = (leaf, path2) => {
127
+ if (leaf.type === "entry") {
128
+ const entryId = asString(_optionalChain([rowAt, 'call', _9 => _9(ctx.entries, leaf.entry), 'optionalAccess', _10 => _10.id]));
129
+ if (entryId !== void 0) found.add(entryId);
130
+ } else if (leaf.type === "dataAssembly") {
131
+ const row = asIndex(leaf.dataAssembly);
132
+ const leafPath = isPath(leaf.path) ? leaf.path : [];
133
+ if (row !== void 0) followAssembly(row, [...leafPath, ...path2]);
134
+ }
135
+ };
136
+ const walk = (value, path2) => {
137
+ const [head, ...rest] = path2;
138
+ if (Array.isArray(value)) {
139
+ if (head === void 0) value.forEach((child) => walk(child, []));
140
+ else if (typeof head === "number") walk(value[head], rest);
141
+ return;
142
+ }
143
+ const record = asRecord(value);
144
+ if (record === void 0) return;
145
+ if (typeof record.type === "string") walkLeaf(record, path2);
146
+ else if (head === void 0) Object.values(record).forEach((child) => walk(child, []));
147
+ else walk(record[String(head)], rest);
148
+ };
149
+ followAssembly(assemblyRow, path);
150
+ const ids = [...found];
151
+ ctx.bindingEntries.set(cacheKey, ids);
152
+ return ids;
153
+ }
154
+ function readNodeEntries(ctx, entry) {
155
+ const properties = Array.isArray(entry.contentProperties) ? entry.contentProperties : [];
156
+ const ids = /* @__PURE__ */ new Set();
157
+ for (const property of properties) {
158
+ const item = asRecord(property);
159
+ const assemblyRow = asIndex(_optionalChain([item, 'optionalAccess', _11 => _11.dataAssembly]));
160
+ const bindings = asRecord(_optionalChain([item, 'optionalAccess', _12 => _12.bindings]));
161
+ if (_optionalChain([item, 'optionalAccess', _13 => _13.type]) !== "dataAssembly" || assemblyRow === void 0 || bindings === void 0) {
162
+ continue;
163
+ }
164
+ for (const path of Object.values(bindings).filter(isPath)) {
165
+ for (const id of entriesBoundAt(ctx, assemblyRow, path)) ids.add(id);
166
+ }
167
+ }
168
+ return [...ids];
169
+ }
170
+ function addScopeEntries(ctx, scope, entryIds) {
171
+ const owned = _nullishCoalesce(ctx.scopeEntries.get(scope), () => ( /* @__PURE__ */ new Set()));
172
+ for (const id of entryIds) owned.add(id);
173
+ ctx.scopeEntries.set(scope, owned);
174
+ }
175
+ function readChain(entry) {
176
+ const { layers } = entry;
177
+ return Array.isArray(layers) && layers.every(Number.isInteger) ? layers : [];
178
+ }
179
+ function attributeNode(ctx, node, parentKeys, previousKeys, listPath, index) {
180
+ const entry = node.nodeId === void 0 ? void 0 : asRecord(ctx.nodes[node.nodeId]);
181
+ if (entry === void 0) return void 0;
182
+ const scopes = reportableScopes(ctx, readChain(entry));
183
+ if (scopes.length === 0) return void 0;
184
+ const keys = /* @__PURE__ */ new Map();
185
+ const attribution = { scopes: [], roots: [] };
186
+ let parentExperience;
187
+ let nearest;
188
+ const previousScopes = previousKeys.entries();
189
+ let sameOccurrencePrefix = true;
190
+ for (const scope of scopes) {
191
+ const previous = previousScopes.next().value;
192
+ sameOccurrencePrefix &&= _optionalChain([previous, 'optionalAccess', _14 => _14[0]]) === scope.row;
193
+ const isRoot = !parentKeys.has(scope.row);
194
+ const key = _nullishCoalesce(_nullishCoalesce(parentKeys.get(scope.row), () => ( (sameOccurrencePrefix ? _optionalChain([previous, 'optionalAccess', _15 => _15[1]]) : void 0))), () => ( occurrenceKey(scope.row, listPath, index)));
195
+ sameOccurrencePrefix &&= _optionalChain([previous, 'optionalAccess', _16 => _16[1]]) === key;
196
+ keys.set(scope.row, key);
197
+ nearest = ctx.scopes[key] ??= buildScope(ctx, scope, key, parentExperience);
198
+ attribution.scopes.push(nearest);
199
+ if (isRoot) attribution.roots.push(nearest);
200
+ if (scope.kind === "Experience" && parentExperience === void 0) parentExperience = nearest;
201
+ }
202
+ const entryIds = readNodeEntries(ctx, entry);
203
+ if (entryIds.length > 0 && nearest !== void 0) {
204
+ attribution.entryIds = entryIds;
205
+ addScopeEntries(ctx, nearest, entryIds);
206
+ }
207
+ node.attribution = attribution;
208
+ return keys;
209
+ }
210
+ function assignSiblings(ctx, siblings, parentKeys, listPath = "") {
211
+ let previousKeys = /* @__PURE__ */ new Map();
212
+ for (const [index, node] of siblings.entries()) {
213
+ const ownKeys = attributeNode(ctx, node, parentKeys, previousKeys, listPath, index);
214
+ previousKeys = _nullishCoalesce(ownKeys, () => ( /* @__PURE__ */ new Map()));
215
+ for (const [slotName, children] of Object.entries(node.slots)) {
216
+ assignSiblings(ctx, children, _nullishCoalesce(ownKeys, () => ( parentKeys)), `${listPath}/${index}.${slotName}`);
217
+ }
218
+ }
219
+ }
220
+ function resolveAttribution(sourceMap, nodes, log) {
221
+ if (sourceMap === void 0) return void 0;
222
+ const ctx = createContext(sourceMap, log);
223
+ if (ctx === void 0) return void 0;
224
+ assignSiblings(ctx, nodes, /* @__PURE__ */ new Map());
225
+ for (const [scope, ids] of ctx.scopeEntries) scope.entryIds = [...ids];
226
+ const scopes = Object.values(ctx.scopes);
227
+ for (const scope of scopes) Object.freeze(scope);
228
+ return scopes.length > 0 ? { scopes: ctx.scopes } : void 0;
229
+ }
230
+
231
+ // src/debug-logger.ts
232
+ var PREFIX = "[experiences:debug]";
233
+ function now() {
234
+ if (typeof performance !== "undefined" && typeof performance.now === "function") {
235
+ return performance.now();
236
+ }
237
+ if (typeof Date !== "undefined" && typeof Date.now === "function") return Date.now();
238
+ return 0;
239
+ }
240
+ var NOOP_LOGGER = {
241
+ log() {
242
+ },
243
+ lazy() {
244
+ },
245
+ time: (_label, fn) => fn(),
246
+ enabled: false
247
+ };
248
+ function createDebugLogger(debug, scope) {
249
+ if (!debug || typeof console === "undefined") return NOOP_LOGGER;
250
+ const tag = `${PREFIX}[${scope}]`;
251
+ return {
252
+ enabled: true,
253
+ log(message, data) {
254
+ if (data === void 0) console.log(`${tag} ${message}`);
255
+ else console.log(`${tag} ${message}`, data);
256
+ },
257
+ lazy(message, getData) {
258
+ console.log(`${tag} ${message}`, getData());
259
+ },
260
+ async time(label, fn) {
261
+ const start = now();
262
+ try {
263
+ const result = await fn();
264
+ console.log(`${tag} \u23F1 ${label} \u2014 ${(now() - start).toFixed(1)}ms`);
265
+ return result;
266
+ } catch (err) {
267
+ console.log(`${tag} \u23F1 ${label} \u2014 failed after ${(now() - start).toFixed(1)}ms`, err);
268
+ throw err;
269
+ }
270
+ }
271
+ };
272
+ }
273
+
274
+ // src/design-properties.ts
275
+ function resolveDesignProperties(designProperties) {
276
+ const out = {};
277
+ if (!designProperties) return out;
278
+ for (const [key, prop] of Object.entries(designProperties)) {
279
+ out[key] = prop.type === "ManualDesignValue" ? prop.value : prop;
280
+ }
281
+ return out;
282
+ }
283
+ function applyTokenResolver(props, resolveToken) {
284
+ const out = {};
285
+ const unresolved = [];
286
+ for (const [key, value] of Object.entries(props)) {
287
+ if (typeof value === "object" && value !== null && value.type === "DesignToken") {
288
+ const resolved = _optionalChain([resolveToken, 'optionalCall', _17 => _17(value)]);
289
+ if (resolved === void 0) {
290
+ out[key] = value;
291
+ unresolved.push(value.value);
292
+ continue;
293
+ }
294
+ out[key] = resolved;
295
+ continue;
296
+ }
297
+ out[key] = value;
298
+ }
299
+ return { props: out, unresolved };
300
+ }
301
+
302
+ // src/resolve-experience.ts
303
+ function getResolver(entry) {
304
+ if (typeof entry !== "object" || entry === null) return void 0;
305
+ const candidate = entry.resolveData;
306
+ return typeof candidate === "function" ? candidate : void 0;
307
+ }
308
+ var DEFAULT_EXPERIENCE = {
309
+ debug: false,
310
+ metadata: {}
311
+ };
312
+ function lookupEntry(config, registration) {
313
+ return registration.kind === "experienceTemplate" ? _optionalChain([config, 'access', _18 => _18.experienceTemplates, 'optionalAccess', _19 => _19[registration.id]]) : config.components[registration.id];
314
+ }
315
+ function extractIdFromUrn(urn) {
316
+ const segments = urn.split("/").filter((s) => s.length > 0);
317
+ return _nullishCoalesce(segments[segments.length - 1], () => ( urn));
318
+ }
319
+ function readNodeRef(node) {
320
+ const isExperienceTemplate = "experienceTemplate" in node;
321
+ const ref = isExperienceTemplate ? node.experienceTemplate : "component" in node ? node.component : void 0;
322
+ const urn = _optionalChain([ref, 'optionalAccess', _20 => _20.sys, 'optionalAccess', _21 => _21.urn]);
323
+ if (typeof urn !== "string" || urn.length === 0) return null;
324
+ return { kind: isExperienceTemplate ? "experienceTemplate" : "component", urn };
325
+ }
326
+ function ensureArray(value, field, log, diagnostics) {
327
+ if (Array.isArray(value)) return value;
328
+ 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.`;
329
+ if (typeof console !== "undefined") {
330
+ console.warn(`[@contentful/experiences] ${message}`);
331
+ }
332
+ log.log(message);
333
+ diagnostics.push(new Error(message));
334
+ return [];
335
+ }
336
+ function countPayloadNodes(node) {
337
+ const slots = node.slots;
338
+ let total = 1;
339
+ if (slots && typeof slots === "object") {
340
+ for (const children of Object.values(slots)) {
341
+ if (!Array.isArray(children)) continue;
342
+ for (const child of children) total += countPayloadNodes(child);
343
+ }
344
+ }
345
+ return total;
346
+ }
347
+ function warnUnrenderableNode(node, log, diagnostics) {
348
+ const id = node.id;
349
+ const label = typeof id === "string" ? ` "${id}"` : "";
350
+ const keys = Object.keys(node);
351
+ const descendants = countPayloadNodes(node) - 1;
352
+ 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.`;
353
+ if (typeof console !== "undefined") {
354
+ console.warn(`[@contentful/experiences] ${message}`);
355
+ }
356
+ log.log(message);
357
+ diagnostics.push(new Error(message));
358
+ }
359
+ function buildNodes(nodes, config, nodeRefs, log, diagnostics) {
360
+ const built = [];
361
+ for (const node of nodes) {
362
+ const one = buildNode(node, config, nodeRefs, log, diagnostics);
363
+ if (one !== null) built.push(one);
364
+ }
365
+ return built;
366
+ }
367
+ function buildNode(node, config, nodeRefs, log, diagnostics) {
368
+ const ref = readNodeRef(node);
369
+ if (ref === null) {
370
+ warnUnrenderableNode(node, log, diagnostics);
371
+ return null;
372
+ }
373
+ const registration = {
374
+ kind: ref.kind,
375
+ id: extractIdFromUrn(ref.urn)
376
+ };
377
+ const nodeId = typeof node.id === "string" ? node.id : void 0;
378
+ const slots = {};
379
+ if (node.slots) {
380
+ for (const [slotName, children] of Object.entries(node.slots)) {
381
+ if (!Array.isArray(children)) {
382
+ 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.`;
383
+ if (typeof console !== "undefined") {
384
+ console.warn(`[@contentful/experiences] ${message}`);
385
+ }
386
+ log.log(message);
387
+ diagnostics.push(new Error(message));
388
+ slots[slotName] = [];
389
+ continue;
390
+ }
391
+ slots[slotName] = buildNodes(children, config, nodeRefs, log, diagnostics);
392
+ }
393
+ }
394
+ const built = {
395
+ registration,
396
+ props: {
397
+ content: { ..._nullishCoalesce(node.contentProperties, () => ( {})) },
398
+ // Resolved design values are written by the pre-resolution pass below.
399
+ design: {},
400
+ designRaw: { ..._nullishCoalesce(node.designProperties, () => ( {})) }
401
+ },
402
+ slots
403
+ };
404
+ if (node.id) built.nodeId = node.id;
405
+ if (getResolver(lookupEntry(config, registration))) {
406
+ nodeRefs.push(built);
407
+ }
408
+ return built;
409
+ }
410
+ function preResolveDesignProperties(design, resolveToken) {
411
+ return applyTokenResolver(resolveDesignProperties(design), resolveToken);
412
+ }
413
+ function warnUnresolvedTokens(label, unresolved, log, diagnostics) {
414
+ if (!unresolved.length) return;
415
+ 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.`;
416
+ if (typeof console !== "undefined") {
417
+ console.warn(`[@contentful/experiences] ${message}`);
418
+ }
419
+ log.log(`unresolved token id(s) on "${label}": ${unresolved.join(", ")}`);
420
+ for (const tokenId of unresolved) {
421
+ diagnostics.push(
422
+ new Error(
423
+ `Design token "${tokenId}" on ${label} has no \`resolveToken\` mapping; the raw token reaches the component unresolved.`
424
+ )
425
+ );
426
+ }
427
+ }
428
+ function preResolveNodeTree(node, resolveToken, log, diagnostics) {
429
+ const { props, unresolved } = preResolveDesignProperties(node.props.designRaw, resolveToken);
430
+ node.props.design = props;
431
+ warnUnresolvedTokens(
432
+ `${node.registration.kind}:${node.registration.id}`,
433
+ unresolved,
434
+ log,
435
+ diagnostics
436
+ );
437
+ for (const children of Object.values(node.slots)) {
438
+ for (const child of children) {
439
+ preResolveNodeTree(child, resolveToken, log, diagnostics);
440
+ }
441
+ }
442
+ }
443
+ async function resolveExperience(payload, config, options = {}) {
444
+ const log = createDebugLogger(options.debug, "core");
445
+ log.lazy("resolveExperience called with payload", () => payload);
446
+ const diagnostics = [];
447
+ const isPlainPayload = payload !== null && typeof payload === "object";
448
+ if (!isPlainPayload) {
449
+ 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.`;
450
+ if (typeof console !== "undefined") {
451
+ console.warn(`[@contentful/experiences] ${message}`);
452
+ }
453
+ log.log(message);
454
+ diagnostics.push(new Error(message));
455
+ }
456
+ const payloadNodes = isPlainPayload ? ensureArray(payload.nodes, "nodes", log, diagnostics) : [];
457
+ const nodeRefs = [];
458
+ const nodes = buildNodes(payloadNodes, config, nodeRefs, log, diagnostics);
459
+ log.log(`built ${nodes.length} top-level node(s); ${nodeRefs.length} declare resolveData`);
460
+ const experience = {
461
+ debug: _nullishCoalesce(options.debug, () => ( DEFAULT_EXPERIENCE.debug)),
462
+ metadata: {
463
+ ...DEFAULT_EXPERIENCE.metadata,
464
+ ..._nullishCoalesce(options.metadata, () => ( {}))
465
+ }
466
+ };
467
+ const tasks = [];
468
+ for (const node of nodeRefs) {
469
+ const resolver = getResolver(lookupEntry(config, node.registration));
470
+ if (!resolver) continue;
471
+ const ctx = {
472
+ content: node.props.content,
473
+ design: node.props.designRaw,
474
+ experience
475
+ };
476
+ tasks.push(
477
+ // Deferred via `.then(() => resolver(ctx))` rather than
478
+ // `Promise.resolve(resolver(ctx))`: the latter calls `resolver(ctx)`
479
+ // eagerly as an argument, so a resolver that throws *synchronously*
480
+ // escapes immediately instead of becoming a rejection. The `onFailure`
481
+ // handler below never rethrows, so one broken resolver can't fail the
482
+ // `Promise.all` for every other node.
483
+ Promise.resolve().then(() => resolver(ctx)).then(
484
+ (resolved) => {
485
+ node.props.resolved = resolved;
486
+ },
487
+ (err) => {
488
+ const label = `${node.registration.kind}:${node.registration.id}`;
489
+ const reason = err instanceof Error ? err.message : String(err);
490
+ 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.`;
491
+ if (typeof console !== "undefined") {
492
+ console.warn(`[@contentful/experiences] ${message}`);
493
+ }
494
+ log.log(message);
495
+ diagnostics.push(new Error(message, { cause: err instanceof Error ? err : void 0 }));
496
+ }
497
+ )
498
+ );
499
+ }
500
+ if (tasks.length > 0) {
501
+ await log.time(`${tasks.length} resolveData hook(s)`, () => Promise.all(tasks));
502
+ }
503
+ for (const node of nodes) {
504
+ preResolveNodeTree(node, config.resolveToken, log, diagnostics);
505
+ }
506
+ log.log("resolved design properties");
507
+ const plan = {
508
+ nodes,
509
+ diagnostics,
510
+ metadata: experience.metadata,
511
+ debug: experience.debug
512
+ };
513
+ const sourceMap = _nullishCoalesce(options.sourceMap, () => ( (isPlainPayload ? _optionalChain([payload, 'access', _22 => _22.extensions, 'optionalAccess', _23 => _23.sourceMap]) : void 0)));
514
+ if (sourceMap) {
515
+ plan.sourceMap = sourceMap;
516
+ const attribution = resolveAttribution(sourceMap, nodes, log);
517
+ if (attribution) plan.attribution = attribution;
518
+ }
519
+ const profileId = isPlainPayload && _optionalChain([payload, 'access', _24 => _24.extensions, 'optionalAccess', _25 => _25.personalization, 'optionalAccess', _26 => _26.profile, 'optionalAccess', _27 => _27.id]);
520
+ if (profileId) {
521
+ plan.personalization = { profileId };
522
+ }
523
+ return plan;
524
+ }
525
+
526
+ // src/tracking-attributes.ts
527
+ var TRACKING_SCOPES_ATTRIBUTE = "data-ctfl-scopes";
528
+ var TRACKING_CLICKABLE_ATTRIBUTE = "data-ctfl-clickable";
529
+ function getTrackingAttributes(attribution) {
530
+ const keys = _nullishCoalesce(_optionalChain([attribution, 'optionalAccess', _28 => _28.roots, 'access', _29 => _29.map, 'call', _30 => _30((scope) => scope.key)]), () => ( []));
531
+ return keys.length > 0 ? { [TRACKING_SCOPES_ATTRIBUTE]: keys.join(" ") } : {};
532
+ }
533
+
534
+
535
+
536
+
537
+
538
+
539
+
540
+
541
+ exports.TRACKING_CLICKABLE_ATTRIBUTE = TRACKING_CLICKABLE_ATTRIBUTE; exports.TRACKING_SCOPES_ATTRIBUTE = TRACKING_SCOPES_ATTRIBUTE; exports.applyTokenResolver = applyTokenResolver; exports.createDebugLogger = createDebugLogger; exports.getTrackingAttributes = getTrackingAttributes; exports.resolveDesignProperties = resolveDesignProperties; exports.resolveExperience = resolveExperience;
542
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/experiences/experiences/packages/core/dist/index.cjs","../src/attribution.ts","../src/debug-logger.ts","../src/design-properties.ts","../src/resolve-experience.ts","../src/tracking-attributes.ts"],"names":["path"],"mappings":"AAAA;ACSA,IAAM,kBAAA,EAAoB,CAAA;AAO1B,IAAM,oBAAA,EAAkD;AAAA,EACt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AA;AACA,IAAA;AACF,EAAA;AACkD,EAAA;AAClB,IAAA;AAC4B,MAAA;AAC1D,IAAA;AACF,EAAA;AACF;AAgB+B;AACsB,EAAA;AACY,EAAA;AAEjC,EAAA;AASgC,EAAA;AACzC,EAAA;AAEoC,IAAA;AAInB,IAAA;AACiB,MAAA;AACrD,IAAA;AACe,IAAA;AACoB,IAAA;AACrC,EAAA;AAEwD,EAAA;AAIhB,EAAA;AACuD,EAAA;AAC5B,EAAA;AAG7B,EAAA;AACO,IAAA;AACjC,IAAA;AACc,MAAA;AACG,MAAA;AAC3B,IAAA;AACF,EAAA;AAEqC,EAAA;AAER,EAAA;AACwC,IAAA;AACpD,IAAA;AACa,IAAA;AACN,MAAA;AACD,MAAA;AACnB,MAAA;AACF,IAAA;AACM,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASD,MAAA;AACe,QAAA;AACU,UAAA;AACxB,QAAA;AACkB,QAAA;AAC+C,UAAA;AACD,UAAA;AAEnB,UAAA;AAGP,UAAA;AACiB,YAAA;AACrD,UAAA;AACe,UAAA;AAC6C,UAAA;AAC9D,QAAA;AACF,MAAA;AACJ,IAAA;AACF,EAAA;AAIsB,EAAA;AACoD,IAAA;AAC1E,EAAA;AAE0B,EAAA;AACsC,IAAA;AAChE,EAAA;AACoC,EAAA;AAIH,EAAA;AAC/B,IAAA;AACA,IAAA;AACqB,IAAA;AACH,IAAA;AACpB,EAAA;AAEiD,EAAA;AAClC,EAAA;AACI,IAAA;AAC2C,IAAA;AACxB,IAAA;AACtC,EAAA;AACyE,EAAA;AAC1D,EAAA;AACsB,IAAA;AACrC,EAAA;AACO,EAAA;AACT;AJsD6E;AACA;AKxgBpC;AAOG;AAoBtB;AAC0C,EAAA;AACa,EAAA;AAC7E;ALif6E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/experiences/experiences/packages/core/dist/index.cjs","sourcesContent":[null,"import type { DebugLogger } from './debug-logger.js';\nimport type {\n ExperienceSourceMap,\n NodeAttribution,\n PlanAttribution,\n PortableRenderNode,\n ScopeAttribution,\n} from './types.js';\n\nconst SUPPORTED_VERSION = 1;\n\ntype EntityKind = ScopeAttribution['entityKind'];\ntype VariantFields = Pick<ScopeAttribution, 'optimizationId' | 'variantId' | 'variantIndex'>;\ntype Rec = Record<string, unknown>;\ntype PathSegment = string | number;\n\nconst DEFINING_LAYER_KIND: Record<EntityKind, string> = {\n Experience: 'ExperienceTemplate',\n ExperienceFragment: 'Component',\n};\n\nfunction asRecord(value: unknown): Rec | undefined {\n return typeof value === 'object' && value !== null ? (value as Rec) : undefined;\n}\n\nfunction asIndex(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isInteger(value) && value >= 0 ? value : undefined;\n}\n\nfunction asString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction rowAt(rows: unknown[], ref: unknown): Rec | undefined {\n const index = asIndex(ref);\n return index === undefined ? undefined : asRecord(rows[index]);\n}\n\nfunction isPath(value: unknown): value is PathSegment[] {\n return Array.isArray(value) && value.every((s) => typeof s === 'string' || Number.isInteger(s));\n}\n\ninterface Layer {\n record: Rec;\n kind: string | undefined;\n id: string | undefined;\n}\n\nfunction parseLayer(value: unknown): Layer | undefined {\n const record = asRecord(value);\n if (record === undefined) return undefined;\n return { record, kind: asString(record.kind), id: asString(record.id) };\n}\n\nfunction scopeKind(layer: Layer): EntityKind | undefined {\n if (layer.kind === 'Experience') return 'Experience';\n if (layer.kind === 'ExperienceFragment') return 'ExperienceFragment';\n return undefined;\n}\n\ninterface Context {\n nodes: Rec;\n layers: (Layer | undefined)[];\n variants: unknown[];\n entries: unknown[];\n dataAssemblies: unknown[];\n log: DebugLogger;\n scopes: Record<string, ScopeAttribution>;\n scopeEntries: Map<ScopeAttribution, Set<string>>;\n bindingEntries: Map<string, readonly string[]>;\n}\n\nfunction createContext(sourceMap: ExperienceSourceMap, log: DebugLogger): Context | undefined {\n const map = asRecord(sourceMap);\n if (map?.version !== SUPPORTED_VERSION) {\n log.log(`ignoring source map: unsupported version ${String(map?.version)}`);\n return undefined;\n }\n const nodes = asRecord(map.nodes);\n if (!Array.isArray(map.layers) || !Array.isArray(map.variants) || nodes === undefined) {\n log.log('ignoring source map: missing layers, variants or nodes');\n return undefined;\n }\n return {\n nodes,\n layers: map.layers.map(parseLayer),\n variants: map.variants,\n entries: Array.isArray(map.entries) ? map.entries : [],\n dataAssemblies: Array.isArray(map.dataAssemblies) ? map.dataAssemblies : [],\n log,\n scopes: {},\n scopeEntries: new Map(),\n bindingEntries: new Map(),\n };\n}\n\ninterface ChainScope {\n row: number;\n layer: Layer;\n entityId: string;\n kind: EntityKind;\n entityKindId: string | undefined;\n}\n\nfunction reportableScopes(ctx: Context, chain: number[]): ChainScope[] {\n const outerFirst = [...chain].reverse();\n const scopes: ChainScope[] = [];\n\n for (const [position, row] of outerFirst.entries()) {\n const layer = ctx.layers[row];\n const kind = layer === undefined ? undefined : scopeKind(layer);\n if (layer?.id === undefined || kind === undefined) continue;\n if (scopes.some((scope) => scope.row === row)) continue;\n\n const innerRow = outerFirst[position + 1];\n const innerLayer = innerRow === undefined ? undefined : ctx.layers[innerRow];\n const definesThisScope = innerLayer?.kind === DEFINING_LAYER_KIND[kind];\n\n scopes.push({\n row,\n layer,\n entityId: layer.id,\n kind,\n entityKindId: definesThisScope ? innerLayer?.id : undefined,\n });\n }\n return scopes;\n}\n\nfunction occurrenceKey(row: number, listPath: string, runStart: number): string {\n return `s${row}@${listPath}#${runStart}`;\n}\n\nfunction readVariant(ctx: Context, scope: ChainScope): VariantFields {\n const refs = scope.layer.record.variants;\n if (!Array.isArray(refs) || refs.length === 0) return { variantId: 'default' };\n if (refs.length > 1) {\n ctx.log.log(`layer \"${scope.entityId}\" lists ${refs.length} variants; using the first`);\n }\n\n const variant = rowAt(ctx.variants, refs[0]);\n const optimizationId = asString(variant?.optimizationId);\n const variantId = asString(variant?.variantId) ?? 'default';\n const variantIndex = variant?.variantIndex;\n\n const fields: VariantFields = { variantId };\n if (optimizationId !== undefined) fields.optimizationId = optimizationId;\n if (typeof variantIndex === 'number') fields.variantIndex = variantIndex;\n return fields;\n}\n\nfunction buildScope(\n ctx: Context,\n scope: ChainScope,\n key: string,\n parentExperience: ScopeAttribution | undefined\n): ScopeAttribution {\n const attribution: ScopeAttribution = {\n key,\n entityId: scope.entityId,\n entityKind: scope.kind,\n ...readVariant(ctx, scope),\n };\n if (scope.entityKindId !== undefined) {\n attribution.entityKindId = scope.entityKindId;\n }\n if (scope.kind === 'ExperienceFragment' && parentExperience !== undefined) {\n attribution.parentExperienceId = parentExperience.entityId;\n if (parentExperience.variantId !== undefined) {\n attribution.parentVariantId = parentExperience.variantId;\n }\n }\n return attribution;\n}\n\nfunction entriesBoundAt(ctx: Context, assemblyRow: number, path: PathSegment[]): readonly string[] {\n const cacheKey = `${assemblyRow}|${JSON.stringify(path)}`;\n const cached = ctx.bindingEntries.get(cacheKey);\n if (cached !== undefined) return cached;\n\n const found = new Set<string>();\n const visited = new Set<string>();\n\n const followAssembly = (row: number, path: PathSegment[]): void => {\n const visitKey = `${row}|${JSON.stringify(path)}`;\n const assembly = asRecord(ctx.dataAssemblies[row]);\n if (assembly === undefined || visited.has(visitKey)) return;\n visited.add(visitKey);\n walk(assembly.return, path);\n };\n\n const walkLeaf = (leaf: Rec, path: PathSegment[]): void => {\n if (leaf.type === 'entry') {\n const entryId = asString(rowAt(ctx.entries, leaf.entry)?.id);\n if (entryId !== undefined) found.add(entryId);\n } else if (leaf.type === 'dataAssembly') {\n const row = asIndex(leaf.dataAssembly);\n const leafPath = isPath(leaf.path) ? leaf.path : [];\n if (row !== undefined) followAssembly(row, [...leafPath, ...path]);\n }\n };\n\n const walk = (value: unknown, path: PathSegment[]): void => {\n const [head, ...rest] = path;\n\n if (Array.isArray(value)) {\n if (head === undefined) value.forEach((child) => walk(child, []));\n else if (typeof head === 'number') walk(value[head], rest);\n return;\n }\n\n const record = asRecord(value);\n if (record === undefined) return;\n if (typeof record.type === 'string') walkLeaf(record, path);\n else if (head === undefined) Object.values(record).forEach((child) => walk(child, []));\n else walk(record[String(head)], rest);\n };\n\n followAssembly(assemblyRow, path);\n const ids = [...found];\n ctx.bindingEntries.set(cacheKey, ids);\n return ids;\n}\n\nfunction readNodeEntries(ctx: Context, entry: Rec): string[] {\n const properties: unknown[] = Array.isArray(entry.contentProperties)\n ? entry.contentProperties\n : [];\n const ids = new Set<string>();\n\n for (const property of properties) {\n const item = asRecord(property);\n const assemblyRow = asIndex(item?.dataAssembly);\n const bindings = asRecord(item?.bindings);\n if (item?.type !== 'dataAssembly' || assemblyRow === undefined || bindings === undefined) {\n continue;\n }\n for (const path of Object.values(bindings).filter(isPath)) {\n for (const id of entriesBoundAt(ctx, assemblyRow, path)) ids.add(id);\n }\n }\n return [...ids];\n}\n\nfunction addScopeEntries(ctx: Context, scope: ScopeAttribution, entryIds: string[]): void {\n const owned = ctx.scopeEntries.get(scope) ?? new Set<string>();\n for (const id of entryIds) owned.add(id);\n ctx.scopeEntries.set(scope, owned);\n}\n\nfunction readChain(entry: Rec): number[] {\n const { layers } = entry;\n return Array.isArray(layers) && layers.every(Number.isInteger) ? (layers as number[]) : [];\n}\n\nfunction attributeNode(\n ctx: Context,\n node: PortableRenderNode,\n parentKeys: Map<number, string>,\n previousKeys: Map<number, string>,\n listPath: string,\n index: number\n): Map<number, string> | undefined {\n const entry = node.nodeId === undefined ? undefined : asRecord(ctx.nodes[node.nodeId]);\n if (entry === undefined) return undefined;\n const scopes = reportableScopes(ctx, readChain(entry));\n if (scopes.length === 0) return undefined;\n\n const keys = new Map<number, string>();\n const attribution: NodeAttribution = { scopes: [], roots: [] };\n let parentExperience: ScopeAttribution | undefined;\n let nearest: ScopeAttribution | undefined;\n\n // A sibling's key is only reusable while every enclosing scope matches as well.\n const previousScopes = previousKeys.entries();\n let sameOccurrencePrefix = true;\n\n for (const scope of scopes) {\n const previous = previousScopes.next().value;\n sameOccurrencePrefix &&= previous?.[0] === scope.row;\n\n const isRoot = !parentKeys.has(scope.row);\n const key: string =\n parentKeys.get(scope.row) ??\n (sameOccurrencePrefix ? previous?.[1] : undefined) ??\n occurrenceKey(scope.row, listPath, index);\n sameOccurrencePrefix &&= previous?.[1] === key;\n keys.set(scope.row, key);\n\n nearest = ctx.scopes[key] ??= buildScope(ctx, scope, key, parentExperience);\n attribution.scopes.push(nearest);\n if (isRoot) attribution.roots.push(nearest);\n if (scope.kind === 'Experience' && parentExperience === undefined) parentExperience = nearest;\n }\n\n const entryIds = readNodeEntries(ctx, entry);\n if (entryIds.length > 0 && nearest !== undefined) {\n attribution.entryIds = entryIds;\n addScopeEntries(ctx, nearest, entryIds);\n }\n node.attribution = attribution;\n return keys;\n}\n\nfunction assignSiblings(\n ctx: Context,\n siblings: PortableRenderNode[],\n parentKeys: Map<number, string>,\n listPath = ''\n): void {\n let previousKeys = new Map<number, string>();\n for (const [index, node] of siblings.entries()) {\n const ownKeys = attributeNode(ctx, node, parentKeys, previousKeys, listPath, index);\n previousKeys = ownKeys ?? new Map();\n\n for (const [slotName, children] of Object.entries(node.slots)) {\n assignSiblings(ctx, children, ownKeys ?? parentKeys, `${listPath}/${index}.${slotName}`);\n }\n }\n}\n\nexport function resolveAttribution(\n sourceMap: ExperienceSourceMap | undefined,\n nodes: PortableRenderNode[],\n log: DebugLogger\n): PlanAttribution | undefined {\n if (sourceMap === undefined) return undefined;\n const ctx = createContext(sourceMap, log);\n if (ctx === undefined) return undefined;\n\n assignSiblings(ctx, nodes, new Map());\n for (const [scope, ids] of ctx.scopeEntries) scope.entryIds = [...ids];\n\n const scopes = Object.values(ctx.scopes);\n for (const scope of scopes) Object.freeze(scope);\n return scopes.length > 0 ? { scopes: ctx.scopes } : undefined;\n}\n","/*\n * Debug logging for the SDK. The whole surface is gated on a single `debug`\n * boolean that threads through `fetchExperience` / `resolveExperience` and the\n * renderers (see `ExperienceContext.debug`). When `debug` is off, every call\n * here is a cheap no-op — nothing is logged, no strings are built (callers pass\n * thunks for anything expensive to serialize).\n *\n * This is intentionally console-based, not a pluggable logger. v1 goal is\n * \"turn it on, see what the SDK is doing\"; a customer-supplied sink can land\n * later without changing call sites (the `debug` boolean would widen to\n * `boolean | DebugSink`).\n */\n\n/** Prefix on every debug line so customers can filter their console. */\nconst PREFIX = '[experiences:debug]';\n\n/**\n * Monotonic-ish clock for span timings. Prefers `performance.now()` (present\n * in modern Node and every browser); falls back to `Date.now()`. Returns 0\n * when neither is available so timing degrades to \"no duration\" rather than\n * throwing.\n */\nfunction now(): number {\n if (typeof performance !== 'undefined' && typeof performance.now === 'function') {\n return performance.now();\n }\n if (typeof Date !== 'undefined' && typeof Date.now === 'function') return Date.now();\n return 0;\n}\n\n/**\n * A scoped debug logger. `scope` names the emitting subsystem (e.g. `core`,\n * `client`, `react`) so interleaved logs stay legible.\n */\nexport interface DebugLogger {\n /** Log a message with optional structured data. */\n log(message: string, data?: unknown): void;\n /**\n * Log a message whose payload is expensive to build. The thunk only runs\n * when debug is enabled — keep large payload serialization out of the hot\n * path when debug is off.\n */\n lazy(message: string, getData: () => unknown): void;\n /** Time an async span and log its duration when it settles. */\n time<T>(label: string, fn: () => Promise<T>): Promise<T>;\n /** True when this logger is actually emitting. */\n readonly enabled: boolean;\n}\n\nconst NOOP_LOGGER: DebugLogger = {\n log() {},\n lazy() {},\n time: (_label, fn) => fn(),\n enabled: false,\n};\n\n/**\n * Build a debug logger. Returns a shared no-op when `debug` is falsy so\n * callers can hold onto the result unconditionally and pay nothing when off.\n */\nexport function createDebugLogger(debug: boolean | undefined, scope: string): DebugLogger {\n if (!debug || typeof console === 'undefined') return NOOP_LOGGER;\n\n const tag = `${PREFIX}[${scope}]`;\n return {\n enabled: true,\n log(message, data) {\n if (data === undefined) console.log(`${tag} ${message}`);\n else console.log(`${tag} ${message}`, data);\n },\n lazy(message, getData) {\n console.log(`${tag} ${message}`, getData());\n },\n async time(label, fn) {\n const start = now();\n try {\n const result = await fn();\n console.log(`${tag} ⏱ ${label} — ${(now() - start).toFixed(1)}ms`);\n return result;\n } catch (err) {\n console.log(`${tag} ⏱ ${label} — failed after ${(now() - start).toFixed(1)}ms`, err);\n throw err;\n }\n },\n };\n}\n","/* Design-property and token resolution for the core render-plan builder. */\n\nimport type { DesignPropValue, DesignToken, ResolveToken } from './types.js';\n\n/**\n * Resolve every design property on a node into a record keyed by name.\n */\nexport function resolveDesignProperties(\n designProperties: Record<string, DesignPropValue> | undefined\n): Record<string, string | number | boolean | DesignToken> {\n const out: Record<string, string | number | boolean | DesignToken> = {};\n if (!designProperties) return out;\n for (const [key, prop] of Object.entries(designProperties)) {\n out[key] = prop.type === 'ManualDesignValue' ? prop.value : prop;\n }\n return out;\n}\n\n/**\n * Resolve `DesignToken` values via `resolveToken`; scalars pass through.\n * Keys that don't resolve — no `resolveToken` configured, or the resolver\n * returns `undefined` for that particular token — pass through as the raw\n * `DesignToken` and their id is collected in `unresolved` for the caller to\n * warn/diagnose (see `warnUnresolvedTokens` in `resolve-experience.ts`, which\n * already dedupes per `resolveExperience()` call, so this function carries\n * no warn-once state of its own).\n */\nexport function applyTokenResolver(\n props: Record<string, string | number | boolean | DesignToken>,\n resolveToken?: ResolveToken\n): { props: Record<string, unknown>; unresolved: string[] } {\n const out: Record<string, unknown> = {};\n const unresolved: string[] = [];\n for (const [key, value] of Object.entries(props)) {\n if (typeof value === 'object' && value !== null && value.type === 'DesignToken') {\n const resolved = resolveToken?.(value);\n if (resolved === undefined) {\n out[key] = value;\n unresolved.push(value.value);\n continue;\n }\n out[key] = resolved;\n continue;\n }\n out[key] = value;\n }\n return { props: out, unresolved };\n}\n","/*\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","/**\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"]}