
    iCt                        d dl Z d dlmZmZmZmZ d dlmZ d dlm	Z	m
Z
mZ d dlmZ d dlmZ d dlmZ d dlmZ d d	lmZ d d
lmZ d dlmZ d dlmZ d dlmZ d dlmZ  d dlm!Z" d dl#m$Z$m%Z% d dl&m'Z' d dl&m(Z( d dl)m*Z*m+Z+ d dl,m-Z-m.Z.m/Z/m0Z0 d dl1m2Z2m3Z3 d dl1m4Z4 d dl5m6Z6 e6Z7	 dHdZdIdZde8fdZde8fdZd e8fd!Zd"e9fd#Zd$e:fd%Zd&e:fd'Zd(e8d)efd*Zd+ee8ef         fd,Z!	 dZ;dZ<dZ=dZ>dZ?dZ@dZAdZBdZCd-ZDdZEd.ZFdZGdZHdZIdZJdZKdZLdaMdZNe%ZOe$ZPdZQd/e8d0ee
         d+ee8         fd1ZRd0ee         d+ee8         fd2ZSd0ee         d+ee8         fd3ZT	 	 	 	 dJd4ZU	 	 	 dKd5ZV	 dLd6ee	         d0ee
         fd7ZW	 	 	 	 	 	 	 dMd8ZX	 	 	 	 	 	 	 dMd+ee2         fd9ZY	 	 	 	 	 	 dNd+eeZe8e2f                  fd:Z[	 	 	 	 	 	 	 dMd;Z\	 	 	 	 	 	 	 	 dOd+ee8         fd<Z]d= Z^	 	 	 	 	 	 dNd+e3fd>Z_d? Z`d@ ZadA ZbdB ZcdC Zdd+efdDZedE Zf G dF dGe          ZgdS )P    N)AnyCallableDictOptional)Unpack)ExceptionArgOptionalCaptureArgsOptionalSetArgs)Client)identify_context)new_context)scoped),set_capture_exception_code_variables_context)*set_code_variables_ignore_patterns_context)(set_code_variables_mask_patterns_context)set_context_device_id)set_context_session)tag)get_tags)&DEFAULT_CODE_VARIABLES_IGNORE_PATTERNS$DEFAULT_CODE_VARIABLES_MASK_PATTERNS)InconclusiveMatchError)RequiresServerEvaluation)FlagDefinitionCacheDataFlagDefinitionCacheProvider)disable_connection_reuseenable_keep_aliveset_socket_optionsSocketOptions)FeatureFlagFlagsAndPayloads)FeatureFlagResult)VERSIONFTc                 &    t          | ||          S )ar  
    Create a new context scope that will be active for the duration of the with block.

    Args:
        fresh: Whether to start with a fresh context (default: False)
        capture_exceptions: Whether to capture exceptions raised within the context (default: True)
        client: Optional Posthog client instance to use for this context (default: None)

    Examples:
        ```python
        from posthog import new_context, tag, capture
        with new_context():
            tag("request_id", "123")
            capture("event_name", properties={"property": "value"})
        ```

    Category:
        Contexts
    freshcapture_exceptionsclient)inner_new_contextr%   s      C/var/www/icac/venv/lib/python3.11/site-packages/posthog/__init__.pyr   r   H   s#    ( (:6       c                 $    t          | |          S )a  
    Decorator that creates a new context for the function.

    Args:
        fresh: Whether to start with a fresh context (default: False)
        capture_exceptions: Whether to capture and track exceptions with posthog error tracking (default: True)

    Examples:
        ```python
        from posthog import scoped, tag, capture
        @scoped()
        def process_payment(payment_id):
            tag("payment_id", payment_id)
            capture("payment_started")
        ```

    Category:
        Contexts
    r&   r'   )inner_scopedr-   s     r*   r   r   a   s    ( e8JKKKKr+   
session_idc                      t          |           S )aB  
    Set the session ID for the current context.

    Args:
        session_id: The session ID to associate with the current context and its children

    Examples:
        ```python
        from posthog import set_context_session
        set_context_session("session_123")
        ```

    Category:
        Contexts
    )inner_set_context_session)r/   s    r*   r   r   x   s      %Z000r+   	device_idc                      t          |           S )a  
    Set the device ID for the current context, associating all feature flag requests
    in this or child contexts with the given device ID.

    Args:
        device_id: The device ID to associate with the current context and its children

    Examples:
        ```python
        from posthog import set_context_device_id
        set_context_device_id("device_123")
        ```

    Category:
        Contexts
    )inner_set_context_device_id)r2   s    r*   r   r      s    " 'y111r+   distinct_idc                      t          |           S )aF  
    Identify the current context with a distinct ID.

    Args:
        distinct_id: The distinct ID to associate with the current context and its children

    Examples:
        ```python
        from posthog import identify_context
        identify_context("user_123")
        ```

    Category:
        Identification
    )inner_identify_context)r5   s    r*   r   r      s      "+...r+   enabledc                      t          |           S )zJ
    Set whether code variables are captured for the current context.
    )2inner_set_capture_exception_code_variables_context)r8   s    r*   r   r      s     >gFFFr+   mask_patternsc                      t          |           S )zg
    Variable names matching these patterns will be masked with *** when capturing code variables.
    ).inner_set_code_variables_mask_patterns_context)r;   s    r*   r   r      s     :-HHHr+   ignore_patternsc                      t          |           S )zj
    Variable names matching these patterns will be ignored completely when capturing code variables.
    )0inner_set_code_variables_ignore_patterns_context)r>   s    r*   r   r      s     <OLLLr+   namevaluec                 "    t          | |          S )z
    Add a tag to the current context.

    Args:
        name: The tag key
        value: The tag value

    Examples:
        ```python
        from posthog import tag
        tag("user_id", "123")
        ```

    Category:
        Contexts
    )	inner_tag)rA   rB   s     r*   r   r      s    " T5!!!r+   returnc                      t                      S )z
    Get all tags from the current context.

    Returns:
        Dict of all tags in the current context

    Category:
        Contexts
    )inner_get_tags r+   r*   r   r      s     r+         eventkwargsc                     t          d| fi |S )aZ
  
    Capture anything a user does within your system.

    Args:
        event: The event name to specify the event
        **kwargs: Optional arguments including:
            distinct_id: Unique identifier for the user
            properties: Dict of event properties
            timestamp: When the event occurred
            groups: Dict of group types and IDs
            disable_geoip: Whether to disable GeoIP lookup

    Details:
        Capture allows you to capture anything a user does within your system, which you can later use in PostHog to find patterns in usage, work out which features to improve or where people are giving up. A capture call requires an event name to specify the event. We recommend using [verb] [noun], like `movie played` or `movie updated` to easily identify what your events mean later on. Capture takes a number of optional arguments, which are defined by the `OptionalCaptureArgs` type.

    Examples:
        ```python
        # Context and capture usage
        from posthog import new_context, identify_context, tag_context, capture
        # Enter a new context (e.g. a request/response cycle, an instance of a background job, etc)
        with new_context():
            # Associate this context with some user, by distinct_id
            identify_context('some user')

            # Capture an event, associated with the context-level distinct ID ('some user')
            capture('movie started')

            # Capture an event associated with some other user (overriding the context-level distinct ID)
            capture('movie joined', distinct_id='some-other-user')

            # Capture an event with some properties
            capture('movie played', properties={'movie_id': '123', 'category': 'romcom'})

            # Capture an event with some properties
            capture('purchase', properties={'product_id': '123', 'category': 'romcom'})
            # Capture an event with some associated group
            capture('purchase', groups={'company': 'id:5'})

            # Adding a tag to the current context will cause it to appear on all subsequent events
            tag_context('some-tag', 'some-value')

            capture('another-event') # Will be captured with `'some-tag': 'some-value'` in the properties dict
        ```
        ```python
        # Set event properties
        from posthog import capture
        capture(
            "user_signed_up",
            distinct_id="distinct_id_of_the_user",
            properties={
                "login_type": "email",
                "is_free_trial": "true"
            }
        )
        ```
    Category:
        Events
    capture_proxy)rK   rL   s     r*   rN   rN     s    x )U--f---r+   c                      t          di | S )a  
    Set properties on a user record.

    Details:
        This will overwrite previous people property values. Generally operates similar to `capture`, with distinct_id being an optional argument, defaulting to the current context's distinct ID. If there is no context-level distinct ID, and no override distinct_id is passed, this function will do nothing. Context tags are folded into $set properties, so tagging the current context and then calling `set` will cause those tags to be set on the user (unlike capture, which causes them to just be set on the event).

    Examples:
        ```python
        # Set person properties
        from posthog import capture
        capture(
            'distinct_id',
            event='event_name',
            properties={
                '$set': {'name': 'Max Hedgehog'},
                '$set_once': {'initial_url': '/blog'}
            }
        )
        ```
    Category:
        Identification
    set)rR   rO   rL   s    r*   rR   rR   L  s    0 ""6"""r+   c                      t          di | S )aS  
    Set properties on a user record, only if they do not yet exist.

    Details:
        This will not overwrite previous people property values, unlike `set`. Otherwise, operates in an identical manner to `set`.

    Examples:
        ```python
        # Set property once
        from posthog import capture
        capture(
            'distinct_id',
            event='event_name',
            properties={
                '$set': {'name': 'Max Hedgehog'},
                '$set_once': {'initial_url': '/blog'}
            }
        )

        ```
    Category:
        Identification
    set_once)rU   rO   rS   s    r*   rU   rU   g  s    0 '''''r+   c           	      .    t          d| |||||          S )an  
    Set properties on a group.

    Args:
        group_type: Type of your group
        group_key: Unique identifier of the group
        properties: Properties to set on the group
        timestamp: Optional timestamp for the event
        uuid: Optional UUID for the event
        disable_geoip: Whether to disable GeoIP lookup

    Examples:
        ```python
        # Group identify
        from posthog import group_identify
        group_identify('company', 'company_id_in_your_db', {
            'name': 'Awesome Inc.',
            'employees': 11
        })
        ```
    Category:
        Identification
    group_identify
group_type	group_key
properties	timestampuuiddisable_geoiprO   rX   s         r*   rW   rW     s1    B #   r+   c                 ,    t          d| ||||          S )a  
    Associate user behaviour before and after they e.g. register, login, or perform some other identifying action.

    Args:
        previous_id: The unique ID of the user before
        distinct_id: The current unique id
        timestamp: Optional timestamp for the event
        uuid: Optional UUID for the event
        disable_geoip: Whether to disable GeoIP lookup

    Details:
        To marry up whatever a user does before they sign up or log in with what they do after you need to make an alias call. This will allow you to answer questions like "Which marketing channels leads to users churning after a month?" or "What do users do on our website before signing up?". Particularly useful for associating user behaviour before and after they e.g. register, login, or perform some other identifying action.

    Examples:
        ```python
        # Alias user
        from posthog import alias
        alias(previous_id='distinct_id', distinct_id='alias_id')
        ```
    Category:
        Identification
    aliasprevious_idr5   r\   r]   r^   rO   ra   s        r*   r`   r`     s-    > #   r+   	exceptionc                     t          dd| i|S )a  
    Capture exceptions that happen in your code.

    Args:
        exception: The exception to capture. If not provided, the current exception is captured via `sys.exc_info()`

    Details:
        Capture exception is idempotent - if it is called twice with the same exception instance, only a occurrence will be tracked in posthog. This is because, generally, contexts will cause exceptions to be captured automatically. However, to ensure you track an exception, if you catch and do not re-raise it, capturing it manually is recommended, unless you are certain it will have crossed a context boundary (e.g. by existing a `with posthog.new_context():` block already). If the passed exception was raised and caught, the captured stack trace will consist of every frame between where the exception was raised and the point at which it is captured (the "traceback"). If the passed exception was never raised, e.g. if you call `posthog.capture_exception(ValueError("Some Error"))`, the stack trace captured will be the full stack trace at the moment the exception was captured. Note that heavy use of contexts will lead to truncated stack traces, as the exception will be captured by the context entered most recently, which may not be the point you catch the exception for the final time in your code. It's recommended to use contexts sparingly, for this reason. `capture_exception` takes the same set of optional arguments as `capture`.

    Examples:
        ```python
        # Capture exception
        from posthog import capture_exception
        try:
            risky_operation()
        except Exception as e:
            capture_exception(e)
        ```
    Category:
        Events
    capture_exceptionrc   )re   rO   )rc   rL   s     r*   re   re     s    4 EEEfEEEr+   c	                 @    t          d| ||pi |pi |pi ||||
  
        S )a  
    Use feature flags to enable or disable features for users.

    Args:
        key: The feature flag key
        distinct_id: The user's distinct ID
        groups: Groups mapping
        person_properties: Person properties
        group_properties: Group properties
        only_evaluate_locally: Whether to evaluate only locally
        send_feature_flag_events: Whether to send feature flag events
        disable_geoip: Whether to disable GeoIP lookup

    Details:
        You can call `posthog.load_feature_flags()` before to make sure you're not doing unexpected requests.

    Examples:
        ```python
        # Boolean feature flag
        from posthog import feature_enabled, get_feature_flag_payload
        is_my_flag_enabled = feature_enabled('flag-key', 'distinct_id_of_your_user')
        if is_my_flag_enabled:
            matched_flag_payload = get_feature_flag_payload('flag-key', 'distinct_id_of_your_user')
        ```
    Category:
        Feature flags
    feature_enabled	keyr5   groupsperson_propertiesgroup_propertiesonly_evaluate_locallysend_feature_flag_eventsr^   r2   rO   rh   s	            r*   rg   rg     sH    N |+1r)/R3!9#   r+   c	                 @    t          d| ||pi |pi |pi ||||
  
        S )a  
    Get feature flag variant for users. Used with experiments.

    Args:
        key: The feature flag key
        distinct_id: The user's distinct ID
        groups: Groups mapping from group type to group key
        person_properties: Person properties
        group_properties: Group properties in format { group_type_name: { group_properties } }
        only_evaluate_locally: Whether to evaluate only locally
        send_feature_flag_events: Whether to send feature flag events
        disable_geoip: Whether to disable GeoIP lookup

    Details:
        `groups` are a mapping from group type to group key. So, if you have a group type of "organization" and a group key of "5", you would pass groups={"organization": "5"}. `group_properties` take the format: { group_type_name: { group_properties } }. So, for example, if you have the group type "organization" and the group key "5", with the properties name, and employee count, you'll send these as: group_properties={"organization": {"name": "PostHog", "employees": 11}}.

    Examples:
        ```python
        # Multivariate feature flag
        from posthog import get_feature_flag, get_feature_flag_payload
        enabled_variant = get_feature_flag('flag-key', 'distinct_id_of_your_user')
        if enabled_variant == 'variant-key':
            matched_flag_payload = get_feature_flag_payload('flag-key', 'distinct_id_of_your_user')
        ```
    Category:
        Feature flags
    get_feature_flagrh   rO   rh   s	            r*   rp   rp   )  sH    L |+1r)/R3!9#   r+   c           
      <    t          d| |pi |pi |pi |||          S )a  
    Get all flags for a given user.

    Args:
        distinct_id: The user's distinct ID
        groups: Groups mapping
        person_properties: Person properties
        group_properties: Group properties
        only_evaluate_locally: Whether to evaluate only locally
        disable_geoip: Whether to disable GeoIP lookup

    Details:
        Flags are key-value pairs where the key is the flag key and the value is the flag variant, or True, or False.

    Examples:
        ```python
        # All flags for user
        from posthog import get_all_flags
        get_all_flags('distinct_id_of_your_user')
        ```
    Category:
        Feature flags
    get_all_flagsr5   rj   rk   rl   rm   r^   r2   rO   rs   s          r*   rr   rr   ]  sB    @ |+1r)/R3#	 	 	 	r+   c	                 @    t          d| ||pi |pi |pi ||||
  
        S )a  
    Get a FeatureFlagResult object which contains the flag result and payload.

    This method evaluates a feature flag and returns a FeatureFlagResult object containing:
    - enabled: Whether the flag is enabled
    - variant: The variant value if the flag has variants
    - payload: The payload associated with the flag (automatically deserialized from JSON)
    - key: The flag key
    - reason: Why the flag was enabled/disabled

    Example:
    ```python
    result = posthog.get_feature_flag_result('beta-feature', 'distinct_id')
    if result and result.enabled:
        # Use the variant and payload
        print(f"Variant: {result.variant}")
        print(f"Payload: {result.payload}")
    ```
    get_feature_flag_resultrh   rO   rh   s	            r*   ru   ru     sG    > !|+1r)/R3!9#   r+   c
                 B    t          d| |||pi |pi |pi ||||	          S )Nget_feature_flag_payload
ri   r5   match_valuerj   rk   rl   rm   rn   r^   r2   rO   rx   s
             r*   rw   rw     sJ     "|+1r)/R3!9#   r+   c                 $    t          d|           S )a1  Get the payload for a remote config feature flag.

    Args:
        key: The key of the feature flag

    Returns:
        The payload associated with the feature flag. If payload is encrypted, the return value will decrypted

    Note:
        Requires personal_api_key to be set for authentication
    get_remote_config_payloadri   rO   r|   s    r*   r{   r{     s!     #   r+   c           
      <    t          d| |pi |pi |pi |||          S )Nget_all_flags_and_payloadsrs   rO   rs   s          r*   r~   r~     sA     $|+1r)/R3#	 	 	 	r+   c                       t          d          S )aX  
    Returns loaded feature flags.

    Details:
        Returns loaded feature flags, if any. Helpful for debugging what flag information you have loaded.

    Examples:
        ```python
        from posthog import feature_flag_definitions
        definitions = feature_flag_definitions()
        ```

    Category:
        Feature flags
    feature_flag_definitionsrO   rH   r+   r*   r   r     s      ,---r+   c                       t          d          S )z
    Load feature flag definitions from PostHog.

    Examples:
        ```python
        from posthog import load_feature_flags
        load_feature_flags()
        ```

    Category:
        Feature flags
    load_feature_flagsrO   rH   r+   r*   r   r     s     &'''r+   c                  $    t          d           dS )z
    Tell the client to flush all queued events.

    Examples:
        ```python
        from posthog import flush
        flush()
        ```

    Category:
        Client management
    flushNrO   rH   r+   r*   r   r     s     7OOOOOr+   c                  $    t          d           dS )a  
    Block program until the client clears the queue. Used during program shutdown. You should use `shutdown()` directly in most cases.

    Examples:
        ```python
        from posthog import join
        join()
        ```

    Category:
        Client management
    joinNrO   rH   r+   r*   r   r   -  s     6NNNNNr+   c                  B    t          d           t          d           dS )z
    Flush all messages and cleanly shutdown the client.

    Examples:
        ```python
        from posthog import shutdown
        shutdown()
        ```

    Category:
        Client management
    r   r   NrO   rH   r+   r*   shutdownr   =  s     7OOO
6NNNNNr+   c                     t           st          st          d          t          t          fi dt          dt
          dt          dt          dt          dt          dt          d	t          d
t          dt          dt          dt          dt           dt"          dt$          dt&          dt(          dt*          a t          t           _        t
          t           _        t           S )NzAPI key is requiredhostdebugon_errorsend	sync_modepersonal_api_keypoll_intervaldisabledr^   %feature_flags_request_timeout_secondssuper_propertiesenable_exception_autocapturelog_captured_exceptionsenable_local_evaluation capture_exception_code_variablescode_variables_mask_patternscode_variables_ignore_patternsin_app_modules)default_clientapi_key
ValueErrorr   r   r   r   r   r   r   r   r   r^   r   r   r   r   r   r   r   r   r   rH   r+   r*   setupr   N  s4    
 	42333
 
 

 %
 X	

 
  i
 .-
 (-
 X
 (-
 3X2W
 .-
  *F)E!
" %<$;#
$ %<$;%
& .N-M'
( *F)E)
* ,J+I+
, *>-
4 'N Nr+   c                 X    t                       t          t          |           } ||i |S )z?Create an analytics client if one doesn't exist and send to it.)r   getattrr   )methodargsrL   fns       r*   rP   rP   s  s/    	GGG		(	(B2tvr+   c                       e Zd ZdS )PosthogN)__name__
__module____qualname__rH   r+   r*   r   r   {  s        Dr+   r   )FTN)FT)NNNN)NNN)N)NNNFTNN)NNNFNN)NNNNFTNN)hdatetimetypingr   r   r   r   typing_extensionsr   posthog.argsr   r	   r
   posthog.clientr   posthog.contextsr   r7   r   r)   r   r.   r   r:   r   r@   r   r=   r   r4   r   r1   r   rD   r   rG   posthog.exception_utilsr   r   posthog.feature_flagsr   r   posthog.flag_definition_cacher   r   posthog.requestr   r   r   r   posthog.typesr    r!   r"   posthog.versionr#   __version__strboollistr   r   r   r   r   r   r   r   project_api_keyr   r^   r   r   r   r   project_rootprivacy_moder   r   r   r   r   r   rN   rR   rU   rW   r`   re   rg   rp   dictrr   ru   rw   r{   r~   r   r   r   r   r   r   rP   r   rH   r+   r*   <module>r      s    0 0 0 0 0 0 0 0 0 0 0 0 $ $ $ $ $ $ K K K K K K K K K K ! ! ! ! ! !                                                                                                  $ # # # # #    2L L L L.1C 1 1 1 1&2S 2 2 2 2(/# / / / /&G$ G G G GID I I I IM M M M M"c "# " " " "(
$sCx. 
 
 
 
 
	 () % $    #(  C !G <.3 <.&)<"= <.(3- <. <. <. <.~#&) #hsm # # # #6(vo. (8C= ( ( ( (< 	) ) ) )^ 	& & & &T )-F F%F()F F F F@ !2 2 2 2p !1 1 k1 1 1 1l ) ) d3#$%) ) ) )^ !* * * *` !  c]   6  ,      *. . .&( ( (         ""v " " " "J  	 	 	 	 	f 	 	 	 	 	r+   