@posthog/browser-common 0.9.5 → 0.9.6

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 (86) hide show
  1. package/dist/client.d.ts +6 -0
  2. package/dist/config.js +1 -1
  3. package/dist/config.mjs +1 -1
  4. package/dist/index.d.ts +1 -0
  5. package/dist/index.js +58 -10
  6. package/dist/index.mjs +1 -0
  7. package/dist/survey-action-matcher.d.ts +27 -0
  8. package/dist/survey-action-matcher.js +169 -0
  9. package/dist/survey-action-matcher.mjs +131 -0
  10. package/dist/survey-constants.d.ts +86 -0
  11. package/dist/survey-constants.js +144 -0
  12. package/dist/survey-constants.mjs +76 -0
  13. package/dist/survey-event-host.d.ts +15 -0
  14. package/dist/survey-event-host.js +18 -0
  15. package/dist/survey-event-host.mjs +1 -0
  16. package/dist/survey-event-receiver-base.d.ts +180 -0
  17. package/dist/survey-event-receiver-base.js +354 -0
  18. package/dist/survey-event-receiver-base.mjs +316 -0
  19. package/dist/survey-event-receiver.d.ts +36 -0
  20. package/dist/survey-event-receiver.js +133 -0
  21. package/dist/survey-event-receiver.mjs +95 -0
  22. package/dist/survey-render-context.d.ts +13 -0
  23. package/dist/survey-render-context.js +45 -0
  24. package/dist/survey-render-context.mjs +7 -0
  25. package/dist/surveys/components/BottomSection.d.ts +12 -0
  26. package/dist/surveys/components/BottomSection.js +82 -0
  27. package/dist/surveys/components/BottomSection.mjs +44 -0
  28. package/dist/surveys/components/ConfirmationMessage.d.ts +10 -0
  29. package/dist/surveys/components/ConfirmationMessage.js +92 -0
  30. package/dist/surveys/components/ConfirmationMessage.mjs +54 -0
  31. package/dist/surveys/components/IntroScreen.d.ts +10 -0
  32. package/dist/surveys/components/IntroScreen.js +78 -0
  33. package/dist/surveys/components/IntroScreen.mjs +40 -0
  34. package/dist/surveys/components/PostHogLogo.d.ts +5 -0
  35. package/dist/surveys/components/PostHogLogo.js +54 -0
  36. package/dist/surveys/components/PostHogLogo.mjs +16 -0
  37. package/dist/surveys/components/QuestionHeader.d.ts +10 -0
  38. package/dist/surveys/components/QuestionHeader.js +82 -0
  39. package/dist/surveys/components/QuestionHeader.mjs +41 -0
  40. package/dist/surveys/components/QuestionTypes.d.ts +31 -0
  41. package/dist/surveys/components/QuestionTypes.js +519 -0
  42. package/dist/surveys/components/QuestionTypes.mjs +469 -0
  43. package/dist/surveys/icons.d.ts +12 -0
  44. package/dist/surveys/icons.js +212 -0
  45. package/dist/surveys/icons.mjs +147 -0
  46. package/dist/surveys/survey-branching.d.ts +12 -0
  47. package/dist/surveys/survey-branching.js +101 -0
  48. package/dist/surveys/survey-branching.mjs +60 -0
  49. package/dist/surveys/survey-styles.d.ts +1 -0
  50. package/dist/surveys/survey-styles.js +40 -0
  51. package/dist/surveys/survey-styles.mjs +2 -0
  52. package/dist/surveys/survey-translations.d.ts +22 -0
  53. package/dist/surveys/survey-translations.js +68 -0
  54. package/dist/surveys/survey-translations.mjs +27 -0
  55. package/dist/surveys/survey-url-prefill.d.ts +36 -0
  56. package/dist/surveys/survey-url-prefill.js +162 -0
  57. package/dist/surveys/survey-url-prefill.mjs +118 -0
  58. package/dist/surveys/surveys-extension-utils.d.ts +133 -0
  59. package/dist/surveys/surveys-extension-utils.js +739 -0
  60. package/dist/surveys/surveys-extension-utils.mjs +608 -0
  61. package/dist/surveys-config.d.ts +60 -0
  62. package/dist/surveys-config.js +68 -0
  63. package/dist/surveys-config.mjs +9 -0
  64. package/dist/surveys-renderer.d.ts +248 -0
  65. package/dist/surveys-renderer.js +1299 -0
  66. package/dist/surveys-renderer.mjs +1230 -0
  67. package/dist/surveys.d.ts +117 -0
  68. package/dist/surveys.js +566 -0
  69. package/dist/surveys.mjs +495 -0
  70. package/dist/types/surveys.d.ts +83 -86
  71. package/dist/types/surveys.js +1 -127
  72. package/dist/types/surveys.mjs +1 -76
  73. package/dist/utils/autocapture-utils.js +8 -9
  74. package/dist/utils/autocapture-utils.mjs +8 -9
  75. package/dist/utils/matcher-utils.d.ts +1 -1
  76. package/dist/utils/matcher-utils.js +13 -10
  77. package/dist/utils/matcher-utils.mjs +10 -7
  78. package/dist/utils/survey-utils.d.ts +16 -0
  79. package/dist/utils/survey-utils.js +121 -0
  80. package/dist/utils/survey-utils.mjs +38 -0
  81. package/dist/utils/url-targeting-utils.d.ts +3 -1
  82. package/dist/utils/url-targeting-utils.js +1 -2
  83. package/dist/utils/url-targeting-utils.mjs +1 -2
  84. package/dist/utils/uuidv7.js +4 -4
  85. package/dist/utils/uuidv7.mjs +4 -4
  86. package/package.json +96 -2
@@ -0,0 +1,117 @@
1
+ export { SurveyEventType, SurveyWidgetType, SurveyPosition, SurveyTabPosition, SurveyType, SurveyQuestionType, SurveyQuestionBranchingType, SurveySchedule, SurveyEventName, SurveyEventProperties, DisplaySurveyType, } from './survey-constants';
2
+ import type { SurveyRenderContext } from './survey-render-context';
3
+ import type { Client } from './client';
4
+ import type { DeepReadonly } from './client';
5
+ import type { Extension } from './extension';
6
+ import type { SurveysEventReceiver } from './surveys-config';
7
+ import { type DisplaySurveyOptions, type Survey, type SurveyCallback, type SurveyRenderReason } from './types/surveys';
8
+ import type { SurveysConfigSource } from './surveys-config';
9
+ import type { Properties } from '@posthog/types';
10
+ import type { RemoteConfigResult } from './types/remote-config';
11
+ export type SurveyFetchResult = {
12
+ surveys: Survey[];
13
+ context?: {
14
+ isLoaded: boolean;
15
+ error?: string;
16
+ };
17
+ };
18
+ export declare class PostHogSurveys implements Extension {
19
+ private readonly _configSource;
20
+ readonly name: string;
21
+ private _isSurveysEnabled?;
22
+ _surveyEventReceiver: SurveysEventReceiver | null;
23
+ private _surveyManager;
24
+ private _isInitializingSurveys;
25
+ private _surveyInitializationFailed;
26
+ private _surveyCallbacks;
27
+ private _activeMatchingSurveyCallbacks;
28
+ private _activeMatchingSurveyConditionsUnsubscribe;
29
+ private _getSurveysInFlightPromise;
30
+ private _lastSurveyRefreshFailedAt;
31
+ private _client;
32
+ private _initializingClient;
33
+ private _remoteConfigSubscription;
34
+ private _disposed;
35
+ private _renderTimeouts;
36
+ constructor(_configSource: SurveysConfigSource);
37
+ setup(client: Client): void | Promise<void>;
38
+ dispose(): void;
39
+ private get _config();
40
+ getRenderContext(): SurveyRenderContext | undefined;
41
+ initialize(): void;
42
+ onRemoteConfig: (result: DeepReadonly<RemoteConfigResult>) => void;
43
+ reset(): void;
44
+ loadIfEnabled(): void;
45
+ /** Helper to finalize survey initialization */
46
+ private _completeSurveyInitialization;
47
+ /** Helper to handle errors during survey loading */
48
+ private _handleSurveyLoadError;
49
+ /**
50
+ * Register a callback that runs when surveys are initialized.
51
+ * ### Usage:
52
+ *
53
+ * posthog.onSurveysLoaded((surveys) => {
54
+ * // You can work with all surveys
55
+ * console.log('All available surveys:', surveys)
56
+ *
57
+ * // Or get active matching surveys
58
+ * posthog.getActiveMatchingSurveys((activeMatchingSurveys) => {
59
+ * if (activeMatchingSurveys.length > 0) {
60
+ * posthog.renderSurvey(activeMatchingSurveys[0].id, '#survey-container')
61
+ * }
62
+ * })
63
+ * })
64
+ *
65
+ * @param {Function} callback The callback function will be called when surveys are loaded or updated.
66
+ * It receives the array of all surveys and a context object with error status.
67
+ * @returns {Function} A function that can be called to unsubscribe the listener.
68
+ */
69
+ onSurveysLoaded(callback: SurveyCallback): () => void;
70
+ getSurveys(callback: SurveyCallback, forceReload?: boolean): void;
71
+ private _handleSurveyResponse;
72
+ private _registerEventOrActionBasedSurveys;
73
+ /**
74
+ * Whether to kick off a background refresh of the cached definitions: the cache is stale, no
75
+ * fetch is already in flight, and we're not backing off after a recent failure.
76
+ */
77
+ private _shouldBackgroundRefreshSurveys;
78
+ /**
79
+ * Whether the cached `$surveys` definitions have aged past their TTL. Returns false when no
80
+ * timestamp is recorded (e.g. surveys injected directly in tests) so the cache stays valid.
81
+ */
82
+ private _isSurveyCacheStale;
83
+ private _isSurveyRefreshBackingOff;
84
+ /**
85
+ * Marks a survey as seen for the current device, mirroring the local state the SDK records
86
+ * when it shows or sends a survey itself.
87
+ *
88
+ * Use this when you display surveys through your own backend/integration (so the SDK never
89
+ * captures the `survey shown`/`sent`/`dismissed` events) and still want PostHog's display
90
+ * logic to honour the "already seen" and wait-period checks on subsequent page loads.
91
+ *
92
+ * Note: surveys configured to repeat (`schedule: 'always'` or event `repeatedActivation`)
93
+ * intentionally bypass the seen check, so marking them as seen will not stop them showing.
94
+ *
95
+ * @param surveyId The ID of the survey to mark as seen.
96
+ * @param options Optional settings. `iteration` is the survey's current iteration number, if any.
97
+ */
98
+ markSurveyAsSeen(surveyId: string, options?: {
99
+ iteration?: number | null;
100
+ }): void;
101
+ /** Helper method to notify all registered callbacks */
102
+ private _notifySurveyCallbacks;
103
+ getActiveMatchingSurveys(callback: SurveyCallback, forceReload?: boolean): void;
104
+ onActiveMatchingSurveysChanged(callback: SurveyCallback): () => void;
105
+ private _startActiveMatchingSurveyConditions;
106
+ private _notifyActiveMatchingSurveyCallback;
107
+ private _notifyActiveMatchingSurveyCallbacks;
108
+ private _getSurveyById;
109
+ private _checkSurveyEligibility;
110
+ private _checkSurveyRenderability;
111
+ canRenderSurvey(surveyId: string | Survey): SurveyRenderReason;
112
+ canRenderSurveyAsync(surveyId: string, forceReload: boolean): Promise<SurveyRenderReason>;
113
+ renderSurvey(surveyId: string | Survey, selector: string, properties?: Properties): void;
114
+ displaySurvey(surveyId: string, options: DisplaySurveyOptions): void;
115
+ cancelPendingSurvey(surveyId: string): void;
116
+ handlePageUnload(): void;
117
+ }
@@ -0,0 +1,566 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, getters, values)=>{
5
+ var define = (defs, kind)=>{
6
+ for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
7
+ enumerable: true,
8
+ [kind]: defs[key]
9
+ });
10
+ };
11
+ define(getters, "get");
12
+ define(values, "value");
13
+ };
14
+ })();
15
+ (()=>{
16
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
17
+ })();
18
+ (()=>{
19
+ __webpack_require__.r = (exports1)=>{
20
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
21
+ value: 'Module'
22
+ });
23
+ Object.defineProperty(exports1, '__esModule', {
24
+ value: true
25
+ });
26
+ };
27
+ })();
28
+ var __webpack_exports__ = {};
29
+ __webpack_require__.r(__webpack_exports__);
30
+ __webpack_require__.d(__webpack_exports__, {
31
+ DisplaySurveyType: ()=>external_survey_constants_js_namespaceObject.DisplaySurveyType,
32
+ PostHogSurveys: ()=>PostHogSurveys,
33
+ SurveyEventName: ()=>external_survey_constants_js_namespaceObject.SurveyEventName,
34
+ SurveyEventProperties: ()=>external_survey_constants_js_namespaceObject.SurveyEventProperties,
35
+ SurveyEventType: ()=>external_survey_constants_js_namespaceObject.SurveyEventType,
36
+ SurveyPosition: ()=>external_survey_constants_js_namespaceObject.SurveyPosition,
37
+ SurveyQuestionBranchingType: ()=>external_survey_constants_js_namespaceObject.SurveyQuestionBranchingType,
38
+ SurveyQuestionType: ()=>external_survey_constants_js_namespaceObject.SurveyQuestionType,
39
+ SurveySchedule: ()=>external_survey_constants_js_namespaceObject.SurveySchedule,
40
+ SurveyTabPosition: ()=>external_survey_constants_js_namespaceObject.SurveyTabPosition,
41
+ SurveyType: ()=>external_survey_constants_js_namespaceObject.SurveyType,
42
+ SurveyWidgetType: ()=>external_survey_constants_js_namespaceObject.SurveyWidgetType
43
+ });
44
+ const external_survey_constants_js_namespaceObject = require("./survey-constants.js");
45
+ const external_survey_event_receiver_js_namespaceObject = require("./survey-event-receiver.js");
46
+ const promise_utils_js_namespaceObject = require("./utils/promise-utils.js");
47
+ const core_namespaceObject = require("@posthog/core");
48
+ const external_surveys_config_js_namespaceObject = require("./surveys-config.js");
49
+ const survey_utils_js_namespaceObject = require("./utils/survey-utils.js");
50
+ const SURVEY_NOT_LOADED = 'SDK is not enabled or survey functionality is not yet loaded';
51
+ const SURVEY_DISABLED = 'Disabled. Not loading surveys.';
52
+ class PostHogSurveys {
53
+ constructor(_configSource){
54
+ this._configSource = _configSource;
55
+ this.name = 'surveys';
56
+ this._surveyEventReceiver = null;
57
+ this._surveyManager = null;
58
+ this._isInitializingSurveys = false;
59
+ this._surveyInitializationFailed = false;
60
+ this._surveyCallbacks = [];
61
+ this._activeMatchingSurveyCallbacks = [];
62
+ this._getSurveysInFlightPromise = null;
63
+ this._lastSurveyRefreshFailedAt = null;
64
+ this._disposed = false;
65
+ this._renderTimeouts = new Set();
66
+ this.onRemoteConfig = (result)=>{
67
+ if (this._disposed) return;
68
+ if (this._config.disableSurveys) return;
69
+ if (!result.ok) {
70
+ this._surveyInitializationFailed = true;
71
+ this._notifyActiveMatchingSurveyCallbacks({
72
+ isLoaded: false,
73
+ error: 'Remote config unavailable. Not loading surveys.'
74
+ });
75
+ return survey_utils_js_namespaceObject.SURVEY_LOGGER.warn('Remote config unavailable. Not loading surveys.');
76
+ }
77
+ const surveys = result.config['surveys'];
78
+ if ((0, core_namespaceObject.isNullish)(surveys)) return survey_utils_js_namespaceObject.SURVEY_LOGGER.warn('Flags not loaded yet. Not loading surveys.');
79
+ this._isSurveysEnabled = (0, core_namespaceObject.isBoolean)(surveys) ? surveys : surveys.length > 0;
80
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.info(`flags response received, isSurveysEnabled: ${this._isSurveysEnabled}`);
81
+ this.loadIfEnabled();
82
+ };
83
+ this._notifyActiveMatchingSurveyCallbacks = (context)=>{
84
+ this._activeMatchingSurveyCallbacks.slice().forEach((subscription)=>this._notifyActiveMatchingSurveyCallback(subscription, context));
85
+ };
86
+ }
87
+ setup(client) {
88
+ if (this._disposed) return;
89
+ this._initializingClient = client;
90
+ return (0, promise_utils_js_namespaceObject.continueWith)(client.kv.initialize(), ()=>{
91
+ if (this._initializingClient !== client || this._disposed) return;
92
+ this._initializingClient = void 0;
93
+ this._client = client;
94
+ const subscription = client.onRemoteConfig(this.onRemoteConfig);
95
+ if (this._disposed) return void subscription.dispose();
96
+ this._remoteConfigSubscription = subscription;
97
+ this.loadIfEnabled();
98
+ });
99
+ }
100
+ dispose() {
101
+ if (this._disposed) return;
102
+ this._disposed = true;
103
+ this._initializingClient = void 0;
104
+ this._client = void 0;
105
+ this._remoteConfigSubscription?.dispose();
106
+ this._remoteConfigSubscription = void 0;
107
+ this._surveyEventReceiver?.dispose();
108
+ this._surveyEventReceiver = null;
109
+ this._surveyManager?.dispose?.();
110
+ this._surveyManager = null;
111
+ this._surveyCallbacks = [];
112
+ this._activeMatchingSurveyCallbacks.forEach((subscription)=>{
113
+ subscription.active = false;
114
+ });
115
+ this._activeMatchingSurveyCallbacks = [];
116
+ this._activeMatchingSurveyConditionsUnsubscribe?.();
117
+ this._activeMatchingSurveyConditionsUnsubscribe = void 0;
118
+ this._getSurveysInFlightPromise = null;
119
+ this._renderTimeouts.forEach((timeout)=>clearTimeout(timeout));
120
+ this._renderTimeouts.clear();
121
+ }
122
+ get _config() {
123
+ return this._configSource.get();
124
+ }
125
+ getRenderContext() {
126
+ if (!this._client) return;
127
+ const surveys = this;
128
+ return {
129
+ client: this._client,
130
+ get config () {
131
+ return surveys._config;
132
+ },
133
+ surveys
134
+ };
135
+ }
136
+ initialize() {
137
+ this.loadIfEnabled();
138
+ }
139
+ reset() {
140
+ this._surveyManager?.clearInMemoryInProgressSurveyState?.();
141
+ try {
142
+ this._surveyEventReceiver?.reset();
143
+ localStorage.removeItem('lastSeenSurveyDate');
144
+ const surveyKeys = [];
145
+ for(let i = 0; i < localStorage.length; i++){
146
+ const key = localStorage.key(i);
147
+ if (key?.startsWith(survey_utils_js_namespaceObject.SURVEY_SEEN_PREFIX) || key?.startsWith(survey_utils_js_namespaceObject.SURVEY_IN_PROGRESS_PREFIX)) surveyKeys.push(key);
148
+ }
149
+ surveyKeys.forEach((key)=>localStorage.removeItem(key));
150
+ } catch {}
151
+ this._notifyActiveMatchingSurveyCallbacks();
152
+ }
153
+ loadIfEnabled() {
154
+ if (this._disposed || !this._client) return;
155
+ const config = this._config;
156
+ if (this._surveyManager) return;
157
+ if (this._isInitializingSurveys) return void survey_utils_js_namespaceObject.SURVEY_LOGGER.info('Already initializing surveys, skipping...');
158
+ if (config.disableSurveys) return void survey_utils_js_namespaceObject.SURVEY_LOGGER.info(SURVEY_DISABLED);
159
+ if (config.cookielessMode && this._client.isOptedOut) return void survey_utils_js_namespaceObject.SURVEY_LOGGER.info('Not loading surveys in cookieless mode without consent.');
160
+ const phExtensions = this._configSource.getExtensions();
161
+ if (!phExtensions) return void this._handleSurveyLoadError('PostHog Extensions not found.');
162
+ if ((0, core_namespaceObject.isUndefined)(this._isSurveysEnabled) && !config.advancedEnableSurveys) return;
163
+ const isSurveysEnabled = this._isSurveysEnabled || config.advancedEnableSurveys;
164
+ this._isInitializingSurveys = true;
165
+ this._surveyInitializationFailed = false;
166
+ try {
167
+ const generateSurveys = phExtensions.generateSurveys;
168
+ if (generateSurveys) {
169
+ this._completeSurveyInitialization(generateSurveys, isSurveysEnabled);
170
+ this._isInitializingSurveys = false;
171
+ return;
172
+ }
173
+ const loadExternalDependency = phExtensions.loadExternalDependency;
174
+ if (!loadExternalDependency) {
175
+ this._handleSurveyLoadError(external_surveys_config_js_namespaceObject.LOAD_EXT_NOT_FOUND);
176
+ this._isInitializingSurveys = false;
177
+ return;
178
+ }
179
+ loadExternalDependency((err)=>{
180
+ try {
181
+ if (this._disposed) return;
182
+ const loadedExtensions = this._configSource.getExtensions();
183
+ if (err || !loadedExtensions?.generateSurveys) this._handleSurveyLoadError("Could not load surveys script", err);
184
+ else this._completeSurveyInitialization(loadedExtensions.generateSurveys, isSurveysEnabled);
185
+ } finally{
186
+ this._isInitializingSurveys = false;
187
+ }
188
+ });
189
+ } catch (e) {
190
+ this._isInitializingSurveys = false;
191
+ this._handleSurveyLoadError('Error initializing surveys', e);
192
+ throw e;
193
+ }
194
+ }
195
+ _completeSurveyInitialization(generateSurveysFn, isSurveysEnabled) {
196
+ if (this._disposed) return;
197
+ this._surveyManager = generateSurveysFn(isSurveysEnabled);
198
+ this._surveyEventReceiver = new external_survey_event_receiver_js_namespaceObject.SurveyEventReceiver(this._client, this, this._notifyActiveMatchingSurveyCallbacks);
199
+ const cachedSurveys = this._client?.kv.get(external_surveys_config_js_namespaceObject.SURVEYS);
200
+ if (cachedSurveys) this._registerEventOrActionBasedSurveys(cachedSurveys);
201
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.info('Surveys loaded successfully');
202
+ this._startActiveMatchingSurveyConditions();
203
+ this._notifyActiveMatchingSurveyCallbacks();
204
+ this._notifySurveyCallbacks({
205
+ isLoaded: true
206
+ });
207
+ }
208
+ _handleSurveyLoadError(message, error) {
209
+ this._surveyInitializationFailed = true;
210
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.error(message, error);
211
+ this._notifyActiveMatchingSurveyCallbacks({
212
+ isLoaded: false,
213
+ error: message
214
+ });
215
+ this._notifySurveyCallbacks({
216
+ isLoaded: false,
217
+ error: message
218
+ });
219
+ }
220
+ onSurveysLoaded(callback) {
221
+ this._surveyCallbacks.push(callback);
222
+ if (this._surveyManager) this._notifySurveyCallbacks({
223
+ isLoaded: true
224
+ });
225
+ return ()=>{
226
+ this._surveyCallbacks = this._surveyCallbacks.filter((cb)=>cb !== callback);
227
+ };
228
+ }
229
+ getSurveys(callback, forceReload = false) {
230
+ if (this._disposed) return;
231
+ const client = this._client;
232
+ if (!client) return callback([], {
233
+ isLoaded: false,
234
+ error: SURVEY_NOT_LOADED
235
+ });
236
+ if (this._config.disableSurveys) {
237
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.info(SURVEY_DISABLED);
238
+ return callback([]);
239
+ }
240
+ const surveys = client.kv.get(external_surveys_config_js_namespaceObject.SURVEYS);
241
+ if (surveys && !forceReload) {
242
+ callback(surveys, {
243
+ isLoaded: true
244
+ });
245
+ if (this._shouldBackgroundRefreshSurveys()) this.getSurveys(()=>{}, true);
246
+ return;
247
+ }
248
+ if (this._getSurveysInFlightPromise) return void this._getSurveysInFlightPromise.then(({ surveys, context })=>{
249
+ if (!this._disposed) callback(surveys, context);
250
+ }).catch((error)=>survey_utils_js_namespaceObject.SURVEY_LOGGER.error('Error in survey callback', error));
251
+ const request = client.sendRequest('/api/surveys/', {
252
+ method: 'GET',
253
+ query: {
254
+ token: client.projectToken
255
+ },
256
+ sentAt: 'query',
257
+ timeoutMs: this._config.requestTimeoutMs
258
+ }).then((response)=>{
259
+ try {
260
+ return this._handleSurveyResponse(client, response);
261
+ } catch (error) {
262
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.error('Error processing surveys response', error);
263
+ return this._handleSurveyResponse(client, {
264
+ statusCode: 0,
265
+ error
266
+ });
267
+ }
268
+ }, (error)=>this._handleSurveyResponse(client, {
269
+ statusCode: 0,
270
+ error
271
+ }));
272
+ this._getSurveysInFlightPromise = request;
273
+ const clearInFlight = ()=>{
274
+ if (this._getSurveysInFlightPromise === request) this._getSurveysInFlightPromise = null;
275
+ };
276
+ request.then((result)=>{
277
+ clearInFlight();
278
+ if (!this._disposed) {
279
+ this._notifyActiveMatchingSurveyCallbacks(result.context);
280
+ callback(result.surveys, result.context);
281
+ }
282
+ }, clearInFlight).catch((error)=>survey_utils_js_namespaceObject.SURVEY_LOGGER.error('Error in survey callback', error));
283
+ }
284
+ _handleSurveyResponse(client, response) {
285
+ if (this._disposed) return {
286
+ surveys: [],
287
+ context: {
288
+ isLoaded: false,
289
+ error: SURVEY_NOT_LOADED
290
+ }
291
+ };
292
+ const statusCode = response.statusCode;
293
+ if (200 !== statusCode || !response.json) {
294
+ const error = `Surveys API could not be loaded, status: ${statusCode}`;
295
+ if (0 !== statusCode) survey_utils_js_namespaceObject.SURVEY_LOGGER.error(error);
296
+ else if (!response.error) survey_utils_js_namespaceObject.SURVEY_LOGGER.warn(error);
297
+ this._lastSurveyRefreshFailedAt = Date.now();
298
+ return {
299
+ surveys: [],
300
+ context: {
301
+ isLoaded: false,
302
+ error
303
+ }
304
+ };
305
+ }
306
+ this._lastSurveyRefreshFailedAt = null;
307
+ const surveys = response.json.surveys || [];
308
+ client.kv.set({
309
+ [external_surveys_config_js_namespaceObject.SURVEYS]: surveys,
310
+ [external_surveys_config_js_namespaceObject.SURVEYS_LOADED_AT]: Date.now()
311
+ });
312
+ this._registerEventOrActionBasedSurveys(surveys);
313
+ return {
314
+ surveys,
315
+ context: {
316
+ isLoaded: true
317
+ }
318
+ };
319
+ }
320
+ _registerEventOrActionBasedSurveys(surveys) {
321
+ const eventOrActionBasedSurveys = surveys.filter((survey)=>(0, survey_utils_js_namespaceObject.isSurveyRunning)(survey) && ((0, survey_utils_js_namespaceObject.doesSurveyActivateByEvent)(survey) || (0, survey_utils_js_namespaceObject.doesSurveyActivateByAction)(survey)));
322
+ this._surveyEventReceiver?.replace(eventOrActionBasedSurveys);
323
+ }
324
+ _shouldBackgroundRefreshSurveys() {
325
+ return this._isSurveyCacheStale() && !this._getSurveysInFlightPromise && !this._isSurveyRefreshBackingOff();
326
+ }
327
+ _isSurveyCacheStale() {
328
+ const surveysLoadedAt = this._client?.kv.get(external_surveys_config_js_namespaceObject.SURVEYS_LOADED_AT);
329
+ return (0, core_namespaceObject.isNumber)(surveysLoadedAt) && Date.now() - surveysLoadedAt > external_surveys_config_js_namespaceObject.SURVEYS_CACHE_TTL_MS;
330
+ }
331
+ _isSurveyRefreshBackingOff() {
332
+ return (0, core_namespaceObject.isNumber)(this._lastSurveyRefreshFailedAt) && Date.now() - this._lastSurveyRefreshFailedAt < external_surveys_config_js_namespaceObject.SURVEYS_REFRESH_BACKOFF_MS;
333
+ }
334
+ markSurveyAsSeen(surveyId, options) {
335
+ const survey = {
336
+ id: surveyId,
337
+ current_iteration: options?.iteration ?? null
338
+ };
339
+ (0, survey_utils_js_namespaceObject.setSurveySeenOnLocalStorage)(survey);
340
+ try {
341
+ localStorage.setItem('lastSeenSurveyDate', new Date().toISOString());
342
+ } catch {}
343
+ this._notifyActiveMatchingSurveyCallbacks();
344
+ }
345
+ _notifySurveyCallbacks(context) {
346
+ for (const callback of this._surveyCallbacks){
347
+ if (this._disposed) return;
348
+ try {
349
+ if (context.isLoaded) this.getSurveys(callback);
350
+ else callback([], context);
351
+ } catch (error) {
352
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.error('Error in survey callback', error);
353
+ }
354
+ }
355
+ }
356
+ getActiveMatchingSurveys(callback, forceReload = false) {
357
+ if ((0, core_namespaceObject.isNullish)(this._surveyManager)) return void survey_utils_js_namespaceObject.SURVEY_LOGGER.warn('init was not called');
358
+ return this._surveyManager.getActiveMatchingSurveys(callback, forceReload);
359
+ }
360
+ onActiveMatchingSurveysChanged(callback) {
361
+ if (this._disposed) return ()=>{};
362
+ const subscription = {
363
+ callback,
364
+ active: true,
365
+ revision: 0
366
+ };
367
+ this._activeMatchingSurveyCallbacks.push(subscription);
368
+ this._startActiveMatchingSurveyConditions();
369
+ const cached = this._client?.kv.get(external_surveys_config_js_namespaceObject.SURVEYS);
370
+ const unavailable = this._config.disableSurveys || !this._surveyManager && this._surveyInitializationFailed && !this._isInitializingSurveys || !cached && !(0, core_namespaceObject.isNullish)(this._lastSurveyRefreshFailedAt) && !this._getSurveysInFlightPromise;
371
+ if (unavailable) this._notifyActiveMatchingSurveyCallback(subscription, {
372
+ isLoaded: false
373
+ });
374
+ else if (this._surveyManager) this._notifyActiveMatchingSurveyCallback(subscription);
375
+ return ()=>{
376
+ subscription.active = false;
377
+ this._activeMatchingSurveyCallbacks = this._activeMatchingSurveyCallbacks.filter((current)=>current !== subscription);
378
+ if (0 === this._activeMatchingSurveyCallbacks.length) {
379
+ this._activeMatchingSurveyConditionsUnsubscribe?.();
380
+ this._activeMatchingSurveyConditionsUnsubscribe = void 0;
381
+ }
382
+ };
383
+ }
384
+ _startActiveMatchingSurveyConditions() {
385
+ if (this._surveyManager && this._activeMatchingSurveyCallbacks.length > 0) this._activeMatchingSurveyConditionsUnsubscribe ??= this._configSource.onMatchingConditionsChanged?.(this._notifyActiveMatchingSurveyCallbacks);
386
+ }
387
+ _notifyActiveMatchingSurveyCallback(subscription, context) {
388
+ if (this._disposed || !subscription.active) return;
389
+ const revision = ++subscription.revision;
390
+ const deliver = (surveys)=>{
391
+ if (this._disposed || !subscription.active || revision !== subscription.revision) return;
392
+ try {
393
+ const resultContext = context ?? {
394
+ isLoaded: true
395
+ };
396
+ const result = JSON.stringify([
397
+ surveys,
398
+ resultContext
399
+ ]);
400
+ if (result === subscription.lastResult) return;
401
+ subscription.lastResult = result;
402
+ subscription.callback(surveys, resultContext);
403
+ } catch (error) {
404
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.error('Error in active matching surveys callback', error);
405
+ }
406
+ };
407
+ try {
408
+ if (context && !context.isLoaded) deliver([]);
409
+ else this.getActiveMatchingSurveys(deliver);
410
+ } catch (error) {
411
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.error('Error in active matching surveys callback', error);
412
+ }
413
+ }
414
+ _getSurveyById(surveyId) {
415
+ let survey = null;
416
+ this.getSurveys((surveys)=>{
417
+ survey = surveys.find((x)=>x.id === surveyId) ?? null;
418
+ });
419
+ return survey;
420
+ }
421
+ _checkSurveyEligibility(surveyId) {
422
+ if ((0, core_namespaceObject.isNullish)(this._surveyManager)) return {
423
+ eligible: false,
424
+ reason: SURVEY_NOT_LOADED
425
+ };
426
+ const survey = 'string' == typeof surveyId ? this._getSurveyById(surveyId) : surveyId;
427
+ if (!survey) return {
428
+ eligible: false,
429
+ reason: 'Survey not found'
430
+ };
431
+ return this._surveyManager.checkSurveyEligibility(survey);
432
+ }
433
+ _checkSurveyRenderability(surveyId) {
434
+ if (!this._client?.canCapture) return {
435
+ eligible: false,
436
+ reason: survey_utils_js_namespaceObject.SURVEY_CAPTURING_DISABLED
437
+ };
438
+ if ((0, core_namespaceObject.isNullish)(this._surveyManager)) return {
439
+ eligible: false,
440
+ reason: SURVEY_NOT_LOADED
441
+ };
442
+ const survey = 'string' == typeof surveyId ? this._getSurveyById(surveyId) : surveyId;
443
+ if (!survey) return {
444
+ eligible: false,
445
+ reason: 'Survey not found'
446
+ };
447
+ return this._surveyManager.checkSurveyRenderability(survey);
448
+ }
449
+ canRenderSurvey(surveyId) {
450
+ if ((0, core_namespaceObject.isNullish)(this._surveyManager)) {
451
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.warn('init was not called');
452
+ return {
453
+ visible: false,
454
+ disabledReason: SURVEY_NOT_LOADED
455
+ };
456
+ }
457
+ const eligibility = this._checkSurveyRenderability(surveyId);
458
+ return {
459
+ visible: eligibility.eligible,
460
+ disabledReason: eligibility.reason
461
+ };
462
+ }
463
+ canRenderSurveyAsync(surveyId, forceReload) {
464
+ if ((0, core_namespaceObject.isNullish)(this._surveyManager)) {
465
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.warn('init was not called');
466
+ return Promise.resolve({
467
+ visible: false,
468
+ disabledReason: SURVEY_NOT_LOADED
469
+ });
470
+ }
471
+ return new Promise((resolve)=>{
472
+ this.getSurveys((surveys)=>{
473
+ const survey = surveys.find((x)=>x.id === surveyId) ?? null;
474
+ if (survey) {
475
+ const eligibility = this._checkSurveyRenderability(survey);
476
+ resolve({
477
+ visible: eligibility.eligible,
478
+ disabledReason: eligibility.reason
479
+ });
480
+ } else resolve({
481
+ visible: false,
482
+ disabledReason: 'Survey not found'
483
+ });
484
+ }, forceReload);
485
+ });
486
+ }
487
+ renderSurvey(surveyId, selector, properties) {
488
+ if (!this._client?.canCapture) return;
489
+ if ((0, core_namespaceObject.isNullish)(this._surveyManager)) return void survey_utils_js_namespaceObject.SURVEY_LOGGER.warn('init was not called');
490
+ const survey = 'string' == typeof surveyId ? this._getSurveyById(surveyId) : surveyId;
491
+ if (!survey?.id) return void survey_utils_js_namespaceObject.SURVEY_LOGGER.warn('Survey not found');
492
+ if (!survey_utils_js_namespaceObject.IN_APP_SURVEY_TYPES.includes(survey.type)) return void survey_utils_js_namespaceObject.SURVEY_LOGGER.warn(`Surveys of type ${survey.type} cannot be rendered in the app`);
493
+ const elem = ("u" < typeof document ? void 0 : document)?.querySelector(selector);
494
+ if (!elem) return void survey_utils_js_namespaceObject.SURVEY_LOGGER.warn('Survey element not found');
495
+ if (survey.appearance?.surveyPopupDelaySeconds) {
496
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.info(`Rendering survey ${survey.id} with delay of ${survey.appearance.surveyPopupDelaySeconds} seconds`);
497
+ const timeout = setTimeout(()=>{
498
+ this._renderTimeouts.delete(timeout);
499
+ if (this._disposed || !this._client?.canCapture) return;
500
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.info(`Rendering survey ${survey.id} with delay of ${survey.appearance?.surveyPopupDelaySeconds} seconds`);
501
+ this._surveyManager?.renderSurvey(survey, elem, properties);
502
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.info(`Survey ${survey.id} rendered`);
503
+ }, 1000 * survey.appearance.surveyPopupDelaySeconds);
504
+ this._renderTimeouts.add(timeout);
505
+ return;
506
+ }
507
+ this._surveyManager.renderSurvey(survey, elem, properties);
508
+ }
509
+ displaySurvey(surveyId, options) {
510
+ if (!this._client?.canCapture) return;
511
+ if ((0, core_namespaceObject.isNullish)(this._surveyManager)) return void survey_utils_js_namespaceObject.SURVEY_LOGGER.warn('init was not called');
512
+ const survey = this._getSurveyById(surveyId);
513
+ if (!survey) return void survey_utils_js_namespaceObject.SURVEY_LOGGER.warn('Survey not found');
514
+ let surveyToDisplay = survey;
515
+ if (survey.appearance?.surveyPopupDelaySeconds && options.ignoreDelay) surveyToDisplay = {
516
+ ...survey,
517
+ appearance: {
518
+ ...survey.appearance,
519
+ surveyPopupDelaySeconds: 0
520
+ }
521
+ };
522
+ if (options.displayType !== external_survey_constants_js_namespaceObject.DisplaySurveyType.Popover && options.initialResponses) survey_utils_js_namespaceObject.SURVEY_LOGGER.warn('initialResponses is only supported for popover surveys. prefill will not be applied.');
523
+ if (false === options.ignoreConditions) {
524
+ const eligibility = this._checkSurveyEligibility(survey);
525
+ if (!eligibility.eligible) return void survey_utils_js_namespaceObject.SURVEY_LOGGER.warn('Survey is not eligible to be displayed: ', eligibility.reason);
526
+ }
527
+ if (options.displayType === external_survey_constants_js_namespaceObject.DisplaySurveyType.Inline) return void this.renderSurvey(surveyToDisplay, options.selector, options.properties);
528
+ this._surveyManager.handlePopoverSurvey(surveyToDisplay, options);
529
+ }
530
+ cancelPendingSurvey(surveyId) {
531
+ if ((0, core_namespaceObject.isNullish)(this._surveyManager)) return void survey_utils_js_namespaceObject.SURVEY_LOGGER.warn('init was not called');
532
+ this._surveyManager.cancelSurvey(surveyId);
533
+ }
534
+ handlePageUnload() {
535
+ this._surveyManager?.handlePageUnload?.();
536
+ }
537
+ }
538
+ exports.DisplaySurveyType = __webpack_exports__.DisplaySurveyType;
539
+ exports.PostHogSurveys = __webpack_exports__.PostHogSurveys;
540
+ exports.SurveyEventName = __webpack_exports__.SurveyEventName;
541
+ exports.SurveyEventProperties = __webpack_exports__.SurveyEventProperties;
542
+ exports.SurveyEventType = __webpack_exports__.SurveyEventType;
543
+ exports.SurveyPosition = __webpack_exports__.SurveyPosition;
544
+ exports.SurveyQuestionBranchingType = __webpack_exports__.SurveyQuestionBranchingType;
545
+ exports.SurveyQuestionType = __webpack_exports__.SurveyQuestionType;
546
+ exports.SurveySchedule = __webpack_exports__.SurveySchedule;
547
+ exports.SurveyTabPosition = __webpack_exports__.SurveyTabPosition;
548
+ exports.SurveyType = __webpack_exports__.SurveyType;
549
+ exports.SurveyWidgetType = __webpack_exports__.SurveyWidgetType;
550
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
551
+ "DisplaySurveyType",
552
+ "PostHogSurveys",
553
+ "SurveyEventName",
554
+ "SurveyEventProperties",
555
+ "SurveyEventType",
556
+ "SurveyPosition",
557
+ "SurveyQuestionBranchingType",
558
+ "SurveyQuestionType",
559
+ "SurveySchedule",
560
+ "SurveyTabPosition",
561
+ "SurveyType",
562
+ "SurveyWidgetType"
563
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
564
+ Object.defineProperty(exports, '__esModule', {
565
+ value: true
566
+ });