@preprio/prepr-nextjs 2.0.0-alpha.10 → 2.0.0-alpha.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +248 -38
- package/dist/chunk-6FNC3XMI.js +45 -0
- package/dist/chunk-DI26GYQY.js +201 -0
- package/dist/chunk-MKSF2TOK.js +2 -0
- package/dist/chunk-MKSF2TOK.js.map +1 -0
- package/dist/metafile-cjs.json +1 -1
- package/dist/metafile-esm.json +1 -1
- package/dist/middleware/index.cjs +1 -1
- package/dist/middleware/index.cjs.map +1 -1
- package/dist/middleware/index.js +1 -1
- package/dist/react/index.cjs +6 -1
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.d.cts +47 -9
- package/dist/react/index.d.ts +47 -9
- package/dist/react/index.js +6 -1
- package/dist/react/index.js.map +1 -1
- package/dist/server/index.cjs +2 -2
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.d.cts +14 -3
- package/dist/server/index.d.ts +14 -3
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/types/index.d.cts +3 -3
- package/dist/types/index.d.ts +3 -3
- package/dist/utils/index.cjs +1 -1
- package/dist/utils/index.cjs.map +1 -1
- package/dist/utils/index.d.cts +6 -2
- package/dist/utils/index.d.ts +6 -2
- package/dist/utils/index.js +1 -1
- package/dist/utils/index.js.map +1 -1
- package/package.json +8 -17
- package/dist/chunk-LVXDK2EY.js +0 -2
- package/dist/chunk-LVXDK2EY.js.map +0 -1
package/dist/utils/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/errors.ts","../../src/utils/dom.ts","../../src/utils/debug.ts","../../src/utils/performance.ts","../../src/utils/index.ts"],"names":["StegaError","createErrorInfo","type","context","error","additionalData","handleStegaError","errorInfo","handleDOMError","handleContextError","contextName","DOMService","tag","className","element","styles","property","value","rect","x1","y1","x2","y2","pointX","pointY","elements","closestElement","minDistance","distance","event","handler","options","DebugLogger","_DebugLogger","__spreadValues","message","args","prefix","scopeName","__spreadProps","globalDebugLogger","initDebugLogger","enabled","getDebugLogger","debugLog","debugWarn","debugError","createScopedLogger","throttle","func","delay","timeoutId","lastExecTime","throttledFunc","currentTime","timeSinceLastExec","debounce","debouncedFunc","createElementCache","query","ttl","cache","lastCacheTime","now","cn","inputs","twMerge","clsx","sendPreprEvent","data"],"mappings":"+GAAaA,CAAAA,CAAa,CACxB,cAAe,qBAAA,CACf,cAAA,CAAgB,uBAChB,uBAAA,CAAyB,yBAAA,CACzB,kBAAmB,mBACrB,EAqBO,SAASC,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACAC,EACAC,CAAAA,CACW,CACX,OAAO,CACL,IAAA,CAAAH,EACA,OAAA,CAAAC,CAAAA,CACA,OAAA,CAASC,CAAAA,CAAM,OAAA,CACf,SAAA,CAAW,IAAI,IAAA,EAAK,CAAE,aAAY,CAClC,KAAA,CAAOA,EAAM,KAAA,CACb,cAAA,CAAAC,CACF,CACF,CAEO,SAASC,EACdF,CAAAA,CACAD,CAAAA,CACAE,EACA,CACA,IAAME,EAAYN,CAAAA,CAChBD,CAAAA,CAAW,cACXG,CAAAA,CACAC,CAAAA,CACAC,CACF,CAAA,CAEA,OAAA,OAAA,CAAQ,MAAM,cAAA,CAAgBE,CAAS,EAGnC,OAAA,CAAQ,GAAA,CAAI,QAAA,CAITA,CACT,CAEO,SAASC,EAAeJ,CAAAA,CAAcD,CAAAA,CAAiB,CAC5D,IAAMI,CAAAA,CAAYN,EAChBD,CAAAA,CAAW,uBAAA,CACXG,CAAAA,CACAC,CACF,CAAA,CAEA,OAAA,OAAA,CAAQ,MAAM,YAAA,CAAcG,CAAS,EAC9BA,CACT,CAEO,SAASE,CAAAA,CAAmBC,CAAAA,CAAqB,CACtD,IAAMN,CAAAA,CAAQ,IAAI,MAAM,CAAA,EAAGM,CAAW,mCAAmC,CAAA,CACnEH,CAAAA,CAAYN,EAChBD,CAAAA,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AAM,CACX,IAAMC,CAAAA,CAAM,IAAA,CAAK,KAAI,CACrB,OAAA,CAAI,CAACF,CAAAA,EAASE,CAAAA,CAAMD,EAAgBF,CAAAA,IAClCC,CAAAA,CAAQ,QAAA,CAAS,gBAAA,CAAoBF,CAAK,CAAA,CAC1CG,EAAgBC,CAAAA,CAAAA,CAEXF,CACT,CACF,CC/FO,SAASG,KAAMC,CAAAA,CAAsB,CAC1C,OAAOC,OAAAA,CAAQC,IAAAA,CAAKF,CAAM,CAAC,CAC7B,CAeO,SAASG,CAAAA,CACdvC,CAAAA,CACAwC,EACM,CACF,OAAO,MAAA,EAAW,WAAA,EAAe,MAAA,CAAO,MAAA,EAC1C,OAAO,MAAA,CAAO,WAAA,CACZnC,EAAA,CACE,IAAA,CAAM,oBACN,KAAA,CAAAL,CAAAA,CAAAA,CACGwC,CAAAA,CAAAA,CAEL,GACF,EAEJ","file":"index.js","sourcesContent":["export const StegaError = {\n DECODE_FAILED: 'STEGA_DECODE_FAILED',\n INVALID_FORMAT: 'STEGA_INVALID_FORMAT',\n DOM_MANIPULATION_FAILED: 'DOM_MANIPULATION_FAILED',\n CONTEXT_NOT_FOUND: 'CONTEXT_NOT_FOUND',\n} as const;\n\nexport type StegaErrorType = (typeof StegaError)[keyof typeof StegaError];\n\n// Define specific types for error additional data\nexport interface ErrorAdditionalData {\n input?: string;\n element?: HTMLElement;\n context?: string;\n [key: string]: string | HTMLElement | undefined;\n}\n\nexport interface ErrorInfo {\n type: StegaErrorType;\n context: string;\n message: string;\n timestamp: string;\n stack?: string;\n additionalData?: ErrorAdditionalData;\n}\n\nexport function createErrorInfo(\n type: StegaErrorType,\n context: string,\n error: Error,\n additionalData?: ErrorAdditionalData\n): ErrorInfo {\n return {\n type,\n context,\n message: error.message,\n timestamp: new Date().toISOString(),\n stack: error.stack,\n additionalData,\n };\n}\n\nexport function handleStegaError(\n error: Error,\n context: string,\n additionalData?: ErrorAdditionalData\n) {\n const errorInfo = createErrorInfo(\n StegaError.DECODE_FAILED,\n context,\n error,\n additionalData\n );\n\n console.error('Stega Error:', errorInfo);\n\n // In production, you might want to send this to an error tracking service\n if (process.env.NODE_ENV === 'production') {\n // sendToErrorTrackingService(errorInfo);\n }\n\n return errorInfo;\n}\n\nexport function handleDOMError(error: Error, context: string) {\n const errorInfo = createErrorInfo(\n StegaError.DOM_MANIPULATION_FAILED,\n context,\n error\n );\n\n console.error('DOM Error:', errorInfo);\n return errorInfo;\n}\n\nexport function handleContextError(contextName: string) {\n const error = new Error(`${contextName} must be used within its provider`);\n const errorInfo = createErrorInfo(\n StegaError.CONTEXT_NOT_FOUND,\n contextName,\n error\n );\n\n console.error('Context Error:', errorInfo);\n throw error;\n}\n","import { handleDOMError } from './errors';\n\nexport class DOMService {\n /**\n * Creates an HTML element with specified tag and class name\n */\n static createElement(tag: string, className: string): HTMLElement {\n try {\n const element = document.createElement(tag);\n element.className = className;\n return element;\n } catch (error) {\n handleDOMError(error as Error, 'createElement');\n throw error;\n }\n }\n\n /**\n * Appends an element to the document body\n */\n static appendToBody(element: HTMLElement): void {\n try {\n document.body.appendChild(element);\n } catch (error) {\n handleDOMError(error as Error, 'appendToBody');\n throw error;\n }\n }\n\n /**\n * Removes an element from the document body\n */\n static removeFromBody(element: HTMLElement): void {\n try {\n if (element.parentNode) {\n element.parentNode.removeChild(element);\n }\n } catch (error) {\n handleDOMError(error as Error, 'removeFromBody');\n throw error;\n }\n }\n\n /**\n * Sets multiple CSS properties on an element\n */\n static setElementStyles(\n element: HTMLElement,\n styles: Record<string, string>\n ): void {\n try {\n Object.entries(styles).forEach(([property, value]) => {\n element.style.setProperty(property, value);\n });\n } catch (error) {\n handleDOMError(error as Error, 'setElementStyles');\n throw error;\n }\n }\n\n /**\n * Gets the bounding rectangle of an element\n */\n static getElementRect(element: HTMLElement): DOMRect {\n try {\n return element.getBoundingClientRect();\n } catch (error) {\n handleDOMError(error as Error, 'getElementRect');\n throw error;\n }\n }\n\n /**\n * Checks if an element is in the viewport\n */\n static isElementInViewport(element: HTMLElement): boolean {\n try {\n const rect = this.getElementRect(element);\n return (\n rect.top >= 0 &&\n rect.left >= 0 &&\n rect.bottom <=\n (window.innerHeight || document.documentElement.clientHeight) &&\n rect.right <=\n (window.innerWidth || document.documentElement.clientWidth)\n );\n } catch (error) {\n handleDOMError(error as Error, 'isElementInViewport');\n return false;\n }\n }\n\n /**\n * Calculates distance between two points\n */\n static calculateDistance(\n x1: number,\n y1: number,\n x2: number,\n y2: number\n ): number {\n return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));\n }\n\n /**\n * Finds the closest element to a point from a list of elements\n */\n static findClosestElement(\n pointX: number,\n pointY: number,\n elements: NodeListOf<Element>\n ): HTMLElement | null {\n try {\n let closestElement: HTMLElement | null = null;\n let minDistance = Infinity;\n\n elements.forEach(element => {\n const rect = this.getElementRect(element as HTMLElement);\n const distance = this.calculateDistance(\n pointX,\n pointY,\n rect.left + rect.width / 2,\n rect.top + rect.height / 2\n );\n\n if (distance < minDistance) {\n minDistance = distance;\n closestElement = element as HTMLElement;\n }\n });\n\n return closestElement;\n } catch (error) {\n handleDOMError(error as Error, 'findClosestElement');\n return null;\n }\n }\n\n /**\n * Safely adds event listeners\n */\n static addEventListener(\n element: EventTarget,\n event: string,\n handler: EventListener,\n options?: AddEventListenerOptions\n ): void {\n try {\n element.addEventListener(event, handler, options);\n } catch (error) {\n handleDOMError(error as Error, 'addEventListener');\n throw error;\n }\n }\n\n /**\n * Safely removes event listeners\n */\n static removeEventListener(\n element: EventTarget,\n event: string,\n handler: EventListener,\n options?: EventListenerOptions\n ): void {\n try {\n element.removeEventListener(event, handler, options);\n } catch (error) {\n handleDOMError(error as Error, 'removeEventListener');\n throw error;\n }\n }\n}\n","/**\n * Debug utility for Prepr Next.js package\n * Provides centralized debug logging with performance optimizations\n */\n\n// Define specific types for debug arguments\nexport type DebugArg = string | number | boolean | null | undefined | object;\n\ninterface DebugOptions {\n enabled: boolean;\n prefix?: string;\n}\n\nclass DebugLogger {\n private options: DebugOptions;\n\n constructor(options: DebugOptions) {\n this.options = {\n prefix: '[Prepr]',\n ...options,\n };\n }\n\n /**\n * Log a debug message if debug is enabled\n */\n log(message: string, ...args: DebugArg[]): void {\n if (!this.options.enabled) return;\n\n const prefix = this.options.prefix;\n console.log(`${prefix} ${message}`, ...args);\n }\n\n /**\n * Log a debug warning if debug is enabled\n */\n warn(message: string, ...args: DebugArg[]): void {\n if (!this.options.enabled) return;\n\n const prefix = this.options.prefix;\n console.warn(`${prefix} ${message}`, ...args);\n }\n\n /**\n * Log a debug error if debug is enabled\n */\n error(message: string, ...args: DebugArg[]): void {\n if (!this.options.enabled) return;\n\n const prefix = this.options.prefix;\n console.error(`${prefix} ${message}`, ...args);\n }\n\n /**\n * Create a scoped logger with additional context\n */\n scope(scopeName: string): DebugLogger {\n return new DebugLogger({\n ...this.options,\n prefix: `${this.options.prefix}[${scopeName}]`,\n });\n }\n}\n\n// Global debug instance\nlet globalDebugLogger: DebugLogger | null = null;\n\n/**\n * Initialize the debug logger\n */\nexport function initDebugLogger(enabled: boolean = false): void {\n globalDebugLogger = new DebugLogger({ enabled });\n}\n\n/**\n * Get the debug logger instance\n */\nexport function getDebugLogger(): DebugLogger {\n if (!globalDebugLogger) {\n // Fallback to disabled logger if not initialized\n globalDebugLogger = new DebugLogger({ enabled: false });\n }\n return globalDebugLogger;\n}\n\n/**\n * Convenience function for logging\n */\nexport function debugLog(message: string, ...args: DebugArg[]): void {\n getDebugLogger().log(message, ...args);\n}\n\n/**\n * Convenience function for warning\n */\nexport function debugWarn(message: string, ...args: DebugArg[]): void {\n getDebugLogger().warn(message, ...args);\n}\n\n/**\n * Convenience function for errors\n */\nexport function debugError(message: string, ...args: DebugArg[]): void {\n getDebugLogger().error(message, ...args);\n}\n\n/**\n * Create a scoped debug logger\n */\nexport function createScopedLogger(scopeName: string): DebugLogger {\n return getDebugLogger().scope(scopeName);\n}\n","// Performance utilities\n\n/**\n * Throttled function with cancellation support\n */\nexport interface ThrottledFunction<T extends (...args: any[]) => any> {\n (...args: Parameters<T>): void;\n cancel(): void;\n}\n\n/**\n * Improved throttle function with better memory management and cancellation\n * @param func - The function to throttle\n * @param delay - The delay in milliseconds\n * @returns Throttled function with cancel method\n */\nexport function throttle<T extends (...args: any[]) => any>(\n func: T,\n delay: number\n): ThrottledFunction<T> {\n let timeoutId: NodeJS.Timeout | null = null;\n let lastExecTime = 0;\n\n const throttledFunc = ((...args: Parameters<T>) => {\n const currentTime = Date.now();\n const timeSinceLastExec = currentTime - lastExecTime;\n\n if (timeSinceLastExec >= delay) {\n func(...args);\n lastExecTime = currentTime;\n } else {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n timeoutId = setTimeout(() => {\n func(...args);\n lastExecTime = Date.now();\n timeoutId = null;\n }, delay - timeSinceLastExec);\n }\n }) as ThrottledFunction<T>;\n\n throttledFunc.cancel = () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n };\n\n return throttledFunc;\n}\n\n/**\n * Debounce function with cancellation support\n * @param func - The function to debounce\n * @param delay - The delay in milliseconds\n * @returns Debounced function with cancel method\n */\nexport function debounce<T extends (...args: any[]) => any>(\n func: T,\n delay: number\n): ThrottledFunction<T> {\n let timeoutId: NodeJS.Timeout | null = null;\n\n const debouncedFunc = ((...args: Parameters<T>) => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n timeoutId = setTimeout(() => {\n func(...args);\n timeoutId = null;\n }, delay);\n }) as ThrottledFunction<T>;\n\n debouncedFunc.cancel = () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n };\n\n return debouncedFunc;\n}\n\n// Simple DOM element cache for querySelectorAll\nexport function createElementCache<T extends Element = Element>(\n query: string,\n ttl: number = 1000\n) {\n let cache: NodeListOf<T> | null = null;\n let lastCacheTime = 0;\n return () => {\n const now = Date.now();\n if (!cache || now - lastCacheTime > ttl) {\n cache = document.querySelectorAll<T>(query);\n lastCacheTime = now;\n }\n return cache;\n };\n}\n","import { ClassValue, clsx } from 'clsx';\nimport { twMerge } from 'tailwind-merge';\nimport { PreprEventType } from '../types';\n\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs));\n}\n\n// Define specific types for Prepr events\nexport interface PreprEventData {\n readonly segment?: string;\n readonly variant?: string;\n readonly editMode?: boolean;\n readonly [key: string]: string | boolean | number | undefined;\n}\n\n/**\n * Sends a Prepr event to the parent window\n * @param event - The event type to send\n * @param data - Optional event data\n */\nexport function sendPreprEvent(\n event: PreprEventType,\n data?: PreprEventData\n): void {\n if (typeof window !== 'undefined' && window.parent) {\n window.parent.postMessage(\n {\n name: 'prepr_preview_bar',\n event,\n ...data,\n },\n '*'\n );\n }\n}\n\n// Export error handling utilities\nexport * from './errors';\n\n// Export DOM service\nexport * from './dom';\n\n// Export debug utilities\nexport * from './debug';\n\n// Export performance utilities\nexport * from './performance';\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/errors.ts","../../src/utils/dom.ts","../../src/utils/debug.ts","../../src/utils/performance.ts","../../src/utils/index.ts"],"names":["StegaError","createErrorInfo","type","context","error","additionalData","handleStegaError","errorInfo","handleDOMError","handleContextError","contextName","DOMService","tag","className","element","styles","property","value","rect","x1","y1","x2","y2","pointX","pointY","elements","closestElement","minDistance","distance","event","handler","options","DebugLogger","_DebugLogger","__spreadValues","_a","_b","globalDebugLogger","message","args","prefix","scopeName","__spreadProps","initDebugLogger","enabled","getDebugLogger","debugLog","debugWarn","debugError","createScopedLogger","throttle","func","delay","timeoutId","lastExecTime","throttledFunc","currentTime","timeSinceLastExec","debounce","debouncedFunc","createElementCache","query","ttl","cache","lastCacheTime","now","cn","inputs","twMerge","clsx","sendPreprEvent","data"],"mappings":"oGAAO,IAAMA,CAAAA,CAAa,CACxB,aAAA,CAAe,sBACf,cAAA,CAAgB,sBAAA,CAChB,wBAAyB,yBAAA,CACzB,iBAAA,CAAmB,mBACrB,EAqBO,SAASC,CAAAA,C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AA,GACF,aAAaA,CAAS,CAAA,CACtBA,EAAY,IAAA,EAEhB,CAAA,CAEOM,CACT,CAGO,SAASC,CAAAA,CACdC,EACAC,CAAAA,CAAc,GAAA,CACd,CACA,IAAIC,CAAAA,CAA8B,IAAA,CAC9BC,EAAgB,CAAA,CACpB,OAAO,IAAM,CACX,IAAMC,CAAAA,CAAM,KAAK,GAAA,EAAI,CACrB,QAAI,CAACF,CAAAA,EAASE,EAAMD,CAAAA,CAAgBF,CAAAA,IAClCC,CAAAA,CAAQ,QAAA,CAAS,gBAAA,CAAoBF,CAAK,EAC1CG,CAAAA,CAAgBC,CAAAA,CAAAA,CAEXF,CACT,CACF,CC/FO,SAASG,CAAAA,CAAAA,GAAMC,CAAAA,CAAsB,CAC1C,OAAOC,OAAAA,CAAQC,IAAAA,CAAKF,CAAM,CAAC,CAC7B,CAeO,SAASG,CAAAA,CACdzC,EACA0C,CAAAA,CACM,CACF,OAAO,MAAA,EAAW,WAAA,EAAe,MAAA,CAAO,QAC1C,MAAA,CAAO,MAAA,CAAO,WAAA,CACZrC,CAAAA,CAAA,CACE,IAAA,CAAM,oBACN,KAAA,CAAAL,CAAAA,CAAAA,CACG0C,CAAAA,CAAAA,CAEL,GACF,EAEJ","file":"index.js","sourcesContent":["export const StegaError = {\n DECODE_FAILED: 'STEGA_DECODE_FAILED',\n INVALID_FORMAT: 'STEGA_INVALID_FORMAT',\n DOM_MANIPULATION_FAILED: 'DOM_MANIPULATION_FAILED',\n CONTEXT_NOT_FOUND: 'CONTEXT_NOT_FOUND',\n} as const;\n\nexport type StegaErrorType = (typeof StegaError)[keyof typeof StegaError];\n\n// Define specific types for error additional data\nexport interface ErrorAdditionalData {\n input?: string;\n element?: HTMLElement;\n context?: string;\n [key: string]: string | HTMLElement | undefined;\n}\n\nexport interface ErrorInfo {\n type: StegaErrorType;\n context: string;\n message: string;\n timestamp: string;\n stack?: string;\n additionalData?: ErrorAdditionalData;\n}\n\nexport function createErrorInfo(\n type: StegaErrorType,\n context: string,\n error: Error,\n additionalData?: ErrorAdditionalData\n): ErrorInfo {\n return {\n type,\n context,\n message: error.message,\n timestamp: new Date().toISOString(),\n stack: error.stack,\n additionalData,\n };\n}\n\nexport function handleStegaError(\n error: Error,\n context: string,\n additionalData?: ErrorAdditionalData\n) {\n const errorInfo = createErrorInfo(\n StegaError.DECODE_FAILED,\n context,\n error,\n additionalData\n );\n\n console.error('Stega Error:', errorInfo);\n\n // In production, you might want to send this to an error tracking service\n if (process.env.NODE_ENV === 'production') {\n // sendToErrorTrackingService(errorInfo);\n }\n\n return errorInfo;\n}\n\nexport function handleDOMError(error: Error, context: string) {\n const errorInfo = createErrorInfo(\n StegaError.DOM_MANIPULATION_FAILED,\n context,\n error\n );\n\n console.error('DOM Error:', errorInfo);\n return errorInfo;\n}\n\nexport function handleContextError(contextName: string) {\n const error = new Error(`${contextName} must be used within its provider`);\n const errorInfo = createErrorInfo(\n StegaError.CONTEXT_NOT_FOUND,\n contextName,\n error\n );\n\n console.error('Context Error:', errorInfo);\n throw error;\n}\n","import { handleDOMError } from './errors';\n\nexport class DOMService {\n /**\n * Creates an HTML element with specified tag and class name\n */\n static createElement(tag: string, className: string): HTMLElement {\n try {\n const element = document.createElement(tag);\n element.className = className;\n return element;\n } catch (error) {\n handleDOMError(error as Error, 'createElement');\n throw error;\n }\n }\n\n /**\n * Appends an element to the document body\n */\n static appendToBody(element: HTMLElement): void {\n try {\n document.body.appendChild(element);\n } catch (error) {\n handleDOMError(error as Error, 'appendToBody');\n throw error;\n }\n }\n\n /**\n * Removes an element from the document body\n */\n static removeFromBody(element: HTMLElement): void {\n try {\n if (element.parentNode) {\n element.parentNode.removeChild(element);\n }\n } catch (error) {\n handleDOMError(error as Error, 'removeFromBody');\n throw error;\n }\n }\n\n /**\n * Sets multiple CSS properties on an element\n */\n static setElementStyles(\n element: HTMLElement,\n styles: Record<string, string>\n ): void {\n try {\n Object.entries(styles).forEach(([property, value]) => {\n element.style.setProperty(property, value);\n });\n } catch (error) {\n handleDOMError(error as Error, 'setElementStyles');\n throw error;\n }\n }\n\n /**\n * Gets the bounding rectangle of an element\n */\n static getElementRect(element: HTMLElement): DOMRect {\n try {\n return element.getBoundingClientRect();\n } catch (error) {\n handleDOMError(error as Error, 'getElementRect');\n throw error;\n }\n }\n\n /**\n * Checks if an element is in the viewport\n */\n static isElementInViewport(element: HTMLElement): boolean {\n try {\n const rect = this.getElementRect(element);\n return (\n rect.top >= 0 &&\n rect.left >= 0 &&\n rect.bottom <=\n (window.innerHeight || document.documentElement.clientHeight) &&\n rect.right <=\n (window.innerWidth || document.documentElement.clientWidth)\n );\n } catch (error) {\n handleDOMError(error as Error, 'isElementInViewport');\n return false;\n }\n }\n\n /**\n * Calculates distance between two points\n */\n static calculateDistance(\n x1: number,\n y1: number,\n x2: number,\n y2: number\n ): number {\n return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));\n }\n\n /**\n * Finds the closest element to a point from a list of elements\n */\n static findClosestElement(\n pointX: number,\n pointY: number,\n elements: NodeListOf<Element>\n ): HTMLElement | null {\n try {\n let closestElement: HTMLElement | null = null;\n let minDistance = Infinity;\n\n elements.forEach(element => {\n const rect = this.getElementRect(element as HTMLElement);\n const distance = this.calculateDistance(\n pointX,\n pointY,\n rect.left + rect.width / 2,\n rect.top + rect.height / 2\n );\n\n if (distance < minDistance) {\n minDistance = distance;\n closestElement = element as HTMLElement;\n }\n });\n\n return closestElement;\n } catch (error) {\n handleDOMError(error as Error, 'findClosestElement');\n return null;\n }\n }\n\n /**\n * Safely adds event listeners\n */\n static addEventListener(\n element: EventTarget,\n event: string,\n handler: EventListener,\n options?: AddEventListenerOptions\n ): void {\n try {\n element.addEventListener(event, handler, options);\n } catch (error) {\n handleDOMError(error as Error, 'addEventListener');\n throw error;\n }\n }\n\n /**\n * Safely removes event listeners\n */\n static removeEventListener(\n element: EventTarget,\n event: string,\n handler: EventListener,\n options?: EventListenerOptions\n ): void {\n try {\n element.removeEventListener(event, handler, options);\n } catch (error) {\n handleDOMError(error as Error, 'removeEventListener');\n throw error;\n }\n }\n}\n","/**\n * Debug utility for Prepr Next.js package\n * Provides centralized debug logging with performance optimizations\n */\n\n// Define specific types for debug arguments\nexport type DebugArg = string | number | boolean | null | undefined | object;\n\ninterface DebugOptions {\n enabled?: boolean;\n prefix?: string;\n}\n\nclass DebugLogger {\n private options: DebugOptions;\n\n constructor(options: DebugOptions) {\n this.options = {\n prefix: '[Prepr]',\n ...options,\n };\n }\n\n /**\n * Check if debug is enabled - checks both local and global state\n */\n private isEnabled(): boolean {\n // If this logger has a local enabled state, use it\n if (this.options.enabled !== undefined) {\n return this.options.enabled;\n }\n\n // Otherwise, check the global logger state\n return globalDebugLogger?.options?.enabled ?? false;\n }\n\n /**\n * Log a debug message if debug is enabled\n */\n log(message: string, ...args: DebugArg[]): void {\n if (!this.isEnabled()) return;\n\n const prefix = this.options.prefix;\n console.log(`${prefix} ${message}`, ...args);\n }\n\n /**\n * Log a debug warning if debug is enabled\n */\n warn(message: string, ...args: DebugArg[]): void {\n if (!this.isEnabled()) return;\n\n const prefix = this.options.prefix;\n console.warn(`${prefix} ${message}`, ...args);\n }\n\n /**\n * Log a debug error if debug is enabled\n */\n error(message: string, ...args: DebugArg[]): void {\n if (!this.isEnabled()) return;\n\n const prefix = this.options.prefix;\n console.error(`${prefix} ${message}`, ...args);\n }\n\n /**\n * Create a scoped logger with additional context\n */\n scope(scopeName: string): DebugLogger {\n return new DebugLogger({\n ...this.options,\n prefix: `${this.options.prefix}[${scopeName}]`,\n });\n }\n}\n\n// Global debug instance\nlet globalDebugLogger: DebugLogger | null = null;\n\n/**\n * Initialize the debug logger\n */\nexport function initDebugLogger(enabled: boolean = false): void {\n globalDebugLogger = new DebugLogger({ enabled });\n}\n\n/**\n * Get the debug logger instance\n */\nexport function getDebugLogger(): DebugLogger {\n if (!globalDebugLogger) {\n // Fallback to disabled logger if not initialized\n globalDebugLogger = new DebugLogger({ enabled: false });\n }\n return globalDebugLogger;\n}\n\n/**\n * Convenience function for logging\n */\nexport function debugLog(message: string, ...args: DebugArg[]): void {\n getDebugLogger().log(message, ...args);\n}\n\n/**\n * Convenience function for warning\n */\nexport function debugWarn(message: string, ...args: DebugArg[]): void {\n getDebugLogger().warn(message, ...args);\n}\n\n/**\n * Convenience function for errors\n */\nexport function debugError(message: string, ...args: DebugArg[]): void {\n getDebugLogger().error(message, ...args);\n}\n\n/**\n * Create a scoped debug logger that dynamically checks global debug state\n */\nexport function createScopedLogger(scopeName: string): DebugLogger {\n // Create a scoped logger without its own enabled state\n // This allows it to dynamically check the global logger state\n return new DebugLogger({\n prefix: `[Prepr][${scopeName}]`,\n });\n}\n","// Performance utilities\n\n/**\n * Throttled function with cancellation support\n */\nexport interface ThrottledFunction<T extends (...args: any[]) => any> {\n (...args: Parameters<T>): void;\n cancel(): void;\n}\n\n/**\n * Improved throttle function with better memory management and cancellation\n * @param func - The function to throttle\n * @param delay - The delay in milliseconds\n * @returns Throttled function with cancel method\n */\nexport function throttle<T extends (...args: any[]) => any>(\n func: T,\n delay: number\n): ThrottledFunction<T> {\n let timeoutId: NodeJS.Timeout | null = null;\n let lastExecTime = 0;\n\n const throttledFunc = ((...args: Parameters<T>) => {\n const currentTime = Date.now();\n const timeSinceLastExec = currentTime - lastExecTime;\n\n if (timeSinceLastExec >= delay) {\n func(...args);\n lastExecTime = currentTime;\n } else {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n timeoutId = setTimeout(() => {\n func(...args);\n lastExecTime = Date.now();\n timeoutId = null;\n }, delay - timeSinceLastExec);\n }\n }) as ThrottledFunction<T>;\n\n throttledFunc.cancel = () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n };\n\n return throttledFunc;\n}\n\n/**\n * Debounce function with cancellation support\n * @param func - The function to debounce\n * @param delay - The delay in milliseconds\n * @returns Debounced function with cancel method\n */\nexport function debounce<T extends (...args: any[]) => any>(\n func: T,\n delay: number\n): ThrottledFunction<T> {\n let timeoutId: NodeJS.Timeout | null = null;\n\n const debouncedFunc = ((...args: Parameters<T>) => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n timeoutId = setTimeout(() => {\n func(...args);\n timeoutId = null;\n }, delay);\n }) as ThrottledFunction<T>;\n\n debouncedFunc.cancel = () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n };\n\n return debouncedFunc;\n}\n\n// Simple DOM element cache for querySelectorAll\nexport function createElementCache<T extends Element = Element>(\n query: string,\n ttl: number = 1000\n) {\n let cache: NodeListOf<T> | null = null;\n let lastCacheTime = 0;\n return () => {\n const now = Date.now();\n if (!cache || now - lastCacheTime > ttl) {\n cache = document.querySelectorAll<T>(query);\n lastCacheTime = now;\n }\n return cache;\n };\n}\n","import { ClassValue, clsx } from 'clsx';\nimport { twMerge } from 'tailwind-merge';\nimport { PreprEventType } from '../types';\n\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs));\n}\n\n// Define specific types for Prepr events\nexport interface PreprEventData {\n readonly segment?: string;\n readonly variant?: string;\n readonly editMode?: boolean;\n readonly [key: string]: string | boolean | number | undefined;\n}\n\n/**\n * Sends a Prepr event to the parent window\n * @param event - The event type to send\n * @param data - Optional event data\n */\nexport function sendPreprEvent(\n event: PreprEventType,\n data?: PreprEventData\n): void {\n if (typeof window !== 'undefined' && window.parent) {\n window.parent.postMessage(\n {\n name: 'prepr_preview_bar',\n event,\n ...data,\n },\n '*'\n );\n }\n}\n\n// Export error handling utilities\nexport * from './errors';\n\n// Export DOM service\nexport * from './dom';\n\n// Export debug utilities\nexport * from './debug';\n\n// Export performance utilities\nexport * from './performance';\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@preprio/prepr-nextjs",
|
|
3
|
-
"version": "2.0.0-alpha.
|
|
3
|
+
"version": "2.0.0-alpha.13",
|
|
4
4
|
"description": "Next.js package for Prepr CMS preview functionality with advanced debugging and visual editing capabilities",
|
|
5
5
|
"main": "dist/react/index.cjs",
|
|
6
6
|
"types": "./dist/react/index.d.ts",
|
|
@@ -9,18 +9,13 @@
|
|
|
9
9
|
"scripts": {
|
|
10
10
|
"build": "tsup",
|
|
11
11
|
"dev": "tsup --watch",
|
|
12
|
-
"dev:css": "postcss ./src/globals.css -o ./src/output.css --watch",
|
|
13
|
-
"build:css": "NODE_ENV=production postcss ./src/globals.css -o ./dist/index.css",
|
|
14
|
-
"test": "echo \"Error: no test specified\" && exit 1",
|
|
15
12
|
"clean": "rm -rf dist",
|
|
16
|
-
"
|
|
17
|
-
"
|
|
18
|
-
"
|
|
19
|
-
"
|
|
20
|
-
"
|
|
21
|
-
"
|
|
22
|
-
"lint:check": "eslint src --ext .ts,.tsx",
|
|
23
|
-
"prepublishOnly": "npm run check && npm run build"
|
|
13
|
+
"check": "tsc --noEmit && eslint src --ext .ts,.tsx && prettier --check \"src/**/*.{ts,tsx,js,jsx,json,md}\"",
|
|
14
|
+
"fix": "eslint src --ext .ts,.tsx --fix && prettier --write \"src/**/*.{ts,tsx,js,jsx,json,md}\"",
|
|
15
|
+
"changeset": "changeset",
|
|
16
|
+
"version": "changeset version",
|
|
17
|
+
"release": "pnpm run build && changeset publish",
|
|
18
|
+
"prepublishOnly": "pnpm run check && pnpm run build"
|
|
24
19
|
},
|
|
25
20
|
"exports": {
|
|
26
21
|
"./middleware": {
|
|
@@ -38,11 +33,6 @@
|
|
|
38
33
|
"types": "./dist/react/index.d.ts",
|
|
39
34
|
"require": "./dist/react/index.cjs"
|
|
40
35
|
},
|
|
41
|
-
"./contexts": {
|
|
42
|
-
"import": "./dist/contexts/index.js",
|
|
43
|
-
"types": "./dist/contexts/index.d.ts",
|
|
44
|
-
"require": "./dist/contexts/index.cjs"
|
|
45
|
-
},
|
|
46
36
|
"./utils": {
|
|
47
37
|
"import": "./dist/utils/index.js",
|
|
48
38
|
"types": "./dist/utils/index.d.ts",
|
|
@@ -78,6 +68,7 @@
|
|
|
78
68
|
"license": "MIT",
|
|
79
69
|
"packageManager": "pnpm@10.5.2",
|
|
80
70
|
"devDependencies": {
|
|
71
|
+
"@changesets/cli": "^2.29.5",
|
|
81
72
|
"@eslint/js": "^9.25.1",
|
|
82
73
|
"@types/node": "^20.11.5",
|
|
83
74
|
"@types/react": "19.1.0",
|
package/dist/chunk-LVXDK2EY.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {ipAddress}from'@vercel/functions';import {NextResponse}from'next/server';function l(t,o,x){var m,u,f,_;let e,s;o&&"headers"in o?(e=o,s=x):(e=NextResponse.next(),s=o),process.env.PREPR_GRAPHQL_URL||console.error("PREPR_GRAPHQL_URL is not set"),t.nextUrl.searchParams.forEach((r,p)=>{switch(p){case "utm_source":e.headers.set("Prepr-Context-utm_source",r);break;case "utm_medium":e.headers.set("Prepr-Context-utm_medium",r);break;case "utm_term":e.headers.set("Prepr-Context-utm_term",r);break;case "utm_content":e.headers.set("Prepr-Context-utm_content",r);break;case "utm_campaign":e.headers.set("Prepr-Context-utm_campaign",r);break}});let a=t.headers.get("referer");a&&e.headers.set("Prepr-Context-initial_referral",a);let n=ipAddress(t);n&&e.headers.set("Prepr-Visitor-IP",n);let d=(m=t.cookies.get("hubspotutk"))==null?void 0:m.value;d&&e.headers.set("Prepr-Hubspot-Id",d);let i=(u=t.cookies.get("__prepr_uid"))==null?void 0:u.value;if(i||(i=crypto.randomUUID(),e.cookies.set("__prepr_uid",i,{maxAge:1*365*24*60}),e.headers.set("Prepr-Customer-Id-Created","true")),e.headers.set("Prepr-Customer-Id",i),!(s!=null&&s.preview)||process.env.PREPR_ENV!=="preview")return e;e.headers.set("Prepr-Preview-Bar","true");let P=(f=t.cookies.get("Prepr-Segments"))==null?void 0:f.value;P&&e.headers.set("Prepr-Segments",P);let c=(_=t.cookies.get("Prepr-ABtesting"))==null?void 0:_.value;return c&&e.headers.set("Prepr-ABtesting",c),t.nextUrl.searchParams.forEach((r,p)=>{p==="prepr_preview_ab"&&(e.headers.set("Prepr-ABtesting",r),e.cookies.set("Prepr-ABtesting",r)),p==="prepr_preview_segment"&&(e.headers.set("Prepr-Segments",r),e.cookies.set("Prepr-Segments",r));}),e}export{l as a};//# sourceMappingURL=chunk-LVXDK2EY.js.map
|
|
2
|
-
//# sourceMappingURL=chunk-LVXDK2EY.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/middleware/index.ts"],"names":["createPreprMiddleware","request","responseOrOptions","options","_a","_b","_c","_d","response","finalOptions","NextResponse","value","key","referrer","ip","ipAddress","hutkCookie","cookie","segmentCookie","abCookie"],"mappings":"iFAsCe,SAARA,CAAAA,CACLC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACc,CA1ChB,IAAAC,CAAAA,CAAAC,CAAAA,CAAAC,CAAAA,CAAAC,CAAAA,CA2CE,IAAIC,CAAAA,CACAC,CAAAA,CAGAP,GAAqB,SAAA,GAAaA,CAAAA,EAEpCM,CAAAA,CAAWN,CAAAA,CACXO,CAAAA,CAAeN,CAAAA,GAGfK,CAAAA,CAAWE,YAAAA,CAAa,MAAK,CAC7BD,CAAAA,CAAeP,CAAAA,CAAAA,CAGZ,OAAA,CAAQ,GAAA,CAAI,iBAAA,EACf,OAAA,CAAQ,KAAA,CAAM,8BAA8B,CAAA,CAI9CD,CAAAA,CAAQ,OAAA,CAAQ,YAAA,CAAa,OAAA,CAAQ,CAACU,CAAAA,CAAOC,IAAQ,CACnD,OAAQA,CAAAA,EACN,KAAK,YAAA,CACHJ,CAAAA,CAAS,OAAA,CAAQ,IAAI,0BAAA,CAA4BG,CAAK,CAAA,CACtD,MACF,KAAK,YAAA,CACHH,CAAAA,CAAS,OAAA,CAAQ,IAAI,0BAAA,CAA4BG,CAAK,CAAA,CACtD,MACF,KAAK,UAAA,CACHH,CAAAA,CAAS,OAAA,CAAQ,GAAA,CAAI,wBAAA,CAA0BG,CAAK,CAAA,CACpD,MACF,KAAK,aAAA,CACHH,C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MAAAA,CAAAA,CAAc,OAAA,CAAA,EAAW,OAAA,CAAQ,GAAA,CAAI,SAAA,GAAc,SAAA,CACtD,OAAOD,CAAAA,CAITA,EAAS,OAAA,CAAQ,GAAA,CAAI,mBAAA,CAAqB,MAAM,CAAA,CAGhD,IAAMU,CAAAA,CAAAA,CAAgBZ,CAAAA,CAAAL,EAAQ,OAAA,CAAQ,GAAA,CAAI,gBAAgB,CAAA,GAApC,IAAA,CAAA,MAAA,CAAAK,CAAAA,CAAuC,KAAA,CACzDY,CAAAA,EACFV,CAAAA,CAAS,OAAA,CAAQ,GAAA,CAAI,gBAAA,CAAkBU,CAAa,CAAA,CAGtD,IAAMC,CAAAA,CAAAA,CAAWZ,EAAAN,CAAAA,CAAQ,OAAA,CAAQ,GAAA,CAAI,iBAAiB,CAAA,GAArC,IAAA,CAAA,MAAA,CAAAM,CAAAA,CAAwC,KAAA,CACzD,OAAIY,CAAAA,EACFX,CAAAA,CAAS,OAAA,CAAQ,GAAA,CAAI,iBAAA,CAAmBW,CAAQ,CAAA,CAIlDlB,CAAAA,CAAQ,QAAQ,YAAA,CAAa,OAAA,CAAQ,CAACU,CAAAA,CAAOC,CAAAA,GAAQ,CAC/CA,CAAAA,GAAQ,kBAAA,GACVJ,EAAS,OAAA,CAAQ,GAAA,CAAI,iBAAA,CAAmBG,CAAK,CAAA,CAC7CH,CAAAA,CAAS,OAAA,CAAQ,GAAA,CAAI,kBAAmBG,CAAK,CAAA,CAAA,CAG3CC,CAAAA,GAAQ,uBAAA,GACVJ,CAAAA,CAAS,OAAA,CAAQ,GAAA,CAAI,gBAAA,CAAkBG,CAAK,CAAA,CAC5CH,CAAAA,CAAS,OAAA,CAAQ,GAAA,CAAI,gBAAA,CAAkBG,CAAK,CAAA,EAEhD,CAAC,EAEMH,CACT","file":"chunk-LVXDK2EY.js","sourcesContent":["import { ipAddress } from '@vercel/functions';\nimport { NextRequest, NextResponse } from 'next/server';\n\nexport interface PreprMiddlewareOptions {\n preview?: boolean;\n}\n\n/**\n * Middleware to set Prepr headers for personalization.\n *\n * @overload\n * @param request - NextRequest object\n * @param options - Options object\n * @returns NextResponse with Prepr headers set\n */\nexport default function createPreprMiddleware(\n request: NextRequest,\n options?: PreprMiddlewareOptions\n): NextResponse;\n\n/**\n * Middleware to set Prepr headers for personalization.\n *\n * @overload\n * @param request - NextRequest object\n * @param response - NextResponse object to chain with\n * @param options - Options object\n * @returns NextResponse with Prepr headers set\n */\nexport default function createPreprMiddleware(\n request: NextRequest,\n response: NextResponse,\n options?: PreprMiddlewareOptions\n): NextResponse;\n\n/**\n * Implementation of createPreprMiddleware with function overloads\n */\nexport default function createPreprMiddleware(\n request: NextRequest,\n responseOrOptions?: NextResponse | PreprMiddlewareOptions,\n options?: PreprMiddlewareOptions\n): NextResponse {\n let response: NextResponse;\n let finalOptions: PreprMiddlewareOptions | undefined;\n\n // Handle overloads\n if (responseOrOptions && 'headers' in responseOrOptions) {\n // Second parameter is NextResponse\n response = responseOrOptions;\n finalOptions = options;\n } else {\n // Second parameter is options or undefined\n response = NextResponse.next();\n finalOptions = responseOrOptions as PreprMiddlewareOptions | undefined;\n }\n\n if (!process.env.PREPR_GRAPHQL_URL) {\n console.error('PREPR_GRAPHQL_URL is not set');\n }\n\n // Map over search params and set headers\n request.nextUrl.searchParams.forEach((value, key) => {\n switch (key) {\n case 'utm_source':\n response.headers.set('Prepr-Context-utm_source', value);\n break;\n case 'utm_medium':\n response.headers.set('Prepr-Context-utm_medium', value);\n break;\n case 'utm_term':\n response.headers.set('Prepr-Context-utm_term', value);\n break;\n case 'utm_content':\n response.headers.set('Prepr-Context-utm_content', value);\n break;\n case 'utm_campaign':\n response.headers.set('Prepr-Context-utm_campaign', value);\n break;\n }\n });\n\n // Set initial referral header\n const referrer = request.headers.get('referer');\n if (referrer) {\n response.headers.set('Prepr-Context-initial_referral', referrer);\n }\n\n // Set IP address header\n const ip = ipAddress(request);\n if (ip) {\n response.headers.set('Prepr-Visitor-IP', ip);\n }\n\n // Set HubSpot cookie header\n const hutkCookie = request.cookies.get('hubspotutk')?.value;\n if (hutkCookie) {\n response.headers.set('Prepr-Hubspot-Id', hutkCookie);\n }\n\n // Check for existing Prepr UID cookie or create a new one\n let cookie = request.cookies.get('__prepr_uid')?.value;\n if (!cookie) {\n cookie = crypto.randomUUID();\n response.cookies.set('__prepr_uid', cookie, {\n maxAge: 1 * 365 * 24 * 60, // Set for one year\n });\n response.headers.set('Prepr-Customer-Id-Created', 'true');\n }\n\n // Set the Prepr Customer ID header\n response.headers.set('Prepr-Customer-Id', cookie);\n\n // If preview mode is not enabled, return the response\n if (!finalOptions?.preview || process.env.PREPR_ENV !== 'preview') {\n return response;\n }\n\n // If preview mode is enabled, set additional headers\n response.headers.set('Prepr-Preview-Bar', 'true');\n\n // Set Prepr Preview Segment and AB test cookies\n const segmentCookie = request.cookies.get('Prepr-Segments')?.value;\n if (segmentCookie) {\n response.headers.set('Prepr-Segments', segmentCookie);\n }\n\n const abCookie = request.cookies.get('Prepr-ABtesting')?.value;\n if (abCookie) {\n response.headers.set('Prepr-ABtesting', abCookie);\n }\n\n // Set Prepr Preview Segment and AB test headers from query params\n request.nextUrl.searchParams.forEach((value, key) => {\n if (key === 'prepr_preview_ab') {\n response.headers.set('Prepr-ABtesting', value);\n response.cookies.set('Prepr-ABtesting', value);\n }\n\n if (key === 'prepr_preview_segment') {\n response.headers.set('Prepr-Segments', value);\n response.cookies.set('Prepr-Segments', value);\n }\n });\n\n return response;\n}\n"]}
|