o
    6dF                     @   s  d Z ddlmZmZ ddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlmZmZ dZer>ddlZG dd deZG dd	 d	eZG d
d deZG dd deZG dd deZG dd deZ		d'ddZ		d(ddZG dd deZ		d)ddZ			d*ddZe
 dZ!dd Z"d d! Z#zddl$Z$W n
 e%y   Y dS w ej&edd"Z'd#d$ Z(ej&edd"Z)	d+d%d&Z*dS ),a  
Serializers for Stone data types.

Currently, only JSON is officially supported, but there's an experimental
msgpack integration. If possible, serializers should be kept separate from the
RPC format.

This module should be dropped into a project that requires the use of Stone. In
the future, this could be imported from a pre-installed Python package, rather
than being added to a project.
    )absolute_importunicode_literalsN)
stone_basestone_validatorsFc                   @      e Zd Zedd ZdS )CallerPermissionsInterfacec                 C      t )zL
        Returns the list of permissions this caller has access to.
        NotImplementedErrorself r   C:\Users\jesus\OneDrive\Desktop\erpjis_fastapi\backend\jisbackend\Lib\site-packages\stone/backends/python_rsrc/stone_serializers.pypermissions'   s   z&CallerPermissionsInterface.permissionsN__name__
__module____qualname__propertyr   r   r   r   r   r   %       r   c                   @   r   )CallerPermissionsDefaultc                 C   s   g S Nr   r   r   r   r   r   1   s   z$CallerPermissionsDefault.permissionsNr   r   r   r   r   r   /   r   r   c                   @   s   e Zd ZdZdd ZdS )StoneEncoderInterfacez4
    Interface defining a stone object encoder.
    c                 C   r   )a  
        Validate ``value`` using ``validator`` and return the encoding.

        Args:
            validator: the ``stone_validators.Validator`` used to validate
                ``value``
            value: the object to encode

        Returns:
            The encoded object. This is implementation-defined.

        Raises:
            stone_validators.ValidationError: Raised if ``value`` (or one
                of its sub-values).
        r	   r   	validatorvaluer   r   r   encode;   s   zStoneEncoderInterface.encodeN)r   r   r   __doc__r   r   r   r   r   r   6   s    r   c                   @   sh   e Zd Zdd Zedd Zdd Zdd Zd	d
 Zdd Z	dd Z
dd Zdd Zdd Zdd ZdS )StoneSerializerBasec                 C   s2   |r|nt  | _i | _|dur| j| dS dS )a_  
        Constructor, `obviously
        <http://www.geekalerts.com/ew-hand-sanitizer/>`.

        Args:
            caller_permissions (list): The list of raw-string caller permissions with which
                to serialize.
            alias_validators (``typing.Mapping``, optional): A mapping of
                custom validation callables in the format
                ``{stone_validators.Validator:
                typing.Callable[[typing.Any], None], ...}``. These callables must
                raise a ``stone_validators.ValidationError`` on failure.
                Defaults to ``None``.
        N)r   caller_permissions_alias_validatorsupdate)r   r   alias_validatorsr   r   r   __init__Q   s   zStoneSerializerBase.__init__c                 C      | j S )z
        A ``typing.Mapping`` of custom validation callables in the format
        ``{stone_validators.Validator: typing.Callable[typing.Any],
        ...}``.
        )r    r   r   r   r   r"   h      z$StoneSerializerBase.alias_validatorsc                 C   s   |  ||S r   )
encode_subr   r   r   r   r   q   s   zStoneSerializerBase.encodec                    s  t tjrj} j}nut tjrj} j}nht tjr'j} j}n[t tj	r4j} j
}nNt tjrjt tjrU jjrN fdd}|}nj} j}n- jjrc fdd}|}nj} j}nt tjrwj} j}ntdtj|| ||S )z
        Callback intended to be called by other ``encode`` methods to
        delegate encoding of sub-values. Arguments have the same semantics
        as with the ``encode`` method.
        c                        |  j d S r   validate_with_permissionsr   valr   r   r   r   r)         zAStoneSerializerBase.encode_sub.<locals>.validate_with_permissionsc                    r'   r   r(   r*   r,   r   r   r)      r-   zUnsupported data type {})
isinstancebvListvalidateencode_listMap
encode_mapNullableencode_nullable	Primitiveencode_primitiveStruct
StructTreer   r   encode_struct_treeZvalidate_type_onlyencode_structUnionencode_unionValidationErrorformattyper   )r   r   r   Z
validate_fZencode_fr)   r   r,   r   r&   t   s<   
zStoneSerializerBase.encode_subc                 C   r   )z
        Callback for serializing a ``stone_validators.List``. Arguments
        have the same semantics as with the ``encode`` method.
        r	   r   r   r   r   r2         zStoneSerializerBase.encode_listc                 C   r   )z
        Callback for serializing a ``stone_validators.Map``. Arguments
        have the same semantics as with the ``encode`` method.
        r	   r   r   r   r   r4      rB   zStoneSerializerBase.encode_mapc                 C   r   )z
        Callback for serializing a ``stone_validators.Nullable``.
        Arguments have the same semantics as with the ``encode`` method.
        r	   r   r   r   r   r6      rB   z#StoneSerializerBase.encode_nullablec                 C   r   )z
        Callback for serializing a ``stone_validators.Primitive``.
        Arguments have the same semantics as with the ``encode`` method.
        r	   r   r   r   r   r8      rB   z$StoneSerializerBase.encode_primitivec                 C   r   )z
        Callback for serializing a ``stone_validators.Struct``. Arguments
        have the same semantics as with the ``encode`` method.
        r	   r   r   r   r   r<      rB   z!StoneSerializerBase.encode_structc                 C   r   )z
        Callback for serializing a ``stone_validators.StructTree``.
        Arguments have the same semantics as with the ``encode`` method.
        r	   r   r   r   r   r;      rB   z&StoneSerializerBase.encode_struct_treec                 C   r   )z
        Callback for serializing a ``stone_validators.Union``. Arguments
        have the same semantics as with the ``encode`` method.
        r	   r   r   r   r   r>      rB   z StoneSerializerBase.encode_unionN)r   r   r   r#   r   r"   r   r&   r2   r4   r6   r8   r<   r;   r>   r   r   r   r   r   O   s    
6r   c                       sx   e Zd Z fddZedd Zedd Z fddZd	d
 Zdd Z	dd Z
dd Zdd Zdd Zdd Z  ZS ) StoneToPythonPrimitiveSerializerc                    s*   t t| j||d || _|| _|| _dS )a  
        Args:
            alias_validators (``typing.Mapping``, optional): Passed
                to ``StoneSerializer.__init__``. Defaults to ``None``.
            for_msgpack (bool, optional): See the like-named property.
                Defaults to ``False``.
            old_style (bool, optional): See the like-named property.
                Defaults to ``False``.
            should_redact (bool, optional): Whether to perform redaction on
                marked fields. Defaults to ``False``.
        )r"   N)superrC   r#   _for_msgpack
_old_styleshould_redact)r   r   r"   for_msgpack	old_stylerG   	__class__r   r   r#      s   

z)StoneToPythonPrimitiveSerializer.__init__c                 C   r$   )z
        EXPERIMENTAL: A flag associated with the serializer indicating
        whether objects produced by the ``encode`` method should be
        encoded for msgpack.

        rE   r   r   r   r   rH      s   z,StoneToPythonPrimitiveSerializer.for_msgpackc                 C   r$   z
        A flag associated with the serializer indicating whether objects
        produced by the ``encode`` method should be encoded according to
        Dropbox's old or new API styles.
        rF   r   r   r   r   rI     r%   z*StoneToPythonPrimitiveSerializer.old_stylec                    sj   | j r,t dr,t|tr fdd|D S t|tr& fdd| D S  j|S tt	| 
 |S )N_redactc                    s   g | ]} j |qS r   rO   apply).0vr   r   r   
<listcomp>  s    z?StoneToPythonPrimitiveSerializer.encode_sub.<locals>.<listcomp>c                    s   i | ]\}}| j |qS r   rP   )rR   krS   rT   r   r   
<dictcomp>  s    z?StoneToPythonPrimitiveSerializer.encode_sub.<locals>.<dictcomp>)rG   hasattrr.   listdictitemsrO   rQ   rD   rC   r&   r   rJ   rT   r   r&     s   

z+StoneToPythonPrimitiveSerializer.encode_subc                    s    |} fdd|D S )Nc                    s   g | ]	}  j|qS r   )r&   item_validator)rR   Z
value_itemr,   r   r   rU     s    z@StoneToPythonPrimitiveSerializer.encode_list.<locals>.<listcomp>)r1   r   r   r   Zvalidated_valuer   r,   r   r2     s   
z,StoneToPythonPrimitiveSerializer.encode_listc                    s"    |} fdd| D S )Nc                    s*   i | ]\}}  j|  j|qS r   )r&   key_validatorvalue_validatorrR   keyr   r,   r   r   rW      
    z?StoneToPythonPrimitiveSerializer.encode_map.<locals>.<dictcomp>)r1   r[   r]   r   r,   r   r4     s   
z+StoneToPythonPrimitiveSerializer.encode_mapc                 C   s   |d u rd S |  |j|S r   )r&   r   r   r   r   r   r6   &  s   z0StoneToPythonPrimitiveSerializer.encode_nullablec                 C   s   || j v r| j | | t|tjrd S t|tjr t||jS t|tjr3| jr+|S t	
|dS t|tjrBt|trBt|S |S )Nascii)r"   r.   r/   Void	Timestamp	_strftimer@   BytesrH   base64	b64encodedecodeIntegerboolintr   r   r   r   r8   ,  s   
z1StoneToPythonPrimitiveSerializer.encode_primitivec                 C   s   t  }|jj}| jjD ]}d|}|t|j|g  }q|D ]N\}}zt||}	W n ty> }
 zt	
|
jd d }
~
ww d| }|	d urmt||tjurmz
| ||	||< W q t	j
yl }
 z|
|  d }
~
ww q|S )N_all_{}_fields_r   z	_%s_value)collectionsOrderedDict
definition_all_fields_r   r   r@   getattrAttributeErrorr/   r?   argsbbZNOT_SETr&   
add_parent)r   r   r   d
all_fieldsextra_permissionZall_fields_name
field_namefield_validatorZfield_valueexcZ	value_keyr   r   r   r<   B  s0   

z.StoneToPythonPrimitiveSerializer.encode_structc                 C   s   t ||jjv sJ dt ||jf |jjt | \}}t|dks'J |t|tjr4J d|j | jrC|d | ||i}|S t	
 }|d |d< || || |S )Nz'%r is not a serializable subtype of %r.   z8Cannot serialize type %r because it enumerates subtypes.r   .tag)rA   rq   Z_pytype_to_tag_and_subtype_lenr.   r/   r:   rI   r<   ro   rp   r!   )r   r   r   tagssubtyperx   r   r   r   r;   a  s    z3StoneToPythonPrimitiveSerializer.encode_struct_treec                    s2  |j d u r
td|j|j  jstd|j |j|j  j}t|tj	p5t|tj
o5|jd u } fdd} jrX|d u rF|j S |rK|j S |||j|j }|j |iS |r_d|j iS |||j|j }t|tj
rp|j}t|tjrt|tjst }|j |d< || |S td|j f|j |ffS )Nz
no tag setz'caller does not have access to '{}' tagc              
      s:   z	  | |}W |S  tjy } z||  d }~ww r   )r&   r/   r?   rw   )Zsub_validatorZ	sub_valueZ
parent_tagencoded_valr}   r   r   r   r&     s   
zAStoneToPythonPrimitiveSerializer.encode_union.<locals>.encode_subr   )Z_tagr/   r?   rq   _is_tag_presentr   r@   _get_val_data_typer.   rd   r5   _valuerI   r   r9   r:   ro   rp   r!   )r   r   r   r|   Zis_noner&   r   rx   r   r   r   r>   v  sJ   









z-StoneToPythonPrimitiveSerializer.encode_union)r   r   r   r#   r   rH   rI   r&   r2   r4   r6   r8   r<   r;   r>   __classcell__r   r   rJ   r   rC      s    
	
	rC   c                       s   e Zd Z fddZ  ZS )StoneToJsonSerializerc                    s   t tt| ||S r   )jsondumpsrD   r   r   r   rJ   r   r   r     s   zStoneToJsonSerializer.encode)r   r   r   r   r   r   r   rJ   r   r     s    r   c                 C   s    d}t |||||}|| |S )aA  Encodes an object into JSON based on its type.

    Args:
        data_type (Validator): Validator for obj.
        obj (object): Object to be serialized.
        caller_permissions (list): The list of raw-string caller permissions with which
                to serialize.
        alias_validators (Optional[Mapping[bv.Validator, Callable[[], None]]]):
            Custom validation functions. These must raise bv.ValidationError on
            failure.

    Returns:
        str: JSON-encoded object.

    This function will also do additional validation that wasn't done by the
    objects themselves:

    1. The passed in obj may not have been validated with data_type yet.
    2. If an object that should be a Struct was assigned to a field, its
       type has been validated, but the presence of all required fields
       hasn't been.
    3. If an object that should be a Union was assigned to a field, whether
       or not a tag has been set has not been validated.
    4. A list may have passed validation initially, but been mutated since.

    Example of serializing a struct to JSON:

    struct FileRef
       path String
       rev String

    > fr = FileRef()
    > fr.path = 'a/b/c'
    > fr.rev = '1234'
    > JsonEncoder.encode(fr)
    "{'path': 'a/b/c', 'rev': '1234'}"

    Example of serializing a union to JSON:

    union UploadMode
        add
        overwrite
        update FileRef

    > um = UploadMode()
    > um.set_add()
    > JsonEncoder.encode(um)
    '"add"'
    > um.update = fr
    > JsonEncoder.encode(um)
    "{'update': {'path': 'a/b/c', 'rev': '1234'}}"
    F)r   r   )	data_typeobjr   r"   rI   rG   rH   
serializerr   r   r   json_encode  s
   6
r   c                 C   s   t |||||}|| |S )a  Encodes an object into a JSON-compatible dict based on its type.

    Args:
        data_type (Validator): Validator for obj.
        obj (object): Object to be serialized.
        caller_permissions (list): The list of raw-string caller permissions
            with which to serialize.

    Returns:
        An object that when passed to json.dumps() will produce a string
        giving the JSON-encoded object.

    See json_encode() for additional information about validation.
    )rC   r   )r   r   r   r"   rI   rH   rG   r   r   r   r   json_compat_obj_encode  s   
r   c                   @   s   e Zd Zdd Zedd Zedd Zdd Zd	d
 Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd ZdS ) PythonPrimitiveToStoneDecoderc                 C   s,   |r|nt  | _|| _|| _|| _|| _d S r   )r   r   r"   strictrF   rE   )r   r   r"   rH   rI   r   r   r   r   r#     s   
z&PythonPrimitiveToStoneDecoder.__init__c                 C   r$   )z
        EXPERIMENTAL: A flag associated with the serializer indicating
        whether objects produced by the ``encode`` method should be
        encoded for msgpack.
        rL   r   r   r   r   rH     r%   z)PythonPrimitiveToStoneDecoder.for_msgpackc                 C   r$   rM   rN   r   r   r   r   rI     r%   z'PythonPrimitiveToStoneDecoder.old_stylec                 C   s   t |tjr| ||S t |tjr| ||S t |tjr-| jr'| ||S | 	||S t |tj
r9| ||S t |tjrE| ||S t |tjrQ| ||S t |tjr^| ||dS td| )zI
        See json_compat_obj_decode() for argument descriptions.
        FzCannot handle type %r.)r.   r/   r:   decode_struct_treer9   decode_structr=   rI   decode_union_olddecode_unionr0   decode_listr3   
decode_mapr5   decode_nullabler7   make_stone_friendlyAssertionErrorr   r   r   r   r   r   json_compat_obj_decode_helper'  s.   z;PythonPrimitiveToStoneDecoder.json_compat_obj_decode_helperc           
      C   s   |du r|  r| S t|tstdt| |jj}| j	j
D ]}d|}|t|j|g  }q#| jrf|jj}| j	j
D ]}d|}|t|j|i }q?|D ]}||vre|dsetd| qS| }	| |	|| ||	| j	 |	S )zz
        The data_type argument must be a Struct.
        See json_compat_obj_decode() for argument descriptions.
        Nzexpected object, got %srn   z_all_{}_field_names_r   zunknown field '%s')has_defaultget_defaultr.   rZ   r/   r?   generic_type_namerq   rr   r   r   r@   rs   r   Z_all_field_names_union
startswithdecode_struct_fieldsZ%validate_fields_only_with_permissions)
r   r   r   ry   rz   Zall_extra_fieldsZall_field_namesZall_extra_field_namesra   insr   r   r   r   D  s6   


z+PythonPrimitiveToStoneDecoder.decode_structc                 C   sz   |D ]8\}}||v r.z|  ||| }t||| W q tjy- } z||  d}~ww | r:t|||  qdS )a  
        Args:
            ins: An instance of the class representing the data type being decoded.
                The object will have its fields set.
            fields: A tuple of (field_name: str, field_validator: Validator)
            obj (dict): JSON-compatible dict that is being decoded.
            strict (bool): See :func:`json_compat_obj_decode`.
        Returns:
            None: `ins` has its fields set based on the contents of `obj`.
        N)r   setattrr/   r?   rw   r   r   )r   r   fieldsr   nameZfield_data_typerS   er   r   r   r   d  s   
z2PythonPrimitiveToStoneDecoder.decode_struct_fieldsc                 C   s   d}t |tjrK|}|j|| jr8|j|| j}t |tjtj	fs*t
d| ||jjkr7t
d| n+| jsD|jjrD|jj}nt
d| t |trY| ||\}}n
t
dt| |t||S )y
        The data_type argument must be a Union.
        See json_compat_obj_decode() for argument descriptions.
        N$expected object for '%s', got symbol(unexpected use of the catch-all tag '%s'unknown tag '%s'!expected string or object, got %s)r.   sixstring_typesrq   r   r   r   r/   rd   r5   r?   
_catch_allr   rZ   decode_union_dictr   
ensure_str)r   r   r   r+   tagval_data_typer   r   r   r   z  s2   

z*PythonPrimitiveToStoneDecoder.decode_unionc           
   
   C   sV  d|vr	t d|d }t|tjst dt | |j|| js9| j	s2|jj
r2|jj
d fS t d| ||jj
krFt d| |j|| j}t|t jrZ|j}d}nd}t|t jr| j	r||v r{|| d ur{t dt ||  |D ]}||kr|dkrt d	| q}d }||fS t|t jt jt jt jt jfr||v r|| }z| ||}W n t jy }	 z|	|  d }	~	ww |rd }nt d
| |D ]}||kr|dkrt d	| q||fS t|t jr%|rt|dkrd }||fS |}z| ||}W ||fS  t jy$ }	 z|	|  d }	~	ww J t|)Nr   missing '.tag' keyztag must be string, got %sr   r   TFexpected null, got %szunexpected key '%s'zmissing '%s' keyr~   )r/   r?   r.   r   r   r   rq   r   r   r   r   r   r5   r   rd   r7   r0   r:   r=   r3   r   rw   r9   r   rA   )
r   r   r   r   r   Znullablera   r+   raw_valr   r   r   r   r     s   
 

z/PythonPrimitiveToStoneDecoder.decode_union_dictc              
   C   s  d}t |tjr>|}|j|| jr+|j|| j}t |tjtj	fs*t
d| n| js7|jjr7|jj}nt
d| t |trt|dkrRt
dt| t|d }|| }|j|| jr|j|| j}t |tj	ry|du ryd}nSt |tjr|du s| jsd}nCt
dt| z| ||}W n0 tj
y } z||  d}~ww | js|jjr|jj}nt
d| t
dt| |t||S )	r   Nr   r   r~   zexpected 1 key, got %sr   r   r   )r.   r   r   rq   r   r   r   r/   rd   r5   r?   r   r   rZ   r   rY   r   r   rw   r   )r   r   r   r+   r   r   r   r   r   r   r   r     s\   



z.PythonPrimitiveToStoneDecoder.decode_union_oldc                 C   s   |  ||}| ||S )z~
        The data_type argument must be a StructTree.
        See json_compat_obj_decode() for argument descriptions.
        )determine_struct_tree_subtyper   )r   r   r   r   r   r   r   r     s   z0PythonPrimitiveToStoneDecoder.decode_struct_treec                 C   s   d|vr	t dt|d tjst jdt |d  dd|d f}||jjv rB|jj| }t|t jr@t dd	| |S | j
rOt dd	| |jjrU|S t dd	||jjf )	z
        Searches through the JSON-object-compatible dict using the data type
        definition to determine which of the enumerated subtypes `obj` is.
        r   r   zexpected string, got %s)parentz#tag '%s' refers to non-leaf subtype.zunknown subtype '%s'z0unknown subtype '%s' and '%s' is not a catch-all)r/   r?   r.   r   r   r   rq   Z_tag_to_subtype_r:   joinr   Z_is_catch_all_r   )r   r   r   Zfull_tags_tupler   r   r   r   r     s6   

z;PythonPrimitiveToStoneDecoder.determine_struct_tree_subtypec                    s2   t |tstdt|  fdd|D S )zx
        The data_type argument must be a List.
        See json_compat_obj_decode() for argument descriptions.
        zexpected list, got %sc                    s   g | ]	}  j|qS r   )r   r\   )rR   itemr   r   r   r   rU   J  s    z=PythonPrimitiveToStoneDecoder.decode_list.<locals>.<listcomp>)r.   rY   r/   r?   r   r   r   r   r   r   B  s   
z)PythonPrimitiveToStoneDecoder.decode_listc                    s6   t |tstdt|  fdd| D S )zw
        The data_type argument must be a Map.
        See json_compat_obj_decode() for argument descriptions.
        zexpected dict, got %sc                    s*   i | ]\}}  j|  j|qS r   )r   r^   r_   r`   r   r   r   rW   V  rb   z<PythonPrimitiveToStoneDecoder.decode_map.<locals>.<dictcomp>)r.   rZ   r/   r?   r   r[   r   r   r   r   r   N  s   
z(PythonPrimitiveToStoneDecoder.decode_mapc                 C   s   |dur|  |j|S dS )z|
        The data_type argument must be a Nullable.
        See json_compat_obj_decode() for argument descriptions.
        N)r   r   r   r   r   r   r   \  s   z-PythonPrimitiveToStoneDecoder.decode_nullablec              
   C   s$  t |tjr'z
tj||j}W nn ttfy& } zt|j	d d}~ww t |tj
rV| jr?t |tjr<|d}nC|}n@zt|}W n8 ttjfyU   tdw t |tjrj| jrh|durhtddS |r}| jjrx||| j n|| |}| jdur|| jv r| j| | |S )z
        Convert a Python object to a type that will pass validation by its
        validator.
        Validation by ``alias_validators`` is performed even if ``validate`` is
        false.
        r   Nutf-8zinvalid base64-encoded byteszexpected null, got value)r.   r/   re   datetimestrptimer@   	TypeError
ValueErrorr?   ru   rg   rH   r   	text_typer   rh   	b64decodebinasciiErrorrd   r   r   r   r)   r1   r"   )r   r   r+   r1   retr   r   r   r   r   f  s:   


z1PythonPrimitiveToStoneDecoder.make_stone_friendlyN)r   r   r   r#   r   rH   rI   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r     s$    

 F9#
r   Tc                 C   s<   zt |}W n ty   tdw t| |||||dS )au  Performs the reverse operation of json_encode.

    Args:
        data_type (Validator): Validator for serialized_obj.
        serialized_obj (str): The JSON string to deserialize.
        caller_permissions (list): The list of raw-string caller permissions
            with which to serialize.
        alias_validators (Optional[Mapping[bv.Validator, Callable[[], None]]]):
            Custom validation functions. These must raise bv.ValidationError on
            failure.
        strict (bool): If strict, then unknown struct fields will raise an
            error, and unknown union variants will raise an error even if a
            catch all field is specified. strict should only be used by a
            recipient of serialized JSON if it's guaranteed that its Stone
            specs are at least as recent as the senders it receives messages
            from.

    Returns:
        The returned object depends on the input data_type.
            - Boolean -> bool
            - Bytes -> bytes
            - Float -> float
            - Integer -> long
            - List -> list
            - Map -> dict
            - Nullable -> None or its wrapped type.
            - String -> unicode (PY2) or str (PY3)
            - Struct -> An instance of its definition attribute.
            - Timestamp -> datetime.datetime
            - Union -> An instance of its definition attribute.
    zcould not decode input as JSON)r   r"   r   rI   )r   loadsr   r/   r?   json_compat_obj_decode)r   serialized_objr   r"   r   rI   deserialized_objr   r   r   json_decode  s   !
r   c                 C   s6   t |||||}t| tjr|| |dS || |S )ap  
    Decodes a JSON-compatible object based on its data type into a
    representative Python object.

    Args:
        data_type (Validator): Validator for serialized_obj.
        obj: The JSON-compatible object to decode based on data_type.
        caller_permissions (list): The list of raw-string caller permissions
            with which to serialize.
        strict (bool): If strict, then unknown struct fields will raise an
            error, and unknown union variants will raise an error even if a
            catch all field is specified. See json_decode() for more.

    Returns:
        See json_decode().
    T)r   r.   r/   r7   r   r   )r   r   r   r"   r   rI   rH   decoderr   r   r   r     s   r   z((^|[^%])(%%)*%s)c                 C   s8   g }d}	 |  ||}|dkr	 |S || |d }q)Nr   r~   )findappend)textsubstrsitesijr   r   r   _findall  s   
r   c                 C   s@  z|  |W S  ty   tjr| jdkr Y nw t|r"td| j}d| }d|d |d   }|| }|d| d d  }|  }t	 ||f|dd   }t
|t|}t	 ||d f|dd   }t
|t|d }	g }
|D ]}||	v r|
| qu|}d	| jf }|
D ]}|d | | ||d
 d   }q|S )Nil  z/This strftime implementation does not handle %si     d   i     r~   z%4d   )strftimer   r   PY2year
_ILLEGAL_Ssearchr   	timetupletimer   strr   )dtfmtr   deltaoffr   s1Zsites1s2Zsites2r   sitesZsyearr   r   r   rf     s:   

"rf   )rH   c                 C   s   t jt| |ddS )Nr   )encoding)msgpackr   msgpack_compat_obj_encode)r   r   r   r   r   msgpack_encode   s   
r   c                 C   s   t j|ddd}t| |||S )Nr   ignore)r   unicode_errors)r   r   msgpack_compat_obj_decode)r   r   r"   r   r   r   r   r   msgpack_decode'  s   r   )NNFF)NNFFF)NNTF)NNTFF)NT)+r   
__future__r   r   rh   r   ro   r   	functoolsr   rer   r   Zstone.backends.python_rsrcr   rv   r   r/   Z_MYPYtypingobjectr   r   r   r   rC   r   r   r   r   r   r   compiler   r   rf   r   ImportErrorpartialr   r   r   r   r   r   r   r   <module>   sr    
  O

;
   
+

#*