@weaverse/react 5.8.3 → 5.8.5

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/dist/index.js CHANGED
@@ -392,45 +392,8 @@ var useChildInstances = (id) => {
392
392
  };
393
393
 
394
394
  // src/renderer.tsx
395
- var import_clsx2 = __toESM(require("clsx"));
396
- var import_react3 = __toESM(require("react"));
397
-
398
- // src/utils/css.ts
399
395
  var import_clsx = __toESM(require("clsx"));
400
- function formatCSS(css) {
401
- return {
402
- "@desktop": css["@desktop"],
403
- "@mobile": css["@mobile"]
404
- };
405
- }
406
- var permanentClasses = {};
407
- function generateItemClassName(instance, stitchesInstance) {
408
- let { css, type, className: cls = "" } = instance.data;
409
- let className = "";
410
- let permanentClass = "";
411
- let perCss = instance.Element?.permanentCss;
412
- if (perCss) {
413
- if (type in permanentClasses) {
414
- permanentClass = permanentClasses[type];
415
- } else {
416
- let { className: perCls } = stitchesInstance.css(perCss)();
417
- Object.assign(permanentClasses, { [type]: perCls });
418
- permanentClass = perCls;
419
- }
420
- }
421
- className = permanentClass;
422
- if (css) {
423
- let formattedCss = formatCSS(css);
424
- let newStitchesClass = stitchesInstance.css(formattedCss)().className || "";
425
- let { stitchesClass = "" } = instance;
426
- let otherClass = (instance.ref.current?.className || "").replace(stitchesClass, "").replace(cls, "").replace(permanentClass, "").trim();
427
- className = (0, import_clsx.default)(permanentClass, cls, newStitchesClass, otherClass);
428
- instance.stitchesClass = newStitchesClass;
429
- }
430
- return className;
431
- }
432
-
433
- // src/renderer.tsx
396
+ var import_react3 = __toESM(require("react"));
434
397
  var import_jsx_runtime = require("react/jsx-runtime");
435
398
  var import_react4 = require("react");
436
399
  var REACT_VERSION_THRESHOLD = 18;
@@ -465,12 +428,11 @@ var WeaverseRoot = (0, import_react3.memo)(({ context }) => {
465
428
  context.contentRootElement = rootRef.current;
466
429
  }, [context]);
467
430
  const eventHandlers = context?.studioBridge?.eventHandlers || {};
468
- const themeClass = context.stitchesInstance.theme.className;
469
431
  if (context.projectId) {
470
432
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
471
433
  "div",
472
434
  {
473
- className: `weaverse-content-root ${themeClass}`,
435
+ className: "weaverse-content-root",
474
436
  ...eventHandlers,
475
437
  "data-weaverse-project-id": context.projectId,
476
438
  "data-weaverse-template-id": data.id,
@@ -484,7 +446,7 @@ var WeaverseRoot = (0, import_react3.memo)(({ context }) => {
484
446
  WeaverseRoot.displayName = "WeaverseRoot";
485
447
  var ItemComponent = (0, import_react3.memo)(({ instance }) => {
486
448
  const context = useWeaverse();
487
- const { stitchesInstance, elementRegistry, platformType } = context;
449
+ const { elementRegistry } = context;
488
450
  const data = useSafeExternalStore(
489
451
  instance.subscribe,
490
452
  instance.getSnapShot,
@@ -522,7 +484,7 @@ var ItemComponent = (0, import_react3.memo)(({ instance }) => {
522
484
  if (Element?.Component) {
523
485
  const Component = Element.Component;
524
486
  Component.displayName = type;
525
- if (Component.$$typeof === Symbol.for("react.forward_ref") || reactVersion > REACT_VERSION_THRESHOLD) {
487
+ if (Component.$$typeof === /* @__PURE__ */ Symbol.for("react.forward_ref") || reactVersion > REACT_VERSION_THRESHOLD) {
526
488
  processedRest.ref = instance.ref;
527
489
  }
528
490
  const childItems = children?.length ? children : childIds?.length ? childIds.map((cid) => ({ id: cid })) : [];
@@ -534,10 +496,7 @@ var ItemComponent = (0, import_react3.memo)(({ instance }) => {
534
496
  {
535
497
  ...processedRest,
536
498
  children: renderChildren.length ? renderChildren : void 0,
537
- className: (0, import_clsx2.default)(
538
- platformType !== "shopify-hydrogen" && generateItemClassName(instance, stitchesInstance),
539
- processedRest.data?.className
540
- ),
499
+ className: (0, import_clsx.default)(processedRest.data?.className),
541
500
  "data-wv-id": id,
542
501
  "data-wv-type": type,
543
502
  key: id
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/context.ts","../src/hooks.ts","../src/utils/data-connector.ts","../src/renderer.tsx","../src/utils/css.ts"],"sourcesContent":["export * from '@weaverse/core'\nexport * from './context'\nexport * from './hooks'\nexport * from './renderer'\nexport * from './types'\n","import type { Weaverse } from '@weaverse/core'\nimport { createContext } from 'react'\n\nexport let WeaverseContext = createContext<Weaverse>({} as Weaverse)\nexport let WeaverseContextProvider = WeaverseContext.Provider\nexport let WeaverseItemContext = createContext<{\n id: string\n parentId: string\n}>({ id: '', parentId: '' })\n","import { Weaverse, type WeaverseItemStore } from '@weaverse/core'\nimport { useContext } from 'react'\nimport { WeaverseContext, WeaverseItemContext } from '~/context'\n\n// Re-export the data connector utilities\nexport {\n replaceContentDataConnectors,\n replaceContentDataConnectorsDeep,\n} from './utils/data-connector'\n\nexport function useWeaverse<T = Weaverse>() {\n let weaverse = useContext(WeaverseContext)\n return weaverse as T\n}\n\nexport let useItemInstance = (id?: string) => {\n let { id: currentId } = useContext(WeaverseItemContext)\n let instance = Weaverse.itemInstances.get(id || currentId)\n if (!instance) {\n console.log(`Item instance ${id} not found`)\n return null\n }\n return instance as WeaverseItemStore\n}\n\nexport let useParentInstance = () => {\n let { parentId } = useContext(WeaverseItemContext)\n return useItemInstance(parentId || '')\n}\n\nexport let useChildInstances = (id?: string) => {\n let currentInstance = useItemInstance(id)\n if (!currentInstance) {\n return []\n }\n let { itemInstances } = Weaverse\n\n let {\n data: { children },\n } = currentInstance\n return children\n .map(({ id }: { id: string }) => itemInstances.get(id))\n .filter(Boolean) as WeaverseItemStore[]\n}\n","// Data connector utilities for replacing placeholders with real data\n// Generic data context type for flexible usage\nexport type DataContext = Record<string, unknown>\n\n// Cached regex pattern for better performance\nconst TEMPLATE_REGEX = /\\{\\{([^}]+)\\}\\}/g\nconst ARRAY_INDEX_REGEX = /^(\\w+)\\[(\\d+)\\]$/\n\n// Cache eviction ratio - remove oldest 25% when cache is full\nconst CACHE_EVICTION_RATIO = 0.25\n\n/**\n * Validates that a property name is safe to access (prevents prototype pollution)\n * Enhanced to handle route-specific patterns with special characters\n */\nfunction isSafePropertyName(key: string): boolean {\n // Block dangerous prototype pollution patterns\n const dangerousPatterns = ['__proto__', 'constructor', 'prototype']\n return !dangerousPatterns.includes(key)\n}\n\n/**\n * Parses a template path into route key and property path components\n * Handles complex routes like: routes/($locale).blogs.$blogHandle.$articleHandle\n * Enhanced with caching for improved performance\n *\n * @param path - The full path from template (e.g., \"routes/($locale)._index.weaverseData.page.name\")\n * @param dataContext - Available route data context\n * @returns Object with routeKey and propertyPath\n */\nfunction parseRouteAndProperty(\n path: string,\n dataContext: DataContext\n): {\n routeKey: string | null\n propertyPath: string\n} {\n if (!dataContext || typeof path !== 'string') {\n return { routeKey: null, propertyPath: path }\n }\n\n const trimmedPath = path.trim()\n\n // Create a cache key using stable hash instead of serializing route keys\n const dataHash = getDataContextHash(dataContext)\n const cacheKey = `${trimmedPath}::${dataHash}`\n\n // Check cache first\n const cachedResult = routeParsingCache.get(cacheKey)\n if (cachedResult) {\n // Update timestamp on cache hit\n cachedResult.timestamp = Date.now()\n return {\n routeKey: cachedResult.routeKey,\n propertyPath: cachedResult.propertyPath,\n }\n }\n\n // Get all available routes and sort by length (longest first for specificity)\n const availableRoutes = Object.keys(dataContext).sort(\n (a, b) => b.length - a.length\n )\n\n let result: { routeKey: string | null; propertyPath: string } = {\n routeKey: null,\n propertyPath: trimmedPath,\n }\n\n // Try to find the longest matching route key\n let found = false\n for (const routeKey of availableRoutes) {\n // Exact match\n if (trimmedPath === routeKey) {\n result = { routeKey, propertyPath: '' }\n found = true\n break\n }\n\n // Route key with property path\n if (trimmedPath.startsWith(`${routeKey}.`)) {\n const propertyPath = trimmedPath.substring(routeKey.length + 1)\n result = { routeKey, propertyPath }\n found = true\n break\n }\n }\n\n if (!found) {\n // No route key found, treat entire path as property path\n result = { routeKey: null, propertyPath: trimmedPath }\n }\n\n // Cache the result\n if (routeParsingCache.size >= ROUTE_PARSING_CACHE_MAX_SIZE) {\n // Clean cache by removing oldest entries\n const entries = Array.from(routeParsingCache.entries())\n entries.sort((a, b) => a[1].timestamp - b[1].timestamp)\n const toRemove = Math.floor(entries.length * CACHE_EVICTION_RATIO)\n for (let i = 0; i < toRemove; i++) {\n routeParsingCache.delete(entries[i][0])\n }\n }\n\n routeParsingCache.set(cacheKey, {\n routeKey: result.routeKey,\n propertyPath: result.propertyPath,\n timestamp: Date.now(),\n })\n\n return result\n}\n\n// Simple cache for parsed templates (max 100 entries)\nconst templateCache = new Map<string, string>()\nconst MAX_CACHE_SIZE = 100\n\n// Cache for fallback lookups to improve performance (moved to module level to prevent memory leaks)\nconst fallbackCache = new Map<\n string,\n { routeKey: string; value: unknown; timestamp: number }\n>()\nconst FALLBACK_CACHE_MAX_SIZE = 50\n\n// Route parsing cache for performance optimization\nconst routeParsingCache = new Map<\n string,\n { routeKey: string | null; propertyPath: string; timestamp: number }\n>()\nconst ROUTE_PARSING_CACHE_MAX_SIZE = 100\n\n// WeakMap for stable dataContext hashing - prevents repeated JSON.stringify\nconst dataContextHashCache = new WeakMap<object, string>()\nlet hashCounter = 0\n\n/**\n * Safely gets a nested value from an object using dot notation path\n * Supports array indexing with [index] syntax\n * @param obj - The object to traverse\n * @param path - Dot notation path (e.g., \"user.name\" or \"items[0].title\")\n * @param visited - Set to track visited objects for circular reference protection\n * @returns The resolved value or undefined if not found\n */\nfunction getNestedValue(\n obj: unknown,\n path: string,\n visited = new WeakSet()\n): unknown {\n return path.split('.').reduce((current, key) => {\n if (!current || typeof current !== 'object') {\n return\n }\n\n // Protect against circular references\n if (visited.has(current as WeakKey)) {\n console.warn('Circular reference detected in data connector path:', path)\n return\n }\n\n // Add to circular reference tracking\n visited.add(current as WeakKey)\n\n // Handle array indexing like items[0] or items[1]\n const arrayMatch = key.match(ARRAY_INDEX_REGEX)\n if (arrayMatch) {\n const [, arrayKey, index] = arrayMatch\n const arrayObj = (current as Record<string, unknown>)[arrayKey]\n if (Array.isArray(arrayObj)) {\n const indexNum = Number.parseInt(index, 10)\n if (indexNum >= 0 && indexNum < arrayObj.length) {\n return arrayObj[indexNum]\n }\n }\n return\n }\n\n // Handle regular object property access with security validation\n if (!isSafePropertyName(key)) {\n console.warn(`Unsafe property access attempted: ${key}`)\n return\n }\n\n return current !== null && key in current\n ? (current as Record<string, unknown>)[key]\n : undefined\n }, obj)\n}\n\n/**\n * Sanitizes a string value to prevent XSS attacks\n * @param value - The value to sanitize\n * @returns Sanitized string safe for HTML rendering\n */\nfunction sanitizeValue(value: unknown): string {\n if (value === null || value === undefined) {\n return ''\n }\n\n const stringValue = String(value)\n\n // Basic HTML entity encoding to prevent XSS\n return stringValue\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#x27;')\n .replace(/\\//g, '&#x2F;')\n}\n\n/**\n * Creates a stable hash for dataContext object\n * Uses WeakMap to cache hash per object reference (no serialization needed)\n */\nfunction getDataContextHash(data: Record<string, unknown>): string {\n if (!dataContextHashCache.has(data)) {\n // Generate unique hash for this dataContext instance\n dataContextHashCache.set(data, `ctx_${++hashCounter}`)\n }\n const hash = dataContextHashCache.get(data)\n return hash || `ctx_${++hashCounter}`\n}\n\n/**\n * Creates a safe cache key from content and data\n * Uses stable hashing instead of JSON.stringify for massive performance gain\n */\nfunction createCacheKey(\n content: string,\n data: Record<string, unknown>\n): string {\n // Use stable hash instead of expensive JSON.stringify\n const dataHash = getDataContextHash(data)\n return `${content}:${dataHash}`\n}\n\n/**\n * Resolves data from the flat route-keyed data context\n * Enhanced to support complex route patterns with special characters\n * Supports: {{root.layout.shop.name}}, {{routes/($locale)._index.data}}, {{routes/($locale).blogs.$handle.$article.content}}\n */\nfunction resolveDataFromContext(\n path: string,\n dataContext: DataContext | null | undefined\n): unknown {\n if (!dataContext) {\n return\n }\n\n const trimmedPath = path.trim()\n\n // Use intelligent route parsing to separate route key from property path\n const { routeKey, propertyPath } = parseRouteAndProperty(\n trimmedPath,\n dataContext\n )\n\n // If we found a specific route key, resolve from that route's data\n if (routeKey && dataContext[routeKey]) {\n const routeData = dataContext[routeKey]\n if (typeof routeData === 'object' && routeData !== null) {\n if (propertyPath) {\n return getNestedValue(routeData, propertyPath)\n }\n return routeData\n }\n }\n\n // Fallback: search across all route data for backward compatibility\n // This handles cases like {{shop.name}} without route prefix\n\n // Check cache first\n const cachedResult = fallbackCache.get(trimmedPath)\n if (cachedResult && dataContext[cachedResult.routeKey]) {\n const value = getNestedValue(\n dataContext[cachedResult.routeKey],\n trimmedPath\n )\n if (value !== undefined) {\n // Update timestamp on cache hit\n cachedResult.timestamp = Date.now()\n return value\n }\n }\n\n // Search with priority order (most common routes first)\n const priorityRoutes = ['root', 'routes/product', 'routes/collection']\n const allRoutes = [\n ...priorityRoutes,\n ...Object.keys(dataContext).filter((k) => !priorityRoutes.includes(k)),\n ]\n\n for (const routeKey of allRoutes) {\n const routeData = dataContext[routeKey]\n if (routeData && typeof routeData === 'object' && routeData !== null) {\n const value = getNestedValue(routeData, trimmedPath)\n if (value !== undefined) {\n // Clean cache if it's getting too large\n if (fallbackCache.size >= FALLBACK_CACHE_MAX_SIZE) {\n const entries = Array.from(fallbackCache.entries())\n entries.sort((a, b) => a[1].timestamp - b[1].timestamp)\n // Remove oldest 25% of entries\n const toRemove = Math.floor(entries.length * CACHE_EVICTION_RATIO)\n for (let i = 0; i < toRemove; i++) {\n fallbackCache.delete(entries[i][0])\n }\n }\n fallbackCache.set(trimmedPath, {\n routeKey,\n value,\n timestamp: Date.now(),\n })\n return value\n }\n }\n }\n\n // Final fallback: try direct access (for non-route-keyed legacy data)\n return getNestedValue(dataContext, trimmedPath)\n}\n\n/**\n * Replaces data connector placeholders in content with actual values from data context\n * Supports {{path}} syntax with dot notation, array indexing, and route prefixes\n *\n * Enhanced syntax:\n * - {{root.siteSettings.title}} - Access root route data\n * - {{layout.navigation.items}} - Access layout route data\n * - {{parent.category.name}} - Access parent route data\n * - {{current.product.title}} - Access current route data\n * - {{user.name}} - Auto-resolved from combined data (backward compatible)\n *\n * @param content - The content string containing {{}} placeholders\n * @param dataContext - The enhanced WeaverseDataContext with route-keyed data\n * @returns The content with placeholders replaced by actual values\n */\nexport function replaceContentDataConnectors(\n content: string,\n dataContext: DataContext | null | undefined\n): string {\n if (!dataContext || typeof content !== 'string') {\n return content\n }\n\n try {\n // Simplified caching - dataContext is already the combined data\n const cacheKey = createCacheKey(content, dataContext)\n\n const cachedContent = templateCache.get(cacheKey)\n if (cachedContent) {\n return cachedContent\n }\n\n const newContent = content.replace(TEMPLATE_REGEX, (match, path) => {\n try {\n const value = resolveDataFromContext(path, dataContext)\n\n if (value === undefined || value === null) {\n return match // Return original placeholder if value not found\n }\n\n return sanitizeValue(value)\n } catch (pathError) {\n console.warn(\n `Error resolving data connector path \"${path}\":`,\n pathError\n )\n return match\n }\n })\n\n // Cache the result (with size limit)\n if (templateCache.size >= MAX_CACHE_SIZE) {\n const firstKey = templateCache.keys().next().value\n templateCache.delete(firstKey)\n }\n templateCache.set(cacheKey, newContent)\n\n return newContent\n } catch (error) {\n console.warn('Error processing data connectors:', error, { content })\n return content\n }\n}\n\n/**\n * Fast check if data contains any {{...}} placeholders\n * Returns true if any string value contains the pattern\n * This is MUCH faster than processing and allows early exit\n *\n * IMPORTANT: Uses global TEMPLATE_REGEX, must reset lastIndex\n */\nfunction hasPlaceholders(data: unknown, visited = new WeakSet()): boolean {\n if (typeof data === 'string') {\n // Reset regex state before testing to ensure consistent results\n TEMPLATE_REGEX.lastIndex = 0\n return TEMPLATE_REGEX.test(data)\n }\n\n if (typeof data !== 'object' || data === null) {\n return false\n }\n\n // Skip Date objects - they can't contain placeholders\n if (data instanceof Date) {\n return false\n }\n\n // Protect against circular references\n if (visited.has(data as WeakKey)) {\n return false\n }\n visited.add(data as WeakKey)\n\n try {\n if (Array.isArray(data)) {\n return data.some((item) => hasPlaceholders(item, visited))\n }\n\n // Check object values safely (skip property access errors)\n for (const key of Object.keys(data)) {\n try {\n const value = (data as Record<string, unknown>)[key]\n if (hasPlaceholders(value, visited)) {\n return true\n }\n } catch {\n // Ignore property access errors - continue checking other properties\n }\n }\n\n return false\n } finally {\n visited.delete(data as WeakKey)\n }\n}\n\n/**\n * Recursively replaces data connector placeholders in any data structure\n * IMMUTABLE: Creates deep copies during processing to avoid mutating original data\n * Handles strings, objects, arrays, and nested combinations\n *\n * PERFORMANCE: Now includes early exit if no placeholders detected\n *\n * @param data - The data to process (string, object, array, or primitive)\n * @param dataContext - The data context for replacements\n * @param visited - Set to track visited objects for circular reference protection\n * @param forceClone - Internal flag to force cloning even if no placeholders (for parent immutability)\n * @returns IMMUTABLE copy of the data with all string placeholders replaced\n */\nexport function replaceContentDataConnectorsDeep<T>(\n data: T,\n dataContext: DataContext | null | undefined,\n visited = new WeakSet(),\n forceClone = false\n): T {\n if (!dataContext) {\n return data\n }\n\n const dataHasPlaceholders = hasPlaceholders(data, new WeakSet())\n\n // PERFORMANCE: Fast check - if no placeholders exist and not forced to clone, skip ALL processing\n // This saves 90%+ of CPU time for components without data connectors\n if (!(dataHasPlaceholders || forceClone)) {\n return data\n }\n\n // Handle primitive types - no cloning needed for primitives\n if (typeof data === 'string') {\n return replaceContentDataConnectors(data, dataContext) as T\n }\n\n if (typeof data !== 'object' || data === null) {\n return data\n }\n\n // Protect against circular references\n if (visited.has(data as WeakKey)) {\n console.warn(\n 'Circular reference detected in deep data connector replacement'\n )\n return data\n }\n\n // Add to circular reference tracking\n visited.add(data as WeakKey)\n\n try {\n // Handle special objects that should be cloned as-is\n if (data instanceof Date) {\n // Date objects can't contain placeholders, but clone if forced (parent has placeholders)\n // or if somehow detected (shouldn't happen but be safe)\n if (forceClone || dataHasPlaceholders) {\n return new Date(data.getTime()) as T\n }\n return data\n }\n\n // Handle arrays - create new array with processed items\n // Force clone children if parent has placeholders (for immutability)\n if (Array.isArray(data)) {\n const result = data.map((item) =>\n replaceContentDataConnectorsDeep(\n item,\n dataContext,\n visited,\n dataHasPlaceholders\n )\n ) as T\n return result\n }\n\n // Handle plain objects - create new object with processed values\n // Force clone children if parent has placeholders (for immutability)\n const result = {} as T\n\n // Use Object.entries with try-catch per property to handle getter errors\n for (const key of Object.keys(data)) {\n try {\n const value = (data as Record<string, unknown>)[key]\n ;(result as Record<string, unknown>)[key] =\n replaceContentDataConnectorsDeep(\n value,\n dataContext,\n visited,\n dataHasPlaceholders\n )\n } catch (propertyError) {\n // If property access throws, skip it but continue processing\n console.warn(`Error accessing property \"${key}\":`, propertyError)\n // Don't include this property in result\n }\n }\n\n return result\n } catch (error) {\n console.warn('Error in deep data connector replacement:', error)\n return data\n } finally {\n // Remove from tracking when done processing this object\n visited.delete(data as WeakKey)\n }\n}\n","import type { Weaverse } from '@weaverse/core'\nimport clsx from 'clsx'\nimport React, { memo, useEffect, useRef } from 'react'\nimport { useItemInstance, useWeaverse } from '~/hooks'\nimport { WeaverseContextProvider, WeaverseItemContext } from './context'\nimport type { ItemComponentProps, WeaverseRootPropsType } from './types'\nimport { generateItemClassName } from './utils/css'\nimport { replaceContentDataConnectorsDeep } from './utils/data-connector'\n\nconst REACT_VERSION_THRESHOLD = 18\nconst reactVersion = Number(React.version?.split('.')[0]) || 0\n\n// Create a safe version of useSyncExternalStore that works in both client and server environments\nexport const useSafeExternalStore = (\n subscribe: any,\n getSnapshot: any,\n getServerSnapshot: any = getSnapshot\n) => {\n // In server environment or during SSR, just return the snapshot directly\n if (typeof window === 'undefined') {\n return getServerSnapshot()\n }\n\n // In client environment, use React.useSyncExternalStore if available (React 18+)\n if (React.useSyncExternalStore) {\n // biome-ignore lint/correctness/useHookAtTopLevel: <$>\n return React.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)\n }\n\n // Fallback for older React versions - just return the current snapshot\n return getSnapshot()\n}\n\n/**\n * Determines the root element ID for the Weaverse component tree.\n * Falls back through multiple strategies to ensure a valid root is always found:\n * 1. Use explicit rootId from context.data if available\n * 2. Find the first element with type 'main' in items array\n * 3. Use projectId as final fallback\n */\nconst getRootId = (context: Weaverse): string => {\n // Strategy 1: Explicit rootId\n if (context.data.rootId) {\n return context.data.rootId\n }\n\n // Strategy 2: Find main element\n let mainItem = context.data?.items?.find((item) => item.type === 'main')\n if (mainItem?.id) {\n return mainItem.id\n }\n\n // Strategy 3: Fallback to projectId\n return context.projectId\n}\nexport const WeaverseRoot = memo(({ context }: WeaverseRootPropsType) => {\n const data = useSafeExternalStore(\n context.subscribe,\n context.getSnapShot,\n context.getSnapShot\n )\n const rootRef = useRef<HTMLElement>(null)\n\n useEffect(() => {\n context.contentRootElement = rootRef.current\n }, [context])\n\n const eventHandlers = context?.studioBridge?.eventHandlers || {}\n const themeClass = context.stitchesInstance.theme.className\n\n if (context.projectId) {\n return (\n <div\n className={`weaverse-content-root ${themeClass}`}\n {...eventHandlers}\n data-weaverse-project-id={context.projectId}\n data-weaverse-template-id={data.id}\n ref={rootRef}\n >\n <WeaverseContextProvider value={context}>\n <ItemInstance id={getRootId(context)} parentId={''} />\n </WeaverseContextProvider>\n </div>\n )\n }\n return null\n})\nWeaverseRoot.displayName = 'WeaverseRoot'\nconst ItemComponent = memo(({ instance }: ItemComponentProps) => {\n const context = useWeaverse()\n const { stitchesInstance, elementRegistry, platformType } = context\n const data = useSafeExternalStore(\n instance.subscribe,\n instance.getSnapShot,\n instance.getSnapShot\n )\n const {\n id,\n type,\n childIds = [],\n children = [],\n\n createdAt,\n updatedAt,\n deletedAt,\n css,\n __hidden,\n // Need to get rid of this `data` property\n data: _,\n ...rest\n } = data\n\n // Replace data connectors in all component data (handles strings, objects, and arrays recursively)\n // IMMUTABLE: Process the entire rest object to avoid mutating original content\n const processedRest = replaceContentDataConnectorsDeep(\n rest,\n context.dataContext\n )\n\n useEffect(() => {\n if (!instance.ref.current) {\n // Fallback `ref` if the element isn't created by `React.forwardRef`\n Object.assign(instance.ref, {\n current: document.querySelector(`[data-wv-id=\"${id}\"]`),\n })\n }\n }, [instance, id])\n\n if (__hidden) {\n return null\n }\n\n const Element = elementRegistry.get(type)\n\n if (Element?.Component) {\n const Component = Element.Component\n Component.displayName = type\n if (\n Component.$$typeof === Symbol.for('react.forward_ref') ||\n reactVersion > REACT_VERSION_THRESHOLD\n ) {\n processedRest.ref = instance.ref\n }\n const childItems = children?.length\n ? children\n : childIds?.length\n ? childIds.map((cid: string) => ({ id: cid }))\n : []\n\n const renderChildren = childItems.map(\n (item: { id: string }, index: number) => (\n <ItemInstance id={item.id} key={`${item.id}-${index}`} parentId={id} />\n )\n )\n\n return (\n <Component\n {...processedRest}\n children={renderChildren.length ? renderChildren : undefined}\n className={clsx(\n platformType !== 'shopify-hydrogen' &&\n generateItemClassName(instance, stitchesInstance),\n processedRest.data?.className\n )}\n data-wv-id={id}\n data-wv-type={type}\n key={id}\n />\n )\n }\n instance._store.deleted = true\n return null\n})\nItemComponent.displayName = 'WeaverseComponent'\n\nconst ItemInstance = memo(\n ({ id, parentId }: { id: string; parentId: string }) => {\n const instance = useItemInstance(id)\n if (!instance) {\n return <div style={{ display: 'none' }}>Item instance {id} not found</div>\n }\n return (\n <WeaverseItemContext.Provider value={{ parentId, id }}>\n <ItemComponent instance={instance} key={id} />\n </WeaverseItemContext.Provider>\n )\n }\n)\nItemInstance.displayName = 'WeaverseInstanceProvider'\n","import type Stitches from '@stitches/react/types/stitches'\nimport type { ElementCSS, WeaverseItemStore } from '@weaverse/core'\nimport clsx from 'clsx'\n\n// Make the css data formatted to correct order (desktop, tablet, mobile)\nfunction formatCSS(css: ElementCSS) {\n return {\n '@desktop': css['@desktop'],\n '@mobile': css['@mobile'],\n }\n}\n\nlet permanentClasses: Record<string, string> = {}\nexport function generateItemClassName(\n instance: WeaverseItemStore,\n stitchesInstance: Stitches\n) {\n let { css, type, className: cls = '' } = instance.data\n let className = ''\n let permanentClass = ''\n let perCss = instance.Element?.permanentCss\n if (perCss) {\n if (type in permanentClasses) {\n permanentClass = permanentClasses[type]\n } else {\n // @ts-expect-error\n let { className: perCls } = stitchesInstance.css(perCss)()\n Object.assign(permanentClasses, { [type]: perCls })\n permanentClass = perCls\n }\n }\n className = permanentClass\n if (css) {\n // let stitches create the style from css object and\n // then return the classname, so we can use it in the render\n let formattedCss = formatCSS(css)\n let newStitchesClass = stitchesInstance.css(formattedCss)().className || ''\n let { stitchesClass = '' } = instance\n let otherClass = (instance.ref.current?.className || '')\n .replace(stitchesClass, '')\n .replace(cls, '')\n .replace(permanentClass, '')\n .trim()\n className = clsx(permanentClass, cls, newStitchesClass, otherClass)\n instance.stitchesClass = newStitchesClass\n }\n return className\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,0BAAc,2BAAd;;;ACCA,mBAA8B;AAEvB,IAAI,sBAAkB,4BAAwB,CAAC,CAAa;AAC5D,IAAI,0BAA0B,gBAAgB;AAC9C,IAAI,0BAAsB,4BAG9B,EAAE,IAAI,IAAI,UAAU,GAAG,CAAC;;;ACR3B,kBAAiD;AACjD,IAAAA,gBAA2B;;;ACI3B,IAAM,iBAAiB;AACvB,IAAM,oBAAoB;AAG1B,IAAM,uBAAuB;AAM7B,SAAS,mBAAmB,KAAsB;AAEhD,QAAM,oBAAoB,CAAC,aAAa,eAAe,WAAW;AAClE,SAAO,CAAC,kBAAkB,SAAS,GAAG;AACxC;AAWA,SAAS,sBACP,MACA,aAIA;AACA,MAAI,CAAC,eAAe,OAAO,SAAS,UAAU;AAC5C,WAAO,EAAE,UAAU,MAAM,cAAc,KAAK;AAAA,EAC9C;AAEA,QAAM,cAAc,KAAK,KAAK;AAG9B,QAAM,WAAW,mBAAmB,WAAW;AAC/C,QAAM,WAAW,GAAG,WAAW,KAAK,QAAQ;AAG5C,QAAM,eAAe,kBAAkB,IAAI,QAAQ;AACnD,MAAI,cAAc;AAEhB,iBAAa,YAAY,KAAK,IAAI;AAClC,WAAO;AAAA,MACL,UAAU,aAAa;AAAA,MACvB,cAAc,aAAa;AAAA,IAC7B;AAAA,EACF;A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AsB,UACrB,4CAAC,gBAAa,IAAI,KAAK,IAAgC,UAAU,MAAjC,GAAG,KAAK,EAAE,IAAI,KAAK,EAAkB;AAAA,IAEzE;AAEA,WACE;AAAA,MAAC;AAAA;AAAA,QACE,GAAG;AAAA,QACJ,UAAU,eAAe,SAAS,iBAAiB;AAAA,QACnD,eAAW,aAAAC;AAAA,UACT,iBAAiB,sBACf,sBAAsB,UAAU,gBAAgB;AAAA,UAClD,cAAc,MAAM;AAAA,QACtB;AAAA,QACA,cAAY;AAAA,QACZ,gBAAc;AAAA,QACd,KAAK;AAAA;AAAA,IACP;AAAA,EAEJ;AACA,WAAS,OAAO,UAAU;AAC1B,SAAO;AACT,CAAC;AACD,cAAc,cAAc;AAE5B,IAAM,mBAAe;AAAA,EACnB,CAAC,EAAE,IAAI,SAAS,MAAwC;AACtD,UAAM,WAAW,gBAAgB,EAAE;AACnC,QAAI,CAAC,UAAU;AACb,aAAO,6CAAC,SAAI,OAAO,EAAE,SAAS,OAAO,GAAG;AAAA;AAAA,QAAe;AAAA,QAAG;AAAA,SAAU;AAAA,IACtE;AACA,WACE,4CAAC,oBAAoB,UAApB,EAA6B,OAAO,EAAE,UAAU,GAAG,GAClD,sDAAC,iBAAc,YAAyB,EAAI,GAC9C;AAAA,EAEJ;AACF;AACA,aAAa,cAAc;","names":["import_react","routeKey","result","id","import_clsx","import_react","clsx","import_react","React","clsx"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/context.ts","../src/hooks.ts","../src/utils/data-connector.ts","../src/renderer.tsx"],"sourcesContent":["export * from '@weaverse/core'\nexport * from './context'\nexport * from './hooks'\nexport * from './renderer'\nexport * from './types'\n","import type { Weaverse } from '@weaverse/core'\nimport { createContext } from 'react'\n\nexport let WeaverseContext = createContext<Weaverse>({} as Weaverse)\nexport let WeaverseContextProvider = WeaverseContext.Provider\nexport let WeaverseItemContext = createContext<{\n id: string\n parentId: string\n}>({ id: '', parentId: '' })\n","import { Weaverse, type WeaverseItemStore } from '@weaverse/core'\nimport { useContext } from 'react'\nimport { WeaverseContext, WeaverseItemContext } from '~/context'\n\n// Re-export the data connector utilities\nexport {\n replaceContentDataConnectors,\n replaceContentDataConnectorsDeep,\n} from './utils/data-connector'\n\nexport function useWeaverse<T = Weaverse>() {\n let weaverse = useContext(WeaverseContext)\n return weaverse as T\n}\n\nexport let useItemInstance = (id?: string) => {\n let { id: currentId } = useContext(WeaverseItemContext)\n let instance = Weaverse.itemInstances.get(id || currentId)\n if (!instance) {\n console.log(`Item instance ${id} not found`)\n return null\n }\n return instance as WeaverseItemStore\n}\n\nexport let useParentInstance = () => {\n let { parentId } = useContext(WeaverseItemContext)\n return useItemInstance(parentId || '')\n}\n\nexport let useChildInstances = (id?: string) => {\n let currentInstance = useItemInstance(id)\n if (!currentInstance) {\n return []\n }\n let { itemInstances } = Weaverse\n\n let {\n data: { children },\n } = currentInstance\n return children\n .map(({ id }: { id: string }) => itemInstances.get(id))\n .filter(Boolean) as WeaverseItemStore[]\n}\n","// Data connector utilities for replacing placeholders with real data\n// Generic data context type for flexible usage\nexport type DataContext = Record<string, unknown>\n\n// Cached regex pattern for better performance\nconst TEMPLATE_REGEX = /\\{\\{([^}]+)\\}\\}/g\nconst ARRAY_INDEX_REGEX = /^(\\w+)\\[(\\d+)\\]$/\n\n// Cache eviction ratio - remove oldest 25% when cache is full\nconst CACHE_EVICTION_RATIO = 0.25\n\n/**\n * Validates that a property name is safe to access (prevents prototype pollution)\n * Enhanced to handle route-specific patterns with special characters\n */\nfunction isSafePropertyName(key: string): boolean {\n // Block dangerous prototype pollution patterns\n const dangerousPatterns = ['__proto__', 'constructor', 'prototype']\n return !dangerousPatterns.includes(key)\n}\n\n/**\n * Parses a template path into route key and property path components\n * Handles complex routes like: routes/($locale).blogs.$blogHandle.$articleHandle\n * Enhanced with caching for improved performance\n *\n * @param path - The full path from template (e.g., \"routes/($locale)._index.weaverseData.page.name\")\n * @param dataContext - Available route data context\n * @returns Object with routeKey and propertyPath\n */\nfunction parseRouteAndProperty(\n path: string,\n dataContext: DataContext\n): {\n routeKey: string | null\n propertyPath: string\n} {\n if (!dataContext || typeof path !== 'string') {\n return { routeKey: null, propertyPath: path }\n }\n\n const trimmedPath = path.trim()\n\n // Create a cache key using stable hash instead of serializing route keys\n const dataHash = getDataContextHash(dataContext)\n const cacheKey = `${trimmedPath}::${dataHash}`\n\n // Check cache first\n const cachedResult = routeParsingCache.get(cacheKey)\n if (cachedResult) {\n // Update timestamp on cache hit\n cachedResult.timestamp = Date.now()\n return {\n routeKey: cachedResult.routeKey,\n propertyPath: cachedResult.propertyPath,\n }\n }\n\n // Get all available routes and sort by length (longest first for specificity)\n const availableRoutes = Object.keys(dataContext).sort(\n (a, b) => b.length - a.length\n )\n\n let result: { routeKey: string | null; propertyPath: string } = {\n routeKey: null,\n propertyPath: trimmedPath,\n }\n\n // Try to find the longest matching route key\n let found = false\n for (const routeKey of availableRoutes) {\n // Exact match\n if (trimmedPath === routeKey) {\n result = { routeKey, propertyPath: '' }\n found = true\n break\n }\n\n // Route key with property path\n if (trimmedPath.startsWith(`${routeKey}.`)) {\n const propertyPath = trimmedPath.substring(routeKey.length + 1)\n result = { routeKey, propertyPath }\n found = true\n break\n }\n }\n\n if (!found) {\n // No route key found, treat entire path as property path\n result = { routeKey: null, propertyPath: trimmedPath }\n }\n\n // Cache the result\n if (routeParsingCache.size >= ROUTE_PARSING_CACHE_MAX_SIZE) {\n // Clean cache by removing oldest entries\n const entries = Array.from(routeParsingCache.entries())\n entries.sort((a, b) => a[1].timestamp - b[1].timestamp)\n const toRemove = Math.floor(entries.length * CACHE_EVICTION_RATIO)\n for (let i = 0; i < toRemove; i++) {\n routeParsingCache.delete(entries[i][0])\n }\n }\n\n routeParsingCache.set(cacheKey, {\n routeKey: result.routeKey,\n propertyPath: result.propertyPath,\n timestamp: Date.now(),\n })\n\n return result\n}\n\n// Simple cache for parsed templates (max 100 entries)\nconst templateCache = new Map<string, string>()\nconst MAX_CACHE_SIZE = 100\n\n// Cache for fallback lookups to improve performance (moved to module level to prevent memory leaks)\nconst fallbackCache = new Map<\n string,\n { routeKey: string; value: unknown; timestamp: number }\n>()\nconst FALLBACK_CACHE_MAX_SIZE = 50\n\n// Route parsing cache for performance optimization\nconst routeParsingCache = new Map<\n string,\n { routeKey: string | null; propertyPath: string; timestamp: number }\n>()\nconst ROUTE_PARSING_CACHE_MAX_SIZE = 100\n\n// WeakMap for stable dataContext hashing - prevents repeated JSON.stringify\nconst dataContextHashCache = new WeakMap<object, string>()\nlet hashCounter = 0\n\n/**\n * Safely gets a nested value from an object using dot notation path\n * Supports array indexing with [index] syntax\n * @param obj - The object to traverse\n * @param path - Dot notation path (e.g., \"user.name\" or \"items[0].title\")\n * @param visited - Set to track visited objects for circular reference protection\n * @returns The resolved value or undefined if not found\n */\nfunction getNestedValue(\n obj: unknown,\n path: string,\n visited = new WeakSet()\n): unknown {\n return path.split('.').reduce((current, key) => {\n if (!current || typeof current !== 'object') {\n return\n }\n\n // Protect against circular references\n if (visited.has(current as WeakKey)) {\n console.warn('Circular reference detected in data connector path:', path)\n return\n }\n\n // Add to circular reference tracking\n visited.add(current as WeakKey)\n\n // Handle array indexing like items[0] or items[1]\n const arrayMatch = key.match(ARRAY_INDEX_REGEX)\n if (arrayMatch) {\n const [, arrayKey, index] = arrayMatch\n const arrayObj = (current as Record<string, unknown>)[arrayKey]\n if (Array.isArray(arrayObj)) {\n const indexNum = Number.parseInt(index, 10)\n if (indexNum >= 0 && indexNum < arrayObj.length) {\n return arrayObj[indexNum]\n }\n }\n return\n }\n\n // Handle regular object property access with security validation\n if (!isSafePropertyName(key)) {\n console.warn(`Unsafe property access attempted: ${key}`)\n return\n }\n\n return current !== null && key in current\n ? (current as Record<string, unknown>)[key]\n : undefined\n }, obj)\n}\n\n/**\n * Sanitizes a string value to prevent XSS attacks\n * @param value - The value to sanitize\n * @returns Sanitized string safe for HTML rendering\n */\nfunction sanitizeValue(value: unknown): string {\n if (value === null || value === undefined) {\n return ''\n }\n\n const stringValue = String(value)\n\n // Basic HTML entity encoding to prevent XSS\n return stringValue\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#x27;')\n .replace(/\\//g, '&#x2F;')\n}\n\n/**\n * Creates a stable hash for dataContext object\n * Uses WeakMap to cache hash per object reference (no serialization needed)\n */\nfunction getDataContextHash(data: Record<string, unknown>): string {\n if (!dataContextHashCache.has(data)) {\n // Generate unique hash for this dataContext instance\n dataContextHashCache.set(data, `ctx_${++hashCounter}`)\n }\n const hash = dataContextHashCache.get(data)\n return hash || `ctx_${++hashCounter}`\n}\n\n/**\n * Creates a safe cache key from content and data\n * Uses stable hashing instead of JSON.stringify for massive performance gain\n */\nfunction createCacheKey(\n content: string,\n data: Record<string, unknown>\n): string {\n // Use stable hash instead of expensive JSON.stringify\n const dataHash = getDataContextHash(data)\n return `${content}:${dataHash}`\n}\n\n/**\n * Resolves data from the flat route-keyed data context\n * Enhanced to support complex route patterns with special characters\n * Supports: {{root.layout.shop.name}}, {{routes/($locale)._index.data}}, {{routes/($locale).blogs.$handle.$article.content}}\n */\nfunction resolveDataFromContext(\n path: string,\n dataContext: DataContext | null | undefined\n): unknown {\n if (!dataContext) {\n return\n }\n\n const trimmedPath = path.trim()\n\n // Use intelligent route parsing to separate route key from property path\n const { routeKey, propertyPath } = parseRouteAndProperty(\n trimmedPath,\n dataContext\n )\n\n // If we found a specific route key, resolve from that route's data\n if (routeKey && dataContext[routeKey]) {\n const routeData = dataContext[routeKey]\n if (typeof routeData === 'object' && routeData !== null) {\n if (propertyPath) {\n return getNestedValue(routeData, propertyPath)\n }\n return routeData\n }\n }\n\n // Fallback: search across all route data for backward compatibility\n // This handles cases like {{shop.name}} without route prefix\n\n // Check cache first\n const cachedResult = fallbackCache.get(trimmedPath)\n if (cachedResult && dataContext[cachedResult.routeKey]) {\n const value = getNestedValue(\n dataContext[cachedResult.routeKey],\n trimmedPath\n )\n if (value !== undefined) {\n // Update timestamp on cache hit\n cachedResult.timestamp = Date.now()\n return value\n }\n }\n\n // Search with priority order (most common routes first)\n const priorityRoutes = ['root', 'routes/product', 'routes/collection']\n const allRoutes = [\n ...priorityRoutes,\n ...Object.keys(dataContext).filter((k) => !priorityRoutes.includes(k)),\n ]\n\n for (const routeKey of allRoutes) {\n const routeData = dataContext[routeKey]\n if (routeData && typeof routeData === 'object' && routeData !== null) {\n const value = getNestedValue(routeData, trimmedPath)\n if (value !== undefined) {\n // Clean cache if it's getting too large\n if (fallbackCache.size >= FALLBACK_CACHE_MAX_SIZE) {\n const entries = Array.from(fallbackCache.entries())\n entries.sort((a, b) => a[1].timestamp - b[1].timestamp)\n // Remove oldest 25% of entries\n const toRemove = Math.floor(entries.length * CACHE_EVICTION_RATIO)\n for (let i = 0; i < toRemove; i++) {\n fallbackCache.delete(entries[i][0])\n }\n }\n fallbackCache.set(trimmedPath, {\n routeKey,\n value,\n timestamp: Date.now(),\n })\n return value\n }\n }\n }\n\n // Final fallback: try direct access (for non-route-keyed legacy data)\n return getNestedValue(dataContext, trimmedPath)\n}\n\n/**\n * Replaces data connector placeholders in content with actual values from data context\n * Supports {{path}} syntax with dot notation, array indexing, and route prefixes\n *\n * Enhanced syntax:\n * - {{root.siteSettings.title}} - Access root route data\n * - {{layout.navigation.items}} - Access layout route data\n * - {{parent.category.name}} - Access parent route data\n * - {{current.product.title}} - Access current route data\n * - {{user.name}} - Auto-resolved from combined data (backward compatible)\n *\n * @param content - The content string containing {{}} placeholders\n * @param dataContext - The enhanced WeaverseDataContext with route-keyed data\n * @returns The content with placeholders replaced by actual values\n */\nexport function replaceContentDataConnectors(\n content: string,\n dataContext: DataContext | null | undefined\n): string {\n if (!dataContext || typeof content !== 'string') {\n return content\n }\n\n try {\n // Simplified caching - dataContext is already the combined data\n const cacheKey = createCacheKey(content, dataContext)\n\n const cachedContent = templateCache.get(cacheKey)\n if (cachedContent) {\n return cachedContent\n }\n\n const newContent = content.replace(TEMPLATE_REGEX, (match, path) => {\n try {\n const value = resolveDataFromContext(path, dataContext)\n\n if (value === undefined || value === null) {\n return match // Return original placeholder if value not found\n }\n\n return sanitizeValue(value)\n } catch (pathError) {\n console.warn(\n `Error resolving data connector path \"${path}\":`,\n pathError\n )\n return match\n }\n })\n\n // Cache the result (with size limit)\n if (templateCache.size >= MAX_CACHE_SIZE) {\n const firstKey = templateCache.keys().next().value\n templateCache.delete(firstKey)\n }\n templateCache.set(cacheKey, newContent)\n\n return newContent\n } catch (error) {\n console.warn('Error processing data connectors:', error, { content })\n return content\n }\n}\n\n/**\n * Fast check if data contains any {{...}} placeholders\n * Returns true if any string value contains the pattern\n * This is MUCH faster than processing and allows early exit\n *\n * IMPORTANT: Uses global TEMPLATE_REGEX, must reset lastIndex\n */\nfunction hasPlaceholders(data: unknown, visited = new WeakSet()): boolean {\n if (typeof data === 'string') {\n // Reset regex state before testing to ensure consistent results\n TEMPLATE_REGEX.lastIndex = 0\n return TEMPLATE_REGEX.test(data)\n }\n\n if (typeof data !== 'object' || data === null) {\n return false\n }\n\n // Skip Date objects - they can't contain placeholders\n if (data instanceof Date) {\n return false\n }\n\n // Protect against circular references\n if (visited.has(data as WeakKey)) {\n return false\n }\n visited.add(data as WeakKey)\n\n try {\n if (Array.isArray(data)) {\n return data.some((item) => hasPlaceholders(item, visited))\n }\n\n // Check object values safely (skip property access errors)\n for (const key of Object.keys(data)) {\n try {\n const value = (data as Record<string, unknown>)[key]\n if (hasPlaceholders(value, visited)) {\n return true\n }\n } catch {\n // Ignore property access errors - continue checking other properties\n }\n }\n\n return false\n } finally {\n visited.delete(data as WeakKey)\n }\n}\n\n/**\n * Recursively replaces data connector placeholders in any data structure\n * IMMUTABLE: Creates deep copies during processing to avoid mutating original data\n * Handles strings, objects, arrays, and nested combinations\n *\n * PERFORMANCE: Now includes early exit if no placeholders detected\n *\n * @param data - The data to process (string, object, array, or primitive)\n * @param dataContext - The data context for replacements\n * @param visited - Set to track visited objects for circular reference protection\n * @param forceClone - Internal flag to force cloning even if no placeholders (for parent immutability)\n * @returns IMMUTABLE copy of the data with all string placeholders replaced\n */\nexport function replaceContentDataConnectorsDeep<T>(\n data: T,\n dataContext: DataContext | null | undefined,\n visited = new WeakSet(),\n forceClone = false\n): T {\n if (!dataContext) {\n return data\n }\n\n const dataHasPlaceholders = hasPlaceholders(data, new WeakSet())\n\n // PERFORMANCE: Fast check - if no placeholders exist and not forced to clone, skip ALL processing\n // This saves 90%+ of CPU time for components without data connectors\n if (!(dataHasPlaceholders || forceClone)) {\n return data\n }\n\n // Handle primitive types - no cloning needed for primitives\n if (typeof data === 'string') {\n return replaceContentDataConnectors(data, dataContext) as T\n }\n\n if (typeof data !== 'object' || data === null) {\n return data\n }\n\n // Protect against circular references\n if (visited.has(data as WeakKey)) {\n console.warn(\n 'Circular reference detected in deep data connector replacement'\n )\n return data\n }\n\n // Add to circular reference tracking\n visited.add(data as WeakKey)\n\n try {\n // Handle special objects that should be cloned as-is\n if (data instanceof Date) {\n // Date objects can't contain placeholders, but clone if forced (parent has placeholders)\n // or if somehow detected (shouldn't happen but be safe)\n if (forceClone || dataHasPlaceholders) {\n return new Date(data.getTime()) as T\n }\n return data\n }\n\n // Handle arrays - create new array with processed items\n // Force clone children if parent has placeholders (for immutability)\n if (Array.isArray(data)) {\n const result = data.map((item) =>\n replaceContentDataConnectorsDeep(\n item,\n dataContext,\n visited,\n dataHasPlaceholders\n )\n ) as T\n return result\n }\n\n // Handle plain objects - create new object with processed values\n // Force clone children if parent has placeholders (for immutability)\n const result = {} as T\n\n // Use Object.entries with try-catch per property to handle getter errors\n for (const key of Object.keys(data)) {\n try {\n const value = (data as Record<string, unknown>)[key]\n ;(result as Record<string, unknown>)[key] =\n replaceContentDataConnectorsDeep(\n value,\n dataContext,\n visited,\n dataHasPlaceholders\n )\n } catch (propertyError) {\n // If property access throws, skip it but continue processing\n console.warn(`Error accessing property \"${key}\":`, propertyError)\n // Don't include this property in result\n }\n }\n\n return result\n } catch (error) {\n console.warn('Error in deep data connector replacement:', error)\n return data\n } finally {\n // Remove from tracking when done processing this object\n visited.delete(data as WeakKey)\n }\n}\n","import type { Weaverse } from '@weaverse/core'\nimport clsx from 'clsx'\nimport React, { memo, useEffect, useRef } from 'react'\nimport { useItemInstance, useWeaverse } from '~/hooks'\nimport { WeaverseContextProvider, WeaverseItemContext } from './context'\nimport type { ItemComponentProps, WeaverseRootPropsType } from './types'\nimport { replaceContentDataConnectorsDeep } from './utils/data-connector'\n\nconst REACT_VERSION_THRESHOLD = 18\nconst reactVersion = Number(React.version?.split('.')[0]) || 0\n\n// Create a safe version of useSyncExternalStore that works in both client and server environments\nexport const useSafeExternalStore = (\n subscribe: any,\n getSnapshot: any,\n getServerSnapshot: any = getSnapshot\n) => {\n // In server environment or during SSR, just return the snapshot directly\n if (typeof window === 'undefined') {\n return getServerSnapshot()\n }\n\n // In client environment, use React.useSyncExternalStore if available (React 18+)\n if (React.useSyncExternalStore) {\n // biome-ignore lint/correctness/useHookAtTopLevel: <$>\n return React.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)\n }\n\n // Fallback for older React versions - just return the current snapshot\n return getSnapshot()\n}\n\n/**\n * Determines the root element ID for the Weaverse component tree.\n * Falls back through multiple strategies to ensure a valid root is always found:\n * 1. Use explicit rootId from context.data if available\n * 2. Find the first element with type 'main' in items array\n * 3. Use projectId as final fallback\n */\nconst getRootId = (context: Weaverse): string => {\n // Strategy 1: Explicit rootId\n if (context.data.rootId) {\n return context.data.rootId\n }\n\n // Strategy 2: Find main element\n let mainItem = context.data?.items?.find((item) => item.type === 'main')\n if (mainItem?.id) {\n return mainItem.id\n }\n\n // Strategy 3: Fallback to projectId\n return context.projectId\n}\nexport const WeaverseRoot = memo(({ context }: WeaverseRootPropsType) => {\n const data = useSafeExternalStore(\n context.subscribe,\n context.getSnapShot,\n context.getSnapShot\n )\n const rootRef = useRef<HTMLElement>(null)\n\n useEffect(() => {\n context.contentRootElement = rootRef.current\n }, [context])\n\n const eventHandlers = context?.studioBridge?.eventHandlers || {}\n\n if (context.projectId) {\n return (\n <div\n className=\"weaverse-content-root\"\n {...eventHandlers}\n data-weaverse-project-id={context.projectId}\n data-weaverse-template-id={data.id}\n ref={rootRef}\n >\n <WeaverseContextProvider value={context}>\n <ItemInstance id={getRootId(context)} parentId={''} />\n </WeaverseContextProvider>\n </div>\n )\n }\n return null\n})\nWeaverseRoot.displayName = 'WeaverseRoot'\nconst ItemComponent = memo(({ instance }: ItemComponentProps) => {\n const context = useWeaverse()\n const { elementRegistry } = context\n const data = useSafeExternalStore(\n instance.subscribe,\n instance.getSnapShot,\n instance.getSnapShot\n )\n const {\n id,\n type,\n childIds = [],\n children = [],\n\n createdAt,\n updatedAt,\n deletedAt,\n css,\n __hidden,\n // Need to get rid of this `data` property\n data: _,\n ...rest\n } = data\n\n // Replace data connectors in all component data (handles strings, objects, and arrays recursively)\n // IMMUTABLE: Process the entire rest object to avoid mutating original content\n const processedRest = replaceContentDataConnectorsDeep(\n rest,\n context.dataContext\n )\n\n useEffect(() => {\n if (!instance.ref.current) {\n // Fallback `ref` if the element isn't created by `React.forwardRef`\n Object.assign(instance.ref, {\n current: document.querySelector(`[data-wv-id=\"${id}\"]`),\n })\n }\n }, [instance, id])\n\n if (__hidden) {\n return null\n }\n\n const Element = elementRegistry.get(type)\n\n if (Element?.Component) {\n const Component = Element.Component\n Component.displayName = type\n if (\n Component.$$typeof === Symbol.for('react.forward_ref') ||\n reactVersion > REACT_VERSION_THRESHOLD\n ) {\n processedRest.ref = instance.ref\n }\n const childItems = children?.length\n ? children\n : childIds?.length\n ? childIds.map((cid: string) => ({ id: cid }))\n : []\n\n const renderChildren = childItems.map(\n (item: { id: string }, index: number) => (\n <ItemInstance id={item.id} key={`${item.id}-${index}`} parentId={id} />\n )\n )\n\n return (\n <Component\n {...processedRest}\n children={renderChildren.length ? renderChildren : undefined}\n className={clsx(processedRest.data?.className)}\n data-wv-id={id}\n data-wv-type={type}\n key={id}\n />\n )\n }\n instance._store.deleted = true\n return null\n})\nItemComponent.displayName = 'WeaverseComponent'\n\nconst ItemInstance = memo(\n ({ id, parentId }: { id: string; parentId: string }) => {\n const instance = useItemInstance(id)\n if (!instance) {\n return <div style={{ display: 'none' }}>Item instance {id} not found</div>\n }\n return (\n <WeaverseItemContext.Provider value={{ parentId, id }}>\n <ItemComponent instance={instance} key={id} />\n </WeaverseItemContext.Provider>\n )\n }\n)\nItemInstance.displayName = 'WeaverseInstanceProvider'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,0BAAc,2BAAd;;;ACCA,mBAA8B;AAEvB,IAAI,sBAAkB,4BAAwB,CAAC,CAAa;AAC5D,IAAI,0BAA0B,gBAAgB;AAC9C,IAAI,0BAAsB,4BAG9B,EAAE,IAAI,IAAI,UAAU,GAAG,CAAC;;;ACR3B,kBAAiD;AACjD,IAAAA,gBAA2B;;;ACI3B,IAAM,iBAAiB;AACvB,IAAM,oBAAoB;AAG1B,IAAM,uBAAuB;AAM7B,SAAS,mBAAmB,KAAsB;AAEhD,QAAM,oBAAoB,CAAC,aAAa,eAAe,WAAW;AAClE,SAAO,CAAC,kBAAkB,SAAS,GAAG;AACxC;AAWA,SAAS,sBACP,MACA,aAIA;AACA,MAAI,CAAC,eAAe,OAAO,SAAS,UAAU;AAC5C,WAAO,EAAE,UAAU,MAAM,cAAc,KAAK;AAAA,EAC9C;AAEA,QAAM,cAAc,KAAK,KAAK;AAG9B,QAAM,WAAW,mBAAmB,WAAW;AAC/C,QAAM,WAAW,GAAG,WAAW,KAAK,QAAQ;AAG5C,QAAM,eAAe,kBAAkB,IAAI,QAAQ;AACnD,MAAI,cAAc;AAEhB,iBAAa,YAAY,KAAK,IAAI;AAClC,WAAO;AAAA,MACL,UAAU,aAAa;AAAA,MACvB,cAAc,aAAa;AAAA,I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,eAAe,yBACf;AACA,oBAAc,MAAM,SAAS;AAAA,IAC/B;AACA,UAAM,aAAa,UAAU,SACzB,WACA,UAAU,SACR,SAAS,IAAI,CAAC,SAAiB,EAAE,IAAI,IAAI,EAAE,IAC3C,CAAC;AAEP,UAAM,iBAAiB,WAAW;AAAA,MAChC,CAAC,MAAsB,UACrB,4CAAC,gBAAa,IAAI,KAAK,IAAgC,UAAU,MAAjC,GAAG,KAAK,EAAE,IAAI,KAAK,EAAkB;AAAA,IAEzE;AAEA,WACE;AAAA,MAAC;AAAA;AAAA,QACE,GAAG;AAAA,QACJ,UAAU,eAAe,SAAS,iBAAiB;AAAA,QACnD,eAAW,YAAAC,SAAK,cAAc,MAAM,SAAS;AAAA,QAC7C,cAAY;AAAA,QACZ,gBAAc;AAAA,QACd,KAAK;AAAA;AAAA,IACP;AAAA,EAEJ;AACA,WAAS,OAAO,UAAU;AAC1B,SAAO;AACT,CAAC;AACD,cAAc,cAAc;AAE5B,IAAM,mBAAe;AAAA,EACnB,CAAC,EAAE,IAAI,SAAS,MAAwC;AACtD,UAAM,WAAW,gBAAgB,EAAE;AACnC,QAAI,CAAC,UAAU;AACb,aAAO,6CAAC,SAAI,OAAO,EAAE,SAAS,OAAO,GAAG;AAAA;AAAA,QAAe;AAAA,QAAG;AAAA,SAAU;AAAA,IACtE;AACA,WACE,4CAAC,oBAAoB,UAApB,EAA6B,OAAO,EAAE,UAAU,GAAG,GAClD,sDAAC,iBAAc,YAAyB,EAAI,GAC9C;AAAA,EAEJ;AACF;AACA,aAAa,cAAc;","names":["import_react","routeKey","result","id","import_react","import_react","React","clsx"]}
package/dist/index.mjs CHANGED
@@ -348,45 +348,8 @@ var useChildInstances = (id) => {
348
348
  };
349
349
 
350
350
  // src/renderer.tsx
351
- import clsx2 from "clsx";
352
- import React, { memo, useEffect, useRef } from "react";
353
-
354
- // src/utils/css.ts
355
351
  import clsx from "clsx";
356
- function formatCSS(css) {
357
- return {
358
- "@desktop": css["@desktop"],
359
- "@mobile": css["@mobile"]
360
- };
361
- }
362
- var permanentClasses = {};
363
- function generateItemClassName(instance, stitchesInstance) {
364
- let { css, type, className: cls = "" } = instance.data;
365
- let className = "";
366
- let permanentClass = "";
367
- let perCss = instance.Element?.permanentCss;
368
- if (perCss) {
369
- if (type in permanentClasses) {
370
- permanentClass = permanentClasses[type];
371
- } else {
372
- let { className: perCls } = stitchesInstance.css(perCss)();
373
- Object.assign(permanentClasses, { [type]: perCls });
374
- permanentClass = perCls;
375
- }
376
- }
377
- className = permanentClass;
378
- if (css) {
379
- let formattedCss = formatCSS(css);
380
- let newStitchesClass = stitchesInstance.css(formattedCss)().className || "";
381
- let { stitchesClass = "" } = instance;
382
- let otherClass = (instance.ref.current?.className || "").replace(stitchesClass, "").replace(cls, "").replace(permanentClass, "").trim();
383
- className = clsx(permanentClass, cls, newStitchesClass, otherClass);
384
- instance.stitchesClass = newStitchesClass;
385
- }
386
- return className;
387
- }
388
-
389
- // src/renderer.tsx
352
+ import React, { memo, useEffect, useRef } from "react";
390
353
  import { jsx, jsxs } from "react/jsx-runtime";
391
354
  import { createElement } from "react";
392
355
  var REACT_VERSION_THRESHOLD = 18;
@@ -421,12 +384,11 @@ var WeaverseRoot = memo(({ context }) => {
421
384
  context.contentRootElement = rootRef.current;
422
385
  }, [context]);
423
386
  const eventHandlers = context?.studioBridge?.eventHandlers || {};
424
- const themeClass = context.stitchesInstance.theme.className;
425
387
  if (context.projectId) {
426
388
  return /* @__PURE__ */ jsx(
427
389
  "div",
428
390
  {
429
- className: `weaverse-content-root ${themeClass}`,
391
+ className: "weaverse-content-root",
430
392
  ...eventHandlers,
431
393
  "data-weaverse-project-id": context.projectId,
432
394
  "data-weaverse-template-id": data.id,
@@ -440,7 +402,7 @@ var WeaverseRoot = memo(({ context }) => {
440
402
  WeaverseRoot.displayName = "WeaverseRoot";
441
403
  var ItemComponent = memo(({ instance }) => {
442
404
  const context = useWeaverse();
443
- const { stitchesInstance, elementRegistry, platformType } = context;
405
+ const { elementRegistry } = context;
444
406
  const data = useSafeExternalStore(
445
407
  instance.subscribe,
446
408
  instance.getSnapShot,
@@ -478,7 +440,7 @@ var ItemComponent = memo(({ instance }) => {
478
440
  if (Element?.Component) {
479
441
  const Component = Element.Component;
480
442
  Component.displayName = type;
481
- if (Component.$$typeof === Symbol.for("react.forward_ref") || reactVersion > REACT_VERSION_THRESHOLD) {
443
+ if (Component.$$typeof === /* @__PURE__ */ Symbol.for("react.forward_ref") || reactVersion > REACT_VERSION_THRESHOLD) {
482
444
  processedRest.ref = instance.ref;
483
445
  }
484
446
  const childItems = children?.length ? children : childIds?.length ? childIds.map((cid) => ({ id: cid })) : [];
@@ -490,10 +452,7 @@ var ItemComponent = memo(({ instance }) => {
490
452
  {
491
453
  ...processedRest,
492
454
  children: renderChildren.length ? renderChildren : void 0,
493
- className: clsx2(
494
- platformType !== "shopify-hydrogen" && generateItemClassName(instance, stitchesInstance),
495
- processedRest.data?.className
496
- ),
455
+ className: clsx(processedRest.data?.className),
497
456
  "data-wv-id": id,
498
457
  "data-wv-type": type,
499
458
  key: id
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/context.ts","../src/hooks.ts","../src/utils/data-connector.ts","../src/renderer.tsx","../src/utils/css.ts"],"sourcesContent":["export * from '@weaverse/core'\nexport * from './context'\nexport * from './hooks'\nexport * from './renderer'\nexport * from './types'\n","import type { Weaverse } from '@weaverse/core'\nimport { createContext } from 'react'\n\nexport let WeaverseContext = createContext<Weaverse>({} as Weaverse)\nexport let WeaverseContextProvider = WeaverseContext.Provider\nexport let WeaverseItemContext = createContext<{\n id: string\n parentId: string\n}>({ id: '', parentId: '' })\n","import { Weaverse, type WeaverseItemStore } from '@weaverse/core'\nimport { useContext } from 'react'\nimport { WeaverseContext, WeaverseItemContext } from '~/context'\n\n// Re-export the data connector utilities\nexport {\n replaceContentDataConnectors,\n replaceContentDataConnectorsDeep,\n} from './utils/data-connector'\n\nexport function useWeaverse<T = Weaverse>() {\n let weaverse = useContext(WeaverseContext)\n return weaverse as T\n}\n\nexport let useItemInstance = (id?: string) => {\n let { id: currentId } = useContext(WeaverseItemContext)\n let instance = Weaverse.itemInstances.get(id || currentId)\n if (!instance) {\n console.log(`Item instance ${id} not found`)\n return null\n }\n return instance as WeaverseItemStore\n}\n\nexport let useParentInstance = () => {\n let { parentId } = useContext(WeaverseItemContext)\n return useItemInstance(parentId || '')\n}\n\nexport let useChildInstances = (id?: string) => {\n let currentInstance = useItemInstance(id)\n if (!currentInstance) {\n return []\n }\n let { itemInstances } = Weaverse\n\n let {\n data: { children },\n } = currentInstance\n return children\n .map(({ id }: { id: string }) => itemInstances.get(id))\n .filter(Boolean) as WeaverseItemStore[]\n}\n","// Data connector utilities for replacing placeholders with real data\n// Generic data context type for flexible usage\nexport type DataContext = Record<string, unknown>\n\n// Cached regex pattern for better performance\nconst TEMPLATE_REGEX = /\\{\\{([^}]+)\\}\\}/g\nconst ARRAY_INDEX_REGEX = /^(\\w+)\\[(\\d+)\\]$/\n\n// Cache eviction ratio - remove oldest 25% when cache is full\nconst CACHE_EVICTION_RATIO = 0.25\n\n/**\n * Validates that a property name is safe to access (prevents prototype pollution)\n * Enhanced to handle route-specific patterns with special characters\n */\nfunction isSafePropertyName(key: string): boolean {\n // Block dangerous prototype pollution patterns\n const dangerousPatterns = ['__proto__', 'constructor', 'prototype']\n return !dangerousPatterns.includes(key)\n}\n\n/**\n * Parses a template path into route key and property path components\n * Handles complex routes like: routes/($locale).blogs.$blogHandle.$articleHandle\n * Enhanced with caching for improved performance\n *\n * @param path - The full path from template (e.g., \"routes/($locale)._index.weaverseData.page.name\")\n * @param dataContext - Available route data context\n * @returns Object with routeKey and propertyPath\n */\nfunction parseRouteAndProperty(\n path: string,\n dataContext: DataContext\n): {\n routeKey: string | null\n propertyPath: string\n} {\n if (!dataContext || typeof path !== 'string') {\n return { routeKey: null, propertyPath: path }\n }\n\n const trimmedPath = path.trim()\n\n // Create a cache key using stable hash instead of serializing route keys\n const dataHash = getDataContextHash(dataContext)\n const cacheKey = `${trimmedPath}::${dataHash}`\n\n // Check cache first\n const cachedResult = routeParsingCache.get(cacheKey)\n if (cachedResult) {\n // Update timestamp on cache hit\n cachedResult.timestamp = Date.now()\n return {\n routeKey: cachedResult.routeKey,\n propertyPath: cachedResult.propertyPath,\n }\n }\n\n // Get all available routes and sort by length (longest first for specificity)\n const availableRoutes = Object.keys(dataContext).sort(\n (a, b) => b.length - a.length\n )\n\n let result: { routeKey: string | null; propertyPath: string } = {\n routeKey: null,\n propertyPath: trimmedPath,\n }\n\n // Try to find the longest matching route key\n let found = false\n for (const routeKey of availableRoutes) {\n // Exact match\n if (trimmedPath === routeKey) {\n result = { routeKey, propertyPath: '' }\n found = true\n break\n }\n\n // Route key with property path\n if (trimmedPath.startsWith(`${routeKey}.`)) {\n const propertyPath = trimmedPath.substring(routeKey.length + 1)\n result = { routeKey, propertyPath }\n found = true\n break\n }\n }\n\n if (!found) {\n // No route key found, treat entire path as property path\n result = { routeKey: null, propertyPath: trimmedPath }\n }\n\n // Cache the result\n if (routeParsingCache.size >= ROUTE_PARSING_CACHE_MAX_SIZE) {\n // Clean cache by removing oldest entries\n const entries = Array.from(routeParsingCache.entries())\n entries.sort((a, b) => a[1].timestamp - b[1].timestamp)\n const toRemove = Math.floor(entries.length * CACHE_EVICTION_RATIO)\n for (let i = 0; i < toRemove; i++) {\n routeParsingCache.delete(entries[i][0])\n }\n }\n\n routeParsingCache.set(cacheKey, {\n routeKey: result.routeKey,\n propertyPath: result.propertyPath,\n timestamp: Date.now(),\n })\n\n return result\n}\n\n// Simple cache for parsed templates (max 100 entries)\nconst templateCache = new Map<string, string>()\nconst MAX_CACHE_SIZE = 100\n\n// Cache for fallback lookups to improve performance (moved to module level to prevent memory leaks)\nconst fallbackCache = new Map<\n string,\n { routeKey: string; value: unknown; timestamp: number }\n>()\nconst FALLBACK_CACHE_MAX_SIZE = 50\n\n// Route parsing cache for performance optimization\nconst routeParsingCache = new Map<\n string,\n { routeKey: string | null; propertyPath: string; timestamp: number }\n>()\nconst ROUTE_PARSING_CACHE_MAX_SIZE = 100\n\n// WeakMap for stable dataContext hashing - prevents repeated JSON.stringify\nconst dataContextHashCache = new WeakMap<object, string>()\nlet hashCounter = 0\n\n/**\n * Safely gets a nested value from an object using dot notation path\n * Supports array indexing with [index] syntax\n * @param obj - The object to traverse\n * @param path - Dot notation path (e.g., \"user.name\" or \"items[0].title\")\n * @param visited - Set to track visited objects for circular reference protection\n * @returns The resolved value or undefined if not found\n */\nfunction getNestedValue(\n obj: unknown,\n path: string,\n visited = new WeakSet()\n): unknown {\n return path.split('.').reduce((current, key) => {\n if (!current || typeof current !== 'object') {\n return\n }\n\n // Protect against circular references\n if (visited.has(current as WeakKey)) {\n console.warn('Circular reference detected in data connector path:', path)\n return\n }\n\n // Add to circular reference tracking\n visited.add(current as WeakKey)\n\n // Handle array indexing like items[0] or items[1]\n const arrayMatch = key.match(ARRAY_INDEX_REGEX)\n if (arrayMatch) {\n const [, arrayKey, index] = arrayMatch\n const arrayObj = (current as Record<string, unknown>)[arrayKey]\n if (Array.isArray(arrayObj)) {\n const indexNum = Number.parseInt(index, 10)\n if (indexNum >= 0 && indexNum < arrayObj.length) {\n return arrayObj[indexNum]\n }\n }\n return\n }\n\n // Handle regular object property access with security validation\n if (!isSafePropertyName(key)) {\n console.warn(`Unsafe property access attempted: ${key}`)\n return\n }\n\n return current !== null && key in current\n ? (current as Record<string, unknown>)[key]\n : undefined\n }, obj)\n}\n\n/**\n * Sanitizes a string value to prevent XSS attacks\n * @param value - The value to sanitize\n * @returns Sanitized string safe for HTML rendering\n */\nfunction sanitizeValue(value: unknown): string {\n if (value === null || value === undefined) {\n return ''\n }\n\n const stringValue = String(value)\n\n // Basic HTML entity encoding to prevent XSS\n return stringValue\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#x27;')\n .replace(/\\//g, '&#x2F;')\n}\n\n/**\n * Creates a stable hash for dataContext object\n * Uses WeakMap to cache hash per object reference (no serialization needed)\n */\nfunction getDataContextHash(data: Record<string, unknown>): string {\n if (!dataContextHashCache.has(data)) {\n // Generate unique hash for this dataContext instance\n dataContextHashCache.set(data, `ctx_${++hashCounter}`)\n }\n const hash = dataContextHashCache.get(data)\n return hash || `ctx_${++hashCounter}`\n}\n\n/**\n * Creates a safe cache key from content and data\n * Uses stable hashing instead of JSON.stringify for massive performance gain\n */\nfunction createCacheKey(\n content: string,\n data: Record<string, unknown>\n): string {\n // Use stable hash instead of expensive JSON.stringify\n const dataHash = getDataContextHash(data)\n return `${content}:${dataHash}`\n}\n\n/**\n * Resolves data from the flat route-keyed data context\n * Enhanced to support complex route patterns with special characters\n * Supports: {{root.layout.shop.name}}, {{routes/($locale)._index.data}}, {{routes/($locale).blogs.$handle.$article.content}}\n */\nfunction resolveDataFromContext(\n path: string,\n dataContext: DataContext | null | undefined\n): unknown {\n if (!dataContext) {\n return\n }\n\n const trimmedPath = path.trim()\n\n // Use intelligent route parsing to separate route key from property path\n const { routeKey, propertyPath } = parseRouteAndProperty(\n trimmedPath,\n dataContext\n )\n\n // If we found a specific route key, resolve from that route's data\n if (routeKey && dataContext[routeKey]) {\n const routeData = dataContext[routeKey]\n if (typeof routeData === 'object' && routeData !== null) {\n if (propertyPath) {\n return getNestedValue(routeData, propertyPath)\n }\n return routeData\n }\n }\n\n // Fallback: search across all route data for backward compatibility\n // This handles cases like {{shop.name}} without route prefix\n\n // Check cache first\n const cachedResult = fallbackCache.get(trimmedPath)\n if (cachedResult && dataContext[cachedResult.routeKey]) {\n const value = getNestedValue(\n dataContext[cachedResult.routeKey],\n trimmedPath\n )\n if (value !== undefined) {\n // Update timestamp on cache hit\n cachedResult.timestamp = Date.now()\n return value\n }\n }\n\n // Search with priority order (most common routes first)\n const priorityRoutes = ['root', 'routes/product', 'routes/collection']\n const allRoutes = [\n ...priorityRoutes,\n ...Object.keys(dataContext).filter((k) => !priorityRoutes.includes(k)),\n ]\n\n for (const routeKey of allRoutes) {\n const routeData = dataContext[routeKey]\n if (routeData && typeof routeData === 'object' && routeData !== null) {\n const value = getNestedValue(routeData, trimmedPath)\n if (value !== undefined) {\n // Clean cache if it's getting too large\n if (fallbackCache.size >= FALLBACK_CACHE_MAX_SIZE) {\n const entries = Array.from(fallbackCache.entries())\n entries.sort((a, b) => a[1].timestamp - b[1].timestamp)\n // Remove oldest 25% of entries\n const toRemove = Math.floor(entries.length * CACHE_EVICTION_RATIO)\n for (let i = 0; i < toRemove; i++) {\n fallbackCache.delete(entries[i][0])\n }\n }\n fallbackCache.set(trimmedPath, {\n routeKey,\n value,\n timestamp: Date.now(),\n })\n return value\n }\n }\n }\n\n // Final fallback: try direct access (for non-route-keyed legacy data)\n return getNestedValue(dataContext, trimmedPath)\n}\n\n/**\n * Replaces data connector placeholders in content with actual values from data context\n * Supports {{path}} syntax with dot notation, array indexing, and route prefixes\n *\n * Enhanced syntax:\n * - {{root.siteSettings.title}} - Access root route data\n * - {{layout.navigation.items}} - Access layout route data\n * - {{parent.category.name}} - Access parent route data\n * - {{current.product.title}} - Access current route data\n * - {{user.name}} - Auto-resolved from combined data (backward compatible)\n *\n * @param content - The content string containing {{}} placeholders\n * @param dataContext - The enhanced WeaverseDataContext with route-keyed data\n * @returns The content with placeholders replaced by actual values\n */\nexport function replaceContentDataConnectors(\n content: string,\n dataContext: DataContext | null | undefined\n): string {\n if (!dataContext || typeof content !== 'string') {\n return content\n }\n\n try {\n // Simplified caching - dataContext is already the combined data\n const cacheKey = createCacheKey(content, dataContext)\n\n const cachedContent = templateCache.get(cacheKey)\n if (cachedContent) {\n return cachedContent\n }\n\n const newContent = content.replace(TEMPLATE_REGEX, (match, path) => {\n try {\n const value = resolveDataFromContext(path, dataContext)\n\n if (value === undefined || value === null) {\n return match // Return original placeholder if value not found\n }\n\n return sanitizeValue(value)\n } catch (pathError) {\n console.warn(\n `Error resolving data connector path \"${path}\":`,\n pathError\n )\n return match\n }\n })\n\n // Cache the result (with size limit)\n if (templateCache.size >= MAX_CACHE_SIZE) {\n const firstKey = templateCache.keys().next().value\n templateCache.delete(firstKey)\n }\n templateCache.set(cacheKey, newContent)\n\n return newContent\n } catch (error) {\n console.warn('Error processing data connectors:', error, { content })\n return content\n }\n}\n\n/**\n * Fast check if data contains any {{...}} placeholders\n * Returns true if any string value contains the pattern\n * This is MUCH faster than processing and allows early exit\n *\n * IMPORTANT: Uses global TEMPLATE_REGEX, must reset lastIndex\n */\nfunction hasPlaceholders(data: unknown, visited = new WeakSet()): boolean {\n if (typeof data === 'string') {\n // Reset regex state before testing to ensure consistent results\n TEMPLATE_REGEX.lastIndex = 0\n return TEMPLATE_REGEX.test(data)\n }\n\n if (typeof data !== 'object' || data === null) {\n return false\n }\n\n // Skip Date objects - they can't contain placeholders\n if (data instanceof Date) {\n return false\n }\n\n // Protect against circular references\n if (visited.has(data as WeakKey)) {\n return false\n }\n visited.add(data as WeakKey)\n\n try {\n if (Array.isArray(data)) {\n return data.some((item) => hasPlaceholders(item, visited))\n }\n\n // Check object values safely (skip property access errors)\n for (const key of Object.keys(data)) {\n try {\n const value = (data as Record<string, unknown>)[key]\n if (hasPlaceholders(value, visited)) {\n return true\n }\n } catch {\n // Ignore property access errors - continue checking other properties\n }\n }\n\n return false\n } finally {\n visited.delete(data as WeakKey)\n }\n}\n\n/**\n * Recursively replaces data connector placeholders in any data structure\n * IMMUTABLE: Creates deep copies during processing to avoid mutating original data\n * Handles strings, objects, arrays, and nested combinations\n *\n * PERFORMANCE: Now includes early exit if no placeholders detected\n *\n * @param data - The data to process (string, object, array, or primitive)\n * @param dataContext - The data context for replacements\n * @param visited - Set to track visited objects for circular reference protection\n * @param forceClone - Internal flag to force cloning even if no placeholders (for parent immutability)\n * @returns IMMUTABLE copy of the data with all string placeholders replaced\n */\nexport function replaceContentDataConnectorsDeep<T>(\n data: T,\n dataContext: DataContext | null | undefined,\n visited = new WeakSet(),\n forceClone = false\n): T {\n if (!dataContext) {\n return data\n }\n\n const dataHasPlaceholders = hasPlaceholders(data, new WeakSet())\n\n // PERFORMANCE: Fast check - if no placeholders exist and not forced to clone, skip ALL processing\n // This saves 90%+ of CPU time for components without data connectors\n if (!(dataHasPlaceholders || forceClone)) {\n return data\n }\n\n // Handle primitive types - no cloning needed for primitives\n if (typeof data === 'string') {\n return replaceContentDataConnectors(data, dataContext) as T\n }\n\n if (typeof data !== 'object' || data === null) {\n return data\n }\n\n // Protect against circular references\n if (visited.has(data as WeakKey)) {\n console.warn(\n 'Circular reference detected in deep data connector replacement'\n )\n return data\n }\n\n // Add to circular reference tracking\n visited.add(data as WeakKey)\n\n try {\n // Handle special objects that should be cloned as-is\n if (data instanceof Date) {\n // Date objects can't contain placeholders, but clone if forced (parent has placeholders)\n // or if somehow detected (shouldn't happen but be safe)\n if (forceClone || dataHasPlaceholders) {\n return new Date(data.getTime()) as T\n }\n return data\n }\n\n // Handle arrays - create new array with processed items\n // Force clone children if parent has placeholders (for immutability)\n if (Array.isArray(data)) {\n const result = data.map((item) =>\n replaceContentDataConnectorsDeep(\n item,\n dataContext,\n visited,\n dataHasPlaceholders\n )\n ) as T\n return result\n }\n\n // Handle plain objects - create new object with processed values\n // Force clone children if parent has placeholders (for immutability)\n const result = {} as T\n\n // Use Object.entries with try-catch per property to handle getter errors\n for (const key of Object.keys(data)) {\n try {\n const value = (data as Record<string, unknown>)[key]\n ;(result as Record<string, unknown>)[key] =\n replaceContentDataConnectorsDeep(\n value,\n dataContext,\n visited,\n dataHasPlaceholders\n )\n } catch (propertyError) {\n // If property access throws, skip it but continue processing\n console.warn(`Error accessing property \"${key}\":`, propertyError)\n // Don't include this property in result\n }\n }\n\n return result\n } catch (error) {\n console.warn('Error in deep data connector replacement:', error)\n return data\n } finally {\n // Remove from tracking when done processing this object\n visited.delete(data as WeakKey)\n }\n}\n","import type { Weaverse } from '@weaverse/core'\nimport clsx from 'clsx'\nimport React, { memo, useEffect, useRef } from 'react'\nimport { useItemInstance, useWeaverse } from '~/hooks'\nimport { WeaverseContextProvider, WeaverseItemContext } from './context'\nimport type { ItemComponentProps, WeaverseRootPropsType } from './types'\nimport { generateItemClassName } from './utils/css'\nimport { replaceContentDataConnectorsDeep } from './utils/data-connector'\n\nconst REACT_VERSION_THRESHOLD = 18\nconst reactVersion = Number(React.version?.split('.')[0]) || 0\n\n// Create a safe version of useSyncExternalStore that works in both client and server environments\nexport const useSafeExternalStore = (\n subscribe: any,\n getSnapshot: any,\n getServerSnapshot: any = getSnapshot\n) => {\n // In server environment or during SSR, just return the snapshot directly\n if (typeof window === 'undefined') {\n return getServerSnapshot()\n }\n\n // In client environment, use React.useSyncExternalStore if available (React 18+)\n if (React.useSyncExternalStore) {\n // biome-ignore lint/correctness/useHookAtTopLevel: <$>\n return React.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)\n }\n\n // Fallback for older React versions - just return the current snapshot\n return getSnapshot()\n}\n\n/**\n * Determines the root element ID for the Weaverse component tree.\n * Falls back through multiple strategies to ensure a valid root is always found:\n * 1. Use explicit rootId from context.data if available\n * 2. Find the first element with type 'main' in items array\n * 3. Use projectId as final fallback\n */\nconst getRootId = (context: Weaverse): string => {\n // Strategy 1: Explicit rootId\n if (context.data.rootId) {\n return context.data.rootId\n }\n\n // Strategy 2: Find main element\n let mainItem = context.data?.items?.find((item) => item.type === 'main')\n if (mainItem?.id) {\n return mainItem.id\n }\n\n // Strategy 3: Fallback to projectId\n return context.projectId\n}\nexport const WeaverseRoot = memo(({ context }: WeaverseRootPropsType) => {\n const data = useSafeExternalStore(\n context.subscribe,\n context.getSnapShot,\n context.getSnapShot\n )\n const rootRef = useRef<HTMLElement>(null)\n\n useEffect(() => {\n context.contentRootElement = rootRef.current\n }, [context])\n\n const eventHandlers = context?.studioBridge?.eventHandlers || {}\n const themeClass = context.stitchesInstance.theme.className\n\n if (context.projectId) {\n return (\n <div\n className={`weaverse-content-root ${themeClass}`}\n {...eventHandlers}\n data-weaverse-project-id={context.projectId}\n data-weaverse-template-id={data.id}\n ref={rootRef}\n >\n <WeaverseContextProvider value={context}>\n <ItemInstance id={getRootId(context)} parentId={''} />\n </WeaverseContextProvider>\n </div>\n )\n }\n return null\n})\nWeaverseRoot.displayName = 'WeaverseRoot'\nconst ItemComponent = memo(({ instance }: ItemComponentProps) => {\n const context = useWeaverse()\n const { stitchesInstance, elementRegistry, platformType } = context\n const data = useSafeExternalStore(\n instance.subscribe,\n instance.getSnapShot,\n instance.getSnapShot\n )\n const {\n id,\n type,\n childIds = [],\n children = [],\n\n createdAt,\n updatedAt,\n deletedAt,\n css,\n __hidden,\n // Need to get rid of this `data` property\n data: _,\n ...rest\n } = data\n\n // Replace data connectors in all component data (handles strings, objects, and arrays recursively)\n // IMMUTABLE: Process the entire rest object to avoid mutating original content\n const processedRest = replaceContentDataConnectorsDeep(\n rest,\n context.dataContext\n )\n\n useEffect(() => {\n if (!instance.ref.current) {\n // Fallback `ref` if the element isn't created by `React.forwardRef`\n Object.assign(instance.ref, {\n current: document.querySelector(`[data-wv-id=\"${id}\"]`),\n })\n }\n }, [instance, id])\n\n if (__hidden) {\n return null\n }\n\n const Element = elementRegistry.get(type)\n\n if (Element?.Component) {\n const Component = Element.Component\n Component.displayName = type\n if (\n Component.$$typeof === Symbol.for('react.forward_ref') ||\n reactVersion > REACT_VERSION_THRESHOLD\n ) {\n processedRest.ref = instance.ref\n }\n const childItems = children?.length\n ? children\n : childIds?.length\n ? childIds.map((cid: string) => ({ id: cid }))\n : []\n\n const renderChildren = childItems.map(\n (item: { id: string }, index: number) => (\n <ItemInstance id={item.id} key={`${item.id}-${index}`} parentId={id} />\n )\n )\n\n return (\n <Component\n {...processedRest}\n children={renderChildren.length ? renderChildren : undefined}\n className={clsx(\n platformType !== 'shopify-hydrogen' &&\n generateItemClassName(instance, stitchesInstance),\n processedRest.data?.className\n )}\n data-wv-id={id}\n data-wv-type={type}\n key={id}\n />\n )\n }\n instance._store.deleted = true\n return null\n})\nItemComponent.displayName = 'WeaverseComponent'\n\nconst ItemInstance = memo(\n ({ id, parentId }: { id: string; parentId: string }) => {\n const instance = useItemInstance(id)\n if (!instance) {\n return <div style={{ display: 'none' }}>Item instance {id} not found</div>\n }\n return (\n <WeaverseItemContext.Provider value={{ parentId, id }}>\n <ItemComponent instance={instance} key={id} />\n </WeaverseItemContext.Provider>\n )\n }\n)\nItemInstance.displayName = 'WeaverseInstanceProvider'\n","import type Stitches from '@stitches/react/types/stitches'\nimport type { ElementCSS, WeaverseItemStore } from '@weaverse/core'\nimport clsx from 'clsx'\n\n// Make the css data formatted to correct order (desktop, tablet, mobile)\nfunction formatCSS(css: ElementCSS) {\n return {\n '@desktop': css['@desktop'],\n '@mobile': css['@mobile'],\n }\n}\n\nlet permanentClasses: Record<string, string> = {}\nexport function generateItemClassName(\n instance: WeaverseItemStore,\n stitchesInstance: Stitches\n) {\n let { css, type, className: cls = '' } = instance.data\n let className = ''\n let permanentClass = ''\n let perCss = instance.Element?.permanentCss\n if (perCss) {\n if (type in permanentClasses) {\n permanentClass = permanentClasses[type]\n } else {\n // @ts-expect-error\n let { className: perCls } = stitchesInstance.css(perCss)()\n Object.assign(permanentClasses, { [type]: perCls })\n permanentClass = perCls\n }\n }\n className = permanentClass\n if (css) {\n // let stitches create the style from css object and\n // then return the classname, so we can use it in the render\n let formattedCss = formatCSS(css)\n let newStitchesClass = stitchesInstance.css(formattedCss)().className || ''\n let { stitchesClass = '' } = instance\n let otherClass = (instance.ref.current?.className || '')\n .replace(stitchesClass, '')\n .replace(cls, '')\n .replace(permanentClass, '')\n .trim()\n className = clsx(permanentClass, cls, newStitchesClass, otherClass)\n instance.stitchesClass = newStitchesClass\n }\n return className\n}\n"],"mappings":";AAAA,cAAc;;;ACCd,SAAS,qBAAqB;AAEvB,IAAI,kBAAkB,cAAwB,CAAC,CAAa;AAC5D,IAAI,0BAA0B,gBAAgB;AAC9C,IAAI,sBAAsB,cAG9B,EAAE,IAAI,IAAI,UAAU,GAAG,CAAC;;;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A;AAAA,QAAe;AAAA,QAAG;AAAA,SAAU;AAAA,IACtE;AACA,WACE,oBAAC,oBAAoB,UAApB,EAA6B,OAAO,EAAE,UAAU,GAAG,GAClD,8BAAC,iBAAc,YAAyB,EAAI,GAC9C;AAAA,EAEJ;AACF;AACA,aAAa,cAAc;","names":["routeKey","result","id","clsx","clsx"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/context.ts","../src/hooks.ts","../src/utils/data-connector.ts","../src/renderer.tsx"],"sourcesContent":["export * from '@weaverse/core'\nexport * from './context'\nexport * from './hooks'\nexport * from './renderer'\nexport * from './types'\n","import type { Weaverse } from '@weaverse/core'\nimport { createContext } from 'react'\n\nexport let WeaverseContext = createContext<Weaverse>({} as Weaverse)\nexport let WeaverseContextProvider = WeaverseContext.Provider\nexport let WeaverseItemContext = createContext<{\n id: string\n parentId: string\n}>({ id: '', parentId: '' })\n","import { Weaverse, type WeaverseItemStore } from '@weaverse/core'\nimport { useContext } from 'react'\nimport { WeaverseContext, WeaverseItemContext } from '~/context'\n\n// Re-export the data connector utilities\nexport {\n replaceContentDataConnectors,\n replaceContentDataConnectorsDeep,\n} from './utils/data-connector'\n\nexport function useWeaverse<T = Weaverse>() {\n let weaverse = useContext(WeaverseContext)\n return weaverse as T\n}\n\nexport let useItemInstance = (id?: string) => {\n let { id: currentId } = useContext(WeaverseItemContext)\n let instance = Weaverse.itemInstances.get(id || currentId)\n if (!instance) {\n console.log(`Item instance ${id} not found`)\n return null\n }\n return instance as WeaverseItemStore\n}\n\nexport let useParentInstance = () => {\n let { parentId } = useContext(WeaverseItemContext)\n return useItemInstance(parentId || '')\n}\n\nexport let useChildInstances = (id?: string) => {\n let currentInstance = useItemInstance(id)\n if (!currentInstance) {\n return []\n }\n let { itemInstances } = Weaverse\n\n let {\n data: { children },\n } = currentInstance\n return children\n .map(({ id }: { id: string }) => itemInstances.get(id))\n .filter(Boolean) as WeaverseItemStore[]\n}\n","// Data connector utilities for replacing placeholders with real data\n// Generic data context type for flexible usage\nexport type DataContext = Record<string, unknown>\n\n// Cached regex pattern for better performance\nconst TEMPLATE_REGEX = /\\{\\{([^}]+)\\}\\}/g\nconst ARRAY_INDEX_REGEX = /^(\\w+)\\[(\\d+)\\]$/\n\n// Cache eviction ratio - remove oldest 25% when cache is full\nconst CACHE_EVICTION_RATIO = 0.25\n\n/**\n * Validates that a property name is safe to access (prevents prototype pollution)\n * Enhanced to handle route-specific patterns with special characters\n */\nfunction isSafePropertyName(key: string): boolean {\n // Block dangerous prototype pollution patterns\n const dangerousPatterns = ['__proto__', 'constructor', 'prototype']\n return !dangerousPatterns.includes(key)\n}\n\n/**\n * Parses a template path into route key and property path components\n * Handles complex routes like: routes/($locale).blogs.$blogHandle.$articleHandle\n * Enhanced with caching for improved performance\n *\n * @param path - The full path from template (e.g., \"routes/($locale)._index.weaverseData.page.name\")\n * @param dataContext - Available route data context\n * @returns Object with routeKey and propertyPath\n */\nfunction parseRouteAndProperty(\n path: string,\n dataContext: DataContext\n): {\n routeKey: string | null\n propertyPath: string\n} {\n if (!dataContext || typeof path !== 'string') {\n return { routeKey: null, propertyPath: path }\n }\n\n const trimmedPath = path.trim()\n\n // Create a cache key using stable hash instead of serializing route keys\n const dataHash = getDataContextHash(dataContext)\n const cacheKey = `${trimmedPath}::${dataHash}`\n\n // Check cache first\n const cachedResult = routeParsingCache.get(cacheKey)\n if (cachedResult) {\n // Update timestamp on cache hit\n cachedResult.timestamp = Date.now()\n return {\n routeKey: cachedResult.routeKey,\n propertyPath: cachedResult.propertyPath,\n }\n }\n\n // Get all available routes and sort by length (longest first for specificity)\n const availableRoutes = Object.keys(dataContext).sort(\n (a, b) => b.length - a.length\n )\n\n let result: { routeKey: string | null; propertyPath: string } = {\n routeKey: null,\n propertyPath: trimmedPath,\n }\n\n // Try to find the longest matching route key\n let found = false\n for (const routeKey of availableRoutes) {\n // Exact match\n if (trimmedPath === routeKey) {\n result = { routeKey, propertyPath: '' }\n found = true\n break\n }\n\n // Route key with property path\n if (trimmedPath.startsWith(`${routeKey}.`)) {\n const propertyPath = trimmedPath.substring(routeKey.length + 1)\n result = { routeKey, propertyPath }\n found = true\n break\n }\n }\n\n if (!found) {\n // No route key found, treat entire path as property path\n result = { routeKey: null, propertyPath: trimmedPath }\n }\n\n // Cache the result\n if (routeParsingCache.size >= ROUTE_PARSING_CACHE_MAX_SIZE) {\n // Clean cache by removing oldest entries\n const entries = Array.from(routeParsingCache.entries())\n entries.sort((a, b) => a[1].timestamp - b[1].timestamp)\n const toRemove = Math.floor(entries.length * CACHE_EVICTION_RATIO)\n for (let i = 0; i < toRemove; i++) {\n routeParsingCache.delete(entries[i][0])\n }\n }\n\n routeParsingCache.set(cacheKey, {\n routeKey: result.routeKey,\n propertyPath: result.propertyPath,\n timestamp: Date.now(),\n })\n\n return result\n}\n\n// Simple cache for parsed templates (max 100 entries)\nconst templateCache = new Map<string, string>()\nconst MAX_CACHE_SIZE = 100\n\n// Cache for fallback lookups to improve performance (moved to module level to prevent memory leaks)\nconst fallbackCache = new Map<\n string,\n { routeKey: string; value: unknown; timestamp: number }\n>()\nconst FALLBACK_CACHE_MAX_SIZE = 50\n\n// Route parsing cache for performance optimization\nconst routeParsingCache = new Map<\n string,\n { routeKey: string | null; propertyPath: string; timestamp: number }\n>()\nconst ROUTE_PARSING_CACHE_MAX_SIZE = 100\n\n// WeakMap for stable dataContext hashing - prevents repeated JSON.stringify\nconst dataContextHashCache = new WeakMap<object, string>()\nlet hashCounter = 0\n\n/**\n * Safely gets a nested value from an object using dot notation path\n * Supports array indexing with [index] syntax\n * @param obj - The object to traverse\n * @param path - Dot notation path (e.g., \"user.name\" or \"items[0].title\")\n * @param visited - Set to track visited objects for circular reference protection\n * @returns The resolved value or undefined if not found\n */\nfunction getNestedValue(\n obj: unknown,\n path: string,\n visited = new WeakSet()\n): unknown {\n return path.split('.').reduce((current, key) => {\n if (!current || typeof current !== 'object') {\n return\n }\n\n // Protect against circular references\n if (visited.has(current as WeakKey)) {\n console.warn('Circular reference detected in data connector path:', path)\n return\n }\n\n // Add to circular reference tracking\n visited.add(current as WeakKey)\n\n // Handle array indexing like items[0] or items[1]\n const arrayMatch = key.match(ARRAY_INDEX_REGEX)\n if (arrayMatch) {\n const [, arrayKey, index] = arrayMatch\n const arrayObj = (current as Record<string, unknown>)[arrayKey]\n if (Array.isArray(arrayObj)) {\n const indexNum = Number.parseInt(index, 10)\n if (indexNum >= 0 && indexNum < arrayObj.length) {\n return arrayObj[indexNum]\n }\n }\n return\n }\n\n // Handle regular object property access with security validation\n if (!isSafePropertyName(key)) {\n console.warn(`Unsafe property access attempted: ${key}`)\n return\n }\n\n return current !== null && key in current\n ? (current as Record<string, unknown>)[key]\n : undefined\n }, obj)\n}\n\n/**\n * Sanitizes a string value to prevent XSS attacks\n * @param value - The value to sanitize\n * @returns Sanitized string safe for HTML rendering\n */\nfunction sanitizeValue(value: unknown): string {\n if (value === null || value === undefined) {\n return ''\n }\n\n const stringValue = String(value)\n\n // Basic HTML entity encoding to prevent XSS\n return stringValue\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#x27;')\n .replace(/\\//g, '&#x2F;')\n}\n\n/**\n * Creates a stable hash for dataContext object\n * Uses WeakMap to cache hash per object reference (no serialization needed)\n */\nfunction getDataContextHash(data: Record<string, unknown>): string {\n if (!dataContextHashCache.has(data)) {\n // Generate unique hash for this dataContext instance\n dataContextHashCache.set(data, `ctx_${++hashCounter}`)\n }\n const hash = dataContextHashCache.get(data)\n return hash || `ctx_${++hashCounter}`\n}\n\n/**\n * Creates a safe cache key from content and data\n * Uses stable hashing instead of JSON.stringify for massive performance gain\n */\nfunction createCacheKey(\n content: string,\n data: Record<string, unknown>\n): string {\n // Use stable hash instead of expensive JSON.stringify\n const dataHash = getDataContextHash(data)\n return `${content}:${dataHash}`\n}\n\n/**\n * Resolves data from the flat route-keyed data context\n * Enhanced to support complex route patterns with special characters\n * Supports: {{root.layout.shop.name}}, {{routes/($locale)._index.data}}, {{routes/($locale).blogs.$handle.$article.content}}\n */\nfunction resolveDataFromContext(\n path: string,\n dataContext: DataContext | null | undefined\n): unknown {\n if (!dataContext) {\n return\n }\n\n const trimmedPath = path.trim()\n\n // Use intelligent route parsing to separate route key from property path\n const { routeKey, propertyPath } = parseRouteAndProperty(\n trimmedPath,\n dataContext\n )\n\n // If we found a specific route key, resolve from that route's data\n if (routeKey && dataContext[routeKey]) {\n const routeData = dataContext[routeKey]\n if (typeof routeData === 'object' && routeData !== null) {\n if (propertyPath) {\n return getNestedValue(routeData, propertyPath)\n }\n return routeData\n }\n }\n\n // Fallback: search across all route data for backward compatibility\n // This handles cases like {{shop.name}} without route prefix\n\n // Check cache first\n const cachedResult = fallbackCache.get(trimmedPath)\n if (cachedResult && dataContext[cachedResult.routeKey]) {\n const value = getNestedValue(\n dataContext[cachedResult.routeKey],\n trimmedPath\n )\n if (value !== undefined) {\n // Update timestamp on cache hit\n cachedResult.timestamp = Date.now()\n return value\n }\n }\n\n // Search with priority order (most common routes first)\n const priorityRoutes = ['root', 'routes/product', 'routes/collection']\n const allRoutes = [\n ...priorityRoutes,\n ...Object.keys(dataContext).filter((k) => !priorityRoutes.includes(k)),\n ]\n\n for (const routeKey of allRoutes) {\n const routeData = dataContext[routeKey]\n if (routeData && typeof routeData === 'object' && routeData !== null) {\n const value = getNestedValue(routeData, trimmedPath)\n if (value !== undefined) {\n // Clean cache if it's getting too large\n if (fallbackCache.size >= FALLBACK_CACHE_MAX_SIZE) {\n const entries = Array.from(fallbackCache.entries())\n entries.sort((a, b) => a[1].timestamp - b[1].timestamp)\n // Remove oldest 25% of entries\n const toRemove = Math.floor(entries.length * CACHE_EVICTION_RATIO)\n for (let i = 0; i < toRemove; i++) {\n fallbackCache.delete(entries[i][0])\n }\n }\n fallbackCache.set(trimmedPath, {\n routeKey,\n value,\n timestamp: Date.now(),\n })\n return value\n }\n }\n }\n\n // Final fallback: try direct access (for non-route-keyed legacy data)\n return getNestedValue(dataContext, trimmedPath)\n}\n\n/**\n * Replaces data connector placeholders in content with actual values from data context\n * Supports {{path}} syntax with dot notation, array indexing, and route prefixes\n *\n * Enhanced syntax:\n * - {{root.siteSettings.title}} - Access root route data\n * - {{layout.navigation.items}} - Access layout route data\n * - {{parent.category.name}} - Access parent route data\n * - {{current.product.title}} - Access current route data\n * - {{user.name}} - Auto-resolved from combined data (backward compatible)\n *\n * @param content - The content string containing {{}} placeholders\n * @param dataContext - The enhanced WeaverseDataContext with route-keyed data\n * @returns The content with placeholders replaced by actual values\n */\nexport function replaceContentDataConnectors(\n content: string,\n dataContext: DataContext | null | undefined\n): string {\n if (!dataContext || typeof content !== 'string') {\n return content\n }\n\n try {\n // Simplified caching - dataContext is already the combined data\n const cacheKey = createCacheKey(content, dataContext)\n\n const cachedContent = templateCache.get(cacheKey)\n if (cachedContent) {\n return cachedContent\n }\n\n const newContent = content.replace(TEMPLATE_REGEX, (match, path) => {\n try {\n const value = resolveDataFromContext(path, dataContext)\n\n if (value === undefined || value === null) {\n return match // Return original placeholder if value not found\n }\n\n return sanitizeValue(value)\n } catch (pathError) {\n console.warn(\n `Error resolving data connector path \"${path}\":`,\n pathError\n )\n return match\n }\n })\n\n // Cache the result (with size limit)\n if (templateCache.size >= MAX_CACHE_SIZE) {\n const firstKey = templateCache.keys().next().value\n templateCache.delete(firstKey)\n }\n templateCache.set(cacheKey, newContent)\n\n return newContent\n } catch (error) {\n console.warn('Error processing data connectors:', error, { content })\n return content\n }\n}\n\n/**\n * Fast check if data contains any {{...}} placeholders\n * Returns true if any string value contains the pattern\n * This is MUCH faster than processing and allows early exit\n *\n * IMPORTANT: Uses global TEMPLATE_REGEX, must reset lastIndex\n */\nfunction hasPlaceholders(data: unknown, visited = new WeakSet()): boolean {\n if (typeof data === 'string') {\n // Reset regex state before testing to ensure consistent results\n TEMPLATE_REGEX.lastIndex = 0\n return TEMPLATE_REGEX.test(data)\n }\n\n if (typeof data !== 'object' || data === null) {\n return false\n }\n\n // Skip Date objects - they can't contain placeholders\n if (data instanceof Date) {\n return false\n }\n\n // Protect against circular references\n if (visited.has(data as WeakKey)) {\n return false\n }\n visited.add(data as WeakKey)\n\n try {\n if (Array.isArray(data)) {\n return data.some((item) => hasPlaceholders(item, visited))\n }\n\n // Check object values safely (skip property access errors)\n for (const key of Object.keys(data)) {\n try {\n const value = (data as Record<string, unknown>)[key]\n if (hasPlaceholders(value, visited)) {\n return true\n }\n } catch {\n // Ignore property access errors - continue checking other properties\n }\n }\n\n return false\n } finally {\n visited.delete(data as WeakKey)\n }\n}\n\n/**\n * Recursively replaces data connector placeholders in any data structure\n * IMMUTABLE: Creates deep copies during processing to avoid mutating original data\n * Handles strings, objects, arrays, and nested combinations\n *\n * PERFORMANCE: Now includes early exit if no placeholders detected\n *\n * @param data - The data to process (string, object, array, or primitive)\n * @param dataContext - The data context for replacements\n * @param visited - Set to track visited objects for circular reference protection\n * @param forceClone - Internal flag to force cloning even if no placeholders (for parent immutability)\n * @returns IMMUTABLE copy of the data with all string placeholders replaced\n */\nexport function replaceContentDataConnectorsDeep<T>(\n data: T,\n dataContext: DataContext | null | undefined,\n visited = new WeakSet(),\n forceClone = false\n): T {\n if (!dataContext) {\n return data\n }\n\n const dataHasPlaceholders = hasPlaceholders(data, new WeakSet())\n\n // PERFORMANCE: Fast check - if no placeholders exist and not forced to clone, skip ALL processing\n // This saves 90%+ of CPU time for components without data connectors\n if (!(dataHasPlaceholders || forceClone)) {\n return data\n }\n\n // Handle primitive types - no cloning needed for primitives\n if (typeof data === 'string') {\n return replaceContentDataConnectors(data, dataContext) as T\n }\n\n if (typeof data !== 'object' || data === null) {\n return data\n }\n\n // Protect against circular references\n if (visited.has(data as WeakKey)) {\n console.warn(\n 'Circular reference detected in deep data connector replacement'\n )\n return data\n }\n\n // Add to circular reference tracking\n visited.add(data as WeakKey)\n\n try {\n // Handle special objects that should be cloned as-is\n if (data instanceof Date) {\n // Date objects can't contain placeholders, but clone if forced (parent has placeholders)\n // or if somehow detected (shouldn't happen but be safe)\n if (forceClone || dataHasPlaceholders) {\n return new Date(data.getTime()) as T\n }\n return data\n }\n\n // Handle arrays - create new array with processed items\n // Force clone children if parent has placeholders (for immutability)\n if (Array.isArray(data)) {\n const result = data.map((item) =>\n replaceContentDataConnectorsDeep(\n item,\n dataContext,\n visited,\n dataHasPlaceholders\n )\n ) as T\n return result\n }\n\n // Handle plain objects - create new object with processed values\n // Force clone children if parent has placeholders (for immutability)\n const result = {} as T\n\n // Use Object.entries with try-catch per property to handle getter errors\n for (const key of Object.keys(data)) {\n try {\n const value = (data as Record<string, unknown>)[key]\n ;(result as Record<string, unknown>)[key] =\n replaceContentDataConnectorsDeep(\n value,\n dataContext,\n visited,\n dataHasPlaceholders\n )\n } catch (propertyError) {\n // If property access throws, skip it but continue processing\n console.warn(`Error accessing property \"${key}\":`, propertyError)\n // Don't include this property in result\n }\n }\n\n return result\n } catch (error) {\n console.warn('Error in deep data connector replacement:', error)\n return data\n } finally {\n // Remove from tracking when done processing this object\n visited.delete(data as WeakKey)\n }\n}\n","import type { Weaverse } from '@weaverse/core'\nimport clsx from 'clsx'\nimport React, { memo, useEffect, useRef } from 'react'\nimport { useItemInstance, useWeaverse } from '~/hooks'\nimport { WeaverseContextProvider, WeaverseItemContext } from './context'\nimport type { ItemComponentProps, WeaverseRootPropsType } from './types'\nimport { replaceContentDataConnectorsDeep } from './utils/data-connector'\n\nconst REACT_VERSION_THRESHOLD = 18\nconst reactVersion = Number(React.version?.split('.')[0]) || 0\n\n// Create a safe version of useSyncExternalStore that works in both client and server environments\nexport const useSafeExternalStore = (\n subscribe: any,\n getSnapshot: any,\n getServerSnapshot: any = getSnapshot\n) => {\n // In server environment or during SSR, just return the snapshot directly\n if (typeof window === 'undefined') {\n return getServerSnapshot()\n }\n\n // In client environment, use React.useSyncExternalStore if available (React 18+)\n if (React.useSyncExternalStore) {\n // biome-ignore lint/correctness/useHookAtTopLevel: <$>\n return React.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)\n }\n\n // Fallback for older React versions - just return the current snapshot\n return getSnapshot()\n}\n\n/**\n * Determines the root element ID for the Weaverse component tree.\n * Falls back through multiple strategies to ensure a valid root is always found:\n * 1. Use explicit rootId from context.data if available\n * 2. Find the first element with type 'main' in items array\n * 3. Use projectId as final fallback\n */\nconst getRootId = (context: Weaverse): string => {\n // Strategy 1: Explicit rootId\n if (context.data.rootId) {\n return context.data.rootId\n }\n\n // Strategy 2: Find main element\n let mainItem = context.data?.items?.find((item) => item.type === 'main')\n if (mainItem?.id) {\n return mainItem.id\n }\n\n // Strategy 3: Fallback to projectId\n return context.projectId\n}\nexport const WeaverseRoot = memo(({ context }: WeaverseRootPropsType) => {\n const data = useSafeExternalStore(\n context.subscribe,\n context.getSnapShot,\n context.getSnapShot\n )\n const rootRef = useRef<HTMLElement>(null)\n\n useEffect(() => {\n context.contentRootElement = rootRef.current\n }, [context])\n\n const eventHandlers = context?.studioBridge?.eventHandlers || {}\n\n if (context.projectId) {\n return (\n <div\n className=\"weaverse-content-root\"\n {...eventHandlers}\n data-weaverse-project-id={context.projectId}\n data-weaverse-template-id={data.id}\n ref={rootRef}\n >\n <WeaverseContextProvider value={context}>\n <ItemInstance id={getRootId(context)} parentId={''} />\n </WeaverseContextProvider>\n </div>\n )\n }\n return null\n})\nWeaverseRoot.displayName = 'WeaverseRoot'\nconst ItemComponent = memo(({ instance }: ItemComponentProps) => {\n const context = useWeaverse()\n const { elementRegistry } = context\n const data = useSafeExternalStore(\n instance.subscribe,\n instance.getSnapShot,\n instance.getSnapShot\n )\n const {\n id,\n type,\n childIds = [],\n children = [],\n\n createdAt,\n updatedAt,\n deletedAt,\n css,\n __hidden,\n // Need to get rid of this `data` property\n data: _,\n ...rest\n } = data\n\n // Replace data connectors in all component data (handles strings, objects, and arrays recursively)\n // IMMUTABLE: Process the entire rest object to avoid mutating original content\n const processedRest = replaceContentDataConnectorsDeep(\n rest,\n context.dataContext\n )\n\n useEffect(() => {\n if (!instance.ref.current) {\n // Fallback `ref` if the element isn't created by `React.forwardRef`\n Object.assign(instance.ref, {\n current: document.querySelector(`[data-wv-id=\"${id}\"]`),\n })\n }\n }, [instance, id])\n\n if (__hidden) {\n return null\n }\n\n const Element = elementRegistry.get(type)\n\n if (Element?.Component) {\n const Component = Element.Component\n Component.displayName = type\n if (\n Component.$$typeof === Symbol.for('react.forward_ref') ||\n reactVersion > REACT_VERSION_THRESHOLD\n ) {\n processedRest.ref = instance.ref\n }\n const childItems = children?.length\n ? children\n : childIds?.length\n ? childIds.map((cid: string) => ({ id: cid }))\n : []\n\n const renderChildren = childItems.map(\n (item: { id: string }, index: number) => (\n <ItemInstance id={item.id} key={`${item.id}-${index}`} parentId={id} />\n )\n )\n\n return (\n <Component\n {...processedRest}\n children={renderChildren.length ? renderChildren : undefined}\n className={clsx(processedRest.data?.className)}\n data-wv-id={id}\n data-wv-type={type}\n key={id}\n />\n )\n }\n instance._store.deleted = true\n return null\n})\nItemComponent.displayName = 'WeaverseComponent'\n\nconst ItemInstance = memo(\n ({ id, parentId }: { id: string; parentId: string }) => {\n const instance = useItemInstance(id)\n if (!instance) {\n return <div style={{ display: 'none' }}>Item instance {id} not found</div>\n }\n return (\n <WeaverseItemContext.Provider value={{ parentId, id }}>\n <ItemComponent instance={instance} key={id} />\n </WeaverseItemContext.Provider>\n )\n }\n)\nItemInstance.displayName = 'WeaverseInstanceProvider'\n"],"mappings":";AAAA,cAAc;;;ACCd,SAAS,qBAAqB;AAEvB,IAAI,kBAAkB,cAAwB,CAAC,CAAa;AAC5D,IAAI,0BAA0B,gBAAgB;AAC9C,IAAI,sBAAsB,cAG9B,EAAE,IAAI,IAAI,UAAU,GAAG,CAAC;;;ACR3B,SAAS,gBAAwC;AACjD,SAAS,kBAAkB;;;ACI3B,IAAM,iBAAiB;AACvB,IAAM,oBAAoB;AAG1B,IAAM,uBAAuB;AAM7B,SAAS,mBAAmB,KAAsB;AAEhD,QAAM,oBAAoB,CAAC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AAAA,SAAU;AAAA,IACtE;AACA,WACE,oBAAC,oBAAoB,UAApB,EAA6B,OAAO,EAAE,UAAU,GAAG,GAClD,8BAAC,iBAAc,YAAyB,EAAI,GAC9C;AAAA,EAEJ;AACF;AACA,aAAa,cAAc;","names":["routeKey","result","id"]}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@weaverse/react",
3
3
  "author": "Weaverse Team",
4
4
  "description": "React bindings for Weaverse",
5
- "version": "5.8.3",
5
+ "version": "5.8.5",
6
6
  "license": "MIT",
7
7
  "main": "dist/index.js",
8
8
  "typings": "dist/index.d.ts",
@@ -26,7 +26,8 @@
26
26
  "build": "tsup",
27
27
  "clean": "rimraf dist",
28
28
  "test": "vitest --run",
29
- "test:watch": "vitest --watch"
29
+ "test:watch": "vitest --watch",
30
+ "typecheck": "tsc --noEmit"
30
31
  },
31
32
  "tsup": {
32
33
  "entry": [
@@ -42,7 +43,7 @@
42
43
  "outDir": "dist"
43
44
  },
44
45
  "dependencies": {
45
- "@weaverse/core": "5.8.3",
46
+ "@weaverse/core": "5.8.5",
46
47
  "clsx": "^2.1.1",
47
48
  "react": ">=18",
48
49
  "react-dom": ">=18"