posthog-js 1.232.6 → 1.232.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/all-external-dependencies.js.map +1 -1
- package/dist/array.full.es5.js +1 -1
- package/dist/array.full.es5.js.map +1 -1
- package/dist/array.full.js +1 -1
- package/dist/array.full.js.map +1 -1
- package/dist/array.full.no-external.js +1 -1
- package/dist/array.full.no-external.js.map +1 -1
- package/dist/array.js +1 -1
- package/dist/array.js.map +1 -1
- package/dist/array.no-external.js +1 -1
- package/dist/array.no-external.js.map +1 -1
- package/dist/customizations.full.js +1 -1
- package/dist/main.js +1 -1
- package/dist/main.js.map +1 -1
- package/dist/module.d.ts +29 -1
- package/dist/module.full.d.ts +29 -1
- package/dist/module.full.js +1 -1
- package/dist/module.full.js.map +1 -1
- package/dist/module.full.no-external.d.ts +29 -1
- package/dist/module.full.no-external.js +1 -1
- package/dist/module.full.no-external.js.map +1 -1
- package/dist/module.js +1 -1
- package/dist/module.js.map +1 -1
- package/dist/module.no-external.d.ts +29 -1
- package/dist/module.no-external.js +1 -1
- package/dist/module.no-external.js.map +1 -1
- package/dist/src/posthog-core.d.ts +1 -0
- package/dist/src/posthog-surveys-types.d.ts +4 -1
- package/dist/src/posthog-surveys.d.ts +24 -0
- package/dist/surveys-preview.d.ts +29 -1
- package/dist/surveys-preview.js.map +1 -1
- package/dist/surveys.js.map +1 -1
- package/lib/package.json +1 -1
- package/lib/src/posthog-core.d.ts +1 -0
- package/lib/src/posthog-core.js +17 -0
- package/lib/src/posthog-core.js.map +1 -1
- package/lib/src/posthog-surveys-types.d.ts +4 -1
- package/lib/src/posthog-surveys-types.js.map +1 -1
- package/lib/src/posthog-surveys.d.ts +24 -0
- package/lib/src/posthog-surveys.js +104 -6
- package/lib/src/posthog-surveys.js.map +1 -1
- package/package.json +1 -1
|
@@ -100,7 +100,10 @@ interface SpecificQuestionBranching {
|
|
|
100
100
|
export interface SurveyResponse {
|
|
101
101
|
surveys: Survey[];
|
|
102
102
|
}
|
|
103
|
-
export type SurveyCallback = (surveys: Survey[]
|
|
103
|
+
export type SurveyCallback = (surveys: Survey[], context?: {
|
|
104
|
+
isLoaded: boolean;
|
|
105
|
+
error?: string;
|
|
106
|
+
}) => void;
|
|
104
107
|
export type SurveyMatchType = 'regex' | 'not_regex' | 'exact' | 'is_not' | 'icontains' | 'not_icontains';
|
|
105
108
|
export interface SurveyElement {
|
|
106
109
|
text?: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"posthog-surveys-types.js","sourceRoot":"","sources":["../../src/posthog-surveys-types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAuCH,MAAM,CAAN,IAAY,UAIX;AAJD,WAAY,UAAU;IAClB,iCAAmB,CAAA;IACnB,yBAAW,CAAA;IACX,+BAAiB,CAAA;AACrB,CAAC,EAJW,UAAU,KAAV,UAAU,QAIrB;AAwCD,MAAM,CAAN,IAAY,kBAMX;AAND,WAAY,kBAAkB;IAC1B,mCAAa,CAAA;IACb,wDAAkC,CAAA;IAClC,oDAA8B,CAAA;IAC9B,uCAAiB,CAAA;IACjB,mCAAa,CAAA;AACjB,CAAC,EANW,kBAAkB,KAAlB,kBAAkB,QAM7B;AAED,MAAM,CAAN,IAAY,2BAKX;AALD,WAAY,2BAA2B;IACnC,6DAA8B,CAAA;IAC9B,0CAAW,CAAA;IACX,+DAAgC,CAAA;IAChC,qEAAsC,CAAA;AAC1C,CAAC,EALW,2BAA2B,KAA3B,2BAA2B,QAKtC;AA+CD,MAAM,CAAN,IAAY,cAIX;AAJD,WAAY,cAAc;IACtB,+BAAa,CAAA;IACb,yCAAuB,CAAA;IACvB,mCAAiB,CAAA;AACrB,CAAC,EAJW,cAAc,KAAd,cAAc,QAIzB","sourcesContent":["/**\n * Having Survey types in types.ts was confusing tsc\n * and generating an invalid module.d.ts\n * See https://github.com/PostHog/posthog-js/issues/698\n */\n\nexport interface SurveyAppearance {\n // keep in sync with frontend/src/types.ts -> SurveyAppearance\n backgroundColor?: string\n submitButtonColor?: string\n // text color is deprecated, use auto contrast text color instead\n textColor?: string\n // deprecate submit button text eventually\n submitButtonText?: string\n submitButtonTextColor?: string\n descriptionTextColor?: string\n ratingButtonColor?: string\n ratingButtonActiveColor?: string\n ratingButtonHoverColor?: string\n whiteLabel?: boolean\n autoDisappear?: boolean\n displayThankYouMessage?: boolean\n thankYouMessageHeader?: string\n thankYouMessageDescription?: string\n thankYouMessageDescriptionContentType?: SurveyQuestionDescriptionContentType\n thankYouMessageCloseButtonText?: string\n borderColor?: string\n position?: 'left' | 'right' | 'center'\n placeholder?: string\n shuffleQuestions?: boolean\n surveyPopupDelaySeconds?: number\n // widget options\n widgetType?: 'button' | 'tab' | 'selector'\n widgetSelector?: string\n widgetLabel?: string\n widgetColor?: string\n fontFamily?: string\n // questionable: Not in frontend/src/types.ts -> SurveyAppearance, but used in site app\n maxWidth?: string\n zIndex?: string\n disabledButtonOpacity?: string\n}\n\nexport enum SurveyType {\n Popover = 'popover',\n API = 'api',\n Widget = 'widget',\n}\n\nexport type SurveyQuestion = BasicSurveyQuestion | LinkSurveyQuestion | RatingSurveyQuestion | MultipleSurveyQuestion\n\nexport type SurveyQuestionDescriptionContentType = 'html' | 'text'\n\ninterface SurveyQuestionBase {\n question: string\n id?: string\n description?: string | null\n descriptionContentType?: SurveyQuestionDescriptionContentType\n optional?: boolean\n buttonText?: string\n branching?: NextQuestionBranching | EndBranching | ResponseBasedBranching | SpecificQuestionBranching\n}\n\nexport interface BasicSurveyQuestion extends SurveyQuestionBase {\n type: SurveyQuestionType.Open\n}\n\nexport interface LinkSurveyQuestion extends SurveyQuestionBase {\n type: SurveyQuestionType.Link\n link?: string | null\n}\n\nexport interface RatingSurveyQuestion extends SurveyQuestionBase {\n type: SurveyQuestionType.Rating\n display: 'number' | 'emoji'\n scale: 3 | 5 | 7 | 10\n lowerBoundLabel: string\n upperBoundLabel: string\n}\n\nexport interface MultipleSurveyQuestion extends SurveyQuestionBase {\n type: SurveyQuestionType.SingleChoice | SurveyQuestionType.MultipleChoice\n choices: string[]\n hasOpenChoice?: boolean\n shuffleOptions?: boolean\n}\n\nexport enum SurveyQuestionType {\n Open = 'open',\n MultipleChoice = 'multiple_choice',\n SingleChoice = 'single_choice',\n Rating = 'rating',\n Link = 'link',\n}\n\nexport enum SurveyQuestionBranchingType {\n NextQuestion = 'next_question',\n End = 'end',\n ResponseBased = 'response_based',\n SpecificQuestion = 'specific_question',\n}\n\ninterface NextQuestionBranching {\n type: SurveyQuestionBranchingType.NextQuestion\n}\n\ninterface EndBranching {\n type: SurveyQuestionBranchingType.End\n}\n\ninterface ResponseBasedBranching {\n type: SurveyQuestionBranchingType.ResponseBased\n responseValues: Record<string, any>\n}\n\ninterface SpecificQuestionBranching {\n type: SurveyQuestionBranchingType.SpecificQuestion\n index: number\n}\n\nexport interface SurveyResponse {\n surveys: Survey[]\n}\n\nexport type SurveyCallback = (surveys: Survey[]) => void\n\nexport type SurveyMatchType = 'regex' | 'not_regex' | 'exact' | 'is_not' | 'icontains' | 'not_icontains'\n\nexport interface SurveyElement {\n text?: string\n $el_text?: string\n tag_name?: string\n href?: string\n attr_id?: string\n attr_class?: string[]\n nth_child?: number\n nth_of_type?: number\n attributes?: Record<string, any>\n event_id?: number\n order?: number\n group_id?: number\n}\nexport interface SurveyRenderReason {\n visible: boolean\n disabledReason?: string\n}\n\nexport enum SurveySchedule {\n Once = 'once',\n Recurring = 'recurring',\n Always = 'always',\n}\n\nexport interface Survey {\n // Sync this with the backend's SurveyAPISerializer!\n id: string\n name: string\n description: string\n type: SurveyType\n feature_flag_keys:\n | {\n key: string\n value?: string\n }[]\n | null\n linked_flag_key: string | null\n targeting_flag_key: string | null\n internal_targeting_flag_key: string | null\n questions: SurveyQuestion[]\n appearance: SurveyAppearance | null\n conditions: {\n url?: string\n selector?: string\n seenSurveyWaitPeriodInDays?: number\n urlMatchType?: SurveyMatchType\n events: {\n repeatedActivation?: boolean\n values: {\n name: string\n }[]\n } | null\n actions: {\n values: SurveyActionType[]\n } | null\n deviceTypes?: string[]\n deviceTypesMatchType?: SurveyMatchType\n } | null\n start_date: string | null\n end_date: string | null\n current_iteration: number | null\n current_iteration_start_date: string | null\n schedule?: SurveySchedule | null\n}\n\nexport interface SurveyActionType {\n id: number\n name: string | null\n steps?: ActionStepType[]\n}\n\n/** Sync with plugin-server/src/types.ts */\nexport type ActionStepStringMatching = 'contains' | 'exact' | 'regex'\n\nexport interface ActionStepType {\n event?: string | null\n selector?: string | null\n /** @deprecated Only `selector` should be used now. */\n tag_name?: string\n text?: string | null\n /** @default StringMatching.Exact */\n text_matching?: ActionStepStringMatching | null\n href?: string | null\n /** @default ActionStepStringMatching.Exact */\n href_matching?: ActionStepStringMatching | null\n url?: string | null\n /** @default StringMatching.Contains */\n url_matching?: ActionStepStringMatching | null\n}\n"]}
|
|
1
|
+
{"version":3,"file":"posthog-surveys-types.js","sourceRoot":"","sources":["../../src/posthog-surveys-types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAuCH,MAAM,CAAN,IAAY,UAIX;AAJD,WAAY,UAAU;IAClB,iCAAmB,CAAA;IACnB,yBAAW,CAAA;IACX,+BAAiB,CAAA;AACrB,CAAC,EAJW,UAAU,KAAV,UAAU,QAIrB;AAwCD,MAAM,CAAN,IAAY,kBAMX;AAND,WAAY,kBAAkB;IAC1B,mCAAa,CAAA;IACb,wDAAkC,CAAA;IAClC,oDAA8B,CAAA;IAC9B,uCAAiB,CAAA;IACjB,mCAAa,CAAA;AACjB,CAAC,EANW,kBAAkB,KAAlB,kBAAkB,QAM7B;AAED,MAAM,CAAN,IAAY,2BAKX;AALD,WAAY,2BAA2B;IACnC,6DAA8B,CAAA;IAC9B,0CAAW,CAAA;IACX,+DAAgC,CAAA;IAChC,qEAAsC,CAAA;AAC1C,CAAC,EALW,2BAA2B,KAA3B,2BAA2B,QAKtC;AA+CD,MAAM,CAAN,IAAY,cAIX;AAJD,WAAY,cAAc;IACtB,+BAAa,CAAA;IACb,yCAAuB,CAAA;IACvB,mCAAiB,CAAA;AACrB,CAAC,EAJW,cAAc,KAAd,cAAc,QAIzB","sourcesContent":["/**\n * Having Survey types in types.ts was confusing tsc\n * and generating an invalid module.d.ts\n * See https://github.com/PostHog/posthog-js/issues/698\n */\n\nexport interface SurveyAppearance {\n // keep in sync with frontend/src/types.ts -> SurveyAppearance\n backgroundColor?: string\n submitButtonColor?: string\n // text color is deprecated, use auto contrast text color instead\n textColor?: string\n // deprecate submit button text eventually\n submitButtonText?: string\n submitButtonTextColor?: string\n descriptionTextColor?: string\n ratingButtonColor?: string\n ratingButtonActiveColor?: string\n ratingButtonHoverColor?: string\n whiteLabel?: boolean\n autoDisappear?: boolean\n displayThankYouMessage?: boolean\n thankYouMessageHeader?: string\n thankYouMessageDescription?: string\n thankYouMessageDescriptionContentType?: SurveyQuestionDescriptionContentType\n thankYouMessageCloseButtonText?: string\n borderColor?: string\n position?: 'left' | 'right' | 'center'\n placeholder?: string\n shuffleQuestions?: boolean\n surveyPopupDelaySeconds?: number\n // widget options\n widgetType?: 'button' | 'tab' | 'selector'\n widgetSelector?: string\n widgetLabel?: string\n widgetColor?: string\n fontFamily?: string\n // questionable: Not in frontend/src/types.ts -> SurveyAppearance, but used in site app\n maxWidth?: string\n zIndex?: string\n disabledButtonOpacity?: string\n}\n\nexport enum SurveyType {\n Popover = 'popover',\n API = 'api',\n Widget = 'widget',\n}\n\nexport type SurveyQuestion = BasicSurveyQuestion | LinkSurveyQuestion | RatingSurveyQuestion | MultipleSurveyQuestion\n\nexport type SurveyQuestionDescriptionContentType = 'html' | 'text'\n\ninterface SurveyQuestionBase {\n question: string\n id?: string\n description?: string | null\n descriptionContentType?: SurveyQuestionDescriptionContentType\n optional?: boolean\n buttonText?: string\n branching?: NextQuestionBranching | EndBranching | ResponseBasedBranching | SpecificQuestionBranching\n}\n\nexport interface BasicSurveyQuestion extends SurveyQuestionBase {\n type: SurveyQuestionType.Open\n}\n\nexport interface LinkSurveyQuestion extends SurveyQuestionBase {\n type: SurveyQuestionType.Link\n link?: string | null\n}\n\nexport interface RatingSurveyQuestion extends SurveyQuestionBase {\n type: SurveyQuestionType.Rating\n display: 'number' | 'emoji'\n scale: 3 | 5 | 7 | 10\n lowerBoundLabel: string\n upperBoundLabel: string\n}\n\nexport interface MultipleSurveyQuestion extends SurveyQuestionBase {\n type: SurveyQuestionType.SingleChoice | SurveyQuestionType.MultipleChoice\n choices: string[]\n hasOpenChoice?: boolean\n shuffleOptions?: boolean\n}\n\nexport enum SurveyQuestionType {\n Open = 'open',\n MultipleChoice = 'multiple_choice',\n SingleChoice = 'single_choice',\n Rating = 'rating',\n Link = 'link',\n}\n\nexport enum SurveyQuestionBranchingType {\n NextQuestion = 'next_question',\n End = 'end',\n ResponseBased = 'response_based',\n SpecificQuestion = 'specific_question',\n}\n\ninterface NextQuestionBranching {\n type: SurveyQuestionBranchingType.NextQuestion\n}\n\ninterface EndBranching {\n type: SurveyQuestionBranchingType.End\n}\n\ninterface ResponseBasedBranching {\n type: SurveyQuestionBranchingType.ResponseBased\n responseValues: Record<string, any>\n}\n\ninterface SpecificQuestionBranching {\n type: SurveyQuestionBranchingType.SpecificQuestion\n index: number\n}\n\nexport interface SurveyResponse {\n surveys: Survey[]\n}\n\nexport type SurveyCallback = (surveys: Survey[], context?: { isLoaded: boolean; error?: string }) => void\n\nexport type SurveyMatchType = 'regex' | 'not_regex' | 'exact' | 'is_not' | 'icontains' | 'not_icontains'\n\nexport interface SurveyElement {\n text?: string\n $el_text?: string\n tag_name?: string\n href?: string\n attr_id?: string\n attr_class?: string[]\n nth_child?: number\n nth_of_type?: number\n attributes?: Record<string, any>\n event_id?: number\n order?: number\n group_id?: number\n}\nexport interface SurveyRenderReason {\n visible: boolean\n disabledReason?: string\n}\n\nexport enum SurveySchedule {\n Once = 'once',\n Recurring = 'recurring',\n Always = 'always',\n}\n\nexport interface Survey {\n // Sync this with the backend's SurveyAPISerializer!\n id: string\n name: string\n description: string\n type: SurveyType\n feature_flag_keys:\n | {\n key: string\n value?: string\n }[]\n | null\n linked_flag_key: string | null\n targeting_flag_key: string | null\n internal_targeting_flag_key: string | null\n questions: SurveyQuestion[]\n appearance: SurveyAppearance | null\n conditions: {\n url?: string\n selector?: string\n seenSurveyWaitPeriodInDays?: number\n urlMatchType?: SurveyMatchType\n events: {\n repeatedActivation?: boolean\n values: {\n name: string\n }[]\n } | null\n actions: {\n values: SurveyActionType[]\n } | null\n deviceTypes?: string[]\n deviceTypesMatchType?: SurveyMatchType\n } | null\n start_date: string | null\n end_date: string | null\n current_iteration: number | null\n current_iteration_start_date: string | null\n schedule?: SurveySchedule | null\n}\n\nexport interface SurveyActionType {\n id: number\n name: string | null\n steps?: ActionStepType[]\n}\n\n/** Sync with plugin-server/src/types.ts */\nexport type ActionStepStringMatching = 'contains' | 'exact' | 'regex'\n\nexport interface ActionStepType {\n event?: string | null\n selector?: string | null\n /** @deprecated Only `selector` should be used now. */\n tag_name?: string\n text?: string | null\n /** @default StringMatching.Exact */\n text_matching?: ActionStepStringMatching | null\n href?: string | null\n /** @default ActionStepStringMatching.Exact */\n href_matching?: ActionStepStringMatching | null\n url?: string | null\n /** @default StringMatching.Contains */\n url_matching?: ActionStepStringMatching | null\n}\n"]}
|
|
@@ -12,11 +12,35 @@ export declare class PostHogSurveys {
|
|
|
12
12
|
private _surveyManager;
|
|
13
13
|
private _isFetchingSurveys;
|
|
14
14
|
private _isInitializingSurveys;
|
|
15
|
+
private _surveyCallbacks;
|
|
15
16
|
constructor(instance: PostHog);
|
|
16
17
|
onRemoteConfig(response: RemoteConfig): void;
|
|
17
18
|
reset(): void;
|
|
18
19
|
loadIfEnabled(): void;
|
|
20
|
+
/**
|
|
21
|
+
* Register a callback that runs when surveys are initialized.
|
|
22
|
+
* ### Usage:
|
|
23
|
+
*
|
|
24
|
+
* posthog.onSurveysLoaded((surveys) => {
|
|
25
|
+
* // You can work with all surveys
|
|
26
|
+
* console.log('All available surveys:', surveys)
|
|
27
|
+
*
|
|
28
|
+
* // Or get active matching surveys
|
|
29
|
+
* posthog.getActiveMatchingSurveys((activeMatchingSurveys) => {
|
|
30
|
+
* if (activeMatchingSurveys.length > 0) {
|
|
31
|
+
* posthog.renderSurvey(activeMatchingSurveys[0].id, '#survey-container')
|
|
32
|
+
* }
|
|
33
|
+
* })
|
|
34
|
+
* })
|
|
35
|
+
*
|
|
36
|
+
* @param {Function} callback The callback function will be called when surveys are loaded or updated.
|
|
37
|
+
* It receives the array of all surveys and a context object with error status.
|
|
38
|
+
* @returns {Function} A function that can be called to unsubscribe the listener.
|
|
39
|
+
*/
|
|
40
|
+
onSurveysLoaded(callback: SurveyCallback): () => void;
|
|
19
41
|
getSurveys(callback: SurveyCallback, forceReload?: boolean): void;
|
|
42
|
+
/** Helper method to notify all registered callbacks */
|
|
43
|
+
private _notifySurveyCallbacks;
|
|
20
44
|
private isSurveyFeatureFlagEnabled;
|
|
21
45
|
getActiveMatchingSurveys(callback: SurveyCallback, forceReload?: boolean): void;
|
|
22
46
|
checkFlags(survey: Survey): boolean;
|
|
@@ -1,3 +1,14 @@
|
|
|
1
|
+
var __values = (this && this.__values) || function(o) {
|
|
2
|
+
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
|
|
3
|
+
if (m) return m.call(o);
|
|
4
|
+
if (o && typeof o.length === "number") return {
|
|
5
|
+
next: function () {
|
|
6
|
+
if (o && i >= o.length) o = void 0;
|
|
7
|
+
return { value: o && o[i++], done: !o };
|
|
8
|
+
}
|
|
9
|
+
};
|
|
10
|
+
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
|
|
11
|
+
};
|
|
1
12
|
import { SURVEYS } from './constants';
|
|
2
13
|
import { getSurveySeenStorageKeys } from './extensions/surveys/surveys-utils';
|
|
3
14
|
import { Info } from './utils/event-utils';
|
|
@@ -49,6 +60,7 @@ var PostHogSurveys = /** @class */ (function () {
|
|
|
49
60
|
this.instance = instance;
|
|
50
61
|
this._isFetchingSurveys = false;
|
|
51
62
|
this._isInitializingSurveys = false;
|
|
63
|
+
this._surveyCallbacks = [];
|
|
52
64
|
// we set this to undefined here because we need the persistence storage for this type
|
|
53
65
|
// but that's not initialized until loadIfEnabled is called.
|
|
54
66
|
this._surveyEventReceiver = null;
|
|
@@ -103,11 +115,19 @@ var PostHogSurveys = /** @class */ (function () {
|
|
|
103
115
|
_this._isInitializingSurveys = false;
|
|
104
116
|
_this._surveyEventReceiver = new SurveyEventReceiver(_this.instance);
|
|
105
117
|
logger.info('Surveys loaded successfully');
|
|
118
|
+
_this._notifySurveyCallbacks({
|
|
119
|
+
isLoaded: true,
|
|
120
|
+
});
|
|
106
121
|
});
|
|
107
122
|
}
|
|
108
123
|
else {
|
|
109
|
-
|
|
124
|
+
var error = 'PostHog loadExternalDependency extension not found. Cannot load remote config.';
|
|
125
|
+
logger.error(error);
|
|
110
126
|
this._isInitializingSurveys = false;
|
|
127
|
+
this._notifySurveyCallbacks({
|
|
128
|
+
isLoaded: false,
|
|
129
|
+
error: error,
|
|
130
|
+
});
|
|
111
131
|
}
|
|
112
132
|
}
|
|
113
133
|
else {
|
|
@@ -115,14 +135,54 @@ var PostHogSurveys = /** @class */ (function () {
|
|
|
115
135
|
this._isInitializingSurveys = false;
|
|
116
136
|
this._surveyEventReceiver = new SurveyEventReceiver(this.instance);
|
|
117
137
|
logger.info('Surveys loaded successfully');
|
|
138
|
+
this._notifySurveyCallbacks({
|
|
139
|
+
isLoaded: true,
|
|
140
|
+
});
|
|
118
141
|
}
|
|
119
142
|
}
|
|
120
143
|
catch (e) {
|
|
121
144
|
logger.error('Error initializing surveys', e);
|
|
122
145
|
this._isInitializingSurveys = false;
|
|
146
|
+
this._notifySurveyCallbacks({
|
|
147
|
+
isLoaded: false,
|
|
148
|
+
error: 'Error initializing surveys',
|
|
149
|
+
});
|
|
123
150
|
throw e;
|
|
124
151
|
}
|
|
125
152
|
};
|
|
153
|
+
/**
|
|
154
|
+
* Register a callback that runs when surveys are initialized.
|
|
155
|
+
* ### Usage:
|
|
156
|
+
*
|
|
157
|
+
* posthog.onSurveysLoaded((surveys) => {
|
|
158
|
+
* // You can work with all surveys
|
|
159
|
+
* console.log('All available surveys:', surveys)
|
|
160
|
+
*
|
|
161
|
+
* // Or get active matching surveys
|
|
162
|
+
* posthog.getActiveMatchingSurveys((activeMatchingSurveys) => {
|
|
163
|
+
* if (activeMatchingSurveys.length > 0) {
|
|
164
|
+
* posthog.renderSurvey(activeMatchingSurveys[0].id, '#survey-container')
|
|
165
|
+
* }
|
|
166
|
+
* })
|
|
167
|
+
* })
|
|
168
|
+
*
|
|
169
|
+
* @param {Function} callback The callback function will be called when surveys are loaded or updated.
|
|
170
|
+
* It receives the array of all surveys and a context object with error status.
|
|
171
|
+
* @returns {Function} A function that can be called to unsubscribe the listener.
|
|
172
|
+
*/
|
|
173
|
+
PostHogSurveys.prototype.onSurveysLoaded = function (callback) {
|
|
174
|
+
var _this = this;
|
|
175
|
+
this._surveyCallbacks.push(callback);
|
|
176
|
+
if (this._surveyManager) {
|
|
177
|
+
this._notifySurveyCallbacks({
|
|
178
|
+
isLoaded: true,
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
// Return unsubscribe function
|
|
182
|
+
return function () {
|
|
183
|
+
_this._surveyCallbacks = _this._surveyCallbacks.filter(function (cb) { return cb !== callback; });
|
|
184
|
+
};
|
|
185
|
+
};
|
|
126
186
|
PostHogSurveys.prototype.getSurveys = function (callback, forceReload) {
|
|
127
187
|
var _this = this;
|
|
128
188
|
if (forceReload === void 0) { forceReload = false; }
|
|
@@ -136,7 +196,10 @@ var PostHogSurveys = /** @class */ (function () {
|
|
|
136
196
|
if (!existingSurveys || forceReload) {
|
|
137
197
|
// Prevent concurrent API calls
|
|
138
198
|
if (this._isFetchingSurveys) {
|
|
139
|
-
return callback([]
|
|
199
|
+
return callback([], {
|
|
200
|
+
isLoaded: false,
|
|
201
|
+
error: 'Surveys are already being loaded',
|
|
202
|
+
});
|
|
140
203
|
}
|
|
141
204
|
try {
|
|
142
205
|
this._isFetchingSurveys = true;
|
|
@@ -150,8 +213,12 @@ var PostHogSurveys = /** @class */ (function () {
|
|
|
150
213
|
_this._isFetchingSurveys = false;
|
|
151
214
|
var statusCode = response.statusCode;
|
|
152
215
|
if (statusCode !== 200 || !response.json) {
|
|
153
|
-
|
|
154
|
-
|
|
216
|
+
var error = "Surveys API could not be loaded, status: ".concat(statusCode);
|
|
217
|
+
logger.error(error);
|
|
218
|
+
return callback([], {
|
|
219
|
+
isLoaded: false,
|
|
220
|
+
error: error,
|
|
221
|
+
});
|
|
155
222
|
}
|
|
156
223
|
var surveys = response.json.surveys || [];
|
|
157
224
|
var eventOrActionBasedSurveys = surveys.filter(function (survey) {
|
|
@@ -167,7 +234,9 @@ var PostHogSurveys = /** @class */ (function () {
|
|
|
167
234
|
(_b = _this._surveyEventReceiver) === null || _b === void 0 ? void 0 : _b.register(eventOrActionBasedSurveys);
|
|
168
235
|
}
|
|
169
236
|
(_c = _this.instance.persistence) === null || _c === void 0 ? void 0 : _c.register((_a = {}, _a[SURVEYS] = surveys, _a));
|
|
170
|
-
return callback(surveys
|
|
237
|
+
return callback(surveys, {
|
|
238
|
+
isLoaded: true,
|
|
239
|
+
});
|
|
171
240
|
},
|
|
172
241
|
});
|
|
173
242
|
}
|
|
@@ -177,7 +246,36 @@ var PostHogSurveys = /** @class */ (function () {
|
|
|
177
246
|
}
|
|
178
247
|
}
|
|
179
248
|
else {
|
|
180
|
-
return callback(existingSurveys
|
|
249
|
+
return callback(existingSurveys, {
|
|
250
|
+
isLoaded: true,
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
/** Helper method to notify all registered callbacks */
|
|
255
|
+
PostHogSurveys.prototype._notifySurveyCallbacks = function (context) {
|
|
256
|
+
var e_1, _a;
|
|
257
|
+
try {
|
|
258
|
+
for (var _b = __values(this._surveyCallbacks), _c = _b.next(); !_c.done; _c = _b.next()) {
|
|
259
|
+
var callback = _c.value;
|
|
260
|
+
try {
|
|
261
|
+
if (!context.isLoaded) {
|
|
262
|
+
callback([], context);
|
|
263
|
+
}
|
|
264
|
+
else {
|
|
265
|
+
this.getSurveys(callback);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
catch (error) {
|
|
269
|
+
logger.error('Error in survey callback', error);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
274
|
+
finally {
|
|
275
|
+
try {
|
|
276
|
+
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
|
|
277
|
+
}
|
|
278
|
+
finally { if (e_1) throw e_1.error; }
|
|
181
279
|
}
|
|
182
280
|
};
|
|
183
281
|
PostHogSurveys.prototype.isSurveyFeatureFlagEnabled = function (flagKey) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"posthog-surveys.js","sourceRoot":"","sources":["../../src/posthog-surveys.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAA;AACrC,OAAO,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAA;AAI7E,OAAO,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAA;AAC1C,OAAO,EAAE,gBAAgB,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AAC/E,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAA;AAC7C,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAA;AACrD,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAA;AACnE,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAA;AAE9C,IAAM,MAAM,GAAG,YAAY,CAAC,WAAW,CAAC,CAAA;AAExC,MAAM,CAAC,IAAM,mBAAmB,GAA2E;IACvG,SAAS,EAAE,UAAC,OAAO,EAAE,KAAK,IAAK,OAAA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AAM,CAAC,UAAC,CAAC,IAAK,OAAA,CAAC,CAAC,EAAE,KAAK,QAAQ,EAAjB,CAAiB,CAAC,CAAC,CAAC,CAAC,CAAA;YAC1D,KAAI,CAAC,cAAc,CAAC,eAAe,CAAC,MAAM,CAAC,CAAA;QAC/C,CAAC,CAAC,CAAA;IACN,CAAC;IAED,qCAAY,GAAZ,UAAa,QAAgB,EAAE,QAAgB;QAA/C,iBASC;QARG,IAAI,SAAS,CAAC,IAAI,CAAC,cAAc,CAAC,EAAE,CAAC;YACjC,MAAM,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAA;YAClC,OAAM;QACV,CAAC;QACD,IAAI,CAAC,UAAU,CAAC,UAAC,OAAO;YACpB,IAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,UAAC,CAAC,IAAK,OAAA,CAAC,CAAC,EAAE,KAAK,QAAQ,EAAjB,CAAiB,CAAC,CAAC,CAAC,CAAC,CAAA;YAC1D,KAAI,CAAC,cAAc,CAAC,YAAY,CAAC,MAAM,EAAE,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,aAAa,CAAC,QAAQ,CAAC,CAAC,CAAA;QAC/E,CAAC,CAAC,CAAA;IACN,CAAC;IACL,qBAAC;AAAD,CAAC,AAvQD,IAuQC","sourcesContent":["import { SURVEYS } from './constants'\nimport { getSurveySeenStorageKeys } from './extensions/surveys/surveys-utils'\nimport { PostHog } from './posthog-core'\nimport { Survey, SurveyCallback, SurveyMatchType } from './posthog-surveys-types'\nimport { RemoteConfig } from './types'\nimport { Info } from './utils/event-utils'\nimport { assignableWindow, document, userAgent, window } from './utils/globals'\nimport { createLogger } from './utils/logger'\nimport { isMatchingRegex } from './utils/regex-utils'\nimport { SurveyEventReceiver } from './utils/survey-event-receiver'\nimport { isNullish } from './utils/type-utils'\n\nconst logger = createLogger('[Surveys]')\n\nexport const surveyValidationMap: Record<SurveyMatchType, (targets: string[], value: string) => boolean> = {\n icontains: (targets, value) => targets.some((target) => value.toLowerCase().includes(target.toLowerCase())),\n\n not_icontains: (targets, value) => targets.every((target) => !value.toLowerCase().includes(target.toLowerCase())),\n\n regex: (targets, value) => targets.some((target) => isMatchingRegex(value, target)),\n\n not_regex: (targets, value) => targets.every((target) => !isMatchingRegex(value, target)),\n\n exact: (targets, value) => targets.some((target) => value === target),\n\n is_not: (targets, value) => targets.every((target) => value !== target),\n}\n\nfunction defaultMatchType(matchType?: SurveyMatchType): SurveyMatchType {\n return matchType ?? 'icontains'\n}\n\n// use urlMatchType to validate url condition, fallback to contains for backwards compatibility\nexport function doesSurveyUrlMatch(survey: Pick<Survey, 'conditions'>): boolean {\n if (!survey.conditions?.url) {\n return true\n }\n // if we dont know the url, assume it is not a match\n const href = window?.location?.href\n if (!href) {\n return false\n }\n\n const targets = [survey.conditions.url]\n return surveyValidationMap[defaultMatchType(survey.conditions?.urlMatchType)](targets, href)\n}\n\nexport function doesSurveyDeviceTypesMatch(survey: Survey): boolean {\n if (!survey.conditions?.deviceTypes || survey.conditions?.deviceTypes.length === 0) {\n return true\n }\n // if we dont know the device type, assume it is not a match\n if (!userAgent) {\n return false\n }\n\n const deviceType = Info.deviceType(userAgent)\n return surveyValidationMap[defaultMatchType(survey.conditions?.deviceTypesMatchType)](\n survey.conditions.deviceTypes,\n deviceType\n )\n}\n\nexport class PostHogSurveys {\n private _decideServerResponse?: boolean\n public _surveyEventReceiver: SurveyEventReceiver | null\n private _surveyManager: any\n private _isFetchingSurveys: boolean = false\n private _isInitializingSurveys: boolean = false\n\n constructor(private readonly instance: PostHog) {\n // we set this to undefined here because we need the persistence storage for this type\n // but that's not initialized until loadIfEnabled is called.\n this._surveyEventReceiver = null\n }\n\n onRemoteConfig(response: RemoteConfig) {\n this._decideServerResponse = !!response['surveys']\n logger.info(`decideServerResponse set to ${this._decideServerResponse}`)\n\n this.loadIfEnabled()\n }\n\n reset(): void {\n localStorage.removeItem('lastSeenSurveyDate')\n const surveyKeys = getSurveySeenStorageKeys()\n surveyKeys.forEach((key) => localStorage.removeItem(key))\n }\n\n loadIfEnabled() {\n if (this._surveyManager) {\n // Surveys already loaded.\n return\n }\n\n if (this._isInitializingSurveys) {\n logger.info('Already initializing surveys, skipping...')\n return\n }\n\n const disableSurveys = this.instance.config.disable_surveys\n\n if (disableSurveys) {\n logger.info('Disabled. Not loading surveys.')\n return\n }\n\n const phExtensions = assignableWindow?.__PosthogExtensions__\n\n if (!phExtensions) {\n logger.error('PostHog Extensions not found.')\n return\n }\n\n if (!this._decideServerResponse) {\n logger.warn('Decide not loaded yet. Not loading surveys.')\n return\n }\n\n this._isInitializingSurveys = true\n\n try {\n const generateSurveys = phExtensions.generateSurveys\n\n if (!generateSurveys) {\n const loadExternalDependency = phExtensions.loadExternalDependency\n\n if (loadExternalDependency) {\n loadExternalDependency(this.instance, 'surveys', (err) => {\n if (err || !phExtensions.generateSurveys) {\n logger.error('Could not load surveys script', err)\n this._isInitializingSurveys = false\n return\n }\n\n this._surveyManager = phExtensions.generateSurveys(this.instance)\n this._isInitializingSurveys = false\n this._surveyEventReceiver = new SurveyEventReceiver(this.instance)\n logger.info('Surveys loaded successfully')\n })\n } else {\n logger.error('PostHog loadExternalDependency extension not found. Cannot load remote config.')\n this._isInitializingSurveys = false\n }\n } else {\n this._surveyManager = generateSurveys(this.instance)\n this._isInitializingSurveys = false\n this._surveyEventReceiver = new SurveyEventReceiver(this.instance)\n logger.info('Surveys loaded successfully')\n }\n } catch (e) {\n logger.error('Error initializing surveys', e)\n this._isInitializingSurveys = false\n throw e\n }\n }\n\n getSurveys(callback: SurveyCallback, forceReload = false) {\n // In case we manage to load the surveys script, but config says not to load surveys\n // then we shouldn't return survey data\n if (this.instance.config.disable_surveys) {\n logger.info('Disabled. Not loading surveys.')\n return callback([])\n }\n\n const existingSurveys = this.instance.get_property(SURVEYS)\n\n if (!existingSurveys || forceReload) {\n // Prevent concurrent API calls\n if (this._isFetchingSurveys) {\n return callback([])\n }\n\n try {\n this._isFetchingSurveys = true\n this.instance._send_request({\n url: this.instance.requestRouter.endpointFor(\n 'api',\n `/api/surveys/?token=${this.instance.config.token}`\n ),\n method: 'GET',\n timeout: this.instance.config.surveys_request_timeout_ms,\n callback: (response) => {\n this._isFetchingSurveys = false\n const statusCode = response.statusCode\n if (statusCode !== 200 || !response.json) {\n logger.error(`Surveys API could not be loaded, status: ${statusCode}`)\n return callback([])\n }\n const surveys = response.json.surveys || []\n\n const eventOrActionBasedSurveys = surveys.filter(\n (survey: Survey) =>\n (survey.conditions?.events &&\n survey.conditions?.events?.values &&\n survey.conditions?.events?.values?.length > 0) ||\n (survey.conditions?.actions &&\n survey.conditions?.actions?.values &&\n survey.conditions?.actions?.values?.length > 0)\n )\n\n if (eventOrActionBasedSurveys.length > 0) {\n this._surveyEventReceiver?.register(eventOrActionBasedSurveys)\n }\n\n this.instance.persistence?.register({ [SURVEYS]: surveys })\n return callback(surveys)\n },\n })\n } catch (e) {\n this._isFetchingSurveys = false\n throw e\n }\n } else {\n return callback(existingSurveys)\n }\n }\n\n private isSurveyFeatureFlagEnabled(flagKey: string | null) {\n if (!flagKey) {\n return true\n }\n return this.instance.featureFlags.isFeatureEnabled(flagKey)\n }\n\n getActiveMatchingSurveys(callback: SurveyCallback, forceReload = false) {\n this.getSurveys((surveys) => {\n const activeSurveys = surveys.filter((survey) => {\n return !!(survey.start_date && !survey.end_date)\n })\n\n const conditionMatchedSurveys = activeSurveys.filter((survey) => {\n if (!survey.conditions) {\n return true\n }\n\n const urlCheck = doesSurveyUrlMatch(survey)\n const selectorCheck = survey.conditions?.selector\n ? document?.querySelector(survey.conditions.selector)\n : true\n const deviceTypeCheck = doesSurveyDeviceTypesMatch(survey)\n return urlCheck && selectorCheck && deviceTypeCheck\n })\n\n // get all the surveys that have been activated so far with user actions.\n const activatedSurveys: string[] | undefined = this._surveyEventReceiver?.getSurveys()\n const targetingMatchedSurveys = conditionMatchedSurveys.filter((survey) => {\n if (\n !survey.linked_flag_key &&\n !survey.targeting_flag_key &&\n !survey.internal_targeting_flag_key &&\n !survey.feature_flag_keys?.length\n ) {\n return true\n }\n const linkedFlagCheck = this.isSurveyFeatureFlagEnabled(survey.linked_flag_key)\n const targetingFlagCheck = this.isSurveyFeatureFlagEnabled(survey.targeting_flag_key)\n\n const hasEvents = (survey.conditions?.events?.values?.length ?? 0) > 0\n const hasActions = (survey.conditions?.actions?.values?.length ?? 0) > 0\n\n const eventBasedTargetingFlagCheck =\n hasEvents || hasActions ? activatedSurveys?.includes(survey.id) : true\n\n const overrideInternalTargetingFlagCheck = this._canActivateRepeatedly(survey)\n const internalTargetingFlagCheck =\n overrideInternalTargetingFlagCheck ||\n this.isSurveyFeatureFlagEnabled(survey.internal_targeting_flag_key)\n\n const flagsCheck = this.checkFlags(survey)\n return (\n linkedFlagCheck &&\n targetingFlagCheck &&\n internalTargetingFlagCheck &&\n eventBasedTargetingFlagCheck &&\n flagsCheck\n )\n })\n\n return callback(targetingMatchedSurveys)\n }, forceReload)\n }\n\n checkFlags(survey: Survey): boolean {\n if (!survey.feature_flag_keys?.length) {\n return true\n }\n\n return survey.feature_flag_keys.every(({ key, value }) => {\n if (!key || !value) {\n return true\n }\n return this.instance.featureFlags.isFeatureEnabled(value)\n })\n }\n\n // this method is lazily loaded onto the window to avoid loading preact and other dependencies if surveys is not enabled\n private _canActivateRepeatedly(survey: Survey) {\n if (isNullish(assignableWindow.__PosthogExtensions__?.canActivateRepeatedly)) {\n logger.warn('init was not called')\n return false // TODO does it make sense to have a default here?\n }\n return assignableWindow.__PosthogExtensions__.canActivateRepeatedly(survey)\n }\n\n canRenderSurvey(surveyId: string) {\n if (isNullish(this._surveyManager)) {\n logger.warn('init was not called')\n return\n }\n this.getSurveys((surveys) => {\n const survey = surveys.filter((x) => x.id === surveyId)[0]\n this._surveyManager.canRenderSurvey(survey)\n })\n }\n\n renderSurvey(surveyId: string, selector: string) {\n if (isNullish(this._surveyManager)) {\n logger.warn('init was not called')\n return\n }\n this.getSurveys((surveys) => {\n const survey = surveys.filter((x) => x.id === surveyId)[0]\n this._surveyManager.renderSurvey(survey, document?.querySelector(selector))\n })\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"posthog-surveys.js","sourceRoot":"","sources":["../../src/posthog-surveys.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAA;AACrC,OAAO,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAA;AAI7E,OAAO,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAA;AAC1C,OAAO,EAAE,gBAAgB,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AAC/E,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAA;AAC7C,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAA;AACrD,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAA;AACnE,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAA;AAE9C,IAAM,MAAM,GAAG,YAAY,CAAC,WAAW,CAAC,CAAA;AAExC,MAAM,CAAC,IAAM,mBAAmB,GAA2E;IACvG,SAAS,EAAE,UAAC,OAAO,EAAE,KAAK,IAAK,OAAA,OAAO,CAAC,IAAI,CAAC,UAAC,MAAM,IAAK,OAAA,KAAK,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC,EAAlD,CAAkD,CAAC,EAA5E,CAA4E;IAE3G,aAAa,EAAE,UAAC,OAAO,EAAE,KAAK,IAAK,OAAA,OAAO,CAAC,KAAK,CAAC,UAAC,MAAM,IAAK,OAAA,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC,EAAnD,CAAmD,CAAC,EAA9E,CAA8E;IAEjH,KAAK,EAAE,UAAC,OAAO,EAAE,KAAK,IAAK,OAAA,OAAO,CAAC,IAAI,CAAC,UAAC,MAAM,IA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AAK,QAAQ,EAAjB,CAAiB,CAAC,CAAC,CAAC,CAAC,CAAA;YAC1D,KAAI,CAAC,cAAc,CAAC,eAAe,CAAC,MAAM,CAAC,CAAA;QAC/C,CAAC,CAAC,CAAA;IACN,CAAC;IAED,qCAAY,GAAZ,UAAa,QAAgB,EAAE,QAAgB;QAA/C,iBASC;QARG,IAAI,SAAS,CAAC,IAAI,CAAC,cAAc,CAAC,EAAE,CAAC;YACjC,MAAM,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAA;YAClC,OAAM;QACV,CAAC;QACD,IAAI,CAAC,UAAU,CAAC,UAAC,OAAO;YACpB,IAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,UAAC,CAAC,IAAK,OAAA,CAAC,CAAC,EAAE,KAAK,QAAQ,EAAjB,CAAiB,CAAC,CAAC,CAAC,CAAC,CAAA;YAC1D,KAAI,CAAC,cAAc,CAAC,YAAY,CAAC,MAAM,EAAE,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,aAAa,CAAC,QAAQ,CAAC,CAAC,CAAA;QAC/E,CAAC,CAAC,CAAA;IACN,CAAC;IACL,qBAAC;AAAD,CAAC,AAnVD,IAmVC","sourcesContent":["import { SURVEYS } from './constants'\nimport { getSurveySeenStorageKeys } from './extensions/surveys/surveys-utils'\nimport { PostHog } from './posthog-core'\nimport { Survey, SurveyCallback, SurveyMatchType } from './posthog-surveys-types'\nimport { RemoteConfig } from './types'\nimport { Info } from './utils/event-utils'\nimport { assignableWindow, document, userAgent, window } from './utils/globals'\nimport { createLogger } from './utils/logger'\nimport { isMatchingRegex } from './utils/regex-utils'\nimport { SurveyEventReceiver } from './utils/survey-event-receiver'\nimport { isNullish } from './utils/type-utils'\n\nconst logger = createLogger('[Surveys]')\n\nexport const surveyValidationMap: Record<SurveyMatchType, (targets: string[], value: string) => boolean> = {\n icontains: (targets, value) => targets.some((target) => value.toLowerCase().includes(target.toLowerCase())),\n\n not_icontains: (targets, value) => targets.every((target) => !value.toLowerCase().includes(target.toLowerCase())),\n\n regex: (targets, value) => targets.some((target) => isMatchingRegex(value, target)),\n\n not_regex: (targets, value) => targets.every((target) => !isMatchingRegex(value, target)),\n\n exact: (targets, value) => targets.some((target) => value === target),\n\n is_not: (targets, value) => targets.every((target) => value !== target),\n}\n\nfunction defaultMatchType(matchType?: SurveyMatchType): SurveyMatchType {\n return matchType ?? 'icontains'\n}\n\n// use urlMatchType to validate url condition, fallback to contains for backwards compatibility\nexport function doesSurveyUrlMatch(survey: Pick<Survey, 'conditions'>): boolean {\n if (!survey.conditions?.url) {\n return true\n }\n // if we dont know the url, assume it is not a match\n const href = window?.location?.href\n if (!href) {\n return false\n }\n\n const targets = [survey.conditions.url]\n return surveyValidationMap[defaultMatchType(survey.conditions?.urlMatchType)](targets, href)\n}\n\nexport function doesSurveyDeviceTypesMatch(survey: Survey): boolean {\n if (!survey.conditions?.deviceTypes || survey.conditions?.deviceTypes.length === 0) {\n return true\n }\n // if we dont know the device type, assume it is not a match\n if (!userAgent) {\n return false\n }\n\n const deviceType = Info.deviceType(userAgent)\n return surveyValidationMap[defaultMatchType(survey.conditions?.deviceTypesMatchType)](\n survey.conditions.deviceTypes,\n deviceType\n )\n}\n\nexport class PostHogSurveys {\n private _decideServerResponse?: boolean\n public _surveyEventReceiver: SurveyEventReceiver | null\n private _surveyManager: any\n private _isFetchingSurveys: boolean = false\n private _isInitializingSurveys: boolean = false\n private _surveyCallbacks: SurveyCallback[] = []\n\n constructor(private readonly instance: PostHog) {\n // we set this to undefined here because we need the persistence storage for this type\n // but that's not initialized until loadIfEnabled is called.\n this._surveyEventReceiver = null\n }\n\n onRemoteConfig(response: RemoteConfig) {\n this._decideServerResponse = !!response['surveys']\n logger.info(`decideServerResponse set to ${this._decideServerResponse}`)\n\n this.loadIfEnabled()\n }\n\n reset(): void {\n localStorage.removeItem('lastSeenSurveyDate')\n const surveyKeys = getSurveySeenStorageKeys()\n surveyKeys.forEach((key) => localStorage.removeItem(key))\n }\n\n loadIfEnabled() {\n if (this._surveyManager) {\n // Surveys already loaded.\n return\n }\n\n if (this._isInitializingSurveys) {\n logger.info('Already initializing surveys, skipping...')\n return\n }\n\n const disableSurveys = this.instance.config.disable_surveys\n\n if (disableSurveys) {\n logger.info('Disabled. Not loading surveys.')\n return\n }\n\n const phExtensions = assignableWindow?.__PosthogExtensions__\n\n if (!phExtensions) {\n logger.error('PostHog Extensions not found.')\n return\n }\n\n if (!this._decideServerResponse) {\n logger.warn('Decide not loaded yet. Not loading surveys.')\n return\n }\n\n this._isInitializingSurveys = true\n\n try {\n const generateSurveys = phExtensions.generateSurveys\n\n if (!generateSurveys) {\n const loadExternalDependency = phExtensions.loadExternalDependency\n\n if (loadExternalDependency) {\n loadExternalDependency(this.instance, 'surveys', (err) => {\n if (err || !phExtensions.generateSurveys) {\n logger.error('Could not load surveys script', err)\n this._isInitializingSurveys = false\n return\n }\n\n this._surveyManager = phExtensions.generateSurveys(this.instance)\n this._isInitializingSurveys = false\n this._surveyEventReceiver = new SurveyEventReceiver(this.instance)\n logger.info('Surveys loaded successfully')\n this._notifySurveyCallbacks({\n isLoaded: true,\n })\n })\n } else {\n const error = 'PostHog loadExternalDependency extension not found. Cannot load remote config.'\n logger.error(error)\n this._isInitializingSurveys = false\n this._notifySurveyCallbacks({\n isLoaded: false,\n error,\n })\n }\n } else {\n this._surveyManager = generateSurveys(this.instance)\n this._isInitializingSurveys = false\n this._surveyEventReceiver = new SurveyEventReceiver(this.instance)\n logger.info('Surveys loaded successfully')\n this._notifySurveyCallbacks({\n isLoaded: true,\n })\n }\n } catch (e) {\n logger.error('Error initializing surveys', e)\n this._isInitializingSurveys = false\n this._notifySurveyCallbacks({\n isLoaded: false,\n error: 'Error initializing surveys',\n })\n throw e\n }\n }\n\n /**\n * Register a callback that runs when surveys are initialized.\n * ### Usage:\n *\n * posthog.onSurveysLoaded((surveys) => {\n * // You can work with all surveys\n * console.log('All available surveys:', surveys)\n *\n * // Or get active matching surveys\n * posthog.getActiveMatchingSurveys((activeMatchingSurveys) => {\n * if (activeMatchingSurveys.length > 0) {\n * posthog.renderSurvey(activeMatchingSurveys[0].id, '#survey-container')\n * }\n * })\n * })\n *\n * @param {Function} callback The callback function will be called when surveys are loaded or updated.\n * It receives the array of all surveys and a context object with error status.\n * @returns {Function} A function that can be called to unsubscribe the listener.\n */\n onSurveysLoaded(callback: SurveyCallback): () => void {\n this._surveyCallbacks.push(callback)\n\n if (this._surveyManager) {\n this._notifySurveyCallbacks({\n isLoaded: true,\n })\n }\n // Return unsubscribe function\n return () => {\n this._surveyCallbacks = this._surveyCallbacks.filter((cb: SurveyCallback) => cb !== callback)\n }\n }\n\n getSurveys(callback: SurveyCallback, forceReload = false) {\n // In case we manage to load the surveys script, but config says not to load surveys\n // then we shouldn't return survey data\n if (this.instance.config.disable_surveys) {\n logger.info('Disabled. Not loading surveys.')\n return callback([])\n }\n\n const existingSurveys = this.instance.get_property(SURVEYS)\n\n if (!existingSurveys || forceReload) {\n // Prevent concurrent API calls\n if (this._isFetchingSurveys) {\n return callback([], {\n isLoaded: false,\n error: 'Surveys are already being loaded',\n })\n }\n\n try {\n this._isFetchingSurveys = true\n this.instance._send_request({\n url: this.instance.requestRouter.endpointFor(\n 'api',\n `/api/surveys/?token=${this.instance.config.token}`\n ),\n method: 'GET',\n timeout: this.instance.config.surveys_request_timeout_ms,\n callback: (response) => {\n this._isFetchingSurveys = false\n const statusCode = response.statusCode\n if (statusCode !== 200 || !response.json) {\n const error = `Surveys API could not be loaded, status: ${statusCode}`\n logger.error(error)\n return callback([], {\n isLoaded: false,\n error,\n })\n }\n const surveys = response.json.surveys || []\n\n const eventOrActionBasedSurveys = surveys.filter(\n (survey: Survey) =>\n (survey.conditions?.events &&\n survey.conditions?.events?.values &&\n survey.conditions?.events?.values?.length > 0) ||\n (survey.conditions?.actions &&\n survey.conditions?.actions?.values &&\n survey.conditions?.actions?.values?.length > 0)\n )\n\n if (eventOrActionBasedSurveys.length > 0) {\n this._surveyEventReceiver?.register(eventOrActionBasedSurveys)\n }\n\n this.instance.persistence?.register({ [SURVEYS]: surveys })\n return callback(surveys, {\n isLoaded: true,\n })\n },\n })\n } catch (e) {\n this._isFetchingSurveys = false\n throw e\n }\n } else {\n return callback(existingSurveys, {\n isLoaded: true,\n })\n }\n }\n\n /** Helper method to notify all registered callbacks */\n private _notifySurveyCallbacks(context: { isLoaded: boolean; error?: string }): void {\n for (const callback of this._surveyCallbacks) {\n try {\n if (!context.isLoaded) {\n callback([], context)\n } else {\n this.getSurveys(callback)\n }\n } catch (error) {\n logger.error('Error in survey callback', error)\n }\n }\n }\n\n private isSurveyFeatureFlagEnabled(flagKey: string | null) {\n if (!flagKey) {\n return true\n }\n return this.instance.featureFlags.isFeatureEnabled(flagKey)\n }\n\n getActiveMatchingSurveys(callback: SurveyCallback, forceReload = false) {\n this.getSurveys((surveys) => {\n const activeSurveys = surveys.filter((survey) => {\n return !!(survey.start_date && !survey.end_date)\n })\n\n const conditionMatchedSurveys = activeSurveys.filter((survey) => {\n if (!survey.conditions) {\n return true\n }\n\n const urlCheck = doesSurveyUrlMatch(survey)\n const selectorCheck = survey.conditions?.selector\n ? document?.querySelector(survey.conditions.selector)\n : true\n const deviceTypeCheck = doesSurveyDeviceTypesMatch(survey)\n return urlCheck && selectorCheck && deviceTypeCheck\n })\n\n // get all the surveys that have been activated so far with user actions.\n const activatedSurveys: string[] | undefined = this._surveyEventReceiver?.getSurveys()\n const targetingMatchedSurveys = conditionMatchedSurveys.filter((survey) => {\n if (\n !survey.linked_flag_key &&\n !survey.targeting_flag_key &&\n !survey.internal_targeting_flag_key &&\n !survey.feature_flag_keys?.length\n ) {\n return true\n }\n const linkedFlagCheck = this.isSurveyFeatureFlagEnabled(survey.linked_flag_key)\n const targetingFlagCheck = this.isSurveyFeatureFlagEnabled(survey.targeting_flag_key)\n\n const hasEvents = (survey.conditions?.events?.values?.length ?? 0) > 0\n const hasActions = (survey.conditions?.actions?.values?.length ?? 0) > 0\n\n const eventBasedTargetingFlagCheck =\n hasEvents || hasActions ? activatedSurveys?.includes(survey.id) : true\n\n const overrideInternalTargetingFlagCheck = this._canActivateRepeatedly(survey)\n const internalTargetingFlagCheck =\n overrideInternalTargetingFlagCheck ||\n this.isSurveyFeatureFlagEnabled(survey.internal_targeting_flag_key)\n\n const flagsCheck = this.checkFlags(survey)\n return (\n linkedFlagCheck &&\n targetingFlagCheck &&\n internalTargetingFlagCheck &&\n eventBasedTargetingFlagCheck &&\n flagsCheck\n )\n })\n\n return callback(targetingMatchedSurveys)\n }, forceReload)\n }\n\n checkFlags(survey: Survey): boolean {\n if (!survey.feature_flag_keys?.length) {\n return true\n }\n\n return survey.feature_flag_keys.every(({ key, value }) => {\n if (!key || !value) {\n return true\n }\n return this.instance.featureFlags.isFeatureEnabled(value)\n })\n }\n\n // this method is lazily loaded onto the window to avoid loading preact and other dependencies if surveys is not enabled\n private _canActivateRepeatedly(survey: Survey) {\n if (isNullish(assignableWindow.__PosthogExtensions__?.canActivateRepeatedly)) {\n logger.warn('init was not called')\n return false // TODO does it make sense to have a default here?\n }\n return assignableWindow.__PosthogExtensions__.canActivateRepeatedly(survey)\n }\n\n canRenderSurvey(surveyId: string) {\n if (isNullish(this._surveyManager)) {\n logger.warn('init was not called')\n return\n }\n this.getSurveys((surveys) => {\n const survey = surveys.filter((x) => x.id === surveyId)[0]\n this._surveyManager.canRenderSurvey(survey)\n })\n }\n\n renderSurvey(surveyId: string, selector: string) {\n if (isNullish(this._surveyManager)) {\n logger.warn('init was not called')\n return\n }\n this.getSurveys((surveys) => {\n const survey = surveys.filter((x) => x.id === surveyId)[0]\n this._surveyManager.renderSurvey(survey, document?.querySelector(selector))\n })\n }\n}\n"]}
|
package/package.json
CHANGED