@encatch/web-sdk 0.0.35 → 1.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/README.md +140 -638
  2. package/dist/encatch.es.js +2 -0
  3. package/dist/encatch.es.js.map +1 -0
  4. package/dist/encatch.iife.js +2 -0
  5. package/dist/encatch.iife.js.map +1 -0
  6. package/dist/index.d.ts +197 -0
  7. package/package.json +32 -50
  8. package/dist-sdk/plugin/sdk/core-wrapper-BMvOyc0u.js +0 -22926
  9. package/dist-sdk/plugin/sdk/module-DC2Edddk.js +0 -481
  10. package/dist-sdk/plugin/sdk/module.js +0 -5
  11. package/dist-sdk/plugin/sdk/preview-sdk.html +0 -1182
  12. package/dist-sdk/plugin/sdk/vite.svg +0 -15
  13. package/dist-sdk/plugin/sdk/web-form-engine-core.css +0 -1
  14. package/index.d.ts +0 -207
  15. package/src/@types/encatch-type.ts +0 -111
  16. package/src/encatch-instance.ts +0 -161
  17. package/src/feedback-api-types.ts +0 -18
  18. package/src/hooks/useDevice.ts +0 -30
  19. package/src/hooks/useFeedbackInterval.ts +0 -71
  20. package/src/hooks/useFeedbackTriggers.ts +0 -342
  21. package/src/hooks/useFetchElligibleFeedbackConfiguration.ts +0 -363
  22. package/src/hooks/useFetchFeedbackConfigurationDetails.ts +0 -92
  23. package/src/hooks/usePageChangeTracker.ts +0 -88
  24. package/src/hooks/usePrepopulatedAnswers.ts +0 -123
  25. package/src/hooks/useRefineTextForm.ts +0 -55
  26. package/src/hooks/useSubmitFeedbackForm.ts +0 -134
  27. package/src/hooks/useUserSession.ts +0 -53
  28. package/src/module.tsx +0 -428
  29. package/src/store/formResponses.ts +0 -211
  30. package/src/utils/browser-details.ts +0 -36
  31. package/src/utils/duration-utils.ts +0 -158
  32. package/src/utils/feedback-frequency-storage.ts +0 -214
  33. package/src/utils/feedback-storage.ts +0 -166
@@ -0,0 +1,2 @@
1
+ const e="encatch-sdk-script";let n=!1,t=!1,i=null;function o(e,n){return function(...t){e.push([n,...t])}}const r=["init","identifyUser","setLocale","setCountry","setTheme","trackEvent","trackScreen","startSession","resetUser","showForm","addToResponse"];function c(){const c=[],s=[],a={_q:c,_eventCallbacks:s,_initialized:!1,_apiKey:null,_config:{},init(o,r){a._initialized?console.warn("[Encatch] SDK already initialized. Ignoring init call."):(a._apiKey=o,a._config=r||{},a._initialized=!0,c.push(["init",o,r]),"undefined"!=typeof window&&"undefined"!=typeof document&&function(o){return t?Promise.resolve():i?Promise.reject(i):n?new Promise((e,n)=>{const o=setInterval(()=>{t?(clearInterval(o),e()):i&&(clearInterval(o),n(i))},50)}):(n=!0,new Promise((r,c)=>{if(document.getElementById(e))return n=!1,t=!0,void r();const s=(o.webHost||"https://app.encatch.com")+"/s/sdk/v1/encatch.js",a=document.createElement("script");a.id=e,a.src=s,a.type="module",a.async=!0,a.onload=()=>{n=!1,t=!0,r()},a.onerror=e=>{n=!1,i=new Error(`[Encatch] Failed to load SDK from ${s}. Please check your network connection and web host configuration.`),console.error(i.message,e),c(i)};const d=document.getElementsByTagName("script")[0];d&&d.parentNode?d.parentNode.insertBefore(a,d):document.head.appendChild(a)}))}(a._config).catch(e=>{console.error("[Encatch] Failed to initialize SDK:",e)}))},on:e=>(s.push(e),()=>{const n=s.indexOf(e);n>-1&&s.splice(n,1)}),identifyUser:()=>{},setLocale:()=>{},setCountry:()=>{},setTheme:()=>{},trackEvent:()=>{},trackScreen:()=>{},startSession:()=>{},resetUser:()=>{},showForm:()=>{},addToResponse:()=>{}},d=r.filter(e=>"init"!==e);for(const e of d)a[e]=o(c,e);return a}const s=function(){if("undefined"!=typeof window){const e=window._encatch;if(e&&Array.isArray(e._q)){const n=c();return n._q.push(...e._q),Array.isArray(e._eventCallbacks)&&n._eventCallbacks.push(...e._eventCallbacks),e._initialized&&(n._initialized=e._initialized,n._apiKey=e._apiKey,n._config=e._config||{}),window._encatch=n,n}const n=c();return window._encatch=n,n}return c()}();export{s as _encatch,s as default};
2
+ //# sourceMappingURL=encatch.es.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encatch.es.js","sources":["../src/loader.ts","../src/queue.ts","../src/index.ts"],"sourcesContent":["/**\n * Script Loader Utility\n * \n * Handles the dynamic loading of the remote SDK implementation script.\n * Provides error handling and prevents duplicate script injection.\n */\n\nimport type { EncatchConfig } from './types';\n\n/** Default web host for the remote implementation script */\nconst DEFAULT_WEB_HOST = 'https://app.encatch.com';\n\n/** Fixed path for the SDK script */\nconst SDK_SCRIPT_PATH = '/s/sdk/v1/encatch.js';\n\n/** Script element ID to prevent duplicate injections */\nconst SCRIPT_ID = 'encatch-sdk-script';\n\n/** Track loading state */\nlet isLoading = false;\nlet isLoaded = false;\nlet loadError: Error | null = null;\n\n/**\n * Load the remote SDK implementation script\n * \n * @param config - Configuration containing optional custom web host\n * @returns Promise that resolves when script loads, rejects on error\n */\nexport function loadRemoteScript(config: EncatchConfig): Promise<void> {\n // Return early if already loaded\n if (isLoaded) {\n return Promise.resolve();\n }\n\n // Return error if previous load failed\n if (loadError) {\n return Promise.reject(loadError);\n }\n\n // Return existing promise if already loading\n if (isLoading) {\n return new Promise((resolve, reject) => {\n const checkInterval = setInterval(() => {\n if (isLoaded) {\n clearInterval(checkInterval);\n resolve();\n } else if (loadError) {\n clearInterval(checkInterval);\n reject(loadError);\n }\n }, 50);\n });\n }\n\n isLoading = true;\n\n return new Promise((resolve, reject) => {\n // Check if script already exists in DOM\n const existingScript = document.getElementById(SCRIPT_ID);\n if (existingScript) {\n isLoading = false;\n isLoaded = true;\n resolve();\n return;\n }\n\n // Determine script URL from webHost\n const webHost = config.webHost || DEFAULT_WEB_HOST;\n const scriptUrl = webHost + SDK_SCRIPT_PATH;\n\n // Create and configure script element\n const script = document.createElement('script');\n script.id = SCRIPT_ID;\n script.src = scriptUrl;\n script.type = 'module';\n script.async = true;\n\n // Handle successful load\n script.onload = () => {\n isLoading = false;\n isLoaded = true;\n resolve();\n };\n\n // Handle load error\n script.onerror = (event) => {\n isLoading = false;\n loadError = new Error(\n `[Encatch] Failed to load SDK from ${scriptUrl}. ` +\n `Please check your network connection and web host configuration.`\n );\n console.error(loadError.message, event);\n reject(loadError);\n };\n\n // Inject script into document head\n const firstScript = document.getElementsByTagName('script')[0];\n if (firstScript && firstScript.parentNode) {\n firstScript.parentNode.insertBefore(script, firstScript);\n } else {\n document.head.appendChild(script);\n }\n });\n}\n\n/**\n * Check if the remote script has been loaded\n */\nexport function isScriptLoaded(): boolean {\n return isLoaded;\n}\n\n/**\n * Reset loader state (useful for testing)\n */\nexport function resetLoaderState(): void {\n isLoading = false;\n isLoaded = false;\n loadError = null;\n}\n\n/**\n * Get the default script URL\n */\nexport function getDefaultScriptUrl(): string {\n return DEFAULT_WEB_HOST + SDK_SCRIPT_PATH;\n}\n","/**\n * Command Queue Implementation\n * \n * Manages the queue of SDK method calls that occur before the remote\n * implementation script has loaded. Commands are stored as tuples\n * and processed FIFO when the remote script becomes available.\n */\n\nimport type { Command, EncatchSDK } from './types';\n\n/**\n * Process all queued commands by calling the corresponding methods\n * on the SDK instance. This is called by the remote script once loaded.\n * \n * @param sdk - The SDK instance with real implementations\n * @param queue - Array of queued commands to process\n */\nexport function processQueue(sdk: EncatchSDK, queue: Command[]): void {\n while (queue.length > 0) {\n const command = queue.shift();\n if (!command) continue;\n\n const [method, ...args] = command;\n \n // Skip internal properties\n if (method.startsWith('_')) continue;\n\n // Get the method from the SDK\n const fn = sdk[method as keyof EncatchSDK];\n \n if (typeof fn === 'function') {\n try {\n (fn as (...args: unknown[]) => void).apply(sdk, args);\n } catch (error) {\n console.error(`[Encatch] Error processing queued command \"${method}\":`, error);\n }\n } else {\n console.warn(`[Encatch] Unknown method in queue: \"${method}\"`);\n }\n }\n}\n\n/**\n * Creates a stub method that queues calls for later processing\n * \n * @param queue - The command queue array\n * @param methodName - Name of the method being stubbed\n * @returns A function that pushes calls to the queue\n */\nexport function createQueuedMethod(\n queue: Command[],\n methodName: string\n): (...args: unknown[]) => void {\n return function (...args: unknown[]): void {\n queue.push([methodName, ...args]);\n };\n}\n\n/**\n * List of SDK methods that should be queued before initialization\n */\nexport const QUEUED_METHODS = [\n 'init',\n 'identifyUser',\n 'setLocale',\n 'setCountry',\n 'setTheme',\n 'trackEvent',\n 'trackScreen',\n 'startSession',\n 'resetUser',\n 'showForm',\n 'addToResponse',\n] as const;\n\nexport type QueuedMethodName = typeof QUEUED_METHODS[number];\n","/**\n * Encatch Web SDK\n * \n * A lightweight, type-safe SDK for integrating Encatch forms and surveys.\n * This module creates the _encatch global object that queues commands\n * until the remote implementation script loads.\n */\n\nimport type {\n EncatchSDK,\n EncatchConfig,\n UserTraits,\n IdentifyOptions,\n EventCallback,\n Command,\n} from './types';\nimport { loadRemoteScript } from './loader';\nimport { createQueuedMethod, QUEUED_METHODS } from './queue';\n\n// Re-export types for consumers\nexport type {\n EncatchSDK,\n EncatchConfig,\n UserTraits,\n IdentifyOptions,\n EventType,\n EventCallback,\n EventPayload,\n Theme,\n ResetMode,\n ShowFormOptions,\n} from './types';\n\n/**\n * Creates the Encatch SDK stub instance\n * All method calls are queued until setProject() is called and the\n * remote implementation script loads.\n */\nfunction createEncatchStub(): EncatchSDK {\n // Command queue for calls made before remote script loads\n const queue: Command[] = [];\n \n // Event callbacks - all callbacks receive all form events\n const eventCallbacks: EventCallback[] = [];\n\n // Create the SDK object\n const sdk: EncatchSDK = {\n // Internal state\n _q: queue,\n _eventCallbacks: eventCallbacks,\n _initialized: false,\n _apiKey: null,\n _config: {},\n\n // init is special - it triggers script loading\n init(apiKey: string, config?: EncatchConfig): void {\n if (sdk._initialized) {\n console.warn('[Encatch] SDK already initialized. Ignoring init call.');\n return;\n }\n\n sdk._apiKey = apiKey;\n sdk._config = config || {};\n sdk._initialized = true;\n\n // Queue this call for the remote implementation\n queue.push(['init', apiKey, config]);\n\n // Load the remote script\n if (typeof window !== 'undefined' && typeof document !== 'undefined') {\n loadRemoteScript(sdk._config).catch((error) => {\n console.error('[Encatch] Failed to initialize SDK:', error);\n });\n }\n },\n\n // Event subscription - receives all form events\n on(callback: EventCallback): () => void {\n eventCallbacks.push(callback);\n\n // Return unsubscribe function\n return () => {\n const index = eventCallbacks.indexOf(callback);\n if (index > -1) {\n eventCallbacks.splice(index, 1);\n }\n };\n },\n\n // Stub implementations - will be replaced by remote script\n identifyUser: () => {},\n setLocale: () => {},\n setCountry: () => {},\n setTheme: () => {},\n trackEvent: () => {},\n trackScreen: () => {},\n startSession: () => {},\n resetUser: () => {},\n showForm: () => {},\n addToResponse: () => {},\n };\n\n // Replace stub methods with queue-based versions\n // Skip init (handled specially above) and on (handled locally)\n const methodsToQueue = QUEUED_METHODS.filter(m => m !== 'init');\n \n for (const method of methodsToQueue) {\n // Use type assertion to assign queued methods\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (sdk as any)[method] = createQueuedMethod(queue, method);\n }\n\n return sdk;\n}\n\n/**\n * Initialize the global _encatch object\n * This runs immediately when the script loads\n */\nfunction initGlobal(): EncatchSDK {\n // Check for existing instance (may have been created by snippet)\n if (typeof window !== 'undefined') {\n // If _encatch already exists with a queue, preserve it\n const existing = window._encatch;\n if (existing && Array.isArray(existing._q)) {\n // Merge existing queue into new instance\n const sdk = createEncatchStub();\n sdk._q.push(...existing._q);\n \n // Copy over any existing callbacks\n if (Array.isArray(existing._eventCallbacks)) {\n sdk._eventCallbacks.push(...existing._eventCallbacks);\n }\n \n // Copy initialization state\n if (existing._initialized) {\n sdk._initialized = existing._initialized;\n sdk._apiKey = existing._apiKey;\n sdk._config = existing._config || {};\n }\n \n window._encatch = sdk;\n return sdk;\n }\n\n // Create fresh instance\n const sdk = createEncatchStub();\n window._encatch = sdk;\n return sdk;\n }\n\n // Non-browser environment\n return createEncatchStub();\n}\n\n// Initialize and export\nexport const _encatch = initGlobal();\n\n// Default export for convenience\nexport default _encatch;\n"],"names":["SCRIPT_ID","isLoading","isLoaded","loadError","createQueuedMethod","queue","methodName","args","push","QUEUED_METHODS","createEncatchStub","eventCallbacks","sdk","_q","_eventCallbacks","_initialized","_apiKey","_config","init","apiKey","config","console","warn","window","document","Promise","resolve","reject","checkInterval","setInterval","clearInterval","getElementById","scriptUrl","webHost","script","createElement","id","src","type","async","onload","onerror","event","Error","error","message","firstScript","getElementsByTagName","parentNode","insertBefore","head","appendChild","loadRemoteScript","catch","on","callback","index","indexOf","splice","identifyUser","setLocale","setCountry","setTheme","trackEvent","trackScreen","startSession","resetUser","showForm","addToResponse","methodsToQueue","filter","m","method","_encatch","existing","Array","isArray","initGlobal"],"mappings":"AAUA,MAMMA,EAAY,qBAGlB,IAAIC,GAAY,EACZC,GAAW,EACXC,EAA0B,KC4BvB,SAASC,EACdC,EACAC,GAEA,OAAO,YAAaC,GAClBF,EAAMG,KAAK,CAACF,KAAeC,GAC7B,CACF,CAKO,MAAME,EAAiB,CAC5B,OACA,eACA,YACA,aACA,WACA,aACA,cACA,eACA,YACA,WACA,iBClCF,SAASC,IAEP,MAAML,EAAmB,GAGnBM,EAAkC,GAGlCC,EAAkB,CAEtBC,GAAIR,EACJS,gBAAiBH,EACjBI,cAAc,EACdC,QAAS,KACTC,QAAS,CAAA,EAGT,IAAAC,CAAKC,EAAgBC,GACfR,EAAIG,aACNM,QAAQC,KAAK,2DAIfV,EAAII,QAAUG,EACdP,EAAIK,QAAUG,GAAU,CAAA,EACxBR,EAAIG,cAAe,EAGnBV,EAAMG,KAAK,CAAC,OAAQW,EAAQC,IAGN,oBAAXG,QAA8C,oBAAbC,UFxC3C,SAA0BJ,GAE/B,OAAIlB,EACKuB,QAAQC,UAIbvB,EACKsB,QAAQE,OAAOxB,GAIpBF,EACK,IAAIwB,QAAQ,CAACC,EAASC,KAC3B,MAAMC,EAAgBC,YAAY,KAC5B3B,GACF4B,cAAcF,GACdF,KACSvB,IACT2B,cAAcF,GACdD,EAAOxB,KAER,OAIPF,GAAY,EAEL,IAAIwB,QAAQ,CAACC,EAASC,KAG3B,GADuBH,SAASO,eAAe/B,G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BN,QAAQkE,EAAS5D,iBAInC4D,EAAS3D,eACXH,EAAIG,aAAe2D,EAAS3D,aAC5BH,EAAII,QAAU0D,EAAS1D,QACvBJ,EAAIK,QAAUyD,EAASzD,SAAW,CAAA,GAGpCM,OAAOkD,SAAW7D,EACXA,CACT,CAGA,MAAMA,EAAMF,IAEZ,OADAa,OAAOkD,SAAW7D,EACXA,CACT,CAGA,OAAOF,GACT,CAGwBmE"}
@@ -0,0 +1,2 @@
1
+ !function(e){"use strict";const n="encatch-sdk-script";let t=!1,i=!1,o=null;function c(e,n){return function(...t){e.push([n,...t])}}const r=["init","identifyUser","setLocale","setCountry","setTheme","trackEvent","trackScreen","startSession","resetUser","showForm","addToResponse"];function s(){const e=[],s=[],a={_q:e,_eventCallbacks:s,_initialized:!1,_apiKey:null,_config:{},init(c,r){a._initialized?console.warn("[Encatch] SDK already initialized. Ignoring init call."):(a._apiKey=c,a._config=r||{},a._initialized=!0,e.push(["init",c,r]),"undefined"!=typeof window&&"undefined"!=typeof document&&function(e){return i?Promise.resolve():o?Promise.reject(o):t?new Promise((e,n)=>{const t=setInterval(()=>{i?(clearInterval(t),e()):o&&(clearInterval(t),n(o))},50)}):(t=!0,new Promise((c,r)=>{if(document.getElementById(n))return t=!1,i=!0,void c();const s=(e.webHost||"https://app.encatch.com")+"/s/sdk/v1/encatch.js",a=document.createElement("script");a.id=n,a.src=s,a.type="module",a.async=!0,a.onload=()=>{t=!1,i=!0,c()},a.onerror=e=>{t=!1,o=new Error(`[Encatch] Failed to load SDK from ${s}. Please check your network connection and web host configuration.`),console.error(o.message,e),r(o)};const l=document.getElementsByTagName("script")[0];l&&l.parentNode?l.parentNode.insertBefore(a,l):document.head.appendChild(a)}))}(a._config).catch(e=>{console.error("[Encatch] Failed to initialize SDK:",e)}))},on:e=>(s.push(e),()=>{const n=s.indexOf(e);n>-1&&s.splice(n,1)}),identifyUser:()=>{},setLocale:()=>{},setCountry:()=>{},setTheme:()=>{},trackEvent:()=>{},trackScreen:()=>{},startSession:()=>{},resetUser:()=>{},showForm:()=>{},addToResponse:()=>{}},l=r.filter(e=>"init"!==e);for(const n of l)a[n]=c(e,n);return a}const a=function(){if("undefined"!=typeof window){const e=window._encatch;if(e&&Array.isArray(e._q)){const n=s();return n._q.push(...e._q),Array.isArray(e._eventCallbacks)&&n._eventCallbacks.push(...e._eventCallbacks),e._initialized&&(n._initialized=e._initialized,n._apiKey=e._apiKey,n._config=e._config||{}),window._encatch=n,n}const n=s();return window._encatch=n,n}return s()}();e._encatch=a,e.default=a,Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}(this._encatch=this._encatch||{});
2
+ //# sourceMappingURL=encatch.iife.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encatch.iife.js","sources":["../src/loader.ts","../src/queue.ts","../src/index.ts"],"sourcesContent":["/**\n * Script Loader Utility\n * \n * Handles the dynamic loading of the remote SDK implementation script.\n * Provides error handling and prevents duplicate script injection.\n */\n\nimport type { EncatchConfig } from './types';\n\n/** Default web host for the remote implementation script */\nconst DEFAULT_WEB_HOST = 'https://app.encatch.com';\n\n/** Fixed path for the SDK script */\nconst SDK_SCRIPT_PATH = '/s/sdk/v1/encatch.js';\n\n/** Script element ID to prevent duplicate injections */\nconst SCRIPT_ID = 'encatch-sdk-script';\n\n/** Track loading state */\nlet isLoading = false;\nlet isLoaded = false;\nlet loadError: Error | null = null;\n\n/**\n * Load the remote SDK implementation script\n * \n * @param config - Configuration containing optional custom web host\n * @returns Promise that resolves when script loads, rejects on error\n */\nexport function loadRemoteScript(config: EncatchConfig): Promise<void> {\n // Return early if already loaded\n if (isLoaded) {\n return Promise.resolve();\n }\n\n // Return error if previous load failed\n if (loadError) {\n return Promise.reject(loadError);\n }\n\n // Return existing promise if already loading\n if (isLoading) {\n return new Promise((resolve, reject) => {\n const checkInterval = setInterval(() => {\n if (isLoaded) {\n clearInterval(checkInterval);\n resolve();\n } else if (loadError) {\n clearInterval(checkInterval);\n reject(loadError);\n }\n }, 50);\n });\n }\n\n isLoading = true;\n\n return new Promise((resolve, reject) => {\n // Check if script already exists in DOM\n const existingScript = document.getElementById(SCRIPT_ID);\n if (existingScript) {\n isLoading = false;\n isLoaded = true;\n resolve();\n return;\n }\n\n // Determine script URL from webHost\n const webHost = config.webHost || DEFAULT_WEB_HOST;\n const scriptUrl = webHost + SDK_SCRIPT_PATH;\n\n // Create and configure script element\n const script = document.createElement('script');\n script.id = SCRIPT_ID;\n script.src = scriptUrl;\n script.type = 'module';\n script.async = true;\n\n // Handle successful load\n script.onload = () => {\n isLoading = false;\n isLoaded = true;\n resolve();\n };\n\n // Handle load error\n script.onerror = (event) => {\n isLoading = false;\n loadError = new Error(\n `[Encatch] Failed to load SDK from ${scriptUrl}. ` +\n `Please check your network connection and web host configuration.`\n );\n console.error(loadError.message, event);\n reject(loadError);\n };\n\n // Inject script into document head\n const firstScript = document.getElementsByTagName('script')[0];\n if (firstScript && firstScript.parentNode) {\n firstScript.parentNode.insertBefore(script, firstScript);\n } else {\n document.head.appendChild(script);\n }\n });\n}\n\n/**\n * Check if the remote script has been loaded\n */\nexport function isScriptLoaded(): boolean {\n return isLoaded;\n}\n\n/**\n * Reset loader state (useful for testing)\n */\nexport function resetLoaderState(): void {\n isLoading = false;\n isLoaded = false;\n loadError = null;\n}\n\n/**\n * Get the default script URL\n */\nexport function getDefaultScriptUrl(): string {\n return DEFAULT_WEB_HOST + SDK_SCRIPT_PATH;\n}\n","/**\n * Command Queue Implementation\n * \n * Manages the queue of SDK method calls that occur before the remote\n * implementation script has loaded. Commands are stored as tuples\n * and processed FIFO when the remote script becomes available.\n */\n\nimport type { Command, EncatchSDK } from './types';\n\n/**\n * Process all queued commands by calling the corresponding methods\n * on the SDK instance. This is called by the remote script once loaded.\n * \n * @param sdk - The SDK instance with real implementations\n * @param queue - Array of queued commands to process\n */\nexport function processQueue(sdk: EncatchSDK, queue: Command[]): void {\n while (queue.length > 0) {\n const command = queue.shift();\n if (!command) continue;\n\n const [method, ...args] = command;\n \n // Skip internal properties\n if (method.startsWith('_')) continue;\n\n // Get the method from the SDK\n const fn = sdk[method as keyof EncatchSDK];\n \n if (typeof fn === 'function') {\n try {\n (fn as (...args: unknown[]) => void).apply(sdk, args);\n } catch (error) {\n console.error(`[Encatch] Error processing queued command \"${method}\":`, error);\n }\n } else {\n console.warn(`[Encatch] Unknown method in queue: \"${method}\"`);\n }\n }\n}\n\n/**\n * Creates a stub method that queues calls for later processing\n * \n * @param queue - The command queue array\n * @param methodName - Name of the method being stubbed\n * @returns A function that pushes calls to the queue\n */\nexport function createQueuedMethod(\n queue: Command[],\n methodName: string\n): (...args: unknown[]) => void {\n return function (...args: unknown[]): void {\n queue.push([methodName, ...args]);\n };\n}\n\n/**\n * List of SDK methods that should be queued before initialization\n */\nexport const QUEUED_METHODS = [\n 'init',\n 'identifyUser',\n 'setLocale',\n 'setCountry',\n 'setTheme',\n 'trackEvent',\n 'trackScreen',\n 'startSession',\n 'resetUser',\n 'showForm',\n 'addToResponse',\n] as const;\n\nexport type QueuedMethodName = typeof QUEUED_METHODS[number];\n","/**\n * Encatch Web SDK\n * \n * A lightweight, type-safe SDK for integrating Encatch forms and surveys.\n * This module creates the _encatch global object that queues commands\n * until the remote implementation script loads.\n */\n\nimport type {\n EncatchSDK,\n EncatchConfig,\n UserTraits,\n IdentifyOptions,\n EventCallback,\n Command,\n} from './types';\nimport { loadRemoteScript } from './loader';\nimport { createQueuedMethod, QUEUED_METHODS } from './queue';\n\n// Re-export types for consumers\nexport type {\n EncatchSDK,\n EncatchConfig,\n UserTraits,\n IdentifyOptions,\n EventType,\n EventCallback,\n EventPayload,\n Theme,\n ResetMode,\n ShowFormOptions,\n} from './types';\n\n/**\n * Creates the Encatch SDK stub instance\n * All method calls are queued until setProject() is called and the\n * remote implementation script loads.\n */\nfunction createEncatchStub(): EncatchSDK {\n // Command queue for calls made before remote script loads\n const queue: Command[] = [];\n \n // Event callbacks - all callbacks receive all form events\n const eventCallbacks: EventCallback[] = [];\n\n // Create the SDK object\n const sdk: EncatchSDK = {\n // Internal state\n _q: queue,\n _eventCallbacks: eventCallbacks,\n _initialized: false,\n _apiKey: null,\n _config: {},\n\n // init is special - it triggers script loading\n init(apiKey: string, config?: EncatchConfig): void {\n if (sdk._initialized) {\n console.warn('[Encatch] SDK already initialized. Ignoring init call.');\n return;\n }\n\n sdk._apiKey = apiKey;\n sdk._config = config || {};\n sdk._initialized = true;\n\n // Queue this call for the remote implementation\n queue.push(['init', apiKey, config]);\n\n // Load the remote script\n if (typeof window !== 'undefined' && typeof document !== 'undefined') {\n loadRemoteScript(sdk._config).catch((error) => {\n console.error('[Encatch] Failed to initialize SDK:', error);\n });\n }\n },\n\n // Event subscription - receives all form events\n on(callback: EventCallback): () => void {\n eventCallbacks.push(callback);\n\n // Return unsubscribe function\n return () => {\n const index = eventCallbacks.indexOf(callback);\n if (index > -1) {\n eventCallbacks.splice(index, 1);\n }\n };\n },\n\n // Stub implementations - will be replaced by remote script\n identifyUser: () => {},\n setLocale: () => {},\n setCountry: () => {},\n setTheme: () => {},\n trackEvent: () => {},\n trackScreen: () => {},\n startSession: () => {},\n resetUser: () => {},\n showForm: () => {},\n addToResponse: () => {},\n };\n\n // Replace stub methods with queue-based versions\n // Skip init (handled specially above) and on (handled locally)\n const methodsToQueue = QUEUED_METHODS.filter(m => m !== 'init');\n \n for (const method of methodsToQueue) {\n // Use type assertion to assign queued methods\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (sdk as any)[method] = createQueuedMethod(queue, method);\n }\n\n return sdk;\n}\n\n/**\n * Initialize the global _encatch object\n * This runs immediately when the script loads\n */\nfunction initGlobal(): EncatchSDK {\n // Check for existing instance (may have been created by snippet)\n if (typeof window !== 'undefined') {\n // If _encatch already exists with a queue, preserve it\n const existing = window._encatch;\n if (existing && Array.isArray(existing._q)) {\n // Merge existing queue into new instance\n const sdk = createEncatchStub();\n sdk._q.push(...existing._q);\n \n // Copy over any existing callbacks\n if (Array.isArray(existing._eventCallbacks)) {\n sdk._eventCallbacks.push(...existing._eventCallbacks);\n }\n \n // Copy initialization state\n if (existing._initialized) {\n sdk._initialized = existing._initialized;\n sdk._apiKey = existing._apiKey;\n sdk._config = existing._config || {};\n }\n \n window._encatch = sdk;\n return sdk;\n }\n\n // Create fresh instance\n const sdk = createEncatchStub();\n window._encatch = sdk;\n return sdk;\n }\n\n // Non-browser environment\n return createEncatchStub();\n}\n\n// Initialize and export\nexport const _encatch = initGlobal();\n\n// Default export for convenience\nexport default _encatch;\n"],"names":["SCRIPT_ID","isLoading","isLoaded","loadError","createQueuedMethod","queue","methodName","args","push","QUEUED_METHODS","createEncatchStub","eventCallbacks","sdk","_q","_eventCallbacks","_initialized","_apiKey","_config","init","apiKey","config","console","warn","window","document","Promise","resolve","reject","checkInterval","setInterval","clearInterval","getElementById","scriptUrl","webHost","script","createElement","id","src","type","async","onload","onerror","event","Error","error","message","firstScript","getElementsByTagName","parentNode","insertBefore","head","appendChild","loadRemoteScript","catch","on","callback","index","indexOf","splice","identifyUser","setLocale","setCountry","setTheme","trackEvent","trackScreen","startSession","resetUser","showForm","addToResponse","methodsToQueue","filter","m","method","_encatch","existing","Array","isArray","initGlobal"],"mappings":"0BAUA,MAMMA,EAAY,qBAGlB,IAAIC,GAAY,EACZC,GAAW,EACXC,EAA0B,KC4BvB,SAASC,EACdC,EACAC,GAEA,OAAO,YAAaC,GAClBF,EAAMG,KAAK,CAACF,KAAeC,GAC7B,CACF,CAKO,MAAME,EAAiB,CAC5B,OACA,eACA,YACA,aACA,WACA,aACA,cACA,eACA,YACA,WACA,iBClCF,SAASC,IAEP,MAAML,EAAmB,GAGnBM,EAAkC,GAGlCC,EAAkB,CAEtBC,GAAIR,EACJS,gBAAiBH,EACjBI,cAAc,EACdC,QAAS,KACTC,QAAS,CAAA,EAGT,IAAAC,CAAKC,EAAgBC,GACfR,EAAIG,aACNM,QAAQC,KAAK,2DAIfV,EAAII,QAAUG,EACdP,EAAIK,QAAUG,G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VC,cAAe,QAKXC,EAAiB5D,EAAe6D,OAAOC,GAAW,SAANA,GAElD,IAAA,MAAWC,KAAUH,EAGlBzD,EAAY4D,GAAUpE,EAAmBC,EAAOmE,GAGnD,OAAO5D,CACT,CA2CO,MAAM6D,EArCb,WAEE,GAAsB,oBAAXlD,OAAwB,CAEjC,MAAMmD,EAAWnD,OAAOkD,SACxB,GAAIC,GAAYC,MAAMC,QAAQF,EAAS7D,IAAK,CAE1C,MAAMD,EAAMF,IAgBZ,OAfAE,EAAIC,GAAGL,QAAQkE,EAAS7D,IAGpB8D,MAAMC,QAAQF,EAAS5D,kBACzBF,EAAIE,gBAAgBN,QAAQkE,EAAS5D,iBAInC4D,EAAS3D,eACXH,EAAIG,aAAe2D,EAAS3D,aAC5BH,EAAII,QAAU0D,EAAS1D,QACvBJ,EAAIK,QAAUyD,EAASzD,SAAW,CAAA,GAGpCM,OAAOkD,SAAW7D,EACXA,CACT,CAGA,MAAMA,EAAMF,IAEZ,OADAa,OAAOkD,SAAW7D,EACXA,CACT,CAGA,OAAOF,GACT,CAGwBmE"}
@@ -0,0 +1,197 @@
1
+ /**
2
+ * Internal command tuple type for the queue
3
+ */
4
+ declare type Command = [string, ...unknown[]];
5
+
6
+ declare const _encatch: EncatchSDK;
7
+ export { _encatch }
8
+ export default _encatch;
9
+
10
+ /**
11
+ * Configuration options for the SDK
12
+ */
13
+ export declare interface EncatchConfig {
14
+ /** Override the default web host for loading the SDK script */
15
+ webHost?: string;
16
+ /** Theme setting - defaults to 'system' */
17
+ theme?: Theme;
18
+ /** API base URL - defaults to 'https://app.encatch.com' */
19
+ apiBaseUrl?: string;
20
+ /** When true, displays the form inline at full height without modal overlay */
21
+ isFullScreen?: boolean;
22
+ }
23
+
24
+ /**
25
+ * The Encatch SDK interface
26
+ */
27
+ export declare interface EncatchSDK {
28
+ /**
29
+ * Initialize the SDK with an API key
30
+ * This triggers the loading of the remote implementation script
31
+ * @param apiKey - Your Encatch API key
32
+ * @param config - Optional configuration options
33
+ */
34
+ init(apiKey: string, config?: EncatchConfig): void;
35
+ /**
36
+ * Identify the current user
37
+ * @param id - Unique user identifier (required)
38
+ * @param traits - Optional user traits with nested operations ($set, $setOnce, $increment, $decrement, $unset)
39
+ * @param options - Optional settings like locale, country, and secure signature
40
+ */
41
+ identifyUser(id: string, traits?: UserTraits, options?: IdentifyOptions): void;
42
+ /**
43
+ * Set the user's preferred locale
44
+ * @param locale - Comma-separated ISO 639-1 language codes (e.g., 'fr,en,es')
45
+ */
46
+ setLocale(locale: string): void;
47
+ /**
48
+ * Set the user's country
49
+ * @param country - ISO 3166 country code (e.g., 'US', 'FR')
50
+ */
51
+ setCountry(country: string): void;
52
+ /**
53
+ * Set the theme
54
+ * @param theme - Theme value ('light', 'dark', or 'system')
55
+ */
56
+ setTheme(theme: Theme): void;
57
+ /**
58
+ * Track a custom event
59
+ * @param eventName - Name of the event to track
60
+ */
61
+ trackEvent(eventName: string): void;
62
+ /**
63
+ * Track a screen view
64
+ * @param screenName - Name of the screen to track
65
+ */
66
+ trackScreen(screenName: string): void;
67
+ /**
68
+ * Manually start a new session
69
+ * Useful after user login to reset session timing
70
+ */
71
+ startSession(): void;
72
+ /**
73
+ * Reset the current user (logout)
74
+ * Reverts the SDK to anonymous mode
75
+ */
76
+ resetUser(): void;
77
+ /**
78
+ * Show a specific form by ID
79
+ * @param formId - The ID of the form to display
80
+ * @param options - Optional settings for form display behavior
81
+ */
82
+ showForm(formId: string, options?: ShowFormOptions): void;
83
+ /**
84
+ * Prepopulate a form response
85
+ * @param questionId - The ID of the question to prepopulate
86
+ * @param value - The value to set
87
+ */
88
+ addToResponse(questionId: string, value: unknown): void;
89
+ /**
90
+ * Subscribe to all form events
91
+ * The callback receives all form events (show, submit, close, complete, error)
92
+ * @param callback - Function to call when any form event occurs
93
+ * @returns Unsubscribe function
94
+ */
95
+ on(callback: EventCallback): () => void;
96
+ /** Internal: Command queue for calls made before script loads */
97
+ _q: Command[];
98
+ /** Internal: Event callbacks */
99
+ _eventCallbacks: EventCallback[];
100
+ /** Internal: Whether the SDK has been initialized */
101
+ _initialized: boolean;
102
+ /** Internal: The API key */
103
+ _apiKey: string | null;
104
+ /** Internal: Configuration */
105
+ _config: EncatchConfig;
106
+ }
107
+
108
+ /**
109
+ * Event callback function type
110
+ * Receives all form events with the event type and payload
111
+ */
112
+ export declare type EventCallback = (eventType: EventType, payload: EventPayload) => void;
113
+
114
+ /**
115
+ * Event payload structure
116
+ */
117
+ export declare interface EventPayload {
118
+ /** The form ID related to the event */
119
+ formId?: string;
120
+ /** Timestamp of the event */
121
+ timestamp: number;
122
+ /** Additional event-specific data */
123
+ data?: Record<string, unknown>;
124
+ }
125
+
126
+ /**
127
+ * Event types that can be subscribed to
128
+ */
129
+ export declare type EventType = 'form:show' | 'form:started' | 'form:submit' | 'form:complete' | 'form:close' | 'form:dismissed' | 'form:error' | 'form:section:change' | 'form:question:answered';
130
+
131
+ /**
132
+ * Options for the identifyUser method
133
+ */
134
+ export declare interface IdentifyOptions {
135
+ /** User's preferred locale (ISO 639-1 codes, comma-separated) */
136
+ locale?: string;
137
+ /** User's country (ISO 3166 country code) */
138
+ country?: string;
139
+ /** Secure identification options with signature */
140
+ secure?: SecureOptions;
141
+ }
142
+
143
+ /**
144
+ * Reset mode for form data when showing a form
145
+ * - 'always': Clear form data every time showForm is called (default)
146
+ * - 'on-complete': Clear form data only if form was previously completed
147
+ * - 'never': Never clear form data (preserve user's previous answers)
148
+ */
149
+ export declare type ResetMode = 'always' | 'on-complete' | 'never';
150
+
151
+ /**
152
+ * Secure options for user identification
153
+ */
154
+ declare interface SecureOptions {
155
+ /** User signature (required when secure is set) */
156
+ signature: string;
157
+ /** Optional datetime in UTC when the signature was generated */
158
+ generatedDateTimeinUTC?: string;
159
+ }
160
+
161
+ /**
162
+ * Options for the showForm method
163
+ */
164
+ export declare interface ShowFormOptions {
165
+ /**
166
+ * Controls when form data should be cleared
167
+ * @default 'always'
168
+ */
169
+ reset?: ResetMode;
170
+ }
171
+
172
+ /**
173
+ * Theme options
174
+ */
175
+ export declare type Theme = 'light' | 'dark' | 'system';
176
+
177
+ /**
178
+ * Encatch Web SDK Type Definitions
179
+ */
180
+ /**
181
+ * User traits for identifying users
182
+ * Supports nested operations: $set, $setOnce, $increment, $decrement, $unset
183
+ */
184
+ export declare interface UserTraits {
185
+ /** Set user attributes (overwrites existing values) */
186
+ $set?: Record<string, any>;
187
+ /** Set user attributes only if they don't already exist */
188
+ $setOnce?: Record<string, any>;
189
+ /** Increment numeric user attributes */
190
+ $increment?: Record<string, number>;
191
+ /** Decrement numeric user attributes */
192
+ $decrement?: Record<string, number>;
193
+ /** Remove user attributes */
194
+ $unset?: string[];
195
+ }
196
+
197
+ export { }
package/package.json CHANGED
@@ -1,72 +1,54 @@
1
1
  {
2
2
  "name": "@encatch/web-sdk",
3
- "version": "0.0.35",
4
- "description": "A powerful, lightweight JavaScript SDK for collecting user feedback and running surveys on web applications",
3
+ "version": "1.0.0-beta.1",
4
+ "description": "A lightweight, type-safe JavaScript SDK for integrating Encatch forms and surveys",
5
5
  "type": "module",
6
- "main": "dist-sdk/plugin/sdk/module.js",
7
- "module": "dist-sdk/plugin/sdk/module.js",
8
- "types": "index.d.ts",
6
+ "main": "dist/encatch.es.js",
7
+ "module": "dist/encatch.es.js",
8
+ "types": "dist/index.d.ts",
9
9
  "exports": {
10
10
  ".": {
11
- "import": "./dist-sdk/plugin/sdk/module.js",
12
- "types": "./index.d.ts"
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/encatch.es.js",
13
+ "require": "./dist/encatch.iife.js"
13
14
  },
14
- "./cdn": {
15
- "import": "./dist-sdk/plugin/sdk/encatch-web-sdk.js"
16
- },
17
- "./embedded": {
18
- "import": "./dist-sdk/plugin/sdk/embedded-sdk.js"
19
- },
20
- "./preview": {
21
- "import": "./dist-sdk/plugin/sdk/preview-sdk.js"
15
+ "./iife": {
16
+ "import": "./dist/encatch.iife.js"
22
17
  }
23
18
  },
24
19
  "files": [
25
- "dist-sdk",
26
- "index.d.ts",
27
- "src/@types",
28
- "src/hooks",
29
- "src/utils",
30
- "src/store",
31
- "src/feedback-api-types.ts",
32
- "src/module.tsx",
33
- "src/encatch-instance.ts",
20
+ "dist",
34
21
  "README.md"
35
22
  ],
23
+ "sideEffects": false,
36
24
  "keywords": [
37
- "feedback",
38
- "survey",
39
- "sdk",
40
25
  "encatch",
26
+ "sdk",
27
+ "forms",
28
+ "surveys",
29
+ "feedback",
30
+ "analytics",
41
31
  "user-feedback",
42
32
  "web-sdk"
43
33
  ],
44
- "dependencies": {
45
- "@preact/signals": "^2.5.1",
46
- "json-logic-js": "2.0.5",
47
- "lucide-preact": "^0.555.0",
48
- "path-to-regexp": "^8.3.0",
49
- "preact": "^10.27.2",
50
- "preact-iso": "^2.11.0",
51
- "ua-parser-js": "^2.0.6",
52
- "@encatch/api-sdk": "0.0.11",
53
- "@encatch/schema": "0.1.38",
54
- "@encatch/event-publisher": "0.0.2"
55
- },
56
34
  "devDependencies": {
57
- "@preact/preset-vite": "^2.10.2",
58
- "vite": "^7.2.4",
59
- "@encatch/web-form-engine-core": "0.0.0"
35
+ "typescript": "^5.9.3",
36
+ "vite": "^7.3.1",
37
+ "vite-plugin-dts": "^4.5.4",
38
+ "terser": "^5.44.1"
39
+ },
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "https://github.com/encatch/web-sdk"
60
43
  },
61
- "eslintConfig": {
62
- "extends": "preact"
44
+ "license": "MIT",
45
+ "engines": {
46
+ "node": ">=18"
63
47
  },
64
48
  "scripts": {
65
- "dev": "vite",
66
- "build": "vite build && vite build --config vite.module.config.ts",
67
- "build:module": "vite build --config vite.module.config.ts",
68
- "preview": "vite preview",
69
- "preview:sdk": "vite preview --config vite.config.ts",
70
- "clean": "rm -rf dist-sdk"
49
+ "dev": "vite build --watch",
50
+ "build": "vite build",
51
+ "clean": "rm -rf dist",
52
+ "typecheck": "tsc --noEmit"
71
53
  }
72
54
  }