posthog-react-native 4.74.1 → 4.74.2

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 (126) hide show
  1. package/dist/PostHogContext.js +2 -1
  2. package/dist/PostHogContext.js.map +1 -1
  3. package/dist/PostHogErrorBoundary.js +2 -1
  4. package/dist/PostHogErrorBoundary.js.map +1 -1
  5. package/dist/PostHogMaskView.js +2 -1
  6. package/dist/PostHogMaskView.js.map +1 -1
  7. package/dist/PostHogProvider.js +2 -1
  8. package/dist/PostHogProvider.js.map +1 -1
  9. package/dist/autocapture.js +2 -1
  10. package/dist/autocapture.js.map +1 -1
  11. package/dist/error-tracking/exception-context.js +2 -1
  12. package/dist/error-tracking/exception-context.js.map +1 -1
  13. package/dist/error-tracking/index.js +2 -1
  14. package/dist/error-tracking/index.js.map +1 -1
  15. package/dist/error-tracking/utils.js +2 -1
  16. package/dist/error-tracking/utils.js.map +1 -1
  17. package/dist/frameworks/wix-navigation.js +2 -1
  18. package/dist/frameworks/wix-navigation.js.map +1 -1
  19. package/dist/hooks/useFeatureFlag.js +2 -1
  20. package/dist/hooks/useFeatureFlag.js.map +1 -1
  21. package/dist/hooks/useFeatureFlagResult.js +2 -1
  22. package/dist/hooks/useFeatureFlagResult.js.map +1 -1
  23. package/dist/hooks/useFeatureFlags.js +2 -1
  24. package/dist/hooks/useFeatureFlags.js.map +1 -1
  25. package/dist/hooks/useNavigationTracker.js +2 -1
  26. package/dist/hooks/useNavigationTracker.js.map +1 -1
  27. package/dist/hooks/usePostHog.js +2 -1
  28. package/dist/hooks/usePostHog.js.map +1 -1
  29. package/dist/hooks/utils.js +2 -1
  30. package/dist/hooks/utils.js.map +1 -1
  31. package/dist/index.js +2 -1
  32. package/dist/index.js.map +1 -1
  33. package/dist/logs-defaults.js +2 -1
  34. package/dist/logs-defaults.js.map +1 -1
  35. package/dist/native-deps.js +2 -1
  36. package/dist/native-deps.js.map +1 -1
  37. package/dist/optional/OptionalAsyncStorage.js +2 -1
  38. package/dist/optional/OptionalAsyncStorage.js.map +1 -1
  39. package/dist/optional/OptionalExpoApplication.js +2 -1
  40. package/dist/optional/OptionalExpoApplication.js.map +1 -1
  41. package/dist/optional/OptionalExpoDevice.js +2 -1
  42. package/dist/optional/OptionalExpoDevice.js.map +1 -1
  43. package/dist/optional/OptionalExpoFileSystem.js +2 -1
  44. package/dist/optional/OptionalExpoFileSystem.js.map +1 -1
  45. package/dist/optional/OptionalExpoFileSystemLegacy.js +2 -1
  46. package/dist/optional/OptionalExpoFileSystemLegacy.js.map +1 -1
  47. package/dist/optional/OptionalExpoLocalization.js +2 -1
  48. package/dist/optional/OptionalExpoLocalization.js.map +1 -1
  49. package/dist/optional/OptionalExpoUpdates.js +2 -1
  50. package/dist/optional/OptionalExpoUpdates.js.map +1 -1
  51. package/dist/optional/OptionalPlugin.js +2 -1
  52. package/dist/optional/OptionalPlugin.js.map +1 -1
  53. package/dist/optional/OptionalReactNativeDeviceInfo.js +2 -1
  54. package/dist/optional/OptionalReactNativeDeviceInfo.js.map +1 -1
  55. package/dist/optional/OptionalReactNativeLocalize.js +2 -1
  56. package/dist/optional/OptionalReactNativeLocalize.js.map +1 -1
  57. package/dist/optional/OptionalReactNativeNavigation.js +2 -1
  58. package/dist/optional/OptionalReactNativeNavigation.js.map +1 -1
  59. package/dist/optional/OptionalReactNativeNavigationWix.js +2 -1
  60. package/dist/optional/OptionalReactNativeNavigationWix.js.map +1 -1
  61. package/dist/optional/OptionalReactNativeSafeArea.js +2 -1
  62. package/dist/optional/OptionalReactNativeSafeArea.js.map +1 -1
  63. package/dist/optional/OptionalReactNativeSvg.js +2 -1
  64. package/dist/optional/OptionalReactNativeSvg.js.map +1 -1
  65. package/dist/posthog-rn.js +2 -1
  66. package/dist/posthog-rn.js.map +1 -1
  67. package/dist/storage.js +2 -1
  68. package/dist/storage.js.map +1 -1
  69. package/dist/surveys/PostHogSurveyProvider.js +2 -1
  70. package/dist/surveys/PostHogSurveyProvider.js.map +1 -1
  71. package/dist/surveys/components/BottomSection.js +2 -1
  72. package/dist/surveys/components/BottomSection.js.map +1 -1
  73. package/dist/surveys/components/Cancel.js +2 -1
  74. package/dist/surveys/components/Cancel.js.map +1 -1
  75. package/dist/surveys/components/ConfirmationMessage.js +2 -1
  76. package/dist/surveys/components/ConfirmationMessage.js.map +1 -1
  77. package/dist/surveys/components/IntroMessage.js +2 -1
  78. package/dist/surveys/components/IntroMessage.js.map +1 -1
  79. package/dist/surveys/components/QuestionHeader.js +2 -1
  80. package/dist/surveys/components/QuestionHeader.js.map +1 -1
  81. package/dist/surveys/components/QuestionTypes.js +2 -1
  82. package/dist/surveys/components/QuestionTypes.js.map +1 -1
  83. package/dist/surveys/components/SurveyModal.js +2 -1
  84. package/dist/surveys/components/SurveyModal.js.map +1 -1
  85. package/dist/surveys/components/Surveys.js +2 -1
  86. package/dist/surveys/components/Surveys.js.map +1 -1
  87. package/dist/surveys/getActiveMatchingSurveys.js +2 -1
  88. package/dist/surveys/getActiveMatchingSurveys.js.map +1 -1
  89. package/dist/surveys/icons.js +2 -1
  90. package/dist/surveys/icons.js.map +1 -1
  91. package/dist/surveys/index.js +2 -1
  92. package/dist/surveys/index.js.map +1 -1
  93. package/dist/surveys/safeStyleSheet.js +2 -1
  94. package/dist/surveys/safeStyleSheet.js.map +1 -1
  95. package/dist/surveys/survey-shuffling.js +2 -1
  96. package/dist/surveys/survey-shuffling.js.map +1 -1
  97. package/dist/surveys/survey-translations.js +2 -1
  98. package/dist/surveys/survey-translations.js.map +1 -1
  99. package/dist/surveys/surveys-utils.js +2 -1
  100. package/dist/surveys/surveys-utils.js.map +1 -1
  101. package/dist/surveys/useActivatedSurveys.js +2 -1
  102. package/dist/surveys/useActivatedSurveys.js.map +1 -1
  103. package/dist/surveys/useSurveyStorage.js +2 -1
  104. package/dist/surveys/useSurveyStorage.js.map +1 -1
  105. package/dist/tooling/expoconfig.js +2 -1
  106. package/dist/tooling/expoconfig.js.map +1 -1
  107. package/dist/tooling/metroconfig.js +2 -1
  108. package/dist/tooling/metroconfig.js.map +1 -1
  109. package/dist/tooling/posthogMetroSerializer.js +2 -1
  110. package/dist/tooling/posthogMetroSerializer.js.map +1 -1
  111. package/dist/tooling/utils.js +2 -1
  112. package/dist/tooling/utils.js.map +1 -1
  113. package/dist/tooling/vendor/expo/expoconfig.js +2 -1
  114. package/dist/tooling/vendor/expo/expoconfig.js.map +1 -1
  115. package/dist/tooling/vendor/metro/countLines.js +2 -1
  116. package/dist/tooling/vendor/metro/countLines.js.map +1 -1
  117. package/dist/tooling/vendor/metro/utils.js +2 -1
  118. package/dist/tooling/vendor/metro/utils.js.map +1 -1
  119. package/dist/types.js +2 -1
  120. package/dist/types.js.map +1 -1
  121. package/dist/utils.js +2 -1
  122. package/dist/utils.js.map +1 -1
  123. package/dist/version.d.ts +1 -1
  124. package/dist/version.js +2 -1
  125. package/dist/version.js.map +1 -1
  126. package/package.json +7 -6
@@ -1 +1 @@
1
- {"version":3,"file":"surveys-utils.js","sourceRoot":"","sources":["../../src/surveys/surveys-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,2BAA2B,EAC3B,kBAAkB,EAIlB,cAAc,EACd,oCAAoC,GACrC,MAAM,eAAe,CAAA;AAGtB,OAAO,EACL,eAAe,EACf,oBAAoB,EACpB,mBAAmB,IAAI,mBAAmB,GAC3C,MAAM,uBAAuB,CAAA;AAE9B,SAAS,SAAS,CAAC,KAAc;IAC/B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAA;AAC7D,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,uBAAuB,CACrC,WAA2B,EAC3B,WAAkD;IAElD,MAAM,oBAAoB,GAAG,WAAW,aAAX,WAAW,cAAX,WAAW,GAAI,oCAAoC,CAAC,IAAI,CAAA;IACrF,OAAO,OAAO,CAAC,WAAW,IAAI,oBAAoB,KAAK,oCAAoC,CAAC,IAAI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,SAAS;QAClB,MAAM,EAAE,SAAS;QACjB,SAAS,EAAE,SAAS;QACpB,MAAM,EAAE,SAAS;QACjB,KAAK,EAAE,SAAS;QAChB,KAAK,EAAE,SAAS;QAChB,UAAU,EAAE,SAAS;QACrB,MAAM,EAAE,SAAS;QACjB,WAAW,EAAE,SAAS;KACvB,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,CAAA;AACvB,CAAC"}
1
+ {"version":3,"file":"surveys-utils.js","names":["_core","require","_surveys","isInteger","value","Number","shouldRenderDescription","description","contentType","effectiveContentType","SurveyQuestionDescriptionContentType","Text","Boolean","defaultBackgroundColor","exports","defaultDescriptionOpacity","defaultRatingLabelOpacity","closeButtonSize","getMaxFontSizeMultiplier","appearance","role","configured","maxFontSizeMultiplier","defaultSurveyAppearance","backgroundColor","submitButtonColor","submitButtonTextColor","ratingButtonColor","ratingButtonActiveColor","inputBackground","borderColor","displayThankYouMessage","thankYouMessageHeader","position","SurveyPosition","Center","submitButtonText","autoDisappear","thankYouMessageDescription","thankYouMessageDescriptionContentType","thankYouMessageCloseButtonText","displayIntroScreen","introScreenHeader","introScreenDescription","introScreenDescriptionContentType","introScreenButtonText","surveyPopupDelaySeconds","allowGoBack","backButtonText","KNOWN_SURVEY_POSITIONS","Set","Object","values","warnedUnknownPositions","normalizeSurveyPosition","replace","resolveSurveyAlignment","resolvedPosition","normalizedPosition","has","add","console","warn","concat","JSON","stringify","join","isTop","TopLeft","TopCenter","TopRight","isMiddle","MiddleLeft","MiddleCenter","MiddleRight","isLeft","Left","isRight","Right","vertical","horizontal","getDisplayOrderQuestions","survey","questions","forEach","question","idx","originalQuestionIndex","getRatingBucketForResponseValue","responseValue","scale","getNextSurveyStep","currentQuestionIndex","response","nextQuestionIndex","_a","branching","type","length","SurveyQuestionBranchingType","End","SpecificQuestion","index","ResponseBased","SurveyQuestionType","SingleChoice","selectedChoiceIndex","choices","indexOf","hasOpenChoice","_c","_b","responseValues","hasOwnProperty","nextStep","Rating","ratingQuestion","ratingBucket","_e","_d","getContrastingTextColor","color","rgb","startsWith","hex2rgb","nameColorToHex","nameToHex","colorMatch","match","r","parseInt","g","b","hsp","Math","sqrt","c","hexColor","test","slice","name","aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","green","greenyellow","honeydew","hotpink","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgrey","lightgreen","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen","toLowerCase"],"sources":["../../src/surveys/surveys-utils.ts"],"sourcesContent":["import {\n Survey,\n SurveyQuestion,\n SurveyQuestionBranchingType,\n SurveyQuestionType,\n SurveyRatingDisplay,\n RatingSurveyQuestion,\n SurveyAppearance as CoreSurveyAppearance,\n SurveyPosition,\n SurveyQuestionDescriptionContentType,\n} from '@posthog/core'\n\nexport type { PropertyFilters, PropertyOperator, SurveyEventWithFilters } from '@posthog/core'\nexport {\n isMatchingRegex,\n matchPropertyFilters,\n propertyComparisons as surveyValidationMap,\n} from '@posthog/core/surveys'\n\nfunction isInteger(value: unknown): boolean {\n return typeof value === 'number' && Number.isInteger(value)\n}\n\n/**\n * Utility function to determine if a description should be rendered based on content type\n * Only renders text content, skips HTML content for React Native compatibility\n * Defaults to Text content type when not specified\n * @param description The description text\n * @param contentType The content type (text or html), defaults to Text if not provided\n * @returns True if the description should be rendered, false otherwise\n */\nexport function shouldRenderDescription(\n description?: string | null,\n contentType?: SurveyQuestionDescriptionContentType\n): boolean {\n const effectiveContentType = contentType ?? SurveyQuestionDescriptionContentType.Text\n return Boolean(description && effectiveContentType === SurveyQuestionDescriptionContentType.Text)\n}\n\nexport const defaultBackgroundColor = '#eeeded' as const\nexport const defaultDescriptionOpacity = 0.8\nexport const defaultRatingLabelOpacity = 0.7\n\n/**\n * Side of the circular close button. The button is absolutely positioned in the modal's\n * top-right corner, so the content containers underneath it reserve this much padding on\n * their right edge to keep long text from wrapping into it.\n */\nexport const closeButtonSize = 40\n\n/**\n * The distinct kinds of text a survey renders, each at its own base size. They\n * are separate because one ceiling cannot serve all of them: `question` is an\n * 18pt headline that can wrap freely, while `ratingNumber` sits inside a\n * fixed-width button and has nowhere to grow.\n */\nexport type SurveyTextRole =\n /** The question headline. */\n | 'question'\n /** Body copy under a question, an intro screen, or the thank-you screen. */\n | 'description'\n /** The intro-screen and thank-you-screen headers. */\n | 'header'\n /** A choice label in a single- or multiple-choice question. */\n | 'choice'\n /** Text the user types - the open-text answer and the open-choice field. */\n | 'input'\n /** The submit / next button label. */\n | 'button'\n /** The lower- and upper-bound labels under a rating scale. */\n | 'ratingLabel'\n /** The numeral inside a rating button, which cannot grow past the button. */\n | 'ratingNumber'\n /** The validation hint under an open-text answer. */\n | 'validationHint'\n\n/** React Native survey appearance, including native-only text scaling options. */\nexport interface SurveyAppearance extends CoreSurveyAppearance {\n /**\n * Caps how far survey text may grow under the OS text-size setting, as a\n * multiple of its base size - React Native's `maxFontSizeMultiplier`, applied\n * to every semantic `Text` and `TextInput` the survey renders. Icon-only text\n * fallbacks do not scale because they occupy fixed-size icon boxes.\n *\n * Pass a number to cap every role at once, or an object to cap them\n * separately: a survey headline can usually take more scaling than a numeral\n * inside a rating button, and a host app that already caps its own text by\n * role will want to match those ceilings here.\n *\n * ```ts\n * maxFontSizeMultiplier: 1.6\n * // or\n * maxFontSizeMultiplier: { question: 1.5, description: 1.8, ratingNumber: 1.2 }\n * ```\n *\n * Roles left out of the object are uncapped, as they are today. Use `0` for\n * no maximum, or a value of `1` or greater to set a cap. Other values below\n * `1` (such as `0.8`) do not shrink text and are unsupported by React Native;\n * depending on the platform and version, they may be ignored or rejected.\n *\n * Leave it unset (the default) and survey text scales without a ceiling. That\n * is what the OS asks for, but not always what a fixed-size survey card can\n * hold - at the largest accessibility sizes an unbounded 18pt headline renders\n * roughly one word per line.\n *\n * React Native only inherits this prop through nested `Text`, so a host app\n * cannot apply it from the outside - it has to come in here.\n *\n * @default undefined (no ceiling)\n */\n maxFontSizeMultiplier?: number | Partial<Record<SurveyTextRole, number>>\n}\n\n// textColor and inputTextColor are optional overrides (auto-calculated if not provided)\n// placeholder is optional too: open text questions only show placeholder text when the survey's\n// appearance sets one, so clearing the field in the survey editor clears it here too.\nexport type SurveyAppearanceTheme = Omit<\n Required<SurveyAppearance>,\n | 'widgetSelector'\n | 'widgetType'\n | 'widgetColor'\n | 'widgetLabel'\n | 'shuffleQuestions'\n | 'textColor'\n | 'inputTextColor'\n | 'placeholder'\n | 'maxFontSizeMultiplier'\n> & {\n textColor?: string\n inputTextColor?: string\n placeholder?: string\n maxFontSizeMultiplier?: SurveyAppearance['maxFontSizeMultiplier']\n}\n\n/**\n * The ceiling for one role, from either form of `maxFontSizeMultiplier`.\n *\n * Returns `undefined` when nothing is configured for that role, which is also\n * React Native's \"no ceiling\" - so an unset appearance renders exactly as it\n * did before this option existed.\n */\nexport function getMaxFontSizeMultiplier(\n appearance: Pick<SurveyAppearance, 'maxFontSizeMultiplier'>,\n role: SurveyTextRole\n): number | undefined {\n const configured = appearance.maxFontSizeMultiplier\n if (typeof configured === 'number') {\n return configured\n }\n return configured?.[role]\n}\nexport const defaultSurveyAppearance: SurveyAppearanceTheme = {\n backgroundColor: defaultBackgroundColor,\n submitButtonColor: 'black',\n submitButtonTextColor: 'white',\n ratingButtonColor: 'white',\n ratingButtonActiveColor: 'black',\n inputBackground: 'white',\n borderColor: '#c9c6c6',\n displayThankYouMessage: true,\n thankYouMessageHeader: 'Thank you for your feedback!',\n position: SurveyPosition.Center,\n submitButtonText: 'Submit',\n autoDisappear: false,\n thankYouMessageDescription: '',\n thankYouMessageDescriptionContentType: SurveyQuestionDescriptionContentType.Text,\n thankYouMessageCloseButtonText: 'Close',\n displayIntroScreen: false,\n introScreenHeader: '',\n introScreenDescription: '',\n introScreenDescriptionContentType: SurveyQuestionDescriptionContentType.Text,\n introScreenButtonText: 'Get started',\n surveyPopupDelaySeconds: 0,\n allowGoBack: false,\n backButtonText: 'Back',\n}\n\nexport type SurveyFlexAlign = 'flex-start' | 'center' | 'flex-end'\n\nconst KNOWN_SURVEY_POSITIONS: ReadonlySet<string> = new Set(Object.values(SurveyPosition))\nconst warnedUnknownPositions = new Set<string>()\n\n// Some survey API clients use CSS-style names such as `bottom-right`, while\n// SurveyPosition represents the bottom row as `left`, `center`, and `right`.\nfunction normalizeSurveyPosition(position: string): string {\n return position.replace(/-/g, '_').replace(/^bottom_/, '')\n}\n\n// Mirrors web SDK semantics: `.ph-survey` is bottom-anchored by default and\n// getPopoverPosition only overrides `top` for top_* / middle_* variants. So\n// `left` / `right` / `center` (no prefix) anchor to the bottom edge — they\n// are NOT shorthand for middle.\nexport function resolveSurveyAlignment(position: string | undefined): {\n vertical: SurveyFlexAlign\n horizontal: SurveyFlexAlign\n} {\n let resolvedPosition: SurveyPosition = defaultSurveyAppearance.position\n if (position) {\n const normalizedPosition = typeof position === 'string' ? normalizeSurveyPosition(position) : ''\n if (KNOWN_SURVEY_POSITIONS.has(normalizedPosition)) {\n resolvedPosition = normalizedPosition as SurveyPosition\n } else if (!warnedUnknownPositions.has(normalizedPosition)) {\n warnedUnknownPositions.add(normalizedPosition)\n console.warn(\n `[PostHog.surveys] Unknown survey position ${JSON.stringify(position)} — falling back to ${defaultSurveyAppearance.position}. Expected one of: ${Object.values(SurveyPosition).join(', ')}.`\n )\n }\n }\n const isTop =\n resolvedPosition === SurveyPosition.TopLeft ||\n resolvedPosition === SurveyPosition.TopCenter ||\n resolvedPosition === SurveyPosition.TopRight\n const isMiddle =\n resolvedPosition === SurveyPosition.MiddleLeft ||\n resolvedPosition === SurveyPosition.MiddleCenter ||\n resolvedPosition === SurveyPosition.MiddleRight\n const isLeft =\n resolvedPosition === SurveyPosition.TopLeft ||\n resolvedPosition === SurveyPosition.MiddleLeft ||\n resolvedPosition === SurveyPosition.Left\n const isRight =\n resolvedPosition === SurveyPosition.TopRight ||\n resolvedPosition === SurveyPosition.MiddleRight ||\n resolvedPosition === SurveyPosition.Right\n return {\n vertical: isTop ? 'flex-start' : isMiddle ? 'center' : 'flex-end',\n horizontal: isLeft ? 'flex-start' : isRight ? 'flex-end' : 'center',\n }\n}\n\nexport const getDisplayOrderQuestions = (survey: Survey): SurveyQuestion[] => {\n // retain the original questionIndex so we can correlate values in the webapp\n survey.questions.forEach((question: SurveyQuestion, idx: number) => {\n question.originalQuestionIndex = idx\n })\n\n // TODO: shuffle questions\n return survey.questions\n\n // if (!survey.appearance?.shuffleQuestions) {\n // return survey.questions\n // }\n\n // return reverseIfUnshuffled(survey.questions, shuffle(survey.questions))\n}\n\n/**\n * Use the Fisher-yates algorithm to shuffle this array\n * https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\n */\n// export const shuffle = <T>(array: T[]): T[] => {\n// return array\n// .map((a) => ({ sort: Math.floor(Math.random() * 10), value: a }))\n// .sort((a, b) => a.sort - b.sort)\n// .map((a) => a.value)\n// }\n\n// const reverseIfUnshuffled = <T>(unshuffled: T[], shuffled: T[]): T[] => {\n// if (unshuffled.length === shuffled.length && unshuffled.every((val, index) => val === shuffled[index])) {\n// return shuffled.reverse()\n// }\n\n// return shuffled\n// }\n\n/**\n * Get the rating bucket for a response value based on the scale\n * @param responseValue The numeric rating value\n * @param scale The scale of the rating (3, 5, 7, or 10)\n * @returns The bucket name for the rating\n */\nfunction getRatingBucketForResponseValue(responseValue: number, scale: number): string {\n if (scale === 3) {\n if (responseValue < 1 || responseValue > 3) {\n console.warn('PostHog Debug: Rating response out of range for scale 3:', responseValue)\n return 'neutral' // Default to neutral for out-of-range values\n }\n\n return responseValue === 1 ? 'negative' : responseValue === 2 ? 'neutral' : 'positive'\n } else if (scale === 5) {\n if (responseValue < 1 || responseValue > 5) {\n console.warn('PostHog Debug: Rating response out of range for scale 5:', responseValue)\n return 'neutral' // Default to neutral for out-of-range values\n }\n\n return responseValue <= 2 ? 'negative' : responseValue === 3 ? 'neutral' : 'positive'\n } else if (scale === 7) {\n if (responseValue < 1 || responseValue > 7) {\n console.warn('PostHog Debug: Rating response out of range for scale 7:', responseValue)\n return 'neutral' // Default to neutral for out-of-range values\n }\n\n return responseValue <= 3 ? 'negative' : responseValue === 4 ? 'neutral' : 'positive'\n } else if (scale === 10) {\n if (responseValue < 0 || responseValue > 10) {\n console.warn('PostHog Debug: Rating response out of range for scale 10:', responseValue)\n return 'passives' // Default to passives for out-of-range values\n }\n\n return responseValue <= 6 ? 'detractors' : responseValue <= 8 ? 'passives' : 'promoters'\n }\n\n console.warn('PostHog Debug: Unsupported rating scale:', scale)\n return 'neutral' // Default fallback for unsupported scales\n}\n\n/**\n * Determines the next question to show based on the survey's branching logic\n * @param survey The survey object\n * @param currentQuestionIndex The current question index\n * @param response The user's response to the current question\n * @returns The index of the next question or SurveyQuestionBranchingType.End if the survey should end\n */\nexport function getNextSurveyStep(\n survey: Survey,\n currentQuestionIndex: number,\n response: string | string[] | number | null\n): number | typeof SurveyQuestionBranchingType.End {\n const question = survey.questions[currentQuestionIndex]\n const nextQuestionIndex = currentQuestionIndex + 1\n\n if (!question.branching?.type) {\n if (currentQuestionIndex === survey.questions.length - 1) {\n return SurveyQuestionBranchingType.End\n }\n\n return nextQuestionIndex\n }\n\n if (question.branching.type === SurveyQuestionBranchingType.End) {\n return SurveyQuestionBranchingType.End\n } else if (question.branching.type === SurveyQuestionBranchingType.SpecificQuestion) {\n if (isInteger(question.branching.index)) {\n return question.branching.index\n }\n } else if (question.branching.type === SurveyQuestionBranchingType.ResponseBased) {\n // Single choice\n if (question.type === SurveyQuestionType.SingleChoice) {\n // Look up the choiceIndex based on the response\n let selectedChoiceIndex = question.choices.indexOf(`${response}`)\n\n if (selectedChoiceIndex === -1 && question.hasOpenChoice) {\n // if the response is not found in the choices, it must be the open choice,\n // which is always the last choice\n selectedChoiceIndex = question.choices.length - 1\n }\n\n if (question.branching?.responseValues?.hasOwnProperty(selectedChoiceIndex)) {\n const nextStep = question.branching.responseValues[selectedChoiceIndex]\n\n // Specific question\n if (isInteger(nextStep)) {\n return nextStep\n }\n\n if (nextStep === SurveyQuestionBranchingType.End) {\n return SurveyQuestionBranchingType.End\n }\n\n return nextQuestionIndex\n }\n } else if (question.type === SurveyQuestionType.Rating) {\n if (!isInteger(response)) {\n console.warn('PostHog Debug: Expected integer response for rating question but received:', response)\n return nextQuestionIndex // Fail gracefully by continuing to next question\n }\n\n const ratingQuestion = question as RatingSurveyQuestion\n const ratingBucket = getRatingBucketForResponseValue(response as number, ratingQuestion.scale)\n\n if (question.branching?.responseValues?.hasOwnProperty(ratingBucket)) {\n const nextStep = question.branching.responseValues[ratingBucket]\n\n // Specific question\n if (isInteger(nextStep)) {\n return nextStep\n }\n\n if (nextStep === SurveyQuestionBranchingType.End) {\n return SurveyQuestionBranchingType.End\n }\n\n return nextQuestionIndex\n }\n }\n\n return nextQuestionIndex\n }\n\n console.warn('Falling back to next question index due to unexpected branching type')\n return nextQuestionIndex\n}\n\nexport function getContrastingTextColor(color: string): 'black' | 'white' {\n let rgb: string | undefined\n if (color.startsWith('#')) {\n rgb = hex2rgb(color)\n }\n if (color.startsWith('rgb')) {\n rgb = color\n }\n // otherwise it's a color name\n const nameColorToHex = nameToHex(color)\n if (nameColorToHex) {\n rgb = hex2rgb(nameColorToHex)\n }\n if (!rgb) {\n return 'black'\n }\n const colorMatch = rgb.match(/^rgba?\\((\\d+),\\s*(\\d+),\\s*(\\d+)(?:,\\s*(\\d+(?:\\.\\d+)?))?\\)$/)\n if (colorMatch) {\n const r = parseInt(colorMatch[1], 10)\n const g = parseInt(colorMatch[2], 10)\n const b = parseInt(colorMatch[3], 10)\n const hsp = Math.sqrt(0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b))\n return hsp > 127.5 ? 'black' : 'white'\n }\n return 'black'\n}\n\nfunction hex2rgb(c: string): string {\n if (c.startsWith('#')) {\n let hexColor = c.replace(/^#/, '')\n // Handle 3-character shorthand (e.g., #111 -> #111111, #abc -> #aabbcc)\n if (/^[0-9A-Fa-f]{3}$/.test(hexColor)) {\n hexColor = hexColor[0] + hexColor[0] + hexColor[1] + hexColor[1] + hexColor[2] + hexColor[2]\n }\n if (!/^[0-9A-Fa-f]{6}$/.test(hexColor)) {\n return 'rgb(255, 255, 255)'\n }\n const r = parseInt(hexColor.slice(0, 2), 16)\n const g = parseInt(hexColor.slice(2, 4), 16)\n const b = parseInt(hexColor.slice(4, 6), 16)\n return `rgb(${r},${g},${b})`\n }\n return 'rgb(255, 255, 255)'\n}\n\nfunction nameToHex(name: string): string | undefined {\n return {\n aliceblue: '#f0f8ff',\n antiquewhite: '#faebd7',\n aqua: '#00ffff',\n aquamarine: '#7fffd4',\n azure: '#f0ffff',\n beige: '#f5f5dc',\n bisque: '#ffe4c4',\n black: '#000000',\n blanchedalmond: '#ffebcd',\n blue: '#0000ff',\n blueviolet: '#8a2be2',\n brown: '#a52a2a',\n burlywood: '#deb887',\n cadetblue: '#5f9ea0',\n chartreuse: '#7fff00',\n chocolate: '#d2691e',\n coral: '#ff7f50',\n cornflowerblue: '#6495ed',\n cornsilk: '#fff8dc',\n crimson: '#dc143c',\n cyan: '#00ffff',\n darkblue: '#00008b',\n darkcyan: '#008b8b',\n darkgoldenrod: '#b8860b',\n darkgray: '#a9a9a9',\n darkgreen: '#006400',\n darkkhaki: '#bdb76b',\n darkmagenta: '#8b008b',\n darkolivegreen: '#556b2f',\n darkorange: '#ff8c00',\n darkorchid: '#9932cc',\n darkred: '#8b0000',\n darksalmon: '#e9967a',\n darkseagreen: '#8fbc8f',\n darkslateblue: '#483d8b',\n darkslategray: '#2f4f4f',\n darkturquoise: '#00ced1',\n darkviolet: '#9400d3',\n deeppink: '#ff1493',\n deepskyblue: '#00bfff',\n dimgray: '#696969',\n dodgerblue: '#1e90ff',\n firebrick: '#b22222',\n floralwhite: '#fffaf0',\n forestgreen: '#228b22',\n fuchsia: '#ff00ff',\n gainsboro: '#dcdcdc',\n ghostwhite: '#f8f8ff',\n gold: '#ffd700',\n goldenrod: '#daa520',\n gray: '#808080',\n green: '#008000',\n greenyellow: '#adff2f',\n honeydew: '#f0fff0',\n hotpink: '#ff69b4',\n 'indianred ': '#cd5c5c',\n indigo: '#4b0082',\n ivory: '#fffff0',\n khaki: '#f0e68c',\n lavender: '#e6e6fa',\n lavenderblush: '#fff0f5',\n lawngreen: '#7cfc00',\n lemonchiffon: '#fffacd',\n lightblue: '#add8e6',\n lightcoral: '#f08080',\n lightcyan: '#e0ffff',\n lightgoldenrodyellow: '#fafad2',\n lightgrey: '#d3d3d3',\n lightgreen: '#90ee90',\n lightpink: '#ffb6c1',\n lightsalmon: '#ffa07a',\n lightseagreen: '#20b2aa',\n lightskyblue: '#87cefa',\n lightslategray: '#778899',\n lightsteelblue: '#b0c4de',\n lightyellow: '#ffffe0',\n lime: '#00ff00',\n limegreen: '#32cd32',\n linen: '#faf0e6',\n magenta: '#ff00ff',\n maroon: '#800000',\n mediumaquamarine: '#66cdaa',\n mediumblue: '#0000cd',\n mediumorchid: '#ba55d3',\n mediumpurple: '#9370d8',\n mediumseagreen: '#3cb371',\n mediumslateblue: '#7b68ee',\n mediumspringgreen: '#00fa9a',\n mediumturquoise: '#48d1cc',\n mediumvioletred: '#c71585',\n midnightblue: '#191970',\n mintcream: '#f5fffa',\n mistyrose: '#ffe4e1',\n moccasin: '#ffe4b5',\n navajowhite: '#ffdead',\n navy: '#000080',\n oldlace: '#fdf5e6',\n olive: '#808000',\n olivedrab: '#6b8e23',\n orange: '#ffa500',\n orangered: '#ff4500',\n orchid: '#da70d6',\n palegoldenrod: '#eee8aa',\n palegreen: '#98fb98',\n paleturquoise: '#afeeee',\n palevioletred: '#d87093',\n papayawhip: '#ffefd5',\n peachpuff: '#ffdab9',\n peru: '#cd853f',\n pink: '#ffc0cb',\n plum: '#dda0dd',\n powderblue: '#b0e0e6',\n purple: '#800080',\n red: '#ff0000',\n rosybrown: '#bc8f8f',\n royalblue: '#4169e1',\n saddlebrown: '#8b4513',\n salmon: '#fa8072',\n sandybrown: '#f4a460',\n seagreen: '#2e8b57',\n seashell: '#fff5ee',\n sienna: '#a0522d',\n silver: '#c0c0c0',\n skyblue: '#87ceeb',\n slateblue: '#6a5acd',\n slategray: '#708090',\n snow: '#fffafa',\n springgreen: '#00ff7f',\n steelblue: '#4682b4',\n tan: '#d2b48c',\n teal: '#008080',\n thistle: '#d8bfd8',\n tomato: '#ff6347',\n turquoise: '#40e0d0',\n violet: '#ee82ee',\n wheat: '#f5deb3',\n white: '#ffffff',\n whitesmoke: '#f5f5f5',\n yellow: '#ffff00',\n yellowgreen: '#9acd32',\n }[name.toLowerCase()]\n}\n"],"mappings":"s5BAAA,IAAAA,KAAA,CAAAC,OAAA,kBAaA,IAAAC,QAAA,CAAAD,OAAA,0BAMA,QAAS,CAAAE,SAASA,CAACC,KAAc,EAC/B,MAAO,OAAO,CAAAA,KAAK,GAAK,QAAQ,EAAIC,MAAM,CAACF,SAAS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equireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.useActivatedSurveys=useActivatedSurveys;var _toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));var _react=require("react");var _surveys=require("@posthog/core/surveys");function _createForOfIteratorHelper(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=_unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var _n=0,F=function F(){};return{s:F,n:function n(){return _n>=r.length?{done:!0}:{done:!1,value:r[_n++]};},e:function e(r){throw r;},f:F};}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}var o,a=!0,u=!1;return{s:function s(){t=t.call(r);},n:function n(){var r=t.next();return a=r.done,r;},e:function e(r){u=!0,o=r;},f:function f(){try{a||null==t["return"]||t["return"]();}finally{if(u)throw o;}}};}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0;}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n;}var SURVEY_SHOWN_EVENT_NAME='survey shown';function useActivatedSurveys(posthog,surveys){var _useState=(0,_react.useState)(new Set()),_useState2=(0,_slicedToArray2["default"])(_useState,2),activatedSurveys=_useState2[0],setActivatedSurveys=_useState2[1];var eventMap=(0,_react.useMemo)(function(){var _a,_b,_c,_d;var newEventMap=new Map();var _iterator=_createForOfIteratorHelper(surveys.filter(_surveys.doesSurveyActivateByEvent)),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var survey=_step.value;var _iterator2=_createForOfIteratorHelper((_c=(_b=(_a=survey.conditions)===null||_a===void 0?void 0:_a.events)===null||_b===void 0?void 0:_b.values)!==null&&_c!==void 0?_c:[]),_step2;try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var event=_step2.value;var configs=(_d=newEventMap.get(event.name))!==null&&_d!==void 0?_d:[];configs.push({surveyId:survey.id,propertyFilters:event.propertyFilters});newEventMap.set(event.name,configs);}}catch(err){_iterator2.e(err);}finally{_iterator2.f();}}}catch(err){_iterator.e(err);}finally{_iterator.f();}return newEventMap;},[surveys]);(0,_react.useEffect)(function(){if(eventMap.size>0){return posthog.on('capture',function(payload){var _a,_b;if(eventMap.has(payload.event)){var configs=(_a=eventMap.get(payload.event))!==null&&_a!==void 0?_a:[];var matchingSurveyIds=configs.filter(function(config){return(0,_surveys.matchPropertyFilters)(config.propertyFilters,payload.properties);}).map(function(config){return config.surveyId;});if(matchingSurveyIds.length>0){setActivatedSurveys(function(current){return new Set([].concat((0,_toConsumableArray2["default"])(current),(0,_toConsumableArray2["default"])(matchingSurveyIds)));});}}else if(payload.event===SURVEY_SHOWN_EVENT_NAME){var surveyId=(_b=payload.properties)===null||_b===void 0?void 0:_b.$survey_id;if(surveyId){setActivatedSurveys(function(current){if(!current.has(surveyId)){return current;}var next=new Set(current);next["delete"](surveyId);return next;});}}});}},[eventMap,posthog]);return activatedSurveys;}
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.useActivatedSurveys=useActivatedSurveys;var _toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));var _react=require("react");var _surveys=require("@posthog/core/surveys");function _createForOfIteratorHelper(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=_unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var _n=0,F=function F(){};return{s:F,n:function n(){return _n>=r.length?{done:!0}:{done:!1,value:r[_n++]};},e:function e(r){throw r;},f:F};}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}var o,a=!0,u=!1;return{s:function s(){t=t.call(r);},n:function n(){var r=t.next();return a=r.done,r;},e:function e(r){u=!0,o=r;},f:function f(){try{a||null==t["return"]||t["return"]();}finally{if(u)throw o;}}};}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0;}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n;}var SURVEY_SHOWN_EVENT_NAME='survey shown';function useActivatedSurveys(posthog,surveys){var _useState=(0,_react.useState)(new Set()),_useState2=(0,_slicedToArray2["default"])(_useState,2),activatedSurveys=_useState2[0],setActivatedSurveys=_useState2[1];var eventMap=(0,_react.useMemo)(function(){var _a,_b,_c,_d;var newEventMap=new Map();var _iterator=_createForOfIteratorHelper(surveys.filter(_surveys.doesSurveyActivateByEvent)),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var survey=_step.value;var _iterator2=_createForOfIteratorHelper((_c=(_b=(_a=survey.conditions)===null||_a===void 0?void 0:_a.events)===null||_b===void 0?void 0:_b.values)!==null&&_c!==void 0?_c:[]),_step2;try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var event=_step2.value;var configs=(_d=newEventMap.get(event.name))!==null&&_d!==void 0?_d:[];configs.push({surveyId:survey.id,propertyFilters:event.propertyFilters});newEventMap.set(event.name,configs);}}catch(err){_iterator2.e(err);}finally{_iterator2.f();}}}catch(err){_iterator.e(err);}finally{_iterator.f();}return newEventMap;},[surveys]);(0,_react.useEffect)(function(){if(eventMap.size>0){return posthog.on('capture',function(payload){var _a,_b;if(eventMap.has(payload.event)){var configs=(_a=eventMap.get(payload.event))!==null&&_a!==void 0?_a:[];var matchingSurveyIds=configs.filter(function(config){return(0,_surveys.matchPropertyFilters)(config.propertyFilters,payload.properties);}).map(function(config){return config.surveyId;});if(matchingSurveyIds.length>0){setActivatedSurveys(function(current){return new Set([].concat((0,_toConsumableArray2["default"])(current),(0,_toConsumableArray2["default"])(matchingSurveyIds)));});}}else if(payload.event===SURVEY_SHOWN_EVENT_NAME){var surveyId=(_b=payload.properties)===null||_b===void 0?void 0:_b.$survey_id;if(surveyId){setActivatedSurveys(function(current){if(!current.has(surveyId)){return current;}var next=new Set(current);next["delete"](surveyId);return next;});}}});}},[eventMap,posthog]);return activatedSurveys;}
2
+ //# sourceMappingURL=useActivatedSurveys.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useActivatedSurveys.js","sourceRoot":"","sources":["../../src/surveys/useActivatedSurveys.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AAGpD,OAAO,EAAE,yBAAyB,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAA;AAGvF,MAAM,uBAAuB,GAAG,cAAc,CAAA;AAO9C,MAAM,UAAU,mBAAmB,CAAC,OAAgB,EAAE,OAAiB;IACrE,MAAM,CAAC,gBAAgB,EAAE,mBAAmB,CAAC,GAAG,QAAQ,CAAsB,IAAI,GAAG,EAAE,CAAC,CAAA;IAExF,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,EAAE;;QAC5B,MAAM,WAAW,GAAG,IAAI,GAAG,EAA+B,CAAA;QAC1D,KAAK,MAAM,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC,yBAAyB,CAAC,EAAE,CAAC;YAC/D,KAAK,M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AC,CAAC,CAAC,CAAA;oBAC/E,CAAC;gBACH,CAAC;qBAAM,IAAI,OAAO,CAAC,KAAK,KAAK,uBAAuB,EAAE,CAAC;oBACrD,MAAM,QAAQ,GAAG,MAAA,OAAO,CAAC,UAAU,0CAAE,UAAgC,CAAA;oBACrE,IAAI,QAAQ,EAAE,CAAC;wBACb,mBAAmB,CAAC,CAAC,OAAO,EAAE,EAAE;4BAC9B,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;gCAC3B,OAAO,OAAO,CAAA;4BAChB,CAAC;4BACD,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,CAAA;4BAC7B,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAA;4BACrB,OAAO,IAAI,CAAA;wBACb,CAAC,CAAC,CAAA;oBACJ,CAAC;gBACH,CAAC;YACH,CAAC,CAAC,CAAA;QACJ,CAAC;IACH,CAAC,EAAE,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC,CAAA;IAEvB,OAAO,gBAAgB,CAAA;AACzB,CAAC"}
1
+ {"version":3,"file":"useActivatedSurveys.js","names":["_react","require","_surveys","_createForOfIteratorHelper","r","e","t","Symbol","iterator","Array","isArray","_unsupportedIterableToArray","length","_n","F","s","n","done","value","f","TypeError","o","a","u","call","next","_arrayLikeToArray","toString","slice","constructor","name","from","test","SURVEY_SHOWN_EVENT_NAME","useActivatedSurveys","posthog","surveys","_useState","useState","Set","_useState2","_slicedToArray2","activatedSurveys","setActivatedSurveys","eventMap","useMemo","newEventMap","Map","_iterator","filter","doesSurveyActivateByEvent","_step","survey","_iterator2","_c","_b","_a","conditions","events","values","_step2","event","configs","_d","get","push","surveyId","id","propertyFilters","set","err","useEffect","size","on","payload","has","matchingSurveyIds","config","matchPropertyFilters","properties","map","current","concat","_toConsumableArray2","$survey_id"],"sources":["../../src/surveys/useActivatedSurveys.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'react'\n\nimport type { PropertyFilters, Survey } from '@posthog/core'\nimport { doesSurveyActivateByEvent, matchPropertyFilters } from '@posthog/core/surveys'\nimport { PostHog } from '../posthog-rn'\n\nconst SURVEY_SHOWN_EVENT_NAME = 'survey shown'\n\ninterface EventSurveyConfig {\n surveyId: string\n propertyFilters?: PropertyFilters\n}\n\nexport function useActivatedSurveys(posthog: PostHog, surveys: Survey[]): ReadonlySet<string> {\n const [activatedSurveys, setActivatedSurveys] = useState<ReadonlySet<string>>(new Set())\n\n const eventMap = useMemo(() => {\n const newEventMap = new Map<string, EventSurveyConfig[]>()\n for (const survey of surveys.filter(doesSurveyActivateByEvent)) {\n for (const event of survey.conditions?.events?.values ?? []) {\n const configs = newEventMap.get(event.name) ?? []\n configs.push({\n surveyId: survey.id,\n propertyFilters: event.propertyFilters,\n })\n newEventMap.set(event.name, configs)\n }\n }\n return newEventMap\n }, [surveys])\n\n useEffect(() => {\n if (eventMap.size > 0) {\n return posthog.on('capture', (payload: { event: string; properties?: Record<string, unknown> }) => {\n if (eventMap.has(payload.event)) {\n const configs = eventMap.get(payload.event) ?? []\n const matchingSurveyIds = configs\n .filter((config) => matchPropertyFilters(config.propertyFilters, payload.properties))\n .map((config) => config.surveyId)\n\n if (matchingSurveyIds.length > 0) {\n setActivatedSurveys((current) => new Set([...current, ...matchingSurveyIds]))\n }\n } else if (payload.event === SURVEY_SHOWN_EVENT_NAME) {\n const surveyId = payload.properties?.$survey_id as string | undefined\n if (surveyId) {\n setActivatedSurveys((current) => {\n if (!current.has(surveyId)) {\n return current\n }\n const next = new Set(current)\n next.delete(surveyId)\n return next\n })\n }\n }\n })\n }\n }, [eventMap, posthog])\n\n return activatedSurveys\n}\n"],"mappings":"yYAAA,IAAAA,MAAA,CAAAC,OAAA,UAGA,IAAAC,QAAA,CAAAD,OAAA,0BAAuF,SAAAE,2BAAAC,CAAA,CAAAC,CAAA,MAAAC,CAAA,qBAAAC,MAAA,EAAAH,CAAA,CAAAG,MAAA,CAAAC,QAAA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CAAC,SAAC4B,MAAM,QAAK,GAAAC,6BAAoB,EAACD,MAAM,CAACT,eAAe,CAAEM,OAAO,CAACK,UAAU,CAAC,GAAC,CACpFC,GAAG,CAAC,SAACH,MAAM,QAAK,CAAAA,MAAM,CAACX,QAAQ,GAAC,CAEnC,GAAIU,iBAAiB,CAAChE,MAAM,CAAG,CAAC,CAAE,CAChC+B,mBAAmB,CAAC,SAACsC,OAAO,QAAK,IAAI,CAAA1C,GAAG,IAAA2C,MAAA,IAAAC,mBAAA,aAAKF,OAAO,KAAAE,mBAAA,aAAKP,iBAAiB,EAAC,CAAC,GAAC,CAC/E,CACF,CAAC,IAAM,IAAIF,OAAO,CAACb,KAAK,GAAK5B,uBAAuB,CAAE,CACpD,GAAM,CAAAiC,QAAQ,CAAG,CAAAX,EAAA,CAAAmB,OAAO,CAACK,UAAU,UAAAxB,EAAA,iBAAAA,EAAA,CAAE6B,UAAgC,CACrE,GAAIlB,QAAQ,CAAE,CACZvB,mBAAmB,CAAC,SAACsC,OAAO,CAAI,CAC9B,GAAI,CAACA,OAAO,CAACN,GAAG,CAACT,QAAQ,CAAC,CAAE,CAC1B,MAAO,CAAAe,OAAO,CAChB,CACA,GAAM,CAAAxD,IAAI,CAAG,GAAI,CAAAc,GAAG,CAAC0C,OAAO,CAAC,CAC7BxD,IAAI,UAAO,CAACyC,QAAQ,CAAC,CACrB,MAAO,CAAAzC,IAAI,CACb,CAAC,CAAC,CACJ,CACF,CACF,CAAC,CAAC,CACJ,CACF,CAAC,CAAE,CAACmB,QAAQ,CAAET,OAAO,CAAC,CAAC,CAEvB,MAAO,CAAAO,gBAAgB,CACzB","ignoreList":[]}
@@ -1 +1,2 @@
1
- "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.updateSeenSurveys=updateSeenSurveys;exports.useSurveyStorage=useSurveyStorage;var _slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));var _toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _core=require("@posthog/core");var _surveys=require("@posthog/core/surveys");var _react=require("react");var _usePostHog=require("../hooks/usePostHog");var MAX_SEEN_SURVEYS=20;function updateSeenSurveys(current,survey){var surveyKey=(0,_surveys.getSurveyIterationKey)(survey);return[surveyKey].concat((0,_toConsumableArray2["default"])(current.filter(function(key){return!(0,_surveys.isSurveyKeyForSurvey)(key,survey.id);}))).slice(0,MAX_SEEN_SURVEYS);}function useSurveyStorage(){var posthogStorage=(0,_usePostHog.usePostHog)();var _useState=(0,_react.useState)(undefined),_useState2=(0,_slicedToArray2["default"])(_useState,2),lastSeenSurveyDate=_useState2[0],setLastSeenSurveyDate=_useState2[1];var _useState3=(0,_react.useState)([]),_useState4=(0,_slicedToArray2["default"])(_useState3,2),seenSurveys=_useState4[0],setSeenSurveys=_useState4[1];(0,_react.useEffect)(function(){posthogStorage.ready().then(function(){var lastSeenSurveyDate=posthogStorage.getPersistedProperty(_core.PostHogPersistedProperty.SurveyLastSeenDate);if(typeof lastSeenSurveyDate==='string'){setLastSeenSurveyDate(new Date(lastSeenSurveyDate));}var serialisedSeenSurveys=posthogStorage.getPersistedProperty(_core.PostHogPersistedProperty.SurveysSeen);if(typeof serialisedSeenSurveys==='string'){var parsedSeenSurveys=JSON.parse(serialisedSeenSurveys);if(Array.isArray(parsedSeenSurveys)){setSeenSurveys(parsedSeenSurveys.filter(function(key){return typeof key==='string';}));}}});},[posthogStorage]);return{seenSurveys:seenSurveys,setSeenSurvey:(0,_react.useCallback)(function(survey){setSeenSurveys(function(current){var newValue=updateSeenSurveys(current,survey);posthogStorage.setPersistedProperty(_core.PostHogPersistedProperty.SurveysSeen,JSON.stringify(newValue));return newValue;});},[posthogStorage]),lastSeenSurveyDate:lastSeenSurveyDate,setLastSeenSurveyDate:(0,_react.useCallback)(function(date){setLastSeenSurveyDate(date);posthogStorage.setPersistedProperty(_core.PostHogPersistedProperty.SurveyLastSeenDate,date.toISOString());},[posthogStorage])};}
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.updateSeenSurveys=updateSeenSurveys;exports.useSurveyStorage=useSurveyStorage;var _slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));var _toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _core=require("@posthog/core");var _surveys=require("@posthog/core/surveys");var _react=require("react");var _usePostHog=require("../hooks/usePostHog");var MAX_SEEN_SURVEYS=20;function updateSeenSurveys(current,survey){var surveyKey=(0,_surveys.getSurveyIterationKey)(survey);return[surveyKey].concat((0,_toConsumableArray2["default"])(current.filter(function(key){return!(0,_surveys.isSurveyKeyForSurvey)(key,survey.id);}))).slice(0,MAX_SEEN_SURVEYS);}function useSurveyStorage(){var posthogStorage=(0,_usePostHog.usePostHog)();var _useState=(0,_react.useState)(undefined),_useState2=(0,_slicedToArray2["default"])(_useState,2),lastSeenSurveyDate=_useState2[0],setLastSeenSurveyDate=_useState2[1];var _useState3=(0,_react.useState)([]),_useState4=(0,_slicedToArray2["default"])(_useState3,2),seenSurveys=_useState4[0],setSeenSurveys=_useState4[1];(0,_react.useEffect)(function(){posthogStorage.ready().then(function(){var lastSeenSurveyDate=posthogStorage.getPersistedProperty(_core.PostHogPersistedProperty.SurveyLastSeenDate);if(typeof lastSeenSurveyDate==='string'){setLastSeenSurveyDate(new Date(lastSeenSurveyDate));}var serialisedSeenSurveys=posthogStorage.getPersistedProperty(_core.PostHogPersistedProperty.SurveysSeen);if(typeof serialisedSeenSurveys==='string'){var parsedSeenSurveys=JSON.parse(serialisedSeenSurveys);if(Array.isArray(parsedSeenSurveys)){setSeenSurveys(parsedSeenSurveys.filter(function(key){return typeof key==='string';}));}}});},[posthogStorage]);return{seenSurveys:seenSurveys,setSeenSurvey:(0,_react.useCallback)(function(survey){setSeenSurveys(function(current){var newValue=updateSeenSurveys(current,survey);posthogStorage.setPersistedProperty(_core.PostHogPersistedProperty.SurveysSeen,JSON.stringify(newValue));return newValue;});},[posthogStorage]),lastSeenSurveyDate:lastSeenSurveyDate,setLastSeenSurveyDate:(0,_react.useCallback)(function(date){setLastSeenSurveyDate(date);posthogStorage.setPersistedProperty(_core.PostHogPersistedProperty.SurveyLastSeenDate,date.toISOString());},[posthogStorage])};}
2
+ //# sourceMappingURL=useSurveyStorage.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useSurveyStorage.js","sourceRoot":"","sources":["../../src/surveys/useSurveyStorage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAA;AACxD,OAAO,EAAE,qBAAqB,EAAE,oBAAoB,EAAuB,MAAM,uBAAuB,CAAA;AACxG,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AACxD,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAA;AAUhD,8DAA8D;AAC9D,MAAM,gBAAgB,GAAG,EAAE,CAAA;AAE3B,yFAAyF;AACzF,6EAA6E;AAC7E,MAAM,UAAU,iBAAiB,CAAC,OAAiB,EAAE,MAA2B;IAC9E,MAAM,SAAS,GAAG,qBAAqB,CAAC,MAAM,CAAC,CAAA;IAC/C,OAAO,CAAC,SAAS,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,oBAAoB,CAAC,GAAG,EAAE,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,gBAAgB,CAAC,CAAA;AAClH,CAAC;AAED,MAAM,UAAU,gBAAgB;IAC9B,MAAM,cAAc,GAAG,UAAU,EAAE,CAAA;IACnC,MAAM,CAAC,kBAAkB,EAAE,qBAAqB,CAAC,GAAG,QAAQ,CAAmB,SAAS,CAAC,CAAA;IACzF,MAAM,CAAC,WAAW,EAAE,cAAc,CAAC,GAAG,QAAQ,CA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ClB,qBAAqB,EAAE,WAAW,CAChC,CAAC,IAAU,EAAE,EAAE;YACb,qBAAqB,CAAC,IAAI,CAAC,CAAA;YAC3B,cAAc,CAAC,oBAAoB,CAAC,wBAAwB,CAAC,kBAAkB,EAAE,IAAI,CAAC,WAAW,EAAE,CAAC,CAAA;QACtG,CAAC,EACD,CAAC,cAAc,CAAC,CACjB;KACF,CAAA;AACH,CAAC"}
1
+ {"version":3,"file":"useSurveyStorage.js","names":["_core","require","_surveys","_react","_usePostHog","MAX_SEEN_SURVEYS","updateSeenSurveys","current","survey","surveyKey","getSurveyIterationKey","concat","_toConsumableArray2","filter","key","isSurveyKeyForSurvey","id","slice","useSurveyStorage","posthogStorage","usePostHog","_useState","useState","undefined","_useState2","_slicedToArray2","lastSeenSurveyDate","setLastSeenSurveyDate","_useState3","_useState4","seenSurveys","setSeenSurveys","useEffect","ready","then","getPersistedProperty","PostHogPersistedProperty","SurveyLastSeenDate","Date","serialisedSeenSurveys","SurveysSeen","parsedSeenSurveys","JSON","parse","Array","isArray","setSeenSurvey","useCallback","newValue","setPersistedProperty","stringify","date","toISOString"],"sources":["../../src/surveys/useSurveyStorage.ts"],"sourcesContent":["import { PostHogPersistedProperty } from '@posthog/core'\nimport { getSurveyIterationKey, isSurveyKeyForSurvey, SurveyWithIteration } from '@posthog/core/surveys'\nimport { useCallback, useEffect, useState } from 'react'\nimport { usePostHog } from '../hooks/usePostHog'\n\ntype SurveyStorage = {\n // Iteration-qualified keys (getSurveyIterationKey) so repeating surveys re-show when a new iteration starts\n seenSurveys: string[]\n setSeenSurvey: (survey: SurveyWithIteration) => void\n lastSeenSurveyDate: Date | undefined\n setLastSeenSurveyDate: (date: Date) => void\n}\n\n// To keep storage bounded, only keep the last 20 seen surveys\nconst MAX_SEEN_SURVEYS = 20\n\n// One slot per survey: stale keys from earlier iterations (or the pre-iteration bare id)\n// can never match again and would otherwise evict other surveys' seen state.\nexport function updateSeenSurveys(current: string[], survey: SurveyWithIteration): string[] {\n const surveyKey = getSurveyIterationKey(survey)\n return [surveyKey, ...current.filter((key) => !isSurveyKeyForSurvey(key, survey.id))].slice(0, MAX_SEEN_SURVEYS)\n}\n\nexport function useSurveyStorage(): SurveyStorage {\n const posthogStorage = usePostHog()\n const [lastSeenSurveyDate, setLastSeenSurveyDate] = useState<Date | undefined>(undefined)\n const [seenSurveys, setSeenSurveys] = useState<string[]>([])\n\n useEffect(() => {\n posthogStorage.ready().then(() => {\n const lastSeenSurveyDate = posthogStorage.getPersistedProperty(PostHogPersistedProperty.SurveyLastSeenDate)\n if (typeof lastSeenSurveyDate === 'string') {\n setLastSeenSurveyDate(new Date(lastSeenSurveyDate))\n }\n\n const serialisedSeenSurveys = posthogStorage.getPersistedProperty(PostHogPersistedProperty.SurveysSeen)\n if (typeof serialisedSeenSurveys === 'string') {\n const parsedSeenSurveys: unknown = JSON.parse(serialisedSeenSurveys)\n if (Array.isArray(parsedSeenSurveys)) {\n setSeenSurveys(parsedSeenSurveys.filter((key): key is string => typeof key === 'string'))\n }\n }\n })\n }, [posthogStorage])\n\n return {\n seenSurveys,\n setSeenSurvey: useCallback(\n (survey: SurveyWithIteration) => {\n setSeenSurveys((current) => {\n const newValue = updateSeenSurveys(current, survey)\n posthogStorage.setPersistedProperty(PostHogPersistedProperty.SurveysSeen, JSON.stringify(newValue))\n return newValue\n })\n },\n [posthogStorage]\n ),\n lastSeenSurveyDate,\n setLastSeenSurveyDate: useCallback(\n (date: Date) => {\n setLastSeenSurveyDate(date)\n posthogStorage.setPersistedProperty(PostHogPersistedProperty.SurveyLastSeenDate, date.toISOString())\n },\n [posthogStorage]\n ),\n }\n}\n"],"mappings":"+aAAA,IAAAA,KAAA,CAAAC,OAAA,kBACA,IAAAC,QAAA,CAAAD,OAAA,0BACA,IAAAE,MAAA,CAAAF,OAAA,UACA,IAAAG,WAAA,CAAAH,OAAA,wBAWA,GAAM,CAAAI,gBAAgB,CAAG,EAAE,CAIrB,QAAU,CAAAC,iBAAiBA,CAACC,OAA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AqB,CAAC,CACpE,GAAIK,KAAK,CAACC,OAAO,CAACJ,iBAAiB,CAAC,CAAE,CACpCV,cAAc,CAACU,iBAAiB,CAAC5B,MAAM,CAAC,SAACC,GAAG,QAAoB,OAAO,CAAAA,GAAG,GAAK,QAAQ,GAAC,CAAC,CAC3F,CACF,CACF,CAAC,CAAC,CACJ,CAAC,CAAE,CAACK,cAAc,CAAC,CAAC,CAEpB,MAAO,CACLW,WAAW,CAAXA,WAAW,CACXgB,aAAa,CAAE,GAAAC,kBAAW,EACxB,SAACvC,MAA2B,CAAI,CAC9BuB,cAAc,CAAC,SAACxB,OAAO,CAAI,CACzB,GAAM,CAAAyC,QAAQ,CAAG1C,iBAAiB,CAACC,OAAO,CAAEC,MAAM,CAAC,CACnDW,cAAc,CAAC8B,oBAAoB,CAACb,8BAAwB,CAACI,WAAW,CAAEE,IAAI,CAACQ,SAAS,CAACF,QAAQ,CAAC,CAAC,CACnG,MAAO,CAAAA,QAAQ,CACjB,CAAC,CAAC,CACJ,CAAC,CACD,CAAC7B,cAAc,CAAC,CACjB,CACDO,kBAAkB,CAAlBA,kBAAkB,CAClBC,qBAAqB,CAAE,GAAAoB,kBAAW,EAChC,SAACI,IAAU,CAAI,CACbxB,qBAAqB,CAACwB,IAAI,CAAC,CAC3BhC,cAAc,CAAC8B,oBAAoB,CAACb,8BAAwB,CAACC,kBAAkB,CAAEc,IAAI,CAACC,WAAW,EAAE,CAAC,CACtG,CAAC,CACD,CAACjC,cAAc,CAAC,C,CAEnB,CACH","ignoreList":[]}
@@ -1 +1,2 @@
1
- "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.POSTHOG_RELEASE_MODES=void 0;exports.addDsymUploadBuildPhase=addDsymUploadBuildPhase;exports.addPostHogAndroidGradlePluginClasspath=addPostHogAndroidGradlePluginClasspath;exports.addPostHogWithBundledScriptsToBundleShellScript=addPostHogWithBundledScriptsToBundleShellScript;exports.applyDotenvFileBuildSetting=applyDotenvFileBuildSetting;exports.applyPostHogAndroidGradlePlugin=applyPostHogAndroidGradlePlugin;exports.buildAndroidDotenvFileGradleValue=buildAndroidDotenvFileGradleValue;exports.buildAndroidSkipOnConflictGradleLine=buildAndroidSkipOnConflictGradleLine;exports.buildDsymUploadShellScript=buildDsymUploadShellScript;exports.buildIosDotenvFileBuildSetting=buildIosDotenvFileBuildSetting;exports.disableUserScriptSandboxing=disableUserScriptSandboxing;exports.modifyExistingXcodeBuildScript=modifyExistingXcodeBuildScript;exports.moveDsymUploadBuildPhaseToEnd=moveDsymUploadBuildPhaseToEnd;exports.resolveDotenvFileProp=resolveDotenvFileProp;exports.resolveNativeSymbolUpload=resolveNativeSymbolUpload;exports.resolveReleaseModeProp=resolveReleaseModeProp;exports.updateDotenvFileGradleProperties=updateDotenvFileGradleProperties;exports.updateHermesReleaseModeGradleProperties=updateHermesReleaseModeGradleProperties;exports.updateMainActivityNewIntentOverride=updateMainActivityNewIntentOverride;var _regenerator=_interopRequireDefault(require("@babel/runtime/regenerator"));var _typeof2=_interopRequireDefault(require("@babel/runtime/helpers/typeof"));var _toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _objectWithoutProperties2=_interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));var _asyncToGenerator2=_interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));var _excluded=["nextMod"],_excluded2=["nextMod"];function _createForOfIteratorHelper(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=_unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var _n=0,F=function F(){};return{s:F,n:function n(){return _n>=r.length?{done:!0}:{done:!1,value:r[_n++]};},e:function e(r){throw r;},f:F};}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}var o,a=!0,u=!1;return{s:function s(){t=t.call(r);},n:function n(){var r=t.next();return a=r.done,r;},e:function e(r){u=!0,o=r;},f:function f(){try{a||null==t["return"]||t["return"]();}finally{if(u)throw o;}}};}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0;}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n;}function ownKeys(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable;})),t.push.apply(t,o);}return t;}function _objectSpread(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?ownKeys(Object(t),!0).forEach(function(r){(0,_defineProperty2["default"])(e,r,t[r]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):ownKeys(Object(t)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r));});}return e;}var fs=require('fs');var path=require('path');var _require=require('@expo/config-plugins'),AndroidConfig=_require.AndroidConfig,withAppBuildGradle=_require.withAppBuildGradle,withBaseMod=_require.withBaseMod,withDangerousMod=_require.withDangerousMod,withGradleProperties=_require.withGradleProperties,withXcodeProject=_require.withXcodeProject;var POSTHOG_ANDROID_GRADLE_PLUGIN_VERSION='1.6.0';var resolvePostHogReactNativePackageJsonPath="[\"node\", \"--print\", \"require('path').join(require('path').dirname(require.resolve('posthog-react-native')), '..', 'tooling', 'posthog.gradle')\"].execute().text.trim()";var POSTHOG_ANDROID_SKIP_ON_CONFLICT_PROPERTY='posthogReactNativeSkipOnConflict';var POSTHOG_HERMES_RELEASE_MODE_GRADLE_PROPERTY='posthog.hermesReleaseMode';var POSTHOG_RELEASE_MODES=exports.POSTHOG_RELEASE_MODES=['symbol-set','event'];function resolveReleaseModeProp(releaseMode,environmentMode){var trimmed=(releaseMode===null||releaseMode===void 0?void 0:releaseMode.trim())||(environmentMode===null||environmentMode===void 0?void 0:environmentMode.trim());if(!trimmed){return undefined;}if(!POSTHOG_RELEASE_MODES.includes(trimmed)){throw new Error("[posthog-react-native] releaseMode must be one of ".concat(POSTHOG_RELEASE_MODES.join(', '),", was '").concat(trimmed,"'"));}return trimmed;}function buildAndroidSkipOnConflictGradleLine(skipOnConflict){if(!skipOnConflict){return null;}return"project.ext.".concat(POSTHOG_ANDROID_SKIP_ON_CONFLICT_PROPERTY," = true");}var withAndroidPlugin=function withAndroidPlugin(config){var skipOnConflict=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;return withAppBuildGradle(config,function(config){if(config.modResults.language!=='groovy'){console.warn('Cannot configure PostHog in the app gradle because the build.gradle is not groovy');}var buildGradle=config.modResults.contents;var applyFrom="apply from: new File(".concat(resolvePostHogReactNativePackageJsonPath,")");var skipOnConflictLine=buildAndroidSkipOnConflictGradleLine(skipOnConflict);var applyBlock=skipOnConflictLine?"".concat(skipOnConflictLine,"\n").concat(applyFrom):applyFrom;var skipOnConflictPattern=new RegExp("^project\\.ext\\.".concat(POSTHOG_ANDROID_SKIP_ON_CONFLICT_PROPERTY,"\\s*=\\s*(true|false)\\n?"),'m');if(buildGradle.includes(applyFrom)){var contents=buildGradle.replace(skipOnConflictPattern,'');if(skipOnConflictLine){contents=contents.replace(applyFrom,"".concat(skipOnConflictLine,"\n").concat(applyFrom));}config.modResults.contents=contents;return config;}var pattern=/^android\s*\{/m;if(buildGradle.match(pattern)){config.modResults.contents=buildGradle.replace(pattern,"".concat(applyBlock,"\n\nandroid {"));}else{console.warn('PostHog: Could not find "android {" block in build.gradle');}return config;});};function matchingBraceIndex(s,openBraceIndex){var depth=0;for(var i=openBraceIndex;i<s.length;i++){if(s[i]==='{'){depth++;}else if(s[i]==='}'){depth--;if(depth===0){return i;}}}return-1;}function addPostHogAndroidGradlePluginClasspath(projectBuildGradle){if(projectBuildGradle.includes('posthog-android-gradle-plugin')){return{contents:projectBuildGradle,classpathPresent:true};}var classpathLine=" classpath(\"com.posthog:posthog-android-gradle-plugin:".concat(POSTHOG_ANDROID_GRADLE_PLUGIN_VERSION,"\")");var buildscriptMatch=/buildscript\s*\{/.exec(projectBuildGradle);var buildscriptOpenBrace=buildscriptMatch?buildscriptMatch.index+buildscriptMatch[0].length-1:-1;var buildscriptEnd=buildscriptOpenBrace===-1?-1:matchingBraceIndex(projectBuildGradle,buildscriptOpenBrace);var buildscriptBody=buildscriptEnd===-1?'':projectBuildGradle.slice(buildscriptOpenBrace,buildscriptEnd);var dependenciesMatch=buildscriptBody?/dependencies\s*\{/.exec(buildscriptBody):null;if(!dependenciesMatch){console.warn('PostHog: Could not find a buildscript dependencies block in the project build.gradle; '+'skipping the com.posthog.android classpath. Native symbols will not be uploaded.');return{contents:projectBuildGradle,classpathPresent:false};}var insertAt=buildscriptOpenBrace+dependenciesMatch.index+dependenciesMatch[0].length;return{contents:"".concat(projectBuildGradle.slice(0,insertAt),"\n").concat(classpathLine).concat(projectBuildGradle.slice(insertAt)),classpathPresent:true};}function applyPostHogAndroidGradlePlugin(appBuildGradle){if(/apply plugin: ["']com\.posthog\.android["']/.test(appBuildGradle)){return appBuildGradle;}var applyLine='apply plugin: "com.posthog.android"';var appPluginPattern=/^([ \t]*apply plugin: ["']com\.android\.application["'].*)$/m;if(appPluginPattern.test(appBuildGradle)){return appBuildGradle.replace(appPluginPattern,"$1\n".concat(applyLine));}var androidBlockPattern=/^android\s*\{/m;if(androidBlockPattern.test(appBuildGradle)){return appBuildGradle.replace(androidBlockPattern,"".concat(applyLine,"\n\nandroid {"));}console.warn('PostHog: Could not find where to apply com.posthog.android in the app build.gradle');return appBuildGradle;}var withFinalizedProjectBuildGradle=function withFinalizedProjectBuildGradle(config,_action){return withBaseMod(config,{platform:'android',mod:'projectBuildGradle',skipEmptyMod:false,action:function action(config){return(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee(){var _config$modRequest,nextMod,modRequest,results;return _regenerator["default"].wrap(function(_context){while(1)switch(_context.prev=_context.next){case 0:_config$modRequest=config.modRequest,nextMod=_config$modRequest.nextMod,modRequest=(0,_objectWithoutProperties2["default"])(_config$modRequest,_excluded);_context.next=1;return nextMod(_objectSpread(_objectSpread({},config),{},{modRequest:modRequest}));case 1:results=_context.sent;return _context.abrupt("return",_action(results));case 2:case"end":return _context.stop();}},_callee);}))();}});};var withAndroidNativeSymbolsPlugin=function withAndroidNativeSymbolsPlugin(config){return withFinalizedProjectBuildGradle(config,function(){var _ref=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee2(config){var result,appBuildGradle,contents;return _regenerator["default"].wrap(function(_context2){while(1)switch(_context2.prev=_context2.next){case 0:if(!(config.modResults.language!=='groovy')){_context2.next=1;break;}console.warn('Cannot configure the PostHog Android Gradle plugin because the project build.gradle is not groovy');return _context2.abrupt("return",config);case 1:result=addPostHogAndroidGradlePluginClasspath(config.modResults.contents);if(!(result.contents!==config.modResults.contents)){_context2.next=3;break;}_context2.next=2;return fs.promises.writeFile(config.modResults.path,result.contents);case 2:config.modResults.contents=result.contents;case 3:if(result.classpathPresent){_context2.next=4;break;}return _context2.abrupt("return",config);case 4:_context2.next=5;return AndroidConfig.Paths.getAppBuildGradleAsync(config.modRequest.projectRoot);case 5:appBuildGradle=_context2.sent;if(!(appBuildGradle.language!=='groovy')){_context2.next=6;break;}console.warn('Cannot configure the PostHog Android Gradle plugin because the app build.gradle is not groovy');return _context2.abrupt("return",config);case 6:contents=applyPostHogAndroidGradlePlugin(appBuildGradle.contents);if(!(contents!==appBuildGradle.contents)){_context2.next=7;break;}_context2.next=7;return fs.promises.writeFile(appBuildGradle.path,contents);case 7:return _context2.abrupt("return",config);case 8:case"end":return _context2.stop();}},_callee2);}));return function(_x){return _ref.apply(this,arguments);};}());};var POSTHOG_NEW_INTENT_MARKER='posthog-new-intent';var POSTHOG_NEW_INTENT_BEGIN="// @generated begin ".concat(POSTHOG_NEW_INTENT_MARKER," - posthog-react-native (DO NOT MODIFY)");var POSTHOG_NEW_INTENT_END="// @generated end ".concat(POSTHOG_NEW_INTENT_MARKER);var NEW_INTENT_DOC=" /**\n * Records the intent that reopened the app so getIntent() stays correct.\n *\n * Works around a React Native defect that drops notification taps and deep links arriving while\n * the React context is still starting. Managed by the posthog-react-native Expo config plugin;\n * remove it with { patchMainActivityNewIntent: false } in app.json.\n * https://posthog.com/docs/workflows/push-notifications/react-native\n */";var NEW_INTENT_KOTLIN_BODY=" override fun onNewIntent(intent: android.content.Intent) {\n setIntent(intent)\n super.onNewIntent(intent)\n }";var NEW_INTENT_JAVA_BODY=" @Override\n public void onNewIntent(android.content.Intent intent) {\n setIntent(intent);\n super.onNewIntent(intent);\n }";function newIntentOverrideBlock(language){var body=language==='java'?NEW_INTENT_JAVA_BODY:NEW_INTENT_KOTLIN_BODY;return"\n ".concat(POSTHOG_NEW_INTENT_BEGIN,"\n").concat(NEW_INTENT_DOC,"\n").concat(body,"\n ").concat(POSTHOG_NEW_INTENT_END,"\n");}function escapeRegExp(value){return value.replace(/[.*+?^${}()|[\]\\]/g,'\\$&');}var POSTHOG_NEW_INTENT_BLOCK_PATTERN=new RegExp("\\r?\\n?[ \\t]*".concat(escapeRegExp(POSTHOG_NEW_INTENT_BEGIN),"[\\s\\S]*?").concat(escapeRegExp(POSTHOG_NEW_INTENT_END),"[ \\t]*\\r?\\n"),'g');function literalEnd(s,start,language){var quote=s[start];var raw=quote==='"'&&s.startsWith('"""',start);var i=start+(raw?3:1);while(i<s.length){var c=s[i];if(raw){if(s.startsWith('"""',i)){while(s[i]==='"'){i++;}return i;}}else if(c==='\n'){return-1;}else if(c===quote){return i+1;}if(c==='\\'&&(!raw||language==='java')){i+=2;continue;}if(language==='kt'&&quote==='"'&&c==='$'&&s[i+1]==='{'){var close=matchingBraceIndexInSource(s,i+1,language);if(close===-1){return-1;}i=close+1;continue;}i++;}return-1;}function matchingBraceIndexInSource(s,openBraceIndex,language){var depth=0;var i=openBraceIndex;while(i<s.length){var c=s[i];if(c==='/'&&s[i+1]==='/'){var end=s.indexOf('\n',i);i=end===-1?s.length:end;continue;}if(c==='/'&&s[i+1]==='*'){var depthOfComment=1;i+=2;while(i<s.length&&depthOfComment>0){if(language==='kt'&&s[i]==='/'&&s[i+1]==='*'){depthOfComment++;i+=2;continue;}if(s[i]==='*'&&s[i+1]==='/'){depthOfComment--;i+=2;continue;}i++;}if(depthOfComment>0){return-1;}continue;}if(c==='"'||c==="'"){var _end=literalEnd(s,i,language);if(_end===-1){return-1;}i=_end;continue;}if(c==='{'){depth++;}else if(c==='}'){depth--;if(depth===0){return i;}}i++;}return-1;}function maskCommentsAndLiterals(source,language){var out=source.split('');var blank=function blank(from,to){for(var j=from;j<to&&j<out.length;j++){if(out[j]!=='\n'){out[j]=' ';}}};var i=0;while(i<source.length){var c=source[i];if(c==='/'&&source[i+1]==='/'){var end=source.indexOf('\n',i);var stop=end===-1?source.length:end;blank(i,stop);i=stop;continue;}if(c==='/'&&source[i+1]==='*'){var depth=1;var j=i+2;while(j<source.length&&depth>0){if(language==='kt'&&source[j]==='/'&&source[j+1]==='*'){depth++;j+=2;continue;}if(source[j]==='*'&&source[j+1]==='/'){depth--;j+=2;continue;}j++;}blank(i,j);i=j;continue;}if(c==='"'||c==="'"){var _end2=literalEnd(source,i,language);if(_end2===-1){blank(i,source.length);return out.join('');}blank(i,_end2);i=_end2;continue;}i++;}return out.join('');}function mainActivityBody(contents,language){var code=maskCommentsAndLiterals(contents,language);var declaration=/\bclass\s+MainActivity\b/.exec(code);if(!declaration){return undefined;}var searchFrom=declaration.index+declaration[0].length;var open=code.indexOf('{',searchFrom);if(open===-1||!/^[^;{}]*$/.test(code.slice(searchFrom,open))){return undefined;}var depth=0;var close=-1;for(var i=open;i<code.length;i++){if(code[i]==='{'){depth++;}else if(code[i]==='}'){depth--;if(depth===0){close=i;break;}}}return close===-1?undefined:{open:open,close:close};}function updateMainActivityNewIntentOverride(contents,language,enabled){var withoutManagedBlock=contents.replace(POSTHOG_NEW_INTENT_BLOCK_PATTERN,'');if(!enabled){return withoutManagedBlock;}var body=mainActivityBody(withoutManagedBlock,language);if(!body){console.warn('[posthog-react-native] Could not find the MainActivity class body; skipping the onNewIntent '+'override. Notification taps delivered while the React context is starting will be lost.');return withoutManagedBlock;}var codeOnly=maskCommentsAndLiterals(withoutManagedBlock,language);if(/\b(fun|void)\s+onNewIntent\s*\(/.test(codeOnly.slice(body.open,body.close))){console.warn('[posthog-react-native] MainActivity already overrides onNewIntent; leaving it alone. '+'Add `setIntent(intent)` as its first statement so a notification tap that arrives before '+'the React context is ready is not lost, or set `{ patchMainActivityNewIntent: false }` '+'on the plugin to silence this.');return withoutManagedBlock;}return withoutManagedBlock.slice(0,body.open+1)+newIntentOverrideBlock(language)+withoutManagedBlock.slice(body.open+1);}var MAIN_ACTIVITY_SOURCE_ROOTS=['android/app/src/main/java','android/app/src/main/kotlin'];function findMainActivityPath(projectRoot){var _walk=function walk(dir){if(!fs.existsSync(dir)){return undefined;}var _iterator=_createForOfIteratorHelper(fs.readdirSync(dir,{withFileTypes:true})),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var entry=_step.value;var candidate=path.join(dir,entry.name);if(!entry.isDirectory()){if(/^MainActivity\.(kt|java)$/.test(entry.name)){return candidate;}continue;}var hit=_walk(candidate);if(hit){return hit;}}}catch(err){_iterator.e(err);}finally{_iterator.f();}return undefined;};for(var _i=0,_MAIN_ACTIVITY_SOURCE=MAIN_ACTIVITY_SOURCE_ROOTS;_i<_MAIN_ACTIVITY_SOURCE.length;_i++){var sourceRoot=_MAIN_ACTIVITY_SOURCE[_i];var hit=_walk(path.join(projectRoot,sourceRoot));if(hit){return hit;}}return undefined;}var withMainActivityNewIntent=function withMainActivityNewIntent(config,enabled){return withDangerousMod(config,['android',(function(){var _ref2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee3(config){var mainActivityPath,contents,updated;return _regenerator["default"].wrap(function(_context3){while(1)switch(_context3.prev=_context3.next){case 0:mainActivityPath=findMainActivityPath(config.modRequest.projectRoot);if(mainActivityPath){_context3.next=1;break;}console.warn('[posthog-react-native] Could not find MainActivity under android/app/src/main/{java,kotlin}; '+'skipping the onNewIntent override. Notification taps delivered while the React context is '+'starting will be lost.');return _context3.abrupt("return",config);case 1:_context3.next=2;return fs.promises.readFile(mainActivityPath,'utf8');case 2:contents=_context3.sent;updated=updateMainActivityNewIntentOverride(contents,mainActivityPath.endsWith('.java')?'java':'kt',enabled);if(!(updated!==contents)){_context3.next=3;break;}_context3.next=3;return fs.promises.writeFile(mainActivityPath,updated);case 3:if(!contents.includes(POSTHOG_NEW_INTENT_BEGIN)&&updated.includes(POSTHOG_NEW_INTENT_BEGIN)){console.warn("[posthog-react-native] Added an onNewIntent override to ".concat(path.relative(config.modRequest.projectRoot,mainActivityPath)," so a notification tap that arrives before the React context is ready is not lost. ")+'Set `{ patchMainActivityNewIntent: false }` on the plugin in app.json to opt out.');}return _context3.abrupt("return",config);case 4:case"end":return _context3.stop();}},_callee3);}));return function(_x2){return _ref2.apply(this,arguments);};}())]);};function modifyExistingXcodeBuildScript(script){var skipOnConflict=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var releaseMode=arguments.length>2?arguments[2]:undefined;if(!(script===null||script===void 0?void 0:script.shellScript)){console.warn("[posthog-react-native] Could not find the 'Bundle React Native code and images' build phase; "+'skipping sourcemap upload setup.');return;}if(!script.shellScript.match(/(packager|scripts)\/react-native-xcode\.sh\b/)){return;}if(script.shellScript.includes('posthog-xcode.sh')){var _code=migrateLegacyPostHogWrapperInvocation(JSON.parse(script.shellScript));script.shellScript=JSON.stringify(updatePostHogBundlePhaseExports(_code,skipOnConflict,releaseMode));return;}if(script.shellScript.includes('posthog-react-native')){return;}var code=JSON.parse(script.shellScript);script.shellScript=JSON.stringify(addPostHogWithBundledScriptsToBundleShellScript(code,skipOnConflict,releaseMode));}var POSTHOG_REACT_NATIVE_XCODE_PATH="`\"$NODE_BINARY\" --print \"require('path').join(require('path').dirname(require.resolve('posthog-react-native')), '..', 'tooling', 'posthog-xcode.sh')\"`";var POSTHOG_SKIP_ON_CONFLICT_EXPORT='export POSTHOG_SKIP_ON_CONFLICT=1';var POSTHOG_RELEASE_MODE_EXPORT_PREFIX='export POSTHOG_RELEASE_MODE=';function buildBundlePhaseExports(skipOnConflict,releaseMode){var exports=[];if(skipOnConflict){exports.push(POSTHOG_SKIP_ON_CONFLICT_EXPORT);}if(releaseMode){exports.push("".concat(POSTHOG_RELEASE_MODE_EXPORT_PREFIX).concat(releaseMode));}return exports;}var REACT_NATIVE_XCODE_LINE=/^([ \t]*)(?![A-Za-z_][A-Za-z0-9_]*=)([^\n]*(?:packager|scripts)\/react-native-xcode\.sh\b[^\n]*)$/m;function migrateLegacyPostHogWrapperInvocation(script){return script.replace("/bin/sh ".concat(POSTHOG_REACT_NATIVE_XCODE_PATH),POSTHOG_REACT_NATIVE_XCODE_PATH);}function updatePostHogBundlePhaseExports(script,skipOnConflict,releaseMode){var _a,_b;var skipArg='--posthog-skip-on-conflict --';var lines=script.replace(new RegExp("\\s*".concat(skipArg,"\\s*"),'g'),' ').split('\n').filter(function(line){return line.trim()!==POSTHOG_SKIP_ON_CONFLICT_EXPORT;}).filter(function(line){return!line.trim().startsWith(POSTHOG_RELEASE_MODE_EXPORT_PREFIX);});var exports=buildBundlePhaseExports(skipOnConflict,releaseMode);if(exports.length>0){var commandIndex=lines.findIndex(function(line){return line.includes(POSTHOG_REACT_NATIVE_XCODE_PATH);});if(commandIndex!==-1){var indent=(_b=(_a=lines[commandIndex].match(/^[ \t]*/))===null||_a===void 0?void 0:_a[0])!==null&&_b!==void 0?_b:'';lines.splice.apply(lines,[commandIndex,0].concat((0,_toConsumableArray2["default"])(exports.map(function(line){return"".concat(indent).concat(line);}))));}}return lines.join('\n');}function addPostHogWithBundledScriptsToBundleShellScript(script){var skipOnConflict=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var releaseMode=arguments.length>2?arguments[2]:undefined;return script.replace(REACT_NATIVE_XCODE_LINE,function(_match,indent,rnCommand){var exports=buildBundlePhaseExports(skipOnConflict,releaseMode).map(function(line){return"".concat(indent).concat(line,"\n");}).join('');return"".concat(exports).concat(indent).concat(POSTHOG_REACT_NATIVE_XCODE_PATH," ").concat(rnCommand);});}var POSTHOG_DSYM_BUILD_PHASE_NAME='Upload PostHog Debug Symbols';var POSTHOG_DSYM_INPUT_PATH='"$(DWARF_DSYM_FOLDER_PATH)/$(DWARF_DSYM_FILE_NAME)/Contents/Resources/DWARF/$(EXECUTABLE_NAME)"';function buildDsymUploadShellScript(){var includeSource=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;var skipOnConflict=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;return composeDsymUploadShellScript(includeSource,skipOnConflict);}function composeDsymUploadShellScript(includeSource,skipOnConflict){var lines=['# Upload iOS dSYMs to PostHog so native crashes can be symbolicated.','# upload-symbols.sh ships inside the posthog-ios dependency.'];if(includeSource){lines.push('# Also upload native source files for source-code context around crashes.','export POSTHOG_INCLUDE_SOURCE=1');}if(skipOnConflict){lines.push('# Skip dSYMs that already exist in PostHog with different content instead of failing the build.','export POSTHOG_SKIP_ON_CONFLICT=1');}lines.push('PODS_SCRIPT="${PODS_ROOT}/PostHog/build-tools/upload-symbols.sh"','SPM_SCRIPT="${BUILD_DIR%/Build/*}/SourcePackages/checkouts/posthog-ios/build-tools/upload-symbols.sh"','if [ -f "$PODS_SCRIPT" ]; then',' /bin/sh "$PODS_SCRIPT"','elif [ -f "$SPM_SCRIPT" ]; then',' /bin/sh "$SPM_SCRIPT"','else',' echo "warning: PostHog upload-symbols.sh not found in Pods or SwiftPM checkouts; skipping dSYM upload."','fi');return lines.join('\n');}function legacyDsymReleaseModeLines(releaseMode){return[releaseMode?"POSTHOG_RESOLVED_RELEASE_MODE=\"".concat(releaseMode,"\""):'POSTHOG_RESOLVED_RELEASE_MODE="${POSTHOG_RELEASE_MODE:-}"','case "$POSTHOG_RESOLVED_RELEASE_MODE" in',' ""|symbol-set) ;;',' event)',' # Upload dSYMs without binding them to a release, so each crash resolves its own from the',' # app version and namespace the SDK sends. posthog-ios versions whose upload-symbols.sh',' # does not read this variable ignore it and keep binding the dSYMs.',' export POSTHOG_NO_RELEASE_BIND=1',' ;;',' *)'," echo \"error: posthog release mode must be 'symbol-set' or 'event', was '$POSTHOG_RESOLVED_RELEASE_MODE'\"",' exit 1',' ;;','esac'];}function buildLegacyReleaseModeDsymUploadShellScript(includeSource,skipOnConflict,releaseMode){var lines=composeDsymUploadShellScript(includeSource,skipOnConflict).split('\n');var uploadIndex=lines.findIndex(function(line){return line.startsWith('PODS_SCRIPT=');});lines.splice.apply(lines,[uploadIndex,0].concat((0,_toConsumableArray2["default"])(legacyDsymReleaseModeLines(releaseMode))));return lines.join('\n');}function encodePbxShellScript(script){return'"'+script.replace(/"/g,'\\"')+'"';}function decodePbxShellScript(stored){if(!stored.startsWith('"')||!stored.endsWith('"')){return stored;}return stored.slice(1,-1).replace(/\\(.)/g,function(_match,ch){return ch==='n'?'\n':ch==='t'?'\t':ch;});}function isPluginGeneratedDsymUploadBuildPhase(phase){if(typeof(phase===null||phase===void 0?void 0:phase.shellScript)!=='string'){return false;}var stored=decodePbxShellScript(phase.shellScript);return[false,true].some(function(source){return[false,true].some(function(skip){return stored===buildDsymUploadShellScript(source,skip)||[undefined].concat(POSTHOG_RELEASE_MODES).some(function(mode){return stored===buildLegacyReleaseModeDsymUploadShellScript(source,skip,mode);});});});}function moveDsymUploadBuildPhaseToEnd(xcodeProject){var _a,_b;var existing=xcodeProject.pbxItemByComment(POSTHOG_DSYM_BUILD_PHASE_NAME,'PBXShellScriptBuildPhase');if(!isPluginGeneratedDsymUploadBuildPhase(existing)){return;}var buildPhases=(_b=(_a=xcodeProject.getFirstTarget)===null||_a===void 0?void 0:_a.call(xcodeProject).firstTarget)===null||_b===void 0?void 0:_b.buildPhases;if(Array.isArray(buildPhases)){var phaseIndex=buildPhases.findIndex(function(phase){return phase.comment===POSTHOG_DSYM_BUILD_PHASE_NAME;});if(phaseIndex!==-1&&phaseIndex!==buildPhases.length-1){buildPhases.push.apply(buildPhases,(0,_toConsumableArray2["default"])(buildPhases.splice(phaseIndex,1)));}}}function addDsymUploadBuildPhase(xcodeProject){var includeSource=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var skipOnConflict=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;var existing=xcodeProject.pbxItemByComment(POSTHOG_DSYM_BUILD_PHASE_NAME,'PBXShellScriptBuildPhase');if(existing){if(isPluginGeneratedDsymUploadBuildPhase(existing)){existing.shellScript=encodePbxShellScript(buildDsymUploadShellScript(includeSource,skipOnConflict));existing.inputPaths=Array.from(new Set([].concat((0,_toConsumableArray2["default"])(Array.isArray(existing.inputPaths)?existing.inputPaths:[]),[POSTHOG_DSYM_INPUT_PATH])));}}else{xcodeProject.addBuildPhase([],'PBXShellScriptBuildPhase',POSTHOG_DSYM_BUILD_PHASE_NAME,null,{inputPaths:[POSTHOG_DSYM_INPUT_PATH],shellPath:'/bin/sh',shellScript:buildDsymUploadShellScript(includeSource,skipOnConflict)});}moveDsymUploadBuildPhaseToEnd(xcodeProject);}function disableUserScriptSandboxing(xcodeProject){var configurations=xcodeProject.pbxXCBuildConfigurationSection();for(var key in configurations){var configuration=configurations[key];if(configuration&&configuration.buildSettings){configuration.buildSettings.ENABLE_USER_SCRIPT_SANDBOXING='"NO"';}}}var POSTHOG_DOTENV_BUILD_SETTING='POSTHOG_CLI_DOTENV_FILE';var POSTHOG_DOTENV_GRADLE_PROPERTY='posthog.dotenvFile';function normalizeDotenvFileProp(dotenvFile){return dotenvFile.replace(/^\.\//,'');}function resolveDotenvFileProp(dotenvFile){var trimmed=dotenvFile===null||dotenvFile===void 0?void 0:dotenvFile.trim();return trimmed?trimmed:undefined;}function isAbsoluteDotenvPath(dotenvFile){return dotenvFile.startsWith('/')||/^[A-Za-z]:[\\/]/.test(dotenvFile);}function buildIosDotenvFileBuildSetting(dotenvFile){var value=isAbsoluteDotenvPath(dotenvFile)?dotenvFile:"$(SRCROOT)/../".concat(normalizeDotenvFileProp(dotenvFile));return'"'+value.replace(/(["\\])/g,'\\$1')+'"';}function applyDotenvFileBuildSetting(xcodeProject,dotenvFile){var configurations=xcodeProject.pbxXCBuildConfigurationSection();for(var key in configurations){var configuration=configurations[key];if(configuration&&configuration.buildSettings){if(dotenvFile){configuration.buildSettings[POSTHOG_DOTENV_BUILD_SETTING]=buildIosDotenvFileBuildSetting(dotenvFile);}else{delete configuration.buildSettings[POSTHOG_DOTENV_BUILD_SETTING];}}}}function buildAndroidDotenvFileGradleValue(dotenvFile){return isAbsoluteDotenvPath(dotenvFile)?dotenvFile:"../".concat(normalizeDotenvFileProp(dotenvFile));}function updateDotenvFileGradleProperties(properties,dotenvFile){var rest=properties.filter(function(item){return!(item.type==='property'&&item.key===POSTHOG_DOTENV_GRADLE_PROPERTY);});if(!dotenvFile){return rest;}rest.push({type:'property',key:POSTHOG_DOTENV_GRADLE_PROPERTY,value:buildAndroidDotenvFileGradleValue(dotenvFile)});return rest;}function updateHermesReleaseModeGradleProperties(properties,releaseMode){var rest=properties.filter(function(item){return!(item.type==='property'&&item.key===POSTHOG_HERMES_RELEASE_MODE_GRADLE_PROPERTY);});if(!releaseMode){return rest;}rest.push({type:'property',key:POSTHOG_HERMES_RELEASE_MODE_GRADLE_PROPERTY,value:releaseMode});return rest;}var withPostHogGradleProperties=function withPostHogGradleProperties(config,dotenvFile,releaseMode){return withGradleProperties(config,function(config){config.modResults=updateDotenvFileGradleProperties(config.modResults,dotenvFile);config.modResults=updateHermesReleaseModeGradleProperties(config.modResults,releaseMode);return config;});};function resolveNativeSymbolUpload(prop){if(prop===true){return{enabled:true,includeSource:false};}if(prop&&(0,_typeof2["default"])(prop)==='object'){return{enabled:true,includeSource:prop.includeSource===true};}return{enabled:false,includeSource:false};}var withFinalizedXcodeProject=function withFinalizedXcodeProject(config,_action2){return withBaseMod(config,{platform:'ios',mod:'xcodeproj',action:function action(config){return(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee4(){var _config$modRequest2,nextMod,modRequest,results;return _regenerator["default"].wrap(function(_context4){while(1)switch(_context4.prev=_context4.next){case 0:_config$modRequest2=config.modRequest,nextMod=_config$modRequest2.nextMod,modRequest=(0,_objectWithoutProperties2["default"])(_config$modRequest2,_excluded2);_context4.next=1;return nextMod(_objectSpread(_objectSpread({},config),{},{modRequest:modRequest}));case 1:results=_context4.sent;return _context4.abrupt("return",_action2(results));case 2:case"end":return _context4.stop();}},_callee4);}))();}});};var withIosPlugin=function withIosPlugin(config){var props=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var nativeSymbols=resolveNativeSymbolUpload(props.uploadNativeSymbols);config=withXcodeProject(config,function(config){var xcodeProject=config.modResults;var bundleReactNativePhase=xcodeProject.pbxItemByComment('Bundle React Native code and images','PBXShellScriptBuildPhase');modifyExistingXcodeBuildScript(bundleReactNativePhase,props.skipOnConflict===true,props.releaseMode);if(nativeSymbols.enabled){addDsymUploadBuildPhase(xcodeProject,nativeSymbols.includeSource,props.skipOnConflict===true);}applyDotenvFileBuildSetting(xcodeProject,props.dotenvFile);if(props.disableSandboxing!==false){disableUserScriptSandboxing(xcodeProject);console.warn('[posthog-react-native] Setting ENABLE_USER_SCRIPT_SANDBOXING=NO on all Xcode '+'build configurations so sourcemap uploads can resolve git metadata. '+'If your org requires sandboxing to stay enabled, set `{ disableSandboxing: false }` '+'on the plugin in app.json — note that stock Expo projects may fail to build under '+'sandboxing until every script build phase declares its input/output files.');}return config;});if(nativeSymbols.enabled){config=withFinalizedXcodeProject(config,function(config){moveDsymUploadBuildPhaseToEnd(config.modResults);return config;});}return config;};var withPostHogPlugin=function withPostHogPlugin(config){var rawProps=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var props=_objectSpread(_objectSpread({},rawProps),{},{dotenvFile:resolveDotenvFileProp(rawProps.dotenvFile),releaseMode:resolveReleaseModeProp(rawProps.releaseMode,process.env.POSTHOG_RELEASE_MODE)});if(resolveNativeSymbolUpload(props.uploadNativeSymbols).enabled){config=withAndroidNativeSymbolsPlugin(config);}config=withAndroidPlugin(config,props.skipOnConflict===true);config=withPostHogGradleProperties(config,props.dotenvFile,props.releaseMode);config=withMainActivityNewIntent(config,props.patchMainActivityNewIntent!==false);return withIosPlugin(config,props);};var postHogPlugin=function postHogPlugin(config){var props=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};return withPostHogPlugin(config,props);};module.exports=postHogPlugin;module.exports.modifyExistingXcodeBuildScript=modifyExistingXcodeBuildScript;module.exports.addPostHogWithBundledScriptsToBundleShellScript=addPostHogWithBundledScriptsToBundleShellScript;module.exports.disableUserScriptSandboxing=disableUserScriptSandboxing;module.exports.buildDsymUploadShellScript=buildDsymUploadShellScript;module.exports.addDsymUploadBuildPhase=addDsymUploadBuildPhase;module.exports.moveDsymUploadBuildPhaseToEnd=moveDsymUploadBuildPhaseToEnd;module.exports.resolveNativeSymbolUpload=resolveNativeSymbolUpload;module.exports.buildAndroidSkipOnConflictGradleLine=buildAndroidSkipOnConflictGradleLine;module.exports.addPostHogAndroidGradlePluginClasspath=addPostHogAndroidGradlePluginClasspath;module.exports.applyPostHogAndroidGradlePlugin=applyPostHogAndroidGradlePlugin;module.exports.buildIosDotenvFileBuildSetting=buildIosDotenvFileBuildSetting;module.exports.applyDotenvFileBuildSetting=applyDotenvFileBuildSetting;module.exports.resolveDotenvFileProp=resolveDotenvFileProp;module.exports.buildAndroidDotenvFileGradleValue=buildAndroidDotenvFileGradleValue;module.exports.updateDotenvFileGradleProperties=updateDotenvFileGradleProperties;module.exports.POSTHOG_RELEASE_MODES=POSTHOG_RELEASE_MODES;module.exports.resolveReleaseModeProp=resolveReleaseModeProp;module.exports.updateHermesReleaseModeGradleProperties=updateHermesReleaseModeGradleProperties;module.exports.updateMainActivityNewIntentOverride=updateMainActivityNewIntentOverride;
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.POSTHOG_RELEASE_MODES=void 0;exports.addDsymUploadBuildPhase=addDsymUploadBuildPhase;exports.addPostHogAndroidGradlePluginClasspath=addPostHogAndroidGradlePluginClasspath;exports.addPostHogWithBundledScriptsToBundleShellScript=addPostHogWithBundledScriptsToBundleShellScript;exports.applyDotenvFileBuildSetting=applyDotenvFileBuildSetting;exports.applyPostHogAndroidGradlePlugin=applyPostHogAndroidGradlePlugin;exports.buildAndroidDotenvFileGradleValue=buildAndroidDotenvFileGradleValue;exports.buildAndroidSkipOnConflictGradleLine=buildAndroidSkipOnConflictGradleLine;exports.buildDsymUploadShellScript=buildDsymUploadShellScript;exports.buildIosDotenvFileBuildSetting=buildIosDotenvFileBuildSetting;exports.disableUserScriptSandboxing=disableUserScriptSandboxing;exports.modifyExistingXcodeBuildScript=modifyExistingXcodeBuildScript;exports.moveDsymUploadBuildPhaseToEnd=moveDsymUploadBuildPhaseToEnd;exports.resolveDotenvFileProp=resolveDotenvFileProp;exports.resolveNativeSymbolUpload=resolveNativeSymbolUpload;exports.resolveReleaseModeProp=resolveReleaseModeProp;exports.updateDotenvFileGradleProperties=updateDotenvFileGradleProperties;exports.updateHermesReleaseModeGradleProperties=updateHermesReleaseModeGradleProperties;exports.updateMainActivityNewIntentOverride=updateMainActivityNewIntentOverride;var _regenerator=_interopRequireDefault(require("@babel/runtime/regenerator"));var _typeof2=_interopRequireDefault(require("@babel/runtime/helpers/typeof"));var _toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _objectWithoutProperties2=_interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));var _asyncToGenerator2=_interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));var _excluded=["nextMod"],_excluded2=["nextMod"];function _createForOfIteratorHelper(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=_unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var _n=0,F=function F(){};return{s:F,n:function n(){return _n>=r.length?{done:!0}:{done:!1,value:r[_n++]};},e:function e(r){throw r;},f:F};}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}var o,a=!0,u=!1;return{s:function s(){t=t.call(r);},n:function n(){var r=t.next();return a=r.done,r;},e:function e(r){u=!0,o=r;},f:function f(){try{a||null==t["return"]||t["return"]();}finally{if(u)throw o;}}};}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0;}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n;}function ownKeys(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable;})),t.push.apply(t,o);}return t;}function _objectSpread(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?ownKeys(Object(t),!0).forEach(function(r){(0,_defineProperty2["default"])(e,r,t[r]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):ownKeys(Object(t)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r));});}return e;}var fs=require('fs');var path=require('path');var _require=require('@expo/config-plugins'),AndroidConfig=_require.AndroidConfig,withAppBuildGradle=_require.withAppBuildGradle,withBaseMod=_require.withBaseMod,withDangerousMod=_require.withDangerousMod,withGradleProperties=_require.withGradleProperties,withXcodeProject=_require.withXcodeProject;var POSTHOG_ANDROID_GRADLE_PLUGIN_VERSION='1.6.0';var resolvePostHogReactNativePackageJsonPath="[\"node\", \"--print\", \"require('path').join(require('path').dirname(require.resolve('posthog-react-native')), '..', 'tooling', 'posthog.gradle')\"].execute().text.trim()";var POSTHOG_ANDROID_SKIP_ON_CONFLICT_PROPERTY='posthogReactNativeSkipOnConflict';var POSTHOG_HERMES_RELEASE_MODE_GRADLE_PROPERTY='posthog.hermesReleaseMode';var POSTHOG_RELEASE_MODES=exports.POSTHOG_RELEASE_MODES=['symbol-set','event'];function resolveReleaseModeProp(releaseMode,environmentMode){var trimmed=(releaseMode===null||releaseMode===void 0?void 0:releaseMode.trim())||(environmentMode===null||environmentMode===void 0?void 0:environmentMode.trim());if(!trimmed){return undefined;}if(!POSTHOG_RELEASE_MODES.includes(trimmed)){throw new Error("[posthog-react-native] releaseMode must be one of ".concat(POSTHOG_RELEASE_MODES.join(', '),", was '").concat(trimmed,"'"));}return trimmed;}function buildAndroidSkipOnConflictGradleLine(skipOnConflict){if(!skipOnConflict){return null;}return"project.ext.".concat(POSTHOG_ANDROID_SKIP_ON_CONFLICT_PROPERTY," = true");}var withAndroidPlugin=function withAndroidPlugin(config){var skipOnConflict=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;return withAppBuildGradle(config,function(config){if(config.modResults.language!=='groovy'){console.warn('Cannot configure PostHog in the app gradle because the build.gradle is not groovy');}var buildGradle=config.modResults.contents;var applyFrom="apply from: new File(".concat(resolvePostHogReactNativePackageJsonPath,")");var skipOnConflictLine=buildAndroidSkipOnConflictGradleLine(skipOnConflict);var applyBlock=skipOnConflictLine?"".concat(skipOnConflictLine,"\n").concat(applyFrom):applyFrom;var skipOnConflictPattern=new RegExp("^project\\.ext\\.".concat(POSTHOG_ANDROID_SKIP_ON_CONFLICT_PROPERTY,"\\s*=\\s*(true|false)\\n?"),'m');if(buildGradle.includes(applyFrom)){var contents=buildGradle.replace(skipOnConflictPattern,'');if(skipOnConflictLine){contents=contents.replace(applyFrom,"".concat(skipOnConflictLine,"\n").concat(applyFrom));}config.modResults.contents=contents;return config;}var pattern=/^android\s*\{/m;if(buildGradle.match(pattern)){config.modResults.contents=buildGradle.replace(pattern,"".concat(applyBlock,"\n\nandroid {"));}else{console.warn('PostHog: Could not find "android {" block in build.gradle');}return config;});};function matchingBraceIndex(s,openBraceIndex){var depth=0;for(var i=openBraceIndex;i<s.length;i++){if(s[i]==='{'){depth++;}else if(s[i]==='}'){depth--;if(depth===0){return i;}}}return-1;}function addPostHogAndroidGradlePluginClasspath(projectBuildGradle){if(projectBuildGradle.includes('posthog-android-gradle-plugin')){return{contents:projectBuildGradle,classpathPresent:true};}var classpathLine=" classpath(\"com.posthog:posthog-android-gradle-plugin:".concat(POSTHOG_ANDROID_GRADLE_PLUGIN_VERSION,"\")");var buildscriptMatch=/buildscript\s*\{/.exec(projectBuildGradle);var buildscriptOpenBrace=buildscriptMatch?buildscriptMatch.index+buildscriptMatch[0].length-1:-1;var buildscriptEnd=buildscriptOpenBrace===-1?-1:matchingBraceIndex(projectBuildGradle,buildscriptOpenBrace);var buildscriptBody=buildscriptEnd===-1?'':projectBuildGradle.slice(buildscriptOpenBrace,buildscriptEnd);var dependenciesMatch=buildscriptBody?/dependencies\s*\{/.exec(buildscriptBody):null;if(!dependenciesMatch){console.warn('PostHog: Could not find a buildscript dependencies block in the project build.gradle; '+'skipping the com.posthog.android classpath. Native symbols will not be uploaded.');return{contents:projectBuildGradle,classpathPresent:false};}var insertAt=buildscriptOpenBrace+dependenciesMatch.index+dependenciesMatch[0].length;return{contents:"".concat(projectBuildGradle.slice(0,insertAt),"\n").concat(classpathLine).concat(projectBuildGradle.slice(insertAt)),classpathPresent:true};}function applyPostHogAndroidGradlePlugin(appBuildGradle){if(/apply plugin: ["']com\.posthog\.android["']/.test(appBuildGradle)){return appBuildGradle;}var applyLine='apply plugin: "com.posthog.android"';var appPluginPattern=/^([ \t]*apply plugin: ["']com\.android\.application["'].*)$/m;if(appPluginPattern.test(appBuildGradle)){return appBuildGradle.replace(appPluginPattern,"$1\n".concat(applyLine));}var androidBlockPattern=/^android\s*\{/m;if(androidBlockPattern.test(appBuildGradle)){return appBuildGradle.replace(androidBlockPattern,"".concat(applyLine,"\n\nandroid {"));}console.warn('PostHog: Could not find where to apply com.posthog.android in the app build.gradle');return appBuildGradle;}var withFinalizedProjectBuildGradle=function withFinalizedProjectBuildGradle(config,_action){return withBaseMod(config,{platform:'android',mod:'projectBuildGradle',skipEmptyMod:false,action:function action(config){return(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee(){var _config$modRequest,nextMod,modRequest,results;return _regenerator["default"].wrap(function(_context){while(1)switch(_context.prev=_context.next){case 0:_config$modRequest=config.modRequest,nextMod=_config$modRequest.nextMod,modRequest=(0,_objectWithoutProperties2["default"])(_config$modRequest,_excluded);_context.next=1;return nextMod(_objectSpread(_objectSpread({},config),{},{modRequest:modRequest}));case 1:results=_context.sent;return _context.abrupt("return",_action(results));case 2:case"end":return _context.stop();}},_callee);}))();}});};var withAndroidNativeSymbolsPlugin=function withAndroidNativeSymbolsPlugin(config){return withFinalizedProjectBuildGradle(config,function(){var _ref=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee2(config){var result,appBuildGradle,contents;return _regenerator["default"].wrap(function(_context2){while(1)switch(_context2.prev=_context2.next){case 0:if(!(config.modResults.language!=='groovy')){_context2.next=1;break;}console.warn('Cannot configure the PostHog Android Gradle plugin because the project build.gradle is not groovy');return _context2.abrupt("return",config);case 1:result=addPostHogAndroidGradlePluginClasspath(config.modResults.contents);if(!(result.contents!==config.modResults.contents)){_context2.next=3;break;}_context2.next=2;return fs.promises.writeFile(config.modResults.path,result.contents);case 2:config.modResults.contents=result.contents;case 3:if(result.classpathPresent){_context2.next=4;break;}return _context2.abrupt("return",config);case 4:_context2.next=5;return AndroidConfig.Paths.getAppBuildGradleAsync(config.modRequest.projectRoot);case 5:appBuildGradle=_context2.sent;if(!(appBuildGradle.language!=='groovy')){_context2.next=6;break;}console.warn('Cannot configure the PostHog Android Gradle plugin because the app build.gradle is not groovy');return _context2.abrupt("return",config);case 6:contents=applyPostHogAndroidGradlePlugin(appBuildGradle.contents);if(!(contents!==appBuildGradle.contents)){_context2.next=7;break;}_context2.next=7;return fs.promises.writeFile(appBuildGradle.path,contents);case 7:return _context2.abrupt("return",config);case 8:case"end":return _context2.stop();}},_callee2);}));return function(_x){return _ref.apply(this,arguments);};}());};var POSTHOG_NEW_INTENT_MARKER='posthog-new-intent';var POSTHOG_NEW_INTENT_BEGIN="// @generated begin ".concat(POSTHOG_NEW_INTENT_MARKER," - posthog-react-native (DO NOT MODIFY)");var POSTHOG_NEW_INTENT_END="// @generated end ".concat(POSTHOG_NEW_INTENT_MARKER);var NEW_INTENT_DOC=" /**\n * Records the intent that reopened the app so getIntent() stays correct.\n *\n * Works around a React Native defect that drops notification taps and deep links arriving while\n * the React context is still starting. Managed by the posthog-react-native Expo config plugin;\n * remove it with { patchMainActivityNewIntent: false } in app.json.\n * https://posthog.com/docs/workflows/push-notifications/react-native\n */";var NEW_INTENT_KOTLIN_BODY=" override fun onNewIntent(intent: android.content.Intent) {\n setIntent(intent)\n super.onNewIntent(intent)\n }";var NEW_INTENT_JAVA_BODY=" @Override\n public void onNewIntent(android.content.Intent intent) {\n setIntent(intent);\n super.onNewIntent(intent);\n }";function newIntentOverrideBlock(language){var body=language==='java'?NEW_INTENT_JAVA_BODY:NEW_INTENT_KOTLIN_BODY;return"\n ".concat(POSTHOG_NEW_INTENT_BEGIN,"\n").concat(NEW_INTENT_DOC,"\n").concat(body,"\n ").concat(POSTHOG_NEW_INTENT_END,"\n");}function escapeRegExp(value){return value.replace(/[.*+?^${}()|[\]\\]/g,'\\$&');}var POSTHOG_NEW_INTENT_BLOCK_PATTERN=new RegExp("\\r?\\n?[ \\t]*".concat(escapeRegExp(POSTHOG_NEW_INTENT_BEGIN),"[\\s\\S]*?").concat(escapeRegExp(POSTHOG_NEW_INTENT_END),"[ \\t]*\\r?\\n"),'g');function literalEnd(s,start,language){var quote=s[start];var raw=quote==='"'&&s.startsWith('"""',start);var i=start+(raw?3:1);while(i<s.length){var c=s[i];if(raw){if(s.startsWith('"""',i)){while(s[i]==='"'){i++;}return i;}}else if(c==='\n'){return-1;}else if(c===quote){return i+1;}if(c==='\\'&&(!raw||language==='java')){i+=2;continue;}if(language==='kt'&&quote==='"'&&c==='$'&&s[i+1]==='{'){var close=matchingBraceIndexInSource(s,i+1,language);if(close===-1){return-1;}i=close+1;continue;}i++;}return-1;}function matchingBraceIndexInSource(s,openBraceIndex,language){var depth=0;var i=openBraceIndex;while(i<s.length){var c=s[i];if(c==='/'&&s[i+1]==='/'){var end=s.indexOf('\n',i);i=end===-1?s.length:end;continue;}if(c==='/'&&s[i+1]==='*'){var depthOfComment=1;i+=2;while(i<s.length&&depthOfComment>0){if(language==='kt'&&s[i]==='/'&&s[i+1]==='*'){depthOfComment++;i+=2;continue;}if(s[i]==='*'&&s[i+1]==='/'){depthOfComment--;i+=2;continue;}i++;}if(depthOfComment>0){return-1;}continue;}if(c==='"'||c==="'"){var _end=literalEnd(s,i,language);if(_end===-1){return-1;}i=_end;continue;}if(c==='{'){depth++;}else if(c==='}'){depth--;if(depth===0){return i;}}i++;}return-1;}function maskCommentsAndLiterals(source,language){var out=source.split('');var blank=function blank(from,to){for(var j=from;j<to&&j<out.length;j++){if(out[j]!=='\n'){out[j]=' ';}}};var i=0;while(i<source.length){var c=source[i];if(c==='/'&&source[i+1]==='/'){var end=source.indexOf('\n',i);var stop=end===-1?source.length:end;blank(i,stop);i=stop;continue;}if(c==='/'&&source[i+1]==='*'){var depth=1;var j=i+2;while(j<source.length&&depth>0){if(language==='kt'&&source[j]==='/'&&source[j+1]==='*'){depth++;j+=2;continue;}if(source[j]==='*'&&source[j+1]==='/'){depth--;j+=2;continue;}j++;}blank(i,j);i=j;continue;}if(c==='"'||c==="'"){var _end2=literalEnd(source,i,language);if(_end2===-1){blank(i,source.length);return out.join('');}blank(i,_end2);i=_end2;continue;}i++;}return out.join('');}function mainActivityBody(contents,language){var code=maskCommentsAndLiterals(contents,language);var declaration=/\bclass\s+MainActivity\b/.exec(code);if(!declaration){return undefined;}var searchFrom=declaration.index+declaration[0].length;var open=code.indexOf('{',searchFrom);if(open===-1||!/^[^;{}]*$/.test(code.slice(searchFrom,open))){return undefined;}var depth=0;var close=-1;for(var i=open;i<code.length;i++){if(code[i]==='{'){depth++;}else if(code[i]==='}'){depth--;if(depth===0){close=i;break;}}}return close===-1?undefined:{open:open,close:close};}function updateMainActivityNewIntentOverride(contents,language,enabled){var withoutManagedBlock=contents.replace(POSTHOG_NEW_INTENT_BLOCK_PATTERN,'');if(!enabled){return withoutManagedBlock;}var body=mainActivityBody(withoutManagedBlock,language);if(!body){console.warn('[posthog-react-native] Could not find the MainActivity class body; skipping the onNewIntent '+'override. Notification taps delivered while the React context is starting will be lost.');return withoutManagedBlock;}var codeOnly=maskCommentsAndLiterals(withoutManagedBlock,language);if(/\b(fun|void)\s+onNewIntent\s*\(/.test(codeOnly.slice(body.open,body.close))){console.warn('[posthog-react-native] MainActivity already overrides onNewIntent; leaving it alone. '+'Add `setIntent(intent)` as its first statement so a notification tap that arrives before '+'the React context is ready is not lost, or set `{ patchMainActivityNewIntent: false }` '+'on the plugin to silence this.');return withoutManagedBlock;}return withoutManagedBlock.slice(0,body.open+1)+newIntentOverrideBlock(language)+withoutManagedBlock.slice(body.open+1);}var MAIN_ACTIVITY_SOURCE_ROOTS=['android/app/src/main/java','android/app/src/main/kotlin'];function findMainActivityPath(projectRoot){var _walk=function walk(dir){if(!fs.existsSync(dir)){return undefined;}var _iterator=_createForOfIteratorHelper(fs.readdirSync(dir,{withFileTypes:true})),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var entry=_step.value;var candidate=path.join(dir,entry.name);if(!entry.isDirectory()){if(/^MainActivity\.(kt|java)$/.test(entry.name)){return candidate;}continue;}var hit=_walk(candidate);if(hit){return hit;}}}catch(err){_iterator.e(err);}finally{_iterator.f();}return undefined;};for(var _i=0,_MAIN_ACTIVITY_SOURCE=MAIN_ACTIVITY_SOURCE_ROOTS;_i<_MAIN_ACTIVITY_SOURCE.length;_i++){var sourceRoot=_MAIN_ACTIVITY_SOURCE[_i];var hit=_walk(path.join(projectRoot,sourceRoot));if(hit){return hit;}}return undefined;}var withMainActivityNewIntent=function withMainActivityNewIntent(config,enabled){return withDangerousMod(config,['android',(function(){var _ref2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee3(config){var mainActivityPath,contents,updated;return _regenerator["default"].wrap(function(_context3){while(1)switch(_context3.prev=_context3.next){case 0:mainActivityPath=findMainActivityPath(config.modRequest.projectRoot);if(mainActivityPath){_context3.next=1;break;}console.warn('[posthog-react-native] Could not find MainActivity under android/app/src/main/{java,kotlin}; '+'skipping the onNewIntent override. Notification taps delivered while the React context is '+'starting will be lost.');return _context3.abrupt("return",config);case 1:_context3.next=2;return fs.promises.readFile(mainActivityPath,'utf8');case 2:contents=_context3.sent;updated=updateMainActivityNewIntentOverride(contents,mainActivityPath.endsWith('.java')?'java':'kt',enabled);if(!(updated!==contents)){_context3.next=3;break;}_context3.next=3;return fs.promises.writeFile(mainActivityPath,updated);case 3:if(!contents.includes(POSTHOG_NEW_INTENT_BEGIN)&&updated.includes(POSTHOG_NEW_INTENT_BEGIN)){console.warn("[posthog-react-native] Added an onNewIntent override to ".concat(path.relative(config.modRequest.projectRoot,mainActivityPath)," so a notification tap that arrives before the React context is ready is not lost. ")+'Set `{ patchMainActivityNewIntent: false }` on the plugin in app.json to opt out.');}return _context3.abrupt("return",config);case 4:case"end":return _context3.stop();}},_callee3);}));return function(_x2){return _ref2.apply(this,arguments);};}())]);};function modifyExistingXcodeBuildScript(script){var skipOnConflict=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var releaseMode=arguments.length>2?arguments[2]:undefined;if(!(script===null||script===void 0?void 0:script.shellScript)){console.warn("[posthog-react-native] Could not find the 'Bundle React Native code and images' build phase; "+'skipping sourcemap upload setup.');return;}if(!script.shellScript.match(/(packager|scripts)\/react-native-xcode\.sh\b/)){return;}if(script.shellScript.includes('posthog-xcode.sh')){var _code=migrateLegacyPostHogWrapperInvocation(JSON.parse(script.shellScript));script.shellScript=JSON.stringify(updatePostHogBundlePhaseExports(_code,skipOnConflict,releaseMode));return;}if(script.shellScript.includes('posthog-react-native')){return;}var code=JSON.parse(script.shellScript);script.shellScript=JSON.stringify(addPostHogWithBundledScriptsToBundleShellScript(code,skipOnConflict,releaseMode));}var POSTHOG_REACT_NATIVE_XCODE_PATH="`\"$NODE_BINARY\" --print \"require('path').join(require('path').dirname(require.resolve('posthog-react-native')), '..', 'tooling', 'posthog-xcode.sh')\"`";var POSTHOG_SKIP_ON_CONFLICT_EXPORT='export POSTHOG_SKIP_ON_CONFLICT=1';var POSTHOG_RELEASE_MODE_EXPORT_PREFIX='export POSTHOG_RELEASE_MODE=';function buildBundlePhaseExports(skipOnConflict,releaseMode){var exports=[];if(skipOnConflict){exports.push(POSTHOG_SKIP_ON_CONFLICT_EXPORT);}if(releaseMode){exports.push("".concat(POSTHOG_RELEASE_MODE_EXPORT_PREFIX).concat(releaseMode));}return exports;}var REACT_NATIVE_XCODE_LINE=/^([ \t]*)(?![A-Za-z_][A-Za-z0-9_]*=)([^\n]*(?:packager|scripts)\/react-native-xcode\.sh\b[^\n]*)$/m;function migrateLegacyPostHogWrapperInvocation(script){return script.replace("/bin/sh ".concat(POSTHOG_REACT_NATIVE_XCODE_PATH),POSTHOG_REACT_NATIVE_XCODE_PATH);}function updatePostHogBundlePhaseExports(script,skipOnConflict,releaseMode){var _a,_b;var skipArg='--posthog-skip-on-conflict --';var lines=script.replace(new RegExp("\\s*".concat(skipArg,"\\s*"),'g'),' ').split('\n').filter(function(line){return line.trim()!==POSTHOG_SKIP_ON_CONFLICT_EXPORT;}).filter(function(line){return!line.trim().startsWith(POSTHOG_RELEASE_MODE_EXPORT_PREFIX);});var exports=buildBundlePhaseExports(skipOnConflict,releaseMode);if(exports.length>0){var commandIndex=lines.findIndex(function(line){return line.includes(POSTHOG_REACT_NATIVE_XCODE_PATH);});if(commandIndex!==-1){var indent=(_b=(_a=lines[commandIndex].match(/^[ \t]*/))===null||_a===void 0?void 0:_a[0])!==null&&_b!==void 0?_b:'';lines.splice.apply(lines,[commandIndex,0].concat((0,_toConsumableArray2["default"])(exports.map(function(line){return"".concat(indent).concat(line);}))));}}return lines.join('\n');}function addPostHogWithBundledScriptsToBundleShellScript(script){var skipOnConflict=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var releaseMode=arguments.length>2?arguments[2]:undefined;return script.replace(REACT_NATIVE_XCODE_LINE,function(_match,indent,rnCommand){var exports=buildBundlePhaseExports(skipOnConflict,releaseMode).map(function(line){return"".concat(indent).concat(line,"\n");}).join('');return"".concat(exports).concat(indent).concat(POSTHOG_REACT_NATIVE_XCODE_PATH," ").concat(rnCommand);});}var POSTHOG_DSYM_BUILD_PHASE_NAME='Upload PostHog Debug Symbols';var POSTHOG_DSYM_INPUT_PATH='"$(DWARF_DSYM_FOLDER_PATH)/$(DWARF_DSYM_FILE_NAME)/Contents/Resources/DWARF/$(EXECUTABLE_NAME)"';function buildDsymUploadShellScript(){var includeSource=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;var skipOnConflict=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;return composeDsymUploadShellScript(includeSource,skipOnConflict);}function composeDsymUploadShellScript(includeSource,skipOnConflict){var lines=['# Upload iOS dSYMs to PostHog so native crashes can be symbolicated.','# upload-symbols.sh ships inside the posthog-ios dependency.'];if(includeSource){lines.push('# Also upload native source files for source-code context around crashes.','export POSTHOG_INCLUDE_SOURCE=1');}if(skipOnConflict){lines.push('# Skip dSYMs that already exist in PostHog with different content instead of failing the build.','export POSTHOG_SKIP_ON_CONFLICT=1');}lines.push('PODS_SCRIPT="${PODS_ROOT}/PostHog/build-tools/upload-symbols.sh"','SPM_SCRIPT="${BUILD_DIR%/Build/*}/SourcePackages/checkouts/posthog-ios/build-tools/upload-symbols.sh"','if [ -f "$PODS_SCRIPT" ]; then',' /bin/sh "$PODS_SCRIPT"','elif [ -f "$SPM_SCRIPT" ]; then',' /bin/sh "$SPM_SCRIPT"','else',' echo "warning: PostHog upload-symbols.sh not found in Pods or SwiftPM checkouts; skipping dSYM upload."','fi');return lines.join('\n');}function legacyDsymReleaseModeLines(releaseMode){return[releaseMode?"POSTHOG_RESOLVED_RELEASE_MODE=\"".concat(releaseMode,"\""):'POSTHOG_RESOLVED_RELEASE_MODE="${POSTHOG_RELEASE_MODE:-}"','case "$POSTHOG_RESOLVED_RELEASE_MODE" in',' ""|symbol-set) ;;',' event)',' # Upload dSYMs without binding them to a release, so each crash resolves its own from the',' # app version and namespace the SDK sends. posthog-ios versions whose upload-symbols.sh',' # does not read this variable ignore it and keep binding the dSYMs.',' export POSTHOG_NO_RELEASE_BIND=1',' ;;',' *)'," echo \"error: posthog release mode must be 'symbol-set' or 'event', was '$POSTHOG_RESOLVED_RELEASE_MODE'\"",' exit 1',' ;;','esac'];}function buildLegacyReleaseModeDsymUploadShellScript(includeSource,skipOnConflict,releaseMode){var lines=composeDsymUploadShellScript(includeSource,skipOnConflict).split('\n');var uploadIndex=lines.findIndex(function(line){return line.startsWith('PODS_SCRIPT=');});lines.splice.apply(lines,[uploadIndex,0].concat((0,_toConsumableArray2["default"])(legacyDsymReleaseModeLines(releaseMode))));return lines.join('\n');}function encodePbxShellScript(script){return'"'+script.replace(/"/g,'\\"')+'"';}function decodePbxShellScript(stored){if(!stored.startsWith('"')||!stored.endsWith('"')){return stored;}return stored.slice(1,-1).replace(/\\(.)/g,function(_match,ch){return ch==='n'?'\n':ch==='t'?'\t':ch;});}function isPluginGeneratedDsymUploadBuildPhase(phase){if(typeof(phase===null||phase===void 0?void 0:phase.shellScript)!=='string'){return false;}var stored=decodePbxShellScript(phase.shellScript);return[false,true].some(function(source){return[false,true].some(function(skip){return stored===buildDsymUploadShellScript(source,skip)||[undefined].concat(POSTHOG_RELEASE_MODES).some(function(mode){return stored===buildLegacyReleaseModeDsymUploadShellScript(source,skip,mode);});});});}function moveDsymUploadBuildPhaseToEnd(xcodeProject){var _a,_b;var existing=xcodeProject.pbxItemByComment(POSTHOG_DSYM_BUILD_PHASE_NAME,'PBXShellScriptBuildPhase');if(!isPluginGeneratedDsymUploadBuildPhase(existing)){return;}var buildPhases=(_b=(_a=xcodeProject.getFirstTarget)===null||_a===void 0?void 0:_a.call(xcodeProject).firstTarget)===null||_b===void 0?void 0:_b.buildPhases;if(Array.isArray(buildPhases)){var phaseIndex=buildPhases.findIndex(function(phase){return phase.comment===POSTHOG_DSYM_BUILD_PHASE_NAME;});if(phaseIndex!==-1&&phaseIndex!==buildPhases.length-1){buildPhases.push.apply(buildPhases,(0,_toConsumableArray2["default"])(buildPhases.splice(phaseIndex,1)));}}}function addDsymUploadBuildPhase(xcodeProject){var includeSource=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var skipOnConflict=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;var existing=xcodeProject.pbxItemByComment(POSTHOG_DSYM_BUILD_PHASE_NAME,'PBXShellScriptBuildPhase');if(existing){if(isPluginGeneratedDsymUploadBuildPhase(existing)){existing.shellScript=encodePbxShellScript(buildDsymUploadShellScript(includeSource,skipOnConflict));existing.inputPaths=Array.from(new Set([].concat((0,_toConsumableArray2["default"])(Array.isArray(existing.inputPaths)?existing.inputPaths:[]),[POSTHOG_DSYM_INPUT_PATH])));}}else{xcodeProject.addBuildPhase([],'PBXShellScriptBuildPhase',POSTHOG_DSYM_BUILD_PHASE_NAME,null,{inputPaths:[POSTHOG_DSYM_INPUT_PATH],shellPath:'/bin/sh',shellScript:buildDsymUploadShellScript(includeSource,skipOnConflict)});}moveDsymUploadBuildPhaseToEnd(xcodeProject);}function disableUserScriptSandboxing(xcodeProject){var configurations=xcodeProject.pbxXCBuildConfigurationSection();for(var key in configurations){var configuration=configurations[key];if(configuration&&configuration.buildSettings){configuration.buildSettings.ENABLE_USER_SCRIPT_SANDBOXING='"NO"';}}}var POSTHOG_DOTENV_BUILD_SETTING='POSTHOG_CLI_DOTENV_FILE';var POSTHOG_DOTENV_GRADLE_PROPERTY='posthog.dotenvFile';function normalizeDotenvFileProp(dotenvFile){return dotenvFile.replace(/^\.\//,'');}function resolveDotenvFileProp(dotenvFile){var trimmed=dotenvFile===null||dotenvFile===void 0?void 0:dotenvFile.trim();return trimmed?trimmed:undefined;}function isAbsoluteDotenvPath(dotenvFile){return dotenvFile.startsWith('/')||/^[A-Za-z]:[\\/]/.test(dotenvFile);}function buildIosDotenvFileBuildSetting(dotenvFile){var value=isAbsoluteDotenvPath(dotenvFile)?dotenvFile:"$(SRCROOT)/../".concat(normalizeDotenvFileProp(dotenvFile));return'"'+value.replace(/(["\\])/g,'\\$1')+'"';}function applyDotenvFileBuildSetting(xcodeProject,dotenvFile){var configurations=xcodeProject.pbxXCBuildConfigurationSection();for(var key in configurations){var configuration=configurations[key];if(configuration&&configuration.buildSettings){if(dotenvFile){configuration.buildSettings[POSTHOG_DOTENV_BUILD_SETTING]=buildIosDotenvFileBuildSetting(dotenvFile);}else{delete configuration.buildSettings[POSTHOG_DOTENV_BUILD_SETTING];}}}}function buildAndroidDotenvFileGradleValue(dotenvFile){return isAbsoluteDotenvPath(dotenvFile)?dotenvFile:"../".concat(normalizeDotenvFileProp(dotenvFile));}function updateDotenvFileGradleProperties(properties,dotenvFile){var rest=properties.filter(function(item){return!(item.type==='property'&&item.key===POSTHOG_DOTENV_GRADLE_PROPERTY);});if(!dotenvFile){return rest;}rest.push({type:'property',key:POSTHOG_DOTENV_GRADLE_PROPERTY,value:buildAndroidDotenvFileGradleValue(dotenvFile)});return rest;}function updateHermesReleaseModeGradleProperties(properties,releaseMode){var rest=properties.filter(function(item){return!(item.type==='property'&&item.key===POSTHOG_HERMES_RELEASE_MODE_GRADLE_PROPERTY);});if(!releaseMode){return rest;}rest.push({type:'property',key:POSTHOG_HERMES_RELEASE_MODE_GRADLE_PROPERTY,value:releaseMode});return rest;}var withPostHogGradleProperties=function withPostHogGradleProperties(config,dotenvFile,releaseMode){return withGradleProperties(config,function(config){config.modResults=updateDotenvFileGradleProperties(config.modResults,dotenvFile);config.modResults=updateHermesReleaseModeGradleProperties(config.modResults,releaseMode);return config;});};function resolveNativeSymbolUpload(prop){if(prop===true){return{enabled:true,includeSource:false};}if(prop&&(0,_typeof2["default"])(prop)==='object'){return{enabled:true,includeSource:prop.includeSource===true};}return{enabled:false,includeSource:false};}var withFinalizedXcodeProject=function withFinalizedXcodeProject(config,_action2){return withBaseMod(config,{platform:'ios',mod:'xcodeproj',action:function action(config){return(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee4(){var _config$modRequest2,nextMod,modRequest,results;return _regenerator["default"].wrap(function(_context4){while(1)switch(_context4.prev=_context4.next){case 0:_config$modRequest2=config.modRequest,nextMod=_config$modRequest2.nextMod,modRequest=(0,_objectWithoutProperties2["default"])(_config$modRequest2,_excluded2);_context4.next=1;return nextMod(_objectSpread(_objectSpread({},config),{},{modRequest:modRequest}));case 1:results=_context4.sent;return _context4.abrupt("return",_action2(results));case 2:case"end":return _context4.stop();}},_callee4);}))();}});};var withIosPlugin=function withIosPlugin(config){var props=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var nativeSymbols=resolveNativeSymbolUpload(props.uploadNativeSymbols);config=withXcodeProject(config,function(config){var xcodeProject=config.modResults;var bundleReactNativePhase=xcodeProject.pbxItemByComment('Bundle React Native code and images','PBXShellScriptBuildPhase');modifyExistingXcodeBuildScript(bundleReactNativePhase,props.skipOnConflict===true,props.releaseMode);if(nativeSymbols.enabled){addDsymUploadBuildPhase(xcodeProject,nativeSymbols.includeSource,props.skipOnConflict===true);}applyDotenvFileBuildSetting(xcodeProject,props.dotenvFile);if(props.disableSandboxing!==false){disableUserScriptSandboxing(xcodeProject);console.warn('[posthog-react-native] Setting ENABLE_USER_SCRIPT_SANDBOXING=NO on all Xcode '+'build configurations so sourcemap uploads can resolve git metadata. '+'If your org requires sandboxing to stay enabled, set `{ disableSandboxing: false }` '+'on the plugin in app.json — note that stock Expo projects may fail to build under '+'sandboxing until every script build phase declares its input/output files.');}return config;});if(nativeSymbols.enabled){config=withFinalizedXcodeProject(config,function(config){moveDsymUploadBuildPhaseToEnd(config.modResults);return config;});}return config;};var withPostHogPlugin=function withPostHogPlugin(config){var rawProps=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var props=_objectSpread(_objectSpread({},rawProps),{},{dotenvFile:resolveDotenvFileProp(rawProps.dotenvFile),releaseMode:resolveReleaseModeProp(rawProps.releaseMode,process.env.POSTHOG_RELEASE_MODE)});if(resolveNativeSymbolUpload(props.uploadNativeSymbols).enabled){config=withAndroidNativeSymbolsPlugin(config);}config=withAndroidPlugin(config,props.skipOnConflict===true);config=withPostHogGradleProperties(config,props.dotenvFile,props.releaseMode);config=withMainActivityNewIntent(config,props.patchMainActivityNewIntent!==false);return withIosPlugin(config,props);};var postHogPlugin=function postHogPlugin(config){var props=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};return withPostHogPlugin(config,props);};module.exports=postHogPlugin;module.exports.modifyExistingXcodeBuildScript=modifyExistingXcodeBuildScript;module.exports.addPostHogWithBundledScriptsToBundleShellScript=addPostHogWithBundledScriptsToBundleShellScript;module.exports.disableUserScriptSandboxing=disableUserScriptSandboxing;module.exports.buildDsymUploadShellScript=buildDsymUploadShellScript;module.exports.addDsymUploadBuildPhase=addDsymUploadBuildPhase;module.exports.moveDsymUploadBuildPhaseToEnd=moveDsymUploadBuildPhaseToEnd;module.exports.resolveNativeSymbolUpload=resolveNativeSymbolUpload;module.exports.buildAndroidSkipOnConflictGradleLine=buildAndroidSkipOnConflictGradleLine;module.exports.addPostHogAndroidGradlePluginClasspath=addPostHogAndroidGradlePluginClasspath;module.exports.applyPostHogAndroidGradlePlugin=applyPostHogAndroidGradlePlugin;module.exports.buildIosDotenvFileBuildSetting=buildIosDotenvFileBuildSetting;module.exports.applyDotenvFileBuildSetting=applyDotenvFileBuildSetting;module.exports.resolveDotenvFileProp=resolveDotenvFileProp;module.exports.buildAndroidDotenvFileGradleValue=buildAndroidDotenvFileGradleValue;module.exports.updateDotenvFileGradleProperties=updateDotenvFileGradleProperties;module.exports.POSTHOG_RELEASE_MODES=POSTHOG_RELEASE_MODES;module.exports.resolveReleaseModeProp=resolveReleaseModeProp;module.exports.updateHermesReleaseModeGradleProperties=updateHermesReleaseModeGradleProperties;module.exports.updateMainActivityNewIntentOverride=updateMainActivityNewIntentOverride;
2
+ //# sourceMappingURL=expoconfig.js.map