@preprio/prepr-nextjs 2.0.0-alpha.9 → 2.0.0
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 +728 -110
- package/dist/chunk-QZTUT4DH.js +2 -0
- package/dist/chunk-QZTUT4DH.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.d.cts +20 -4
- package/dist/middleware/index.d.ts +20 -4
- package/dist/middleware/index.js +1 -1
- package/dist/middleware/index.js.map +1 -1
- package/dist/react/index.cjs +6 -1
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.d.cts +57 -19
- package/dist/react/index.d.ts +57 -19
- 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 +50 -11
- package/dist/server/index.d.ts +50 -11
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/types/index.d.cts +33 -13
- package/dist/types/index.d.ts +33 -13
- package/dist/utils/index.cjs +1 -1
- package/dist/utils/index.cjs.map +1 -1
- package/dist/utils/index.d.cts +39 -9
- package/dist/utils/index.d.ts +39 -9
- package/dist/utils/index.js +1 -1
- package/dist/utils/index.js.map +1 -1
- package/package.json +13 -24
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/server/index.ts","../../package.json"],"names":["package_default","getPreprUUID","__async","headers","getActiveSegment","getActiveVariant","getPreprHeaders","newHeaders","value","key","getPreprEnvironmentSegments","token","_a","response","getPackageVersion","json","e","error","getPreviewBarProps","data","activeSegment","activeVariant"],"mappings":"iDAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,IAAA,OAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,I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ACT,CACF,CAAA,CAAA,CAOA,SAAsBC,CAAAA,CACpBP,CAAAA,CAC+B,QAAAT,CAAAA,CAAA,IAAA,CAAA,IAAA,CAAA,WAAA,CAC/B,IAAIiB,CAAAA,CAAuB,GACvBC,CAAAA,CAA+B,IAAA,CAC/BC,EAA+B,IAAA,CAGnC,OAAI,QAAQ,GAAA,CAAI,SAAA,GAAc,SAAA,GAC5BF,CAAAA,CAAO,MAAMT,CAAAA,CAA4BC,CAAK,CAAA,CAC9CS,CAAAA,CAAgB,MAAMhB,CAAAA,EAAiB,CACvCiB,EAAgB,MAAMhB,CAAAA,EAAiB,CAAA,CAGlC,CACL,aAAA,CAAAe,CAAAA,CACA,cAAAC,CAAAA,CACA,IAAA,CAAAF,CACF,CACF,CAAA,CAAA,CAEA,SAASL,CAAAA,EAAoB,CAC3B,OAAOd,CAAAA,CAAM,OACf","file":"index.cjs","sourcesContent":["import { headers } from 'next/headers';\nimport { PreprPreviewBarProps, PreprSegment } from '../types';\nimport pjson from '../../package.json';\n\n/**\n * Returns the Prepr Customer ID from the headers\n */\nexport async function getPreprUUID() {\n const headersList = await headers();\n return headersList.get('prepr-customer-id');\n}\n\n/**\n * Retuns the active segment from the headers\n */\nexport async function getActiveSegment() {\n const headersList = await headers();\n return headersList.get('Prepr-Segments');\n}\n\n/**\n * Returns the active variant from the headers\n */\nexport async function getActiveVariant() {\n const headersList = await headers();\n return headersList.get('Prepr-ABtesting');\n}\n\n/**\n * Helper function to retrieve Prepr headers (will filter out customer ID if in preview mode)\n */\nexport async function getPreprHeaders() {\n const newHeaders: {\n [key: string]: string;\n } = {};\n\n const headersList = await headers();\n\n headersList.forEach((value, key) => {\n if (key.startsWith('prepr')) {\n newHeaders[key] = value;\n }\n });\n\n return newHeaders;\n}\n\n/**\n * Fetches the segments from the Prepr API\n * @param token Prepr access token with scope 'segments'\n * @returns Array of PreprSegmentResponse\n */\nexport async function getPreprEnvironmentSegments(\n token: string\n): Promise<PreprSegment[]> {\n if (!token) {\n console.error(\n 'No token provided, make sure you are using your Prepr GraphQL URL'\n );\n return [];\n }\n\n if (!token.startsWith('https://')) {\n console.error(\n 'Invalid token provided, make sure you are using your Prepr GraphQL URL'\n );\n return [];\n }\n\n try {\n const response = await fetch(token, {\n headers: {\n 'User-Agent': `Prepr-Preview-Bar/${getPackageVersion()}`,\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify({\n query: `{\n _Segments {\n _id\n name\n }\n }`,\n }),\n });\n try {\n const json = await response.json();\n\n if (!json || !json.data || !json.data._Segments) {\n return [];\n }\n\n return json.data?._Segments as PreprSegment[];\n } catch {\n console.error('Error parsing JSON, please contact Prepr support');\n return [];\n }\n } catch (error) {\n console.error('Error fetching segments:', error);\n return [];\n }\n}\n\n/**\n * Fetches all the necessary previewbar props\n * @param token Prepr access token with scope 'segments'\n * @returns Object with activeSegment, activeVariant and data\n */\nexport async function getPreviewBarProps(\n token: string\n): Promise<PreprPreviewBarProps> {\n let data: PreprSegment[] = [];\n let activeSegment: string | null = null;\n let activeVariant: string | null = null;\n\n // Prevent unnecessary function calling in production\n if (process.env.PREPR_ENV === 'preview') {\n data = await getPreprEnvironmentSegments(token);\n activeSegment = await getActiveSegment();\n activeVariant = await getActiveVariant();\n }\n\n return {\n activeSegment,\n activeVariant,\n data,\n };\n}\n\nfunction getPackageVersion() {\n return pjson.version;\n}\n","{\n \"name\": \"@preprio/prepr-nextjs\",\n \"version\": \"2.0.0-alpha.9\",\n \"description\": \"Next.js package for Prepr CMS preview functionality with advanced debugging and visual editing capabilities\",\n \"main\": \"dist/react/index.cjs\",\n \"types\": \"./dist/react/index.d.ts\",\n \"module\": \"./dist/react/index.js\",\n \"type\": \"module\",\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"dev:css\": \"postcss ./src/globals.css -o ./src/output.css --watch\",\n \"build:css\": \"NODE_ENV=production postcss ./src/globals.css -o ./dist/index.css\",\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n \"clean\": \"rm -rf dist\",\n \"format\": \"prettier --write \\\"src/**/*.{ts,tsx,js,jsx,json,md}\\\"\",\n \"format:check\": \"prettier --check \\\"src/**/*.{ts,tsx,js,jsx,json,md}\\\"\",\n \"release\": \"node scripts/release.js\",\n \"check\": \"npm run type-check && npm run lint:check && npm run format:check\",\n \"type-check\": \"tsc --noEmit\",\n \"lint\": \"eslint src --ext .ts,.tsx --fix\",\n \"lint:check\": \"eslint src --ext .ts,.tsx\",\n \"prepublishOnly\": \"npm run check && npm run build\"\n },\n \"exports\": {\n \"./middleware\": {\n \"import\": \"./dist/middleware/index.js\",\n \"types\": \"./dist/middleware/index.d.ts\",\n \"require\": \"./dist/middleware/index.cjs\"\n },\n \"./server\": {\n \"import\": \"./dist/server/index.js\",\n \"types\": \"./dist/server/index.d.ts\",\n \"require\": \"./dist/server/index.cjs\"\n },\n \"./react\": {\n \"import\": \"./dist/react/index.js\",\n \"types\": \"./dist/react/index.d.ts\",\n \"require\": \"./dist/react/index.cjs\"\n },\n \"./contexts\": {\n \"import\": \"./dist/contexts/index.js\",\n \"types\": \"./dist/contexts/index.d.ts\",\n \"require\": \"./dist/contexts/index.cjs\"\n },\n \"./utils\": {\n \"import\": \"./dist/utils/index.js\",\n \"types\": \"./dist/utils/index.d.ts\",\n \"require\": \"./dist/utils/index.cjs\"\n },\n \"./types\": {\n \"import\": \"./dist/types/index.js\",\n \"types\": \"./dist/types/index.d.ts\",\n \"require\": \"./dist/types/index.cjs\"\n },\n \"./index.css\": {\n \"import\": \"./dist/index.css\",\n \"require\": \"./dist/index.css\"\n }\n },\n \"files\": [\n \"dist\",\n \"package.json\"\n ],\n \"keywords\": [\n \"prepr\",\n \"cms\",\n \"nextjs\",\n \"preview\",\n \"visual-editing\",\n \"headless-cms\",\n \"react\",\n \"typescript\",\n \"debug\",\n \"stega\"\n ],\n \"author\": \"Preprio\",\n \"license\": \"MIT\",\n \"packageManager\": \"pnpm@10.5.2\",\n \"devDependencies\": {\n \"@eslint/js\": \"^9.25.1\",\n \"@types/node\": \"^20.11.5\",\n \"@types/react\": \"19.1.0\",\n \"@types/react-dom\": \"19.1.2\",\n \"@typescript-eslint/eslint-plugin\": \"^8.31.1\",\n \"@typescript-eslint/parser\": \"^8.31.1\",\n \"autoprefixer\": \"^10.4.21\",\n \"cssnano\": \"^7.0.7\",\n \"eslint\": \"^9.25.1\",\n \"eslint-config-prettier\": \"^10.1.2\",\n \"eslint-plugin-prettier\": \"^5.2.6\",\n \"eslint-plugin-react\": \"^7.37.2\",\n \"eslint-plugin-react-hooks\": \"^5.0.0\",\n \"next\": \"15.3.1\",\n \"postcss\": \"^8\",\n \"prettier\": \"^3.5.3\",\n \"prettier-plugin-tailwindcss\": \"^0.5.12\",\n \"react\": \"^19.1.0\",\n \"react-dom\": \"^19.1.0\",\n \"tailwindcss\": \"^3.4.17\",\n \"tsup\": \"^8.5.0\",\n \"typescript\": \"^5.8.3\"\n },\n \"peerDependencies\": {\n \"next\": \"^15.0.0 || ^14.0.0 || ^13.0.0\",\n \"react\": \"^19.0.0 || ^18.0.0 || ^17.0.0 \",\n \"react-dom\": \"^19.0.0 || ^18.0.0 || ^17.0.0\"\n },\n \"dependencies\": {\n \"@headlessui/react\": \"^2.2.0\",\n \"@vercel/functions\": \"^2.0.0\",\n \"@vercel/stega\": \"^0.1.2\",\n \"clsx\": \"^2.1.1\",\n \"postcss-cli\": \"^11.0.1\",\n \"tailwind-merge\": \"^3.0.1\"\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/server/index.ts","../../package.json","../../src/middleware/index.ts"],"names":["version","package_default","createPreprMiddleware","request","responseOrOptions","options","_a","_b","_c","_d","response","finalOptions","NextResponse","value","key","referrer","ip","ipAddress","hutkCookie","cookie","segmentCookie","abCookie","PreprError","message","code","context","originalError","getPreprHeader","name","__async","headers","getPreprUUID","getActiveSegment","getActiveVariant","getPreprHeaders","preprHeaders","validatePreprToken","token","isPreviewMode","extractAccessToken","graphqlUrl","url","pathParts","e","getPreprEnvironmentSegments","validation","getPackageVersion","json","error","getToolbarProps","data","activeSegment","activeVariant"],"mappings":"sHAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,IAAA,OAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,IAAA,CAAA,CAAA,CAAA,EAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA,CAAA,IAAA,CAAA,CAAA,CAAA,EAAA,CAAA,MAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA,CAAA,KAAA,CAAA,CAAA,CAAA,EAAA,CAAA,MAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAA,CAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,KAAA,CAAA,CAAA,OAAA,CAAA,OAAA,CAAA,CAAA,CAAA,KAAA,CAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,KAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAA,IAAA,EAAA,EAAA,CAAA,CAAA,CCEE,IAAAA,CAAAA,CAAW,OAAA,CAFb,IAAAC,CAAAA,CAAA,CAEE,QAAAD,CAyGF,CAAA,CCpEe,SAARE,EACLC,CAAAA,CACAC,CAAAA,CACAC,EACc,CA3ChB,IAAAC,EAAAC,CAAAA,CAAAC,CAAAA,CAAAC,EA4CE,IAAIC,CAAAA,CACAC,EAGAP,CAAAA,EAAqB,SAAA,GAAaA,GAEpCM,CAAAA,CAAWN,CAAAA,CACXO,CAAAA,CAAeN,CAAAA,GAGfK,EAAWE,mBAAAA,CAAa,IAAA,GACxBD,CAAAA,CAAeP,CAAAA,CAAAA,CAG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xB,CAAA,MAASe,CAAAA,CAAO,CAEd,OAAA,CAAQ,KAAA,CAAM,gCAAA,CAAkCA,CAAK,CAAA,CAErDE,CAAAA,CAAO,GACT,CAGF,OAAO,CACL,aAAA,CAAAC,CAAAA,CACA,aAAA,CAAAC,CAAAA,CACA,IAAA,CAAAF,CACF,CACF,CAAA,CAAA,CAEA,SAASJ,CAAAA,EAAoB,CAC3B,OAAO7C,EAAM,OACf","file":"index.cjs","sourcesContent":["import { headers } from 'next/headers';\nimport {\n PreprToolbarProps,\n PreprSegment,\n PreprHeaderName,\n PreprErrorCode,\n} from '../types';\nimport pjson from '../../package.json';\nimport createPreprMiddleware from '../middleware';\n\n/**\n * Custom error class for Prepr-related errors\n */\nexport class PreprError extends Error {\n constructor(\n message: string,\n public readonly code: PreprErrorCode,\n public readonly context?: string,\n public readonly originalError?: Error\n ) {\n super(message);\n this.name = 'PreprError';\n }\n}\n\n/**\n * Internal helper to get a specific Prepr header value\n * @param name - The header name to retrieve\n * @returns The header value or null if not found\n */\nasync function getPreprHeader(name: PreprHeaderName): Promise<string | null> {\n const headersList = await headers();\n return headersList.get(name);\n}\n\n/**\n * Returns the Prepr Customer ID from the headers\n * @returns Prepr Customer ID\n */\nexport async function getPreprUUID(): Promise<string | null> {\n return getPreprHeader('prepr-customer-id');\n}\n\n/**\n * Returns the active segment from the headers\n * @returns Active segment\n */\nexport async function getActiveSegment(): Promise<string | null> {\n return getPreprHeader('Prepr-Segments');\n}\n\n/**\n * Returns the active variant from the headers\n * @returns Active variant\n */\nexport async function getActiveVariant(): Promise<string | null> {\n return getPreprHeader('Prepr-ABtesting');\n}\n\n/**\n * Helper function to retrieve all Prepr headers\n * @returns Object with Prepr headers\n */\nexport async function getPreprHeaders(): Promise<Record<string, string>> {\n const preprHeaders: Record<string, string> = {};\n const headersList = await headers();\n\n headersList.forEach((value, key) => {\n if (key.startsWith('prepr') || key.startsWith('Prepr')) {\n preprHeaders[key] = value;\n }\n });\n\n return preprHeaders;\n}\n\n/**\n * Validates a Prepr GraphQL token\n * @param token - The token to validate\n * @returns Validation result with error details if invalid\n */\nexport function validatePreprToken(token: string): {\n valid: boolean;\n error?: string;\n} {\n if (!token) {\n return { valid: false, error: 'Token is required' };\n }\n if (!token.startsWith('https://')) {\n return { valid: false, error: 'Token must be a valid HTTPS URL' };\n }\n return { valid: true };\n}\n\n/**\n * Checks if the current environment is in preview mode\n * @returns True if in preview mode\n */\nexport function isPreviewMode(): boolean {\n return process.env.PREPR_ENV === 'preview';\n}\n\n/**\n * Extracts the access token from a Prepr GraphQL URL\n * @param graphqlUrl - The full Prepr GraphQL URL\n * @returns The access token or null if invalid\n * @example\n * ```typescript\n * const token = extractAccessToken('https://graphql.prepr.io/abc123')\n * // Returns: 'abc123'\n * ```\n */\nexport function extractAccessToken(graphqlUrl: string): string | null {\n if (!graphqlUrl) return null;\n\n try {\n const url = new URL(graphqlUrl);\n if (url.hostname !== 'graphql.prepr.io') return null;\n\n const pathParts = url.pathname.split('/');\n const token = pathParts[pathParts.length - 1];\n\n return token && token.length > 0 ? token : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Fetches the segments from the Prepr API\n * @param token Prepr GraphQL URL with scope 'segments'\n * @returns Array of PreprSegment\n * @throws PreprError if the request fails\n */\nexport async function getPreprEnvironmentSegments(\n token: string\n): Promise<PreprSegment[]> {\n const validation = validatePreprToken(token);\n if (!validation.valid) {\n throw new PreprError(\n validation.error!,\n 'INVALID_TOKEN',\n 'getPreprEnvironmentSegments'\n );\n }\n\n try {\n const response = await fetch(token, {\n headers: {\n 'User-Agent': `Prepr-Preview-Bar/${getPackageVersion()}`,\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify({\n query: `{\n _Segments {\n _id\n name\n }\n }`,\n }),\n });\n\n if (!response.ok) {\n throw new PreprError(\n `HTTP ${response.status}: ${response.statusText}`,\n 'HTTP_ERROR',\n 'getPreprEnvironmentSegments'\n );\n }\n\n const json = await response.json();\n\n if (!json || !json.data || !json.data._Segments) {\n throw new PreprError(\n 'Invalid response format from Prepr API',\n 'INVALID_RESPONSE',\n 'getPreprEnvironmentSegments'\n );\n }\n\n return json.data._Segments as PreprSegment[];\n } catch (error) {\n if (error instanceof PreprError) {\n throw error;\n }\n throw new PreprError(\n 'Failed to fetch segments from Prepr API',\n 'FETCH_ERROR',\n 'getPreprEnvironmentSegments',\n error instanceof Error ? error : new Error(String(error))\n );\n }\n}\n\n/**\n * Fetches all the necessary previewbar props\n * @param token Prepr GraphQL URL with scope 'segments'\n * @returns Object with activeSegment, activeVariant and data\n */\nexport async function getToolbarProps(\n token: string\n): Promise<PreprToolbarProps> {\n let data: PreprSegment[] = [];\n let activeSegment: string | null = null;\n let activeVariant: string | null = null;\n\n // Prevent unnecessary function calling in production\n if (isPreviewMode()) {\n try {\n data = await getPreprEnvironmentSegments(token);\n activeSegment = await getActiveSegment();\n activeVariant = await getActiveVariant();\n } catch (error) {\n // In preview mode, we should still return props even if API fails\n console.error('Failed to fetch toolbar props:', error);\n // Return empty data to prevent toolbar from crashing\n data = [];\n }\n }\n\n return {\n activeSegment,\n activeVariant,\n data,\n };\n}\n\nfunction getPackageVersion() {\n return pjson.version;\n}\n\nexport { createPreprMiddleware };\n","{\n \"name\": \"@preprio/prepr-nextjs\",\n \"version\": \"2.0.0\",\n \"description\": \"Next.js package for Prepr CMS preview functionality with advanced debugging and visual editing capabilities\",\n \"main\": \"dist/react/index.cjs\",\n \"types\": \"./dist/react/index.d.ts\",\n \"module\": \"./dist/react/index.js\",\n \"type\": \"module\",\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"clean\": \"rm -rf dist\",\n \"check\": \"tsc --noEmit && eslint src --ext .ts,.tsx && prettier --check \\\"src/**/*.{ts,tsx,js,jsx,json,md}\\\"\",\n \"fix\": \"eslint src --ext .ts,.tsx --fix && prettier --write \\\"src/**/*.{ts,tsx,js,jsx,json,md}\\\"\",\n \"changeset\": \"changeset\",\n \"version\": \"changeset version\",\n \"release\": \"pnpm run build && changeset publish\",\n \"prepublishOnly\": \"pnpm run check && pnpm run build\"\n },\n \"exports\": {\n \"./middleware\": {\n \"import\": \"./dist/middleware/index.js\",\n \"types\": \"./dist/middleware/index.d.ts\",\n \"require\": \"./dist/middleware/index.cjs\"\n },\n \"./server\": {\n \"import\": \"./dist/server/index.js\",\n \"types\": \"./dist/server/index.d.ts\",\n \"require\": \"./dist/server/index.cjs\"\n },\n \"./react\": {\n \"import\": \"./dist/react/index.js\",\n \"types\": \"./dist/react/index.d.ts\",\n \"require\": \"./dist/react/index.cjs\"\n },\n \"./utils\": {\n \"import\": \"./dist/utils/index.js\",\n \"types\": \"./dist/utils/index.d.ts\",\n \"require\": \"./dist/utils/index.cjs\"\n },\n \"./types\": {\n \"import\": \"./dist/types/index.js\",\n \"types\": \"./dist/types/index.d.ts\",\n \"require\": \"./dist/types/index.cjs\"\n },\n \"./index.css\": {\n \"import\": \"./dist/index.css\",\n \"require\": \"./dist/index.css\"\n }\n },\n \"files\": [\n \"dist\",\n \"package.json\"\n ],\n \"keywords\": [\n \"prepr\",\n \"cms\",\n \"nextjs\",\n \"preview\",\n \"visual-editing\",\n \"headless-cms\",\n \"react\",\n \"typescript\",\n \"debug\",\n \"stega\"\n ],\n \"author\": \"Preprio\",\n \"license\": \"MIT\",\n \"packageManager\": \"pnpm@10.5.2\",\n \"devDependencies\": {\n \"@changesets/cli\": \"^2.29.5\",\n \"@eslint/js\": \"^9.25.1\",\n \"@types/node\": \"^20.11.5\",\n \"@types/react\": \"19.1.0\",\n \"@types/react-dom\": \"19.1.2\",\n \"@typescript-eslint/eslint-plugin\": \"^8.31.1\",\n \"@typescript-eslint/parser\": \"^8.31.1\",\n \"autoprefixer\": \"^10.4.21\",\n \"cssnano\": \"^7.0.7\",\n \"eslint\": \"^9.25.1\",\n \"eslint-config-prettier\": \"^10.1.2\",\n \"eslint-plugin-prettier\": \"^5.2.6\",\n \"eslint-plugin-react\": \"^7.37.2\",\n \"eslint-plugin-react-hooks\": \"^5.0.0\",\n \"next\": \"15.3.1\",\n \"postcss\": \"^8\",\n \"prettier\": \"^3.5.3\",\n \"prettier-plugin-tailwindcss\": \"^0.5.12\",\n \"react\": \"^19.1.0\",\n \"react-dom\": \"^19.1.0\",\n \"tailwindcss\": \"^3.4.17\",\n \"tsup\": \"^8.5.0\",\n \"typescript\": \"^5.8.3\"\n },\n \"peerDependencies\": {\n \"next\": \"^15.0.0 || ^14.0.0 || ^13.0.0\",\n \"react\": \"^19.0.0 || ^18.0.0 || ^17.0.0 \",\n \"react-dom\": \"^19.0.0 || ^18.0.0 || ^17.0.0\"\n },\n \"dependencies\": {\n \"@headlessui/react\": \"^2.2.0\",\n \"@vercel/functions\": \"^2.0.0\",\n \"@vercel/stega\": \"^0.1.2\",\n \"clsx\": \"^2.1.1\",\n \"postcss-cli\": \"^11.0.1\",\n \"tailwind-merge\": \"^3.0.1\"\n }\n}\n","import { ipAddress } from '@vercel/functions';\nimport { NextRequest, NextResponse } from 'next/server';\nimport { version } from '../../package.json';\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 Prepr version header\n response.headers.set('Prepr-Package', version);\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"]}
|
package/dist/server/index.d.cts
CHANGED
|
@@ -1,34 +1,73 @@
|
|
|
1
|
-
import { PreprSegment,
|
|
1
|
+
import { PreprErrorCode, PreprSegment, PreprToolbarProps } from '../types/index.cjs';
|
|
2
|
+
export { default as createPreprMiddleware } from '../middleware/index.cjs';
|
|
3
|
+
import 'next/server';
|
|
2
4
|
|
|
5
|
+
/**
|
|
6
|
+
* Custom error class for Prepr-related errors
|
|
7
|
+
*/
|
|
8
|
+
declare class PreprError extends Error {
|
|
9
|
+
readonly code: PreprErrorCode;
|
|
10
|
+
readonly context?: string | undefined;
|
|
11
|
+
readonly originalError?: Error | undefined;
|
|
12
|
+
constructor(message: string, code: PreprErrorCode, context?: string | undefined, originalError?: Error | undefined);
|
|
13
|
+
}
|
|
3
14
|
/**
|
|
4
15
|
* Returns the Prepr Customer ID from the headers
|
|
16
|
+
* @returns Prepr Customer ID
|
|
5
17
|
*/
|
|
6
18
|
declare function getPreprUUID(): Promise<string | null>;
|
|
7
19
|
/**
|
|
8
|
-
*
|
|
20
|
+
* Returns the active segment from the headers
|
|
21
|
+
* @returns Active segment
|
|
9
22
|
*/
|
|
10
23
|
declare function getActiveSegment(): Promise<string | null>;
|
|
11
24
|
/**
|
|
12
25
|
* Returns the active variant from the headers
|
|
26
|
+
* @returns Active variant
|
|
13
27
|
*/
|
|
14
28
|
declare function getActiveVariant(): Promise<string | null>;
|
|
15
29
|
/**
|
|
16
|
-
* Helper function to retrieve Prepr headers
|
|
30
|
+
* Helper function to retrieve all Prepr headers
|
|
31
|
+
* @returns Object with Prepr headers
|
|
32
|
+
*/
|
|
33
|
+
declare function getPreprHeaders(): Promise<Record<string, string>>;
|
|
34
|
+
/**
|
|
35
|
+
* Validates a Prepr GraphQL token
|
|
36
|
+
* @param token - The token to validate
|
|
37
|
+
* @returns Validation result with error details if invalid
|
|
38
|
+
*/
|
|
39
|
+
declare function validatePreprToken(token: string): {
|
|
40
|
+
valid: boolean;
|
|
41
|
+
error?: string;
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* Checks if the current environment is in preview mode
|
|
45
|
+
* @returns True if in preview mode
|
|
46
|
+
*/
|
|
47
|
+
declare function isPreviewMode(): boolean;
|
|
48
|
+
/**
|
|
49
|
+
* Extracts the access token from a Prepr GraphQL URL
|
|
50
|
+
* @param graphqlUrl - The full Prepr GraphQL URL
|
|
51
|
+
* @returns The access token or null if invalid
|
|
52
|
+
* @example
|
|
53
|
+
* ```typescript
|
|
54
|
+
* const token = extractAccessToken('https://graphql.prepr.io/abc123')
|
|
55
|
+
* // Returns: 'abc123'
|
|
56
|
+
* ```
|
|
17
57
|
*/
|
|
18
|
-
declare function
|
|
19
|
-
[key: string]: string;
|
|
20
|
-
}>;
|
|
58
|
+
declare function extractAccessToken(graphqlUrl: string): string | null;
|
|
21
59
|
/**
|
|
22
60
|
* Fetches the segments from the Prepr API
|
|
23
|
-
* @param token Prepr
|
|
24
|
-
* @returns Array of
|
|
61
|
+
* @param token Prepr GraphQL URL with scope 'segments'
|
|
62
|
+
* @returns Array of PreprSegment
|
|
63
|
+
* @throws PreprError if the request fails
|
|
25
64
|
*/
|
|
26
65
|
declare function getPreprEnvironmentSegments(token: string): Promise<PreprSegment[]>;
|
|
27
66
|
/**
|
|
28
67
|
* Fetches all the necessary previewbar props
|
|
29
|
-
* @param token Prepr
|
|
68
|
+
* @param token Prepr GraphQL URL with scope 'segments'
|
|
30
69
|
* @returns Object with activeSegment, activeVariant and data
|
|
31
70
|
*/
|
|
32
|
-
declare function
|
|
71
|
+
declare function getToolbarProps(token: string): Promise<PreprToolbarProps>;
|
|
33
72
|
|
|
34
|
-
export { getActiveSegment, getActiveVariant, getPreprEnvironmentSegments, getPreprHeaders, getPreprUUID,
|
|
73
|
+
export { PreprError, extractAccessToken, getActiveSegment, getActiveVariant, getPreprEnvironmentSegments, getPreprHeaders, getPreprUUID, getToolbarProps, isPreviewMode, validatePreprToken };
|
package/dist/server/index.d.ts
CHANGED
|
@@ -1,34 +1,73 @@
|
|
|
1
|
-
import { PreprSegment,
|
|
1
|
+
import { PreprErrorCode, PreprSegment, PreprToolbarProps } from '../types/index.js';
|
|
2
|
+
export { default as createPreprMiddleware } from '../middleware/index.js';
|
|
3
|
+
import 'next/server';
|
|
2
4
|
|
|
5
|
+
/**
|
|
6
|
+
* Custom error class for Prepr-related errors
|
|
7
|
+
*/
|
|
8
|
+
declare class PreprError extends Error {
|
|
9
|
+
readonly code: PreprErrorCode;
|
|
10
|
+
readonly context?: string | undefined;
|
|
11
|
+
readonly originalError?: Error | undefined;
|
|
12
|
+
constructor(message: string, code: PreprErrorCode, context?: string | undefined, originalError?: Error | undefined);
|
|
13
|
+
}
|
|
3
14
|
/**
|
|
4
15
|
* Returns the Prepr Customer ID from the headers
|
|
16
|
+
* @returns Prepr Customer ID
|
|
5
17
|
*/
|
|
6
18
|
declare function getPreprUUID(): Promise<string | null>;
|
|
7
19
|
/**
|
|
8
|
-
*
|
|
20
|
+
* Returns the active segment from the headers
|
|
21
|
+
* @returns Active segment
|
|
9
22
|
*/
|
|
10
23
|
declare function getActiveSegment(): Promise<string | null>;
|
|
11
24
|
/**
|
|
12
25
|
* Returns the active variant from the headers
|
|
26
|
+
* @returns Active variant
|
|
13
27
|
*/
|
|
14
28
|
declare function getActiveVariant(): Promise<string | null>;
|
|
15
29
|
/**
|
|
16
|
-
* Helper function to retrieve Prepr headers
|
|
30
|
+
* Helper function to retrieve all Prepr headers
|
|
31
|
+
* @returns Object with Prepr headers
|
|
32
|
+
*/
|
|
33
|
+
declare function getPreprHeaders(): Promise<Record<string, string>>;
|
|
34
|
+
/**
|
|
35
|
+
* Validates a Prepr GraphQL token
|
|
36
|
+
* @param token - The token to validate
|
|
37
|
+
* @returns Validation result with error details if invalid
|
|
38
|
+
*/
|
|
39
|
+
declare function validatePreprToken(token: string): {
|
|
40
|
+
valid: boolean;
|
|
41
|
+
error?: string;
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* Checks if the current environment is in preview mode
|
|
45
|
+
* @returns True if in preview mode
|
|
46
|
+
*/
|
|
47
|
+
declare function isPreviewMode(): boolean;
|
|
48
|
+
/**
|
|
49
|
+
* Extracts the access token from a Prepr GraphQL URL
|
|
50
|
+
* @param graphqlUrl - The full Prepr GraphQL URL
|
|
51
|
+
* @returns The access token or null if invalid
|
|
52
|
+
* @example
|
|
53
|
+
* ```typescript
|
|
54
|
+
* const token = extractAccessToken('https://graphql.prepr.io/abc123')
|
|
55
|
+
* // Returns: 'abc123'
|
|
56
|
+
* ```
|
|
17
57
|
*/
|
|
18
|
-
declare function
|
|
19
|
-
[key: string]: string;
|
|
20
|
-
}>;
|
|
58
|
+
declare function extractAccessToken(graphqlUrl: string): string | null;
|
|
21
59
|
/**
|
|
22
60
|
* Fetches the segments from the Prepr API
|
|
23
|
-
* @param token Prepr
|
|
24
|
-
* @returns Array of
|
|
61
|
+
* @param token Prepr GraphQL URL with scope 'segments'
|
|
62
|
+
* @returns Array of PreprSegment
|
|
63
|
+
* @throws PreprError if the request fails
|
|
25
64
|
*/
|
|
26
65
|
declare function getPreprEnvironmentSegments(token: string): Promise<PreprSegment[]>;
|
|
27
66
|
/**
|
|
28
67
|
* Fetches all the necessary previewbar props
|
|
29
|
-
* @param token Prepr
|
|
68
|
+
* @param token Prepr GraphQL URL with scope 'segments'
|
|
30
69
|
* @returns Object with activeSegment, activeVariant and data
|
|
31
70
|
*/
|
|
32
|
-
declare function
|
|
71
|
+
declare function getToolbarProps(token: string): Promise<PreprToolbarProps>;
|
|
33
72
|
|
|
34
|
-
export { getActiveSegment, getActiveVariant, getPreprEnvironmentSegments, getPreprHeaders, getPreprUUID,
|
|
73
|
+
export { PreprError, extractAccessToken, getActiveSegment, getActiveVariant, getPreprEnvironmentSegments, getPreprHeaders, getPreprUUID, getToolbarProps, isPreviewMode, validatePreprToken };
|
package/dist/server/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {a}from'../chunk-QZTUT4DH.js';export{b as createPreprMiddleware}from'../chunk-QZTUT4DH.js';import {c}from'../chunk-E7ATRJ2F.js';import {headers}from'next/headers';var s=class extends Error{constructor(r,t,a,h){super(r);this.code=t;this.context=a;this.originalError=h;this.name="PreprError";}};function i(e){return c(this,null,function*(){return (yield headers()).get(e)})}function S(){return c(this,null,function*(){return i("prepr-customer-id")})}function g(){return c(this,null,function*(){return i("Prepr-Segments")})}function u(){return c(this,null,function*(){return i("Prepr-ABtesting")})}function T(){return c(this,null,function*(){let e={};return (yield headers()).forEach((r,t)=>{(t.startsWith("prepr")||t.startsWith("Prepr"))&&(e[t]=r);}),e})}function P(e){return e?e.startsWith("https://")?{valid:true}:{valid:false,error:"Token must be a valid HTTPS URL"}:{valid:false,error:"Token is required"}}function m(){return process.env.PREPR_ENV==="preview"}function x(e){if(!e)return null;try{let n=new URL(e);if(n.hostname!=="graphql.prepr.io")return null;let r=n.pathname.split("/"),t=r[r.length-1];return t&&t.length>0?t:null}catch(n){return null}}function d(e){return c(this,null,function*(){let n=P(e);if(!n.valid)throw new s(n.error,"INVALID_TOKEN","getPreprEnvironmentSegments");try{let r=yield fetch(e,{headers:{"User-Agent":`Prepr-Preview-Bar/${f()}`,"Content-Type":"application/json"},method:"POST",body:JSON.stringify({query:`{
|
|
2
2
|
_Segments {
|
|
3
3
|
_id
|
|
4
4
|
name
|
|
5
5
|
}
|
|
6
|
-
}`})});
|
|
6
|
+
}`})});if(!r.ok)throw new s(`HTTP ${r.status}: ${r.statusText}`,"HTTP_ERROR","getPreprEnvironmentSegments");let t=yield r.json();if(!t||!t.data||!t.data._Segments)throw new s("Invalid response format from Prepr API","INVALID_RESPONSE","getPreprEnvironmentSegments");return t.data._Segments}catch(r){throw r instanceof s?r:new s("Failed to fetch segments from Prepr API","FETCH_ERROR","getPreprEnvironmentSegments",r instanceof Error?r:new Error(String(r)))}})}function y(e){return c(this,null,function*(){let n=[],r=null,t=null;if(m())try{n=yield d(e),r=yield g(),t=yield u();}catch(a){console.error("Failed to fetch toolbar props:",a),n=[];}return {activeSegment:r,activeVariant:t,data:n}})}function f(){return a.version}export{s as PreprError,x as extractAccessToken,g as getActiveSegment,u as getActiveVariant,d as getPreprEnvironmentSegments,T as getPreprHeaders,S as getPreprUUID,y as getToolbarProps,m as isPreviewMode,P as validatePreprToken};//# sourceMappingURL=index.js.map
|
|
7
7
|
//# sourceMappingURL=index.js.map
|
package/dist/server/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../package.json","../../src/server/index.ts"],"names":["package_default","getPreprUUID","__async","headers","getActiveSegment","getActiveVariant","getPreprHeaders","newHeaders","value","key","getPreprEnvironmentSegments","token","_a","response","getPackageVersion","json","e","error","getPreviewBarProps","data","activeSegment","activeVariant"],"mappings":"+EAAA,IAAAA,CAAAA,CAAA,CAEE,OAAA,CAAW,eAkHb,EC7GA,SAAsBC,CAAAA,EAAe,CAAA,OAAAC,GAAAA,CAAA,sBAEnC,OAAA,CADoB,MAAMC,OAAAA,EAAQ,EACf,IAAI,mBAAmB,CAC5C,GAKA,SAAsBC,CAAAA,EAAmB,QAAAF,GAAAA,CAAA,IAAA,CAAA,IAAA,CAAA,WAAA,CAEvC,OAAA,CADoB,MAAMC,SAAQ,EACf,GAAA,CAAI,gBAAgB,CACzC,GAKA,SAAsBE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,CAAAA,CAAK,OAAL,IAAA,CAAA,KAAA,CAAA,CAAAH,CAAAA,CAAW,SACpB,CAAA,MAAQI,CAAAA,CAAA,CACN,OAAA,OAAA,CAAQ,KAAA,CAAM,kDAAkD,EACzD,EACT,CACF,CAAA,MAASC,CAAAA,CAAO,CACd,OAAA,OAAA,CAAQ,KAAA,CAAM,0BAAA,CAA4BA,CAAK,CAAA,CACxC,EACT,CACF,CAAA,CAAA,CAOA,SAAsBC,CAAAA,CACpBP,CAAAA,CAC+B,QAAAT,GAAAA,CAAA,IAAA,CAAA,IAAA,CAAA,WAAA,CAC/B,IAAIiB,CAAAA,CAAuB,GACvBC,CAAAA,CAA+B,IAAA,CAC/BC,EAA+B,IAAA,CAGnC,OAAI,QAAQ,GAAA,CAAI,SAAA,GAAc,SAAA,GAC5BF,CAAAA,CAAO,MAAMT,CAAAA,CAA4BC,CAAK,CAAA,CAC9CS,CAAAA,CAAgB,MAAMhB,CAAAA,EAAiB,CACvCiB,EAAgB,MAAMhB,CAAAA,EAAiB,CAAA,CAGlC,CACL,aAAA,CAAAe,CAAAA,CACA,cAAAC,CAAAA,CACA,IAAA,CAAAF,CACF,CACF,CAAA,CAAA,CAEA,SAASL,CAAAA,EAAoB,CAC3B,OAAOd,CAAAA,CAAM,OACf","file":"index.js","sourcesContent":["{\n \"name\": \"@preprio/prepr-nextjs\",\n \"version\": \"2.0.0-alpha.9\",\n \"description\": \"Next.js package for Prepr CMS preview functionality with advanced debugging and visual editing capabilities\",\n \"main\": \"dist/react/index.cjs\",\n \"types\": \"./dist/react/index.d.ts\",\n \"module\": \"./dist/react/index.js\",\n \"type\": \"module\",\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"dev:css\": \"postcss ./src/globals.css -o ./src/output.css --watch\",\n \"build:css\": \"NODE_ENV=production postcss ./src/globals.css -o ./dist/index.css\",\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n \"clean\": \"rm -rf dist\",\n \"format\": \"prettier --write \\\"src/**/*.{ts,tsx,js,jsx,json,md}\\\"\",\n \"format:check\": \"prettier --check \\\"src/**/*.{ts,tsx,js,jsx,json,md}\\\"\",\n \"release\": \"node scripts/release.js\",\n \"check\": \"npm run type-check && npm run lint:check && npm run format:check\",\n \"type-check\": \"tsc --noEmit\",\n \"lint\": \"eslint src --ext .ts,.tsx --fix\",\n \"lint:check\": \"eslint src --ext .ts,.tsx\",\n \"prepublishOnly\": \"npm run check && npm run build\"\n },\n \"exports\": {\n \"./middleware\": {\n \"import\": \"./dist/middleware/index.js\",\n \"types\": \"./dist/middleware/index.d.ts\",\n \"require\": \"./dist/middleware/index.cjs\"\n },\n \"./server\": {\n \"import\": \"./dist/server/index.js\",\n \"types\": \"./dist/server/index.d.ts\",\n \"require\": \"./dist/server/index.cjs\"\n },\n \"./react\": {\n \"import\": \"./dist/react/index.js\",\n \"types\": \"./dist/react/index.d.ts\",\n \"require\": \"./dist/react/index.cjs\"\n },\n \"./contexts\": {\n \"import\": \"./dist/contexts/index.js\",\n \"types\": \"./dist/contexts/index.d.ts\",\n \"require\": \"./dist/contexts/index.cjs\"\n },\n \"./utils\": {\n \"import\": \"./dist/utils/index.js\",\n \"types\": \"./dist/utils/index.d.ts\",\n \"require\": \"./dist/utils/index.cjs\"\n },\n \"./types\": {\n \"import\": \"./dist/types/index.js\",\n \"types\": \"./dist/types/index.d.ts\",\n \"require\": \"./dist/types/index.cjs\"\n },\n \"./index.css\": {\n \"import\": \"./dist/index.css\",\n \"require\": \"./dist/index.css\"\n }\n },\n \"files\": [\n \"dist\",\n \"package.json\"\n ],\n \"keywords\": [\n \"prepr\",\n \"cms\",\n \"nextjs\",\n \"preview\",\n \"visual-editing\",\n \"headless-cms\",\n \"react\",\n \"typescript\",\n \"debug\",\n \"stega\"\n ],\n \"author\": \"Preprio\",\n \"license\": \"MIT\",\n \"packageManager\": \"pnpm@10.5.2\",\n \"devDependencies\": {\n \"@eslint/js\": \"^9.25.1\",\n \"@types/node\": \"^20.11.5\",\n \"@types/react\": \"19.1.0\",\n \"@types/react-dom\": \"19.1.2\",\n \"@typescript-eslint/eslint-plugin\": \"^8.31.1\",\n \"@typescript-eslint/parser\": \"^8.31.1\",\n \"autoprefixer\": \"^10.4.21\",\n \"cssnano\": \"^7.0.7\",\n \"eslint\": \"^9.25.1\",\n \"eslint-config-prettier\": \"^10.1.2\",\n \"eslint-plugin-prettier\": \"^5.2.6\",\n \"eslint-plugin-react\": \"^7.37.2\",\n \"eslint-plugin-react-hooks\": \"^5.0.0\",\n \"next\": \"15.3.1\",\n \"postcss\": \"^8\",\n \"prettier\": \"^3.5.3\",\n \"prettier-plugin-tailwindcss\": \"^0.5.12\",\n \"react\": \"^19.1.0\",\n \"react-dom\": \"^19.1.0\",\n \"tailwindcss\": \"^3.4.17\",\n \"tsup\": \"^8.5.0\",\n \"typescript\": \"^5.8.3\"\n },\n \"peerDependencies\": {\n \"next\": \"^15.0.0 || ^14.0.0 || ^13.0.0\",\n \"react\": \"^19.0.0 || ^18.0.0 || ^17.0.0 \",\n \"react-dom\": \"^19.0.0 || ^18.0.0 || ^17.0.0\"\n },\n \"dependencies\": {\n \"@headlessui/react\": \"^2.2.0\",\n \"@vercel/functions\": \"^2.0.0\",\n \"@vercel/stega\": \"^0.1.2\",\n \"clsx\": \"^2.1.1\",\n \"postcss-cli\": \"^11.0.1\",\n \"tailwind-merge\": \"^3.0.1\"\n }\n}\n","import { headers } from 'next/headers';\nimport { PreprPreviewBarProps, PreprSegment } from '../types';\nimport pjson from '../../package.json';\n\n/**\n * Returns the Prepr Customer ID from the headers\n */\nexport async function getPreprUUID() {\n const headersList = await headers();\n return headersList.get('prepr-customer-id');\n}\n\n/**\n * Retuns the active segment from the headers\n */\nexport async function getActiveSegment() {\n const headersList = await headers();\n return headersList.get('Prepr-Segments');\n}\n\n/**\n * Returns the active variant from the headers\n */\nexport async function getActiveVariant() {\n const headersList = await headers();\n return headersList.get('Prepr-ABtesting');\n}\n\n/**\n * Helper function to retrieve Prepr headers (will filter out customer ID if in preview mode)\n */\nexport async function getPreprHeaders() {\n const newHeaders: {\n [key: string]: string;\n } = {};\n\n const headersList = await headers();\n\n headersList.forEach((value, key) => {\n if (key.startsWith('prepr')) {\n newHeaders[key] = value;\n }\n });\n\n return newHeaders;\n}\n\n/**\n * Fetches the segments from the Prepr API\n * @param token Prepr access token with scope 'segments'\n * @returns Array of PreprSegmentResponse\n */\nexport async function getPreprEnvironmentSegments(\n token: string\n): Promise<PreprSegment[]> {\n if (!token) {\n console.error(\n 'No token provided, make sure you are using your Prepr GraphQL URL'\n );\n return [];\n }\n\n if (!token.startsWith('https://')) {\n console.error(\n 'Invalid token provided, make sure you are using your Prepr GraphQL URL'\n );\n return [];\n }\n\n try {\n const response = await fetch(token, {\n headers: {\n 'User-Agent': `Prepr-Preview-Bar/${getPackageVersion()}`,\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify({\n query: `{\n _Segments {\n _id\n name\n }\n }`,\n }),\n });\n try {\n const json = await response.json();\n\n if (!json || !json.data || !json.data._Segments) {\n return [];\n }\n\n return json.data?._Segments as PreprSegment[];\n } catch {\n console.error('Error parsing JSON, please contact Prepr support');\n return [];\n }\n } catch (error) {\n console.error('Error fetching segments:', error);\n return [];\n }\n}\n\n/**\n * Fetches all the necessary previewbar props\n * @param token Prepr access token with scope 'segments'\n * @returns Object with activeSegment, activeVariant and data\n */\nexport async function getPreviewBarProps(\n token: string\n): Promise<PreprPreviewBarProps> {\n let data: PreprSegment[] = [];\n let activeSegment: string | null = null;\n let activeVariant: string | null = null;\n\n // Prevent unnecessary function calling in production\n if (process.env.PREPR_ENV === 'preview') {\n data = await getPreprEnvironmentSegments(token);\n activeSegment = await getActiveSegment();\n activeVariant = await getActiveVariant();\n }\n\n return {\n activeSegment,\n activeVariant,\n data,\n };\n}\n\nfunction getPackageVersion() {\n return pjson.version;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/server/index.ts"],"names":["PreprError","message","code","context","originalError","getPreprHeader","name","__async","headers","getPreprUUID","getActiveSegment","getActiveVariant","getPreprHeaders","preprHeaders","value","key","validatePreprToken","token","isPreviewMode","extractAccessToken","graphqlUrl","url","pathParts","e","getPreprEnvironmentSegments","validation","response","getPackageVersion","json","error","getToolbarProps","data","activeSegment","activeVariant","package_default"],"mappings":"0KAaO,IAAMA,CAAAA,CAAN,cAAyB,KAAM,CACpC,WAAA,CACEC,CAAAA,CACgBC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CAChB,CACA,KAAA,CAAMH,CAAO,CAAA,CAJG,IAAA,CAAA,IAAA,CAAAC,CAAAA,CACA,IAAA,CAAA,OAAA,CAAAC,CAAAA,CACA,IAAA,CAAA,aAAA,CAAAC,CAAAA,CAGhB,IAAA,CAAK,IAAA,CAAO,aACd,CACF,EAOA,SAAeC,CAAAA,CAAeC,CAAAA,CAA+C,CAAA,OAAAC,CAAAA,CAAA,IAAA,CAAA,IAAA,CAAA,WAAA,CAE3E,OAAA,CADoB,MAAMC,OAAAA,EAAQ,EACf,GAAA,CAAIF,CAAI,CAC7B,CAAA,CAAA,CAMA,SAAsBG,GAAuC,CAAA,OAAAF,CAAAA,CAAA,IAAA,CAAA,IAAA,CAAA,WAAA,CAC3D,OAAOF,CAAAA,CAAe,mBAAmB,CAC3C,CAAA,CAAA,CAMA,SAAsBK,CAAAA,EAA2C,CAAA,OAAAH,CAAAA,CAAA,IAAA,CAAA,IAAA,CAAA,WAAA,CAC/D,OAAOF,EAAe,gBAAgB,CACxC,CAAA,CAAA,CAMA,SAAsBM,CAAAA,EAA2C,CAAA,OAAAJ,CAAAA,CAAA,IAAA,CAAA,IAAA,CAAA,WAAA,CAC/D,OAAOF,CAAAA,CAAe,iBAAiB,CACzC,CAAA,CAAA,CAMA,SAAsBO,GAAmD,CAAA,OAAAL,CAAAA,CAAA,IAAA,CAAA,IAAA,CAAA,WAAA,CACvE,IAAMM,CAAAA,CAAuC,EAAC,CAG9C,OAAA,CAFoB,M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AAA,IAAA,CAAA,IAAA,CAAA,WAAA,CAC5B,IAAIwB,EAAuB,EAAC,CACxBC,CAAAA,CAA+B,IAAA,CAC/BC,CAAAA,CAA+B,IAAA,CAGnC,GAAIf,CAAAA,EAAc,CAChB,GAAI,CACFa,CAAAA,CAAO,MAAMP,CAAAA,CAA4BP,CAAK,CAAA,CAC9Ce,EAAgB,MAAMtB,CAAAA,EAAiB,CACvCuB,CAAAA,CAAgB,MAAMtB,CAAAA,GACxB,CAAA,MAASkB,CAAAA,CAAO,CAEd,OAAA,CAAQ,KAAA,CAAM,gCAAA,CAAkCA,CAAK,CAAA,CAErDE,CAAAA,CAAO,GACT,CAGF,OAAO,CACL,aAAA,CAAAC,CAAAA,CACA,aAAA,CAAAC,CAAAA,CACA,IAAA,CAAAF,CACF,CACF,CAAA,CAAA,CAEA,SAASJ,CAAAA,EAAoB,CAC3B,OAAOO,EAAM,OACf","file":"index.js","sourcesContent":["import { headers } from 'next/headers';\nimport {\n PreprToolbarProps,\n PreprSegment,\n PreprHeaderName,\n PreprErrorCode,\n} from '../types';\nimport pjson from '../../package.json';\nimport createPreprMiddleware from '../middleware';\n\n/**\n * Custom error class for Prepr-related errors\n */\nexport class PreprError extends Error {\n constructor(\n message: string,\n public readonly code: PreprErrorCode,\n public readonly context?: string,\n public readonly originalError?: Error\n ) {\n super(message);\n this.name = 'PreprError';\n }\n}\n\n/**\n * Internal helper to get a specific Prepr header value\n * @param name - The header name to retrieve\n * @returns The header value or null if not found\n */\nasync function getPreprHeader(name: PreprHeaderName): Promise<string | null> {\n const headersList = await headers();\n return headersList.get(name);\n}\n\n/**\n * Returns the Prepr Customer ID from the headers\n * @returns Prepr Customer ID\n */\nexport async function getPreprUUID(): Promise<string | null> {\n return getPreprHeader('prepr-customer-id');\n}\n\n/**\n * Returns the active segment from the headers\n * @returns Active segment\n */\nexport async function getActiveSegment(): Promise<string | null> {\n return getPreprHeader('Prepr-Segments');\n}\n\n/**\n * Returns the active variant from the headers\n * @returns Active variant\n */\nexport async function getActiveVariant(): Promise<string | null> {\n return getPreprHeader('Prepr-ABtesting');\n}\n\n/**\n * Helper function to retrieve all Prepr headers\n * @returns Object with Prepr headers\n */\nexport async function getPreprHeaders(): Promise<Record<string, string>> {\n const preprHeaders: Record<string, string> = {};\n const headersList = await headers();\n\n headersList.forEach((value, key) => {\n if (key.startsWith('prepr') || key.startsWith('Prepr')) {\n preprHeaders[key] = value;\n }\n });\n\n return preprHeaders;\n}\n\n/**\n * Validates a Prepr GraphQL token\n * @param token - The token to validate\n * @returns Validation result with error details if invalid\n */\nexport function validatePreprToken(token: string): {\n valid: boolean;\n error?: string;\n} {\n if (!token) {\n return { valid: false, error: 'Token is required' };\n }\n if (!token.startsWith('https://')) {\n return { valid: false, error: 'Token must be a valid HTTPS URL' };\n }\n return { valid: true };\n}\n\n/**\n * Checks if the current environment is in preview mode\n * @returns True if in preview mode\n */\nexport function isPreviewMode(): boolean {\n return process.env.PREPR_ENV === 'preview';\n}\n\n/**\n * Extracts the access token from a Prepr GraphQL URL\n * @param graphqlUrl - The full Prepr GraphQL URL\n * @returns The access token or null if invalid\n * @example\n * ```typescript\n * const token = extractAccessToken('https://graphql.prepr.io/abc123')\n * // Returns: 'abc123'\n * ```\n */\nexport function extractAccessToken(graphqlUrl: string): string | null {\n if (!graphqlUrl) return null;\n\n try {\n const url = new URL(graphqlUrl);\n if (url.hostname !== 'graphql.prepr.io') return null;\n\n const pathParts = url.pathname.split('/');\n const token = pathParts[pathParts.length - 1];\n\n return token && token.length > 0 ? token : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Fetches the segments from the Prepr API\n * @param token Prepr GraphQL URL with scope 'segments'\n * @returns Array of PreprSegment\n * @throws PreprError if the request fails\n */\nexport async function getPreprEnvironmentSegments(\n token: string\n): Promise<PreprSegment[]> {\n const validation = validatePreprToken(token);\n if (!validation.valid) {\n throw new PreprError(\n validation.error!,\n 'INVALID_TOKEN',\n 'getPreprEnvironmentSegments'\n );\n }\n\n try {\n const response = await fetch(token, {\n headers: {\n 'User-Agent': `Prepr-Preview-Bar/${getPackageVersion()}`,\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify({\n query: `{\n _Segments {\n _id\n name\n }\n }`,\n }),\n });\n\n if (!response.ok) {\n throw new PreprError(\n `HTTP ${response.status}: ${response.statusText}`,\n 'HTTP_ERROR',\n 'getPreprEnvironmentSegments'\n );\n }\n\n const json = await response.json();\n\n if (!json || !json.data || !json.data._Segments) {\n throw new PreprError(\n 'Invalid response format from Prepr API',\n 'INVALID_RESPONSE',\n 'getPreprEnvironmentSegments'\n );\n }\n\n return json.data._Segments as PreprSegment[];\n } catch (error) {\n if (error instanceof PreprError) {\n throw error;\n }\n throw new PreprError(\n 'Failed to fetch segments from Prepr API',\n 'FETCH_ERROR',\n 'getPreprEnvironmentSegments',\n error instanceof Error ? error : new Error(String(error))\n );\n }\n}\n\n/**\n * Fetches all the necessary previewbar props\n * @param token Prepr GraphQL URL with scope 'segments'\n * @returns Object with activeSegment, activeVariant and data\n */\nexport async function getToolbarProps(\n token: string\n): Promise<PreprToolbarProps> {\n let data: PreprSegment[] = [];\n let activeSegment: string | null = null;\n let activeVariant: string | null = null;\n\n // Prevent unnecessary function calling in production\n if (isPreviewMode()) {\n try {\n data = await getPreprEnvironmentSegments(token);\n activeSegment = await getActiveSegment();\n activeVariant = await getActiveVariant();\n } catch (error) {\n // In preview mode, we should still return props even if API fails\n console.error('Failed to fetch toolbar props:', error);\n // Return empty data to prevent toolbar from crashing\n data = [];\n }\n }\n\n return {\n activeSegment,\n activeVariant,\n data,\n };\n}\n\nfunction getPackageVersion() {\n return pjson.version;\n}\n\nexport { createPreprMiddleware };\n"]}
|
package/dist/types/index.d.cts
CHANGED
|
@@ -1,14 +1,34 @@
|
|
|
1
|
-
|
|
2
|
-
_id: string;
|
|
3
|
-
name: string;
|
|
4
|
-
}
|
|
5
|
-
|
|
6
|
-
debug?: boolean;
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
activeSegment: string | null;
|
|
10
|
-
activeVariant: string | null;
|
|
11
|
-
data: PreprSegment[];
|
|
12
|
-
}
|
|
1
|
+
interface PreprSegment {
|
|
2
|
+
readonly _id: string;
|
|
3
|
+
readonly name: string;
|
|
4
|
+
}
|
|
5
|
+
interface PreprToolbarOptions {
|
|
6
|
+
readonly debug?: boolean;
|
|
7
|
+
}
|
|
8
|
+
interface PreprToolbarProps {
|
|
9
|
+
readonly activeSegment: string | null;
|
|
10
|
+
readonly activeVariant: string | null;
|
|
11
|
+
readonly data: readonly PreprSegment[];
|
|
12
|
+
}
|
|
13
|
+
type PreprHeaderName = 'prepr-customer-id' | 'Prepr-Segments' | 'Prepr-ABtesting';
|
|
14
|
+
type PreprVariant = 'A' | 'B';
|
|
15
|
+
type PreprEnvironment = 'preview' | 'production';
|
|
16
|
+
type PreprEventType = 'segment_changed' | 'variant_changed' | 'edit_mode_toggled' | 'personalization_reset' | 'getScrollPosition' | 'loaded';
|
|
17
|
+
interface PreprHeaders {
|
|
18
|
+
readonly 'prepr-customer-id'?: string;
|
|
19
|
+
readonly 'Prepr-Segments'?: string;
|
|
20
|
+
readonly 'Prepr-ABtesting'?: PreprVariant;
|
|
21
|
+
readonly 'Prepr-Preview-Bar'?: 'true';
|
|
22
|
+
readonly 'Prepr-Context-utm_source'?: string;
|
|
23
|
+
readonly 'Prepr-Context-utm_medium'?: string;
|
|
24
|
+
readonly 'Prepr-Context-utm_term'?: string;
|
|
25
|
+
readonly 'Prepr-Context-utm_content'?: string;
|
|
26
|
+
readonly 'Prepr-Context-utm_campaign'?: string;
|
|
27
|
+
readonly 'Prepr-Context-initial_referral'?: string;
|
|
28
|
+
readonly 'Prepr-Visitor-IP'?: string;
|
|
29
|
+
readonly 'Prepr-Hubspot-Id'?: string;
|
|
30
|
+
readonly 'Prepr-Customer-Id-Created'?: 'true';
|
|
31
|
+
}
|
|
32
|
+
type PreprErrorCode = 'INVALID_TOKEN' | 'MISSING_TOKEN' | 'HTTP_ERROR' | 'FETCH_ERROR' | 'INVALID_RESPONSE' | 'CONTEXT_ERROR';
|
|
13
33
|
|
|
14
|
-
export type {
|
|
34
|
+
export type { PreprEnvironment, PreprErrorCode, PreprEventType, PreprHeaderName, PreprHeaders, PreprSegment, PreprToolbarOptions, PreprToolbarProps, PreprVariant };
|
package/dist/types/index.d.ts
CHANGED
|
@@ -1,14 +1,34 @@
|
|
|
1
|
-
|
|
2
|
-
_id: string;
|
|
3
|
-
name: string;
|
|
4
|
-
}
|
|
5
|
-
|
|
6
|
-
debug?: boolean;
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
activeSegment: string | null;
|
|
10
|
-
activeVariant: string | null;
|
|
11
|
-
data: PreprSegment[];
|
|
12
|
-
}
|
|
1
|
+
interface PreprSegment {
|
|
2
|
+
readonly _id: string;
|
|
3
|
+
readonly name: string;
|
|
4
|
+
}
|
|
5
|
+
interface PreprToolbarOptions {
|
|
6
|
+
readonly debug?: boolean;
|
|
7
|
+
}
|
|
8
|
+
interface PreprToolbarProps {
|
|
9
|
+
readonly activeSegment: string | null;
|
|
10
|
+
readonly activeVariant: string | null;
|
|
11
|
+
readonly data: readonly PreprSegment[];
|
|
12
|
+
}
|
|
13
|
+
type PreprHeaderName = 'prepr-customer-id' | 'Prepr-Segments' | 'Prepr-ABtesting';
|
|
14
|
+
type PreprVariant = 'A' | 'B';
|
|
15
|
+
type PreprEnvironment = 'preview' | 'production';
|
|
16
|
+
type PreprEventType = 'segment_changed' | 'variant_changed' | 'edit_mode_toggled' | 'personalization_reset' | 'getScrollPosition' | 'loaded';
|
|
17
|
+
interface PreprHeaders {
|
|
18
|
+
readonly 'prepr-customer-id'?: string;
|
|
19
|
+
readonly 'Prepr-Segments'?: string;
|
|
20
|
+
readonly 'Prepr-ABtesting'?: PreprVariant;
|
|
21
|
+
readonly 'Prepr-Preview-Bar'?: 'true';
|
|
22
|
+
readonly 'Prepr-Context-utm_source'?: string;
|
|
23
|
+
readonly 'Prepr-Context-utm_medium'?: string;
|
|
24
|
+
readonly 'Prepr-Context-utm_term'?: string;
|
|
25
|
+
readonly 'Prepr-Context-utm_content'?: string;
|
|
26
|
+
readonly 'Prepr-Context-utm_campaign'?: string;
|
|
27
|
+
readonly 'Prepr-Context-initial_referral'?: string;
|
|
28
|
+
readonly 'Prepr-Visitor-IP'?: string;
|
|
29
|
+
readonly 'Prepr-Hubspot-Id'?: string;
|
|
30
|
+
readonly 'Prepr-Customer-Id-Created'?: 'true';
|
|
31
|
+
}
|
|
32
|
+
type PreprErrorCode = 'INVALID_TOKEN' | 'MISSING_TOKEN' | 'HTTP_ERROR' | 'FETCH_ERROR' | 'INVALID_RESPONSE' | 'CONTEXT_ERROR';
|
|
13
33
|
|
|
14
|
-
export type {
|
|
34
|
+
export type { PreprEnvironment, PreprErrorCode, PreprEventType, PreprHeaderName, PreprHeaders, PreprSegment, PreprToolbarOptions, PreprToolbarProps, PreprVariant };
|
package/dist/utils/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var clsx=require('clsx'),tailwindMerge=require('tailwind-merge');var
|
|
1
|
+
'use strict';var clsx=require('clsx'),tailwindMerge=require('tailwind-merge');var D=Object.defineProperty,x=Object.defineProperties;var v=Object.getOwnPropertyDescriptors;var f=Object.getOwnPropertySymbols;var y=Object.prototype.hasOwnProperty,L=Object.prototype.propertyIsEnumerable;var T=(r,t,e)=>t in r?D(r,t,{enumerable:true,configurable:true,writable:true,value:e}):r[t]=e,u=(r,t)=>{for(var e in t||(t={}))y.call(t,e)&&T(r,e,t[e]);if(f)for(var e of f(t))L.call(t,e)&&T(r,e,t[e]);return r},h=(r,t)=>x(r,v(t));var E={DECODE_FAILED:"STEGA_DECODE_FAILED",INVALID_FORMAT:"STEGA_INVALID_FORMAT",DOM_MANIPULATION_FAILED:"DOM_MANIPULATION_FAILED",CONTEXT_NOT_FOUND:"CONTEXT_NOT_FOUND"};function p(r,t,e,n){return {type:r,context:t,message:e.message,timestamp:new Date().toISOString(),stack:e.stack,additionalData:n}}function M(r,t,e){let n=p(E.DECODE_FAILED,t,r,e);return console.error("Stega Error:",n),process.env.NODE_ENV,n}function s(r,t){let e=p(E.DOM_MANIPULATION_FAILED,t,r);return console.error("DOM Error:",e),e}function I(r){let t=new Error(`${r} must be used within its provider`),e=p(E.CONTEXT_NOT_FOUND,r,t);throw console.error("Context Error:",e),t}var b=class{static createElement(t,e){try{let n=document.createElement(t);return n.className=e,n}catch(n){throw s(n,"createElement"),n}}static appendToBody(t){try{document.body.appendChild(t);}catch(e){throw s(e,"appendToBody"),e}}static removeFromBody(t){try{t.parentNode&&t.parentNode.removeChild(t);}catch(e){throw s(e,"removeFromBody"),e}}static setElementStyles(t,e){try{Object.entries(e).forEach(([n,o])=>{t.style.setProperty(n,o);});}catch(n){throw s(n,"setElementStyles"),n}}static getElementRect(t){try{return t.getBoundingClientRect()}catch(e){throw s(e,"getElementRect"),e}}static isElementInViewport(t){try{let e=this.getElementRect(t);return e.top>=0&&e.left>=0&&e.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&e.right<=(window.innerWidth||document.documentElement.clientWidth)}catch(e){return s(e,"isElementInViewport"),false}}static calculateDistance(t,e,n,o){return Math.sqrt(Math.pow(n-t,2)+Math.pow(o-e,2))}static findClosestElement(t,e,n){try{let o=null,i=1/0;return n.forEach(c=>{let a=this.getElementRect(c),m=this.calculateDistance(t,e,a.left+a.width/2,a.top+a.height/2);m<i&&(i=m,o=c);}),o}catch(o){return s(o,"findClosestElement"),null}}static addEventListener(t,e,n,o){try{t.addEventListener(e,n,o);}catch(i){throw s(i,"addEventListener"),i}}static removeEventListener(t,e,n,o){try{t.removeEventListener(e,n,o);}catch(i){throw s(i,"removeEventListener"),i}}};var d=class r{constructor(t){this.options=u({prefix:"[Prepr]"},t);}isEnabled(){var t,e;return this.options.enabled!==void 0?this.options.enabled:(e=(t=l==null?void 0:l.options)==null?void 0:t.enabled)!=null?e:false}log(t,...e){if(!this.isEnabled())return;let n=this.options.prefix;console.log(`${n} ${t}`,...e);}warn(t,...e){if(!this.isEnabled())return;let n=this.options.prefix;console.warn(`${n} ${t}`,...e);}error(t,...e){if(!this.isEnabled())return;let n=this.options.prefix;console.error(`${n} ${t}`,...e);}scope(t){return new r(h(u({},this.options),{prefix:`${this.options.prefix}[${t}]`}))}},l=null;function S(r=false){l=new d({enabled:r});}function g(){return l||(l=new d({enabled:false})),l}function C(r,...t){g().log(r,...t);}function H(r,...t){g().warn(r,...t);}function P(r,...t){g().error(r,...t);}function $(r){return new d({prefix:`[Prepr][${r}]`})}function k(r,t){let e=null,n=0,o=(...i)=>{let c=Date.now(),a=c-n;a>=t?(r(...i),n=c):(e&&clearTimeout(e),e=setTimeout(()=>{r(...i),n=Date.now(),e=null;},t-a));};return o.cancel=()=>{e&&(clearTimeout(e),e=null);},o}function U(r,t){let e=null,n=(...o)=>{e&&clearTimeout(e),e=setTimeout(()=>{r(...o),e=null;},t);};return n.cancel=()=>{e&&(clearTimeout(e),e=null);},n}function B(r,t=1e3){let e=null,n=0;return ()=>{let o=Date.now();return (!e||o-n>t)&&(e=document.querySelectorAll(r),n=o),e}}function G(...r){return tailwindMerge.twMerge(clsx.clsx(r))}function J(r,t){typeof window!="undefined"&&window.parent&&window.parent.postMessage(u({name:"prepr_preview_bar",event:r},t),"*");}exports.DOMService=b;exports.StegaError=E;exports.cn=G;exports.createElementCache=B;exports.createErrorInfo=p;exports.createScopedLogger=$;exports.debounce=U;exports.debugError=P;exports.debugLog=C;exports.debugWarn=H;exports.getDebugLogger=g;exports.handleContextError=I;exports.handleDOMError=s;exports.handleStegaError=M;exports.initDebugLogger=S;exports.sendPreprEvent=J;exports.throttle=k;//# sourceMappingURL=index.cjs.map
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/utils/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/index.ts","../../src/utils/errors.ts","../../src/utils/dom.ts","../../src/utils/debug.ts","../../src/utils/performance.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","currentTime","createElementCache","query","ttl","cache","lastCacheTime","now","cn","inputs","twMerge","clsx","sendPreprEvent","data"],"mappings":"8EAAA,IAAA,CAAA,CAAA,MAAA,CAAA,cAAA,CAAA,CAAA,CAAA,MAAA,CAAA,gBAAA,CAAA,IAAA,CAAA,CAAA,MAAA,CAAA,yBAAA,CAAA,IAAA,CAAA,CAAA,MAAA,CAAA,qBAAA,CAAA,IAAA,CAAA,CAAA,MAAA,CAAA,SAAA,CAAA,cAAA,CAAA,CAAA,CAAA,MAAA,CAAA,SAAA,CAAA,oBAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,UAAA,CAAA,IAAA,CAAA,YAAA,CAAA,IAAA,CAAA,QAAA,CAAA,IAAA,CAAA,KAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,IAAA,IAAA,CAAA,IAAA,CAAA,GAAA,CAAA,CAAA,EAAA,CAAA,CAAA,CAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,CAAA,IAAA,IAAA,CAAA,IAAA,CAAA,C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CAAA,CAEnB,OAAQ,IAAIhB,CAAAA,GAAoB,CAC9B,IAAMiB,CAAAA,CAAc,IAAA,CAAK,KAAI,CACzBA,CAAAA,CAAcD,CAAAA,CAAeF,CAAAA,EAC/BD,EAAK,GAAIb,CAAsB,EAC/BgB,CAAAA,CAAeC,CAAAA,GAEXF,GAAW,YAAA,CAAaA,CAAS,EACrCA,CAAAA,CAAY,UAAA,CACV,IAAM,CACJF,CAAAA,CAAK,GAAIb,CAAsB,CAAA,CAC/BgB,EAAe,IAAA,CAAK,GAAA,GACtB,CAAA,CACAF,CAAAA,EAASG,EAAcD,CAAAA,CACzB,CAAA,EAEJ,CACF,CAGO,SAASE,EACdC,CAAAA,CACAC,CAAAA,CAAc,IACd,CACA,IAAIC,EAA8B,IAAA,CAC9BC,CAAAA,CAAgB,EACpB,OAAO,IAAM,CACX,IAAMC,CAAAA,CAAM,IAAA,CAAK,GAAA,GACjB,OAAA,CAAI,CAACF,GAASE,CAAAA,CAAMD,CAAAA,CAAgBF,KAClCC,CAAAA,CAAQ,QAAA,CAAS,iBAAoBF,CAAK,CAAA,CAC1CG,EAAgBC,CAAAA,CAAAA,CAEXF,CACT,CACF,CJxCO,SAASG,KAAMC,CAAAA,CAAsB,CAC1C,OAAOC,qBAAAA,CAAQC,SAAAA,CAAKF,CAAM,CAAC,CAC7B,CAUO,SAASG,CAAAA,CAAenC,EAAeoC,CAAAA,CAAuB,CACnE,OAAO,MAAA,CAAO,WAAA,CAAY/B,EAAA,CACxB,IAAA,CAAM,oBACN,KAAA,CAAAL,CAAAA,CAAAA,CACGoC,EACJ,EACH","file":"index.cjs","sourcesContent":["import { ClassValue, clsx } from 'clsx';\nimport { twMerge } from 'tailwind-merge';\n\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs));\n}\n\n// Define specific types for Prepr events\nexport interface PreprEventData {\n segment?: string;\n variant?: string;\n editMode?: boolean;\n [key: string]: string | boolean | number | undefined;\n}\n\nexport function sendPreprEvent(event: string, data?: PreprEventData) {\n window.parent.postMessage({\n name: 'prepr_preview_bar',\n event,\n ...data,\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","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// TODO: Refine the type for args and return value if possible\nexport function throttle<T extends (...args: any[]) => any>(\n func: T,\n delay: number\n): T {\n let timeoutId: NodeJS.Timeout | null = null;\n let lastExecTime = 0;\n\n return ((...args: unknown[]) => {\n const currentTime = Date.now();\n if (currentTime - lastExecTime > delay) {\n func(...(args as Parameters<T>));\n lastExecTime = currentTime;\n } else {\n if (timeoutId) clearTimeout(timeoutId);\n timeoutId = setTimeout(\n () => {\n func(...(args as Parameters<T>));\n lastExecTime = Date.now();\n },\n delay - (currentTime - lastExecTime)\n );\n }\n }) as T;\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"]}
|
|
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":"igBAAO,IAAMA,CAAAA,CAAa,CACxB,aAAA,CAAe,sBACf,cAAA,CAAgB,sBAAA,CAChB,wBAAyB,yBAAA,CACzB,iBAAA,CAAmB,mBACrB,EAqBO,SAASC,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,EACW,CACX,OAAO,CACL,IAAA,CAAAH,CAAAA,CACA,QAAAC,CAAAA,CACA,OAAA,CAASC,CAAAA,CAAM,OAAA,CACf,SAAA,CAAW,IAAI,MAAK,CAAE,WAAA,EAAY,CAClC,KAAA,CAAOA,CAAAA,CAAM,KAAA,CACb,eAAAC,CACF,CACF,CAEO,SAASC,CAAAA,CACdF,CAAAA,CACAD,EACAE,CAAAA,CACA,CACA,IAAME,CAAAA,CAAYN,CAAAA,CAChBD,EAAW,aAAA,CACXG,CAAAA,CACAC,CAAAA,CACAC,CACF,CAAA,CAEA,OAAA,OAAA,C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FO,SAASG,CAAAA,CAAAA,GAAMC,CAAAA,CAAsB,CAC1C,OAAOC,qBAAAA,CAAQC,SAAAA,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.cjs","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"]}
|