
    +h                    b   U d Z ddl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	m
Z
mZmZmZmZmZmZmZmZmZmZ ddlmZmZmZmZ ddlmZ ddlmZmZ ddlm Z m!Z!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/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6 ddl7m8Z8 ej9        ej:        ej;        ej<        ej=        ej>        dZ? G d d          Z@ G d d          ZAe
reeeBef                  ZCneZCdZD G d deC          ZE eEeAjF                  ZGdeHd<   	  eEeAjI                  ZJdeHd<   	  eEeAjK                  ZLdeHd<   	 eLZMdeHd<   	 dd&ZNdd)ZOeMfdd+ZPeMfdd.ZQeMfdd1ZRdd4ZSdd6ZTdd:ZUdd;ZVdd<ZWdd>ZXdd@ZYddAZZddCZ[ddEZ\ddFZ]ddGZ^ddHZ_ddJZ`ddLZaddNZbddPZcddRZdddSZeddUZfi dVeYdWe]dXeXdYeSdZecd[edd\eed]e[d^eTd_d` dae`dbefdcebdde^dee\dfeZdge_dheaiZgdieHdj<    eheg          ZiddlZjddnZkddoZlddpZmddqZnddrZoddsZpddtZqddvZrddwZsddyZtdd{Zudd|Zvdd}Zwdd~ZxddZyddZzddZ{i e|ene}esej        ere!eke~eqeepeBen ed          enej        eueete*emeele&eye,e{e.eze0eve2eoe4eoe6ewe(exiZdeHd<   i ZdeHd<   eD ]Z eed          ree         eej        <    ed eD                       ZeMfddZddZddZddZddZe0dede*de(de6de.de,diZdeHd<   eBee}eej        ee2ee&eiZdeHd<   dddZddZddZdS )aO  Tools for using Python's :mod:`json` module with BSON documents.

This module provides two helper methods `dumps` and `loads` that wrap the
native :mod:`json` methods and provide explicit BSON conversion to and from
JSON. :class:`~bson.json_util.JSONOptions` provides a way to control how JSON
is emitted and parsed, with the default being the Relaxed Extended JSON format.
:mod:`~bson.json_util` can also generate Canonical or legacy `Extended JSON`_
when :const:`CANONICAL_JSON_OPTIONS` or :const:`LEGACY_JSON_OPTIONS` is
provided, respectively.

.. _Extended JSON: https://github.com/mongodb/specifications/blob/master/source/extended-json.rst

Example usage (deserialization):

.. doctest::

   >>> from bson.json_util import loads
   >>> loads(
   ...     '[{"foo": [1, 2]}, {"bar": {"hello": "world"}}, {"code": {"$scope": {}, "$code": "function x() { return 1; }"}}, {"bin": {"$type": "80", "$binary": "AQIDBA=="}}]'
   ... )
   [{'foo': [1, 2]}, {'bar': {'hello': 'world'}}, {'code': Code('function x() { return 1; }', {})}, {'bin': Binary(b'...', 128)}]

Example usage with :const:`RELAXED_JSON_OPTIONS` (the default):

.. doctest::

   >>> from bson import Binary, Code
   >>> from bson.json_util import dumps
   >>> dumps(
   ...     [
   ...         {"foo": [1, 2]},
   ...         {"bar": {"hello": "world"}},
   ...         {"code": Code("function x() { return 1; }")},
   ...         {"bin": Binary(b"")},
   ...     ]
   ... )
   '[{"foo": [1, 2]}, {"bar": {"hello": "world"}}, {"code": {"$code": "function x() { return 1; }"}}, {"bin": {"$binary": {"base64": "AQIDBA==", "subType": "00"}}}]'

Example usage (with :const:`CANONICAL_JSON_OPTIONS`):

.. doctest::

   >>> from bson import Binary, Code
   >>> from bson.json_util import dumps, CANONICAL_JSON_OPTIONS
   >>> dumps(
   ...     [
   ...         {"foo": [1, 2]},
   ...         {"bar": {"hello": "world"}},
   ...         {"code": Code("function x() { return 1; }")},
   ...         {"bin": Binary(b"")},
   ...     ],
   ...     json_options=CANONICAL_JSON_OPTIONS,
   ... )
   '[{"foo": [{"$numberInt": "1"}, {"$numberInt": "2"}]}, {"bar": {"hello": "world"}}, {"code": {"$code": "function x() { return 1; }"}}, {"bin": {"$binary": {"base64": "AQIDBA==", "subType": "00"}}}]'

Example usage (with :const:`LEGACY_JSON_OPTIONS`):

.. doctest::

   >>> from bson import Binary, Code
   >>> from bson.json_util import dumps, LEGACY_JSON_OPTIONS
   >>> dumps(
   ...     [
   ...         {"foo": [1, 2]},
   ...         {"bar": {"hello": "world"}},
   ...         {"code": Code("function x() { return 1; }", {})},
   ...         {"bin": Binary(b"")},
   ...     ],
   ...     json_options=LEGACY_JSON_OPTIONS,
   ... )
   '[{"foo": [1, 2]}, {"bar": {"hello": "world"}}, {"code": {"$code": "function x() { return 1; }", "$scope": {}}}, {"bin": {"$binary": "AQIDBA==", "$type": "00"}}]'

Alternatively, you can manually pass the `default` to :func:`json.dumps`.
It won't handle :class:`~bson.binary.Binary` and :class:`~bson.code.Code`
instances (as they are extended strings you can't provide custom defaults),
but it will be faster as there is less recursion.

.. note::
   If your application does not need the flexibility offered by
   :class:`JSONOptions` and spends a large amount of time in the `json_util`
   module, look to
   `python-bsonjs <https://pypi.python.org/pypi/python-bsonjs>`_ for a nice
   performance improvement. `python-bsonjs` is a fast BSON to MongoDB
   Extended JSON converter for Python built on top of
   `libbson <https://github.com/mongodb/libbson>`_. `python-bsonjs` works best
   with PyMongo when using :class:`~bson.raw_bson.RawBSONDocument`.
    )annotationsN)TYPE_CHECKINGAnyCallableMappingMutableMappingOptionalSequenceTupleTypeUnioncast)ALL_UUID_SUBTYPESUUID_SUBTYPEBinaryUuidRepresentation)Code)CodecOptionsDatetimeConversion)EPOCH_AWARE
DatetimeMS_datetime_to_millis_max_datetime_ms_millis_to_datetime)DBRef)
Decimal128)Int64)MaxKey)MinKey)ObjectId)Regex)RE_TYPE	Timestamp)utc)ilmsuxc                      e Zd ZdZ	 dZ	 dZdS )DatetimeRepresentationr         N)__name__
__module____qualname__LEGACY
NUMBERLONGISO8601     R/var/www/html/e360mart/e360mart_env/lib/python3.11/site-packages/bson/json_util.pyr-   r-      s1        F J G	 	r7   r-   c                      e Zd ZdZ	 dZ	 dZdS )JSONModer   r.   r/   N)r0   r1   r2   r3   RELAXED	CANONICALr6   r7   r8   r:   r:      s1        F G I r7   r:   l        c                       e Zd ZU ded<   ded<   ded<   ded<   ded<   d fdZdddej        fd fdZd fdZd fdZ	ddZ
 xZS )JSONOptionsint	json_modeboolstrict_number_longdatetime_representationstrict_uuidzType[MutableMapping[str, Any]]document_classargsr   kwargsc                H    t                                                       dS )a  Encapsulates JSON options for :func:`dumps` and :func:`loads`.

        :param strict_number_long: If ``True``, :class:`~bson.int64.Int64` objects
            are encoded to MongoDB Extended JSON's *Strict mode* type
            `NumberLong`, ie ``'{"$numberLong": "<number>" }'``. Otherwise they
            will be encoded as an `int`. Defaults to ``False``.
        :param datetime_representation: The representation to use when encoding
            instances of :class:`datetime.datetime`. Defaults to
            :const:`~DatetimeRepresentation.LEGACY`.
        :param strict_uuid: If ``True``, :class:`uuid.UUID` object are encoded to
            MongoDB Extended JSON's *Strict mode* type `Binary`. Otherwise it
            will be encoded as ``'{"$uuid": "<hex>" }'``. Defaults to ``False``.
        :param json_mode: The :class:`JSONMode` to use when encoding BSON types to
            Extended JSON. Defaults to :const:`~JSONMode.LEGACY`.
        :param document_class: BSON documents returned by :func:`loads` will be
            decoded to an instance of this class. Must be a subclass of
            :class:`collections.MutableMapping`. Defaults to :class:`dict`.
        :param uuid_representation: The :class:`~bson.binary.UuidRepresentation`
            to use when encoding and decoding instances of :class:`uuid.UUID`.
            Defaults to :const:`~bson.binary.UuidRepresentation.UNSPECIFIED`.
        :param tz_aware: If ``True``, MongoDB Extended JSON's *Strict mode* type
            `Date` will be decoded to timezone aware instances of
            :class:`datetime.datetime`. Otherwise they will be naive. Defaults
            to ``False``.
        :param tzinfo: A :class:`datetime.tzinfo` subclass that specifies the
            timezone from which :class:`~datetime.datetime` objects should be
            decoded. Defaults to :const:`~bson.tz_util.utc`.
        :param datetime_conversion: Specifies how UTC datetimes should be decoded
            within BSON. Valid options include 'datetime_ms' to return as a
            DatetimeMS, 'datetime' to return as a datetime.datetime and
            raising a ValueError for out-of-range values, 'datetime_auto' to
            return DatetimeMS objects when the underlying datetime is
            out-of-range and 'datetime_clamp' to clamp to the minimum and
            maximum possible datetimes. Defaults to 'datetime'. See
            :ref:`handling-out-of-range-datetimes` for details.
        :param args: arguments to :class:`~bson.codec_options.CodecOptions`
        :param kwargs: arguments to :class:`~bson.codec_options.CodecOptions`

        .. seealso:: The specification for Relaxed and Canonical `Extended JSON`_.

        .. versionchanged:: 4.0
           The default for `json_mode` was changed from :const:`JSONMode.LEGACY`
           to :const:`JSONMode.RELAXED`.
           The default for `uuid_representation` was changed from
           :const:`~bson.binary.UuidRepresentation.PYTHON_LEGACY` to
           :const:`~bson.binary.UuidRepresentation.UNSPECIFIED`.

        .. versionchanged:: 3.5
           Accepts the optional parameter `json_mode`.

        .. versionchanged:: 4.0
           Changed default value of `tz_aware` to False.
        N)super__init__)selfrF   rG   	__class__s      r8   rJ   zJSONOptions.__init__   s"    l 	r7   NclsType[JSONOptions]Optional[bool]Optional[int]returnc                   |                     dd          |d<   |d         r|                     dt                    |d<   |t          j        t          j        t          j        d fvrt          d          t          t           t                      j
        | g|R i |          }|t          j        t          j        t          j        fvrt          d          ||_        |j        t          j        k    rc|rt          d          |d t          j        fvrt          d          |dvrt          d	          d|_        t          j        |_        d
|_        n|j        t          j        k    re|dvrt          d          |d t          j        fvrt          d          |dvrt          d	          d
|_        t          j        |_        d
|_        n:d|_        t          j        |_        d|_        |||_        |||_        |||_        |S )Ntz_awareFtzinfoznJSONOptions.datetime_representation must be one of LEGACY, NUMBERLONG, or ISO8601 from DatetimeRepresentation.zQJSONOptions.json_mode must be one of LEGACY, RELAXED, or CANONICAL from JSONMode.z<Cannot specify strict_number_long=True with JSONMode.RELAXEDz_datetime_representation must be DatetimeRepresentation.ISO8601 or omitted with JSONMode.RELAXED)NTz6Cannot specify strict_uuid=False with JSONMode.RELAXEDTz=Cannot specify strict_number_long=False with JSONMode.RELAXEDzbdatetime_representation must be DatetimeRepresentation.NUMBERLONG or omitted with JSONMode.RELAXED)getr%   r-   r3   r4   r5   
ValueErrorr   r>   rI   __new__r:   r;   r<   r@   rB   rC   rD   )	rM   rB   rC   rD   r@   rF   rG   rK   rL   s	           r8   rW   zJSONOptions.__new__1  sU    $ZZ
E::z* 	9%zz(C88F8"")"-"*	+
 
 
 F   K!Ft!F!F!Fv!F!FGGX_h.>@RSSS.   #>X---! a !_```&t5K5S.TTT ?   ,.. !YZZZ&+D#+A+ID(#D^x111!55 !`aaa&t5K5V.WWW B   ,.. !YZZZ&*D#+A+LD(#D&+D#+A+HD($D!-*<'&2/F,&#. r7   strc                    d                     | j        | j        | j        | j        t                                                                S )Nz[strict_number_long={!r}, datetime_representation={!r}, strict_uuid={!r}, json_mode={!r}, {})formatrB   rC   rD   r@   rI   _arguments_repr)rK   rL   s    r8   r[   zJSONOptions._arguments_reprt  sF    3396', ''))4 4
	
r7   dict[Any, Any]c                    t                                                      }|                    | j        | j        | j        | j        d           |S )NrB   rC   rD   r@   )rI   _options_dictupdaterB   rC   rD   r@   )rK   options_dictrL   s     r8   r_   zJSONOptions._options_dict  sY    ww,,..&*&=+/+G#/!^	 	
 	
 	
 r7   c                    |                                  }dD ])}|                    |t          | |                    ||<   *|                    |           t	          di |S )a  
        Make a copy of this JSONOptions, overriding some options::

            >>> from bson.json_util import CANONICAL_JSON_OPTIONS
            >>> CANONICAL_JSON_OPTIONS.tz_aware
            True
            >>> json_options = CANONICAL_JSON_OPTIONS.with_options(tz_aware=False, tzinfo=None)
            >>> json_options.tz_aware
            False

        .. versionadded:: 3.12
        r^   r6   )r_   rU   getattrr`   r>   )rK   rG   optsopts       r8   with_optionszJSONOptions.with_options  sm     !!##` 	< 	<C

3c(:(:;;DIIF""T"""r7   )rF   r   rG   r   )rM   rN   rB   rO   rC   rP   rD   rO   r@   r?   rF   r   rG   r   rQ   r>   )rQ   rX   )rQ   r\   )rG   r   rQ   r>   )r0   r1   r2   __annotations__rJ   r:   r;   rW   r[   r_   rf   __classcell__)rL   s   @r8   r>   r>      s        NNN    22226 6 6 6 6 6t .215&*!)A A A A A A AF
 
 
 
 
 
     # # # # # # # #r7   r>   )r@   LEGACY_JSON_OPTIONSCANONICAL_JSON_OPTIONSRELAXED_JSON_OPTIONSDEFAULT_JSON_OPTIONSobjr   rF   rG   rQ   rX   c                ~    |                     dt                    }t          j        t	          | |          g|R i |S )aQ  Helper function that wraps :func:`json.dumps`.

    Recursive function that handles all BSON types including
    :class:`~bson.binary.Binary` and :class:`~bson.code.Code`.

    :param json_options: A :class:`JSONOptions` instance used to modify the
        encoding of MongoDB Extended JSON types. Defaults to
        :const:`DEFAULT_JSON_OPTIONS`.

    .. versionchanged:: 4.0
       Now outputs MongoDB Relaxed Extended JSON by default (using
       :const:`DEFAULT_JSON_OPTIONS`).

    .. versionchanged:: 3.4
       Accepts optional parameter `json_options`. See :class:`JSONOptions`.
    json_options)poprl   jsondumps_json_convert)rm   rF   rG   ro   s       r8   rr   rr     sB    " ::n.BCCL:mC66HHHHHHHr7   r)   Union[str, bytes, bytearray]c                    |                     dt                    j        t          u r	fd|d<   nfd|d<   t	          j        | g|R i |S )a  Helper function that wraps :func:`json.loads`.

    Automatically passes the object_hook for BSON type conversion.

    Raises ``TypeError``, ``ValueError``, ``KeyError``, or
    :exc:`~bson.errors.InvalidId` on invalid MongoDB Extended JSON.

    :param json_options: A :class:`JSONOptions` instance used to modify the
        decoding of MongoDB Extended JSON types. Defaults to
        :const:`DEFAULT_JSON_OPTIONS`.

    .. versionchanged:: 4.0
       Now loads :class:`datetime.datetime` instances as naive by default. To
       load timezone aware instances utilize the `json_options` parameter.
       See :ref:`tz_aware_default_change` for an example.

    .. versionchanged:: 3.5
       Parses Relaxed and Canonical Extended JSON as well as PyMongo's legacy
       format. Now raises ``TypeError`` or ``ValueError`` when parsing JSON
       type wrappers with values of the wrong type or any extra keys.

    .. versionchanged:: 3.4
       Accepts optional parameter `json_options`. See :class:`JSONOptions`.
    ro   c                $    t          |           S N)object_hookrm   ro   s    r8   <lambda>zloads.<locals>.<lambda>  s    K\,J,J r7   rx   c                $    t          |           S rw   )object_pairs_hookpairsro   s    r8   rz   zloads.<locals>.<lambda>  s    4Ee\4Z4Z r7   r|   )rp   rl   rE   dictrq   loads)r)   rF   rG   ro   s      @r8   r   r     sq    2 ::n.BCCL"d** J J J J}&Z&Z&Z&Z"#:a)$)))&)))r7   ro   c                   t          | d          r fd|                                 D             S t          | d          r*t          | t          t          f          sfd| D             S 	 t          |           S # t          $ r | cY S w xY w)z]Recursive helper method that converts BSON types so they can be
    converted into json.
    itemsc                8    i | ]\  }}|t          |          S r6   rs   ).0kvro   s      r8   
<dictcomp>z!_json_convert.<locals>.<dictcomp>  s)    JJJda=L11JJJr7   __iter__c                0    g | ]}t          |          S r6   r   )r   r   ro   s     r8   
<listcomp>z!_json_convert.<locals>.<listcomp>  s#    <<<1a..<<<r7   )hasattrr   
isinstancerX   bytesdefault	TypeErrorry   s    `r8   rs   rs     s     sG =JJJJciikkJJJJ	j	!	! =*S3,*G*G =<<<<<<<<sL)))   


s   -A= =BBr~   Sequence[Tuple[str, Any]]c                H    t          |                    |           |          S rw   )rx   rE   r}   s     r8   r|   r|     s"     |22599<HHHr7   dctMapping[str, Any]c                ^    d }| D ]}|t           v r|} n|rt          |         | |          S | S rw   )_PARSERS_SET_PARSERS)r   ro   matchr   s       r8   rx   rx     sS    E  EE   2sL111Jr7   docdummy0c                    | d         }t          |t          t          f          s| S d}|                     dd          D ] }|t                              |d          z  }!t          ||          S )N$regexr   $options )r   rX   r   rU   _RE_OPT_TABLEr!   )r   r   patternflagsre   s        r8   _parse_legacy_regexr     st    (mGgU|,, 
Ewwz2&& + +""3***%   r7   Union[Binary, uuid.UUID]c                \   t          |           dk    rt          d|            t          | d         t                    st          d|            |j        t
          j        k    r,t          j        t          j
        | d                             S t          j
        | d                   S )z*Decode a JSON legacy $uuid to Python UUID.r.   zBad $uuid, extra field(s): $uuidz$uuid must be a string: )lenr   r   rX   uuid_representationr   UNSPECIFIEDr   	from_uuiduuidUUIDr   ro   s     r8   _parse_legacy_uuidr   )  s    
3xx1}};c;;<<<c'lC(( :8388999'+=+III	#g, 7 7888yW&&&r7   datasubtyper?   c                X   |t           v rr|j        }t          | |          }|t          j        k    r|S |t
          k    rt          j        }n|t          j        k    rt          j        }|                    |          S |dk    rt          t          j        |           S t          | |          S Nr   )r   r   r   r   r   r   STANDARDPYTHON_LEGACYas_uuidr   r   r   )r   r   ro   r   binary_values        r8   _binary_or_uuidr   5  s    ###*>dG,,"4"@@@l"""4"= $6$??? #5"B##$7888!||DIt$$$$   r7   c                B   t          | d         t                    rd| d         z  | d<   t          | d         d          }|dk    rt          | d         dd          d          }t          j        | d                                                   }t          |||          S )N$type%02x   l       $binary)r   r?   base64	b64decodeencoder   )r   ro   r   r   s       r8   _parse_legacy_binaryr   J  s    #g,$$ -G,G#g,##G*c'l122&++C	N113344D4,777r7   c                   | d         }|d         }|d         }t          |t                    st          d|            t          |t                    rt          |          dk    rt          d|            t          |          dk    rt          d|            t	          j        |                                          }t          |t          |d          |          S )	Nr   r   subTypez!$binary base64 must be a string: r/   z7$binary subType must be a string at most 2 characters: z=$binary must include only "base64" and "subType" components: r   )	r   rX   r   r   r   r   r   r   r?   )r   ro   binaryb64r   r   s         r8   _parse_canonical_binaryr   T  s    ^F

CYGc3 CACAABBBgs## Ys7||a'7'7WRUWWXXX
6{{a]X[]]^^^CJJLL))D4Wb!1!1<@@@r7   $Union[datetime.datetime, DatetimeMS]c                   | d         }t          |           dk    rt          d|            t          |t                    r|d         dk    r|dd         }d}nm|d         dv r!|d	         d
k    r|dd         }|dd         }nB|d         dv r|dd         }|dd         }n#|d	         dv r|dd	         }|d	d         }n|}d}|                    d          }d}|dk    r1t          t          ||d                   dz            }|d|         }t          j                            |d          	                    |t                    }|r|dk    rt          |          dk    rF|dd                             d
          \  }}	t          |          dz  t          |	          dz  z   }
nvt          |          dk    r6t          |dd                   dz  t          |dd                   dz  z   }
n-t          |          dk    rt          |dd                   dz  }
|d         dk    r|
dz  }
|t          j        |
          z
  }|j        rG|j        r|                    |j                  }|j        t"          j        k    rt'          |          S |S |	                    d          }|j        t"          j        k    rt'          |          S |S t)          t          |          t+          d|                    S )z3Decode a JSON datetime to python datetime.datetime.$dater.   zBad $date, extra field(s): ZNi)+-:r   .r   i@B %Y-%m-%dT%H:%M:%S)microsecondrT   r   i  <         r   )secondsrT   zCodecOptions[Any])r   r   r   rX   rfindr?   floatdatetimestrptimereplacer%   split	timedeltarS   rT   
astimezonedatetime_conversionr   DATETIME_MSr   r   r   )r   ro   dtmdtoffset	dot_indexr   awarehoursminutessecsaware_tzinfo_nones               r8   _parse_canonical_datetimer   c  s0    g,C
3xx1}};c;;<<<#s 6%r7c>>SbSBFFW
""s2w#~~SbSBXFFW
""SbSBXFFW
""SbSBXFFBF HHSMM	??eByzzN33g=>>KJYJB!**2/BCCKK#C L 
 
  
	=fmm6{{a!'!1!1#!6!6w5zzD(3w<<"+<<V!!6!A#;''$.VABBZ21EEV!!6!A#;''$.ayC
H.t<<<<E  
	%" >(()<==/3E3QQQ!%(((L %T : :/3E3QQQ!"3444$$s3xx.A<)P)PQQQr7   r    c                v    t          |           dk    rt          d|            t          | d                   S )z1Decode a JSON ObjectId to bson.objectid.ObjectId.r.   zBad $oid, extra field(s): $oid)r   r   r    r   r   s     r8   _parse_canonical_oidr     s:    
3xx1}}:S::;;;CK   r7   c                z    | d         }t          |           dk    rt          d|            t          |          S )z&Decode a JSON symbol to Python string.$symbolr.   zBad $symbol, extra field(s): )r   r   rX   )r   r   symbols      r8   _parse_canonical_symbolr     s=    ^F
3xx1}}===>>>v;;r7   r   c                    | D ]}|dvrt          d|            t          | d         |                     d                    S )z%Decode a JSON code to bson.code.Code.$code$scopezBad $code, extra field(s): r   r   )scope)r   r   rU   )r   r   keys      r8   _parse_canonical_coder     s^     A A)))?#??@@@ *GCGGH$5$56666r7   
Regex[str]c                J   | d         }t          |           dk    rt          d|            t          |          dk    rt          d|            |d         }t          |t                    st          dt	          |          z            t          |d         |          S )	z(Decode a JSON regex to bson.regex.Regex.$regularExpressionr.   z(Bad $regularExpression, extra field(s): r/   zLBad $regularExpression must include only "pattern and "options" components: optionszCBad $regularExpression options, options must be string, was type %sr   )r   r   r   rX   typer!   )r   r   regexrd   s       r8   _parse_canonical_regexr    s    $%E
3xx1}}H3HHIII
5zzQ`[^``
 
 	
 DdC   
QUYZ^U_U_`
 
 	
 y!4(((r7   c                `   t          |                     d          t                    rd| v rt          |                     d          t          t          d          f          rJt	          |                     d          |                     d          fd|                     dd          i| S | S )z(Decode a JSON DBRef to bson.dbref.DBRef.$refz$idz$dbNdatabase)r   rU   rX   r   r   rp   r   s     r8   _parse_canonical_dbrefr    s     	3776??C((\SLLswwu~~T$ZZ'899  SWWV__cggenn[[swwud?S?S[WZ[[[Jr7   c                   | d         }t          |           dk    rt          d|            t          |t                    r|                                }|j        t          d|           t          |j        t                    st          d|           t          |          dk    rt          d|           |S t          d	|            )
z9Decode a JSON (deprecated) DBPointer to bson.dbref.DBRef.
$dbPointerr.   z Bad $dbPointer, extra field(s): Nz!Bad $dbPointer, extra field $db: z)Bad $dbPointer, $id must be an ObjectId: r/   z)Bad $dbPointer, extra field(s) in DBRef: z"Bad $dbPointer, expected a DBRef: )r   r   r   r   as_docr  idr    )r   r   dbref	dbref_docs       r8   _parse_canonical_dbpointerr    s    E
3xx1}}@3@@AAA% DLLNN	>%K	KKLLL%(H-- 	US	SSTTTy>>QS	SSTTTBSBBCCCr7   c                    | d         }t          |           dk    rt          d|            t          |t                    st          d|            t	          |          S )z"Decode a JSON int32 to python int.
$numberIntr.   z Bad $numberInt, extra field(s): z$numberInt must be string: )r   r   r   rX   r?   )r   r   i_strs      r8   _parse_canonical_int32r    sg    E
3xx1}}@3@@AAAeS!! =;c;;<<<u::r7   r   c                z    | d         }t          |           dk    rt          d|            t          |          S )z(Decode a JSON int64 to bson.int64.Int64.$numberLongr.   z!Bad $numberLong, extra field(s): )r   r   r   )r   r   l_strs      r8   _parse_canonical_int64r    s>    E
3xx1}}ACAABBB<<r7   r   c                    | d         }t          |           dk    rt          d|            t          |t                    st          d|            t	          |          S )z%Decode a JSON double to python float.$numberDoubler.   z#Bad $numberDouble, extra field(s): z$numberDouble must be string: )r   r   r   rX   r   r   r   d_strs      r8   _parse_canonical_doubler    sh     E
3xx1}}CcCCDDDeS!! @>>>???<<r7   r   c                    | d         }t          |           dk    rt          d|            t          |t                    st          d|            t	          |          S )z7Decode a JSON decimal128 to bson.decimal128.Decimal128.$numberDecimalr.   z$Bad $numberDecimal, extra field(s): z$numberDecimal must be string: )r   r   r   rX   r   r  s      r8   _parse_canonical_decimal128r    sk     !E
3xx1}}DsDDEEEeS!! A?#??@@@er7   r   c                    t          | d                   t          us| d         dk    rt          d|            t          |           dk    rt          d|            t	                      S )z,Decode a JSON MinKey to bson.min_key.MinKey.$minKeyr.   z$minKey value must be 1: Bad $minKey, extra field(s): )r   r?   r   r   r   r   s     r8   _parse_canonical_minkeyr     sm    C	N3&&#i.A*=*=9C99:::
3xx1}}===>>>88Or7   r   c                    t          | d                   t          us| d         dk    rt          d| f          t          |           dk    rt          d|            t	                      S )z,Decode a JSON MaxKey to bson.max_key.MaxKey.$maxKeyr.   z$maxKey value must be 1: %sr  )r   r?   r   r   r   r   s     r8   _parse_canonical_maxkeyr#    si    C	N3&&#i.A*=*=5v>>>
3xx1}}===>>>88Or7   c                J    d| v rt          | |          S t          | |          S )Nr   )r   r   r   s     r8   _parse_binaryr%  #  s+    #~~#C666&sL999r7   r$   c                J    | d         }t          |d         |d                   S )N
$timestamptr&   r#   )r   r   tsps      r8   _parse_timestampr*  *  s$    
l
CSXs3x(((r7   r   r  r   r   r  r"  r   r   r   z
$undefinedc                    d S rw   r6   )__1s     r8   rz   rz   9  s     r7   r  r'  r  r  r   r   r  r  z,dict[str, Callable[[Any, JSONOptions], Any]]r   r   c                    |j         t          j        k    r,t          j        |                                           d|z  dS dt          j        |                                           d|z  diS )Nr   )r   r   r   )r   r   )r@   r:   r3   r   	b64encodedecode)r   r   ro   s      r8   _encode_binaryr1  F  sl    00!+D1188::VgEUVVV&"24"8"8"?"?"A"AfW^N^__``r7   r   c                h   |j         t          j        k    rKdt          |           cxk    rt	                      k    r%n n"t          |                                 |          S |j         t          j        k    rdt          t          |                     iS ddt          t          |                     iiS )Nr   r   r  )	rC   r-   r5   r?   r   _encode_datetimeas_datetimer3   rX   ry   s     r8   _encode_datetimemsr5  L  s    ,0F0NNNS////-/////// 1 1<@@@		-1G1N	N	NSXX''mSS]]344r7   c                |    | j         dt          |           iS t          |           t          | j         |          dS )Nr   r   )r   rX   rs   ry   s     r8   _encode_coder7  W  s;    
yS""S]39l-S-STTTr7   c                P    |j         rdt          |           iS t          |           S )Nr  )rB   rX   r?   ry   s     r8   _encode_int64r9  ^  s)    & s3xx((3xxr7   c                    | S rw   r6   rm   r   s     r8   _encode_noopr<  e  s    Jr7   c                   d}| j         t          j        z  r|dz  }| j         t          j        z  r|dz  }| j         t          j        z  r|dz  }| j         t          j        z  r|dz  }| j         t          j        z  r|dz  }| j         t          j        z  r|dz  }t          | j	        t                    r| j	        }n| j	                            d          }|j        t          j        k    r||d	S d
||diS )Nr   r&   r'   r(   r)   r*   r+   zutf-8)r   r   r   )r   r   )r   re
IGNORECASELOCALE	MULTILINEDOTALLUNICODEVERBOSEr   r   rX   r0  r@   r:   r3   )rm   ro   r   r   s       r8   _encode_regexrE  i  s   E
y2=  
y29 
y2< 
y29 
y2: 
y2: #+s## .++$$W--00!u555 g%"H"HIIr7   c                    |j         t          j        k    r=t           | cxk    rt          k     rn ndt	          |           iS dt	          |           iS | S )Nr  r  )r@   r:   r<   
_INT32_MAXrX   ry   s     r8   _encode_intrH    s^    !333;#****
***** #c((++s3xx((Jr7   c                
   |j         t          j        k    rmt          j        |           rddiS t          j        |           r| dk    rdnd}d|iS |j         t          j        k    rdt          t          |                     iS | S )Nr  NaNr   Infinityz	-Infinity)	r@   r:   r3   mathisnanisinfr<   rX   repr)rm   ro   representations      r8   _encode_floatrQ    s    00:c?? 	5#U++Z__ 	5+.77ZZN#^44#x'999 $Sc^^44Jr7   datetime.datetimec                <   |j         t          j        k    r| j        s$|                     t
                    } | j        J | t          k    r| j                            |           }|j        |j	        |j
        fdk    rd}n|                     d          }t          | j        dz            }|rd|fz  nd}dd	                    |                     d
          ||          iS t          |           }|j         t          j        k    rd|iS ddt#          |          iiS )Nr   )r   r   r   r   z%zi  z.%03dr   r   z{}{}{}r   r  )rC   r-   r5   rT   r   r%   r   	utcoffsetdaysr   microsecondsstrftimer?   r   rZ   r   r3   rX   )rm   ro   off	tz_stringmillisfracsecss         r8   r3  r3    s)   +/E/MMMz 	*++S+))C:)))+*&&s++C#+s'78IEE		LL..	4/00F.4<w&**"H6I)J)JHV_``  !%%F+/E/LLL  mS[[122r7   c                $    t          | d|          S r   )r1  ry   s     r8   _encode_bytesr]    s    #q,///r7   r   c                .    t          | | j        |          S rw   )r1  r   ry   s     r8   _encode_binary_objr_    s    #s{L999r7   	uuid.UUIDc                    |j         r1t          j        | |j                  }t	          ||j        |          S d| j        iS )N)r   r   )rD   r   r   r   r1  r   hex)rm   ro   binvals      r8   _encode_uuidrd    sF     "!#<;[\\\ffnlCCC!!r7   c                $    dt          |           iS )Nr   rX   r;  s     r8   _encode_objectidrg    s    CHHr7   c                $    d| j         | j        diS )Nr'  )r(  r&   )timeincr;  s     r8   _encode_timestamprk    s    sw7788r7   c                $    dt          |           iS )Nr  rf  r;  s     r8   _encode_decimal128rm    s    c#hh''r7   r   c                H    t          |                                 |          S )N)ro   )rs   r  ry   s     r8   _encode_dbrefro    s    LAAAAr7   dummy1c                
    ddiS )Nr  r.   r6   r   rp  s     r8   _encode_minkeyrs        q>r7   c                
    ddiS )Nr"  r.   r6   rr  s     r8   _encode_maxkeyrv    rt  r7   z-dict[Type, Callable[[Any, JSONOptions], Any]]	_ENCODERSz,dict[int, Callable[[Any, JSONOptions], Any]]_MARKERS_type_markerc              #     K   | ]}|V  d S rw   r6   )r   r(  s     r8   	<genexpr>r{    s"      --a------r7   c                   	 t          t          |                    | |          S # t          $ r Y nw xY wt          | d          r@| j        }|t
          v r0t
          |         }|t           t          |           <    || |          S t          D ]D}t          | |          r2t           |         }|t           t          |           <    || |          c S Et          d| z            )Nry  z%r is not JSON serializable)	rw  r   KeyErrorr   ry  rx  _BUILT_IN_TYPESr   r   )rm   ro   markerfuncbases        r8   r   r     s   c#C666    sN## +!XF#D#'Id3ii 4\***   + +c4   	+T?D#'Id3ii 4\*****		+ 1C7
8
88s   "% 
22c                     t          |           S rw   )r   rm   s    r8   _get_str_sizer    s    s88Or7   c                d    dt          t          |                                                     z   S )Nr   )r   rX   ri  r  s    r8   _get_datetime_sizer    s#    s3sxxzz??####r7   r!   c                0    dt          | j                  z   S )N   )r   r   r  s    r8   _get_regex_sizer     s    CK    r7   c                0    dt          | j                  z   S )N"   )r   
collectionr  s    r8   _get_dbref_sizer  $  s    CN####r7               zdict[Any, int]_CONSTANT_SIZE_TABLEzdict[Any, Callable[[Any], int]]_VARIABLE_SIZE_TABLEmax_sizecurrent_sizec                   ||k    r|S t          |           }	 t          |         S # t          $ r Y nw xY w	 t          |         |           S # t          $ r Y nw xY w|t          k    r_| j        rB|dt          | j        ||          z   t          |           z   t          | j                  z
  z  }n|dt          |           z   z  }n|t          k    rM| 	                                D ]7\  }}|t          |||          z  }|t          |||          z  }||k    r|c S 8n3t          | d          r#| D ] }|t          |||          z  }||k    r|c S !|S )z!Recursively finds size of objectsr   r   )r   r  r}  r  r   r   get_sizer   r   r   r   )rm   r  r  obj_typer   r   r&   s          r8   r  r  ;  s   xCyyH#H--   #H-c222    49 	)HSY,???#c((JSQTQZ^^[LL ACL(LL	T		IIKK 	$ 	$DAqHQ,???LHQ,???Lx''#### (	$
 
j	!	! $ 	$ 	$AHQ,???Lx''#### (s   & 
33A 
AA
max_lengthTuple[Any, int]c                   |dk    rdS |}t          | d          rBi }|                                 D ]'\  }}t          ||          \  }}|r|||<   |dk    r n(||fS t          | d          rYt          | t          t
          f          s=g }| D ]4}t          ||          \  }}|r|                    |           |dk    r n5||fS t          | |          S )zMRecursively truncate documents as needed to fit inside max_length characters.r   r   r   r   )r   r   _truncate_documentsr   rX   r   append	_truncate)rm   r  	remaining	truncatedr   r   truncated_vs          r8   r  r  d  s#   QwIsG )	IIKK 	 	DAq%8I%F%F"K +*	!A~~ )##	j	!	! 
)*S3,*G*G 
)	 	 	A%8I%F%F"K .  ---A~~ )##i(((r7   r  c                    t          | |          }||k    r| ||z
  fS 	 | d |         }n# t          $ r | }Y nw xY w|||z
  fS rw   )r  r   )rm   r  sizer  s       r8   r  r    st    C##DyI$$$	JYJII 	 	 	III	)d***s   
* 99)rm   r   rF   r   rG   r   rQ   rX   )r)   rt   rF   r   rG   r   rQ   r   )rm   r   ro   r>   rQ   r   )r~   r   ro   r>   rQ   r   )r   r   ro   r>   rQ   r   )r   r   r   r   rQ   r   )r   r   ro   r>   rQ   r   )r   r   r   r?   ro   r>   rQ   r   )r   r   ro   r>   rQ   r   )r   r   r   r   rQ   r    )r   r   r   r   rQ   rX   )r   r   r   r   rQ   r   )r   r   r   r   rQ   r   )r   r   r   r   rQ   r?   )r   r   r   r   rQ   r   )r   r   r   r   rQ   r   )r   r   r   r   rQ   r   )r   r   r   r   rQ   r   )r   r   r   r   rQ   r   )r   r   r   r   rQ   r$   )r   r   r   r?   ro   r>   rQ   r   )rm   r   ro   r>   rQ   r   )rm   r   ro   r>   rQ   r   )rm   r   ro   r>   rQ   r   )rm   r   r   r   rQ   r   )rm   r?   ro   r>   rQ   r   )rm   r   ro   r>   rQ   r   )rm   rR  ro   r>   rQ   r   )rm   r   ro   r>   rQ   r   )rm   r   ro   r>   rQ   r   )rm   r`  ro   r>   rQ   r   )rm   r    r   r   rQ   r   )rm   r$   r   r   rQ   r   )rm   r   ro   r>   rQ   r   )r   r   rp  r   rQ   r   )rm   r   rQ   r?   )rm   rR  rQ   r?   )rm   r!   rQ   r?   )rm   r   rQ   r?   )r   )rm   r   r  r?   r  r?   rQ   r?   )rm   r   r  r?   rQ   r  )rm   r   r  r?   rQ   r  )__doc__
__future__r   r   r   rq   rL  r>  r   typingr   r   r   r   r   r	   r
   r   r   r   r   bson.binaryr   r   r   r   	bson.coder   bson.codec_optionsr   r   bson.datetime_msr   r   r   r   r   
bson.dbrefr   bson.decimal128r   
bson.int64r   bson.max_keyr   bson.min_keyr   bson.objectidr    
bson.regexr!   bson.sonr"   bson.timestampr$   bson.tz_utilr%   ILMSUXr   r-   r:   rX   _BASE_CLASSrG  r>   r3   ri   rg   r<   rj   r;   rk   rl   rr   r   rs   r|   rx   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r  r  r   r#  r%  r*  r   setr   r1  r5  r7  r9  r<  rE  rH  rQ  r3  r]  r_  rd  rg  rk  rm  ro  rs  rv  rA   r   r   r?   r   r   rw  rx  _typr   ry  tupler~  r   r  r  r  r  r  r  r  r  r  r6   r7   r8   <module>r     s	  V V Vn # " " " " "     				                           T S S S S S S S S S S S       ? ? ? ? ? ? ? ?                    & & & & & &                   " " " " " "             $ $ $ $ $ $       
					 ! ! ! ! ! ! ! !H( ( ( ( ( ( ( (V  ~c3h78KKK
m# m# m# m# m#+ m# m# m#` $/;#I#I#I  I I I I '2kH<N&O&O&O  O O O O %0K(:J$K$K$K  K K K K %9  8 8 8 8	I I I I** * * *D 9M      CWI I I I I EY     	! 	! 	! 	!	' 	' 	' 	'! ! ! !*8 8 8 8A A A A?R ?R ?R ?RD! ! ! !   7 7 7 7) ) ) )"   D D D D&                  : : : :) ) ) )
:
 :
": &: !	:
 &: &: }: ": : $$: ): ": 1: ,: 0:  &!:" (#:$ ,%: :    ( s8}}a a a a5 5 5 5U U U U      J J J J.      3 3 3 3.0 0 0 0: : : :" " " "   9 9 9 9( ( ( (B B B B      <,<	=< '< "	<
 
=< < < 	DJJ< 	I|< < 
=< 	,< 
=< N< N<  !<" 
=#<$ ] ")< <	    0 :< ; ; ; ; 6 6Dwt^$$ 6&/o"#%--9----- 3G 9 9 9 9 9>   $ $ $ $! ! ! !$ $ $ $
 b	2r
A
A(      	=)	?	?9     & & & & &R) ) ) )6
+ 
+ 
+ 
+ 
+ 
+r7   