cmi-python 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cmi/__init__.py ADDED
@@ -0,0 +1,92 @@
1
+ """cmi-python: Python SDK for the CMI payment gateway (Centre Monétique Interbancaire, Morocco).
2
+
3
+ Two kits, one package:
4
+
5
+ - **Standard kit** (:mod:`cmi.standard`): signs the payment form that sends the customer to
6
+ CMI's payment page, and verifies CMI's callback. Adapters for Django, Flask and
7
+ FastAPI/Starlette live in :mod:`cmi.adapters`.
8
+ - **API kit** (:mod:`cmi.api`): captures, refunds, voids and checks orders through CMI's
9
+ back-office XML API.
10
+
11
+ Everything is re-exported here, so ``from cmi import CMIPaymentGateway, CMIApiClient`` works.
12
+ """
13
+
14
+ from ._amount import format_amount
15
+ from ._log import logger
16
+ from ._security import SecretString
17
+ from .api import (
18
+ AsyncCMIApiClient,
19
+ CMIApiClient,
20
+ CMIApiResponse,
21
+ CMIOrderHistoryEntry,
22
+ CMIOrderHistoryResult,
23
+ CMIOrderStatus,
24
+ CMIOrderStatusResult,
25
+ CMIOrderTransaction,
26
+ CMITransactionResult,
27
+ HttpPost,
28
+ HttpResponse,
29
+ )
30
+ from .constants import (
31
+ SUPPORTED_ACCOUNT_TYPES,
32
+ SUPPORTED_CONFIRMATION_MODES,
33
+ SUPPORTED_CURRENCIES,
34
+ SUPPORTED_LANGUAGES,
35
+ SUPPORTED_STORE_TYPES,
36
+ SUPPORTED_TRAN_TYPES,
37
+ AccountType,
38
+ ConfirmationMode,
39
+ )
40
+ from .errors import CMIApiError, CMIApiErrorCode, CMIError, CMIValidationError
41
+ from .standard import (
42
+ CallbackAnswer,
43
+ CallbackHandler,
44
+ CallbackResult,
45
+ CallbackStatus,
46
+ CMIPaymentGateway,
47
+ OrderData,
48
+ parse_form_body,
49
+ )
50
+
51
+ __version__ = "1.0.0"
52
+
53
+ __all__ = [
54
+ "__version__",
55
+ # Standard kit
56
+ "CMIPaymentGateway",
57
+ "CallbackHandler",
58
+ "CallbackResult",
59
+ "CallbackAnswer",
60
+ "CallbackStatus",
61
+ "OrderData",
62
+ "parse_form_body",
63
+ # API kit
64
+ "CMIApiClient",
65
+ "AsyncCMIApiClient",
66
+ "CMIApiResponse",
67
+ "CMITransactionResult",
68
+ "CMIOrderStatus",
69
+ "CMIOrderTransaction",
70
+ "CMIOrderStatusResult",
71
+ "CMIOrderHistoryEntry",
72
+ "CMIOrderHistoryResult",
73
+ "HttpPost",
74
+ "HttpResponse",
75
+ # Errors
76
+ "CMIError",
77
+ "CMIValidationError",
78
+ "CMIApiError",
79
+ "CMIApiErrorCode",
80
+ # Values and helpers
81
+ "SUPPORTED_CURRENCIES",
82
+ "SUPPORTED_LANGUAGES",
83
+ "SUPPORTED_STORE_TYPES",
84
+ "SUPPORTED_TRAN_TYPES",
85
+ "SUPPORTED_CONFIRMATION_MODES",
86
+ "SUPPORTED_ACCOUNT_TYPES",
87
+ "ConfirmationMode",
88
+ "AccountType",
89
+ "SecretString",
90
+ "format_amount",
91
+ "logger",
92
+ ]
cmi/_amount.py ADDED
@@ -0,0 +1,58 @@
1
+ """Amount formatting shared by every kit (payment page fields and API requests)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import re
7
+ from decimal import Decimal
8
+ from typing import Union
9
+
10
+ from ._compat import js_number_to_string, js_trim
11
+ from .errors import CMIValidationError
12
+
13
+ AmountInput = Union[int, float, Decimal, str]
14
+
15
+ _AMOUNT = re.compile(r"(-?)([0-9]*)(?:\.([0-9]+))?")
16
+
17
+
18
+ def format_amount(amount: AmountInput) -> str:
19
+ """Format an amount for CMI, with exactly 2 decimals.
20
+
21
+ Any number of decimals is accepted. Amounts with more than 2 decimals are rounded
22
+ half-up to the cent, the way CMI's gateway does it ("125.6578" -> "125.66",
23
+ "1.005" -> "1.01"). The rounding works on the decimal digits, never on a binary
24
+ float, so the charged amount is known exactly. Prefer ``Decimal`` or ``str`` amounts.
25
+ """
26
+ if isinstance(amount, bool):
27
+ raise CMIValidationError(f'Invalid amount format: "{amount}". Amount must be a number.')
28
+ if isinstance(amount, float):
29
+ if not math.isfinite(amount):
30
+ raise CMIValidationError("Amount must be a valid finite number")
31
+ # Shortest decimal that round-trips: 1.005 -> "1.005", 19.99 * 3 -> "59.97000000000001".
32
+ text = js_number_to_string(amount)
33
+ elif isinstance(amount, int):
34
+ text = str(amount)
35
+ elif isinstance(amount, Decimal):
36
+ if not amount.is_finite():
37
+ raise CMIValidationError("Amount must be a valid finite number")
38
+ text = format(amount, "f")
39
+ elif isinstance(amount, str):
40
+ text = js_trim(amount)
41
+ else:
42
+ text = ""
43
+
44
+ match = _AMOUNT.fullmatch(text)
45
+ if not match or (match.group(2) == "" and match.group(3) is None):
46
+ raise CMIValidationError(
47
+ f'Invalid amount format: "{amount}". Amount must contain only numeric characters (e.g., "220" or "220.50")'
48
+ )
49
+
50
+ sign, integer_digits, fraction_digits = match.group(1), match.group(2), match.group(3) or ""
51
+ # Whole cents as an int, so very long inputs stay exact.
52
+ cents = int((integer_digits or "0") + fraction_digits[:2].ljust(2, "0"))
53
+ if len(fraction_digits) > 2 and fraction_digits[2] >= "5":
54
+ cents += 1 # half-up (away from zero)
55
+
56
+ whole, fraction = divmod(cents, 100)
57
+ negative = sign == "-" and cents != 0
58
+ return f"{'-' if negative else ''}{whole}.{fraction:02d}"
cmi/_cc5/__init__.py ADDED
@@ -0,0 +1,19 @@
1
+ """CC5: CMI's XML API format and transport, shared by the kits that call it."""
2
+
3
+ from .transport import MAX_RESPONSE_BYTES, CC5Transport, HttpPost, HttpResponse, require_text, urllib_http_post
4
+ from .xml import CC5Node, CC5Response, CC5XmlError, build_cc5_request, escape_xml, parse_cc5_response
5
+
6
+ __all__ = [
7
+ "MAX_RESPONSE_BYTES",
8
+ "CC5Node",
9
+ "CC5Response",
10
+ "CC5Transport",
11
+ "CC5XmlError",
12
+ "HttpPost",
13
+ "HttpResponse",
14
+ "build_cc5_request",
15
+ "escape_xml",
16
+ "parse_cc5_response",
17
+ "require_text",
18
+ "urllib_http_post",
19
+ ]
cmi/_cc5/transport.py ADDED
@@ -0,0 +1,255 @@
1
+ """CC5 transport: sends one CC5Request to CMI's XML API and reads the CC5Response.
2
+
3
+ - The request is posted as the form field ``DATA=<?xml ...?><CC5Request>...</CC5Request>``,
4
+ with the API user's Name, Password and ClientId first.
5
+ - https only (plain http only for localhost); redirects are refused, so the credentials are
6
+ never resent to another URL.
7
+ - One attempt only: nothing is retried automatically (see CMIApiError).
8
+ - Standard library only (urllib). Pass ``http_post`` to use another HTTP client.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import codecs
14
+ import math
15
+ import re
16
+ import time
17
+ import urllib.error
18
+ import urllib.request
19
+ from collections.abc import Callable, Mapping, Sequence
20
+ from dataclasses import dataclass, field
21
+ from typing import Any
22
+ from urllib.parse import urlencode
23
+
24
+ from .._compat import js_trim
25
+ from .._log import logger
26
+ from .._security import SecretString
27
+ from .._validation import is_secure_or_local_url
28
+ from ..errors import CMIApiError, CMIValidationError
29
+ from .xml import CC5Node, CC5Response, CC5XmlError, build_cc5_request, parse_cc5_response
30
+
31
+ __all__ = ["MAX_RESPONSE_BYTES", "CC5Transport", "HttpPost", "HttpResponse", "require_text", "urllib_http_post"]
32
+
33
+ DEFAULT_TIMEOUT = 30.0
34
+ MAX_TIMEOUT = 300.0
35
+ #: CMI's answers are a few kilobytes; anything far bigger is not a CC5Response.
36
+ MAX_RESPONSE_BYTES = 1024 * 1024
37
+ MAX_CLIENT_ID_LENGTH = 15
38
+ MAX_CREDENTIAL_LENGTH = 255
39
+ _CONTROL_CHARS = re.compile("[\x00-\x1f\x7f]")
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class HttpResponse:
44
+ """What an ``http_post`` function returns."""
45
+
46
+ status: int
47
+ #: Response headers, names in lower case.
48
+ headers: Mapping[str, str] = field(default_factory=dict)
49
+ body: bytes = b""
50
+
51
+
52
+ #: ``http_post(url, body, headers, timeout) -> HttpResponse``. Raise TimeoutError on a
53
+ #: timeout and OSError (or any exception) on a network failure; never follow redirects.
54
+ HttpPost = Callable[[str, bytes, Mapping[str, str], float], HttpResponse]
55
+
56
+
57
+ class _ResponseTooLarge(Exception):
58
+ pass
59
+
60
+
61
+ class _RedirectRefused(urllib.error.URLError):
62
+ pass
63
+
64
+
65
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
66
+ """A redirect would resend the credentials to another URL: refuse it."""
67
+
68
+ def redirect_request(self, req: Any, fp: Any, code: int, msg: str, headers: Any, newurl: str) -> None: # noqa: PLR0917 - urllib's signature
69
+ fp.close() # the redirect answer is not read: release its connection
70
+ raise _RedirectRefused(f"redirect refused (HTTP {code})")
71
+
72
+
73
+ _opener = urllib.request.build_opener(_NoRedirect())
74
+
75
+
76
+ def urllib_http_post(url: str, body: bytes, headers: Mapping[str, str], timeout: float) -> HttpResponse:
77
+ """The default ``http_post``, on :mod:`urllib.request` (certificates are verified).
78
+
79
+ ``timeout`` bounds the connection and every read, and the whole answer must arrive
80
+ before the deadline.
81
+ """
82
+ deadline = time.monotonic() + timeout
83
+ request = urllib.request.Request(url, data=body, headers=dict(headers), method="POST")
84
+ try:
85
+ response = _opener.open(request, timeout=timeout)
86
+ except urllib.error.HTTPError as error:
87
+ status = error.code
88
+ error.close()
89
+ return HttpResponse(status=status, headers={k.lower(): v for k, v in error.headers.items()})
90
+ except urllib.error.URLError as error:
91
+ if isinstance(error.reason, TimeoutError):
92
+ raise error.reason from error
93
+ raise
94
+ with response:
95
+ response_headers = {k.lower(): v for k, v in response.headers.items()}
96
+ declared = response_headers.get("content-length", "")
97
+ if declared.isdigit() and int(declared) > MAX_RESPONSE_BYTES:
98
+ raise _ResponseTooLarge()
99
+ chunks: list[bytes] = []
100
+ size = 0
101
+ while True:
102
+ if time.monotonic() > deadline:
103
+ raise TimeoutError("deadline passed while reading the answer")
104
+ chunk = response.read(64 * 1024)
105
+ if not chunk:
106
+ break
107
+ size += len(chunk)
108
+ if size > MAX_RESPONSE_BYTES:
109
+ raise _ResponseTooLarge()
110
+ chunks.append(chunk)
111
+ return HttpResponse(status=response.status, headers=response_headers, body=b"".join(chunks))
112
+
113
+
114
+ def require_text(value: Any, name: str, max_length: int, trim: bool = True) -> str:
115
+ """A required text setting: trimmed, not empty, not too long, no control characters."""
116
+ if not isinstance(value, str) or js_trim(value) == "":
117
+ raise CMIValidationError(f"{name} is required and must be a non-empty string.")
118
+ text = js_trim(value) if trim else value
119
+ if len(text) > max_length:
120
+ raise CMIValidationError(f"{name} must be at most {max_length} characters.")
121
+ if _CONTROL_CHARS.search(text):
122
+ raise CMIValidationError(
123
+ f"{name} must not contain control characters (line breaks, tabs, invisible characters)."
124
+ )
125
+ return text
126
+
127
+
128
+ def _charset(headers: Mapping[str, str], body: bytes) -> str:
129
+ """Charset: the Content-Type header, else the XML declaration, else UTF-8."""
130
+ match = re.search(r"charset=[\"']?([\w-]+)", headers.get("content-type", ""), re.IGNORECASE | re.ASCII)
131
+ if not match:
132
+ match = re.search(r"<\?xml[^>]*encoding=[\"']([\w-]+)[\"']", body[:200].decode("latin-1"), re.I | re.A)
133
+ charset = match.group(1) if match else "utf-8"
134
+ try:
135
+ codecs.lookup(charset)
136
+ except LookupError:
137
+ return "utf-8"
138
+ return charset
139
+
140
+
141
+ class CC5Transport:
142
+ """One connection to CMI's XML API, with its credentials. Server-only."""
143
+
144
+ __slots__ = ("__password", "_api_url", "_client_id", "_http_post", "_timeout", "_username")
145
+
146
+ def __init__(
147
+ self,
148
+ *,
149
+ api_url: str,
150
+ client_id: str,
151
+ username: str,
152
+ password: str,
153
+ timeout: float = DEFAULT_TIMEOUT,
154
+ http_post: HttpPost | None = None,
155
+ ) -> None:
156
+ api = require_text(api_url, "api_url", 2048)
157
+ if not is_secure_or_local_url(api):
158
+ raise CMIValidationError(f'api_url must be an https:// URL (plain http only for localhost), got "{api}".')
159
+ self._api_url = api
160
+ self._client_id = require_text(client_id, "client_id", MAX_CLIENT_ID_LENGTH)
161
+ self._username = require_text(username, "username", MAX_CREDENTIAL_LENGTH)
162
+ # The password is not trimmed: spaces around it may be part of it.
163
+ if not isinstance(password, str) or password == "":
164
+ raise CMIValidationError("password is required and must be a non-empty string.")
165
+ self.__password = SecretString(require_text(password, "password", MAX_CREDENTIAL_LENGTH, trim=False))
166
+
167
+ if (
168
+ isinstance(timeout, bool)
169
+ or not isinstance(timeout, (int, float))
170
+ or not math.isfinite(timeout)
171
+ or timeout <= 0
172
+ or timeout > MAX_TIMEOUT
173
+ ):
174
+ raise CMIValidationError(f"timeout must be a number of seconds greater than 0 and at most {MAX_TIMEOUT:g}.")
175
+ self._timeout = float(timeout)
176
+ if http_post is not None and not callable(http_post):
177
+ raise CMIValidationError("http_post must be a function (url, body, headers, timeout) -> HttpResponse.")
178
+ self._http_post: HttpPost = http_post or urllib_http_post
179
+
180
+ def describe(self) -> dict[str, str]:
181
+ """Non-secret settings, for logs and ``repr()``."""
182
+ return {"api_url": self._api_url, "client_id": self._client_id, "password": "********"}
183
+
184
+ def _encode(self, elements: Sequence[tuple[str, CC5Node]]) -> bytes:
185
+ xml = build_cc5_request(
186
+ [
187
+ ("Name", self._username),
188
+ ("Password", self.__password.get_value()),
189
+ ("ClientId", self._client_id),
190
+ *elements,
191
+ ]
192
+ )
193
+ return urlencode({"DATA": xml}).encode("ascii")
194
+
195
+ def send(self, operation: str, order_id: str, elements: Sequence[tuple[str, CC5Node]]) -> CC5Response:
196
+ """Send one CC5Request (credentials first, then ``elements``) and read the CC5Response.
197
+
198
+ Raises CMIApiError when no usable answer comes back. Never retries.
199
+ """
200
+ headers = {
201
+ "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
202
+ "Accept": "application/xml, text/xml, */*",
203
+ }
204
+
205
+ def timed_out() -> CMIApiError:
206
+ logger.warning("CMI API %s for order %s: timed out", operation, order_id)
207
+ return CMIApiError("TIMEOUT", operation, f"CMI API {operation} timed out after {self._timeout:g} s.")
208
+
209
+ def too_large() -> CMIApiError:
210
+ logger.warning("CMI API %s for order %s: invalid answer (too large)", operation, order_id)
211
+ return CMIApiError("INVALID_RESPONSE", operation, f"CMI API {operation}: The CMI answer is too large.")
212
+
213
+ # The request body (which holds the password) is never kept in a local variable of this
214
+ # frame, and the HTTP client's frames are cut from the errors ("from None"), so error
215
+ # reporters that capture local variables do not see it.
216
+ try:
217
+ response = self._http_post(self._api_url, self._encode(elements), headers, self._timeout)
218
+ except TimeoutError:
219
+ raise timed_out() from None
220
+ except _ResponseTooLarge:
221
+ raise too_large() from None
222
+ except CC5XmlError as error: # a request value XML cannot carry: nothing was sent
223
+ raise CMIValidationError(str(error)) from None
224
+ except Exception as error: # noqa: BLE001 - any other failure is NETWORK
225
+ logger.warning("CMI API %s for order %s: network error", operation, order_id)
226
+ reason = str(error) or type(error).__name__
227
+ raise CMIApiError("NETWORK", operation, f"CMI API {operation} failed: {reason}.") from None
228
+
229
+ if not 200 <= response.status < 300:
230
+ logger.warning("CMI API %s for order %s: HTTP %s", operation, order_id, response.status)
231
+ raise CMIApiError(
232
+ "HTTP_STATUS",
233
+ operation,
234
+ f"CMI API {operation} answered HTTP {response.status}.",
235
+ status=response.status,
236
+ )
237
+ if len(response.body) > MAX_RESPONSE_BYTES:
238
+ raise too_large()
239
+
240
+ headers_lower = {k.lower(): v for k, v in response.headers.items()}
241
+ text = response.body.decode(_charset(headers_lower, response.body), "replace")
242
+ try:
243
+ answer = parse_cc5_response(text)
244
+ except CC5XmlError as error:
245
+ logger.warning("CMI API %s for order %s: invalid answer (%s)", operation, order_id, error)
246
+ raise CMIApiError("INVALID_RESPONSE", operation, f"CMI API {operation}: {error}") from None
247
+
248
+ logger.debug(
249
+ "CMI API %s for order %s: %s (%s)",
250
+ operation,
251
+ order_id,
252
+ answer.fields.get("Response", "?"),
253
+ answer.fields.get("ProcReturnCode", "?"),
254
+ )
255
+ return answer
cmi/_cc5/xml.py ADDED
@@ -0,0 +1,211 @@
1
+ """CC5 XML: the request builder and a small reader for CMI's CC5Response.
2
+
3
+ CMI's responses are flat: a <CC5Response> root, simple elements, and one <Extra> element
4
+ whose children are simple elements too. The reader below handles exactly that shape,
5
+ with no XML library. It refuses DOCTYPE and entity declarations, so no entity expansion
6
+ (XXE, "billion laughs") can happen, and it is a single forward scan whose time grows
7
+ linearly with the answer's size.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import re
13
+ from collections.abc import Sequence
14
+ from dataclasses import dataclass
15
+ from typing import Union
16
+
17
+ from .._compat import js_trim
18
+
19
+ __all__ = ["CC5Node", "CC5Response", "CC5XmlError", "build_cc5_request", "escape_xml", "parse_cc5_response"]
20
+
21
+
22
+ class CC5XmlError(Exception):
23
+ """A CMI answer is not a readable CC5Response, or a request value cannot be written."""
24
+
25
+
26
+ #: One request element: a text value, or nested (name, node) elements in order.
27
+ CC5Node = Union[str, Sequence[tuple[str, "CC5Node"]]]
28
+
29
+ _ELEMENT_NAME = re.compile(r"[A-Za-z_][\w.\-]*", re.ASCII)
30
+ # Control characters XML 1.0 does not allow (tab, line feed and carriage return are allowed).
31
+ _INVALID_XML_CHARS = re.compile("[\x00-\x08\x0b\x0c\x0e-\x1f￾￿]")
32
+
33
+
34
+ def escape_xml(value: str) -> str:
35
+ """Escape text for an XML element."""
36
+ if _INVALID_XML_CHARS.search(value):
37
+ raise CC5XmlError("A request value contains a control character that XML does not allow.")
38
+ return (
39
+ value.replace("&", "&amp;")
40
+ .replace("<", "&lt;")
41
+ .replace(">", "&gt;")
42
+ .replace('"', "&quot;")
43
+ .replace("'", "&apos;")
44
+ )
45
+
46
+
47
+ def _write_node(name: str, node: CC5Node) -> str:
48
+ if not _ELEMENT_NAME.fullmatch(name):
49
+ raise CC5XmlError(f"Invalid XML element name: {name}")
50
+ if isinstance(node, str):
51
+ return f"<{name}>{escape_xml(node)}</{name}>"
52
+ return f"<{name}>{''.join(_write_node(child, value) for child, value in node)}</{name}>"
53
+
54
+
55
+ def build_cc5_request(elements: Sequence[tuple[str, CC5Node]]) -> str:
56
+ """``<?xml ...?><CC5Request>...</CC5Request>`` from ordered elements."""
57
+ return '<?xml version="1.0" encoding="UTF-8"?>' + _write_node("CC5Request", elements)
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class CC5Response:
62
+ """A parsed CC5Response: its top-level elements and the children of <Extra>, as text."""
63
+
64
+ fields: dict[str, str]
65
+ extra: dict[str, str]
66
+
67
+
68
+ _NAME = re.compile(r"[A-Za-z_][\w.:\-]*", re.ASCII)
69
+ _ENTITY = re.compile(r"&(#x[0-9a-fA-F]+|#[0-9]+|lt|gt|amp|quot|apos);")
70
+ _NAMED = {"lt": "<", "gt": ">", "amp": "&", "quot": '"', "apos": "'"}
71
+
72
+
73
+ def _decode_entity(match: re.Match[str]) -> str:
74
+ entity = match.group(1)
75
+ if entity in _NAMED:
76
+ return _NAMED[entity]
77
+ code = int(entity[2:], 16) if entity[1] == "x" else int(entity[1:], 10)
78
+ try:
79
+ return chr(code)
80
+ except (ValueError, OverflowError):
81
+ raise CC5XmlError("Invalid character reference in the CMI response.") from None
82
+
83
+
84
+ def _decode_entities(text: str) -> str:
85
+ return _ENTITY.sub(_decode_entity, text) if "&" in text else text
86
+
87
+
88
+ def _is_space(char: str) -> bool:
89
+ return char in " \t\n\r"
90
+
91
+
92
+ def _trim_value(text: str) -> str:
93
+ """Trims spaces and line breaks around a value, but keeps tabs: TRXn lines are tab-separated."""
94
+ return text.strip(" \n\r")
95
+
96
+
97
+ class _Element:
98
+ __slots__ = ("children", "name", "parts")
99
+
100
+ def __init__(self, name: str) -> None:
101
+ self.name = name
102
+ self.parts: list[str] = []
103
+ self.children: list[_Element] = []
104
+
105
+ @property
106
+ def text(self) -> str:
107
+ return "".join(self.parts)
108
+
109
+
110
+ def _not_well_formed(detail: str) -> CC5XmlError:
111
+ return CC5XmlError(f"The CMI response is not well-formed XML ({detail}).")
112
+
113
+
114
+ def parse_cc5_response(xml: str) -> CC5Response:
115
+ """Read a CC5Response. Element names are kept as sent; when an element repeats, the last
116
+ one wins. Values are entity-decoded and trimmed (tabs kept)."""
117
+ source = xml[1:] if xml.startswith("") else xml # byte order mark
118
+ root = _Element("#document")
119
+ stack = [root]
120
+ length = len(source)
121
+ i = 0
122
+
123
+ while i < length:
124
+ lt = source.find("<", i)
125
+ text_end = length if lt == -1 else lt
126
+ if text_end > i:
127
+ stack[-1].parts.append(_decode_entities(source[i:text_end]))
128
+ if lt == -1:
129
+ break
130
+
131
+ if source.startswith("<!--", lt):
132
+ end = source.find("-->", lt + 4)
133
+ if end == -1:
134
+ raise _not_well_formed("unclosed comment")
135
+ i = end + 3
136
+ continue
137
+ if source.startswith("<![CDATA[", lt):
138
+ end = source.find("]]>", lt + 9)
139
+ if end == -1:
140
+ raise _not_well_formed("unclosed CDATA section")
141
+ stack[-1].parts.append(source[lt + 9 : end])
142
+ i = end + 3
143
+ continue
144
+ if source.startswith("<?", lt):
145
+ end = source.find("?>", lt + 2)
146
+ if end == -1:
147
+ raise _not_well_formed("unclosed processing instruction")
148
+ i = end + 2
149
+ continue
150
+ if source.startswith("<!", lt):
151
+ # <!DOCTYPE ...>, <!ENTITY ...>: refused, so no entity expansion can happen.
152
+ raise CC5XmlError("The CMI response contains a DOCTYPE or ENTITY declaration, which is refused.")
153
+
154
+ gt = source.find(">", lt + 1)
155
+ if gt == -1:
156
+ raise _not_well_formed("unclosed tag")
157
+ next_lt = source.find("<", lt + 1)
158
+ if next_lt != -1 and next_lt < gt:
159
+ raise _not_well_formed('"<" inside a tag')
160
+
161
+ start, end = lt + 1, gt
162
+ while start < end and _is_space(source[start]):
163
+ start += 1
164
+ closing = start < end and source[start] == "/"
165
+ if closing:
166
+ start += 1
167
+ while start < end and _is_space(source[end - 1]):
168
+ end -= 1
169
+ self_closing = not closing and end > start and source[end - 1] == "/"
170
+ if self_closing:
171
+ end -= 1
172
+ while start < end and _is_space(source[start]):
173
+ start += 1
174
+ name_end = start
175
+ while name_end < end and not _is_space(source[name_end]):
176
+ name_end += 1
177
+ name = source[start:name_end] # anything after the name (attributes) is ignored
178
+ if not _NAME.fullmatch(name):
179
+ raise _not_well_formed(f"invalid tag <{source[lt + 1 : min(gt, lt + 40)]}>")
180
+ if closing and name_end < end:
181
+ raise _not_well_formed(f"unexpected text in </{name}>")
182
+
183
+ current = stack[-1]
184
+ if closing:
185
+ if current.name != name or len(stack) == 1:
186
+ raise _not_well_formed(f"unexpected </{name}>")
187
+ stack.pop()
188
+ else:
189
+ element = _Element(name)
190
+ current.children.append(element)
191
+ if not self_closing:
192
+ stack.append(element)
193
+ i = gt + 1
194
+
195
+ if len(stack) != 1:
196
+ raise _not_well_formed(f"<{stack[-1].name}> is not closed")
197
+ top = root.children
198
+ if len(top) != 1 or js_trim(root.text) != "":
199
+ raise CC5XmlError("The CMI response must have exactly one root element.")
200
+ if top[0].name != "CC5Response":
201
+ raise CC5XmlError(f"Expected a <CC5Response>, got <{top[0].name}>.")
202
+
203
+ fields: dict[str, str] = {}
204
+ extra: dict[str, str] = {}
205
+ for child in top[0].children:
206
+ if child.name == "Extra":
207
+ for item in child.children:
208
+ extra[item.name] = _trim_value(item.text)
209
+ else:
210
+ fields[child.name] = _trim_value(child.text)
211
+ return CC5Response(fields=fields, extra=extra)